repo_name
stringlengths 7
111
| __id__
int64 16.6k
19,705B
| blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
151
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_url
stringlengths 26
130
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
42
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 14.6k
687M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 12
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
10.2M
⌀ | gha_stargazers_count
int32 0
178k
⌀ | gha_forks_count
int32 0
88.9k
⌀ | gha_open_issues_count
int32 0
2.72k
⌀ | gha_language
stringlengths 1
16
⌀ | gha_archived
bool 1
class | gha_disabled
bool 1
class | content
stringlengths 10
2.95M
| src_encoding
stringclasses 5
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 10
2.95M
| extension
stringclasses 19
values | num_repo_files
int64 1
202k
| filename
stringlengths 4
112
| num_lang_files
int64 1
202k
| alphanum_fraction
float64 0.26
0.89
| alpha_fraction
float64 0.2
0.89
| hex_fraction
float64 0
0.09
| num_lines
int32 1
93.6k
| avg_line_length
float64 4.57
103
| max_line_length
int64 7
931
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
MLDSAI/VisionTracing | 15,685,220,607,461 | 2fb72052cd79c3f464b29859604ad643f9a18d6d | e03ec5eb75fed31ad4fe543241ed4f626119fe4f | /vision.py | df995f87212e137ce7a342a86f0356f95bea31b6 | []
| no_license | https://github.com/MLDSAI/VisionTracing | c437f3117a6ddde0db98c739ba259be9d4da8577 | f852b92863b66f03c471e3cdac81479c0c5aea74 | refs/heads/master | 2022-12-16T17:51:51.688631 | 2020-08-25T19:58:24 | 2020-08-25T19:58:24 | 289,623,723 | 0 | 0 | null | false | 2020-09-11T17:27:17 | 2020-08-23T05:40:00 | 2020-08-26T18:39:56 | 2020-09-11T17:21:10 | 2,416 | 0 | 0 | 1 | Python | false | false | import os
import cv2
import numpy as np
import torch
from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from loguru import logger
from tqdm import tqdm
from PIL import Image
import tracking
def get_tracking_video(fpath_video):
logger.info(f'get_tracking_video fpath_video: {fpath_video}')
image_gen = _get_images_from_video(fpath_video)
images = [image for image in image_gen]
predictions = _get_predictions_from_images(images)
tracks = tracking.get_tracks(predictions)
fpath_tracking_video = _get_video_from_tracks(tracks, images)
return len(images), fpath_tracking_video
def _get_images_from_video(fpath_video):
'''
Parameters:
- str fpath_video: path to video file
'''
logger.info(
f'_get_images_from_video() fpath_video: {fpath_video}'
)
def _frame_from_video(_video_capture):
while _video_capture.isOpened():
retval, image = _video_capture.read()
if retval:
yield image
else:
break
video_capture = cv2.VideoCapture(fpath_video)
image_gen = _frame_from_video(video_capture)
return image_gen
def _get_predictions_from_images(images):
'''
Parameters:
- list[np.ndarray images: list of images in chronological order
Return:
- TODO
'''
dirpath_models = os.path.dirname(model_zoo.__file__)
logger.info(
f'_get_predictions_from_images() '
'dirpath_models: {dirpath_models}'
)
fname_config = 'keypoint_rcnn_R_50_FPN_3x.yaml'
DEFAULT_CONFIG = os.path.join(
dirpath_models, 'configs', 'COCO-Keypoints', fname_config
)
DEFAULT_CONF_THRESH = 0.1
DEFAULT_OPTS = [
'MODEL.WEIGHTS',
model_zoo.get_checkpoint_url(
f'COCO-Keypoints/{fname_config}'
)
]
cfg = _setup_cfg(
DEFAULT_CONFIG, DEFAULT_OPTS, DEFAULT_CONF_THRESH
)
predictor = DefaultPredictor(cfg)
predictions = []
for i, image in enumerate(tqdm(images)):
image_predictions = predictor(image)
predictions.append(image_predictions)
predictions = np.array(predictions)
logger.info(
'_get_predictions_from_images() '
'predictions: {predictions}'
)
return predictions
def _setup_cfg(config, opts, conf_thresh):
# load config from file and arguments
cfg = get_cfg()
if not torch.cuda.device_count():
print('Running on CPU')
cfg.MODEL.DEVICE = 'cpu'
cfg.merge_from_file(config)
cfg.merge_from_list(opts)
# Set score_threshold for builtin models
cfg.MODEL.RETINANET.SCORE_THRESH_TEST = conf_thresh
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = conf_thresh
cfg.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = conf_thresh
cfg.freeze()
return cfg
def _get_video_from_tracks(tracks, images):
''' Save a video showing tracks to disk and return the path '''
# fourcc = cv2.VideoWriter_fourcc(*'MP4V')
output_size = images[0].shape
output_file = 'tracks.mp4'
# out = cv2.VideoWriter(output_file, fourcc, 25, output_size[:-1])
for i in range(len(tracks)): # Number of tracks
track_frame = np.zeros((output_size[0], output_size[1], 3), dtype=np.float32)
for j in range(len(tracks[0])): # Number of bounding boxes within a track
pt = tracks[i][j]
if any(np.isnan(pt)):
continue
x1, y1, x2, y2 = pt
x, y, w, h = x1, y1, x2 - x1, y2 - y1 # Top left coordinates and width and height respectively
cv2.rectangle(track_frame, (int(x), int(y)), (int(x + w), int(y + h)),
(0, 255, 0), 10)
frame = np.where(True, images[i], track_frame)
frame = Image.fromarray(frame.astype(np.uint8))
frame.save('image_folder/frame{}.jpg'.format(i))
# out.write(frame.astype(np.uint8))
# out.release()
return output_file
| UTF-8 | Python | false | false | 4,021 | py | 16 | vision.py | 8 | 0.626461 | 0.615519 | 0 | 131 | 29.694656 | 106 |
msr2009/SCRIPTS | 8,246,337,221,398 | cb55a4d53f7991ff1fb4aa337f0bec20f696046e | 19dab019a902783233e4b3115aecbc015a5aa73e | /count_barcodes.py | b9427355d12e8c2ef503aedfdd3740f186f32f3a | []
| no_license | https://github.com/msr2009/SCRIPTS | 1a0308737c71108eb4051a1d88c3c449e64fccee | 42025ac67abe48a298858590ed29df033c8cd93f | refs/heads/master | 2021-01-18T21:30:08.567836 | 2017-08-15T20:44:42 | 2017-08-15T20:44:42 | 16,288,634 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | """
comments
Matt Rich, DATE
"""
def main(f_in):
barcodes = {}
for read in read_fastq(f_in):
if read[1] in barcodes:
barcodes[read[1]] += 1
else:
barcodes[read[1]] = 1
for b in barcodes:
print "\t".join([b, str(barcodes[b])])
if __name__ == "__main__":
from optparse import OptionParser
from fastq_tools import read_fastq
parser = OptionParser()
parser.add_option('--fq', action = 'store', type = 'string', dest = 'fastq', help = "HELP")
(option, args) = parser.parse_args()
main(option.fastq)
| UTF-8 | Python | false | false | 531 | py | 179 | count_barcodes.py | 169 | 0.615819 | 0.606403 | 0 | 30 | 16.633333 | 92 |
andreykirov84/Programming_Fundamentals_with_Python | 17,308,718,242,165 | cd5cbcbe8c17b71b9cfb14b396e5b4de504e9622 | 8610b613f7a5b5fb4b9acd07693b11fef2885c52 | /Python_Fundamentals/Programming Fundamentals Mid Exams/03_Programming_Fundamentals_Mid_Exam_Retake/02_solution.py | 3e42a5d0fc3ca077ffa6cee41a52dfef7aec97d4 | []
| no_license | https://github.com/andreykirov84/Programming_Fundamentals_with_Python | 3f7dd2a4e4d90c154596e7e42df0a0a335968f43 | 5f178d16401b900af9704564e614a3343a18dbe2 | refs/heads/master | 2023-08-29T17:10:18.384225 | 2021-10-27T10:12:41 | 2021-10-27T10:12:41 | 361,666,875 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | ll = input().split(' ')
ll = [int(x) for x in ll]
target = 0
command = input()
while command != 'End':
command = int(command)
if command < len(ll) and ll[command] != -1:
target_value = ll[command]
for i in range(len(ll)):
if ll[i] != -1:
old_value = ll[i]
if ll[i] > target_value:
ll[i] = old_value - target_value
elif ll[i] <= target_value:
ll[i] = old_value + target_value
ll[command] = -1
target += 1
command = input()
else:
command = input()
print(f"Shot targets: {target} -> ", end='')
print(*ll)
| UTF-8 | Python | false | false | 698 | py | 330 | 02_solution.py | 326 | 0.448424 | 0.441261 | 0 | 24 | 26.666667 | 52 |
mesoylu/swe573 | 12,455,405,210,108 | 574912f2c391b5f84b45189add03ee3bcec016a5 | 512dd1bf29d237d28bc3a5d06f3abf30c9bcd563 | /backend/community/migrations/0041_community_is_archived.py | 05a90d952c93ae5acf23427200bb72617528d59d | []
| no_license | https://github.com/mesoylu/swe573 | 4e058c6e31e7ca67cf47d053ef32fd1d1b8ec51f | 3d4a30bc59ce9a5f2930582d8cf05735813f12e9 | refs/heads/master | 2022-05-08T08:20:48.974719 | 2019-12-24T14:14:20 | 2019-12-24T14:14:20 | 210,375,635 | 0 | 0 | null | false | 2022-04-22T22:58:49 | 2019-09-23T14:25:40 | 2019-12-24T14:14:22 | 2022-04-22T22:58:48 | 2,995 | 0 | 0 | 13 | CSS | false | false | # Generated by Django 2.2.6 on 2019-11-23 18:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('community', '0040_datatype_date_created'),
]
operations = [
migrations.AddField(
model_name='community',
name='is_archived',
field=models.BooleanField(default=False),
),
]
| UTF-8 | Python | false | false | 400 | py | 84 | 0041_community_is_archived.py | 44 | 0.6 | 0.5525 | 0 | 18 | 21.222222 | 53 |
Edi31/django-livesettings3 | 9,509,057,611,133 | 7d78c6e0a7deab393401d399d0540bd59022c78e | d58b4d5a4ea4385c50d1b33301e1099ffe9dfb2b | /test-project/test_project/urls.py | 653df3aace3d728f2f9e7384fed289006f49ebf7 | [
"BSD-2-Clause"
]
| permissive | https://github.com/Edi31/django-livesettings3 | 5dfabf5962f057f6703357c22c260b78c3f09e51 | 4f621d2183e090c8d2afc36f1fc71b513ad2cf78 | refs/heads/master | 2021-04-11T10:04:16.072582 | 2020-03-21T16:07:00 | 2020-03-21T16:07:00 | 249,009,936 | 0 | 0 | NOASSERTION | true | 2020-03-21T15:57:38 | 2020-03-21T15:57:38 | 2020-02-03T20:50:14 | 2020-01-18T21:56:20 | 697 | 0 | 0 | 0 | null | false | false | from localsite import views
from django.contrib.auth import views as auth_views
from django.conf.urls import url, include
from django.conf import settings
from django.contrib import admin
from django.views import static
admin.autodiscover()
urlpatterns = [
url(r'^settings/', include('livesettings.urls')),
url(r'^admin/', admin.site.urls),
url(f'^{settings.MEDIA_URL.strip("/")}(?P<path>.*)$', static.serve, {'document_root': settings.MEDIA_ROOT}),
url(r'^accounts/login/', auth_views.LoginView.as_view(template_name='admin/login.html')),
url(r'^$', views.index)
]
| UTF-8 | Python | false | false | 589 | py | 3 | urls.py | 3 | 0.713073 | 0.713073 | 0 | 17 | 33.647059 | 112 |
vlmarcelo/Sistema_Ugel | 712,964,610,694 | d58ce8f0091d18ec895372f5cb6746c912afe8a0 | 60b85430f588f60899228dd0d179d44c0d9c96e8 | /entidades/forms.py | 18637dcc35292054280efd1b983c3ccc15b1bb46 | []
| no_license | https://github.com/vlmarcelo/Sistema_Ugel | c69afa5d333fd528fa8e8635e801d9427ecd9851 | e69e5678a18114e4a8972a5f05c1d1b4f187d282 | refs/heads/master | 2020-04-19T04:36:57.224195 | 2016-08-23T05:32:15 | 2016-08-23T05:32:15 | 66,334,215 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- encoding: utf-8 -*-
from django import forms
from .models import Entidad
from django.forms.formsets import formset_factory
class EntidadModelForm(forms.ModelForm):
class Meta:
model = Entidad
fields = [
'clase_entidad', 'tipo_entidad', 'nombre','siglas', 'documento_identificacion',
'numero_documento_identificacion', 'mision', 'vision',
'fecha_creacion', 'fecha_cese', 'descripcion', 'observacion', 'logotipo', 'activo',
]
widgets = {
'clase_entidad' : forms.Select(attrs={'class':'Select'}),
'tipo_entidad' : forms.Select(attrs={'class':'Select'}),
'nombre' : forms.TextInput(attrs={'class':'InputText'}),
'siglas' : forms.TextInput(attrs={'class':'InputText'}),
'documento_identificacion' : forms.Select(attrs={'class':'Select'}),
'numero_documento_identificacion': forms.TextInput(attrs={'class':'InputText'}),
'mision' : forms.Textarea(attrs={'class':'InputArea'}),
'vision' : forms.Textarea(attrs={'class':'InputArea'}),
'logotipo' : forms.FileInput(attrs={'class':'InputFile'}),
'fecha_creacion' : forms.DateInput(attrs={'class':'InputDate'}),
'fecha_cese' : forms.DateInput(attrs={'class':'InputDate'}),
'descripcion' : forms.Textarea(attrs={'class':'InputArea', }),
'observacion' : forms.Textarea(attrs={'class':'InputArea', }),
'activo' : forms.CheckboxInput(attrs={'class':'Checkbox', })
}
| UTF-8 | Python | false | false | 1,504 | py | 130 | forms.py | 97 | 0.615027 | 0.614362 | 0 | 33 | 44.484848 | 89 |
Inxious/Rarm | 9,758,165,718,461 | b7c3d1418e252796d7badd08145ea93463731885 | 7eb68b2690dab960935f86f15c43cef570f0ddb3 | /frame/SetupProcess_Page.py | 8b2d9a72e4158e4bbc7918650d86417f6448fa8e | []
| no_license | https://github.com/Inxious/Rarm | 2c550e67bc45dfb7065de312ba48beead9d8a23b | 7787566df5ac6bde50c53b91ec4f8a1729b38af5 | refs/heads/master | 2020-03-24T16:05:15.122559 | 2018-07-30T02:07:33 | 2018-07-30T02:07:33 | 142,812,310 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # create a background image on a wxPython panel
# and show a button on top of the image
import wx
import os
import wx.dataview
from copy import deepcopy
from numpy import mean,array
import copy
class Setup_Process(wx.Frame):
"""class Panel1 creates a panel with an image on it, inherits wx.Panel"""
def __init__(self, parent, framename):
# LOAD CONFIG FILE
self.max_axis1 = int(self.config.get('Scroll Limit', 'max_axis1'))
self.min_axis1 = int(self.config.get('Scroll Limit', 'min_axis1'))
self.max_axis2 = int(self.config.get('Scroll Limit', 'max_axis2'))
self.min_axis2 = int(self.config.get('Scroll Limit', 'min_axis2'))
self.max_axis3 = int(self.config.get('Scroll Limit', 'max_axis3'))
self.min_axis3 = int(self.config.get('Scroll Limit', 'min_axis3'))
self.max_axis4 = int(self.config.get('Scroll Limit', 'max_axis4'))
self.min_axis4 = int(self.config.get('Scroll Limit', 'min_axis4'))
self.max_servo = int(self.config.get('Scroll Limit', 'max_servo'))
self.min_servo = int(self.config.get('Scroll Limit', 'min_servo'))
# create the panel
wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
size=wx.Size(1145, 615), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
self.FrameObject.update({framename: self})
self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
fgSizer1 = wx.FlexGridSizer(1, 2, 0, 0)
fgSizer1.SetFlexibleDirection(wx.BOTH)
fgSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
#MENU BAR
self.VMenuBars()
self.SetMenuBar(self.MenuBar_Main)
#PANEL CONTROL
self.StPrcPanelControl(self)
fgSizer1.Add(self.StPrc_Pnl_Main, 1, wx.ALL | wx.EXPAND, 0)
#ADDS INS PANEL CONTROL
self.StPrcIndicator(self.Bit_StPrc_Background_Setup, 0, 480)
#PANEL VIEW
self.StPrcPanelView()
fgSizer1.Add(self.Pnl_StPrc_View, 1, wx.ALL | wx.EXPAND, 0)
self.SetSizer(fgSizer1)
self.Layout()
#LOAD CONSTANT
self.StPrcStarter()
#DISABLES
self.Cmd_StPrc_WidgetUseMouse.Disable()
self.Cmd_StPrc_WidgetUseController.Disable()
#EVENTS
self.SetPrcEvents(framename)
self.Centre(wx.BOTH)
self.Show()
#FRAME PART
def StPrcIndicator(self, parent, x, y):
self.Pnl_StPrcIndicator = wx.Panel(parent, id=wx.ID_ANY, pos=wx.Point(x,y), size=wx.Size(626, 95),
style=wx.TAB_TRAVERSAL)
self.SetBackgroundColour(wx.SystemSettings.GetColour( wx.SYS_COLOUR_INACTIVECAPTION ))
fgSizer2 = wx.FlexGridSizer(1, 2, 0, 0)
fgSizer2.SetFlexibleDirection(wx.BOTH)
fgSizer2.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Pnl_StPrc_WidgetChild1 = wx.Panel(self.Pnl_StPrcIndicator, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
self.Pnl_StPrc_WidgetChild1.SetBackgroundColour(wx.SystemSettings.GetColour( wx.SYS_COLOUR_INACTIVECAPTION ))
fgSizer3 = wx.FlexGridSizer(2, 1, 0, 0)
fgSizer3.SetFlexibleDirection(wx.BOTH)
fgSizer3.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Lbl_Jdl_StPrc_Widget = wx.StaticText(self.Pnl_StPrc_WidgetChild1, wx.ID_ANY, u"SETUP PROCESS",
wx.DefaultPosition, wx.DefaultSize, 0)
self.Lbl_Jdl_StPrc_Widget.Wrap(-1)
self.Lbl_Jdl_StPrc_Widget.SetFont(wx.Font(18, 74, 90, 92, False, "Arial Black"))
self.Lbl_Jdl_StPrc_Widget.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND))
fgSizer3.Add(self.Lbl_Jdl_StPrc_Widget, 0, wx.ALL, 5)
bSizer2 = wx.BoxSizer(wx.HORIZONTAL)
self.Cmd_StPrc_WidgetUseMouse = wx.Button(self.Pnl_StPrc_WidgetChild1, wx.ID_ANY, u"Use Mouse",
wx.DefaultPosition, wx.DefaultSize, 0)
bSizer2.Add(self.Cmd_StPrc_WidgetUseMouse, 0, wx.ALL, 5)
self.Cmd_StPrc_WidgetUseController = wx.Button(self.Pnl_StPrc_WidgetChild1, wx.ID_ANY, u"Use Controller",
wx.DefaultPosition, wx.DefaultSize, 0)
bSizer2.Add(self.Cmd_StPrc_WidgetUseController, 0, wx.ALL, 5)
fgSizer3.Add(bSizer2, 1, wx.ALIGN_CENTER_HORIZONTAL, 5)
self.Pnl_StPrc_WidgetChild1.SetSizer(fgSizer3)
self.Pnl_StPrc_WidgetChild1.Layout()
fgSizer3.Fit(self.Pnl_StPrc_WidgetChild1)
fgSizer2.Add(self.Pnl_StPrc_WidgetChild1, 1, wx.EXPAND | wx.ALL, 2)
self.Pnl_StPrc_WidgetChild2 = wx.Panel(self.Pnl_StPrcIndicator, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, -1), wx.TAB_TRAVERSAL)
self.Pnl_StPrc_WidgetChild2.SetBackgroundColour(wx.Colour(255, 255, 255))
gbSizer3 = wx.GridBagSizer(0, 0)
gbSizer3.SetFlexibleDirection(wx.BOTH)
gbSizer3.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
gbSizer3.SetMinSize(wx.Size(390, -1))
self.Lbl_StPrc_WidgetUsedMode = wx.StaticText(self.Pnl_StPrc_WidgetChild2, wx.ID_ANY, u" Used Mode =",
wx.DefaultPosition, wx.DefaultSize, 0)
self.Lbl_StPrc_WidgetUsedMode.Wrap(-1)
gbSizer3.Add(self.Lbl_StPrc_WidgetUsedMode, wx.GBPosition(1, 0), wx.GBSpan(1, 1), wx.ALL, 5)
self.Lbl_StPrc_WidgetUsedModeView = wx.StaticText(self.Pnl_StPrc_WidgetChild2, wx.ID_ANY, u"-",
wx.DefaultPosition, wx.DefaultSize, 0)
self.Lbl_StPrc_WidgetUsedModeView.Wrap(-1)
self.Lbl_StPrc_WidgetUsedModeView.SetFont(wx.Font(11, 70, 90, 92, False, "Arial"))
gbSizer3.Add(self.Lbl_StPrc_WidgetUsedModeView, wx.GBPosition(1, 1), wx.GBSpan(1, 1), wx.ALL, 5)
self.Lbl_StPrc_WidgetControllerStats = wx.StaticText(self.Pnl_StPrc_WidgetChild2, wx.ID_ANY,
u"Controller Status =", wx.DefaultPosition, wx.DefaultSize,
0)
self.Lbl_StPrc_WidgetControllerStats.Wrap(-1)
gbSizer3.Add(self.Lbl_StPrc_WidgetControllerStats, wx.GBPosition(2, 0), wx.GBSpan(1, 1), wx.ALL, 5)
self.Lbl_StPrc_WidgetControllerStatsView = wx.StaticText(self.Pnl_StPrc_WidgetChild2, wx.ID_ANY,
u"DISCONNECTED", wx.DefaultPosition, wx.DefaultSize, 0)
self.Lbl_StPrc_WidgetControllerStatsView.Wrap(-1)
self.Lbl_StPrc_WidgetControllerStatsView.SetFont(wx.Font(11, 74, 90, 92, False, "Arial"))
self.Lbl_StPrc_WidgetControllerStatsView.SetForegroundColour(wx.Colour(255, 4, 4))
self.Lbl_StPrc_WidgetControllerStatsView.SetBackgroundColour(
wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
gbSizer3.Add(self.Lbl_StPrc_WidgetControllerStatsView, wx.GBPosition(2, 1), wx.GBSpan(1, 1), wx.ALL, 5)
self.Pnl_StPrc_WidgetChild2.SetSizer(gbSizer3)
self.Pnl_StPrc_WidgetChild2.Layout()
gbSizer3.Fit(self.Pnl_StPrc_WidgetChild2)
fgSizer2.Add(self.Pnl_StPrc_WidgetChild2, 1, wx.EXPAND | wx.ALL, 2)
self.Pnl_StPrcIndicator.SetSizer(fgSizer2)
self.Pnl_StPrcIndicator.Layout()
#STARTER
def StPrcStarter(self):
#START POSITION
self.Start_Position = {1:None,2:None,3:None,4:None,5:None,6:None}
#LAST SUDUT VALUE
self.Checkpoint_Sudut = {1:None,2:None,3:None,4:None,5:None,6:None}
#STATUS OF IS6
self.Is6_Status = True
# SLIDER LAST VALUE
self.Last_Slider1 = ''
self.Last_Slider2 = ''
self.Last_Slider3 = ''
self.Last_Slider4 = ''
self.Last_Slider5 = ''
self.Last_Slider6 = ''
# focused box
self.CurrentFocus = ''
self.NowFocus = self.CurrentFocus
# BOX 10
val1 = int(self.CNows(2, need=1))
self.StPrc_Spn_Value1.SetRange(self.min_axis1, self.max_axis1)
self.StPrc_Spn_Value1.SetValue(val1)
self.StPrc_Spn_Value1.SetIncrement(1)
datadict = self.CCalculate('SPIN-SLIDER', 1, max=self.StPrc_Spn_Value1.GetMax(),
min=self.StPrc_Spn_Value1.GetMin(),
inc=self.StPrc_Spn_Value1.GetIncrement())
self.StPrc_Sld_Move1.SetRange(datadict['min'], datadict['max'])
self.StPrc_Sld_Move1.SetValue(val1)
# BOX 2
val2 = int(self.CNows(2, need=2))
self.StPrc_Spn_Value2.SetRange(self.min_axis2, self.max_axis2)
self.StPrc_Spn_Value2.SetValue(val2)
self.StPrc_Spn_Value2.SetIncrement(1)
datadict = self.CCalculate('SPIN-SLIDER', 1, max=self.StPrc_Spn_Value2.GetMax(),
min=self.StPrc_Spn_Value2.GetMin(),
inc=self.StPrc_Spn_Value2.GetIncrement())
self.StPrc_Sld_Move2.SetRange(datadict['min'], datadict['max'])
self.StPrc_Sld_Move2.SetValue(val2)
# BOX 3
val3 = int(self.CNows(2, need=3))
self.StPrc_Spn_Value3.SetRange(self.min_axis3, self.max_axis3)
self.StPrc_Spn_Value3.SetValue(val3)
self.StPrc_Spn_Value3.SetIncrement(1)
datadict = self.CCalculate('SPIN-SLIDER', 1, max=self.StPrc_Spn_Value3.GetMax(),
min=self.StPrc_Spn_Value3.GetMin(),
inc=self.StPrc_Spn_Value3.GetIncrement())
self.StPrc_Sld_Move3.SetRange(datadict['min'], datadict['max'])
self.StPrc_Sld_Move3.SetValue(val3)
# BOX 4
val4 = int(self.CNows(2, need=4))
self.StPrc_Spn_Value4.SetRange(self.min_axis4, self.max_axis4)
self.StPrc_Spn_Value4.SetValue(val4)
self.StPrc_Spn_Value4.SetIncrement(1)
datadict = self.CCalculate('SPIN-SLIDER', 1, max=self.StPrc_Spn_Value4.GetMax(),
min=self.StPrc_Spn_Value4.GetMin(),
inc=self.StPrc_Spn_Value4.GetIncrement())
self.StPrc_Sld_Move4.SetRange(datadict['min'], datadict['max'])
self.StPrc_Sld_Move4.SetValue(val4)
# BOX 5
val5 = int(self.CNows(2, need=5))
self.StPrc_Spn_Value5.SetRange(self.min_servo, self.max_servo)
self.StPrc_Spn_Value5.SetValue(val5)
self.StPrc_Spn_Value5.SetIncrement(1)
datadict = self.CCalculate('SPIN-SLIDER', 1, max=self.StPrc_Spn_Value5.GetMax(),
min=self.StPrc_Spn_Value5.GetMin(),
inc=self.StPrc_Spn_Value5.GetIncrement())
self.StPrc_Sld_Move5.SetRange(datadict['min'], datadict['max'])
self.StPrc_Sld_Move5.SetValue(val5)
# BOX 6
val6 = int(self.CNows(2, need=6))
self.StPrc_Spn_Value6.SetRange(0, 100)
self.StPrc_Spn_Value6.SetValue(val6)
self.StPrc_Spn_Value6.SetIncrement(1)
datadict = self.CCalculate('SPIN-SLIDER', 1, max=self.StPrc_Spn_Value6.GetMax(),
min=self.StPrc_Spn_Value6.GetMin(),
inc=self.StPrc_Spn_Value6.GetIncrement())
self.StPrc_Sld_Move6.SetRange(datadict['min'], datadict['max'])
self.StPrc_Sld_Move6.SetValue(val6)
# Disable Dv Down Button
self.Cmd_Down_Save.Disable()
self.Cmd_Down_Delete.Disable()
self.Cmd_Down_DeleteAll.Disable()
self.Cmd_Down_CheckDetail.Disable()
#DATA
self.StPrcViewConfigH(1)
#START NEW
def StPrcDisableStartNew(self):
#Enable Mode
self.Cmd_StPrc_WidgetUseMouse.Enable()
self.Cmd_StPrc_WidgetUseController.Enable()
#Enable Dv Down Button
self.Cmd_Down_Save.Enable()
self.Cmd_Down_Delete.Enable()
self.Cmd_Down_DeleteAll.Enable()
self.Cmd_Down_CheckDetail.Enable()
#EVENT
def SetPrcEvents(self , framename):
# ==== SLIDER & SPIN ====
# 1
self.StPrc_Spn_Value1.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(2, 1))
self.StPrc_Spn_Value1.Bind(wx.EVT_TEXT, lambda x: self.StPrcOnChange(2, 1))
self.StPrc_Spn_Value1.Bind(wx.EVT_SPINCTRLDOUBLE, lambda x: self.StPrcOnChange(2, 1))
self.StPrc_Sld_Move1.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(1, 1))
self.StPrc_Sld_Move1.Bind(wx.EVT_SCROLL_CHANGED, lambda x: self.StPrcOnChange(1, 1))
self.StPrc_Pnl_Move1.Bind(wx.EVT_SET_FOCUS,
lambda x: self.StPrcOnFocus(3, 1, togglevalue=self.Tgl_StPrc_FocusButton1.GetValue()))
self.Tgl_StPrc_FocusButton1.Bind(wx.EVT_TOGGLEBUTTON, lambda x: self.StPrcOnFocus(3, 1,
togglevalue=self.Tgl_StPrc_FocusButton1.GetValue()))
# 2
self.StPrc_Spn_Value2.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(2, 2))
self.StPrc_Spn_Value2.Bind(wx.EVT_TEXT, lambda x: self.StPrcOnChange(2, 2))
self.StPrc_Spn_Value2.Bind(wx.EVT_SPINCTRLDOUBLE, lambda x: self.StPrcOnChange(2, 2))
self.Axis1_Handler = self.StPrc_Spn_Value2.GetEventHandler()
self.StPrc_Sld_Move2.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(1, 2))
self.StPrc_Sld_Move2.Bind(wx.EVT_SCROLL_CHANGED, lambda x: self.StPrcOnChange(1, 2))
self.StPrc_Pnl_Move2.Bind(wx.EVT_SET_FOCUS,
lambda x: self.StPrcOnFocus(3, 2, togglevalue=self.Tgl_StPrc_FocusButton2.GetValue()))
self.Tgl_StPrc_FocusButton2.Bind(wx.EVT_TOGGLEBUTTON, lambda x: self.StPrcOnFocus(3, 2,
togglevalue=self.Tgl_StPrc_FocusButton2.GetValue()))
# 3
self.StPrc_Spn_Value3.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(2, 3))
self.StPrc_Spn_Value3.Bind(wx.EVT_TEXT, lambda x: self.StPrcOnChange(2, 3))
self.StPrc_Spn_Value3.Bind(wx.EVT_SPINCTRLDOUBLE, lambda x: self.StPrcOnChange(2, 3))
self.Axis2_Handler = self.StPrc_Spn_Value3.GetEventHandler()
self.StPrc_Sld_Move3.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(1, 3))
self.StPrc_Sld_Move3.Bind(wx.EVT_SCROLL_CHANGED, lambda x: self.StPrcOnChange(1, 3))
self.StPrc_Pnl_Move3.Bind(wx.EVT_SET_FOCUS,
lambda x: self.StPrcOnFocus(3, 3, togglevalue=self.Tgl_StPrc_FocusButton3.GetValue()))
self.Tgl_StPrc_FocusButton3.Bind(wx.EVT_TOGGLEBUTTON, lambda x: self.StPrcOnFocus(3, 3,
togglevalue=self.Tgl_StPrc_FocusButton3.GetValue()))
# 4
self.StPrc_Spn_Value4.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(2, 4))
self.StPrc_Spn_Value4.Bind(wx.EVT_TEXT, lambda x: self.StPrcOnChange(2, 4))
self.StPrc_Spn_Value4.Bind(wx.EVT_SPINCTRLDOUBLE, lambda x: self.StPrcOnChange(2, 4))
self.Axis3_Handler = self.StPrc_Spn_Value4.GetEventHandler()
self.StPrc_Sld_Move4.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(1, 4))
self.StPrc_Sld_Move4.Bind(wx.EVT_SCROLL_CHANGED, lambda x: self.StPrcOnChange(1, 4))
self.StPrc_Pnl_Move4.Bind(wx.EVT_SET_FOCUS,
lambda x: self.StPrcOnFocus(3, 4, togglevalue=self.Tgl_StPrc_FocusButton4.GetValue()))
self.Tgl_StPrc_FocusButton4.Bind(wx.EVT_TOGGLEBUTTON, lambda x: self.StPrcOnFocus(3, 4,
togglevalue=self.Tgl_StPrc_FocusButton4.GetValue()))
# 5
self.StPrc_Spn_Value5.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(2, 5))
self.StPrc_Spn_Value5.Bind(wx.EVT_TEXT, lambda x: self.StPrcOnChange(2, 5))
self.StPrc_Spn_Value5.Bind(wx.EVT_SPINCTRLDOUBLE, lambda x: self.StPrcOnChange(2, 5))
self.StPrc_Sld_Move5.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(1, 5))
self.StPrc_Sld_Move5.Bind(wx.EVT_SCROLL_CHANGED, lambda x: self.StPrcOnChange(1, 5))
self.StPrc_Pnl_Move5.Bind(wx.EVT_SET_FOCUS,
lambda x: self.StPrcOnFocus(3, 5, togglevalue=self.Tgl_StPrc_FocusButton5.GetValue()))
self.Tgl_StPrc_FocusButton5.Bind(wx.EVT_TOGGLEBUTTON, lambda x: self.StPrcOnFocus(3, 5,
togglevalue=self.Tgl_StPrc_FocusButton5.GetValue()))
# 6
self.StPrc_Spn_Value6.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(2, 6))
self.StPrc_Spn_Value6.Bind(wx.EVT_TEXT, lambda x: self.StPrcOnChange(2, 6))
self.StPrc_Spn_Value6.Bind(wx.EVT_SPINCTRLDOUBLE, lambda x: self.StPrcOnChange(2, 6))
self.StPrc_Sld_Move6.Bind(wx.EVT_SET_FOCUS, lambda x: self.StPrcOnFocus(1, 6))
self.StPrc_Sld_Move6.Bind(wx.EVT_SCROLL_CHANGED, lambda x: self.StPrcOnChange(1, 6))
self.StPrc_Pnl_Move6.Bind(wx.EVT_SET_FOCUS,
lambda x: self.StPrcOnFocus(3, 6, togglevalue=self.Tgl_StPrc_FocusButton6.GetValue()))
self.Tgl_StPrc_FocusButton6.Bind(wx.EVT_TOGGLEBUTTON, lambda x: self.StPrcOnFocus(3, 6,
togglevalue=self.Tgl_StPrc_FocusButton6.GetValue()))
#ToDo : FrameAction
self.Cmd_Up_NewProcess.Bind(wx.EVT_BUTTON, lambda x:self.StPrcFrameAction(1))
self.Cmd_Up_EditProcess.Bind(wx.EVT_BUTTON, lambda x:self.StPrcFrameAction())
self.Cmd_Up_DeleteProcess.Bind(wx.EVT_BUTTON, lambda x: self.StPrcFrameAction())
self.Cmd_Up_CancelNew.Bind(wx.EVT_BUTTON, lambda x: self.StPrcFrameAction(6))
self.Cmd_Down_Save.Bind(wx.EVT_BUTTON, lambda x: self.StPrcFrameAction(2))
# Connect Events
self.Cmd_StPrc_WidgetUseMouse.Bind(wx.EVT_BUTTON, lambda x:self.StPrcUseMouse())
self.Cmd_StPrc_WidgetUseController.Bind(wx.EVT_BUTTON, lambda x:self.StPrcUseController())
#ACTION
def StPrcFrameAction(self, mode):
#NEW PROSES
if mode == 1:
#ToDo : Enable & Disable
#Enable & Disable button
self.StPrcDisableStartNew()
self.Cmd_Up_CancelNew.Show()
self.StPrc_MakingNewProcess = True
pass
#SAVE TO Dviewlist
elif mode == 2:
#Check if value on slider is same with spinner and self.Nows
#ToDo : Func
container_valid = {}
container_value = {}
for i in range(6):
i += 1
is_valid, val = self.StPrcValuesValidator(i)
container_valid.update({i:is_valid})
container_value.update({i:val})
if len(container_valid) != 6:
validation = None
#ToDo : MsgBox
return
else:
validation = deepcopy(container_valid)
values = deepcopy(container_value)
list_valid = [x for x in validation.keys()].sort()
arraydata = {}
for item in list_valid:
arraydata.update({item:None})
if validation[item] == True:
sudut = values[item]#0`
#ToDo : Function To Check If Value Changes or Not
is_change = True
if is_change:
arraydata[item] = sudut
#DELETE
elif mode == 3:
pass
#DELETE ALL
elif mode == 4:
pass
#Check Detail
elif mode == 5:
pass
#CANCEL NEW PROCESS
elif mode == 6:
# Disable Mode
self.Cmd_StPrc_WidgetUseMouse.Disable()
self.Cmd_StPrc_WidgetUseController.Disable()
# Disable Dv Down Button
self.Cmd_Down_Save.Disable()
self.Cmd_Down_Delete.Disable()
self.Cmd_Down_DeleteAll.Disable()
self.Cmd_Down_CheckDetail.Disable()
self.Cmd_Up_CancelNew.Hide()
#VALIDATOR
def StPrcValuesValidator(self, mode):
if mode == 1:
val1 = self.StPrc_Sld_Move1.GetValue()
val2 = self.StPrc_Spn_Value1.GetValue()
val3 = self.CNows(2, need=int(mode))
data = [int(val1),int(val2),int(val3)]
elif mode == 2:
val1 = self.StPrc_Sld_Move2.GetValue()
val2 = self.StPrc_Spn_Value2.GetValue()
val3 = self.CNows(2, need=int(mode))
data = [int(val1),int(val2),int(val3)]
elif mode == 3:
val1 = self.StPrc_Sld_Move3.GetValue()
val2 = self.StPrc_Spn_Value3.GetValue()
val3 = self.CNows(2, need=int(mode))
data = [int(val1),int(val2),int(val3)]
elif mode == 4:
val1 = self.StPrc_Sld_Move4.GetValue()
val2 = self.StPrc_Spn_Value4.GetValue()
val3 = self.CNows(2, need=int(mode))
data = [int(val1),int(val2),int(val3)]
elif mode == 5:
val1 = self.StPrc_Sld_Move5.GetValue()
val2 = self.StPrc_Spn_Value5.GetValue()
val3 = self.CNows(2, need=int(mode))
data = [int(val1),int(val2),int(val3)]
elif mode == 6:
val1 = self.StPrc_Sld_Move6.GetValue()
val2 = self.StPrc_Spn_Value6.GetValue()
val3 = self.CNows(2, need=int(mode))
data = [int(val1),int(val2),int(val3)]
#Made it to Numpy array
data = array(data)
if float(val1) != float(data.mean()):
return ([False,float(val1)])
else:
return ([True,float(data.mean())])
#SET INACTIVE
def StPrcScrollSetINACT(self, mode):
if mode == 1:
self.Txt_StPrc_StatsFocus6.SetLabel('INACTIVE')
self.Tgl_StPrc_FocusButton6.SetValue(False)
self.Txt_StPrc_StatsFocus6.SetForegroundColour(wx.Colour(255, 0, 0))
elif mode == 2:
self.Txt_StPrc_StatsFocus5.SetLabel('INACTIVE')
self.Tgl_StPrc_FocusButton5.SetValue(False)
self.Txt_StPrc_StatsFocus5.SetForegroundColour(wx.Colour(255, 0, 0))
elif mode == 3:
self.Txt_StPrc_StatsFocus4.SetLabel('INACTIVE')
self.Tgl_StPrc_FocusButton4.SetValue(False)
self.Txt_StPrc_StatsFocus4.SetForegroundColour(wx.Colour(255, 0, 0))
elif mode == 4:
self.Txt_StPrc_StatsFocus3.SetLabel('INACTIVE')
self.Tgl_StPrc_FocusButton3.SetValue(False)
self.Txt_StPrc_StatsFocus3.SetForegroundColour(wx.Colour(255, 0, 0))
elif mode == 5:
self.Txt_StPrc_StatsFocus2.SetLabel('INACTIVE')
self.Tgl_StPrc_FocusButton2.SetValue(False)
self.Txt_StPrc_StatsFocus2.SetForegroundColour(wx.Colour(255, 0, 0))
elif mode == 6:
self.Txt_StPrc_StatsFocus1.SetLabel('INACTIVE')
self.Tgl_StPrc_FocusButton1.SetValue(False)
self.Txt_StPrc_StatsFocus1.SetForegroundColour(wx.Colour(255, 0, 0))
#ON FOCUS
def StPrcOnFocus(self, mode, type, **kwargs):
if mode == 1:
self.StPrc_CurrentSlider = type
elif mode == 2:
self.StPrc_CurrentSpin = type
elif mode == 3:
if type == 1:
self.StPrcScrollSetINACT(mode)
self.Txt_StPrc_StatsFocus1.SetLabel('ACTIVE')
self.Txt_StPrc_StatsFocus1.SetForegroundColour(wx.Colour(0, 255, 0))
self.StPrc_CurrentSlider = type
self.StPrc_CurrentSpin = type
# Deactivate
self.StPrcScrollSetINACT(1)
self.StPrcScrollSetINACT(2)
self.StPrcScrollSetINACT(3)
self.StPrcScrollSetINACT(4)
self.StPrcScrollSetINACT(5)
#self.StPrcScrollSetINACT(6)
elif type == 2:
self.StPrcScrollSetINACT(mode)
self.Txt_StPrc_StatsFocus2.SetLabel('ACTIVE')
self.Txt_StPrc_StatsFocus2.SetForegroundColour(wx.Colour(0, 255, 0))
self.StPrc_CurrentSlider = type
self.StPrc_CurrentSpin = type
# Deactivate
self.StPrcScrollSetINACT(1)
self.StPrcScrollSetINACT(2)
self.StPrcScrollSetINACT(3)
self.StPrcScrollSetINACT(4)
#self.StPrcScrollSetINACT(5)
self.StPrcScrollSetINACT(6)
elif type == 3:
self.StPrcScrollSetINACT(mode)
self.Txt_StPrc_StatsFocus3.SetLabel('ACTIVE')
self.Txt_StPrc_StatsFocus3.SetForegroundColour(wx.Colour(0, 255, 0))
self.StPrc_CurrentSlider = type
self.StPrc_CurrentSpin = type
# Deactivate
self.StPrcScrollSetINACT(1)
self.StPrcScrollSetINACT(2)
self.StPrcScrollSetINACT(3)
#self.StPrcScrollSetINACT(4)
self.StPrcScrollSetINACT(5)
self.StPrcScrollSetINACT(6)
elif type == 4:
self.StPrcScrollSetINACT(mode)
self.Txt_StPrc_StatsFocus4.SetLabel('ACTIVE')
self.Txt_StPrc_StatsFocus4.SetForegroundColour(wx.Colour(0, 255, 0))
self.StPrc_CurrentSlider = type
self.StPrc_CurrentSpin = type
# Deactivate
self.StPrcScrollSetINACT(1)
self.StPrcScrollSetINACT(2)
#self.StPrcScrollSetINACT(3)
self.StPrcScrollSetINACT(4)
self.StPrcScrollSetINACT(5)
self.StPrcScrollSetINACT(6)
elif type == 5:
self.StPrcScrollSetINACT(mode)
self.Txt_StPrc_StatsFocus5.SetLabel('ACTIVE')
self.Txt_StPrc_StatsFocus5.SetForegroundColour(wx.Colour(0, 255, 0))
self.StPrc_CurrentSlider = type
self.StPrc_CurrentSpin = type
# Deactivate
self.StPrcScrollSetINACT(1)
#self.StPrcScrollSetINACT(2)
self.StPrcScrollSetINACT(3)
self.StPrcScrollSetINACT(4)
self.StPrcScrollSetINACT(5)
self.StPrcScrollSetINACT(6)
elif type == 6:
self.StPrcScrollSetINACT(mode)
self.Txt_StPrc_StatsFocus6.SetLabel('ACTIVE')
self.Txt_StPrc_StatsFocus6.SetForegroundColour(wx.Colour(0, 255, 0))
self.StPrc_CurrentSlider = type
self.StPrc_CurrentSpin = type
#Deactivate
#self.StPrcScrollSetINACT(1)
self.StPrcScrollSetINACT(2)
self.StPrcScrollSetINACT(3)
self.StPrcScrollSetINACT(4)
self.StPrcScrollSetINACT(5)
self.StPrcScrollSetINACT(6)
self.CurrentFocus = type
#ON CHANGE
def StPrcOnChange(self, mode , type):
#SLIDER MOVEMENT
self.StPrc_CurrentSlider = type
self.StPrc_CurrentSpin = type
self.CurrentFocus = self.StPrc_CurrentSlider
if mode == 1:
if self.StPrc_CurrentSlider == 1:
self.StPrcOnFocus(3, 1, togglevalue=self.Tgl_StPrc_FocusButton1.GetValue())
values = self.CCalculate('SPIN-SLIDER', 3, value=self.StPrc_Sld_Move1.GetValue(),
inc=self.StPrc_Spn_Value1.GetIncrement())
self.StPrc_Spn_Value1.SetValue(values)
elif self.StPrc_CurrentSlider == 2:
self.StPrcOnFocus(3, 2, togglevalue=self.Tgl_StPrc_FocusButton2.GetValue())
values = self.CCalculate('SPIN-SLIDER', 3, value=self.StPrc_Sld_Move2.GetValue(),
inc=self.StPrc_Spn_Value2.GetIncrement())
self.StPrc_Spn_Value2.SetValue(values)
elif self.StPrc_CurrentSlider == 3:
self.StPrcOnFocus(3, 3, togglevalue=self.Tgl_StPrc_FocusButton3.GetValue())
values = self.CCalculate('SPIN-SLIDER', 3, value=self.StPrc_Sld_Move3.GetValue(),
inc=self.StPrc_Spn_Value3.GetIncrement())
self.StPrc_Spn_Value3.SetValue(values)
elif self.StPrc_CurrentSlider == 4:
self.StPrcOnFocus(3, 4, togglevalue=self.Tgl_StPrc_FocusButton4.GetValue())
values = self.CCalculate('SPIN-SLIDER', 3, value=self.StPrc_Sld_Move4.GetValue(),
inc=self.StPrc_Spn_Value4.GetIncrement())
self.StPrc_Spn_Value4.SetValue(values)
elif self.StPrc_CurrentSlider == 5:
self.StPrcOnFocus(3, 5, togglevalue=self.Tgl_StPrc_FocusButton5.GetValue())
values = self.CCalculate('SPIN-SLIDER', 3, value=self.StPrc_Sld_Move5.GetValue(),
inc=self.StPrc_Spn_Value5.GetIncrement())
self.StPrc_Spn_Value5.SetValue(values)
elif self.StPrc_CurrentSlider == 6:
self.StPrcOnFocus(3, 6, togglevalue=self.Tgl_StPrc_FocusButton6.GetValue())
values = self.CCalculate('SPIN-SLIDER', 3, value=self.StPrc_Sld_Move6.GetValue(),
inc=self.StPrc_Spn_Value6.GetIncrement())
self.StPrc_Spn_Value6.SetValue(values)
else:
return
self.CPrintDebug(2, object=self.Logger_List['Main-Log'],
message=('value sld>>spn [' + str(self.StPrc_CurrentSlider)+'] = ' + str(values)))
elif mode == 2:
if self.StPrc_CurrentSpin == 1:
self.StPrcOnFocus(3, 1, togglevalue=self.Tgl_StPrc_FocusButton1.GetValue())
values = self.CCalculate('SPIN-SLIDER', 2, value=self.StPrc_Spn_Value1.GetValue(),
inc=self.StPrc_Spn_Value6.GetIncrement())
self.StPrc_Sld_Move1.SetValue(values)
elif self.StPrc_CurrentSpin == 2:
self.StPrcOnFocus(3, 2, togglevalue=self.Tgl_StPrc_FocusButton2.GetValue())
values = self.CCalculate('SPIN-SLIDER', 2, value=self.StPrc_Spn_Value2.GetValue(),
inc=self.StPrc_Spn_Value2.GetIncrement())
self.StPrc_Sld_Move2.SetValue(values)
elif self.StPrc_CurrentSpin == 3:
self.StPrcOnFocus(3, 3, togglevalue=self.Tgl_StPrc_FocusButton3.GetValue())
values = self.CCalculate('SPIN-SLIDER', 2, value=self.StPrc_Spn_Value3.GetValue(),
inc=self.StPrc_Spn_Value3.GetIncrement())
self.StPrc_Sld_Move3.SetValue(values)
elif self.StPrc_CurrentSpin == 4:
self.StPrcOnFocus(3, 4 , togglevalue=self.Tgl_StPrc_FocusButton4.GetValue())
values = self.CCalculate('SPIN-SLIDER', 2, value=self.StPrc_Spn_Value4.GetValue(),
inc=self.StPrc_Spn_Value4.GetIncrement())
self.StPrc_Sld_Move4.SetValue(values)
elif self.StPrc_CurrentSpin== 5:
self.StPrcOnFocus(3, 5, togglevalue=self.Tgl_StPrc_FocusButton5.GetValue())
values = self.CCalculate('SPIN-SLIDER', 2, value=self.StPrc_Spn_Value5.GetValue(),
inc=self.StPrc_Spn_Value5.GetIncrement())
self.StPrc_Sld_Move5.SetValue(values)
elif self.StPrc_CurrentSpin == 6:
self.StPrcOnFocus(3, 6, togglevalue=self.Tgl_StPrc_FocusButton6.GetValue())
values = self.CCalculate('SPIN-SLIDER', 2, value=self.StPrc_Spn_Value6.GetValue(),
inc=self.StPrc_Spn_Value6.GetIncrement())
self.StPrc_Sld_Move6.SetValue(values)
else:
return
self.CPrintDebug(2, object=self.Logger_List['Main-Log'],
message=('value spn>>sld ['+str(self.StPrc_CurrentSpin)+'] = ' + str(values)))
#PANEL CONTROL
def StPrcPanelControl(self, parent):
self.StPrc_Pnl_Main = wx.Panel(parent, wx.ID_ANY, wx.DefaultPosition, wx.Size(720, -1), wx.TAB_TRAVERSAL)
try:
# pick an image file you have in the working folder
# you can load .jpg .png .bmp or .gif files
image_file = os.path.normpath('.\\images\\background.png')
bmp1 = wx.Image(image_file, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
# image's upper left corner anchors at panel coordinates (0, 0)
self.Bit_StPrc_Background_Setup = wx.StaticBitmap(self.StPrc_Pnl_Main, -1, bmp1, pos=(0, 0))
# show some image details
str1 = "%s %dx%d" % (image_file, bmp1.GetWidth(), bmp1.GetHeight())
except IOError:
print "Image file %s not found" % image_file
raise SystemExit
# button goes on the image --> self.bitmap1 is the parent
# PANEL 1
self.StPrc_Pnl_Move6 = wx.Panel(self.Bit_StPrc_Background_Setup, wx.ID_ANY, wx.Point(10, 120), wx.Size(170, 60),
wx.TAB_TRAVERSAL)
# SET ID BASED BY MOTOR ID
self.StPrc_Pnl_Move6.SetId(1)
self.StPrc_Pnl_Move6.SetBackgroundColour(wx.Colour(255, 255, 255))
fgSizer17 = wx.FlexGridSizer(1, 2, 0, 0)
fgSizer17.SetFlexibleDirection(wx.BOTH)
fgSizer17.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Pnl_StPrcStats6 = wx.Panel(self.StPrc_Pnl_Move6, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, -1),
wx.TAB_TRAVERSAL)
self.Pnl_StPrcStats6.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION))
fgSizer18 = wx.FlexGridSizer(2, 1, 0, 0)
fgSizer18.SetFlexibleDirection(wx.BOTH)
fgSizer18.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Tgl_StPrc_FocusButton6 = wx.ToggleButton(self.Pnl_StPrcStats6, wx.ID_ANY, u"6", wx.DefaultPosition,
wx.Size(50, 50), 0)
self.Tgl_StPrc_FocusButton6.SetValue(False)
self.Tgl_StPrc_FocusButton6.SetFont(wx.Font(36, 74, 90, 92, False, "Arial"))
self.Tgl_StPrc_FocusButton6.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
fgSizer18.Add(self.Tgl_StPrc_FocusButton6, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, 5)
self.Txt_StPrc_StatsFocus6 = wx.StaticText(self.Pnl_StPrcStats6, wx.ID_ANY, u"INACTIVE", wx.DefaultPosition,
wx.Size(70, 15), wx.ALIGN_CENTRE)
self.Txt_StPrc_StatsFocus6.Wrap(-1)
self.Txt_StPrc_StatsFocus6.SetFont(wx.Font(11, 74, 90, 92, False, "Arial"))
self.Txt_StPrc_StatsFocus6.SetForegroundColour(wx.Colour(255, 0, 0))
self.Txt_StPrc_StatsFocus6.SetBackgroundColour(wx.Colour(0, 0, 0))
fgSizer18.Add(self.Txt_StPrc_StatsFocus6, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
self.Pnl_StPrcStats6.SetSizer(fgSizer18)
self.Pnl_StPrcStats6.Layout()
fgSizer18.Fit(self.Pnl_StPrcStats6)
fgSizer17.Add(self.Pnl_StPrcStats6, 1, wx.EXPAND | wx.ALL, 0)
self.Pnl_StPrc_Scroll6 = wx.Panel(self.StPrc_Pnl_Move6, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
wx.TAB_TRAVERSAL)
self.Pnl_StPrc_Scroll6.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
fgSizer19 = wx.FlexGridSizer(1, 1, 0, 0)
fgSizer19.SetFlexibleDirection(wx.BOTH)
fgSizer19.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizer19.SetMinSize(wx.Size(-1, 80))
bSizer9 = wx.BoxSizer(wx.VERTICAL)
self.Lbl_StPrc_Jdl_Sudut6 = wx.StaticText(self.Pnl_StPrc_Scroll6, wx.ID_ANY, u"Sudut Axis", wx.DefaultPosition,
wx.DefaultSize, 0)
self.Lbl_StPrc_Jdl_Sudut6.Wrap(-1)
self.Lbl_StPrc_Jdl_Sudut6.SetFont(wx.Font(10, 74, 90, 92, False, "Arial"))
bSizer9.Add(self.Lbl_StPrc_Jdl_Sudut6, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)
self.StPrc_Sld_Move6 = wx.Slider(self.Pnl_StPrc_Scroll6, wx.ID_ANY, 50, 0, 100, wx.DefaultPosition,
wx.Size(130, 20),
wx.SL_HORIZONTAL)
bSizer9.Add(self.StPrc_Sld_Move6, 0, wx.ALL, 5)
self.StPrc_Spn_Value6 = wx.SpinCtrlDouble(self.Pnl_StPrc_Scroll6, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
wx.DefaultSize,
wx.SP_ARROW_KEYS, 0, 100, 0)
bSizer9.Add(self.StPrc_Spn_Value6, 0, wx.ALL, 5)
fgSizer19.Add(bSizer9, 1, wx.EXPAND, 5)
self.Pnl_StPrc_Scroll6.SetSizer(fgSizer19)
self.Pnl_StPrc_Scroll6.Layout()
fgSizer19.Fit(self.Pnl_StPrc_Scroll6)
fgSizer17.Add(self.Pnl_StPrc_Scroll6, 1, wx.EXPAND | wx.ALL, 0)
self.StPrc_Pnl_Move6.SetSizer(fgSizer17)
self.StPrc_Pnl_Move6.Layout()
fgSizer17.Fit(self.StPrc_Pnl_Move6)
# PANEL 2
self.StPrc_Pnl_Move5 = wx.Panel(self.Bit_StPrc_Background_Setup, wx.ID_ANY, wx.Point(375, 10), wx.Size(170, 60),
wx.TAB_TRAVERSAL)
# SET ID BASED BY MOTOR ID
self.StPrc_Pnl_Move5.SetId(2)
self.StPrc_Pnl_Move5.SetBackgroundColour(wx.Colour(255, 255, 255))
fgSizer17 = wx.FlexGridSizer(1, 2, 0, 0)
fgSizer17.SetFlexibleDirection(wx.BOTH)
fgSizer17.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Pnl_StPrcStats5 = wx.Panel(self.StPrc_Pnl_Move5, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, -1),
wx.TAB_TRAVERSAL)
self.Pnl_StPrcStats5.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION))
fgSizer18 = wx.FlexGridSizer(2, 1, 0, 0)
fgSizer18.SetFlexibleDirection(wx.BOTH)
fgSizer18.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Tgl_StPrc_FocusButton5 = wx.ToggleButton(self.Pnl_StPrcStats5, wx.ID_ANY, u"5", wx.DefaultPosition,
wx.Size(50, 50), 0)
self.Tgl_StPrc_FocusButton5.SetValue(False)
self.Tgl_StPrc_FocusButton5.SetFont(wx.Font(36, 74, 90, 92, False, "Arial"))
self.Tgl_StPrc_FocusButton5.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
fgSizer18.Add(self.Tgl_StPrc_FocusButton5, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, 5)
self.Txt_StPrc_StatsFocus5 = wx.StaticText(self.Pnl_StPrcStats5, wx.ID_ANY, u"INACTIVE", wx.DefaultPosition,
wx.Size(70, 15), wx.ALIGN_CENTRE)
self.Txt_StPrc_StatsFocus5.Wrap(-1)
self.Txt_StPrc_StatsFocus5.SetFont(wx.Font(11, 74, 90, 92, False, "Arial"))
self.Txt_StPrc_StatsFocus5.SetForegroundColour(wx.Colour(255, 0, 0))
self.Txt_StPrc_StatsFocus5.SetBackgroundColour(wx.Colour(0, 0, 0))
fgSizer18.Add(self.Txt_StPrc_StatsFocus5, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
self.Pnl_StPrcStats5.SetSizer(fgSizer18)
self.Pnl_StPrcStats5.Layout()
fgSizer18.Fit(self.Pnl_StPrcStats5)
fgSizer17.Add(self.Pnl_StPrcStats5, 1, wx.EXPAND | wx.ALL, 0)
self.Pnl_StPrc_Scroll5 = wx.Panel(self.StPrc_Pnl_Move5, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
wx.TAB_TRAVERSAL)
self.Pnl_StPrc_Scroll5.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
fgSizer19 = wx.FlexGridSizer(1, 1, 0, 0)
fgSizer19.SetFlexibleDirection(wx.BOTH)
fgSizer19.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizer19.SetMinSize(wx.Size(-1, 80))
bSizer9 = wx.BoxSizer(wx.VERTICAL)
self.Lbl_StPrc_Jdl_Sudut5 = wx.StaticText(self.Pnl_StPrc_Scroll5, wx.ID_ANY, u"Sudut Axis", wx.DefaultPosition,
wx.DefaultSize, 0)
self.Lbl_StPrc_Jdl_Sudut5.Wrap(-1)
self.Lbl_StPrc_Jdl_Sudut5.SetFont(wx.Font(10, 74, 90, 92, False, "Arial"))
bSizer9.Add(self.Lbl_StPrc_Jdl_Sudut5, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)
self.StPrc_Sld_Move5 = wx.Slider(self.Pnl_StPrc_Scroll5, wx.ID_ANY, 50, 0, 100, wx.DefaultPosition,
wx.Size(130, 20),
wx.SL_HORIZONTAL)
bSizer9.Add(self.StPrc_Sld_Move5, 0, wx.ALL, 5)
self.StPrc_Spn_Value5 = wx.SpinCtrlDouble(self.Pnl_StPrc_Scroll5, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
wx.DefaultSize,
wx.SP_ARROW_KEYS, 0, 100, 0)
bSizer9.Add(self.StPrc_Spn_Value5, 0, wx.ALL, 5)
fgSizer19.Add(bSizer9, 1, wx.EXPAND, 5)
self.Pnl_StPrc_Scroll5.SetSizer(fgSizer19)
self.Pnl_StPrc_Scroll5.Layout()
fgSizer19.Fit(self.Pnl_StPrc_Scroll5)
fgSizer17.Add(self.Pnl_StPrc_Scroll5, 1, wx.EXPAND | wx.ALL, 0)
self.StPrc_Pnl_Move5.SetSizer(fgSizer17)
self.StPrc_Pnl_Move5.Layout()
fgSizer17.Fit(self.StPrc_Pnl_Move5)
# PANEL 3
self.StPrc_Pnl_Move4 = wx.Panel(self.Bit_StPrc_Background_Setup, wx.ID_ANY, wx.Point(55, 235), wx.Size(170, 60),
wx.TAB_TRAVERSAL)
# SET ID BASED BY MOTOR ID
self.StPrc_Pnl_Move4.SetId(3)
self.StPrc_Pnl_Move4.SetBackgroundColour(wx.Colour(255, 255, 255))
fgSizer17 = wx.FlexGridSizer(1, 2, 0, 0)
fgSizer17.SetFlexibleDirection(wx.BOTH)
fgSizer17.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Pnl_StPrcStats4 = wx.Panel(self.StPrc_Pnl_Move4, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, -1),
wx.TAB_TRAVERSAL)
self.Pnl_StPrcStats4.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION))
fgSizer18 = wx.FlexGridSizer(2, 1, 0, 0)
fgSizer18.SetFlexibleDirection(wx.BOTH)
fgSizer18.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Tgl_StPrc_FocusButton4 = wx.ToggleButton(self.Pnl_StPrcStats4, wx.ID_ANY, u"4", wx.DefaultPosition,
wx.Size(50, 50), 0)
self.Tgl_StPrc_FocusButton4.SetValue(False)
self.Tgl_StPrc_FocusButton4.SetFont(wx.Font(36, 74, 90, 92, False, "Arial"))
self.Tgl_StPrc_FocusButton4.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
fgSizer18.Add(self.Tgl_StPrc_FocusButton4, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, 5)
self.Txt_StPrc_StatsFocus4 = wx.StaticText(self.Pnl_StPrcStats4, wx.ID_ANY, u"INACTIVE", wx.DefaultPosition,
wx.Size(70, 15), wx.ALIGN_CENTRE)
self.Txt_StPrc_StatsFocus4.Wrap(-1)
self.Txt_StPrc_StatsFocus4.SetFont(wx.Font(11, 74, 90, 92, False, "Arial"))
self.Txt_StPrc_StatsFocus4.SetForegroundColour(wx.Colour(255, 0, 0))
self.Txt_StPrc_StatsFocus4.SetBackgroundColour(wx.Colour(0, 0, 0))
fgSizer18.Add(self.Txt_StPrc_StatsFocus4, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
self.Pnl_StPrcStats4.SetSizer(fgSizer18)
self.Pnl_StPrcStats4.Layout()
fgSizer18.Fit(self.Pnl_StPrcStats4)
fgSizer17.Add(self.Pnl_StPrcStats4, 1, wx.EXPAND | wx.ALL, 0)
self.Pnl_StPrc_Scroll4 = wx.Panel(self.StPrc_Pnl_Move4, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
wx.TAB_TRAVERSAL)
self.Pnl_StPrc_Scroll4.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
fgSizer19 = wx.FlexGridSizer(1, 1, 0, 0)
fgSizer19.SetFlexibleDirection(wx.BOTH)
fgSizer19.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizer19.SetMinSize(wx.Size(-1, 80))
bSizer9 = wx.BoxSizer(wx.VERTICAL)
self.Lbl_StPrc_Jdl_Sudut4 = wx.StaticText(self.Pnl_StPrc_Scroll4, wx.ID_ANY, u"Sudut Axis", wx.DefaultPosition,
wx.DefaultSize, 0)
self.Lbl_StPrc_Jdl_Sudut4.Wrap(-1)
self.Lbl_StPrc_Jdl_Sudut4.SetFont(wx.Font(10, 74, 90, 92, False, "Arial"))
bSizer9.Add(self.Lbl_StPrc_Jdl_Sudut4, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)
self.StPrc_Sld_Move4 = wx.Slider(self.Pnl_StPrc_Scroll4, wx.ID_ANY, 50, 0, 100, wx.DefaultPosition,
wx.Size(130, 20),
wx.SL_HORIZONTAL)
bSizer9.Add(self.StPrc_Sld_Move4, 0, wx.ALL, 5)
self.StPrc_Spn_Value4 = wx.SpinCtrlDouble(self.Pnl_StPrc_Scroll4, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
wx.DefaultSize,
wx.SP_ARROW_KEYS, 0, 100, 0)
bSizer9.Add(self.StPrc_Spn_Value4, 0, wx.ALL, 5)
fgSizer19.Add(bSizer9, 1, wx.EXPAND, 5)
self.Pnl_StPrc_Scroll4.SetSizer(fgSizer19)
self.Pnl_StPrc_Scroll4.Layout()
fgSizer19.Fit(self.Pnl_StPrc_Scroll4)
fgSizer17.Add(self.Pnl_StPrc_Scroll4, 1, wx.EXPAND | wx.ALL, 0)
self.StPrc_Pnl_Move4.SetSizer(fgSizer17)
self.StPrc_Pnl_Move4.Layout()
fgSizer17.Fit(self.StPrc_Pnl_Move4)
# PANEL 4
self.StPrc_Pnl_Move3 = wx.Panel(self.Bit_StPrc_Background_Setup, wx.ID_ANY, wx.Point(455, 125), wx.Size(170, 60),
wx.TAB_TRAVERSAL)
# SET ID BASED BY MOTOR ID
self.StPrc_Pnl_Move3.SetId(4)
self.StPrc_Pnl_Move3.SetBackgroundColour(wx.Colour(255, 255, 255))
fgSizer17 = wx.FlexGridSizer(1, 2, 0, 0)
fgSizer17.SetFlexibleDirection(wx.BOTH)
fgSizer17.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Pnl_StPrcStats3 = wx.Panel(self.StPrc_Pnl_Move3, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, -1),
wx.TAB_TRAVERSAL)
self.Pnl_StPrcStats3.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION))
fgSizer18 = wx.FlexGridSizer(2, 1, 0, 0)
fgSizer18.SetFlexibleDirection(wx.BOTH)
fgSizer18.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Tgl_StPrc_FocusButton3 = wx.ToggleButton(self.Pnl_StPrcStats3, wx.ID_ANY, u"3", wx.DefaultPosition,
wx.Size(50, 50), 0)
self.Tgl_StPrc_FocusButton3.SetValue(False)
self.Tgl_StPrc_FocusButton3.SetFont(wx.Font(36, 74, 90, 92, False, "Arial"))
self.Tgl_StPrc_FocusButton3.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
fgSizer18.Add(self.Tgl_StPrc_FocusButton3, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, 5)
self.Txt_StPrc_StatsFocus3 = wx.StaticText(self.Pnl_StPrcStats3, wx.ID_ANY, u"INACTIVE", wx.DefaultPosition,
wx.Size(70, 15), wx.ALIGN_CENTRE)
self.Txt_StPrc_StatsFocus3.Wrap(-1)
self.Txt_StPrc_StatsFocus3.SetFont(wx.Font(11, 74, 90, 92, False, "Arial"))
self.Txt_StPrc_StatsFocus3.SetForegroundColour(wx.Colour(255, 0, 0))
self.Txt_StPrc_StatsFocus3.SetBackgroundColour(wx.Colour(0, 0, 0))
fgSizer18.Add(self.Txt_StPrc_StatsFocus3, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
self.Pnl_StPrcStats3.SetSizer(fgSizer18)
self.Pnl_StPrcStats3.Layout()
fgSizer18.Fit(self.Pnl_StPrcStats3)
fgSizer17.Add(self.Pnl_StPrcStats3, 1, wx.EXPAND | wx.ALL, 0)
self.Pnl_StPrc_Scroll3 = wx.Panel(self.StPrc_Pnl_Move3, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
wx.TAB_TRAVERSAL)
self.Pnl_StPrc_Scroll3.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
fgSizer19 = wx.FlexGridSizer(1, 1, 0, 0)
fgSizer19.SetFlexibleDirection(wx.BOTH)
fgSizer19.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizer19.SetMinSize(wx.Size(-1, 80))
bSizer9 = wx.BoxSizer(wx.VERTICAL)
self.Lbl_StPrc_Jdl_Sudut3 = wx.StaticText(self.Pnl_StPrc_Scroll3, wx.ID_ANY, u"Sudut Axis", wx.DefaultPosition,
wx.DefaultSize, 0)
self.Lbl_StPrc_Jdl_Sudut3.Wrap(-1)
self.Lbl_StPrc_Jdl_Sudut3.SetFont(wx.Font(10, 74, 90, 92, False, "Arial"))
bSizer9.Add(self.Lbl_StPrc_Jdl_Sudut3, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)
self.StPrc_Sld_Move3 = wx.Slider(self.Pnl_StPrc_Scroll3, wx.ID_ANY, 50, 0, 100, wx.DefaultPosition,
wx.Size(130, 20),
wx.SL_HORIZONTAL)
bSizer9.Add(self.StPrc_Sld_Move3, 0, wx.ALL, 5)
self.StPrc_Spn_Value3 = wx.SpinCtrlDouble(self.Pnl_StPrc_Scroll3, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
wx.DefaultSize,
wx.SP_ARROW_KEYS, 0, 100, 0)
bSizer9.Add(self.StPrc_Spn_Value3, 0, wx.ALL, 5)
fgSizer19.Add(bSizer9, 1, wx.EXPAND, 5)
self.Pnl_StPrc_Scroll3.SetSizer(fgSizer19)
self.Pnl_StPrc_Scroll3.Layout()
fgSizer19.Fit(self.Pnl_StPrc_Scroll3)
fgSizer17.Add(self.Pnl_StPrc_Scroll3, 1, wx.EXPAND | wx.ALL, 0)
self.StPrc_Pnl_Move3.SetSizer(fgSizer17)
self.StPrc_Pnl_Move3.Layout()
fgSizer17.Fit(self.StPrc_Pnl_Move3)
# PANEL 5
self.StPrc_Pnl_Move2 = wx.Panel(self.Bit_StPrc_Background_Setup, wx.ID_ANY, wx.Point(20, 360), wx.Size(170, 60),
wx.TAB_TRAVERSAL)
# SET ID BASED BY MOTOR ID
self.StPrc_Pnl_Move2.SetId(5)
self.StPrc_Pnl_Move2.SetBackgroundColour(wx.Colour(255, 255, 255))
fgSizer17 = wx.FlexGridSizer(1, 2, 0, 0)
fgSizer17.SetFlexibleDirection(wx.BOTH)
fgSizer17.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Pnl_StPrcStats2 = wx.Panel(self.StPrc_Pnl_Move2, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, -1),
wx.TAB_TRAVERSAL)
self.Pnl_StPrcStats2.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION))
fgSizer18 = wx.FlexGridSizer(2, 1, 0, 0)
fgSizer18.SetFlexibleDirection(wx.BOTH)
fgSizer18.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Tgl_StPrc_FocusButton2 = wx.ToggleButton(self.Pnl_StPrcStats2, wx.ID_ANY, u"2", wx.DefaultPosition,
wx.Size(50, 50), 0)
self.Tgl_StPrc_FocusButton2.SetValue(False)
self.Tgl_StPrc_FocusButton2.SetFont(wx.Font(36, 74, 90, 92, False, "Arial"))
self.Tgl_StPrc_FocusButton2.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
fgSizer18.Add(self.Tgl_StPrc_FocusButton2, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, 5)
self.Txt_StPrc_StatsFocus2 = wx.StaticText(self.Pnl_StPrcStats2, wx.ID_ANY, u"INACTIVE", wx.DefaultPosition,
wx.Size(70, 15), wx.ALIGN_CENTRE)
self.Txt_StPrc_StatsFocus2.Wrap(-1)
self.Txt_StPrc_StatsFocus2.SetFont(wx.Font(11, 74, 90, 92, False, "Arial"))
self.Txt_StPrc_StatsFocus2.SetForegroundColour(wx.Colour(255, 0, 0))
self.Txt_StPrc_StatsFocus2.SetBackgroundColour(wx.Colour(0, 0, 0))
fgSizer18.Add(self.Txt_StPrc_StatsFocus2, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
self.Pnl_StPrcStats2.SetSizer(fgSizer18)
self.Pnl_StPrcStats2.Layout()
fgSizer18.Fit(self.Pnl_StPrcStats2)
fgSizer17.Add(self.Pnl_StPrcStats2, 1, wx.EXPAND | wx.ALL, 0)
self.Pnl_StPrc_Scroll2 = wx.Panel(self.StPrc_Pnl_Move2, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
wx.TAB_TRAVERSAL)
self.Pnl_StPrc_Scroll2.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
fgSizer19 = wx.FlexGridSizer(1, 1, 0, 0)
fgSizer19.SetFlexibleDirection(wx.BOTH)
fgSizer19.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizer19.SetMinSize(wx.Size(-1, 80))
bSizer9 = wx.BoxSizer(wx.VERTICAL)
self.Lbl_StPrc_Jdl_Sudut2 = wx.StaticText(self.Pnl_StPrc_Scroll2, wx.ID_ANY, u"Sudut Axis", wx.DefaultPosition,
wx.DefaultSize, 0)
self.Lbl_StPrc_Jdl_Sudut2.Wrap(-1)
self.Lbl_StPrc_Jdl_Sudut2.SetFont(wx.Font(10, 74, 90, 92, False, "Arial"))
bSizer9.Add(self.Lbl_StPrc_Jdl_Sudut2, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)
self.StPrc_Sld_Move2 = wx.Slider(self.Pnl_StPrc_Scroll2, wx.ID_ANY, 50, 0, 100, wx.DefaultPosition,
wx.Size(130, 20),
wx.SL_HORIZONTAL)
bSizer9.Add(self.StPrc_Sld_Move2, 0, wx.ALL, 5)
self.StPrc_Spn_Value2 = wx.SpinCtrlDouble(self.Pnl_StPrc_Scroll2, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
wx.DefaultSize,
wx.SP_ARROW_KEYS, 0, 100, 0)
bSizer9.Add(self.StPrc_Spn_Value2, 0, wx.ALL, 5)
fgSizer19.Add(bSizer9, 1, wx.EXPAND, 5)
self.Pnl_StPrc_Scroll2.SetSizer(fgSizer19)
self.Pnl_StPrc_Scroll2.Layout()
fgSizer19.Fit(self.Pnl_StPrc_Scroll2)
fgSizer17.Add(self.Pnl_StPrc_Scroll2, 1, wx.EXPAND | wx.ALL, 0)
self.StPrc_Pnl_Move2.SetSizer(fgSizer17)
self.StPrc_Pnl_Move2.Layout()
fgSizer17.Fit(self.StPrc_Pnl_Move2)
# PANEL 6
self.StPrc_Pnl_Move1 = wx.Panel(self.Bit_StPrc_Background_Setup, wx.ID_ANY, wx.Point(450, 280), wx.Size(170, 60),
wx.TAB_TRAVERSAL)
# SET ID BASED BY MOTOR ID
self.StPrc_Pnl_Move1.SetId(6)
self.StPrc_Pnl_Move1.SetBackgroundColour(wx.Colour(255, 255, 255))
fgSizer17 = wx.FlexGridSizer(1, 2, 0, 0)
fgSizer17.SetFlexibleDirection(wx.BOTH)
fgSizer17.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Pnl_StPrcStats1 = wx.Panel(self.StPrc_Pnl_Move1, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1, -1),
wx.TAB_TRAVERSAL)
self.Pnl_StPrcStats1.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_INACTIVECAPTION))
fgSizer18 = wx.FlexGridSizer(2, 1, 0, 0)
fgSizer18.SetFlexibleDirection(wx.BOTH)
fgSizer18.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Tgl_StPrc_FocusButton1 = wx.ToggleButton(self.Pnl_StPrcStats1, wx.ID_ANY, u"1", wx.DefaultPosition,
wx.Size(50, 50), 0)
self.Tgl_StPrc_FocusButton1.SetValue(False)
self.Tgl_StPrc_FocusButton1.SetFont(wx.Font(36, 74, 90, 92, False, "Arial"))
self.Tgl_StPrc_FocusButton1.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
fgSizer18.Add(self.Tgl_StPrc_FocusButton1, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, 5)
self.Txt_StPrc_StatsFocus1 = wx.StaticText(self.Pnl_StPrcStats1, wx.ID_ANY, u"INACTIVE", wx.DefaultPosition,
wx.Size(70, 15), wx.ALIGN_CENTRE)
self.Txt_StPrc_StatsFocus1.Wrap(-1)
self.Txt_StPrc_StatsFocus1.SetFont(wx.Font(11, 74, 90, 92, False, "Arial"))
self.Txt_StPrc_StatsFocus1.SetForegroundColour(wx.Colour(255, 0, 0))
self.Txt_StPrc_StatsFocus1.SetBackgroundColour(wx.Colour(0, 0, 0))
fgSizer18.Add(self.Txt_StPrc_StatsFocus1, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
self.Pnl_StPrcStats1.SetSizer(fgSizer18)
self.Pnl_StPrcStats1.Layout()
fgSizer18.Fit(self.Pnl_StPrcStats1)
fgSizer17.Add(self.Pnl_StPrcStats1, 1, wx.EXPAND | wx.ALL, 0)
self.Pnl_StPrc_Scroll1 = wx.Panel(self.StPrc_Pnl_Move1, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
wx.TAB_TRAVERSAL)
self.Pnl_StPrc_Scroll1.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
fgSizer19 = wx.FlexGridSizer(1, 1, 0, 0)
fgSizer19.SetFlexibleDirection(wx.BOTH)
fgSizer19.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizer19.SetMinSize(wx.Size(-1, 80))
bSizer9 = wx.BoxSizer(wx.VERTICAL)
self.Lbl_StPrc_Jdl_Sudut1 = wx.StaticText(self.Pnl_StPrc_Scroll1, wx.ID_ANY, u"Sudut Axis", wx.DefaultPosition,
wx.DefaultSize, 0)
self.Lbl_StPrc_Jdl_Sudut1.Wrap(-1)
self.Lbl_StPrc_Jdl_Sudut1.SetFont(wx.Font(10, 74, 90, 92, False, "Arial"))
bSizer9.Add(self.Lbl_StPrc_Jdl_Sudut1, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)
self.StPrc_Sld_Move1 = wx.Slider(self.Pnl_StPrc_Scroll1, wx.ID_ANY, 50, 0, 100, wx.DefaultPosition,
wx.Size(130, 20),
wx.SL_HORIZONTAL)
bSizer9.Add(self.StPrc_Sld_Move1, 0, wx.ALL, 5)
self.StPrc_Spn_Value1 = wx.SpinCtrlDouble(self.Pnl_StPrc_Scroll1, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
wx.DefaultSize,
wx.SP_ARROW_KEYS, 0, 100, 0)
bSizer9.Add(self.StPrc_Spn_Value1, 0, wx.ALL, 5)
fgSizer19.Add(bSizer9, 1, wx.EXPAND, 5)
self.Pnl_StPrc_Scroll1.SetSizer(fgSizer19)
self.Pnl_StPrc_Scroll1.Layout()
fgSizer19.Fit(self.Pnl_StPrc_Scroll1)
fgSizer17.Add(self.Pnl_StPrc_Scroll1, 1, wx.EXPAND | wx.ALL, 0)
self.StPrc_Pnl_Move1.SetSizer(fgSizer17)
self.StPrc_Pnl_Move1.Layout()
fgSizer17.Fit(self.StPrc_Pnl_Move1)
#PANEL VIEW
def StPrcPanelView(self):
self.Pnl_StPrc_View = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1,600),
wx.TAB_TRAVERSAL | wx.TRANSPARENT_WINDOW)
if self.Pnl_StPrc_View.CanSetTransparent:
print 'can'
self.Pnl_StPrc_View.SetTransparent(100)
else:
print 'cant'
try:
# pick an image file you have in the working folder
# you can load .jpg .png .bmp or .gif files
image_file = os.path.normpath('.\\images\\background2.png')
bmp1 = wx.Image(image_file, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
# image's upper left corner anchors at panel coordinates (0, 0)
self.Bit_StPrc_Background_Setup2 = wx.StaticBitmap(self.Pnl_StPrc_View, -1, bmp1, pos=(0, 0))
# show some image details
str1 = "%s %dx%d" % (image_file, bmp1.GetWidth(), bmp1.GetHeight())
except IOError:
print "Image file %s not found" % image_file
raise SystemExit
self.Pnl_StPrc_View.SetBackgroundColour(wx.Colour(152, 155, 175))
fgSizer2 = wx.FlexGridSizer(2, 1, 0, 0)
fgSizer2.SetFlexibleDirection(wx.BOTH)
fgSizer2.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizer3 = wx.FlexGridSizer(3, 1, 0, 0)
fgSizer3.SetFlexibleDirection(wx.BOTH)
fgSizer3.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizer6 = wx.FlexGridSizer(0, 3, 0, 0)
fgSizer6.SetFlexibleDirection(wx.BOTH)
fgSizer6.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Lbl_Up_ProcessName = wx.StaticText(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Process Name", wx.DefaultPosition,
wx.DefaultSize, 0|wx.TRANSPARENT_WINDOW )
self.Lbl_Up_ProcessName.Wrap(-1)
fgSizer6.Add(self.Lbl_Up_ProcessName, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
Cmb_Up_ProcessNameChoices = []
self.Cmb_Up_ProcessName = wx.ComboBox(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"From A To B", wx.DefaultPosition,
wx.Size(200, -1), Cmb_Up_ProcessNameChoices, 0)
fgSizer6.Add(self.Cmb_Up_ProcessName, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
self.Cmd_Up_Refresh = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Refresh Data", wx.DefaultPosition,
wx.DefaultSize, 0)
fgSizer6.Add(self.Cmd_Up_Refresh, 0, wx.ALL, 5)
fgSizer3.Add(fgSizer6, 1, wx.EXPAND, 5)
fgSizer7 = wx.FlexGridSizer(1, 1, 0, 0)
fgSizer7.SetFlexibleDirection(wx.BOTH)
fgSizer7.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Dv_Up = wx.dataview.DataViewListCtrl(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, wx.DefaultPosition, wx.Size(400, 200), 0)
fgSizer7.Add(self.Dv_Up, 0, wx.ALL, 5)
self.Dv_Up.AppendTextColumn("ID")
self.Dv_Up.AppendTextColumn("ConfigName")
#self.Dv_Up.AppendTextColumn()
fgSizer3.Add(fgSizer7, 1, wx.EXPAND, 5)
fgSizer8 = wx.FlexGridSizer(1, 5, 0, 0)
fgSizer8.SetFlexibleDirection(wx.BOTH)
fgSizer8.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
#self.Cmd_Up_Home = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Home", wx.DefaultPosition, wx.DefaultSize, 0)
#fgSizer8.Add(self.Cmd_Up_Home, 0, wx.ALL, 5)
#self.Cmd_Up_Zero = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Zero", wx.DefaultPosition,
# wx.DefaultSize, 0)
#fgSizer8.Add(self.Cmd_Up_Zero, 0, wx.ALL, 5)
#ADD By Reza
self.Cmd_Up_NewProcess = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"New Process",
wx.DefaultPosition,
wx.DefaultSize, 0)
fgSizer8.Add(self.Cmd_Up_NewProcess, 0, wx.ALL, 5)
self.Cmd_Up_EditProcess = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Edit Process",
wx.DefaultPosition,
wx.DefaultSize, 0)
fgSizer8.Add(self.Cmd_Up_EditProcess, 0, wx.ALL, 5)
self.Cmd_Up_DeleteProcess = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Delete Process",
wx.DefaultPosition,
wx.DefaultSize, 0)
fgSizer8.Add(self.Cmd_Up_DeleteProcess, 0, wx.ALL, 5)
self.Cmd_Up_CancelNew = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Cancel",
wx.DefaultPosition,
wx.DefaultSize, 0)
fgSizer8.Add(self.Cmd_Up_CancelNew, 0, wx.ALL, 5)
#==================
fgSizer3.Add(fgSizer8, 1, wx.EXPAND, 5)
fgSizer2.Add(fgSizer3, 1, wx.EXPAND, 5)
fgSizer5 = wx.FlexGridSizer(3, 1, 0, 0)
fgSizer5.SetFlexibleDirection(wx.BOTH)
fgSizer5.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizer9 = wx.FlexGridSizer(1, 3, 0, 0)
fgSizer9.SetFlexibleDirection(wx.BOTH)
fgSizer9.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Lbl_Down_ProcessName = wx.StaticText(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Process Name", wx.DefaultPosition,
wx.DefaultSize, 0|wx.TRANSPARENT_WINDOW )
self.Lbl_Down_ProcessName.Wrap(-1)
fgSizer9.Add(self.Lbl_Down_ProcessName, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
self.Txt_Down_ProcessName = wx.TextCtrl(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,
wx.Size(200, -1), 0)
fgSizer9.Add(self.Txt_Down_ProcessName, 0, wx.ALL, 5)
self.Cmd_Down_SaveConfig = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Save Config", wx.DefaultPosition,
wx.DefaultSize, 0)
fgSizer9.Add(self.Cmd_Down_SaveConfig, 0, wx.ALL, 5)
fgSizer5.Add(fgSizer9, 1, wx.EXPAND, 5)
fgSizer10 = wx.FlexGridSizer(1, 1, 0, 0)
fgSizer10.SetFlexibleDirection(wx.BOTH)
fgSizer10.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Dv_Down = wx.dataview.DataViewListCtrl(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, wx.DefaultPosition, wx.Size(400, 200),
0)
self.Dv_Down.AppendTextColumn("HeaderID")
self.Dv_Down.AppendTextColumn("List")
self.Dv_Down.AppendTextColumn("SudutID")
self.Dv_Down.AppendTextColumn("Taggal Pembuatan")
fgSizer10.Add(self.Dv_Down, 0, wx.ALL, 5)
fgSizer5.Add(fgSizer10, 1, wx.EXPAND, 5)
fgSizer11 = wx.FlexGridSizer(1, 4, 0, 0)
fgSizer11.SetFlexibleDirection(wx.BOTH)
fgSizer11.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
self.Cmd_Down_Save = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Save To Table", wx.DefaultPosition, wx.DefaultSize, 0)
fgSizer11.Add(self.Cmd_Down_Save, 0, wx.ALL, 5)
self.Cmd_Down_Delete = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Delete From Table", wx.DefaultPosition, wx.DefaultSize, 0)
fgSizer11.Add(self.Cmd_Down_Delete, 0, wx.ALL, 5)
self.Cmd_Down_DeleteAll = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Clear Table", wx.DefaultPosition,
wx.DefaultSize, 0)
fgSizer11.Add(self.Cmd_Down_DeleteAll, 0, wx.ALL, 5)
self.Cmd_Down_CheckDetail = wx.Button(self.Bit_StPrc_Background_Setup2, wx.ID_ANY, u"Check Position",
wx.DefaultPosition,
wx.DefaultSize, 0)
fgSizer11.Add(self.Cmd_Down_CheckDetail, 0, wx.ALL, 5)
fgSizer5.Add(fgSizer11, 1, wx.EXPAND, 5)
fgSizer2.Add(fgSizer5, 1, wx.EXPAND, 5)
self.Bit_StPrc_Background_Setup2.SetSizer(fgSizer2)
self.Bit_StPrc_Background_Setup2.Layout()
fgSizer2.Fit(self.Bit_StPrc_Background_Setup2)
self.Cmd_Up_CancelNew.Hide()
#USING CONTROLLER
def StPrcUseController(self):
self.Cmd_StPrc_WidgetUseMouse.Enable()
self.Cmd_StPrc_WidgetUseController.Disable()
# PANEL CHANGES
self.Lbl_StPrc_WidgetUsedModeView.SetLabel("BY CONTROLLER")
# Reset Focus and Position Now
self.StPrcResetScroll()
# START WITH CONTROLLER
self.StPrcController_Mode = True
#USING MOUSE
def StPrcUseMouse(self):
# END CONTROLLER MODE
self.StPrcController_Mode = False
# EXECUTE COMMAND
commandlists = []
feedbacklists = []
# GET THE DOL COMMAND
deleting = {}
datacommand = self.MGETManualCommand(1, 8, group='MANUAL', type='RESET')
command = datacommand[0]
marker = datacommand[1]
deleting = {1: str(command)}
deletingfeedback = str('done')
commandlists.append(copy.deepcopy(deleting))
feedbacklists.append(copy.deepcopy(deletingfeedback))
print commandlists
print feedbacklists
# DOL Command
# self.CExecutingCommand(commandlists, feedbacklists, save=True)
self.Cmd_StPrc_WidgetUseMouse.Disable()
self.Cmd_StPrc_WidgetUseController.Enable()
# Realtime = False
# PANEL BUTTON
self.Lbl_StPrc_WidgetUsedModeView.SetLabel("BY MOUSE")
# START DETECTING POS
self.DetectingPos = True
#RESET SLIDER AND SPINER
def StPrcResetScroll(self):
self.StPrc_Sld_Move1.SetValue(0)
self.StPrc_Spn_Value1.SetValue(0)
self.StPrc_Sld_Move2.SetValue(0)
self.StPrc_Spn_Value2.SetValue(0)
self.StPrc_Sld_Move3.SetValue(0)
self.StPrc_Spn_Value3.SetValue(0)
self.StPrc_Sld_Move4.SetValue(0)
self.StPrc_Spn_Value4.SetValue(0)
self.StPrc_Sld_Move5.SetValue(0)
self.StPrc_Spn_Value5.SetValue(0)
self.StPrc_Sld_Move6.SetValue(0)
self.StPrc_Spn_Value6.SetValue(0)
self.PositionNow = ''
self.CurrentFocus = ''
#DATA Configurasi H From DBase
def StPrcViewConfigH(self, mode):
if mode == 1:
self.Dv_Up.DeleteAllItems()
#ToDo = Query Select / FuncSelect
data = self.MGETConfig('HEADER', 4, None)
for items in data:
self.Dv_Up.AppendItem(items)
#DATA Configurasi D FROM DataForm(Slider/etc)
def StPrcViewConfigD(self, mode):
if mode == 1:
self.Dv_Down.DeleteAllItems()
#ToDo = Get Data Form
data = self.MGETConfig('DETAIL', 4, None)
for items in data:
self.Dv_Down.AppendItem(items)
#SAVE TO DETAIL
def StPrcSaveToDv(self, mode):
#DETAIL
if mode == 1:
#ToDo Get Data
data = kwargss_data
#APPEND TO Dv
maxitem = int(self.Dv_Down.GetItemCount())
#ToDo Menage Data Format
#ToDo GetData From Sld and Spin
#SUDUT NOW
listing = maxitem + 1
sudutdata = self.StPrcGetSudut()
for items in sudutdata:
self.Dv_Down.AppendItem(items)
listing += 1
#HEADER
elif mode == 2:
pass
#data = [name]
#Save TO Header
self.MSaveConfigHeader()
def StPrcGetSudutData(self, mode):
if mode == 1:
lists = 0
data1 = []
val1 = self.StPrc_Spn_Value1.GetValue()
#ToDo = Make StPrc_vLastPos[1]
if val1 != '' and val1 != self.StPrc_vLastPos[1]:
lists += 10
data1.append(int(lists))
data1.append(int(1))
data1.append(float(val1))
data1.append(float(self.Speed[1]))
data1.append(str(self.StPrcGetDir(val1)))
data1 = self.SsvDataInputFiltering(data1)
data2 = []
val2 = self.StPrc_Spn_Value2.GetValue()
if val2 != '' and val2 != self.StPrc_vLastPos[2]:
lists += 10
data2.append(int(lists))
data2.append(int(2))
data2.append(float(val2))
data2.append(float(self.Speed[2]))
data2.append(str(self.StPrcGetDir(val2)))
data2 = self.SsvDataInputFiltering(data2)
data3 = []
val3 = self.StPrc_Spn_Value3.GetValue()
if val3 != '' and val3 != self.StPrc_vLastPos[3]:
lists += 10
data3.append(int(lists))
data3.append(int(3))
data3.append(float(val3))
data3.append(float(self.Speed[3]))
data3.append(str(self.StPrcGetDir(val3)))
data3 = self.SsvDataInputFiltering(data3)
data4 = []
val4 = self.StPrc_Spn_Value4.GetValue()
if val4 != '' and val4 != self.StPrc_vLasPos[4]:
lists += 10
data4.append(int(lists))
data4.append(int(4))
data4.append(float(val4))
data4.append(float(self.Speed[4]))
data4.append(str(self.StPrcGetDir(val4)))
data4 = self.SsvDataInputFiltering(data4)
data5 = []
val5 = self.StPrc_Spn_Value5.GetValue()
if val5 != '' and val5 != self.StPrc_vLastPos[5]:
lists += 10
data5.append(int(lists))
data5.append(int(5))
data5.append(int(val5))
data5.append(int(self.Speed[5]))
data5 = self.SsvDataInputFiltering(data5)
data6 = []
val6 = self.StPrc_Spn_Value6.GetValue()
if val6 != '' and val6 != '' and val6 != '-' and val6 != self.StPrc_vLastPos[6]:
lists += 10
data6.append(int(lists))
data6.append(int(6))
data6.append(str(val6))
data6 = self.SsvDataInputFiltering(data6)
data7 = []
if self.Ssv_Cmb_MagnetStat.GetValue() != '' and self.Ssv_Cmb_MagnetStat.GetValue() != '-':
lists += 10
data7.append(int(lists))
data7.append(int(12))
data7.append(str(self.Ssv_Cmb_MagnetStat.GetValue()))
data7 = self.SsvDataInputFiltering(data7)
hasil = [data1, data2, data3, data4, data5, data6, data7]
return hasil
def StPrcAppendDetail(self, mode, **kwargs):
#Append For New
if mode == 1:
try:
data = kwargs['data']
except Exception as e:
print (e)
return
else:
if len(data) == 0:
print ('[SetupProcess]-NoData')
return
else:
#ToDo : Data Filtering For input detail
#Validate Data Sudut
data = self.StPrcValuesValidator(2)
if data == None:
return
else:
for items in data:
pass
def StPrcSaveSudut(self, mode, **kwargs):
#Save Header
if mode == 1:
#Check Parameters
try:
name = kwargs['name']
except Exception as e:
print (e)
else:
self.MRecordSudut('HEADER', 1, name=name)
#Save Detail
elif mode == 2:
#Check Parameters
try:
headid = kwargs['headerid']
arraydata = kwargs['data']
except Exception as e:
print (e)
else:
if len(arraydata) == 0:
print ('No Data')
return
for item in arraydata:
self.MRecordSudut('DETAIL', 1, headerid=headid, list=arraydata[0],
motorid=arraydata[1], val=valuos, speed=speedos,
dirc=directos)
pass
| UTF-8 | Python | false | false | 77,103 | py | 22 | SetupProcess_Page.py | 19 | 0.57667 | 0.544635 | 0 | 1,637 | 45.078192 | 146 |
huangleiCCIE/Pythoncentos | 15,968,688,450,393 | a05f018cbeee752caa4949889c1ca5baa67de9b3 | 01e3274c6f5af89fb9b6d935079990445db725ed | /Python_Practice/basic knowledge.py | 538939cbec1cfe38b1fcad2f1fb12a8eb4ced58b | []
| no_license | https://github.com/huangleiCCIE/Pythoncentos | 9955ed1e87ed60f5f6c0fc301a30efb337a3f3cc | 8ec5403ad3c791b97bfc18c90a4fd0ed9635c8b2 | refs/heads/master | 2020-09-27T21:28:02.161222 | 2019-12-09T08:44:46 | 2019-12-09T08:44:46 | 211,068,532 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # name='huang lei'
# print(name.title()) #title()只是将首字母大写
# name='Huang Lei'
# print(name.upper()) #upper()将字符串所有字符大写
# print(name.lower()) #lower()将字符出所有字符小写
# first_name='huang'
# last_name='lovelace'
# full_name=first_name+' '+last_name
# message='Hello,'+full_name.title()
# print(message)
# print('\thuang \n\t lei \n\tis \n\ta \n\tstudent') #/n换行 /t制表符
# favorite_language='python '
# print(favorite_language.rstrip()) #临时消除字符串中右面的空白,再次打印时空白依然存在
# clean=favorite_language.rstrip() #将消除空白的字符串重新赋值在打印
# print=(clean) # strip消除两边空格,lstrip消除字符串左边的空格,rstrip消除字符串右边的空格
# age = 23
# message = 'happy ' + str(age) + 'rd Birthday!' #字符串与数字连用时,需将数字转换为字符串
# print(message) | UTF-8 | Python | false | false | 954 | py | 55 | basic knowledge.py | 55 | 0.666197 | 0.66338 | 0 | 24 | 28.625 | 85 |
LegeSto/Practice | 2,181,843,391,065 | bd6e34b1243c65259161f853f5649d5e168d2cdc | 80579a1511d3e9fd2eec0e5cc9d868449a0a712f | /this.py | 3aca2013c9e0a77f4fcb4990f8442baf066ca14d | []
| no_license | https://github.com/LegeSto/Practice | cd9a54c89448dcd60585c816578bc7f69c19b414 | 010c7b97ff7620c93733bd838f1209d18788c1ae | refs/heads/master | 2020-08-02T13:12:17.202662 | 2019-09-27T16:59:33 | 2019-09-27T16:59:33 | 211,364,154 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #first
import cv2
import numpy as np
def get_thresh(image):
hls = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)
cv2.imshow("help1", img)
cv2.waitKey(0)
(h1, l1, s1) = (0, 163, 0)
(h2, l2, s2) = (255, 255, 255)
h_min = np.array((h1, l1, s1), np.uint8)
h_max = np.array((h2, l2, s2), np.uint8)
return cv2.inRange(hls, h_min, h_max)
def transform_thresh(thresh):
res = cv2.bitwise_and(img, img, mask = thresh)
cv2.imshow("help2", thresh)
cv2.waitKey(0)
cv2.imshow("help3", res)
cv2.waitKey(0)
shape = (img.shape[0], img.shape[1], 3)
black = np.zeros(shape, np.uint8)
black1 = cv2.rectangle(black, (0, 250), (800, 667), (255, 255, 255), -1)
gray = cv2.cvtColor(black, cv2.COLOR_BGR2GRAY)
ret, b_mask = cv2.threshold(gray, 127, 255, 0)
fin = cv2.bitwise_and(res, res, mask = b_mask)
cv2.imshow("res.jpg", fin)
low_threshold = 50
high_threshold = 150
edges = cv2.Canny(fin, low_threshold, high_threshold)
return cv2.GaussianBlur(edges, (3, 3), 0)
def get_final_image(edges, image):
line_image = np.copy(image) * 0
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 15, np.array([]), 50, 5)
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(line_image, (x1, y1), (x2, y2), (0, 255, 0), 4)
lines_edges = cv2.addWeighted(img, 0.8, line_image, 1, 0)
cv2.imshow('result', lines_edges)
cv2.imwrite('img_out.jpg', lines_edges)
cv2.waitKey(0)
img = cv2.imread("1.jpg")
print(img.shape)
thresh = get_thresh(img)
edges = transform_thresh(thresh)
get_final_image(edges, img)
cv2.destroyAllWindows()
print("Complete")
#second
import cv2
import numpy as np
import matplotlib
from matplotlib.pyplot import imshow
from matplotlib import pyplot as plt
import os
def get_thresh(image):
hls = cv2.cvtColor(image, cv2.COLOR_BGR2HLS)
(h1, l1, s1) = (0, 163, 0)
(h2, l2, s2) = (255, 255, 255)
h_min = np.array((h1, l1, s1), np.uint8)
h_max = np.array((h2, l2, s2), np.uint8)
return cv2.inRange(hls, h_min, h_max)
def transform_thresh(thresh):
res = cv2.bitwise_and(img, img, mask = thresh)
black = np.zeros((img.shape[0], img.shape[1], 3), np.uint8)
black1 = cv2.rectangle(black, (430, 500), (1024, 739), (255, 255, 255), -1)
gray = cv2.cvtColor(black, cv2.COLOR_BGR2GRAY)
ret, b_mask = cv2.threshold(gray, 127, 255, 0)
fin = cv2.bitwise_and(res, res, mask = b_mask)
edges = cv2.Canny(fin, 50, 150)
return cv2.GaussianBlur(edges, (3, 3), 0)
def get_final_video(edges, image):
line_image = np.copy(image) * 0
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 15, np.array([]), 50, 5)
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(line_image, (x1, y1), (x2, y2), (0, 255, 0), 4)
lines_edges = cv2.addWeighted(img, 0.8, line_image, 1, 0)
cv2.imshow('result', lines_edges)
videoWriter.write(lines_edges)
return cv2.waitKey(1) == ord('q')
videoPath = os.getcwd() + '/video.mp4'
videoCapture = cv2.VideoCapture(videoPath)
fps = videoCapture.get(cv2.CAP_PROP_FPS)
size = (int(videoCapture.get(3)),
int(videoCapture.get(4)))
videoWriter = cv2.VideoWriter('new_video_out.avi',
cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, size)
while True:
is_true, img = videoCapture.read()
if is_true:
thresh = get_thresh(img)
edges = transform_thresh(thresh)
if get_final_video(edges, img):
break
else:
exit("OK")
videoCapture.release()
VideoWriter.release()
cv2.destroyAllWindows()
print("OK") | UTF-8 | Python | false | false | 3,753 | py | 1 | this.py | 1 | 0.593125 | 0.523848 | 0 | 120 | 29.291667 | 84 |
7ws/django-emailer | 12,309,376,300,649 | f2b673ea4353bf18200146a4f593d3051b78a10c | 68ab4d4f210d5e24875178948c495bf1e1a16f20 | /emailer/tests.py | 5d90e5803836bcf4150e027cb65442f14af1b5d6 | [
"MIT"
]
| permissive | https://github.com/7ws/django-emailer | 755f1124c03f3554b2659042966a897dc33aa101 | babf900f618a04fecbcb8caa5cadc638a1339178 | refs/heads/master | 2020-05-18T03:39:55.100218 | 2014-09-24T21:47:17 | 2014-09-24T21:47:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.core import mail
from django.core.exceptions import ValidationError
from django.test import TestCase
from emailer.models import ConnectionProfile, EmailTemplate
class EmailTransportTestCase(TestCase):
fixtures = ['email_templates']
def test_connection(self):
# wrong everything
conn = ConnectionProfile(
host='such.an.unknown.n0n3Xizt3ht-server.com',
port=587, use_tls=False,
username='foobar', password='123')
self.assertRaises(ValidationError, lambda: conn.clean())
# valid server, bad credentials
conn.__dict__.update(host='smtp.gmail.com', use_tls=True)
self.assertRaises(ValidationError, lambda: conn.clean())
# TODO: test a valid connection with a dummy server
def test_email_send(self):
to = 'user@server.com'
# render and send the email from a template
email = EmailTemplate.get('TEST_EMAIL').render(
to=to, context={'sender': 'Foo', 'destiny': 'Bar'})
email.send()
self.assertEqual(len(mail.outbox), 1)
sent_email = mail.outbox[0]
# make sure we're using the right connection
connection_profile = ConnectionProfile.objects.all()[0]
for field in ('host', 'port', 'use_tls', 'username', 'password',):
self.assertEqual(
getattr(connection_profile, field),
getattr(sent_email.connection, field))
# test email content
self.assertEqual(set(sent_email.to), set([to]))
self.assertIn('Bar', sent_email.subject)
self.assertIn('Foo', sent_email.body)
| UTF-8 | Python | false | false | 1,636 | py | 7 | tests.py | 4 | 0.634474 | 0.627139 | 0 | 46 | 34.565217 | 74 |
darioAnongba/TCP-Labs | 10,024,453,707,128 | d292dbeb547158262da5038bf80cbdf29c4a254c | 8ef916380e97076c07720058c524260ca3af23ae | /Lab3_226371_229049/Part6_226371_229049 | d8e7977fa4b0832d94619fc5b866d52722db0013 | []
| no_license | https://github.com/darioAnongba/TCP-Labs | ead86c50f0d0da75feb15610bffedb5fbfa52f32 | 88e9d067dabbce79964f00703832ed26bf88255c | refs/heads/master | 2021-01-12T10:05:35.245801 | 2016-12-13T12:52:59 | 2016-12-13T12:52:59 | 76,358,427 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
import re
import math
import socket
import ssl
import sys
HOST_PORT = ('localhost', 5003)
CERT = '229049_cert.pem'
KEY = '229049_key.pem'
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.load_cert_chain(CERT, keyfile=KEY)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = context.wrap_socket(server)
server.bind(HOST_PORT)
server.listen(1)
while True:
sock, _ = server.accept()
cmd = sock.read(11).decode()
if cmd != 'CMD_short:0':
sock.close()
continue
n = 20
for i in range(n):
ans = 'This is PMU data {}'.format(i).encode()
sock.sendall(ans)
sock.close()
server.close()
| UTF-8 | Python | false | false | 686 | 15 | Part6_226371_229049 | 13 | 0.651603 | 0.61516 | 0 | 38 | 17.052632 | 58 |
|
microsoft/ContextualSP | 9,251,359,590,914 | 69838dcc85a9408281d34ef795ed85b0e8f281d0 | 5f1881006aaf4f3c2515f375ad29c15fd6612de2 | /poset_decoding/traversal_path_prediction/MatchZoo-py/tests/data_pack/test_datapack.py | 123445cee0efd76a53db1ec19968d8980bcdf8b2 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
]
| permissive | https://github.com/microsoft/ContextualSP | 4edb598d40f683f9a1143b92a9d24e1066d51ec4 | 4198ebce942f4afe7ddca6a96ab6f4464ade4518 | refs/heads/master | 2023-08-02T22:08:40.503853 | 2023-07-14T07:22:50 | 2023-07-14T07:22:50 | 255,534,819 | 332 | 70 | MIT | false | 2023-07-25T19:23:48 | 2020-04-14T07:01:54 | 2023-07-24T09:57:19 | 2023-07-25T19:23:47 | 74,442 | 316 | 60 | 15 | Python | false | false | import shutil
import pandas as pd
import pytest
from matchzoo import DataPack, load_data_pack
@pytest.fixture
def data_pack():
relation = [['qid0', 'did0', 1], ['qid1', 'did1', 0]]
left = [['qid0', [1, 2]], ['qid1', [2, 3]]]
right = [['did0', [2, 3, 4]], ['did1', [3, 4, 5]]]
relation = pd.DataFrame(relation, columns=['id_left', 'id_right', 'label'])
left = pd.DataFrame(left, columns=['id_left', 'text_left'])
left.set_index('id_left', inplace=True)
right = pd.DataFrame(right, columns=['id_right', 'text_right'])
right.set_index('id_right', inplace=True)
return DataPack(relation=relation,
left=left,
right=right)
def test_length(data_pack):
num_examples = 2
assert len(data_pack) == num_examples
def test_getter(data_pack):
assert data_pack.relation.iloc[0].values.tolist() == ['qid0', 'did0', 1]
assert data_pack.relation.iloc[1].values.tolist() == ['qid1', 'did1', 0]
assert data_pack.left.loc['qid0', 'text_left'] == [1, 2]
assert data_pack.right.loc['did1', 'text_right'] == [3, 4, 5]
def test_save_load(data_pack):
dirpath = '.tmpdir'
data_pack.save(dirpath)
dp = load_data_pack(dirpath)
assert len(data_pack) == 2
assert len(dp) == 2
shutil.rmtree(dirpath)
| UTF-8 | Python | false | false | 1,301 | py | 680 | test_datapack.py | 474 | 0.601845 | 0.572636 | 0 | 42 | 29.97619 | 79 |
DanilZittser/cv2_shape_predictor | 17,746,804,873,088 | 31289083bb54750b54f92db7c2c22ef1bc853568 | 21ca8e93ccd947356670a6bcaf27a3afe7a3271a | /src/tests.py | 53d2f43c21448334a7cf7e5566f18c8f09cf70cc | []
| no_license | https://github.com/DanilZittser/cv2_shape_predictor | b9abe86678af46944d5e224a022bb2618a87bf73 | 8cf728d353eece43588b5d357575dee43287092b | refs/heads/main | 2023-05-04T11:48:10.111228 | 2021-05-26T10:37:50 | 2021-05-26T10:37:50 | 370,994,330 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import cv2
import numpy as np
import pytest
from fastapi.testclient import TestClient
from nptyping import NDArray
from main import app
from models import NPIMAGE_ERRORS
from predictor import shape_predictor
IMAGE_H = 500
IMAGE_W = 500
client = TestClient(app)
@pytest.fixture(scope='function')
def rectangle() -> NDArray[(IMAGE_H, IMAGE_W, 3), np.uint8]:
image = np.zeros(shape=[IMAGE_H, IMAGE_W, 3], dtype=np.uint8)
image = cv2.rectangle(image, (100, 100), (400, 400), (255, 255, 255), -1)
return image
@pytest.fixture(scope='function')
def circle() -> NDArray[(IMAGE_H, IMAGE_W, 3), np.uint8]:
image = np.zeros(shape=[IMAGE_H, IMAGE_W, 3], dtype=np.uint8)
image = cv2.circle(image, (250, 250), (200, 200), (255, 255, 255), -1)
return image
@pytest.fixture(scope='function')
def empty() -> NDArray[(IMAGE_H, IMAGE_W, 3), np.uint8]:
return np.zeros(shape=[IMAGE_H, IMAGE_W, 3], dtype=np.uint8)
def test_shape_predictor(rectangle, circle, empty):
assert shape_predictor(rectangle) == 'rectangle'
assert shape_predictor(circle) == 'circle'
assert shape_predictor(empty) == 'shape not found'
def test_shape_predictor_api_invalid_type():
response = client.post(
'/predictor/',
json={'image': '[0, 1, 2, 3]'},
)
assert response.status_code == 422
assert response.json()['detail'][0]['msg'] == NPIMAGE_ERRORS['INVALID_TYPE_ON_JSON_PARSE']
def test_shape_predictor_api_invalid_ndims():
response = client.post(
'/predictor/',
json={'image': [0, 1, 2, 3]},
)
assert response.status_code == 422
assert response.json()['detail'][0]['msg'] == NPIMAGE_ERRORS['INVALID_NDIMS']
def test_shape_predictor_api_invalid_nchannels():
response = client.post(
'/predictor/',
json={'image': [[[0, 1, 2, 3]]]},
)
assert response.status_code == 422
assert response.json()['detail'][0]['msg'] == NPIMAGE_ERRORS['INVALID_NCHANNELS']
def test_shape_predictor_api(circle):
response = client.post(
'/predictor/',
json={'image': circle.tolist()},
)
assert response.status_code == 200
assert response.json() == {'shape': 'circle'}
| UTF-8 | Python | false | false | 2,187 | py | 11 | tests.py | 5 | 0.641975 | 0.599909 | 0 | 76 | 27.776316 | 94 |
bonheurgirl/python.code | 15,728,170,268,570 | 5a7cc3a47111ed50675b9bd128f7fb2a7d0becdd | e1764d4dab4b6f2b79d7dbe22936a74ce85c4da5 | /Chapter9_Dictionaries.py | 5230f06b6638064b5d1f692288c461fe19425590 | []
| no_license | https://github.com/bonheurgirl/python.code | a3a74c891ae4042e0cfe301870767fcd2c828473 | 434b79a0a588d60c88f2d616829d3e9a4153aba8 | refs/heads/master | 2022-06-21T14:46:09.815884 | 2022-05-21T09:33:37 | 2022-05-21T09:33:37 | 51,653,260 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #Chapter 9 Dictionaries
"""
A collection is nice because we can put more than one value in them and
carry them all around in 1 convenient package.
We have a bunch of values in a single 'variable'
We do this by having more than one place 'in' the variable.
We have ways of finding the different places in the variable.
What is not a 'Collection'?
Most of our variables have one value in them--when we put a new
value in the variable--the old value is over written.
"""
x=2
x=4
print x
"""A story of 2 Collections...
List: A linear collection of values that stay in order. think pringles.
Dictionary: A 'bag' of values, each with its own label. think a purse.
Key value
key is the label.
The value is the thing.
Dictionaries:
-dictionaries are python's most powerful data collection
-dictionaries allow us to do fast database-like operations in python
-dictionaries have different names in different languages
Associative Arrays: Perl/Php
Properties or Map or HashMap: Java
Property Bag: C#/.Net (C sharp)
-Lists index their entries based on the position in the list.
-Dictionaries are like bags-no order.
-So we index the things we put in the dictionary with a 'lookup tag'.
"""
purse = dict()
purse['money'] = 12
purse['candy'] = 3
purse['tissues'] = 75
print purse
#{'money': 12, 'tissues': 75, 'candy': 3}
print purse['candy']
#3
purse['candy'] = purse['candy'] + 2
print purse
#{'money': 12, 'tissues': 75, 'candy': 5}
"""
Comparing Lists & Dictionaries
-Dictionaries are like Lists except they use keys instead of numbers to look up values.
"""
lst = list()
lst.append(21)
lst.append(183)
print lst
#[21, 183]
lst[0] = 23
print lst
#[23, 183]
ddd = dict()
ddd['age'] = 21
ddd['course'] = 182
print ddd
#{'course': 182, 'age': 21}
ddd['age'] = 23
print ddd
#{'course': 182, 'age': 23}
"""Many Counters with a Dictionary
-One common use of a dictionary counting how often we 'see' something.
"""
ccc = dict()
ccc['csev'] = 1
ccc['cwen'] = 1
print ccc
#{'csev': 1, 'cwen': 1}
ccc['cwen'] = ccc['cwen'] + 1
print ccc
#{'csev': 1, 'cwen': 2}
"""DICTIONARY TRACEBACKS
-It is an error to reference a key which is not in the dictionary.
-We can use the in operator to see if a keay is in the dictionary.
"""
"""
ccc = dict()
print ccc['csev']
#traceback
print 'csev' in ccc
#False
"""
"""WHEN WE SEE A NEW NAME
-when we encounter a new name, we need to add a new entry in the
dictionary and if this the second or later time we have seen
the name, we simply add one to the count in the dictionary under
that name
"""
counts = dict()
names = ['csev','cwen','csav','zqian','cwen']
for name in names:
if name not in counts:
counts[name] = 1
else:
counts[name] = counts[name] + 1
print counts
#{'csev': 1, 'zqian': 1, 'csav': 1, 'cwen': 2}
#19 min in
fh = open('babynames.txt','r')
baby = dict()
girls = ['hannah','michelle']
for line in fh:
girls = line.split()
for name in girls:
if name not in baby:
baby[name] = 1
else :
baby[name] = baby[name] + 1
print baby
for girls in baby:
print girls, baby
"""THE GET METHOD FOR DICTIONARY
This pattern of checking to see if a key is already in a
dictionary and assuming a default value if the key is not
there is so common, that there is a method called
get() that does this for us.
Default value if key does not exist(and no Traceback.)"""
if name in counts:
print counts[name]
else:
print 0
print counts.get(name,0)
"""SIMPLIFIED COUNTING WITH GET()
-We can use get() and provide a default value of zero when the key
is not yet in the dictionary-and then just add one-
"""
counts = dict()
names = ['csev','cwen','csav','zqian','cwen']
for name in names:
counts[name] = counts.get(name,0) + 1
print counts
"""COUNTING PATTERN
-THE GENERAL PATTERN TO COUNT THE WORDS IN A LINE OF TEXT
IS TO SPLIT THE LINE INTO WORDS, THEN LOOP THROUGH THE WORDS
AND USE A DICTIONARY TO TRACK THE COUNT OF EACH WORD
INDEPENDENTLY."""
counts = dict()
print 'Enter a line of text:'
line = raw_input(")
words = line.split()
print 'Words:',words
print 'Counting...'
for word in words:
counts[word] = counts.get(word,0) + 1
print 'Counts',counts
#25 min
"""DEFINITE LOOPS AND DICTIONARIES
-Even though dictionaries are not stored in order,
we can write a for loop that goes through all the entries
in a dictionary-actually it goes through all of the keys
in the dictionary and looks up the values.
"""
counts = {'chuck': 1, 'fred': 42, 'jan': 100}
for key in counts:
print key, counts[key]
#jan 100
#chuck 1
#fred 42
counts = {'chuck': 1, 'fred': 42, 'jan': 100}
for key in counts:
print key, counts[key]
print counts.values()
#[100, 1, 42]
"""RETRIEVING LISTS OF KEYS & VALUES
-You can get a list of keys, values
or items (both) from a dictionary.
"""
jjj = {'chuck': 1,'fred': 42,'jan':100}
print list(jjj)
#['jan', 'chuck', 'fred']
print jjj.keys()
#['jan', 'chuck', 'fred']
print jjj.values()
#[100, 1, 42]
print jjj.items()
#[('jan', 100), ('chuck', 1), ('fred', 42)]
#THIS IS A TUPLE
# A TUPLE IS A KEY,VALUE PAIR
#THIS WORKS BEAUTIFULLY ON A FOR LOOP
"""BONUS: 2 ITERATION VARIABLES!
-we loop through the key-value pairs in a
dictionary using 2 iteration variables.
-each iteration, the 1st variable is the key
and the 2nd variable is the corresponding
value for the key."""
jjj = {'chuck': 1,'fred': 42,'jan':100}
for aaa,bbb in jjj.items():
print aaa,bbb
#jan 100
#chuck 1
#fred 42
#this program counts the most common word in a file
name = raw_input('Enter file:')
handle = open(name,'r')
text = handle.read()
words = text.split()
counts = dict()
for word in words:
counts[word] = counts.get(word,0) + 1
bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print bigword,bigcount
#SUMMARY OF CHAPTER 9
"""
What is a collection?
Lists versus Dictionaries
Dictionary constants
The most common word
Using the get() method
HAshing, and lack of order
Writing dictionary loops
Sneak peek:tuples
Sorting dictionaries
An empty pair of curly braces {}
is an empty dictionary, just like
an empty pair of [] is an empty list.
The length len() of a dictionary
is the number of key-value pairs
it has. Each pair counts only once,
even if the value is a list. (That's
right: you can put lists inside
dictionaries!)
| UTF-8 | Python | false | false | 6,798 | py | 28 | Chapter9_Dictionaries.py | 23 | 0.64975 | 0.628714 | 0 | 286 | 21.748252 | 87 |
gaoyunqing/MetReg | 13,915,694,080,434 | 3973bfa78e911ed2ff1ba36565a727496dfd306d | 79ee4a702b541ad4238983d3311f6919f6067e93 | /tests/test_models_ml.py | 0d0e0e67996fd68b7e655be81732f9d0518a63da | [
"MIT"
]
| permissive | https://github.com/gaoyunqing/MetReg | edf428bdda1c1cc0666abec7f0fb39a2bb410995 | 5bcfd68e30477f36736e040e1cdcd26086d325c1 | refs/heads/master | 2023-03-11T18:14:08.615750 | 2021-02-26T06:22:31 | 2021-02-26T06:22:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import sys
sys.path.append('../')
import numpy as np
from MetReg.models.ml.elm import ExtremeLearningRegressor
from MetReg.models.ml.gp import GaussianProcessRegressor
from MetReg.models.ml.knn import KNNRegressor
from MetReg.models.ml.linear import (BaseLinearRegressor, ElasticRegressor,
ExpandLinearRegressor, LassoRegressor,
RidgeRegressor)
from MetReg.models.ml.mlp import MLPRegressor
from MetReg.models.ml.svr import LinearSVRegressor, SVRegressor
from MetReg.models.ml.tree import (AdaptiveBoostingRegressor,
BaseTreeRegressor, ExtraTreesRegressor,
ExtremeGradientBoostingRegressor,
GradientBoostingRegressor,
LightGradientBoostingRegressor,
RandomForestRegressor)
def test_linear_regressors():
X = np.random.random(size=(100, 3))
y = np.random.random(size=(100,))
BLR = BaseLinearRegressor()
BLR.fit(X, y)
BLR.predict(X)
RR = RidgeRegressor()
RR.fit(X, y)
RR.predict(X)
LR = LassoRegressor()
LR.fit(X, y)
LR.predict(X)
ER = ElasticRegressor()
ER.fit(X, y)
ER.predict(X)
def test_tree_regressors():
X = np.random.random(size=(100, 3))
y = np.random.random(size=(100,))
BTR = BaseTreeRegressor()
BTR.fit(X, y)
BTR.predict(X)
RFR = RandomForestRegressor()
RFR.fit(X, y)
RFR.predict(X)
ETR = ExtraTreesRegressor()
ETR.fit(X, y)
ETR.predict(X)
ABR = AdaptiveBoostingRegressor()
ABR.fit(X, y)
ABR.predict(X)
GBR = GradientBoostingRegressor()
GBR.fit(X, y)
GBR.predict(X)
EGBR = ExtremeGradientBoostingRegressor()
EGBR.fit(X, y)
EGBR.predict(X)
LGBR = LightGradientBoostingRegressor()
LGBR.fit(X, y)
LGBR.predict(X)
def test_svr_regressors():
X = np.random.random(size=(100, 3))
y = np.random.random(size=(100,))
LSVR = LinearSVRegressor()
LSVR.fit(X, y)
LSVR.predict(X)
SVR = SVRegressor()
SVR.fit(X, y)
SVR.predict(X)
def test_knn_regressor():
X = np.random.random(size=(100, 3))
y = np.random.random(size=(100,))
KR = KNNRegressor()
KR.fit(X, y)
KR.predict(X)
def test_mlp_regressor():
X = np.random.random(size=(100, 3))
y = np.random.random(size=(100,))
MR = MLPRegressor()
MR.fit(X, y)
MR.predict(X)
def test_gp_regressor():
X = np.random.random(size=(100, 3))
y = np.random.random(size=(100,))
GPR = GaussianProcessRegressor()
GPR.fit(X, y)
GPR.predict(X)
def test_elm_regressor():
X = np.random.random(size=(100, 3))
y = np.random.random(size=(100,))
GPR = ExtremeLearningRegressor()
GPR.fit(X, y)
GPR.predict(X)
if __name__ == '__main__':
#test_linear_regressors()
#test_tree_regressors()
test_svr_regressors()
test_knn_regressor()
test_mlp_regressor()
test_gp_regressor()
test_elm_regressor()
| UTF-8 | Python | false | false | 3,077 | py | 62 | test_models_ml.py | 55 | 0.605785 | 0.58986 | 0 | 131 | 22.480916 | 75 |
thebadaruddinshaikh/CodeChef | 16,166,256,927,016 | 5099ab52696a6938dd0e057f1a6cc50c4f1ead55 | 88139396afc49e7b187f6936e0a9818aeb2286e0 | /BEGNumberMirrior.py | 90e60094f9f7c121bffc6fb5ba49e121a2c2f33a | []
| no_license | https://github.com/thebadaruddinshaikh/CodeChef | b0289bcaea83a245a1a149f18b1faecfc6c41848 | 069db34e564d3ae208a9df5eed820202b10d27bd | refs/heads/master | 2020-04-12T22:20:26.764006 | 2019-07-07T11:04:01 | 2019-07-07T11:04:01 | 162,787,615 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | while True:
x = int(input())
print(x)
| UTF-8 | Python | false | false | 45 | py | 12 | BEGNumberMirrior.py | 12 | 0.533333 | 0.533333 | 0 | 3 | 12.333333 | 17 |
shafferpr/flask_practice | 14,671,608,283,623 | d888f333a666992bf464b122913ed19d23f17610 | 935bcab71ba763f438a33d803ab028263f3ffc35 | /bokehplot.py | 6b0567d9e9d5b35fb9ba171944131417389f5b0a | []
| no_license | https://github.com/shafferpr/flask_practice | 384a86b514e77469682157591fbc5695344e2f22 | 956f9fe37813949bd0ed86d43b68f9b3ff58d17f | refs/heads/master | 2021-01-20T15:26:27.709968 | 2017-05-09T16:30:19 | 2017-05-09T16:30:19 | 90,767,860 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from flask import Flask,render_template,request,redirect
import requests
from bokeh.plotting import figure
from bokeh.embed import components
stock = 'aapl'
api_url = 'https://www.quandl.com/api/v1/datasets/WIKI/%s.json' % stock
session = requests.Session()
session.mount('http://', requests.adapters.HTTPAdapter(max_retries=3))
raw_data = session.get(api_url)
plot = figure(tools=TOOLS,
title='Data from Quandle WIKI set',
x_axis_label='date',
x_axis_type='datetime')
script, div = components(plot)
render_template('graph.html', script=script, div=div)
| UTF-8 | Python | false | false | 600 | py | 2 | bokehplot.py | 2 | 0.703333 | 0.7 | 0 | 19 | 30.578947 | 71 |
satnet-project/server | 8,469,675,536,112 | b2c247ab343232f0f095a3b4fbf5cfe3964d59fc | 400d234a475c7e6c61ef87b8cfda2c34cb363ae1 | /services/configuration/models/segments.py | 2badf48d231560d450c5799e7d44d2d9458cc6d6 | [
"Apache-2.0"
]
| permissive | https://github.com/satnet-project/server | 94a374f916b42a4dd57618eb092ee65c271777a8 | 3bb15f4d4dcd543d6f95d1fda2cb737de0bb9a9b | refs/heads/master | 2022-07-20T11:42:52.821489 | 2017-12-10T15:41:22 | 2017-12-10T15:41:22 | 13,973,082 | 4 | 2 | Apache-2.0 | false | 2022-07-06T19:51:26 | 2013-10-30T00:44:48 | 2017-12-12T11:41:54 | 2022-07-06T19:51:26 | 71,603 | 2 | 0 | 16 | Python | false | false |
from django.core import validators
from django.db import models
from django_countries import fields
import logging
from services.accounts import models as account_models
from services.common import gis
from services.configuration.models import tle as tle_models
"""
Copyright 2013, 2014 Ricardo Tubio-Pardavila
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
__author__ = 'rtubiopa@calpoly.edu'
logger = logging.getLogger('models.segments')
class SpacecraftManager(models.Manager):
"""
Manager that contains all the methods required for accessing to the
contents of the SpacecraftConfiguration database models.
"""
def create(self, tle_id, username=None, user=None, **kwargs):
"""
Overriden "create" that receives an identifier for a TLE, gets the
correspondent TLE object from within the CELESTRAK TLE database and
associates it with this new Spacecraft.
:param tle_id: Identifier of the TLE to be associated with this
spacecraft
:param username: Name of the user this Spacecraft belongs to
:param user: The user object that this Spacecraft belongs to
:param kwargs: Arguments to be used for this spacecraft object
:return: Spacecraft object reference.
"""
if username is not None:
user = account_models.UserProfile.objects.get(username=username)
if user is None:
raise Exception('User <' + username + '> could not be found.')
tle = None
if tle_id:
tle = tle_models.TwoLineElement.objects.get(identifier=tle_id)
return super(SpacecraftManager, self).create(
tle=tle, user=user, **kwargs
)
class Spacecraft(models.Model):
"""
This class models the configuration required for managing any type of
spacecraft in terms of communications and pass simulations.
"""
class Meta:
app_label = 'configuration'
MAX_SC_ID_LEN = 30
MAX_CALLSIGN_LEN = 10
objects = SpacecraftManager()
user = models.ForeignKey(
account_models.UserProfile,
verbose_name='Owner of the Spacecraft'
)
identifier = models.CharField(
'Identifier',
max_length=MAX_SC_ID_LEN,
unique=True,
validators=[validators.RegexValidator(
regex='^[a-zA-Z0-9.\-_]*$',
message="Alphanumeric or '.-_' required",
code='invalid_spacecraft_identifier'
)]
)
callsign = models.CharField(
'Radio amateur callsign',
max_length=MAX_CALLSIGN_LEN,
validators=[validators.RegexValidator(
regex='^[a-zA-Z0-9.\-_]*$',
message="Alphanumeric or '.-_' required",
code='invalid_callsign'
)]
)
tle = models.ForeignKey(
tle_models.TwoLineElement,
verbose_name='TLE object for this Spacecraft'
)
is_cluster = models.BooleanField(
'Flag that indicates whether this object is a cluster or not',
default=False
)
is_ufo = models.BooleanField(
'Flag that defines whether this object is an UFO or not',
default=False
)
def update(self, callsign=None, tle_id=None):
"""
Updates the configuration for the given GroundStation object. It is not
necessary to provide all the parameters for this function, since only
those that are not null will be updated.
:param callsign: Spacecraft's callsign string
:param tle_id: Identifier of the TLE
"""
changes = False
if callsign and self.callsign != callsign:
self.callsign = callsign
changes = True
if tle_id and self.tle.identifier != tle_id:
self.tle = tle_models.TwoLineElement.objects.get(identifier=tle_id)
changes = True
if changes:
self.save()
def __unicode__(self):
"""
Prints in a unicode string the most remarkable data for this
spacecraft object.
"""
return ' >>> SC, id = ' + str(
self.identifier
)
class GroundStationsManager(models.Manager):
"""
Manager that contains all the methods required for accessing to the
contents of the GroundStationConfiguration database models.
"""
def create(
self, latitude, longitude, altitude=None, username=None, user=None,
**kwargs
):
"""
Method that creates a new GroundStation object using the given user as
the owner of this new segment.
:param latitude: Ground Station's latitude.
:param longitude: Ground Station's Longitude.
:param altitude: Ground Station's Altitude.
:param username: Username for the owner
:param user: User object for the owner
:param kwargs: Additional parameters.
:return: The just created GroundStation object.
"""
if username is not None:
user = account_models.UserProfile.objects.get(username=username)
if user is None:
raise Exception('User <' + username + '> could not be found.')
if altitude is None:
altitude = gis.get_altitude(latitude, longitude)[0]
results = gis.get_region(latitude, longitude)
iaru_region = 0
return super(GroundStationsManager, self).create(
latitude=latitude,
longitude=longitude,
altitude=altitude,
country=results[gis.COUNTRY_SHORT_NAME],
IARU_region=iaru_region,
user=user,
**kwargs
)
class GroundStation(models.Model):
"""
This class models the configuration required for managing a generic ground
station, in terms of communication channels and pass simulations.
"""
class Meta:
app_label = 'configuration'
objects = GroundStationsManager()
user = models.ForeignKey(
account_models.UserProfile,
verbose_name='User to which this GroundStation belongs to'
)
identifier = models.CharField(
'Unique alphanumeric identifier for this GroundStation',
max_length=30,
unique=True,
validators=[
validators.RegexValidator(
regex='^[a-zA-Z0-9.\-_]*$',
message="Alphanumeric or '.-_' required",
code='invalid_spacecraft_identifier'
)
]
)
callsign = models.CharField(
'Radio amateur callsign for this GroundStation',
max_length=10,
validators=[
validators.RegexValidator(
regex='^[a-zA-Z0-9.\-_]*$',
message="Alphanumeric or '.-_' required",
code='invalid_callsign'
)
]
)
contact_elevation = models.FloatField(
'Minimum elevation for contact(degrees)'
)
latitude = models.FloatField('Latitude of the Ground Station')
longitude = models.FloatField('Longitude of the Ground Station')
altitude = models.FloatField('Altitude of the Ground Station')
# Necessary for matching this information with the IARU database for band
# regulations.
country = fields.CountryField('Country where the GroundStation is located')
IARU_region = models.SmallIntegerField('IARU region identifier')
is_automatic = models.BooleanField(
'Flag that defines this GroundStation as a fully automated one,'
'so that it will automatically accept any operation request from a '
'remote Spacecraft operator',
default=False
)
def update(
self, callsign=None, contact_elevation=None,
latitude=None, longitude=None, is_automatic=None
):
"""
Updates the configuration for the given GroundStation object. It is not
necessary to provide all the parameters for this function, since only
those that are not null will be updated.
:param callsign: CALLSIGN for this GS
:param contact_elevation: Minimum contact elevation
:param latitude: GS's latitude
:param longitude: GS's longitude
:param is_automatic: Flag that defines whether the station is automatic
"""
changes = False
change_altitude = False
update_fields = []
if callsign and self.callsign != callsign:
self.callsign = callsign
update_fields.append('callsign')
changes = True
if contact_elevation is not None and\
self.contact_elevation != contact_elevation:
self.contact_elevation = contact_elevation
update_fields.append('contact_elevation')
changes = True
if is_automatic and self.is_automatic != is_automatic:
self.is_automatic = is_automatic
update_fields.append('is_automatic')
changes = True
if latitude and self.latitude != latitude:
self.latitude = latitude
update_fields.append('latitude')
changes = True
change_altitude = True
if longitude and self.longitude != longitude:
self.longitude = longitude
update_fields.append('longitude')
changes = True
change_altitude = True
if change_altitude:
self.altitude = gis.get_altitude(self.latitude, self.longitude)[0]
update_fields.append('altitude')
if changes:
self.save(update_fields=update_fields)
def __str__(self):
"""
Prints in a unicode string the most remarkable data for this
spacecraft object.
"""
return ' >>> GS, id = ' + str(
self.identifier
) + ', callsign = ' + str(
self.callsign
)
| UTF-8 | Python | false | false | 10,333 | py | 247 | segments.py | 189 | 0.621988 | 0.618988 | 0 | 312 | 32.115385 | 79 |
disssid/Python-Test | 17,875,653,907,729 | 33f1782d6affcc3821a643fcc917d683c8afdeb2 | 4bb6cd9413abbcf7a79e62ca000e1382a7ad1c16 | /ipc-test/src/process3.py | e69ef59aa2d38cb8ee9263fa64aa4145536d325a | []
| no_license | https://github.com/disssid/Python-Test | 99161b496a88a2a26fb01111b9cb8ec0969b43cf | 19eb5b211c589145cbc8eaa361408e57ecc587da | refs/heads/master | 2021-01-11T14:58:55.612653 | 2017-07-07T18:09:58 | 2017-07-07T18:09:58 | 80,270,229 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''
Created on Jan 27, 2017
@author: sid
'''
from time import sleep
class process2:
name =""
def __init__(self,name):
name = self.name
def process2(self,q):
for i in xrange(1,10):
q.put(i)
sleep(2) | UTF-8 | Python | false | false | 273 | py | 5 | process3.py | 4 | 0.483516 | 0.43956 | 0 | 17 | 15.117647 | 34 |
physicsistic/pythonbee | 8,375,186,252,465 | db6de927b08ef94346479d5128c4b069e2d5e1cd | 9d623cbed88230a110be05a15e1b6b054ab0440b | /testing/solutions/team30/6/code.py | 93e871d8658a2981770a896b5fed871966d37a17 | []
| no_license | https://github.com/physicsistic/pythonbee | 37c81523a6080a74d3ff72883b84afe492fea466 | fefd0f5b612762fb50c90b6c8ff82628c186a7b0 | refs/heads/master | 2021-01-18T04:26:18.833067 | 2013-02-05T05:54:53 | 2013-02-05T05:54:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def fun(l):
m=[]
for i in l:
m.prepend(i)
return m
| UTF-8 | Python | false | false | 56 | py | 161 | code.py | 146 | 0.553571 | 0.553571 | 0 | 5 | 10.2 | 14 |
jhb/noscenda.cachefix | 12,678,743,482,271 | 7d634413a1558301f6d81a7bbf696a723309c720 | 3a56ca64089ce32d76272c7c629b69e24a2788a1 | /noscenda/cachefix/browser.py | d06e682d3a9a7f2e58f4c5c6453f4d6e00a1fbd8 | []
| no_license | https://github.com/jhb/noscenda.cachefix | f7f4fe162b0edd746716cd2cd9739b4bfde5bafa | 25d84289bb9784209ddee9c3ee4852c3376b8ab2 | refs/heads/master | 2020-05-26T00:33:54.246250 | 2013-10-24T15:06:40 | 2013-10-24T15:06:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from zope.publisher.browser import BrowserView
from Products.CMFCore.utils import getToolByName
from zope.annotation.interfaces import IAnnotations
class CacheFix(BrowserView):
def publishTraverse(self,request,name):
#import ipdb; ipdb.set_trace()
if not hasattr(self,'subpath'):
self.subpath = []
self.subpath.append(name)
#print 'in publishTraverse in ATDownload'
return self
def at_download(self):
# print 'atdownload in browserview'
#import ipdb; ipdb.set_trace()
context = self.context
if self.subpath:
field = context.getWrappedField(self.subpath[0])
else:
field= context.getPrimaryField()
if not hasattr(field,'download'):
from zExceptions import NotFound
raise NotFound
return field.download(context)
| UTF-8 | Python | false | false | 906 | py | 4 | browser.py | 2 | 0.628035 | 0.626932 | 0 | 28 | 31.142857 | 60 |
Mohit977/Crime-Analysis | 2,637,109,925,204 | 50514d3f85a436b399de4eade12ee04375bbb30e | c453f85f63051c49659e55522679a5f35c4718d0 | /Abbi_Mohit_Capstone_Project.py | 7587ee4e63c8d5c5422c02e34ba46df4bc028b1b | []
| no_license | https://github.com/Mohit977/Crime-Analysis | dbb4dd4cac3d17dc9b274133e18e3b63fb15ace5 | e1e2c7b3197470ca28e15ed8a867362ed8291a87 | refs/heads/master | 2020-06-18T23:55:16.503882 | 2019-07-12T02:50:47 | 2019-07-12T02:50:47 | 196,497,366 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
# coding: utf-8
# In[1]:
def data_type(df):
sol1=df.dtypes
return sol1
def data_info_shape(df):
sol2=df.info()
sol3=df.shape
return sol2, sol3
def null_values(df):
null1 = df.isna().sum()
return null1
def data_desc(df):
sol3=df.describe(include='all')
return sol3
def data_rename(df):
sol4=df.rename(columns = {"COMPNOS" : "ReportNumber", "INCIDENT_TYPE_DESCRIPTION" : "IncidentClassification", "MAIN_CRIMECODE" : "CrimeCode", "REPORTINGAREA" : "AreaCode", "FROMDATE" : "Date", "DAY_WEEK" : "Day"}, inplace=True)
return sol4
def incidentclass_lowercase(df):
sol5=df["IncidentClassification"] = df.IncidentClassification.str.lower()
return sol5
| UTF-8 | Python | false | false | 736 | py | 2 | Abbi_Mohit_Capstone_Project.py | 1 | 0.657609 | 0.63587 | 0 | 35 | 19.885714 | 231 |
lidongze6/leetcode- | 12,773,232,786,235 | 8201c062f25a7d413695a43fe90339e0212fdf70 | 372185cd159c37d436a2f2518d47b641c5ea6fa4 | /35. 搜索插入位置.py | 54d67def2224188cadba65b1a8d7e1fd11dfa4f8 | []
| no_license | https://github.com/lidongze6/leetcode- | 12022d1a5ecdb669d57274f1db152882f3053839 | 6135067193dbafc89e46c8588702d367489733bf | refs/heads/master | 2021-07-16T09:07:14.256430 | 2021-04-09T11:54:52 | 2021-04-09T11:54:52 | 245,404,304 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def searchInsert(nums, target):
l, r = 0, len(nums)-1
while l + 1 < r:
mid = l + (r - l) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
r = mid
elif nums[mid] < target:
l = mid + 1
if nums[l] == target: return l
if nums[r] == target: return r
if nums[r] < target:
return r + 1
if nums[l] > target:
return l
if nums[l] < target < nums[r]:
return r
print(searchInsert([1,3,5,6],7))
| UTF-8 | Python | false | false | 523 | py | 546 | 35. 搜索插入位置.py | 545 | 0.470363 | 0.449331 | 0 | 20 | 24.95 | 34 |
imsrv01/programs | 3,487,513,467,712 | ac5282d86ca2c584c218fd78435462c132a96ce2 | 495553222d2f203b389a8ff4301a9cc95a43c209 | /yield_example.py | 269b118bdc97d5872b013121c50b1f63668b45a0 | []
| no_license | https://github.com/imsrv01/programs | 77be9e4e1be046105f4a6b4f177c436a1cb0ac32 | c9137c0bddd996d6ecaca538f4847aac1ecba14e | refs/heads/master | 2021-06-26T07:56:33.668190 | 2021-01-09T20:40:08 | 2021-01-09T20:40:08 | 191,448,069 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
def first_tennumbers():
i = 0
while i < 10:
i += 1
yield i # execution of the function is halted here, next run of the function, yield results will be remembered and used in calculation..
g = first_tennumbers() # returns a generator object
print(g)
print(next(g)) # first run of the function
print(next(g)) # second run of the function.
print(next(first_tennumbers())) # next should be called on same generator object, here it returns 1 instead of 3. Next is called on a new generator object..
for i in first_tennumbers():
print(i) | UTF-8 | Python | false | false | 562 | py | 50 | yield_example.py | 50 | 0.699288 | 0.688612 | 0 | 14 | 39.142857 | 156 |
languitar/mdls | 13,640,816,152,033 | e59858419952a5cbb55e03bbe481082faddbb755 | 95fd0832975ce3c66df28fc49c8f1c989ac10c41 | /src/mdls/server.py | a8e3accdb7e63bbcd8a9ba6fa3a45a7dab2a73c4 | []
| no_license | https://github.com/languitar/mdls | 0bb35edf9367f92b733ca3c2806e7f2668e8269c | ec0e9e3d326746707e8aae2846cf6777bbc8a4e6 | refs/heads/master | 2020-03-29T09:52:05.147996 | 2018-09-21T14:51:49 | 2018-09-21T14:51:49 | 149,777,706 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from pathlib import Path
from jsonrpc.dispatchers import MethodDispatcher
from jsonrpc.endpoint import Endpoint
from jsonrpc.streams import JsonRpcStreamReader, JsonRpcStreamWriter
from loggerbyclass import get_logger_by_class
from .completion import HeadingLinkProvider, FootnoteLinkProvider
from .workspace import Document, Workspace
class Mdls(MethodDispatcher):
def __init__(self, rx, tx):
self._logger = get_logger_by_class(self.__class__)
self._jsonrpc_stream_reader = JsonRpcStreamReader(rx)
self._jsonrpc_stream_writer = JsonRpcStreamWriter(tx)
self._endpoint = Endpoint(self, self._jsonrpc_stream_writer.write,
max_workers=64)
self._completion_providers = [
HeadingLinkProvider(),
FootnoteLinkProvider(),
]
self._client_capabilities = {}
self._workspace = None
self._shutdown = False
def start(self):
self._jsonrpc_stream_reader.listen(self._endpoint.consume)
def _capabilities(self):
return {
'completionProvider': {
'resolveProvider': False,
'triggerCharacters': [c
for p in self._completion_providers
for c in p.get_trigger_characters()],
}
}
def m_initialize(self,
processId=None,
rootUri=None,
rootPath=None,
initializationOptions=None,
capabilities=None,
workspaceFolders=None,
**kwargs):
self._logger.debug('Received initialization request')
if rootUri is None:
rootUri = Path(rootPath).as_uri() if rootPath is not None else ''
self._logger.debug('Using rootUri %s', rootUri)
self.workspace = Workspace(rootUri)
self._client_capabilities = capabilities
server_capabilities = self._capabilities()
self._logger.debug('Returning capabilities:\n%s', server_capabilities)
return {'capabilities': server_capabilities}
def m_initialized(self, **_kwargs):
pass
def m_shutdown(self, **_kwargs):
self._shutdown = True
return None
def m_exit(self, **_kwargs):
self._endpoint.shutdown()
self._jsonrpc_stream_reader.close()
self._jsonrpc_stream_writer.close()
def m_text_document__did_open(self, textDocument=None, **_kwargs):
self.workspace.put_document(
Document(textDocument['uri'],
textDocument['text'],
version=textDocument.get('version')))
def m_text_document__did_change(self, contentChanges=None,
textDocument=None, **_kwargs):
for change in contentChanges:
self._logger.debug('Applying change %s to document with URI %s',
change, textDocument['uri'])
document = self.workspace.get_document(textDocument['uri'])
self._logger.debug('Contents before change:\n%s', document.text)
document.update(change, version=textDocument.get('version'))
self._logger.debug('Contents after change:\n%s', document.text)
def m_text_document__did_close(self, textDocument=None, **_kwargs):
self.workspace.remove_document(textDocument['uri'])
def m_text_document__did_save(self, textDocument=None, **_kwargs):
pass
def m_text_document__completion(self, textDocument=None,
position=None, **_kwargs):
document = self.workspace.get_document(textDocument['uri'])
completions = []
for provider in self._completion_providers:
completions.extend(provider.provide(document, position))
self._logger.debug('Collected completions:\n%s', completions)
return {
'isIncomplete': False,
'items': completions,
}
| UTF-8 | Python | false | false | 4,047 | py | 7 | server.py | 5 | 0.591302 | 0.590808 | 0 | 111 | 35.459459 | 78 |
harshitag456/Web_DScrap | 11,536,282,172,211 | 06efce47898944735375dbdd3a0f9e780550f5a5 | 67490cade8dd05d72e36119defdf5ad09e6a56cb | /news.py | 951d9e9bcf8f6103e9bbc5add692f91ef9310649 | []
| no_license | https://github.com/harshitag456/Web_DScrap | 9983320dfcf84eac507798309c28461a67f31c14 | b5297379cfa89dc392b595a3d5432224c89974f8 | refs/heads/master | 2021-05-09T04:10:19.025774 | 2018-01-28T14:24:24 | 2018-01-28T14:24:24 | 119,265,032 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import urllib2
from bs4 import BeautifulSoup
print("Enter the date(DD/MM/YY) to view headlines:")
date = raw_input()
date = date.replace("/","");
url = 'http://www.rediff.com/issues/' + date + 'hl.html'
page = urllib2.urlopen(url);
html = BeautifulSoup(page,"lxml")
count=0
for i in html.find_all('div',attrs={'id':'hdtab1'}):
for j in i('a',attrs={'target':"_new"}):
if count==0:
count=count+1
continue
print(j.text)
print(j.next_sibling)
| UTF-8 | Python | false | false | 497 | py | 2 | news.py | 1 | 0.603622 | 0.589537 | 0 | 21 | 22.619048 | 56 |
Robotislove/Open-World-Semantic-Segmentation | 9,620,726,756,470 | 86245dc429ad592b36bdc6e614535c4b9887e402 | 16839d341a6a3b2caf8e6aaacfa1e1c0c439215f | /anomaly/create_dataset.py | 54b065578ab83f377f06e52cbaded42d53cbc6a5 | [
"MIT"
]
| permissive | https://github.com/Robotislove/Open-World-Semantic-Segmentation | 71460af369401791b7d4ed01689347ce47685810 | a95bac374e573055c23220e299789f34292988bc | refs/heads/main | 2023-07-03T02:14:40.569144 | 2021-08-09T15:48:53 | 2021-08-09T15:48:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import scipy
import scipy.io as sio
import scipy.misc
from scipy.misc import imread, imsave
import matplotlib
import matplotlib.pyplot as plt
import json
import os
import os.path
from tqdm import tqdm
import re
# Replace the colors with our colors
# This is only used for visualization purposes
#color_mat = sio.loadmat("data_ADE/color150.mat")
#StreetHazards colors
#colors = np.array([[ 0, 0, 0],# // unlabeled = 0,
# [ 70, 70, 70],# // building = 1,
# [190, 153, 153],# // fence = 2,
# [250, 170, 160],# // other = 3,
# [220, 20, 60],# // pedestrian = 4,
# [153, 153, 153],# // pole = 5,
# [157, 234, 50],# // road line = 6,
# [128, 64, 128],# // road = 7,
# [244, 35, 232],# // sidewalk = 8,
# [107, 142, 35],# // vegetation = 9,
# [ 0, 0, 142],# // car = 10,
# [102, 102, 156],# // wall = 11,
# [220, 220, 0],# // traffic sign = 12,
# [ 60, 250, 240],# // anomaly = 13,
#
# ])
#color_mat["colors"] = colors
#sio.savemat("data/color150.mat", color_mat)
#####
#create the train and val obgt
# def create_odgt(root_dir, file_dir, ann_dir, out_dir, anom_files=None):
# if anom_files is None:
# anom_files = []
# _files = []
#
# count1 = 0
# count2 = 0
#
# img_files = sorted(os.listdir(os.path.join(root_dir,file_dir)))
# for img in img_files:
# ann_file = img.replace('.jpg', '_train_id.png')
# ann_file_path = os.path.join(root_dir,ann_dir,ann_file)
# # print(ann_file_path)
# if os.path.exists(ann_file_path):
# dict_entry = {
# "dbName": "BDD-anonymous",
# "width": 1280,
# "height": 720,
# "fpath_img": os.path.join(file_dir, img),
# "fpath_segm": os.path.join(ann_dir, ann_file),
# }
# # If converting BDD100K uncomment out the following
# img = imread(ann_file_path)
# # if np.any(np.logical_or( (img == 18))):
# # count2 += 1
# # anom_files.append(dict_entry)
# # if 16 in np.unique(img) or 17 in np.unique(img) or 18 in np.unique(img):
# # count2 += 1
# # anom_files.append(dict_entry)
# # else:
# count1 += 1
# _files.append(dict_entry)
#
# print("total images in = {} and out = {}".format(count1, count2))
#
# with open(out_dir, "w") as outfile:
# json.dump(_files, outfile)
#
# # If converting BDD100K uncomment out the following
# # with open(root_dir + "anom.odgt", "w") as outfile:
# # json.dump(anom_files, outfile)
#
# return anom_files
#
#
# out_dir = "/home/amax_cjh/caijh28/data/bdd100k/bdd100k/seg/train_all.odgt"
# root_dir = "/home/amax_cjh/caijh28/data/bdd100k/bdd100k/seg/"
# train_dir = "images/train"
# ann_dir = "labels/train"
# anom_files = create_odgt(root_dir, train_dir, ann_dir, out_dir)
#
# out_dir = "/home/amax_cjh/caijh28/data/bdd100k/bdd100k/seg/val_all.odgt"
# root_dir = "/home/amax_cjh/caijh28/data/bdd100k/bdd100k/seg/"
# train_dir = "images/val"
# ann_dir = "labels/val"
# create_odgt(root_dir, train_dir, ann_dir, out_dir, anom_files=anom_files)
# out_dir = "data/test_all.odgt"
# root_dir = "data/"
# val_dir = "images/test/"
# ann_dir = "annotations/test/"
# create_odgt(root_dir, val_dir, ann_dir, out_dir)
# BDD100K label map
#colors = np.array(
# [0, # road
# 1, #sidewalk
# 2, # building
# 3, # wall
# 4, # fence
# 5, # pole
# 6, # traffic light
# 7, # traffic sign
# 8, # vegetation
# 9, # terrain
# 10, # sky
# 11, # person
# 12, # rider
# 13, # car
# 14, # truck
# 15, # bus
# 16, # train
# 17, # motorcycle
# 18, # bicycle
# 255,]) # other
### convert BDD100K semantic segmentation images to correct labels
def convert_bdd(root_dir, ann_dir):
count = 0
for img_loc in tqdm(os.listdir(root_dir+ann_dir)):
img = imread(root_dir+ann_dir+img_loc)
if img.ndim <= 1:
continue
#swap 255 with -1
#16 -> 19
#18 -> 16
#19 -> 18
# add 1 to whole array
loc = img == 255
img[loc] = -1
loc = img == 16
img[loc] = 19
loc = img == 18
img[loc] = 16
loc = img == 19
img[loc] = 18
img += 1
scipy.misc.toimage(img, cmin=0, cmax=255).save(root_dir+ann_dir+img_loc)
# root_dir = "data/"
# ann_dir = "seg/train_labels/train/"
# # convert the BDD100K semantic segmentation images.
# convert_bdd(root_dir, ann_dir)
# def create_odgt_road_anom(root_dir, file_dir, out_dir):
# _files = []
#
# count1 = 0
#
# img_files = sorted(os.listdir(os.path.join(root_dir,file_dir)))
# for img in img_files:
# if img.endswith('jpg'):
#
# ann_file = img.replace('.jpg', '.labels')
# ann_file_path = os.path.join(root_dir, file_dir, ann_file, 'labels_semantic.png')
# # print(ann_file_path)
# if os.path.exists(ann_file_path):
# dict_entry = {
# "dbName": "BDD-anonymous",
# "width": 1280,
# "height": 720,
# "fpath_img": os.path.join(file_dir, img),
# "fpath_segm": os.path.join(file_dir, ann_file, 'labels_semantic.png'),
# }
# count1 += 1
# _files.append(dict_entry)
# print(dict_entry)
#
# print("total images in = {}".format(count1))
#
# with open(out_dir, "w") as outfile:
# json.dump(_files, outfile)
#
# # If converting BDD100K uncomment out the following
# # with open(root_dir + "anom.odgt", "w") as outfile:
# # json.dump(anom_files, outfile)
#
# return None
#
# out_dir = "/data1/users/caijh28/data/roadanomaly/RoadAnomaly_jpg/anom.odgt"
# root_dir = "/data1/users/caijh28/data/roadanomaly/RoadAnomaly_jpg"
# train_dir = "frames"
# create_odgt_road_anom(root_dir, train_dir, out_dir)
def create_odgt_LAF(root_dir, file_dir, anno_dir, out_dir):
_files = []
all_frames = []
not_interested = []
seq_intetested = []
count1 = 0
cities = sorted(os.listdir(os.path.join(root_dir,file_dir)))
for city in cities:
for img in os.listdir(os.path.join(root_dir,file_dir,city)):
if img.endswith('png'):
ann_file = img.replace('leftImg8bit', 'gtCoarse_labelIds')
ann_file_path = os.path.join(root_dir, anno_dir, city, ann_file)
m = re.compile(r'([0-9]{2})_.*_([0-9]{6})_([0-9]{6})').match(img)
all_frames.append(dict(scene_id = int(m.group(1)), scene_seq = int(m.group(2)),scene_time = int(m.group(3))))
# print(all_frames[count1])
if os.path.exists(ann_file_path):
dict_entry = {
"dbName": "BDD-anonymous",
"width": 1280,
"height": 720,
"fpath_img": os.path.join(file_dir, city, img),
"fpath_segm": os.path.join(anno_dir, city, ann_file),
}
label = imread(ann_file_path)
if len(np.unique(label)) == 1:
# not_interested.append(count1)
# count1 += 1
continue
count1 += 1
_files.append(dict_entry)
# print(dict_entry)
# print(count1)
# count = 0
# scenes_by_id = dict()
# # print(all_frames[0])
# # print(all_frames[-1])
#
# for fr in all_frames:
# scene_seqs = scenes_by_id.setdefault(fr['scene_id'], dict())
# seq_times = scene_seqs.setdefault(fr['scene_seq'], dict())
# seq_times[fr['scene_time']] = count
# count += 1
# # print(scenes_by_id[2][18][80])
# # print(scenes_by_id[15][3][160])
# for sc_name, sc_sequences in scenes_by_id.items():
# for seq_name, seq_times in sc_sequences.items():
# # ts = list(seq_times.keys())
# # ts.sort()
# # ts_sel = ts[-1:]
# # self.frames_interesting += [seq_times[t] for t in ts_sel]
#
# t_last = max(seq_times.keys())
# seq_intetested.append(seq_times[t_last])
# print(len(seq_intetested))
#
# final_files = [_files[index] for index in seq_intetested if index not in not_interested]
print("total images in = {}".format(len(_files)))
with open(out_dir, "w") as outfile:
json.dump(_files, outfile)
# If converting BDD100K uncomment out the following
# with open(root_dir + "anom.odgt", "w") as outfile:
# json.dump(anom_files, outfile)
return None
out_dir = "/data1/users/caijh28/data/lost_found/anom_all.odgt"
root_dir = "/data1/users/caijh28/data/lost_found"
train_dir = "leftImg8bit/test"
anno_dir = "gtCoarse/test"
create_odgt_LAF(root_dir, train_dir, anno_dir, out_dir) | UTF-8 | Python | false | false | 9,569 | py | 18 | create_dataset.py | 14 | 0.506636 | 0.47006 | 0 | 279 | 32.304659 | 125 |
guilhermegreco/asg-automation | 17,841,294,147,928 | 24e6d4e05eb47f02d865509bdb0c537964ac6207 | 4edf4d6927d65341d3487230404d5cf38669630b | /src/attach-eni.py | a9dc3595f9a3e5ea734dca32ed9780e58491b7ee | []
| no_license | https://github.com/guilhermegreco/asg-automation | e71f8c009792e6b6ae9acf5a6258334cc92e11d8 | d04f62527ad7d093dbd05f9880009dc50f467d95 | refs/heads/master | 2023-03-11T05:28:46.495295 | 2021-02-25T17:24:59 | 2021-02-25T17:24:59 | 342,323,408 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import json,logging,os,boto3, string
from botocore.exceptions import ClientError
client_auto_scaling = boto3.client('autoscaling')
client_ec2 = boto3.client('ec2')
logging.basicConfig(format='%(asctime)s [%(levelname)+8s]%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)
logger.setLevel(getattr(logging, os.getenv('LOG_LEVEL', 'INFO')))
def get_instance_details(ec2_instance_id):
logger.info('Getting Details of instance id %s ' % (ec2_instance_id))
try:
response = client_ec2.describe_instances(
InstanceIds=[
ec2_instance_id
]
)
availability_zone = response['Reservations'][0]['Instances'][0]['Placement']['AvailabilityZone']
return availability_zone
except ClientError as e:
logger.error('Cannot get details from instance %s. The following error was detected %s' % (ec2_instance_id,e))
def get_autoscaling_tag(asg_name):
try:
logger.info('Getting tags from %s: ' % asg_name)
response = client_auto_scaling.describe_auto_scaling_groups(
AutoScalingGroupNames=[
asg_name
]
)
for asg in response['AutoScalingGroups']:
for tags in asg['Tags']:
if tags['Key'] == 'ServerName':
ServerName = tags['Value']
logger.info('Returning servername %s' % (ServerName))
return ServerName
except ClientError as e:
logger.error('Failed to get tags %s:' % e)
return {
'Status' : 'NOTOK'
}
def get_eni(availability_zone, server_name):
try:
logger.info('Getting information about the ENI in the AZ %s, using tag key servername %s ' % (availability_zone, server_name))
response = client_ec2.describe_network_interfaces(
Filters=[
{
'Name': 'availability-zone',
'Values' : [
availability_zone
]
},
{
'Name': 'tag:ServerName',
'Values' : [
server_name
]
}
]
)
eni_id = response['NetworkInterfaces'][0]['NetworkInterfaceId']
return eni_id
except ClientError as e:
logger.error('Cannot get the ENI ID using %s and tag %s with error %s' % (availability_zone,server_name,e ))
return {'Status : NOTOK'}
def attach_eni(ec2_instance_id, eni_id):
try:
client_ec2.attach_network_interface(
DeviceIndex=1,
InstanceId=ec2_instance_id,
NetworkInterfaceId=eni_id
)
logger.info('Interface %s attached to instance %s' % (eni_id, ec2_instance_id))
return True
except ClientError as e:
logger.error('Could not attach ENI %s in the instance %s , with error %s' % (ec2_instance_id, eni_id,e))
return False
def return_lifecycle(lifecycle_token, lifecycle_hook_name,asg_name):
try:
client_auto_scaling.complete_lifecycle_action(
LifecycleHookName=lifecycle_hook_name,
AutoScalingGroupName=asg_name,
LifecycleActionToken=lifecycle_token,
LifecycleActionResult='CONTINUE'
)
logger.info('%s returned with success for %s' % (asg_name, lifecycle_hook_name))
return {'Status' : 'OK'}
except ClientError as e:
logging.error('Cannot update lifecyclehook %s with error %s' % (lifecycle_hook_name,e))
def lambda_handler(event, context):
logger.info('This is the event %s ' % (json.dumps(event)))
ec2_instance_id = event['detail']['EC2InstanceId']
lifecycle_token = event['detail']['LifecycleActionToken']
lifecycle_hook_name = event['detail']['LifecycleHookName']
asg_name = event['detail']['AutoScalingGroupName']
availability_zone = get_instance_details(ec2_instance_id)
server_name = get_autoscaling_tag(asg_name)
eni_id = get_eni(availability_zone, server_name)
if attach_eni(ec2_instance_id,eni_id):
return_lifecycle(lifecycle_token,lifecycle_hook_name,asg_name)
| UTF-8 | Python | false | false | 4,213 | py | 7 | attach-eni.py | 2 | 0.594351 | 0.588417 | 0 | 107 | 38.373832 | 134 |
SterlingYM/PIPS | 2,456,721,310,902 | 707634a74fb22a59075c7c70b45d7fc0f7e3c574 | 02ef3ffb2c0a710f753b593547bbc3ac0bb758dc | /PIPS/periodogram/linalg/linalg.py | 069d6258bbde558b772b3ff53192e362e1ee3737 | [
"MIT"
]
| permissive | https://github.com/SterlingYM/PIPS | ba375fee1db977849e09cbb406c1de609a64fabd | b9173d00e1f4c98f689bd8c5ee7d583849bcab47 | refs/heads/master | 2023-03-20T14:41:22.526501 | 2023-03-04T02:49:55 | 2023-03-04T02:49:55 | 272,082,348 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
from scipy.optimize import curve_fit
from multiprocessing import Pool
def periodogram_fast(p_min,p_max,N,x,y,yerr,Nterms=1,multiprocessing=True,custom_periods=None,model='Fourier',repr_mode='chisq',normalize=True,**kwargs):
''' Generates the periodogram based on linear algebra method.
Args:
p_min: the minimum period of the periodogram grid.
p_max: the maximum period of the periodogram grid.
N: the number of samples in the grid.
x: the time data.
y: the mag/flux data.
yerr: the uncertainties in mag/flux data.
Nterms (int): the number of terms in Fourier/Gaussian models.
multiprocessing (bool): the option to use multiprocessing feature.
custom_periods: the user-defined period values at which the periodogram is evaluated.
model (str): the lightcurve model. It has to be the name of the pre-implemented method ('Fourier' or 'Gaussian').
repr_mode (str)['likelihood','lik','log-likelihood','loglik','chi-square','chisq']: the periodogram representation.
normalize (bool): an option to normalize the resulting periodogram.
Returns:
periods: periods at which periodogram is evaluated.
power: periodogram values.
'''
# avoid invalid log for Gaussian model
if model=='Gaussian':
y -= np.min(y)-1e-10
yerr = yerr/y
y = np.log(y)
# weighted y prep
w = (1/yerr)**2 / np.sum((1/yerr)**2)
Y = (y - np.dot(w,y))/yerr # w*y = weighted mean
# matrix prep
ii = (np.arange(Nterms)+1).repeat(len(x)).reshape(Nterms,len(x),).T
xx = x.repeat(Nterms).reshape(len(x),Nterms)
ee = yerr.repeat(Nterms).reshape(len(x),Nterms)
if xx.shape != ee.shape:
raise ValueError('y-error data size does not match x-data size')
# worker prep -- calculate power (= chi2ref-chi2)
global calc_power
def calc_power(period):
''' find best-fit solution.
X*P = Y ==> XT*X*Q = XT*Y
power(P) = yT*X*
Args:
period (float): the phase-folding period.
Returns:
power (numpy array): the periodogram value at given period.
'''
if model == 'Fourier':
# Fourier series prep
const_term = np.ones_like(x).reshape(len(x),1)
sin_terms = np.sin(ii*2*np.pi*xx/period)/ee
cos_terms = np.cos(ii*2*np.pi*xx/period)/ee
X = np.concatenate((const_term,sin_terms,cos_terms),axis=1)
elif model == 'Gaussian':
# Gaussian series prep
const_term = np.tile(np.ones_like(x).reshape(len(x),1),(1,Nterms))
linear_terms = (xx%period)/ee
square_terms = (xx%period)**2/ee
X = np.concatenate((const_term,linear_terms,square_terms),axis=1)
# linear algebra
XTX = np.dot(X.T,X)
XTY = np.dot(X.T,Y)
params = np.linalg.solve(XTX,XTY)
Yfit = np.dot(X,params)
if repr_mode == 'chisq':
return np.dot(Y,Yfit)+np.dot(Y-Yfit,Yfit)
elif repr_mode in ['likelihood','lik']:
loglik = -0.5*np.sum((Y-Yfit)**2 + np.log(2*np.pi*yerr**2))
return loglik # note: this needs to be brought back to exp later
# return np.prod(np.exp(-0.5*(Y-Yfit)**2)/(np.sqrt(2*np.pi)*yerr))
elif repr_mode in ['log-likelihood','loglik']:
return -0.5*np.sum((Y-Yfit)**2 + np.log(2*np.pi*yerr**2))
# period prep
if custom_periods is not None:
periods = custom_periods
elif (p_min is not None) and (p_max is not None):
# periods = np.linspace(p_min,p_max,N)
periods = 1/np.linspace(1/p_max,1/p_min,N)
else:
raise ValueError('period range or period list are not given')
# main
if multiprocessing:
pool = Pool()
chi2 = pool.map(calc_power,periods)
pool.close()
pool.join()
else:
chi2 = np.asarray(list(map(calc_power,periods)))
# normalize
if repr_mode in ['log-likelihood','loglik']:
if normalize:
return periods,chi2-chi2.max()
else:
return periods,chi2
elif repr_mode in ['likelihood','lik']:
if normalize:
return periods,np.exp(chi2-chi2.max())
else:
return periods,np.exp(chi2)
else:
chi2ref = np.dot(Y,Y)
power = chi2/chi2ref
return periods,power | UTF-8 | Python | false | false | 4,480 | py | 59 | linalg.py | 22 | 0.58683 | 0.576339 | 0 | 118 | 36.974576 | 153 |
janetmugogo/SendIT-api | 5,497,558,174,657 | 5b10340f74a8c80d41ec1692962b080408bab891 | ff316a642c9ecfaf5b7586d5f4d0c5e2b79d84cd | /app/tests/test_parcels.py | 4893361227074ba84884bbabfde920a4022591dd | []
| no_license | https://github.com/janetmugogo/SendIT-api | 7dadfe10b2a434390ac191df359e3d0afd5dd7b7 | 7c252d22e0284dd6cef0df0f356f844d6da45cdb | refs/heads/develop | 2020-04-05T00:36:55.044630 | 2018-11-23T07:19:01 | 2018-11-23T07:19:01 | 156,403,895 | 0 | 1 | null | false | 2018-11-23T07:19:02 | 2018-11-06T15:22:26 | 2018-11-20T20:39:06 | 2018-11-23T07:19:01 | 10,329 | 0 | 0 | 0 | Python | false | null | import unittest
import sys
import os
import json
from app.tests.base_test import BaseTest
import pdb
class TestParcel(BaseTest):
def test_create_invalid_order(self):
resp = self.client.post('/api/v2/auth/signup', json=self.register_user)
resp = self.client.post('/api/v2/auth/login', json=self.login_user)
data = json.loads(resp.get_data(as_text=True))
token = data['access_token']
response = self.client.post('/api/v2/create_parcel', data=json.dumps(self.invalid_order),
content_type='application/json', headers=dict(Authorization="Bearer " + token))
self.assertEqual(response.status_code, 400)
def test_cancel_order(self):
response = self.client.post('/api/v2/create_parcel', data=json.dumps(self.cancel_unexisting_order ), content_type='application/json')
self.assertEqual(response.status_code, 201)
response = self.client.put('/api/v2/get_parcel/1/cancel')
self.assertEqual(response.status_code, 200)
if __name__ == '__main__':
unittest.main()
| UTF-8 | Python | false | false | 1,087 | py | 26 | test_parcels.py | 22 | 0.660534 | 0.646734 | 0 | 32 | 32.96875 | 141 |
Iuty/iutylib | 14,388,140,445,363 | 303fc997be99fc7a106371e8b4e09558c11e3ff1 | 6dca81c7387ec92144dd1908855589e1c92c4057 | /IutyLib/encription/encription.py | a3cf72546c3a5c1a727cb5fb98df800dc306b907 | [
"MIT"
]
| permissive | https://github.com/Iuty/iutylib | bf2010712e3c9d31f00b3ed1bd0d16ec9c5f6350 | 763972642c536aeec352001e649a884784d19a40 | refs/heads/master | 2023-01-23T13:51:01.365025 | 2020-11-19T06:43:43 | 2020-11-19T06:43:43 | 218,896,116 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from pyDes import des, CBC, PAD_PKCS5
import hashlib
import os
import binascii
import time
# 秘钥
def des_encrypt(s,secret_key):
"""
DES 加密
:param s: 原始字符串
:return: 加密后字符串,16进制
"""
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
en = k.encrypt(s, padmode=PAD_PKCS5)
return binascii.b2a_hex(en)
def des_descrypt(s,secret_key):
"""
DES 解密
:param s: 加密后的字符串,16进制
:return: 解密后的字符串
"""
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
return de
def getfilemd5(filepath):
if not os.path.isfile(filepath):
raise Exception("Get MD5 error,it is not a file")
f = open(filepath,'rb')
filehash = hashlib.md5()
while True:
bs = f.read(8096)
if not bs:
break
filehash.update(bs)
f.close()
return filehash.hexdigest()
if __name__ == '__main__':
md5 = getfilemd5('c:\\360base.dll')
print(e-s) | UTF-8 | Python | false | false | 1,122 | py | 50 | encription.py | 48 | 0.593511 | 0.571565 | 0 | 49 | 20.408163 | 61 |
kavalle/valecito-hair | 9,938,554,330,583 | a29686c4e0f67e2330ef9f445f45e5d2cbf83156 | befcc14dedfe0c6fca8113461ce6ad14ca0d75a9 | /main/tests.py | 3ebcbbad4258ed492fe6509fec0c1ec9f9d71ced | []
| no_license | https://github.com/kavalle/valecito-hair | fc746428c249af4d62d80f1f904cdf84d587a01a | 4c8744b6fa670c0b87eb89a3a34f692126c5bd4b | refs/heads/master | 2023-01-21T09:33:19.831002 | 2020-11-28T19:23:23 | 2020-11-28T19:23:23 | 310,471,552 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.test import TestCase
from .models import Reserva
class BasicTest(TestCase):
def test_fields(self):
nueva_reserva = Reserva(
nombre_completo = 'Sady Bachmann',
correo = 'sa.bachmann@alumnos.duoc.cl',
telefono = '981648865',
servicio = 'Corte de pelo',
hora = '00:00'
)
nueva_reserva.save()
record = Reserva.objects.get(id=1)
self.assertEqual(record, 1)
def test_error(self):
nueva_reserva = Reserva(
nombre_completo = 'Sady Bachmann',
correo = 'sa.bachmann@alumnos.duoc.cl',
telefono = '',
servicio = 'Corte de pelo',
hora = '00:00'
)
nueva_reserva.save()
record = Reserva.objects.get(id=1)
self.assertEqual(record != 2) | UTF-8 | Python | false | false | 777 | py | 22 | tests.py | 12 | 0.593308 | 0.566281 | 0 | 27 | 27.814815 | 47 |
apuneet/KG-REP | 5,738,076,347,771 | 6a53b531a3c80aea25cc933f88654c4a472368fa | 7ef59f014401a7bfe88d395074fa74323b6a83ed | /KG-REP/kgrep/model_stqa.py | d76a168e4d549e05c54eaf65b1e1f880533ea8a9 | []
| no_license | https://github.com/apuneet/KG-REP | 2f8865e4e1f4a6eca0d35900efc2fd9a69358773 | 13a83fc3617ae0a4127d3dde1bd5aaf2a3b76a31 | refs/heads/master | 2020-03-31T19:58:48.362653 | 2019-01-13T11:44:49 | 2019-01-13T11:44:49 | 152,519,853 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from keras import callbacks
from keras.utils import plot_model
import load_prepare_data
import run_model_eval
from keras import backend as ke
import os
import sys
import utils.basics as bas_utils
import mods.bidi_lstm_s2s as bidi_s2s
from shutil import copyfile
lfn = None
cos_sim, tf_sess, a, b = None, None, None, None
job_name = 'job-1'
load_legend = ['load from saved_data', 'save to saved_data', 'pre-process, but don\'t save or load']
p = dict()
def check_input_arguments():
if len(sys.argv) < 2:
sys.stderr.write('Error: Not enough arguments. \n')
sys.stderr.write('Help: Set all parameters in kgt.conf, and provide its path-name as argument.\n')
sys.stderr.write(sys.argv[0] + ' <path>/kgt.conf\n')
sys.exit()
conf_path_file = sys.argv[1]
return conf_path_file
def parse_params(conf_pf):
global p
sint = bas_utils.ignore_exception(ValueError)(int)
sfloat = bas_utils.ignore_exception(ValueError)(float)
with open(conf_pf) as f:
content = f.readlines()
for next_line in content:
if next_line.startswith('#') or next_line == '\n' or len(next_line) == 0:
continue
toks = next_line.split('=')
val = toks[1].replace('\n', '')
print toks[0] + '=' + str(val)
if sint(val) is not None:
p[toks[0]] = sint(val)
continue
if sfloat(val) is not None:
p[toks[0]] = sfloat(val)
continue
p[toks[0]] = val
lod_home = os.environ['WORK_DIR']
p['dp_home'] = os.path.join(lod_home, p['dp_name'])
my_args = MyArgs(p)
jf, jn = set_job_folder(os.path.join(p['dp_home'], 'model/kgrep'))
p['job_folder'] = jf
p['job_number'] = jn
p['conf_file'] = conf_pf
my_args.job_folder = jf
copyfile(conf_pf, os.path.join(p['job_folder'], os.path.basename(conf_pf)))
print '========================================================='
return my_args
def set_job_folder(base_folder='/data/Work-Homes/LOD_HOME/fb15k2/model/kgrep/'):
max_ct = 0
for next_file in os.listdir(base_folder):
if next_file.startswith('job-'):
next_ct = int(next_file.replace('job-', ''))
max_ct = max(max_ct, next_ct)
job_number = int(max_ct+1)
tb_log_folder = os.path.join(base_folder, 'job-' + str(job_number))
print 'tb_log_folder=' + tb_log_folder
os.mkdir(tb_log_folder)
return tb_log_folder, job_number
class MyArgs:
def __init__(self, ip):
self.p = ip
self.edge_list_pf = os.path.join(p['dp_home'], 'kg/converted-rdf-' + p['dp_name'] + '.rdf')
self.job_folder = '/data/DATA_HOME/fb15k/model/kgrep/try/'
self.word_embedding = os.path.join(ip['dp_home'], ip['embedding_suffix'])
self.input_path = os.path.join(ip['dp_home'], ip['input_suffix'])
def main(conf_file):
my_args = parse_params(conf_file)
em_dim, word_ind, em_mat, rmat, isl, x_all, np_y_all, y_all, src_ent_all, osl, jos, qs, \
rel_tok_seqs, rel_ids = load_prepare_data.main(my_args)
print_basics(em_dim, len(word_ind), len(em_mat), isl, osl)
if p['load_command'] == 1:
return
x_train, y_train, x_valid, y_valid = x_all[0], np_y_all[0], x_all[1], np_y_all[1]
print 'x_train.shape=' + str(x_train.shape)
print 'isl=' + str(isl)
store_settings(my_args)
preds_trn, preds_tst, learned_emat, ygt = run_model(my_args, em_mat, rmat, word_ind, em_dim, isl, osl, x_train, y_train,
x_valid, y_valid, x_all[2], rel_tok_seqs, rel_ids, y_all,
src_ent_all, jos, qs)
print '\ntb_log_folder=' + str(my_args.job_folder)
save_predictions(my_args, preds_tst, 'tst')
run_model_eval.check_accuracy(my_args, preds_tst, y_all[2], src_ent_all[2], word_ind, learned_emat, rmat,
osl, jos[2], qs[2], split_name='tst')
def run_model(args, em_mat, rel_mat, word_ind, em_dim, isl, osl, x_train, y_train, x_valid, y_valid, x_test,
rel_tok_seqs, rel_ids, y_all, src_ent_all, jos, qs):
my_mod, to_fp = bidi_s2s.get_model3(p, em_mat, rel_mat, word_ind, em_dim, isl, osl)
my_predictions_trn, my_predictions_tst, emat, ygt = fit_and_predict(args, my_mod, x_train, y_train, x_valid, y_valid, x_test)
return my_predictions_trn, my_predictions_tst, emat, ygt
def fit_and_predict(my_args, my_model, x_train, y_train, x_valid, y_valid, x_test):
plot_model(my_model, to_file=os.path.join(my_args.job_folder, 'model-' + str(p['job_number']) + '.png'))
tb = callbacks.TensorBoard(log_dir=my_args.job_folder, histogram_freq=0, batch_size=32, write_graph=False,
write_grads=True, write_images=False, embeddings_freq=0,
embeddings_layer_names=None, embeddings_metadata=None)
fp = my_args.job_folder + '/weights.{epoch:02d}-{val_loss:.4f}.hdf5'
mc = callbacks.ModelCheckpoint(filepath=fp, save_best_only=True, mode='auto')
print 'Starting to fit the model ...'
if 'weight_file' in p.keys():
fn = os.path.join(p['job_folder'], p['weight_file'])
my_model.load_weights(fn)
elif len(x_valid) < 5:
my_model.fit(x=x_train, y=y_train, epochs=p['epoch_count'], verbose=1, callbacks=[tb,mc])
else:
print 'Length of x_valid arrary = ' + str(len(x_valid))
print 'y_train.shape=' + str(y_train.shape)
print 'y_valid.shape=' + str(y_valid.shape)
my_model.fit(x=x_train, y=y_train, validation_data=(x_valid, y_valid), epochs=p['epoch_count'], verbose=1,
callbacks=[tb, mc])
my_model.save(my_args.job_folder + '/final.model.h5')
my_model.save_weights(my_args.job_folder + '/final.model.weights.h5')
print 'Starting to predict using the model ... with Tst Data First'
my_predictions_tst = my_model.predict(x=x_test, verbose=1)
print '\nmy_predictions_tst.shape=' + str(my_predictions_tst.shape)
print 'my_predictions_tst[0].shape=' + str(my_predictions_tst[0].shape)
print 'my_predictions_tst[1].shape=' + str(my_predictions_tst[1].shape)
my_predictions_trn = my_predictions_tst # temporarily disabling this
tst_pres = my_predictions_tst
trn_pres = my_predictions_trn
return trn_pres, tst_pres, my_model.layers[1].get_weights()[0], None
def save_predictions(my_args, np_y_all_pred, split_name):
print 'Entering save_predictions() - for ' + split_name
print 'len(np_y_all_pred)=' + str(len(np_y_all_pred))
print 'np_y_all_pred.shape=' + str(np_y_all_pred.shape)
op_file = bas_utils.open_file(os.path.join(my_args.job_folder, split_name + '_pred_embeddings.txt'))
for i in range(len(np_y_all_pred)):
next_pred_list = np_y_all_pred[i]
for pred_e in next_pred_list:
op_file.write(bas_utils.to_string(pred_e, ',') + ';')
op_file.write('\n')
op_file.close()
print 'Exiting save_predictions() - for ' + split_name
def myloss(y_true, y_pred):
v1 = y_pred
v2 = y_true
numerator = ke.sum(v1 * v2)
denominator = ke.sqrt(ke.sum(v1 ** 2) * ke.sum(v2 ** 2))
loss = abs(1 - numerator/denominator)
return loss
def print_basics(em_dim, len_word_ind, len_em_mat, isl, osl):
print '--------------------------------------------------------------------------'
print 'em_dim=' + str(em_dim)
print 'len_word_ind=' + str(len_word_ind)
print 'len_em_mat=' + str(len_em_mat)
print 'Input Sequence Length=' + str(isl)
print 'Output Sequence Length=' + str(osl)
print '--------------------------------------------------------------------------'
print ' Loaded data '
print '--------------------------------------------------------------------------'
def store_settings(args):
op_file = open(os.path.join(args.job_folder, 'params.txt'), 'w')
for k in p.keys():
op_file.write(k+'=' + str(p[k]) + '\n')
op_file.close()
if __name__ == '__main__':
pf = check_input_arguments()
main(pf)
| UTF-8 | Python | false | false | 8,089 | py | 44 | model_stqa.py | 40 | 0.582025 | 0.574607 | 0 | 188 | 42.026596 | 129 |
SapnaDeshmuk/if_else_python | 2,869,038,196,781 | e9899056addc76a373ae717736b8131440628e02 | 7e6a5986e3492f88d229eef6727f49ad7af4ea04 | /ksis5.py | c32777507b69d998d893e75ec23a01cbbb4c33bb | []
| no_license | https://github.com/SapnaDeshmuk/if_else_python | 39cf8edcf1be32bc35a3130a63f1ee6157a74390 | 5b697b09ab73a8f6d04be12ed6f810d5636d5c46 | refs/heads/master | 2020-06-12T21:17:30.403248 | 2019-06-29T16:45:52 | 2019-06-29T16:45:52 | 194,427,876 | 0 | 2 | null | false | 2019-10-08T17:45:50 | 2019-06-29T16:44:26 | 2019-06-29T16:46:57 | 2019-06-29T16:46:56 | 2 | 0 | 1 | 1 | Python | false | false | a=int(raw_input("enter value"))
b=int(raw_input("enter value"))
c=int(raw_input("enter value"))
if a<b and a<c:
print a
elif b<a and b<c:
print b
else:
print c | UTF-8 | Python | false | false | 162 | py | 17 | ksis5.py | 17 | 0.666667 | 0.666667 | 0 | 9 | 17.111111 | 31 |
xW3CTORx/Kalkulacka-s-GUI | 4,166,118,286,100 | 5f4e3832df76365535be92d9e89527ebefb92fa6 | b2661865f82b6a72c70d1845720fcdf14ace5b1c | /kalkulacka s gui 2.py | bee00828c218b7dc259b6371bf6ebfabfcb63c05 | []
| no_license | https://github.com/xW3CTORx/Kalkulacka-s-GUI | 7a933073572413b27f7fd628764714eb6516b6e0 | a8a9818c38638d768aecbce4fbe27bc1a0ed276d | refs/heads/main | 2023-05-02T12:45:37.657045 | 2021-05-22T17:33:39 | 2021-05-22T17:33:39 | 369,869,134 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import tkinter
cn = tkinter.Canvas()
cn.pack()
cn.config(height= 265, width= 225, bg = 'gray')
cnt = cn.create_text
cnr = cn.create_rectangle
cislo1 = 0
cislo2 = 0
znamienko = 0
vysledok = 0
cnr(15, 35, 220, 70, outline = 'gray35', fill = 'white', width = 2, tags= 'okno')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
#### CISLA
def c1():
global cislo1, cislo2, znamienko
if (znamienko == 0):
cislo1 = cislo1 * 10 + 1
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
else:
cislo2 = cislo2 * 10 + 1
cn.delete('cisla')
cnt(115, 53, text= cislo2, font= 'Ariel 20', tags= 'cisla')
def c2():
global cislo1, cislo2, znamienko
if (znamienko == 0):
cislo1 = cislo1 * 10 + 2
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
else:
cislo2 = cislo2 * 10 + 2
cn.delete('cisla')
cnt(115, 53, text= cislo2, font= 'Ariel 20', tags= 'cisla')
def c3():
global cislo1, cislo2, znamienko
if (znamienko == 0):
cislo1 = cislo1 * 10 + 3
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
else:
cislo2 = cislo2 * 10 + 3
cn.delete('cisla')
cnt(115, 53, text= cislo2, font= 'Ariel 20', tags= 'cisla')
def c4():
global cislo1, cislo2, znamienko
if (znamienko == 0):
cislo1 = cislo1 * 10 + 4
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
else:
cislo2 = cislo2 * 10 + 4
cn.delete('cisla')
cnt(115, 53, text= cislo2, font= 'Ariel 20', tags= 'cisla')
def c5():
global cislo1, cislo2, znamienko
if (znamienko == 0):
cislo1 = cislo1 * 10 + 5
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
else:
cislo2 = cislo2 * 10 + 5
cn.delete('cisla')
cnt(115, 53, text= cislo2, font= 'Ariel 20', tags= 'cisla')
def c6():
global cislo1, cislo2, znamienko
if (znamienko == 0):
cislo1 = cislo1 * 10 + 6
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
else:
cislo2 = cislo2 * 10 + 6
cn.delete('cisla')
cnt(115, 53, text= cislo2, font= 'Ariel 20', tags= 'cisla')
def c7():
global cislo1, cislo2, znamienko
if (znamienko == 0):
cislo1 = cislo1 * 10 + 7
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
else:
cislo2 = cislo2 * 10 + 7
cn.delete('cisla')
cnt(115, 53, text= cislo2, font= 'Ariel 20', tags= 'cisla')
def c8():
global cislo1, cislo2, znamienko
if (znamienko == 0):
cislo1 = cislo1 * 10 + 8
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
else:
cislo2 = cislo2 * 10 + 8
cn.delete('cisla')
cnt(115, 53, text= cislo2, font= 'Ariel 20', tags= 'cisla')
def c9():
global cislo1, cislo2, znamienko
if (znamienko == 0):
cislo1 = cislo1 * 10 + 9
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
else:
cislo2 = cislo2 * 10 + 9
cn.delete('cisla')
cnt(115, 53, text= cislo2, font= 'Ariel 20', tags= 'cisla')
def c0():
global cislo1, cislo2, znamienko
if (znamienko == 0):
cislo1 = cislo1 * 10
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
else:
cislo2 = cislo2 * 10
cn.delete('cisla')
cnt(115, 53, text= cislo2, font= 'Ariel 20', tags= 'cisla')
#### ZNAMIENKA
def pl():
global znamienko
znamienko = 1
def mi():
global znamienko
znamienko = 2
def kr():
global znamienko
znamienko = 3
def de():
global znamienko
znamienko = 4
#### ROVNA SA A ZMAZ FUNKCIE TLACIDIEL
def rov():
global znamienko, cislo1, cislo2, vysledok
if (znamienko == 1):
vysledok = cislo1 + cislo2
elif (znamienko == 2):
vysledok = cislo1 - cislo2
elif (znamienko == 3):
vysledok = cislo1 * cislo2
elif (znamienko == 4):
vysledok = cislo1 / cislo2
cn.delete('cisla')
cnt(115, 53, text= vysledok, font= 'Ariel 20', tags= 'cisla')
vysledok = 0
znamienko = 0
def zmaz():
global znamienko, cislo1, cislo2
znamienko = 0
cislo1 = 0
cislo2 = 0
cn.delete('cisla')
cnt(115, 53, text= cislo1, font= 'Ariel 20', tags= 'cisla')
#### TLACIDLA
b1 = tkinter.Button(text = '1', command=c1, width = 5, bg = 'gray75', activebackground = 'snow')
b2 = tkinter.Button(text = '2', command=c2, width = 5, bg = 'gray75', activebackground = 'snow')
b3 = tkinter.Button(text = '3', command=c3, width = 5, bg = 'gray75', activebackground = 'snow')
b4 = tkinter.Button(text = '4', command=c4, width = 5, bg = 'gray75', activebackground = 'snow')
b5 = tkinter.Button(text = '5', command=c5, width = 5, bg = 'gray75', activebackground = 'snow')
b6 = tkinter.Button(text = '6', command=c6, width = 5, bg = 'gray75', activebackground = 'snow')
b7 = tkinter.Button(text = '7', command=c7, width = 5, bg = 'gray75', activebackground = 'snow')
b8 = tkinter.Button(text = '8', command=c8, width = 5, bg = 'gray75', activebackground = 'snow')
b9 = tkinter.Button(text = '9', command=c9, width = 5, bg = 'gray75', activebackground = 'snow')
b0 = tkinter.Button(text = '0', command=c0, width = 5, bg = 'gray75', activebackground = 'snow')
bx = tkinter.Button(text = '*', command=kr, width = 5, bg = 'gray75', activebackground = 'snow')
bd = tkinter.Button(text = '/', command=de, width = 5, bg = 'gray75', activebackground = 'snow')
bm = tkinter.Button(text = '-', command=mi, width = 5, bg = 'gray75', activebackground = 'snow')
bp = tkinter.Button(text = '+', command=pl, width = 5, bg = 'gray75', activebackground = 'snow')
br = tkinter.Button(text = '=', command=rov, width = 5, bg = 'gray75', activebackground = 'snow')
zm = tkinter.Button(text= 'zmaz', command=zmaz, width = 5, bg = 'gray75', activebackground = 'snow')
b1.place(x= 15, y= 100)
b2.place(x= 65, y= 100)
b3.place(x= 115, y= 100)
b4.place(x= 15, y= 140)
b5.place(x= 65, y= 140)
b6.place(x= 115, y= 140)
b7.place(x= 15, y= 180)
b8.place(x= 65, y= 180)
b9.place(x= 115, y= 180)
b0.place(x= 65, y= 220)
bd.place(x= 165, y= 100)
bx.place(x= 165, y= 140)
bm.place(x= 165, y= 180)
bp.place(x= 165, y= 220)
br.place(x= 115, y= 220)
zm.place(x= 15, y= 220)
cn.move('all', -3, 0)
| UTF-8 | Python | false | false | 6,866 | py | 1 | kalkulacka s gui 2.py | 1 | 0.552724 | 0.472619 | 0 | 227 | 28.246696 | 100 |
anawas/starfield | 17,901,423,718,891 | 87abbdae1a5887753cd7da8aa53792bad396e979 | 038a4beff22ffddbf8474f6e9c2b85751c65e0f6 | /app.py | 784535bf2a9a76badb9fda74ee5505fe49156269 | [
"MIT"
]
| permissive | https://github.com/anawas/starfield | db85cf440ec60db16a7e5ee63713938a0b545317 | 770e326bd3c130da59d3278b3fd7c0721e2ff597 | refs/heads/main | 2023-01-18T22:24:15.139952 | 2020-11-29T20:38:27 | 2020-11-29T20:38:27 | 316,454,782 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pygame
import numpy as np
import random
from game_objects import HorizontalStar
WIDTH = 800
HEIGHT = 800
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
MAX_STARS = 800
starfield = []
def event_handler(event_queue):
for event in event_queue:
if event.type == pygame.QUIT:
return False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
return True
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
for _ in range(MAX_STARS):
starfield.append(HorizontalStar(screen))
pygame.display.set_caption("PyGame")
clock = pygame.time.Clock()
running = True
while running:
clock.tick(30)
screen.fill(BLACK)
running = event_handler(pygame.event.get())
create_stars(screen)
for star in starfield:
star.update()
pygame.display.flip()
def create_stars(screen):
for i in range(0, MAX_STARS):
if starfield[i].done():
del starfield[i]
newStar = HorizontalStar(screen)
newStar.x = 0
starfield.append(newStar)
if __name__ == "__main__":
main() | UTF-8 | Python | false | false | 1,258 | py | 3 | app.py | 2 | 0.596184 | 0.576312 | 0 | 57 | 21.087719 | 73 |
EDataScriptware/SES | 13,365,938,266,543 | 6906a7d89d8ad925d3044800106a92b335f76242 | dca6b359d0a3f5aec9badd4c06e1647399fd3ba6 | /setup.py | c0797a025c4d0143e4e2229e5c8e07c27d259087 | []
| no_license | https://github.com/EDataScriptware/SES | 9318c2391237226407c9bcf0d0ec4207de152635 | 42525613986ff162002c2d106a8ed6016a98707e | refs/heads/main | 2023-07-02T04:19:23.989161 | 2021-08-11T17:50:26 | 2021-08-11T17:50:26 | 389,039,707 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from distutils.core import setup
import py2exe
Mydata_files = [
('util', ['util/profile.json']),
('util', ['util/game_commands.json'])
]
setup(
options = {'py2exe': {'bundle_files': 1, 'compressed': False}},
console=['GUI.py'],
data_files = Mydata_files,
)
| UTF-8 | Python | false | false | 292 | py | 12 | setup.py | 7 | 0.585616 | 0.575342 | 0 | 14 | 19.857143 | 71 |
Rus-Picasso/gb-python | 11,072,425,707,216 | afeaf1341d94113c1924701ccf0540cdaef03f1f | 054dc339b3d3b391d693be0e8ee473ac5040d52a | /H1[1].py | c9db278fc277d81f3b84202e3a1fb7f5e6864e96 | []
| no_license | https://github.com/Rus-Picasso/gb-python | ff2aa065854c63736653835dfa1fd0a58af39d72 | 7d2cc176636653f82e15d9b8d20a59efc293a3a6 | refs/heads/master | 2022-12-16T03:12:52.431221 | 2020-09-21T12:04:51 | 2020-09-21T12:04:51 | 291,006,163 | 0 | 0 | null | false | 2020-08-28T10:46:10 | 2020-08-28T09:27:17 | 2020-08-28T10:31:03 | 2020-08-28T10:31:00 | 5 | 0 | 0 | 1 | Python | false | false | # Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
a = 1
b = 2
c = 3
d = a + (b * c)
print(a, b, c, d)
name = input('Введите Ваше имя: ')
name = 'Привет ' + name + '! Меня зовут Альберт!'
print(name)
case = input('Сколько тебе лет? ')
case = 'Мне тоже ' + case
print(case) | UTF-8 | Python | false | false | 576 | py | 10 | H1[1].py | 10 | 0.676166 | 0.668394 | 0 | 15 | 24.8 | 161 |
freQuensy23-coder/spyTeleBot | 5,944,234,767,867 | ba0be5a4764048a3a509f5e04078e5b04ae35fc4 | 9495161565a80c5ae21e6c99822ac03325305257 | /Exceptions.py | f03454c877e041cff6b8af52cd69fcecb52dd302 | []
| no_license | https://github.com/freQuensy23-coder/spyTeleBot | e17b54c0287e1d6aa25a48a8ba00e92418253a87 | 52d587376be510ca8c39efdb311346fa24c253e1 | refs/heads/main | 2023-06-07T19:56:40.484735 | 2021-06-24T20:09:12 | 2021-06-24T20:09:12 | 364,803,932 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class NoSuchRoomError(Exception):
pass # TODO Add logging to all Exceptions
# TODO Add exceptions to Exceptions file
class NotEnoughPlayersError(Exception):
pass
class GameAlreadyStartedError(Exception):
pass
class CanNotEnterRoomError(Exception):
pass
| UTF-8 | Python | false | false | 281 | py | 4 | Exceptions.py | 3 | 0.758007 | 0.758007 | 0 | 15 | 17.666667 | 46 |
ExoBen/university-project | 16,406,775,073,621 | 8cc8c96520379d7054e7e33b16073b04d4f5cd68 | 0c24b49089017a0f6c9fce2c95f8ca57cf1da71e | /dev/webtulip/tulip_wrapper/tlp_json_converter.py | 6cc8a1b5eeb569909ff10ec018189ccfd1da9da4 | []
| no_license | https://github.com/ExoBen/university-project | 5aff2470e378b646833a419f8bcc294233713c7e | 9e252d5c395d7d6d3a2b1d8cc231462a11ab5efd | refs/heads/master | 2021-03-19T16:45:21.784945 | 2018-10-18T21:33:35 | 2018-10-18T21:33:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class TlpJsonConverter:
def tlp_to_json(name, network, nodesBeenPruned, numDeletedClique, numDeletedEdge):
jsonNetwork = {"nodes": [], "edges": [], "nodesBeenPruned": [], "numDeletedClique": [], "numDeletedEdge": []}
for node in network.getNodes():
jsonNetwork["nodes"].append({"id": node.id})
for edge in network.getEdges():
jsonNetwork["edges"].append({"from": network.source(edge).id, "to": network.target(edge).id})
for nodeNumPair in nodesBeenPruned:
# if a node has since been removed by another algorithm then don't send it across the network
for node in network.getNodes():
if node == nodeNumPair["node"]:
jsonNetwork["nodesBeenPruned"].append({"id": nodeNumPair["node"].id, "number": nodeNumPair["number"]})
for nodeNumPair in numDeletedClique:
# if a node has since been removed by another algorithm then don't send it across the network
for node in network.getNodes():
if node == nodeNumPair["node"]:
jsonNetwork["numDeletedClique"].append({"id": nodeNumPair["node"].id, "numDeleted": nodeNumPair["numDeleted"]})
for nodeNumPair in numDeletedEdge:
# if a node has since been removed by another algorithm then don't send it across the network
for node in network.getNodes():
if node == nodeNumPair["node"]:
jsonNetwork["numDeletedEdge"].append({"id": nodeNumPair["node"].id, "numDeleted": nodeNumPair["numDeleted"]})
return jsonNetwork
| UTF-8 | Python | false | false | 1,421 | py | 44 | tlp_json_converter.py | 18 | 0.706545 | 0.706545 | 0 | 30 | 46.333333 | 116 |
ahunter787/grzzmorgian_project | 6,777,458,439,218 | 6aab644c8e5563c62fc970c02531be508b41d8f6 | ff6996d4852e868d3fbfc2ac508e51b4c04b8f12 | /test.py | 81ee289232e14db83127eb011539c6dac68a6859 | []
| no_license | https://github.com/ahunter787/grzzmorgian_project | 42a4bfa1084c15ae39a72815c9929cce87c859ca | cf227939a515bde9d8125867611e668b9cec8b1e | refs/heads/master | 2021-01-22T04:49:02.737425 | 2014-03-14T02:42:43 | 2014-03-14T02:42:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from dinnerTable import *
from itertools import *
from collections import defaultdict
#indv = Individual(gender, sash, emblem, flower, drink)
# Our first working case - hand calculated
# quick = Individual("q", "black", "planet", "rose", "water")
# male = Individual("m", "blue", "spaceship", "lily", "herbal tea")
# rachial=Individual("r", "scarlet", "ocean", "carnation", "black tea")
# sessile=Individual("s", "orange", "star", "tulip", "coffee")
# female =Individual("f", "purple", "mountain", "orchid", "green tea")
# myDinnerTable = [female, sessile, rachial, male, quick]
#Our second working case - hand calculated
quick = Individual("q", "black", "planet", "rose", "water")
male = Individual("m", "scarlet", "spaceship", "orchid", "herbal tea")
rachial=Individual("r", "orange", "ocean", "carnation", "coffee")
sessile=Individual("s", "blue", "mountain", "lily", "green tea")
female =Individual("f", "purple", "star", "tulip", "black tea")
myDinnerTable = [rachial, male, female, sessile, quick]
#female.toString()
table = dinnerTable(myDinnerTable)
# print table.checkConditions()
# print ""
# table.toString()
validTables = []
## ITS POSSIBLE THE PROBLEM IS IN THE WAY I FILTER THE RESULTS? (filter after whole list of distinct permutations is generated)
## Or am i not generating all of the permutations?
def generateValidTables():
genders = ["m", "f", "r", "q", "s"]
sashes = ["purple", "orange", "scarlet", "black", "blue"]
emblems = ["star", "planet", "spaceship", "mountain", "ocean"]
flowers = ["rose", "orchid", "tulip", "carnation", "lily"]
drinks = ["coffee", "herbal tea", "black tea", "green tea", "water"]
genderPerms = list(permutations(genders))
emblemPerms = list(permutations(emblems))
flowerPerms = list(permutations(flowers))
sashPerms = list(permutations(sashes))
drinkPerms = list(permutations(drinks))
numPerms = len(sashPerms)
allPerms = [genderPerms, sashPerms, emblemPerms, flowerPerms, drinkPerms]
allPermsDict = defaultdict(list)
for i in range(5):
allts = [] # the order of the values of each permutation
for j in range(numPerms): # 0-119
t1, t2, t3, t4, t5 = allPerms[i][j]
ts = [t1, t2, t3, t4, t5]
allts.append(ts)
allPermsDict[i] = allts
#for i in range(5):
# I AM ONLY CREATING 120 TABLES. I NEED TO BE MAKING 600 -- Involves changing the way i create tables at pIndex
for pIndex in range(numPerms):
table = []
for i in range(5): #
igender = allPermsDict[0][pIndex][i]
isash = allPermsDict[1][pIndex][i]
iemblem = allPermsDict[2][pIndex][i]
iflower = allPermsDict[3][pIndex][i]
idrink = allPermsDict[4][pIndex][i]
table.append(Individual(igender, isash, iemblem, iflower, idrink))
table = dinnerTable(table)
table.checkConditions(False)
#print pIndex
print "Errors: " + str(len(table.errors))
#print table.errors
#table.toString()
if len(table.errors) < 1:
validTables.append(table)
print "Valid Tables Found: " + str(len(validTables))
generateValidTables()
print len(validTables)
| UTF-8 | Python | false | false | 3,243 | py | 5 | test.py | 4 | 0.636139 | 0.627197 | 0 | 84 | 37.547619 | 127 |
HPortuga/T1IA2019 | 3,246,995,316,078 | d1604654cdc89dd6b69ca0409282cbdd7377f5d9 | 67ca386d52ad4cac48cc5ab5c983b3940c841fb6 | /RestaUm/heuristica.py | 672c1f61c5c07960ff61bb405bc863605ef303ab | []
| no_license | https://github.com/HPortuga/T1IA2019 | cdda6d4bc620ee6160c272f1c0f95986cd95e2f9 | f1d53bcab2e63e9bfa39d3de9be307e33632d623 | refs/heads/master | 2020-05-04T23:35:58.752484 | 2019-05-12T00:52:46 | 2019-05-12T00:52:46 | 179,548,947 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Matheus Soares / 2016.1904.030-1
# Victor Ezequiel / 2016.1904.047-6
# Gabriel Menezes / 2016.1906.005-1
def calcularHeuristica(node):
numPecas, coordenadasDasPecas = contarPecas(node.estado)
unsPresosNosCantos = contarUnsPresos(node.estado)
distanciaMediaManhattan = calcularDistanciaManhattan(node.estado, coordenadasDasPecas) / numPecas
# fatorDeProfundidade = 1024 - (node.custo * node.custo)
return distanciaMediaManhattan + (pow(unsPresosNosCantos,pow(2,unsPresosNosCantos)))
# Calcula a soma da distancia de cada peca ate todas as outras pecas no tabuleiro
def calcularDistanciaManhattan(estado, coordenadasDasPecas):
dMan = 0
for linha in coordenadasDasPecas:
for coluna in coordenadasDasPecas:
if (linha == coluna): continue
x = abs(linha[0]-coluna[0])
y = abs(linha[1]-coluna[1])
dMan += (x+y)
return dMan
# Conta numero de 1's no tabuleiro
def contarPecas(estado):
numPecas = 0
coordenadasDasPecas = []
for linha in range(0,7):
for coluna in range(0,7):
if (estado[linha][coluna] == 1):
numPecas += estado[linha][coluna]
coordenadasDasPecas.append([linha,coluna])
return (numPecas, coordenadasDasPecas)
# Serao contados 1's nas extremidades dos tabuleiros cujas pecas adjacentes sao 0's
def contarUnsPresos(estado):
unsNosCantos = 0
if (estado[0][2] == 1
and estado[0][3] == 0
and estado[1][2] == 0):
unsNosCantos += 1
if (estado[0][4] == 1
and estado[0][3] == 0
and estado[1][4] == 0):
unsNosCantos += 1
if (estado[2][0] == 1
and estado[3][0] == 0
and estado[2][1] == 0):
unsNosCantos += 1
if (estado[4][0] == 1
and estado[3][0] == 0
and estado[4][1] == 0):
unsNosCantos += 1
if (estado[6][2] == 1
and estado[5][2] == 0
and estado[6][3] == 0):
unsNosCantos += 1
if (estado[6][4] == 1
and estado[6][3] == 0
and estado[5][4] == 0):
unsNosCantos += 1
if (estado[2][6] == 1
and estado[2][5] == 0
and estado[3][6] == 0):
unsNosCantos += 1
if (estado[4][6] == 1
and estado[4][5] == 0
and estado[3][6] == 0):
unsNosCantos += 1
return unsNosCantos
| UTF-8 | Python | false | false | 2,225 | py | 6 | heuristica.py | 6 | 0.618427 | 0.557303 | 0 | 80 | 26.8125 | 100 |
tuankhai3112/tuankhai | 16,277,926,089,441 | 2bc108e421fa575a76784247222a8fafa67645a9 | ddac50d0c868e88f79603aff954991c93aec87bc | /tim gtri tronglist random.py | 58a4a8e1d871ef1684678e05101d1909061547c6 | []
| no_license | https://github.com/tuankhai3112/tuankhai | ce0751d140c78b2c8f78bae24b6feae1c97afd9c | 160d718bc35f5c0a25f615fc858de996eb1447d3 | refs/heads/master | 2022-11-07T01:00:38.834925 | 2020-06-20T16:47:37 | 2020-06-20T16:47:37 | 256,784,684 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from random import sample, randint
A=sample(range(100), 100)
a=randint(0,100)
A.sort()
if a in A:
print(a,' có trong mảng\nVị trí của ',a,'là: ',A.index(a))
| UTF-8 | Python | false | false | 176 | py | 3 | tim gtri tronglist random.py | 3 | 0.634731 | 0.57485 | 0 | 6 | 25.833333 | 62 |
sidbhadur2/ProjectX | 2,035,814,505,207 | 2724cc9d91d89f3f4193cfaaca478f876fd207aa | 64078cc241f096c2b284b77f142cf12271a4b166 | /tests/artist.py | 201b08ca2505cbdc06cee27213fb760ecd3b7baa | []
| no_license | https://github.com/sidbhadur2/ProjectX | 64f84354533fdaa988d5d35e30e09fc56df32ba3 | 1860446de2cebabaeba2bf21ea134d123fe2cce5 | refs/heads/master | 2020-12-11T07:26:57.043841 | 2015-11-28T09:29:04 | 2015-11-28T09:29:04 | 44,497,532 | 0 | 0 | null | true | 2015-10-18T21:34:51 | 2015-10-18T21:34:51 | 2015-10-13T02:51:16 | 2015-10-14T17:46:25 | 111 | 0 | 0 | 0 | null | null | null | from musixmatch import *
from tests import base
class TestArtist(base.TestItem):
Class = artist.Artist
item = {
"artist_id": "292",
"artist_mbid": "292",
}
item_str = "{ 'artist_id': '292',\n 'artist_mbid': '292'}"
item_repr = "Artist({'artist_mbid': '292', 'artist_id': '292'})"
item_hash = 292
class TestArtistsCollection(base.TestCollection):
CollectionClass = artist.ArtistsCollection
AllowedContentClass = artist.ArtistsCollection.allowedin()
item_list = 'artist_list'
item_id = 'artist_id'
item = 'artist'
message = {
"body": {
"artist_list": [
{
"artist": {
"artist_id": "292",
"artist_mbid": "292",
}
},
{
"artist": {
"artist_id": "8976",
"artist_mbid": "8976",
}
},
{
"artist": {
"artist_id": "9673",
"artist_mbid": "9673",
}
}
]
},
"header": {
"execute_time": 0.14144802093506001,
"status_code": 200
}
}
| UTF-8 | Python | false | false | 1,330 | py | 222 | artist.py | 30 | 0.398496 | 0.350376 | 0 | 47 | 27.276596 | 68 |
jbpark/alza-stock | 19,602,230,739,784 | c8ab6f02fbac03b84ffb9e64787b384abd00e628 | 34f817cf5f12469c6daa7a326359e128084bdc98 | /sample/python/back_test/back_test_backtrader.py | 5b8a71df5955868cdced6ea8a9a884776ae141fd | []
| no_license | https://github.com/jbpark/alza-stock | cfb55a3e24ba9eb4e19ea9f15fc028a5b56184bd | b107a660d03332ddcb46e610ab0ac9ae8e7cbd81 | refs/heads/master | 2020-07-30T07:30:51.576528 | 2019-10-29T06:40:58 | 2019-10-29T06:40:58 | 210,135,766 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | # pip install backtesting
# pip install pip install -U finance-datareader
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
from backtesting.test import SMA
import FinanceDataReader as fdr
fdr.__version__
class SmaCross(Strategy):
def init(self):
Close = self.data.Close
self.ma1 = self.I(SMA, Close, 10)
self.ma2 = self.I(SMA, Close, 20)
def next(self):
if crossover(self.ma1, self.ma2):
self.buy()
elif crossover(self.ma2, self.ma1):
self.sell()
# 셀트리온, 2018년~2019년6월
data = fdr.DataReader('068270', '20180104','20190630')
print(data.head())
# 초기투자금 10000, commission 비율 0.002 임의 지정
bt = Backtest(data, SmaCross,
cash=10000, commission=.002)
bt.run()
print(bt._results)
#print(bt._results['Return [%]'])
bt.plot() | UTF-8 | Python | false | false | 874 | py | 48 | back_test_backtrader.py | 12 | 0.661098 | 0.591885 | 0 | 33 | 24.424242 | 54 |
lucaseliascrocha/PFC | 3,092,376,466,924 | 155264daee6bbeeffc7d2461a85028bb10b19b07 | 4cde0062c038804b4e41f29bb4305d2b248841c8 | /Topicos_Infomap/doc_classifier.py | c7d3b278af1cb284cccb1e37579e964f62f70ccb | []
| no_license | https://github.com/lucaseliascrocha/PFC | 1903b1161a5865eb5d4f1f2d92033a7c953ac255 | b953e1c21faedbc9dec4587b13d100fdc76f54a1 | refs/heads/master | 2021-10-25T14:47:48.129530 | 2019-04-04T19:08:16 | 2019-04-04T19:08:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
output_folder = '../Classificação dos Documentos/'
doc_folder = '../Documentos Finais/'
for doc in os.listdir():
if doc.split('.')[1] != 'ftree':
continue
print('--> ' + doc)
#--------- Carregando Topicos/Clusters ----------#
f = open(doc, 'r')
lines = f.readlines()
f.close()
n_cluster = 0
cluster = [] # cada elemento i da lista contém o conjunto de pares termo-flow do cluster i
flow_cluster = [] # cada elemento i da lista contém o flow total do cluster i
flow_sum = 0
for l in lines[2:]:
if l[0] == '*':
break
spl = l.split()
if int(spl[0].split(':')[0]) == n_cluster:
cluster[n_cluster-1][spl[2][1:-1]] = float(spl[1])
flow_sum += float(spl[1])
else:
n_cluster += 1
cluster.append({spl[2][1:-1]:float(spl[1])})
if not n_cluster == 1:
flow_cluster.append(flow_sum)
flow_sum = float(spl[1])
flow_cluster.append(flow_sum)
#--------- Carregando documentos ----------#
ego = doc.split('.')[0]
file = doc_folder + ego + '.txt'
f = open(file, 'r', encoding="utf8")
documentos = f.readlines()
f.close()
#---------- Montando e salvando matriz de classificação ----------#
file = output_folder + ego + '.txt'
output = open(file, 'w+')
alpha = 0.1 #valor mínimo de fluxo que um tópico precisa em relação ao melhor tópco (poda de tópicos)
min_fluxo = alpha * flow_cluster[0]
print('Maior fluxo: ' + str(flow_cluster[0]) + '\nFluxo mínimo: ' + str(min_fluxo) + '\n')
for doc in documentos:
termos = doc.split()
for topic in range(0, n_cluster):
#--- Verificando o valor de poda de tópicos---#
if flow_cluster[topic] < min_fluxo:
break
count = 0
flow = 0
for t in termos:
if t in cluster[topic].keys():
count += 1
flow += cluster[topic][t]
if flow_cluster[topic] == 0 and count > 0:
k = 100
elif flow_cluster[topic] == 0:
k = 0.0
else:
k = count * flow/flow_cluster[topic]
output.write(str(k) + ' ')
output.write('\n')
output.close() | UTF-8 | Python | false | false | 2,362 | py | 90 | doc_classifier.py | 11 | 0.501278 | 0.485094 | 0 | 74 | 30.743243 | 105 |
blengerich/ArXiv-Scraper | 11,416,023,086,864 | 5b72aa3075438629ab790aa769399ea90c21d419 | 2c055175cb4cbcde00503585fba0e1c319ff59f8 | /users_manager.py | 61a7a42746ae2e74f4971a0dea2cb881450ee3ad | []
| no_license | https://github.com/blengerich/ArXiv-Scraper | a9ff85bdab12291c0679311a690140e8c19c7c1d | d5799eb9d4c11a21c4ebe2d812909795f07d186d | refs/heads/master | 2015-08-19T19:20:45.851894 | 2015-03-05T02:51:29 | 2015-03-05T02:51:29 | 29,698,628 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | users_singleton = None
users_file = "users.txt"
"""
Returns/Instantiates the singleton of users
Will be a list
"""
def users():
if users_singleton is not None:
return users_singleton
else:
load_users_from_file(users_file)
return users_singleton
"""
Reads and loads a text file of users with their interest vectors
Stores a list in users_singleton
NOTE: Overwrites users_singleton
"""
def load_users_from_file(filename):
print "load_users_from_file not implemented"
users_singleton = [] | UTF-8 | Python | false | false | 499 | py | 11 | users_manager.py | 8 | 0.747495 | 0.747495 | 0 | 23 | 20.73913 | 64 |
StefanFrederiksen/DeepLearning-Project12 | 4,818,953,351,668 | e5d7009a6dc086d8ab941ec882ca088a0f466674 | 1a3d31a8423ca8185ac55130ce8788cac062ced3 | /Code/spec_generator.py | d6a1b6878a6ec532aad2e6c59827fc233a8d1b47 | []
| no_license | https://github.com/StefanFrederiksen/DeepLearning-Project12 | f41906f4bb33a0a0a357d2dbb511e18aa4c17416 | 7461a3fdd2807d5e67bd540eba50bb8ea8f7a013 | refs/heads/master | 2023-01-10T00:28:18.727721 | 2017-12-04T13:22:32 | 2017-12-04T13:22:32 | 107,981,837 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 23 13:43:34 2017
@author: jacob
"""
import numpy as np
import scipy.signal
import os
import utils
import librosa
from sklearn.preprocessing import normalize
import random
path_to_8k = '/media/jacob/Files/UrbanSound8K'
save_path = path_to_8k+'/spectrograms'
save_path_log= path_to_8k+'/log_spectrograms'
save_path_noise = path_to_8k+'/noise_spectrograms'
save_path_log_noise = path_to_8k+'/log_noise_spectrograms'
path = path_to_8k+'/audio'
os.mkdir(save_path)
os.mkdir(save_path_log)
os.mkdir(save_path_noise)
os.mkdir(save_path_log_noise)
white_noise_db = 6
shuffle_folds = True
test_frac = 0.1
frac = 1./3 #Fraction of energy that must be in a segment, compared to if energy was uniformly distributed
i = 0
j = 0
folders = os.listdir(path)
for folder in folders:
if folder[0:4] == 'fold':
os.mkdir(save_path+'/'+folder)
os.mkdir(save_path_log+'/'+folder)
os.mkdir(save_path_noise+'/'+folder)
os.mkdir(save_path_log_noise+'/'+folder)
path_temp = path+'/'+folder
files = os.listdir(path_temp)
for file in files:
if file[-4:] == '.wav':
try:
sound, sample_rate = librosa.load(path_temp+'/'+file)
var_sound = np.var(sound)
sound_w_noise = np.zeros(len(sound))
f, t, sxx = scipy.signal.spectrogram(sound, sample_rate, noverlap=64)
log_sxx = normalize(librosa.power_to_db(sxx[1:], ref=np.max))
sxx = normalize(sxx[1:])
specs = int((np.shape(sxx)[1]-np.shape(sxx)[1]%128)/128)
energy = sum(sum(sxx))
threshold = float(energy)/specs * frac
var_noise = var_sound*(10**(white_noise_db/10.))**(-1)
noise = np.random.normal(0,var_noise,len(sound))
sound_w_noise = sound + noise
f_noise, t_noise, sxx_noise = scipy.signal.spectrogram(sound_w_noise)
sxx_noise = normalize(sxx_noise[1:])
log_sxx_noise = normalize(librosa.power_to_db(sxx[1:], ref=np.max))
for i in range(specs):
temp = sxx[:,(i)*128:(i+1)*128]
temp_log = log_sxx[:,(i)*128:(i+1)*128]
temp_noise = sxx_noise[:,(i)*128:(i+1)*128]
temp_log_noise = log_sxx_noise[:,(i)*128:(i+1)*128]
if sum(sum(temp)) > threshold:
np.savetxt(save_path+'/'+folder+'/'+file[:-4]+'_'+str(i)+'.txt', temp, delimiter=',')
np.savetxt(save_path_log+'/'+folder+'/'+file[:-4]+'_'+str(i)+'.txt', temp_log, delimiter=',')
np.savetxt(save_path_noise+'/'+folder+'/'+file[:-4]+'_'+str(i)+'.txt', temp_noise, delimiter=',')
np.savetxt(save_path_log_noise+'/'+folder+'/'+file[:-4]+'_'+str(i)+'.txt', temp_log_noise, delimiter=',')
else:
j += 1
except:
i += 1
if shuffle_folds == True:
for i in range(10):
os.mkdir(save_path+'/fold'+str(i+11))
os.mkdir(save_path_log+'/fold'+str(i+11))
os.mkdir(save_path_log_noise+'/fold'+str(i+11))
os.mkdir(save_path_noise+'/fold'+str(i+11))
for i in range(10):
files = os.listdir(save_path+'/fold'+str(i+1))
files_log = os.listdir(save_path_log+'/fold'+str(i+1))
files_noise = os.listdir(save_path_noise+'/fold'+str(i+1))
files_log_noise = os.listdir(save_path_log_noise+'/fold'+str(i+1))
random.shuffle(files)
random.shuffle(files_log)
random.shuffle(files_noise)
random.shuffle(files_log_noise)
length = int(len(files)*test_frac)
for k in range(10):
for j in range(length):
os.rename(save_path+'/fold'+str(i+1)+'/'+files[k*length+j],save_path+'/fold'+str(k+11)+'/'+files[k*length+j])
os.rename(save_path_log+'/fold'+str(i+1)+'/'+files_log[k*length+j],save_path_log+'/fold'+str(k+11)+'/'+files_log[k*length+j])
os.rename(save_path_noise+'/fold'+str(i+1)+'/'+files_noise[k*length+j],save_path_noise+'/fold'+str(k+11)+'/'+files_noise[k*length+j])
os.rename(save_path_log_noise+'/fold'+str(i+1)+'/'+files_log_noise[k*length+j],save_path_log_noise+'/fold'+str(k+11)+'/'+files_log_noise[k*length+j]) | UTF-8 | Python | false | false | 4,564 | py | 22,680 | spec_generator.py | 3 | 0.538124 | 0.512927 | 0 | 102 | 43.754902 | 165 |
takutico/notes | 8,048,768,731,943 | 5628661da8c45fbd0ee2a371d16503f52570ab16 | 0471b91ca8d5e65919db9ea371ca3fd0c0dc157f | /numbers_from_list.py | 2826e5b0113a83b86a970acd92a68f2b404195da | []
| no_license | https://github.com/takutico/notes | 70e37784d5caef46e75890a09e15440355c6d4d7 | c2c262ce4f9b6ba48cb19d93edc0a7573a64b926 | refs/heads/master | 2021-01-17T18:04:59.808050 | 2017-09-13T04:16:35 | 2017-09-13T04:16:35 | 62,384,936 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | L = ['asfd', '1', '44','g', '4 5', '7k', '563']
# tl =[]
# for i in l:
# if i.isdigit():
# tl.append(i)
<<<<<<< HEAD
# print([i for i in l if i.isdigit()])
print([ i for i in l if str(i).isdigit()])
=======
# using for loop
print('Using loop')
print([i for i in L if i.isdigit()])
import re
print('Using regular expressions')
s = '123fdsf24rt3g4'
m = re.findall(r'\d+', s)
print(m)
# print(x for x in re.match(r'\d+', s))
>>>>>>> b303145b58fc925412f7fd25a4e7d53adf50336f
| UTF-8 | Python | false | false | 479 | py | 44 | numbers_from_list.py | 26 | 0.580376 | 0.492693 | 0 | 24 | 18.958333 | 48 |
yuqingwang15/pythonproblempractices | 1,331,439,873,098 | a710473fac485045ca7aef38f591254eadbc25be | 3d9d231ad18742f6a478660bbc692ed58af18994 | /spider/spider.py | 12cd0ea0592ffd0db70b7788a0fec3d1b54bac50 | []
| no_license | https://github.com/yuqingwang15/pythonproblempractices | 9ba91e2eb88757a49842feeb5aae0004d4391e54 | 4e54855597021500b05bf8baaeb79a4ff002def3 | refs/heads/master | 2021-01-20T18:09:50.618739 | 2017-12-12T16:25:37 | 2017-12-12T16:25:37 | 65,372,669 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from urllib import urlopen
from link_finder import LinkFinder
from genneral import *
import scrapy
class Spider:
project_name = ''
base_rul = ''
domain_name = ''
queue_file = ''
crawled_file = ''
queue = set()
crawled = set()
def _init_(self,params):
#super()._init_()
Spider.project_name =params.get("project_name")
Spider.base_rul = params.get("base_rul")
Spider.domain_name = params.get("domain_name")
Spider.queue_file = project_name+'/queue.txt'
Spider.crawled_file = project_name+'/crawled.txt'
self.boot()
self.crawl_page('first spider',Spider.base_rul)
@staticmethod
def boot():
create_project_dir(Spider.project_name)
create_data_files(Spider.project_name,Spider.base_rul)
Spider.queue = file_to_set(Spider.queue_file)
Spider.crawled = file_to_set(Spider.crawled_file)
@staticmethod
def crawl_page(threadname,page_rul):
if page_rul not in Spider.crawled:
print(threadname + 'now crawling'+page_rul)
print('queue' + str(len(Spider.queue)))
Spider.add_links_to_queue(Spider.gather_link(page_rul))
Spider.queue.remove(page_rul)
Spider.crawled.add(page_rul)
Spider.update_file()
@staticmethod
def gather_link(page_rul):
html_string = ''
try:
response =urlopen(page_url)
if response.getheader('content-type'=='text/html'):
html_bytes = response.read()
html_string = html_bytes.decode("utf-8")
finder = LinkFinder(Spider.base_rul,Spider.page_url)
finder.feed(html_bytes)
except:
print("error")
return set()
return finder.page_links
@staticmethod
def add_links_to_queue(links):
for url in links:
if url in Spider.queue:
continue
if url in Spider.crawled:
continue
if Spider.domain_name not in url:
continue
Spider.queue.add(url)
@staticmethod
def update_file():
set_to_file(Spider.queue,Spider.queue_file)
set_to_file(Spider.crawled,Spider.crawled_file)
| UTF-8 | Python | false | false | 1,915 | py | 45 | spider.py | 40 | 0.691384 | 0.690862 | 0 | 73 | 25 | 58 |
EBoespflug/arp-poisoning-scapy | 1,125,281,471,933 | ee166548039e9e3a68ecf11251f4d6135638b63f | ab67368b5082ef1adf2b9b5e2483a3314da9c00d | /UI/host_widgets.py | 3295b1d9672e8cbce1f97ba9a27b255585ca2421 | []
| no_license | https://github.com/EBoespflug/arp-poisoning-scapy | 5fc4eaec785971c9007c8688e1ca4f9331fecee0 | 2de6fbae6427c70c20041d49f3050af1fe1ab4d8 | refs/heads/master | 2021-01-19T07:57:59.140637 | 2018-08-09T18:39:20 | 2018-08-09T18:39:20 | 87,587,507 | 1 | 0 | null | false | 2018-08-09T18:39:21 | 2017-04-07T21:15:26 | 2018-08-09T18:33:30 | 2018-08-09T18:39:21 | 153 | 1 | 0 | 0 | null | false | null | from PyQt5.QtWidgets import *
from PyQt5.QtGui import (QIcon)
from PyQt5.QtCore import (QSize, pyqtSignal)
import sys
sys.path.append('../core/')
sys.path.append('../')
from Host import *
from arp import send_arp
import time, threading
import resources
def PARPThread(target, router, stopEvent):
while(not stopEvent.is_set()):
send_arp(target, router)
time.sleep(1)
class HostWidget(QWidget):
sig_closed = pyqtSignal(QWidget)
def __init__(self, host):
super(HostWidget, self).__init__()
self.mitm = False
self.host = host
self.arpThread = None
self.createWidgets()
def createWidgets(self):
self.nameText = QLineEdit()
self.nameText.setReadOnly(True)
self.nameText.setText(self.host.name)
self.ipText = QLineEdit()
self.ipText.setReadOnly(True)
self.ipText.setText(self.host.ip)
self.macText = QLineEdit()
self.macText.setReadOnly(True)
self.macText.setText(self.host.mac)
self.disconnectButton = QPushButton(QIcon(":/ico/connected"), "")
self.disconnectButton.setCheckable(True)
self.disconnectButton.clicked.connect(self.onDisconnect)
self.poisoningButton = QPushButton(QIcon(":/ico/notPoisoning"), "")
self.poisoningButton.setCheckable(True)
self.poisoningButton.clicked.connect(self.onPoison)
self.deleteButton = QPushButton(QIcon(":/ico/delete"), "")
self.deleteButton.clicked.connect(self.onClose)
hlayout = QHBoxLayout()
hlayout.addWidget(self.ipText)
hlayout.addWidget(self.nameText)
hlayout.addWidget(self.macText)
hlayout.addWidget(self.disconnectButton)
hlayout.addWidget(self.poisoningButton)
hlayout.addWidget(self.deleteButton)
self.setLayout(hlayout)
def stopAll(self):
"""This method stop all activity (destroy the thread and remove iptables rules)."""
self.setMitM(False)
self.setForward(False)
def isInUse(self):
"""Returns true if the host is currently used (Poisoning or Disconnected), false otherwise."""
if self.mitm:
return True
return False
def onClose(self):
"""Slot called when the user click sur the close button. Close the host and emit a close signal. If the host is in use, display a message to the user to confirm."""
closeHost = True
if self.isInUse():
buttonReply = QMessageBox.question(self, "Host in use", "The host" + str(self.host.ip) + " [" + str(self.host.mac) + "] is currently in use.\nDo you want to remove it anyway ?")
if not buttonReply == QMessageBox.Yes:
closeHost = False
if closeHost:
self.sig_closed.emit(self)
def setMitM(self, value):
"""Active or desactive the MitM attack depending on the specified value."""
if value:
self.mitm = True
if self.arpThread is None:
self.arpThread_stop = threading.Event()
self.arpThread = threading.Thread(target=PARPThread, args=(self.host, Host("192.168.1.1", "192.168.1.1", "192.168.1.1"), self.arpThread_stop))
self.arpThread.start()
else:
self.mitm = False
if self.arpThread is not None:
self.arpThread_stop.set() # note that this doesn't really kill the thread, another method should be used later...
self.arpThread = None
print("not ARP")
def setForward(self, value):
"""Active or desactive the trafic forwarding between target and router with iptable.
If the forwarding is disabled, the target is disconnected to the router."""
if value:
print("forward")
else:
print("no forward")
def __setPoisoningChecked(self, value):
if value:
self.poisoningButton.setIcon(QIcon(":/ico/poisoning"))
self.poisoningButton.setChecked(True)
else:
self.poisoningButton.setIcon(QIcon(":/ico/notPoisoning"))
self.poisoningButton.setChecked(False)
def __setDisconnectChecked(self, value):
if value:
self.disconnectButton.setIcon(QIcon(":/ico/disconnected"))
self.disconnectButton.setChecked(True)
else:
self.disconnectButton.setIcon(QIcon(":/ico/connected"))
self.disconnectButton.setChecked(False)
def onDisconnect(self, clicked):
self.setMitM(clicked)
if clicked:
self.setForward(False)
self.__setPoisoningChecked(False)
self.__setDisconnectChecked(True)
else:
self.__setPoisoningChecked(False)
self.__setDisconnectChecked(False)
def onPoison(self, clicked):
self.setMitM(clicked)
if clicked:
self.setForward(True)
self.__setPoisoningChecked(True)
self.__setDisconnectChecked(False)
else:
self.__setPoisoningChecked(False)
self.__setDisconnectChecked(False)
class HostListWidget(QWidget):
def __init__(self):
super(HostListWidget, self).__init__()
self.mainLayout = QVBoxLayout()
self.setLayout(self.mainLayout)
self.host_dic = {}
def refreshHosts(self, hosts):
"""Refrech the list of the host with a new list. Duplicate host are not refreshed."""
for host in hosts:
if host.mac in self.host_dic:
print(str(host.mac) + "is already in the list.")
# Check for changes.
return
else:
hw = HostWidget(host)
self.mainLayout.addWidget(hw)
hw.sig_closed.connect(self.onHostClosed)
self.host_dic[str(host.mac)] = hw
def onHostClosed(self, host_widget):
host_widget.deleteLater()
self.mainLayout.removeWidget(host_widget)
mac = host_widget.host.mac
if mac in self.host_dic:
del self.host_dic[mac]
else:
print("internal error: the host [" + str(mac) + "] is not in the list.")
| UTF-8 | Python | false | false | 6,193 | py | 6 | host_widgets.py | 5 | 0.613919 | 0.609398 | 0 | 171 | 35.216374 | 189 |
odairlemos/Python | 3,719,441,722,553 | 939af8cfa4e5ffe436780d2986492e132501d42e | 0ba2fc433a87904b955f3bd81c51dd57f773d0ed | /exercicio_30.py | b87f718008ff22a5558cac57e66baefaccb62067 | []
| no_license | https://github.com/odairlemos/Python | 78c5cf033c0933f412345c77da9d6e3bf548519d | 14bbb198e2a7b37cc702496930438710b183fd30 | refs/heads/master | 2022-12-19T21:28:19.554765 | 2020-09-22T23:07:19 | 2020-09-22T23:07:19 | 297,793,933 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import copy
#Variables
nome_idade = {'Eduardo': 29, 'Murilo': 27, 'Alessandra': 30, 'Carlos': 17, 'Ana': 14}
duplicando = {}
#Main Code
duplicando = copy.deepcopy(nome_idade)
print(duplicando)
| UTF-8 | Python | false | false | 197 | py | 17 | exercicio_30.py | 17 | 0.680203 | 0.629442 | 0 | 10 | 18.6 | 85 |
yhaddad/KaggleDojo | 9,689,446,250,067 | eca530cc08553bf552c74d1b94fe5ecfb4a04bdc | 094c9e35b3c8b85dc3a7fefbb560329e3e6c2d4e | /test_binner.py | fd5c0963d1853b041bf7003267ee804090783717 | []
| no_license | https://github.com/yhaddad/KaggleDojo | ab3bfea989f509a11f53b9b85406efcc364ebf81 | 053232ada0b3c6b2f5590027bf99cc88d8016b61 | refs/heads/master | 2021-01-10T23:15:28.031091 | 2017-04-19T11:44:20 | 2017-04-19T11:44:20 | 70,625,986 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import pandas as pd
np.set_printoptions(precision=4)
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML
from tools import kde
s_raw = np.random.beta(8,3, 8000)
b_raw = np.random.beta(3,3, 8000)
weight =np.concatenate((np.random.binomial(10,0.5, 8000)/100.0,np.random.binomial(10,0.5, 8000)/1.0))
y =np.concatenate((np.ones(s_raw.shape[0]),np.zeros(b_raw.shape[0])))
data = np.concatenate((s_raw,b_raw))
fig = plt.figure(figsize=(5,5))
pdf_s = kde.gaussian_kde(data[y==1])
pdf_b = kde.gaussian_kde(data[y==0])
x = np.linspace(0,1, 200)
pss = pdf_s(x)
pbb = pdf_b(x)
bb,_,_ = plt.hist(data[y==0], bins=100, range=[0,1],weights=weight[y==0],
histtype='stepfilled', alpha=0.5, normed=True)
ss,_,_ = plt.hist(data[y==1], bins=100, range=[0,1],weights=weight[y==1],
histtype='stepfilled', alpha=0.5, normed=True)
plt.plot(x, pss, label='kde-s')
plt.plot(x, pbb, label='kde-b')
plt.plot(x, kde.gaussian_kde(data[y==1], weights=weight[y==1])(x), label='kde-s')
plt.plot(x, kde.gaussian_kde(data[y==0], weights=weight[y==0])(x), label='kde-b')
plt.savefig('input_data.pdf')
plt.savefig('input_data.png')
print " ----------------------------- "
from tools import binopt as bo
ncat = 6
binner = bo.zbinner(ncat,[0,1], use_kde_density = False)
results = binner.fit(data, y, sample_weights = weight)
print results
fig = plt.figure(figsize=(5,4))
plt.hist(data[y==0], bins=100, range=[0,1],weights=weight[y==0], histtype='stepfilled', alpha=0.5,normed=True)
plt.hist(data[y==1], bins=100, range=[0,1],weights=weight[y==1], histtype='stepfilled', alpha=0.5,normed=True)
for b in np.sort(results.x):
plt.axvline(x=b, linewidth=2.0, color='red',lw=0.8)
for b in np.sort(np.linspace (0,1,ncat+1)):
plt.axvline(x=b, linewidth=2.0, color='blue',lw=0.8, ls='--')
plt.savefig('binning_results.pdf')
plt.savefig('binning_results.png')
fig = plt.figure(figsize=(10,4))
binner.optimisation_monitoring_(fig).savefig('test.pdf')
binner.parameter_scan_2d(label='parameter_scan_SA')
print " ----------------------------- "
| UTF-8 | Python | false | false | 2,134 | py | 15 | test_binner.py | 3 | 0.651359 | 0.601687 | 0 | 68 | 30.382353 | 110 |
li19960612/Human-Centric-Super-Resolution | 3,839,700,788,699 | 752627adc9e0576a24881265444e7a712803e282 | 62b540631de25db2b2646e4189388b458f58896a | /preprocessing.py | 357c949876c5635edda84fe570b07eca98e6ffa2 | []
| no_license | https://github.com/li19960612/Human-Centric-Super-Resolution | bd26f74dcfaa8324892a8c10a70f882bda2de8f5 | b18ef7c331b692beda0f41326efa3c28179454a6 | refs/heads/master | 2023-02-21T21:48:39.314085 | 2021-01-28T14:48:26 | 2021-01-28T14:48:26 | 236,694,946 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
import cfg
def openpose_processing(base_path):
'''
base_path: the image is in base_path/optimization_data
result is saved in base_path/optimization_data/COCO or /MPI
'''
openpose_path = cfg.openpose_path
os.system('cd ' + cfg.openpose_path + ' && ./build/examples/openpose/openpose.bin --image_dir ' + os.path.join(base_path, 'optimization_data') + ' --write_images ' + os.path.join(base_path, 'optimization_data/COCO/images') + ' --write_json ' + os.path.join(base_path, 'optimization_data/COCO'))
os.system('cd ' + cfg.openpose_path + ' && ./build/examples/openpose/openpose.bin --image_dir ' + os.path.join(base_path, 'optimization_data') + ' --model_pose "MPI" --write_images ' + os.path.join(base_path, 'optimization_data/MPI/images') + ' --write_json ' + os.path.join(base_path + 'optimization_data/MPI'))
def PSPNet_processing(base_path):
PSP_path = cfg.PSP_path
os.system('cd ' + PSP_path + ' && source activate PSPNet && rm ' + os.path.join(PSP_path, 'images/*') + ' && rm ' + os.path.join(PSP_path, 'results/*') + ' && cp ' + os.path.join(base_path, 'optimization_data/*.png') + ' ' + os.path.join(PSP_path, 'images') + ' && python pspnet.py && cp ' + os.path.join(PSP_path, 'results/*') + ' ' + os.path.join(base_path, optimization_data))
def hmr_processing(base_path):
hmr_path = cfg.hmr_path
os.system('cd ' + hmr_path ' && source venv/bin/activate && python demo.py ' + base_path + ' && deactivate')
| UTF-8 | Python | false | false | 1,498 | py | 10 | preprocessing.py | 7 | 0.636849 | 0.636849 | 0 | 19 | 76.421053 | 383 |
elpidabantra/Software-Development-Insights | 10,737,418,252,973 | abf9db146c79d2df4ff4be0856f4f178d422fee4 | eb62e19762f6274449bdb189d096d57ee1057365 | /counting_the_commits_by_author.py | 92e549357750693915a2b750573e75172be14c18 | []
| no_license | https://github.com/elpidabantra/Software-Development-Insights | 49db787d6e8e5da8ccdbf12ad90eb275edcee43d | 1992371f533a323f93cccb49ca617e5e368f37db | refs/heads/master | 2021-01-18T20:54:49.777784 | 2020-07-25T09:54:28 | 2020-07-25T09:54:28 | 86,999,400 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import sys
import pygit2
import re
import string
import subprocess
import os
commits_by_author = {}
with open('noa.txt') as f1:
for author in f1:
commits_by_author[author] = 0;
f1.close()
print(commits_by_author)
with open('commit_by_author.txt') as f2:
for author in f2:
commits_by_author[author] = commits_by_author[author] + 1 ;
f2.close()
f = open("number_of_commit_by_author.txt", 'w')
sys.stdout = f
print(commits_by_author)
f.close()
| UTF-8 | Python | false | false | 463 | py | 25 | counting_the_commits_by_author.py | 11 | 0.688985 | 0.669546 | 0 | 33 | 13 | 61 |
jose-correia/surf-ai-chatbot | 16,492,674,455,120 | a13d92c2372555aedf7cf199713f21c45953413e | 6d03f52546bcc28baa7ec6ac93c603d24842fbc1 | /app/handlers/intent_forecast_middleware.py | 4c4ad4f2577745e52cec7116bed78adcec1867e1 | []
| no_license | https://github.com/jose-correia/surf-ai-chatbot | 15353e9496de8778956342a1591e823748fdbf14 | 9b10aab193ea009e03144b9053de202b8a7c6372 | refs/heads/master | 2023-07-12T11:42:45.739967 | 2021-08-25T00:08:31 | 2021-08-25T00:08:31 | 201,694,578 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # SERVICES
from app.services.get_local_coord_service import GetLocalCoordService
from app.handlers.intent_handler import IntentHandler
from app.handlers.weather_forecast_handler import WeatherForecastHandler
from flask import current_app
class IntentForecastMiddleware(object):
@classmethod
def get_forecast_based_on_intent(cls, intent):
# get location
location = IntentHandler.get_intent_location(intent)
latitude, longitude = GetLocalCoordService(location).call()
# get timedelta
(start, end) = IntentHandler.get_intent_timedelta(intent)
display_name = intent.intent.display_name
parameters = []
if display_name in current_app.config.get('LOCATION_AND_PARAMS_INTENTS'):
parameters = IntentHandler.get_intent_parameters(intent)
return WeatherForecastHandler().get_location_parameters(
latitude=latitude,
longitude=longitude,
end=end,
start=start,
parameters=parameters,
)
| UTF-8 | Python | false | false | 1,041 | py | 21 | intent_forecast_middleware.py | 18 | 0.689721 | 0.689721 | 0 | 32 | 31.53125 | 81 |
Zilby/Stuy-Stuff | 14,860,586,894,905 | c721295ade8294c56ae8c56b57851adb63ac59e3 | 2b25aae9266437b657e748f3d6fea4db9e9d7f15 | /graphics/transformations/4/ivy_wong/matrix.py | 0136b6951f3366cf33c05554bced02b27efee725 | []
| no_license | https://github.com/Zilby/Stuy-Stuff | b1c3bc23abf40092a8a7a80e406e7c412bd22ae0 | 5c5e375304952f62667d3b34b36f0056c1a8e753 | refs/heads/master | 2020-05-18T03:03:48.210196 | 2018-11-15T04:50:03 | 2018-11-15T04:50:03 | 24,191,397 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import math
def make_translate( x, y, z ):
trans = []
trans.append([1,0,0,0])
trans.append([0,1,0,0])
trans.append([0,0,1,0])
trans.append([x,y,z,1])
return trans
def make_scale( x, y, z ):
scale = []
scale.append([x,0,0,0])
scale.append([0,y,0,0])
scale.append([0,0,z,0])
scale.append([0,0,0,1])
return scale
def make_rotX( theta ):
theta = math.radians(theta)
rot = []
rot.append([1,0,0,0])
rot.append([0,math.cos(theta),math.sin(theta),0])
rot.append([0,-math.sin(theta),math.cos(theta),0])
rot.append([0,0,0,1])
return rot
def make_rotY( theta ):
theta = math.radians(theta)
rot = []
rot.append([math.cos(theta),0,math.sin(theta),0])
rot.append([0,1,0,0])
rot.append([-math.sin(theta),0,math.cos(theta),0])
rot.append([0,0,0,1])
return rot
def make_rotZ( theta ):
theta = math.radians(theta)
rot = []
rot.append([math.cos(theta),math.sin(theta),0,0])
rot.append([-math.sin(theta),math.cos(theta),0,0])
rot.append([0,0,1,0])
rot.append([0,0,0,1])
return rot
def new_matrix(rows = 4, cols = 4):
m = []
for r in range( rows ):
m.append( [] )
for c in range( cols ):
m[r].append( 0 )
return m
def print_matrix( matrix ):
s = ''
for r in range( len( matrix ) ):
for c in range( len(matrix[0]) ):
s+= str(matrix[r][c]) + ' '
s+= '\n'
print s
def ident( matrix ):
ident = []
ident.append([1,0,0,0])
ident.append([0,1,0,0])
ident.append([0,0,1,0])
ident.append([0,0,0,1])
return ident
def scalar_mult( matrix, x ):
for r in range(len(matrix)):
for c in range(len(matrix[0])):
matrix[r][c] = x*matrix[r][c]
return matrix
def matrix_mult( m1, m2 ):
if len(m1) != len(m2[0]):
print "THIS IS NOT ALLOWED. ABORTING."
return
m3 = new_matrix(len(m1),len(m2[0]))
curr_row = 0
val = 0
while(curr_row < len(m1)): #loop through m1 rows
for col in range(len(m1[0])):
for curr_col in range(len(m2[0])): #loop through m2 cols
val = m1[curr_row][col]*m2[col][curr_col]
m3[curr_row][curr_col]+=val
curr_row+=1
return m3
def matrix_mult( m1, m2 ):
if len(m1[0]) != len(m2):
print "THIS IS NOT ALLOWED. ABORTING."
return
m3 = new_matrix(len(m1),len(m2[0]))
curr_row = 0
val = 0
while(curr_row < len(m1)): #loop through m1 rows
for col in range(len(m1[0])):
for curr_col in range(len(m2[0])): #loop through m2 cols
val = m1[curr_row][col]*m2[col][curr_col]
m3[curr_row][curr_col]+=val
curr_row+=1
return m3
| UTF-8 | Python | false | false | 2,775 | py | 742 | matrix.py | 601 | 0.532252 | 0.485766 | 0 | 106 | 25.179245 | 68 |
borjaf696/mtDNAProject | 670,014,921,998 | 245582de89cf2224a558bdf0ed1947521f06ec56 | 774f4ca62e48da3af8c1b1f240c8592cb65d63d2 | /utils/__init__.py | 2cc418f3aaace4cd017e49a61b00a47ff89b4977 | []
| no_license | https://github.com/borjaf696/mtDNAProject | d467a2db1e88c728754ef033fffa0fcabfcb7c34 | 2d2823489c2f7bf4c23bce8c62fa276dc55b432c | refs/heads/master | 2023-03-31T19:29:12.113211 | 2021-04-06T07:58:47 | 2021-04-06T07:58:47 | 302,108,666 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Borja :) | UTF-8 | Python | false | false | 10 | py | 133 | __init__.py | 3 | 0.5 | 0.5 | 0 | 1 | 10 | 10 |
dkapitan/pandas-gbq | 14,508,399,540,561 | 9777ebd81c08390d7ef28d39ac97f0029dba7022 | f7e78356e278b753b10c5ce66ad38cec78e9daac | /pandas_gbq/schema.py | f44a8b11290a3290d654118a66151cd25d278b48 | [
"BSD-3-Clause"
]
| permissive | https://github.com/dkapitan/pandas-gbq | 161c645228c39c030c4e4968b542c718ef849e62 | 79c592969f2fded075014e0c6aea023cad2a0118 | refs/heads/master | 2020-05-23T22:10:18.578521 | 2019-05-17T23:24:58 | 2019-05-17T23:24:58 | 186,968,316 | 0 | 0 | null | true | 2019-05-16T06:47:18 | 2019-05-16T06:47:18 | 2019-05-12T13:04:42 | 2019-05-10T17:15:40 | 640 | 0 | 0 | 0 | null | false | false | """Helper methods for BigQuery schemas"""
from numpy import uint8, int8, uint16, int16, uint32, int32
# https://www.numpy.org/devdocs/user/basics.types.html
NUMPY_INT_RANGE = {
"int8": (-128, 127),
"int16": (-32768, 32767),
"int32": (-2147483648, 2147483647),
"int64": (-9223372036854775808, 9223372036854775807),
"uint8": (0, 255),
"uint16": (0, 65535),
"uint32": (0, 4294967295),
"uint64": (0, 18446744073709551615),
}
def generate_bq_schema(dataframe, default_type="STRING"):
"""Given a passed dataframe, generate the associated Google BigQuery schema.
Arguments:
dataframe (pandas.DataFrame): D
default_type : string
The default big query type in case the type of the column
does not exist in the schema.
"""
# If you update this mapping, also update the table at
# `docs/source/writing.rst`.
type_mapping = {
"i": "INTEGER",
"b": "BOOLEAN",
"f": "FLOAT",
"O": "STRING",
"S": "STRING",
"U": "STRING",
"M": "TIMESTAMP",
}
fields = []
for column_name, dtype in dataframe.dtypes.iteritems():
fields.append(
{
"name": column_name,
"type": type_mapping.get(dtype.kind, default_type),
}
)
return {"fields": fields}
def update_schema(schema_old, schema_new):
"""
Given an old BigQuery schema, update it with a new one.
Where a field name is the same, the new will replace the old. Any
new fields not present in the old schema will be added.
Arguments:
schema_old: the old schema to update
schema_new: the new schema which will overwrite/extend the old
"""
old_fields = schema_old["fields"]
new_fields = schema_new["fields"]
output_fields = list(old_fields)
field_indices = {field["name"]: i for i, field in enumerate(output_fields)}
for field in new_fields:
name = field["name"]
if name in field_indices:
# replace old field with new field of same name
output_fields[field_indices[name]] = field
else:
# add new field
output_fields.append(field)
return {"fields": output_fields}
def select_columns_by_type(schema, bq_type):
"""
Select columns from schema with type==bq_type
"""
return [
field["name"]
for field in schema
for key, value in field.items()
if key == "type" and value == bq_type
]
def generate_sql(project_id, dataset_id, table_id, schema):
"""
Generates StandardSQL for reflection/inspection of
- MIN,MAX,COUNTIF(IS NULL) for INTEGERS
- COUNT(DISTINCT) for STRINGS
"""
BQ_TYPES = ("INTEGER", "STRING")
col_by_type = {
bq_type: select_columns_by_type(schema, bq_type)
for bq_type in BQ_TYPES
}
select_clause_integers = ", ".join(
[
"MIN({column}) AS {column}_min, \
MAX({column}) AS {column}_max, \
COUNTIF({column} is NULL) AS {column}_countifnull".format(
column=column
)
for column in col_by_type["INTEGER"]
]
)
select_clause_strings = ", ".join(
[
"COUNT(DISTINCT {column}) AS {column}_countdistinct, \
COUNT({column}) AS {column}_count, \
SAFE_DIVIDE(COUNT(DISTINCT {column}), \
COUNT({column})) AS {column}_fractiondistinct".format(
column=column
)
for column in col_by_type["STRING"]
]
)
return (
"SELECT "
+ select_clause_integers
+
# TO DO: FIX TRAILING COMMA ERROR WHEN NO STRING_CLAUSE
" , "
+ select_clause_strings
+ f" FROM `{project_id}.{dataset_id}.{table_id}`"
)
def _determine_int_type(min, max, nullcount):
"""
Determine optimal np.int type based on (min, max) value.
"""
if nullcount != 0:
# return new pandas 0.24 Int64 with since we have nulls
return "Int64"
if min >= 0:
if max <= NUMPY_INT_RANGE["uint8"][1]:
return uint8
elif max <= NUMPY_INT_RANGE["uint16"][1]:
return uint16
elif max <= NUMPY_INT_RANGE["uint32"][1]:
return uint32
else:
return "Int64"
else:
if (
min >= NUMPY_INT_RANGE["int8"][0]
and max <= NUMPY_INT_RANGE["int8"][1]
):
return int8
if (
min >= NUMPY_INT_RANGE["int16"][0]
and max <= NUMPY_INT_RANGE["int16"][1]
):
return int16
if (
min >= NUMPY_INT_RANGE["int32"][0]
and max <= NUMPY_INT_RANGE["int32"][1]
):
return int32
else:
return "Int64"
def _determine_string_type(fraction_unique, threshold=0.5):
"""
"""
return "category" if fraction_unique < threshold else "object"
| UTF-8 | Python | false | false | 5,014 | py | 1 | schema.py | 1 | 0.549462 | 0.511767 | 0 | 175 | 27.651429 | 80 |
rafaelperazzo/programacao-web | 13,821,204,769,084 | ad8065a580fa653cdcffe84fc568df176ee9f178 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/10/usersdata/2/8029/submittedfiles/testes.py | 2c1d80672892972a37095bb995d4c49d43b4bd99 | []
| no_license | https://github.com/rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
#COMECE AQUI ABAIXO
n = input('Digite o valor de n:')
maior = 1
cont = 1
numero = input('Digite um numero: ')
for i in range(1,n,1):
proximo = input('Digite um numero: ')
if proximo>numero:
cont = cont + 1
else:
cont = 1
if cont>maior:
maior = cont
numero = proximo
print maior
| UTF-8 | Python | false | false | 399 | py | 17,467 | testes.py | 16,712 | 0.596491 | 0.578947 | 0 | 19 | 19.947368 | 41 |
asa-kaya/thesis_stuff | 6,725,918,814,008 | 0c2def283adcdfc0e0c1e9612b3906ad892ec92d | c38c238147afbf72e67bd9d6c3a8959b247dd81d | /extract_features.py | 623f63d8e4d1f1d4e3188b641329db7f73f7235a | []
| no_license | https://github.com/asa-kaya/thesis_stuff | 4e83f8797ce3e51fc0af9b750825d43c5198ff06 | 4c95a5c1805d77e26357696af82020d1afc26583 | refs/heads/master | 2023-08-18T13:55:42.827969 | 2021-10-25T12:28:18 | 2021-10-25T12:28:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pandas as pd
import numpy as np
from skimage.io import imread
from matplotlib import pyplot as plt
from skimage import img_as_ubyte
from skimage.measure import regionprops
from skimage.feature import greycomatrix, greycoprops
from skimage.measure import shannon_entropy
from scipy.stats import skew
root_dir = 'preprocessed/'
img_dir = 'masked_images/'
mask_dir = 'masks/'
features = {
'area': [],
'perimeter': [],
'eccentricity': [],
'major axis': [],
'minor axis': [],
'contrast': [],
'homogeneity': [],
'energy': [],
'correlation': [],
'entropy': [],
'mean': [],
'variance': [],
'skewness': [],
'uniformity': [],
'snr': [],
}
no_of_elements = 300
for idx in range(no_of_elements):
img_loc = f'{root_dir}{img_dir}{idx}.png'
mask_loc = f'{root_dir}{mask_dir}{idx}.png'
img = imread(img_loc, as_gray=True)
mask = imread(mask_loc, as_gray=True)
# SHAPE BASED FEATURES
prop = regionprops(mask)[0]
features['area'].append( prop['area'] )
features['perimeter'].append( prop['perimeter'] )
features['eccentricity'].append( prop['eccentricity'] )
features['major axis'].append( prop['major_axis_length'] )
features['minor axis'].append( prop['minor_axis_length'] )
#GLCM TEXTURE BASED FEATURES
glcm = greycomatrix(img_as_ubyte(img), [1, 2, 3, 4], [0, np.pi/4, np.pi/2, 3*np.pi/4])
stats = greycoprops(glcm, prop='contrast')
features['contrast'].append( np.mean(stats) )
stats =greycoprops(glcm, prop='homogeneity')
features['homogeneity'].append( np.mean(stats) )
stats = greycoprops(glcm, prop='energy')
features['energy'].append( np.mean(stats) )
stats = greycoprops(glcm, prop='correlation')
features['correlation'].append( np.mean(stats) )
# ENTROPY
features['entropy'].append( shannon_entropy(img) )
# UNFIROMITY, SKEWNESS, TOTAL MEAN, VARIANCE, SNR
arr = img[img != 0] #remove zeroes (masked out pixels) from image
intensity_lvls = np.unique(arr) # Get all intensity levels
numel = intensity_lvls.size # Number of intensity levels
features['uniformity'].append( numel )
mean = np.mean(arr)
sd = np.std(arr)
features['mean'].append( mean )
features['variance'].append( np.var(arr) )
features['skewness'].append( skew(arr) )
features['snr'].append( np.where(sd == 0, 0, mean/sd) )
print(f'"{idx}.png" feature extraction done')
# save as csv
df = pd.DataFrame.from_dict(features)
metadata_df = pd.read_csv('final_dataset.csv')
df['label'] = metadata_df['finding']
df.to_csv('features.csv')
print('-- FEATURE EXTRACTION FINISHED :P --')
| UTF-8 | Python | false | false | 2,673 | py | 22 | extract_features.py | 3 | 0.640479 | 0.634493 | 0 | 96 | 26.84375 | 90 |
ShuKate/my-sandbox | 10,831,907,571,918 | 8f5cb41c0225eba52365849cff5dab5c3766bcf2 | 62ff44e09d1a5f83b3363921855fba8cad82e451 | /part2/task15.py | edaf1d9f6c3ca4234df31a591168de293e4b8f92 | []
| no_license | https://github.com/ShuKate/my-sandbox | 48e4e925c2993dff2ac4df1a4dff45349ce7e32c | c368ab7eed820a14842bc9d77c71ad831f42acf1 | refs/heads/master | 2021-03-23T09:34:54.583455 | 2020-05-13T17:51:41 | 2020-05-13T17:51:41 | 247,443,085 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #гуглила
#Напишите программу, которая считывает с консоли числа (по одному в строке) до тех пор, пока сумма введённых чисел не будет
#равна 0 и сразу после этого выводит сумму квадратов всех считанных чисел.
#Гарантируется, что в какой-то момент сумма введённых чисел окажется равной 0, после этого считывание продолжать не нужно.
#В примере мы считываем числа 1, -3, 5, -6, -10, 13; в этот момент замечаем, что сумма этих чисел равна нулю и выводим сумму их
#квадратов, не обращая внимания на то, что остались ещё не прочитанные значения.
a = int(input())
s = a
sm = 0 + abs(a ** 2)
while s != 0:
a = int(input())
s = s + a
sm = sm + abs(a) ** 2
if s == 0:
break
print(sm)
| UTF-8 | Python | false | false | 1,114 | py | 18 | task15.py | 17 | 0.69814 | 0.676681 | 0 | 16 | 42.6875 | 127 |
leeyongda/work | 13,005,160,986,111 | b29d97b936984e64b7f3816a6c6f2ecde2fa14a8 | fd6295e78a0a92445b07a27027afc9476f9e3d94 | /yphcn/test.py | f0ca61c4bc867fef535f94e2bae47e987e5bdfee | []
| no_license | https://github.com/leeyongda/work | a80bb1af8fdad40fdc059b8696597c86c42d94e6 | 7a29d8f8a60cbb9736bbbe09204df1907806795a | refs/heads/master | 2021-01-13T14:05:22.717912 | 2018-03-01T03:10:04 | 2018-03-01T03:10:04 | 76,212,381 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #coding:utf8
import requests
import re
url = 'http://www.yph.cn/shop/index.php?act=search&op=index&cate_id=1065'
res = requests.get(url).text
next_href = re.findall(ur'.*</li><li><a class="demo" href="(.*?)"><span>末页</span>',res)
print next_href[0] | UTF-8 | Python | false | false | 261 | py | 54 | test.py | 31 | 0.661479 | 0.638132 | 0 | 16 | 15.125 | 87 |
RosaPetit/Python-II | 3,573,412,825,019 | 6fde11fd0eb486bff83d3e55165a9d25f0f2c971 | 3b813f47cca26bab99f8a3f4bd56dc55ef88e3fd | /Exercise 02.py | d8f3900753fa2d86e9fde262bb0ba0c5de5ebbbc | []
| no_license | https://github.com/RosaPetit/Python-II | 479b78ef749f89510a7b793a4fad616f88d8d2df | f14f37ebc74ab41933452951421ee1faff01900c | refs/heads/main | 2023-07-04T02:21:50.023503 | 2021-07-31T00:24:25 | 2021-07-31T00:24:25 | 384,208,615 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''
Este es un comentario general que se utiliza
para programas y funciones
'''
'''Programa 1'''
#Esto es un comentario
#variable1= input() #La variable input es para interaccion del usuario
#variable2= input()
#print(variable1+variable2)
'''Programa 2 '''
# si queremos trabajar con numeros tenemos que decirle a que la funcion input que los agrega
#variable1= float( input("\n Esbriba un numero \n"))
#variable2= float( input("\n Escriba un numero \n"))
#print("La suma es:", variable1+variable2)
'''Programa 3'''
# Utilicemos el if
if (a<100)&(a>0):
print("\n a es menos que 100 y mayor que cero\n ")
elif a>100:
print("\n a es mayor que 100\n ")
elif a<-100:
print("\n a es menor que -100\n")
else:
print("a es menor que cero, pero mayor que -100")
| UTF-8 | Python | false | false | 784 | py | 12 | Exercise 02.py | 11 | 0.674745 | 0.632653 | 0 | 41 | 18.04878 | 92 |
sreekar-raparthi/binary-classififer | 16,647,293,272,714 | adeaa0834ac76b3cceb4cbaa1eab90f9e9f03c82 | 08fb7f6523be06e96b9dc94c6dcbd1adec85ba40 | /model.py | 9d97b0d4b7a470f02b4c6fb26bdc0bab2390d5a1 | []
| no_license | https://github.com/sreekar-raparthi/binary-classififer | cab25098640cc840632ca93df2734f45aa442cc9 | 7ee09ad225ce7f6320187b46ac5697cdc826fc75 | refs/heads/main | 2023-08-11T18:07:38.528306 | 2021-10-02T08:15:06 | 2021-10-02T08:15:06 | 412,721,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Activation
class Model():
def __init__(self, height=None, width=None):
self.height = height
self.width = width
def build_model(self):
img_rows, img_cols = self.height, self.width
data_format = keras.backend.image_data_format()
model = Sequential()
model.add(Conv2D(64, 3, data_format=data_format,
input_shape=(img_rows, img_cols, 1), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size = (2,2), data_format=data_format))
model.add(Dropout(.5))
model.add(Conv2D(128, 3, data_format=data_format,
padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), data_format=data_format))
model.add(Dropout(.5))
model.add(Conv2D(256, 3, data_format=data_format,
padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), data_format=data_format))
model.add(Dropout(.5))
model.add(Conv2D(512, 3, data_format=data_format,
padding='same', activation='relu'))
model.add(Flatten())
model.add(Dense(512))
model.add(Dropout(.25))
model.add(Dense(3))
model.add(Activation("softmax"))
return model
| UTF-8 | Python | false | false | 1,469 | py | 5 | model.py | 4 | 0.581348 | 0.554118 | 0 | 37 | 37.648649 | 96 |
opensciencegrid/topology | 15,504,831,986,075 | cf75f4d8d2b9eed06e4011538e69dedfdac556c6 | 4a909f0677a97b94273d5ee551078074b121d8f9 | /bin/osg-downtimes | 467ea3b83e3200889475cb43ddb435b6c55c2577 | [
"Apache-2.0"
]
| permissive | https://github.com/opensciencegrid/topology | 6e85b53bdca7e10c7dcab0793c580fa48b861617 | ccbf100a255ec7d4229b023e80d3405fb0f35b1d | refs/heads/master | 2023-08-30T23:13:00.837660 | 2023-08-30T21:15:53 | 2023-08-30T21:15:53 | 128,412,714 | 17 | 259 | Apache-2.0 | false | 2023-09-14T17:36:34 | 2018-04-06T15:28:22 | 2023-06-28T01:14:21 | 2023-09-14T16:56:16 | 15,025 | 15 | 207 | 27 | Python | false | false | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A script to print out information about OSG downtimes
"""
import os, sys
_topdir = os.path.abspath(os.path.dirname(__file__) + "/..")
if __name__ == "__main__" and __package__ is None:
sys.path.append(_topdir + "/src")
from webapp.models import GlobalData
global_data = GlobalData({"TOPOLOGY_DATA_DIR": _topdir})
print(global_data.get_topology().get_downtimes_ical(False, None).to_ical().decode("utf-8"))
| UTF-8 | Python | false | false | 467 | 1,973 | osg-downtimes | 74 | 0.655246 | 0.648822 | 0 | 18 | 24.888889 | 91 |
|
TheAlgorithms/Python | 5,901,285,113,876 | 064cd9cdd3d89f91f34911f53f1263bc55c9974b | 9ed4d46aedd4d4acadb48d610e940594b5b7b3fd | /other/least_recently_used.py | cb692bb1b1c04835e53b5ce818156e6f0eb81b5a | [
"MIT"
]
| permissive | https://github.com/TheAlgorithms/Python | 7596a0e236ed12a61f9db19a7ea68309779cc85b | 421ace81edb0d9af3a173f4ca7e66cc900078c1d | refs/heads/master | 2023-09-01T17:32:20.190949 | 2023-08-29T13:18:10 | 2023-08-29T13:18:10 | 63,476,337 | 184,217 | 48,615 | MIT | false | 2023-09-14T02:05:29 | 2016-07-16T09:44:01 | 2023-09-14T01:45:58 | 2023-09-14T02:05:25 | 13,850 | 168,531 | 41,865 | 109 | Python | false | false | from __future__ import annotations
import sys
from collections import deque
from typing import Generic, TypeVar
T = TypeVar("T")
class LRUCache(Generic[T]):
"""
Page Replacement Algorithm, Least Recently Used (LRU) Caching.
>>> lru_cache: LRUCache[str | int] = LRUCache(4)
>>> lru_cache.refer("A")
>>> lru_cache.refer(2)
>>> lru_cache.refer(3)
>>> lru_cache
LRUCache(4) => [3, 2, 'A']
>>> lru_cache.refer("A")
>>> lru_cache
LRUCache(4) => ['A', 3, 2]
>>> lru_cache.refer(4)
>>> lru_cache.refer(5)
>>> lru_cache
LRUCache(4) => [5, 4, 'A', 3]
"""
dq_store: deque[T] # Cache store of keys
key_reference: set[T] # References of the keys in cache
_MAX_CAPACITY: int = 10 # Maximum capacity of cache
def __init__(self, n: int) -> None:
"""Creates an empty store and map for the keys.
The LRUCache is set the size n.
"""
self.dq_store = deque()
self.key_reference = set()
if not n:
LRUCache._MAX_CAPACITY = sys.maxsize
elif n < 0:
raise ValueError("n should be an integer greater than 0.")
else:
LRUCache._MAX_CAPACITY = n
def refer(self, x: T) -> None:
"""
Looks for a page in the cache store and adds reference to the set.
Remove the least recently used key if the store is full.
Update store to reflect recent access.
"""
if x not in self.key_reference:
if len(self.dq_store) == LRUCache._MAX_CAPACITY:
last_element = self.dq_store.pop()
self.key_reference.remove(last_element)
else:
self.dq_store.remove(x)
self.dq_store.appendleft(x)
self.key_reference.add(x)
def display(self) -> None:
"""
Prints all the elements in the store.
"""
for k in self.dq_store:
print(k)
def __repr__(self) -> str:
return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}"
if __name__ == "__main__":
import doctest
doctest.testmod()
lru_cache: LRUCache[str | int] = LRUCache(4)
lru_cache.refer("A")
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer("A")
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
| UTF-8 | Python | false | false | 2,417 | py | 1,041 | least_recently_used.py | 970 | 0.55813 | 0.546545 | 0 | 92 | 25.271739 | 74 |
av8ramit/caprende | 17,712,445,149,075 | 6d9f813ffea0a09264a9a0f3dbdbd8163d868103 | 5abe2d8bac6e0cbfbaab25024f99fce48bbecd92 | /src/comments/tests.py | dbf56568794c51429959008416469733530ead81 | []
| no_license | https://github.com/av8ramit/caprende | 086cad46d59ff54cacdc7eee2ec084c1528b8947 | cd4ff5222e437fca055dce4790c8c349699d3f5f | refs/heads/master | 2021-03-27T12:30:25.338673 | 2017-02-21T04:34:31 | 2017-02-21T04:34:31 | 58,184,420 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''Tests page for the comments Caprende module.'''
from django.test import TestCase
from course.models import Course, CourseSection
from categories.models import Category, SubCategory
from questions.models import Question
from users.models import MyUser
from .models import Comment
# Create your tests here.
class CommentTests(TestCase):
'''Tests related to the actual Comment functionality.'''
def setUp(self):
'''Set up the test and category infrastructure.'''
#Course Instantiation
self.course = Course(
name="testing course",
slug="testing-course"
)
self.course.save()
#Course Section Instantiation
self.coursesection = CourseSection(
name="Section 1",
course=self.course
)
self.coursesection.save()
#Category Instantiation
self.category = Category(
name="Category 1 for testing course",
slug="cat-1-testing-course",
section=self.coursesection,
)
self.category.save()
#SubCategory Instantiation
self.subcategory = SubCategory(
name="SubCategory 1 for testing course",
slug="subcategory-1-testing-course",
category=self.category,
)
self.subcategory.save()
#User creation
self.user = MyUser.objects.create_test_user(
username="test",
email="test@yahoo.com",
password="password1!",
)
#Question creation
self.question = Question(
course=self.course,
section=self.coursesection,
category=self.category,
subcategory=self.subcategory,
question_text="Here is an example question.",
option_A="Here is option A.",
option_B="Here is option B.",
answer_letter="A",
answer_explanation="Here is an example explanation.",
index=1,
)
self.question.save()
def tearDown(self):
'''Tear down the infrastructure.'''
pass
def test_comment_creation(self):
'''Tests creating a question.'''
Comment.objects.create_comment(
user=self.user,
text="Testing Comment Creation",
question=self.question,
)
def test_reply_creation(self):
'''Tests creating a reply.'''
new_comment = Comment.objects.create_comment(
user=self.user,
text="Testing Comment Creation",
question=self.question,
)
Comment.objects.create_comment(
user=self.user,
parent=new_comment,
text="Testing Reply Creation",
question=self.question,
)
def test_comment_misc(self):
'''Testing the Comment model methods and misc attributes.'''
new_comment = Comment.objects.create_comment(
user=self.user,
text="Testing Comment Creation",
question=self.question,
)
new_reply = Comment.objects.create_comment(
user=self.user,
parent=new_comment,
text="Testing Reply Creation",
question=self.question,
)
#Test is_child
assert not new_comment.is_child()
assert new_reply.is_child()
#Test get_children
assert len(new_comment.get_children()) == 1
assert new_comment.get_children()[0] == new_reply
assert new_reply.get_children() is None
| UTF-8 | Python | false | false | 3,557 | py | 101 | tests.py | 77 | 0.579702 | 0.577172 | 0 | 124 | 27.685484 | 68 |
MaxWellPlanktos/Audio-Stream-Bot | 4,526,895,542,346 | 4194f7d54a63df308850dd0ef79274a928d7588b | 8df7b832dc21c398041d781ceacc9fc315cd5724 | /discord-audio-source-code/gui.py | 7f37af4c24eecff3a621b11234620e7dfb46f6b0 | [
"MIT"
]
| permissive | https://github.com/MaxWellPlanktos/Audio-Stream-Bot | b0b9df30f5db38e8d642055f253ce95441cb05c7 | 2ad1eccb058e96f7003815c61c5b52d17eb0279a | refs/heads/main | 2023-06-19T20:08:27.608995 | 2021-07-15T09:14:03 | 2021-07-15T09:14:03 | 383,408,951 | 1 | 2 | MIT | false | 2021-07-15T09:14:04 | 2021-07-06T09:13:16 | 2021-07-09T13:37:37 | 2021-07-15T09:14:03 | 238 | 1 | 2 | 0 | Python | false | false | import os
import sys
import platform
if platform.system() == 'Linux':
import pulsectl
else:
import sound
import asyncio
import logging
import discord
from PyQt5.QtSvg import QSvgWidget
from PyQt5.QtGui import QFontDatabase, QFontMetrics, QIcon
from PyQt5.QtCore import Qt, QCoreApplication, QEventLoop, QDir, pyqtSignal
from PyQt5.QtWidgets import (
QMainWindow,
QPushButton,
QWidget,
QFrame,
QGridLayout,
QComboBox,
QLabel,
QHBoxLayout,
QStyledItemDelegate,
QListView
)
if getattr(sys, "frozen", False):
bundle_dir = sys._MEIPASS
else:
bundle_dir = os.path.dirname(os.path.abspath(__file__))
class Dropdown(QComboBox):
changed = pyqtSignal(object, object)
def __init__(self):
super(Dropdown, self).__init__()
self.setItemDelegate(QStyledItemDelegate())
self.setPlaceholderText("None")
self.setView(QListView())
self.deselected = None
self.currentIndexChanged.connect(self.changed_signal)
def changed_signal(self, selected):
self.changed.emit(self.deselected, selected)
self.deselected = selected
def setRowHidden(self, idx, hidden):
self.view().setRowHidden(idx, hidden)
class SVGButton(QPushButton):
def __init__(self, text=None):
super(SVGButton, self).__init__(text)
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.svg = QSvgWidget("./assets/loading.svg", self)
self.svg.setVisible(False)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.addWidget(self.svg)
def setEnabled(self, enabled):
super().setEnabled(enabled)
self.svg.setVisible(not enabled)
class Connection:
def __init__(self, layer, parent):
if platform.system() != 'Linux':
self.stream = sound.PCMStream()
self.parent = parent
self.voice = None
# dropdowns
self.devices = Dropdown()
self.servers = Dropdown()
self.channels = Dropdown()
if platform.system() == 'Linux':
for device in parent.devices:
self.devices.addItem(device.description, device.name)
else:
for device, idx in parent.devices.items():
self.devices.addItem(device + " ", idx)
# mute
self.mute = SVGButton("Mute")
self.mute.setObjectName("mute")
# add widgets
parent.layout.addWidget(self.devices, layer, 0)
parent.layout.addWidget(self.servers, layer, 1)
parent.layout.addWidget(self.channels, layer, 2)
parent.layout.addWidget(self.mute, layer, 3)
# events
self.devices.changed.connect(self.change_device)
self.servers.changed.connect(
lambda deselected, selected: asyncio.ensure_future(
self.change_server(deselected, selected)
)
)
self.channels.changed.connect(
lambda: asyncio.ensure_future(self.change_channel())
)
self.mute.clicked.connect(self.toggle_mute)
@staticmethod
def resize_combobox(combobox):
font = combobox.property("font")
metrics = QFontMetrics(font)
min_width = 0
for i in range(combobox.count()):
size = metrics.horizontalAdvance(combobox.itemText(i))
if size > min_width:
min_width = size
combobox.setMinimumWidth(min_width + 30)
def setEnabled(self, enabled):
self.devices.setEnabled(enabled)
self.servers.setEnabled(enabled)
self.channels.setEnabled(enabled)
self.mute.setEnabled(enabled)
self.mute.setText("Mute" if enabled else "")
def set_servers(self, guilds):
for guild in guilds:
self.servers.addItem(guild.name, guild)
def change_device(self):
try:
selection = self.devices.currentData()
self.mute.setText("Mute")
if self.voice is not None:
self.voice.stop()
if platform.system() != 'Linux':
self.stream.change_device(selection)
if self.voice.is_connected():
if platform.system() == 'Linux':
self.voice.play(discord.FFmpegPCMAudio(selection, before_options='-f pulse'))
else:
self.voice.play(discord.PCMAudio(self.stream))
else:
if platform.system() != 'Linux':
self.stream.change_device(selection)
except Exception:
logging.exception("Error on change_device")
async def change_server(self, deselcted, selected):
try:
selection = self.servers.itemData(selected)
self.parent.exclude(deselcted, selected)
self.channels.clear()
self.channels.addItem("None", None)
for channel in selection.channels:
if isinstance(channel, discord.VoiceChannel):
self.channels.addItem(channel.name, channel)
Connection.resize_combobox(self.channels)
except Exception:
logging.exception("Error on change_server")
async def change_channel(self):
try:
selection = self.channels.currentData()
self.mute.setText("Mute")
self.setEnabled(False)
if selection is not None:
not_connected = (
self.voice is None
or self.voice is not None
and not self.voice.is_connected()
)
if not_connected:
self.voice = await selection.connect(timeout=10)
else:
await self.voice.move_to(selection)
not_playing = (
self.devices.currentData() is not None
and not self.voice.is_playing()
)
if not_playing:
if platform.system() == 'Linux':
self.voice.play(discord.FFmpegPCMAudio(self.devices.currentData(), before_options='-f pulse'))
else:
self.voice.play(discord.PCMAudio(self.stream))
else:
if self.voice is not None:
await self.voice.disconnect()
except Exception:
logging.exception("Error on change_channel")
finally:
self.setEnabled(True)
def toggle_mute(self):
try:
if self.voice is not None:
if self.voice.is_playing():
self.voice.pause()
self.mute.setText("Resume")
else:
self.voice.resume()
self.mute.setText("Mute")
except Exception:
logging.exception("Error on toggle_mute")
class TitleBar(QFrame):
def __init__(self, parent):
# title bar
super(TitleBar, self).__init__()
self.setObjectName("titlebar")
# discord
self.parent = parent
self.bot = parent.bot
# layout
layout = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
# window title
title = QLabel("Discord Audio Pipe")
# minimize
minimize_button = QPushButton("—")
minimize_button.setObjectName("minimize")
layout.addWidget(minimize_button)
# close
close_button = QPushButton("✕")
close_button.setObjectName("close")
layout.addWidget(close_button)
# add widgets
layout.addWidget(title)
layout.addStretch()
layout.addWidget(minimize_button)
layout.addWidget(close_button)
# events
minimize_button.clicked.connect(self.minimize)
close_button.clicked.connect(lambda: asyncio.ensure_future(self.close()))
async def close(self):
# workaround for logout bug
for voice in self.bot.voice_clients:
try:
await voice.disconnect()
except Exception:
pass
self.bot._closed = True
await self.bot.ws.close()
self.parent.close()
def minimize(self):
self.parent.showMinimized()
class GUI(QMainWindow):
def __init__(self, app, bot):
# app
super(GUI, self).__init__()
QDir.setCurrent(bundle_dir)
self.app = app
# window info
self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
window_icon = QIcon("./assets/favicon.ico")
self.setWindowTitle("Discord Audio Pipe")
self.app.setWindowIcon(window_icon)
self.position = None
# discord
self.bot = bot
# layout
central = QWidget()
self.layout = QGridLayout()
central.setLayout(self.layout)
# labels
self.info = QLabel("Connecting...")
device_lb = QLabel("Devices")
device_lb.setObjectName("label")
server_lb = QLabel("Servers ")
server_lb.setObjectName("label")
channel_lb = QLabel("Channels ")
channel_lb.setObjectName("label")
# connections
if platform.system() == 'Linux':
self.devices = pulsectl.Pulse('localhost').source_list()
else:
self.devices = sound.query_devices()
self.connections = [Connection(2, self)]
self.connected_servers = set()
# new connections
self.connection_btn = QPushButton("+", self)
self.connection_btn.setObjectName("connection_btn")
# add widgets
self.layout.addWidget(self.info, 0, 0, 1, 3)
self.layout.addWidget(device_lb, 1, 0)
self.layout.addWidget(server_lb, 1, 1)
self.layout.addWidget(channel_lb, 1, 2)
self.layout.addWidget(self.connection_btn, 2, 4)
# events
self.connection_btn.clicked.connect(self.add_connection)
# build window
titlebar = TitleBar(self)
self.setMenuWidget(titlebar)
self.setCentralWidget(central)
self.setEnabled(False)
# load styles
QFontDatabase.addApplicationFont("./assets/Roboto-Black.ttf")
with open("./assets/style.qss", "r") as qss:
self.app.setStyleSheet(qss.read())
# show window
self.show()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.position = event.pos()
event.accept()
def mouseMoveEvent(self, event):
if self.position is not None and event.buttons() == Qt.LeftButton:
self.move(self.pos() + event.pos() - self.position)
event.accept()
def mouseReleaseEvent(self, event):
self.position = None
event.accept()
def setEnabled(self, enabled):
self.connection_btn.setEnabled(enabled)
for connection in self.connections:
connection.setEnabled(enabled)
def add_connection(self):
layer = len(self.connections) + 2
new_connection = Connection(layer, self)
new_connection.set_servers(self.bot.guilds)
for idx in range(new_connection.servers.count()):
if idx in self.connected_servers:
new_connection.servers.setRowHidden(idx, True)
self.layout.removeWidget(self.connection_btn)
self.layout.addWidget(self.connection_btn, layer, 4)
self.connections.append(new_connection)
def exclude(self, deselected, selected):
self.connected_servers.add(selected)
if deselected is not None:
self.connected_servers.remove(deselected)
for connection in self.connections:
connection.servers.setRowHidden(selected, True)
if deselected is not None:
connection.servers.setRowHidden(deselected, False)
async def run_Qt(self, interval=0.01):
while True:
QCoreApplication.processEvents(QEventLoop.AllEvents, interval * 1000)
await asyncio.sleep(interval)
async def ready(self):
await self.bot.wait_until_ready()
self.info.setText(f"Logged in as: {self.bot.user.name}")
self.connections[0].set_servers(self.bot.guilds)
Connection.resize_combobox(self.connections[0].servers)
self.setEnabled(True)
| UTF-8 | Python | false | false | 12,442 | py | 10 | gui.py | 3 | 0.585397 | 0.581779 | 0 | 409 | 29.405868 | 118 |
MrizalMuhaimin/Search-Engine-Vector-Space-Model | 5,772,436,062,991 | 347b62fe346cf6c0692357bb75541d3b3eaba028 | 24bf326133e1c0fc81b4b73b9997b085b1e0f925 | /src/app/saveDatatoSql.py | 600efcd489b5267d9bd0bdc40f31460d7ac2572d | []
| no_license | https://github.com/MrizalMuhaimin/Search-Engine-Vector-Space-Model | 1f12dd4e8a2e58b8e5c545146896d5cd6ad10c79 | 78f9cda0f64a7d41b41101f09d9d23a824e5df80 | refs/heads/main | 2023-01-28T07:38:54.014961 | 2020-12-05T02:09:57 | 2020-12-05T02:09:57 | 318,195,009 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import requests
import bs4
import sqlite3
import re
from Sastrawi.Stemmer.StemmerFactory import StemmerFactory
def urltoSQL(List):
conn = sqlite3.connect('app/data_sql/fileBaseGoogle.sqlite')
cur = conn.cursor()
# Do some setup
cur.executescript('''
DROP TABLE IF EXISTS UrlData;
CREATE TABLE UrlData (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
link TEXT UNIQUE,
judul TEXT,
kal TEXT,
sastra TEXT,
nkar INTEGER,
nkata INTEGER
)
''')
#scaping link dan data mendapatkan artikel
for url in List:
#url di sql
#print ("Alamat:",url)
ttl = url.split('/')
for i in range(len(ttl)-1,1,-1):
if '-' in ttl[i] :
break
if '-' in ttl[i]:
ttl = ttl[i]
else:continue
name_file = re.sub(r'[-]','_',ttl)
ttl = re.sub(r'[-]',' ',ttl)
ttl = ttl.title() #judul di sql
#print(ttl)
try:
URLres = requests.get(url)
URLres.raise_for_status()
URLsoup = bs4.BeautifulSoup(URLres.text, "html.parser")
URLText = URLsoup('p')
URLspan = URLsoup('span')
URLres.close()
#print(URLText)
text=[]
for word in URLText:
for ctk in word.contents:
text.append(ctk)
#pembersihan text dengan '< .....>''
text_clean = ''
for word in text:
try:
dokumen = re.sub(r'^<\S+ \S+>','',word)
if dokumen == ' ' or dokumen ==' .' : continue
#print(dokumen)
text_clean += dokumen +' '
except:
continue
n_karakter = len(text_clean) # banyakny akerakter di sql
if n_karakter == 0: continue #menhapus link yang kaliatny
n_Kata = len(text_clean.split(' '))
kal = text_clean
factory = StemmerFactory()
stemmer = factory.create_stemmer()
output = stemmer.stem(text_clean)
#print(output)
n_out = len(output.split(' '))
################################### Pengulanganketikan <P> tidak bisa dibaca diganri dengan <span>
if(n_out < 10):
text=[]
for word in URLspan:
for ctk in word.contents:
text.append(ctk)
#pembersihan text dengan '< .....>''
text_clean = ''
for word in text:
try:
dokumen = re.sub(r'^<\S+ \S+>','',word)
if dokumen == ' ' or dokumen ==' .' : continue
#print(dokumen)
text_clean += dokumen +' '
except:
continue
n_karakter = len(text_clean) # banyakny akerakter di sql
if n_karakter == 0: continue #menhapus link yang kaliatny
n_Kata = len(text_clean.split(' '))
kal = text_clean
factory = StemmerFactory()
stemmer = factory.create_stemmer()
output = stemmer.stem(text_clean)
'''textTosave= output.split(' ')'''
cur.execute('''INSERT OR IGNORE INTO UrlData (link,judul,kal,sastra,nkar,nkata)
VALUES (?,?,?,?,?,?)''', (url,ttl,kal, output,n_karakter,n_Kata, ) )
except:
continue
conn.commit()
| UTF-8 | Python | false | false | 2,842 | py | 17 | saveDatatoSql.py | 8 | 0.592189 | 0.588318 | 0 | 132 | 20.515152 | 101 |
eggman19/tantrumrepo | 11,003,706,230,058 | 7ccb0259c6359e5c3f4d30a4041e768c67d3e827 | 838971156f241090ee965d2ff4b0a933889b9d28 | /plugin.program.tantrumtv/resources/libs/notify.py | bb388ea2f3b938a9dc69dffa4c6bfcca8f0488b5 | [
"Beerware"
]
| permissive | https://github.com/eggman19/tantrumrepo | 2e147a02b082dbc2976fe81046d9b61a34bfe3ed | 1451c481254d3fedec9f430139d18db7312a9b1a | refs/heads/master | 2020-03-27T16:42:01.189127 | 2018-08-06T15:47:46 | 2018-08-06T15:47:46 | 146,800,742 | 2 | 0 | null | true | 2018-08-30T20:04:34 | 2018-08-30T20:04:33 | 2018-08-17T18:16:32 | 2018-08-06T15:47:55 | 692,089 | 0 | 0 | 0 | null | false | null | #######################################################################
#Import Modules Section
import xbmc, xbmcaddon, xbmcgui, xbmcplugin, xbmcvfs
import os
import sys
import glob
import shutil
import urllib2,urllib
import re
import glo_var
import base_info
import time
from datetime import date, datetime, timedelta
#######################################################################
#######################################################################
#Global Variables
#Do Not Edit These Variables or any others in this wizard!
ADDONS = glo_var.ADDONS
ADDON_ID = glo_var.ADDON_ID
ADDONTITLE = glo_var.ADDONTITLE
ART = glo_var.ART
FANART = glo_var.FANART
BACKGROUND = glo_var.BACKGROUND if not glo_var.BACKGROUND == '' or not base_info.workingURL(glo_var.BACKGROUND) else FANART
cr = glo_var.COLOR
cr2 = glo_var.COLOR2
FONTHEADER = glo_var.FONTHEADER if not glo_var.FONTHEADER == '' else "Font16"
FONTSETTINGS = glo_var.FONTSETTINGS if not glo_var.FONTSETTINGS == '' else "Font14"
HEADERIMAGE = glo_var.HEADERIMAGE
HEADERMESSAGE = glo_var.HEADERMESSAGE
HEADERTYPE = glo_var.HEADERTYPE if glo_var.HEADERTYPE == 'Image' else 'Text'
HOMEPATH = glo_var.HOMEPATH
NOTIFY = glo_var.ENABLE
NOTEID = base_info.getS('noteid')
NOTEDISMISS = base_info.getS('notedismiss')
THEME = glo_var.THEME1
TODAY = date.today()
TOMORROW = TODAY + timedelta(days=1)
THREEDAYS = TODAY + timedelta(days=3)
UPDATECHECK = glo_var.UPDATECHECK if str(glo_var.UPDATECHECK).isdigit() else 1
NEXTCHECK = TODAY + timedelta(days=UPDATECHECK)
#######################################################################
#######################################################################
#NOTIFICATIONS
ACTION_PREVIOUS_MENU = 10 ## ESC action
ACTION_NAV_BACK = 92 ## Backspace action
ACTION_MOVE_LEFT = 1 ## Left arrow key
ACTION_MOVE_RIGHT = 2 ## Right arrow key
ACTION_MOVE_UP = 3 ## Up arrow key
ACTION_MOVE_DOWN = 4 ## Down arrow key
ACTION_MOUSE_WHEEL_UP = 104 ## Mouse wheel up
ACTION_MOUSE_WHEEL_DOWN = 105 ## Mouse wheel down
ACTION_MOVE_MOUSE = 107 ## Down arrow key
ACTION_SELECT_ITEM = 7 ## Number Pad Enter
ACTION_BACKSPACE = 110 ## ?
ACTION_MOUSE_LEFT_CLICK = 100
ACTION_MOUSE_LONG_CLICK = 108
#######################################################################
#######################################################################
def notification(msg='', resize=False, L=0 ,T=0 ,W=1280 ,H=720 , TxtColor='0xFF0000', Font=FONTSETTINGS, BorderWidth=15):
class MyWindow(xbmcgui.WindowDialog):
scr={};
def __init__(self,msg='',L=0,T=0,W=1280,H=720,TxtColor='0xFF0000',Font='font14',BorderWidth=10):
image_path = os.path.join(ART, 'ContentPanel.png')
self.border = xbmcgui.ControlImage(L,T,W,H, image_path)
self.addControl(self.border);
self.BG=xbmcgui.ControlImage(L+BorderWidth,T+BorderWidth,W-(BorderWidth*2),H-(BorderWidth*2), BACKGROUND, aspectRatio=0, colorDiffuse='0x9FFFFFFF')
self.addControl(self.BG)
if HEADERTYPE == 'Image':
iLogoW=144; iLogoH=68
self.iLogo=xbmcgui.ControlImage((L+(W/2))-(iLogoW/2),T+10,iLogoW,iLogoH,HEADERIMAGE,aspectRatio=0)
self.addControl(self.iLogo)
else:
title = HEADERMESSAGE
times = int(float(FONTHEADER[-2:]))
temp = title.replace('[', '<').replace(']', '>')
temp = re.sub('<[^<]+?>', '', temp)
title_width = len(str(temp))*(times - 1)
title = THEME % title
self.title=xbmcgui.ControlTextBox(L+(W-title_width)/2,T+BorderWidth,title_width,30,font=FONTHEADER,textColor='0xFF1E90FF')
self.addControl(self.title)
self.title.setText(title)
msg = THEME % msg
self.TxtMessage=xbmcgui.ControlTextBox(L+BorderWidth+10,T+30+BorderWidth,W-(BorderWidth*2)-20,H-(BorderWidth*2)-75,font=Font,textColor=TxtColor)
self.addControl(self.TxtMessage)
self.TxtMessage.setText(msg)
focus=os.path.join(ART, 'button-focus_lightblue.png'); nofocus=os.path.join(ART, 'button-focus_grey.png')
w1 = int((W-(BorderWidth*5))/3); h1 = 35
t = int(T+H-h1-(BorderWidth*1.5))
space = int(L+(BorderWidth*1.5))
dismiss = int(space+w1+BorderWidth)
later = int(dismiss+w1+BorderWidth)
self.buttonDismiss=xbmcgui.ControlButton(dismiss,t,w1,h1,"Dismiss",textColor="0xFF000000",focusedColor="0xFF000000",alignment=2,focusTexture=focus,noFocusTexture=nofocus)
self.buttonRemindMe=xbmcgui.ControlButton(later,t,w1,h1,"Remind Me Later",textColor="0xFF000000",focusedColor="0xFF000000",alignment=2,focusTexture=focus,noFocusTexture=nofocus)
self.addControl(self.buttonDismiss); self.addControl(self.buttonRemindMe)
self.buttonRemindMe.controlLeft(self.buttonDismiss); self.buttonRemindMe.controlRight(self.buttonDismiss)
self.buttonDismiss.controlLeft(self.buttonRemindMe); self.buttonDismiss.controlRight(self.buttonRemindMe)
self.setFocus(self.buttonRemindMe);
def doRemindMeLater(self):
try:
base_info.setS("notedismiss","false")
base_info.loga("[Notification] NotifyID %s Remind Me Later" % base_info.getS('noteid'))
except: pass
self.CloseWindow()
def doDismiss(self):
try:
base_info.setS("notedismiss","true")
base_info.log("[Notification] NotifyID %s Dismissed" % base_info.getS('noteid'))
except: pass
self.CloseWindow()
def onAction(self,action):
try: F=self.getFocus()
except: F=False
if action == ACTION_PREVIOUS_MENU: self.doRemindMeLater()
elif action == ACTION_NAV_BACK: self.doRemindMeLater()
def onControl(self,control):
if control==self.buttonRemindMe: self.doRemindMeLater()
elif control== self.buttonDismiss: self.doDismiss()
else:
try: self.setFocus(self.buttonRemindMe)
except: pass
def CloseWindow(self): self.close()
if resize==False: maxW=1280; maxH=720; W=int(maxW/1.5); H=int(maxH/1.5); L=int((maxW-W)/2); T=int((maxH-H)/2);
TempWindow=MyWindow(msg=msg,L=L,T=T,W=W,H=H,TxtColor=TxtColor,Font=Font,BorderWidth=BorderWidth)
TempWindow.doModal()
del TempWindow
def firstRun(msg='', TxtColor='0xFFFFFFFF', Font='font12', BorderWidth=10):
class MyWindow(xbmcgui.WindowDialog):
scr={};
def __init__(self,L=0,T=0,W=1280,H=720,TxtColor='0xFFFFFFFF',Font='font12',BorderWidth=10):
image_path = os.path.join(ART, 'ContentPanel.png')
self.border = xbmcgui.ControlImage(L,T,W,H, image_path)
self.addControl(self.border);
self.BG=xbmcgui.ControlImage(L+BorderWidth,T+BorderWidth,W-(BorderWidth*2),H-(BorderWidth*2), FANART, aspectRatio=0, colorDiffuse='0x9FFFFFFF')
self.addControl(self.BG)
title = cr+ADDONTITLE+cr2
times = int(float(Font[-2:]))
temp = title.replace('[', '<').replace(']', '>')
temp = re.sub('<[^<]+?>', '', temp)
title_width = len(str(temp))*(times - 1)
title = THEME % title
self.title=xbmcgui.ControlTextBox(L+(W-title_width)/2,T+BorderWidth,title_width,30,font='font14',textColor='0xFF1E90FF')
self.addControl(self.title)
self.title.setText(title)
msg = "Currently no build installed from %s.\n\nSelect 'Build Menu' to install a Build or 'Ignore' to never see this message again.\n\nThank you for choosing %s." % (cr+ADDONTITLE+cr2, cr+ADDONTITLE+cr2)
msg = THEME % msg
self.TxtMessage=xbmcgui.ControlTextBox(L+(BorderWidth*2),T+30+BorderWidth,W-(BorderWidth*4),H-(BorderWidth*2)-75,font=Font,textColor=TxtColor)
self.addControl(self.TxtMessage)
self.TxtMessage.setText(msg)
focus=os.path.join(ART, 'button-focus_lightblue.png'); nofocus=os.path.join(ART, 'button-focus_grey.png')
w1 = int((W-(BorderWidth*5))/3); h1 = 35
t = int(T+H-h1-(BorderWidth*1.5))
save = int(L+(BorderWidth*1.5))
buildmenu = int(save+w1+BorderWidth)
ignore = int(buildmenu+w1+BorderWidth)
self.buttonSAVEMENU=xbmcgui.ControlButton(save,t,w1,h1,"Save Data Menu",textColor="0xFF000000",focusedColor="0xFF000000",alignment=2,focusTexture=focus,noFocusTexture=nofocus)
self.buttonBUILDMENU=xbmcgui.ControlButton(buildmenu,t,w1,h1,"Build Menu",textColor="0xFF000000",focusedColor="0xFF000000",alignment=2,focusTexture=focus,noFocusTexture=nofocus)
self.buttonIGNORE=xbmcgui.ControlButton(ignore,t,w1,h1,"Ignore",textColor="0xFF000000",focusedColor="0xFF000000",alignment=2,focusTexture=focus,noFocusTexture=nofocus)
self.addControl(self.buttonSAVEMENU); self.addControl(self.buttonBUILDMENU); self.addControl(self.buttonIGNORE)
self.buttonIGNORE.controlLeft(self.buttonBUILDMENU); self.buttonIGNORE.controlRight(self.buttonSAVEMENU)
self.buttonBUILDMENU.controlLeft(self.buttonSAVEMENU); self.buttonBUILDMENU.controlRight(self.buttonIGNORE)
self.buttonSAVEMENU.controlLeft(self.buttonIGNORE); self.buttonSAVEMENU.controlRight(self.buttonBUILDMENU)
self.setFocus(self.buttonIGNORE)
def doSaveMenu(self):
base_info.loga("[Check Updates] [User Selected: Open Save Data Menu] [Next Check: %s]" % str(NEXTCHECK))
base_info.setS('lastbuildcheck', str(NEXTCHECK))
self.CloseWindow()
url = 'plugin://%s/?mode=savedata' % ADDON_ID
xbmc.executebuiltin('ActivateWindow(10025, "%s", return)' % url)
def doBuildMenu(self):
base_info.loga("[Check Updates] [User Selected: Open Build Menu] [Next Check: %s]" % str(NEXTCHECK))
base_info.setS('lastbuildcheck', str(NEXTCHECK))
self.CloseWindow()
url = 'plugin://%s/?mode=builds' % ADDON_ID
xbmc.executebuiltin('ActivateWindow(10025, "%s", return)' % url)
def doIgnore(self):
base_info.loga("[First Run] [User Selected: Ignore Build Menu] [Next Check: %s]" % str(NEXTCHECK))
base_info.setS('lastbuildcheck', str(NEXTCHECK))
self.CloseWindow()
def onAction(self,action):
try: F=self.getFocus()
except: F=False
if action == ACTION_PREVIOUS_MENU: self.doIgnore()
elif action == ACTION_NAV_BACK: self.doIgnore()
elif action == ACTION_MOVE_LEFT and not F: self.setFocus(self.buttonBUILDMENU)
elif action == ACTION_MOVE_RIGHT and not F: self.setFocus(self.buttonIGNORE)
def onControl(self,control):
if control==self.buttonIGNORE: self.doIgnore()
elif control==self.buttonBUILDMENU: self.doBuildMenu()
elif control==self.buttonSAVEMENU: self.doSaveMenu()
else:
try: self.setFocus(self.buttonIGNORE);
except: pass
def CloseWindow(self): self.close()
maxW=1280; maxH=720; W=int(700); H=int(300); L=int((maxW-W)/2); T=int((maxH-H)/2);
TempWindow=MyWindow(L=L,T=T,W=W,H=H,TxtColor=TxtColor,Font=Font,BorderWidth=BorderWidth);
TempWindow.doModal()
del TempWindow | UTF-8 | Python | false | false | 10,537 | py | 163 | notify.py | 39 | 0.678087 | 0.649616 | 0 | 201 | 51.427861 | 208 |
Biksbois/BiksCause | 1,735,166,800,887 | dd58e58954717f362fe7b1f4161c14ba47644bbb | f482fa4419f1b1bb31a884c5c79cdfe8df927b8e | /BiksPrepare/unit_tests/test_duration.py | 718b36171d97caf1ad8ad5e42655dfda6b6dad82 | []
| no_license | https://github.com/Biksbois/BiksCause | 8db99064d541b4d851698c73cedbfed1502eeeb2 | aedddebaa6b6a461e1a314919fc3c3c08c48c360 | refs/heads/main | 2023-05-06T10:02:41.505661 | 2021-05-27T07:19:26 | 2021-05-27T07:19:26 | 355,140,282 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import sys, os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
import unittest
import datetime
from duration_method import *
def init_data():
colum = 'sky is clear'
csv_path = 'BiksPrepare/unit_tests/test_csv'
c_start = 'start'
c_end = 'end'
cluster_name = 'cluster'
return colum, csv_path, c_start, c_end, cluster_name
class test_duration(unittest.TestCase):
def test_extract_start_i5(self):
colum, csv_path, c_start, c_end, cluster_name = init_data()
i = 5
j_start = 0
expected_start = 5
actual_start, _, _, _= extract_start_end(colum, csv_path, i, c_start, c_end, cluster_name, False, j_start)
self.assertEqual(expected_start, actual_start)
def test_extract_end_i5(self):
colum, csv_path, c_start, c_end, cluster_name = init_data()
i = 5
j_start = 0
expected_end = 8
_, actual_end, _, _ = extract_start_end(colum, csv_path, i, c_start, c_end, cluster_name, False, j_start)
self.assertEqual(expected_end, actual_end)
def test_extract_cluster_i5(self):
colum, csv_path, c_start, c_end, cluster_name = init_data()
i = 5
j_start = 0
expected_cluster = 'sky is clear_0'
_, _, actual_cluster, _ = extract_start_end(colum, csv_path, i, c_start, c_end, cluster_name, False, j_start)
self.assertEqual(expected_cluster, actual_cluster)
def test_extract_start_i8(self):
colum, csv_path, c_start, c_end, cluster_name = init_data()
i = 8
j_start = 0
expected_start = 5
actual_start, _, _, _ = extract_start_end(colum, csv_path, i, c_start, c_end, cluster_name, False, j_start)
self.assertEqual(expected_start, actual_start)
def test_extract_end_i8(self):
colum, csv_path, c_start, c_end, cluster_name = init_data()
i = 8
j_start = 0
expected_end = 8
_, actual_end, _, _= extract_start_end(colum, csv_path, i, c_start, c_end, cluster_name, False, j_start)
self.assertEqual(expected_end, actual_end)
def test_extract_cluster_i8(self):
colum, csv_path, c_start, c_end, cluster_name = init_data()
i = 8
j_start = 0
expected_cluster = 'sky is clear_0'
_, _, actual_cluster, _ = extract_start_end(colum, csv_path, i, c_start, c_end, cluster_name, False, j_start)
self.assertEqual(expected_cluster, actual_cluster)
def test_extract_start_i11(self):
colum, csv_path, c_start, c_end, cluster_name = init_data()
i = 11
j_start = 0
expected_start = 11
actual_start, _, _, _ = extract_start_end(colum, csv_path, i, c_start, c_end, cluster_name, False, j_start)
self.assertEqual(expected_start, actual_start)
def test_extract_end_i11(self):
colum, csv_path, c_start, c_end, cluster_name = init_data()
i = 11
j_start = 0
expected_end = 29
_, actual_end, _, _= extract_start_end(colum, csv_path, i, c_start, c_end, cluster_name, False, j_start)
self.assertEqual(expected_end, actual_end)
def test_extract_cluster_i11(self):
colum, csv_path, c_start, c_end, cluster_name = init_data()
i = 11
j_start = 0
expected_cluster = 'sky is clear_2'
_, _, actual_cluster, _= extract_start_end(colum, csv_path, i, c_start, c_end, cluster_name, False, j_start)
self.assertEqual(expected_cluster, actual_cluster) | UTF-8 | Python | false | false | 3,711 | py | 24,522 | test_duration.py | 44 | 0.590407 | 0.578281 | 0 | 102 | 35.392157 | 117 |
niuyb/zhxg_support | 13,795,434,997,829 | 882dc4b9d7e2eb2bafa98b3456a7728ca023b61c | a2dc02ee7b2395ea2f4ea0d1359f262dd977087b | /secretary/utils.py | e9c44d129325a12f85c39cdff2166b5a3efab889 | []
| no_license | https://github.com/niuyb/zhxg_support | 4745a2141d5cf343b834f53e24abf85b177c426b | 8a8ec3e3bb609e8e428bba4d00ee45629c2bd405 | refs/heads/master | 2023-04-06T13:37:13.165744 | 2021-04-26T03:00:12 | 2021-04-26T03:00:12 | 361,599,382 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import json
from django.conf import settings
from secretary.models import WkTDinggroup, Salercansee, DingGroupMemberMap, SalercanseeNew
"""通过部门ID获取下级部门的部门ID和部门名称[{"did": xxx, "name": "yyy"}, ...]"""
def get_ding_groups(dpid):
ding_groups = WkTDinggroup.objects.filter(dpid=dpid).values("did", "name")
return ding_groups
"""获取公司所有部门"""
def get_all_departments():
departments = list(WkTDinggroup.objects.all().values("dpid", "did", "name"))
return departments
"""通过部门did获取下属部门"""
def get_sub_departments(did, all=None):
if all is None:
all = get_all_departments()
sub_departments = []
other = []
for department in all:
if department["dpid"] == did:
sub_departments.append(department)
else:
other.append(department)
return sub_departments, other
"""根据部门did获取所有下属部门"""
def get_all_sub_departments(did, all=None):
def _get_all_sub_departments(did, all, departments):
sub_departments, all = get_sub_departments(did, all)
if not sub_departments or not all:
return departments, all
departments.extend(sub_departments)
for department in sub_departments:
did = department["did"]
departments, all = _get_all_sub_departments(did, all, departments)
return departments, all
if all is None:
all = get_all_departments()
departments = []
_get_all_sub_departments(did, all, departments)
return departments
"""获取政务和企业两个中心的销售部门"""
def get_departments_about_sale():
all = get_all_departments()
dpids = settings.SALE_DEPARTMENT_LEVEL_1
department_data = []
for dpid in dpids:
departments = get_all_sub_departments(dpid, all=all)
department_data.extend(departments)
return department_data
"""查看某商务都能查看谁"""
def get_can_see(salename):
scs = Salercansee.objects.filter(salename=salename).first()
if not scs:
return []
js = scs.cansee
return list(set(json.loads(js)))
"""查看某商务都能查看谁"""
def get_can_see_new(istarshine_id):
scs = SalercanseeNew.objects.filter(saleid=istarshine_id).first()
if not scs:
return []
js = scs.cansee
return list(set(json.loads(js)))
"""查看部门下所有成员名字"""
def get_group_members(group_id):
dgmm = DingGroupMemberMap.objects.filter(group_id=group_id).first()
if not dgmm:
return []
js = dgmm.member_names_all
return json.loads(js)
"""查看部门下所有成员的istarshine_id"""
def get_group_istarshine_ids(group_id):
dgmm = DingGroupMemberMap.objects.filter(group_id=group_id).first()
if not dgmm:
return []
js = dgmm.istarshine_ids_all
return json.loads(js)
| UTF-8 | Python | false | false | 2,893 | py | 356 | utils.py | 275 | 0.654491 | 0.654119 | 0 | 88 | 29.488636 | 90 |
rhythmjain/MUSI6202-DSP | 19,310,172,977,571 | 530caf908830f8407486e9d33490662d1730f67f | 9544c9cb9d0abfd9236c8aa05e2cf05c653868e8 | /assignment02/dsp_q1_q2.py | 58b92bef6437db3b31fca31c63ceda3b069bf424 | []
| no_license | https://github.com/rhythmjain/MUSI6202-DSP | 0b6d4f2bf39b419c070a57b117a8276487e92d9f | cc25b2363237c8543434c2009307f02e0ef51182 | refs/heads/main | 2023-03-07T15:18:57.628199 | 2021-02-19T19:37:06 | 2021-02-19T19:37:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import scipy
from scipy import *
from matplotlib import pyplot as plt
import time
from scipy.io.wavfile import read
import numpy as np
path1 = "piano.wav"
path2 = "impulse-response.wav"
q1_image = 'results/y_time.png'
q2_file_path = "results/res.txt"
def loadSoundFile(path):
s, data = scipy.io.wavfile.read(path)
return np.array(data, dtype=float)
#Q: If the length of 'x' is 200 and the length of 'h' is 100, what is the length of 'y' ?
#A: 299
def myTimeConv(x,h):
x_len = len(x)
h_len = len(h)
y_len = x_len + h_len-1
y = np.zeros(y_len)
m = y_len - x_len
n = y_len - h_len
x =np.pad(x,(0,m),'constant')
h =np.pad(h,(0,n),'constant')
for n in range (y_len):
for k in range (y_len):
if n >= k:
y[n] = y[n]+x[n-k]*h[k]
return y
def plotfn(func):
print(func, len(func))
plt.figure()
plt.plot(func)
def CompareConv(x, h):
time1 = time.perf_counter()
y1 = myTimeConv(x,h)
time2 = time.perf_counter()
y2 = np.convolve(x,h)
time3 = time.perf_counter()
timeArr = [(time2-time1), (time3-time2)]
diff = y2-y1
absDiff = np.abs(diff)
m = np.sum(diff)/(y1.size+ y2.size)
mabs = np.sum(absDiff)/(y1.size+ y2.size)
stddev = np.std(diff)
return [m, mabs, stddev, timeArr]
def main():
x_q1 = np.ones(200)
h = np.arange(0,1,0.04)
h2 = np.zeros(1)
h=np.append(h, np.arange(1,0,-0.04))
h_q1=np.append(h,h2)
y_q1 = myTimeConv(x_q1,h_q1)
#Generating the plot for q1
fig, (ax0) = plt.subplots(nrows=1)
ax0.plot(y_q1)
ax0.set_title('question1', color='green')
ax0.set_xlabel('Time')
ax0.set_ylabel('Amplitude')
plt.subplots_adjust(hspace=2)
plt.savefig(q1_image)
x_q2 = loadSoundFile(path1)
h_q2 = loadSoundFile(path2)
#As this function takes long to evaluate - since myTimeConv is evaluating in time domain,
#here I am evaluating 10000 samples, to just create the file res.txt Otherwise the program takes a long time to evaluate
arr = CompareConv(x_q2[0:10000],h_q2[0:10000])
print(arr)
f=open(q2_file_path,'a')
a = np.array(arr[0:2])
b = np.array(arr[3])
np.savetxt(f, a, fmt='%1.3f', newline=", ")
f.write("\n")
np.savetxt(f, b, fmt='%1.3f', newline=", ")
f.write("\n")
f.close()
if __name__ == "__main__":
main() | UTF-8 | Python | false | false | 2,233 | py | 6 | dsp_q1_q2.py | 3 | 0.639946 | 0.59785 | 0 | 101 | 21.108911 | 121 |
mulinnuha/grit | 16,853,451,713,293 | c0db3562cb2a0c4fabc1ec741d869e70a46f2c9b | 32aa62643481d0c962d8da4d923ef7f16db44bb4 | /grit/delta/edge.py | d80d7f9c707ab07ba430137526599ed15d5054ed | []
| no_license | https://github.com/mulinnuha/grit | 7fbfb2ea897b041765656484da83fff95c2132ad | 521a0f4c6afcf6f248286fe65fd0c23d728f427f | refs/heads/master | 2018-12-10T21:19:24.460512 | 2018-09-19T11:56:02 | 2018-09-19T11:56:02 | 146,632,622 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import json
from grit.delta.entity import GritEntity
class GritEdge(GritEntity):
def __init__(self, grit_id, internal_id=None, edge_type=None,
start_node_grit_id=None, start_node_internal_id=None, start_node_label=None,
end_node_grit_id=None, end_node_internal_id=None, end_node_label=None,
is_created=False, is_changed=False, is_deleted=False, exists_before=False):
super().__init__(grit_id, internal_id, is_created, is_changed, is_deleted, exists_before)
self.edge_type = edge_type
self._start_node_grit_id = start_node_grit_id
self._start_node_internal_id = start_node_internal_id
self._start_node_label = start_node_label
self._end_node_grit_id = end_node_grit_id
self._end_node_internal_id = end_node_internal_id
self._end_node_label = end_node_label
def _format_start_node_label(self):
labels = ""
if self._start_node_label is not None:
labels += ":"
labels += ":".join(self._start_node_label)
return labels
def _format_end_node_label(self):
labels = ""
if self._end_node_label is not None:
labels += ":"
labels += ":".join(self._end_node_label)
return labels
def _format_start_node_grit_id(self):
return "{{grit_id = \"{0}\"}}".format(self._start_node_grit_id)
def _format_end_node_grit_id(self):
return "{{grit_id = \"{0}\"}}".format(self._end_node_grit_id)
def print(self):
print("id: {0}".format(self._internal_id))
print("grit_id: {0}".format(self._id))
print("edge_type: {0}".format(self.edge_type))
print("start_node_label: {0}".format(json.dumps(self._start_node_label)))
print("end_node_label: {0}".format(json.dumps(self._end_node_label)))
print("start_node_id: {0}".format(json.dumps(self._start_node_internal_id)))
print("end_node_id: {0}".format(json.dumps(self._end_node_internal_id)))
print("properties: {0}".format(json.dumps(self.properties_after)))
print("status: {0}".format(str(self.status)))
print("is_created: {0}".format(str(self.is_created)))
print("is_changed: {0}".format(str(self.is_changed)))
print("is_deleted: {0}".format(str(self.is_deleted)))
print("exists_before: {0}".format(str(self.exists_before)))
print("")
def format_edge_diff(self, include_node=True):
if include_node is True:
edge_str = "({0})-[{1}:{2}]->({3})".format(self._start_node_internal_id,
self._internal_id,
self.edge_type,
self._end_node_internal_id)
else:
edge_str = "(n)-[{0}]->(m)".format(self._internal_id)
return edge_str
def _format_edge_type(self):
return ":{}".format(self.edge_type)
def update_cypher(self):
self.diff_create = []
self.diff_update = []
self.diff_delete = []
# print(str(self.edge_type) + " " + str(self.is_created) + " " + str(self.is_changed) + " " + str(self.is_deleted))
if self.is_created and self.is_changed and self.is_deleted:
# forward: [create then change (label/properties)] then delete; ignore this node
# backward: [create then revert change (label/properties)] then delete; ignore this node
# current_log += "R C D"
pass
elif self.is_created and self.is_changed and not self.is_deleted:
# forward: create then change (add/remove label/properties)
# backward: [(revert change then)] delete
# current_log += "R C !D"
change = "Create Edge {0} \n" \
"\t {1}".format(self.format_edge_diff(),
self._format_diff_properties_after())
self.diff_create.append(change)
cypher_f = "MATCH (n{0} {1}), (m{2} {3}) " \
"CREATE (n)-[r{4} {5}]->(m)".format(self._format_start_node_label(),
self._format_start_node_grit_id(),
self._format_end_node_label(),
self._format_end_node_grit_id,
self._format_edge_type(),
self._format_cypher_create_properties_after())
self.cypher_forward.append(cypher_f)
cypher_b = "MATCH (n)-[r]->(m)" \
"WHERE r.grit_id={0}" \
"DELETE r;".format(self._format_id())
self.cypher_backward.append(cypher_b)
self.status = self._STATUS_CREATE
elif self.is_created and not self.is_changed and self.is_deleted:
# forward: [create then] delete; ignore this edge
# backward: [create then] delete; ignore this edge
# current_log += "R !C D "
pass
elif self.is_created and not self.is_changed and not self.is_deleted:
# forward: create node with properties
# backward: delete node
# current_log = "R !C !D"
change = "Create Edge {0} \n" \
"\t {1}".format(self.format_edge_diff(),
self._format_diff_properties_after())
self.diff_create.append(change)
cypher_f = "MATCH (n{0} {1}), (m{2} {3}) " \
"CREATE (n)-[r{4} {5}]->(m)".format(self._format_start_node_label(),
self._format_start_node_grit_id(),
self._format_end_node_label(),
self._format_end_node_grit_id,
self._format_edge_type(),
self._format_cypher_create_properties_after())
self.cypher_forward.append(cypher_f)
cypher_b = "MATCH (n)-[r]->(m)" \
"WHERE r.grit_id={0}" \
"DELETE r;".format(self._format_id())
self.cypher_backward.append(cypher_b)
self.status = self._STATUS_CREATE
elif not self.is_created and self.is_changed and self.is_deleted:
# forward: [change (add/remove label/properties) then] deleted
# backward: create edge then revert properties to before commit
# current_log += "!R C D"
change = "Delete Edge {0} \n" \
"\t {1}".format(self.format_edge_diff(),
self._format_diff_properties_before())
self.diff_delete.append(change)
cypher_f = "MATCH (n)-[r]->(m) " \
"WHERE r.grit_id = {0} " \
"DELETE n".format(self._format_id())
self.cypher_forward.append(cypher_f)
cypher_b = "MATCH (n{0} {1}), (m{2} {3}) " \
"CREATE (n)-[r{4} {5}]->(m)".format(self._format_start_node_label(),
self._format_start_node_grit_id(),
self._format_end_node_label(),
self._format_end_node_grit_id,
self._format_edge_type(),
self._format_cypher_create_properties_before())
self.cypher_backward.append(cypher_b)
self.status = self._STATUS_DELETE
elif not self.is_created and self.is_changed and not self.is_deleted:
# forward: change (add/change/remove properties)
# backward: revert properties to before commit
# current_log += "!R C !D"
change = "Update Edge {0} \n" \
"\t Before: {1} \n" \
"\t After: {2}".format(self.format_edge_diff(include_node=False),
self._format_diff_properties_before(),
self._format_diff_properties_after())
self.diff_update.append(change)
cypher_change_forward = []
cypher_change_backward = []
if len(self.properties_after) > 0:
# "SET key = "value", key2 = "value2", key3 = "value3",..."
cypher_f = "SET {0}".format(self._format_cypher_set_properties_after())
cypher_change_forward.append(cypher_f)
# "REMOVE n:key, n:key2, n:key3"
cypher_b = "REMOVE "
for key in self.properties_after:
cypher_b += "n.{0}, ".format(key)
cypher_change_backward.append(cypher_b[:-2])
if len(self.properties_before) > 0:
# "REMOVE n:key, n:key2, n.key3, ..."
cypher_f = "REMOVE "
for key in self.properties_before:
cypher_f += "n.{0}, ".format(key)
cypher_change_forward.append(cypher_f[:-2])
# "SET key = "value", key2 = "value2", key3 = "value3",..."
cypher_b = "SET {0}".format(self._format_cypher_set_properties_before())
cypher_change_backward.append(cypher_b)
for cypher in cypher_change_forward:
self.cypher_forward.append("MATCH (a)-[n]->(b) "
"WHERE n.grit_id = {0} "
"{1}".format(self._format_id(), cypher))
for cypher in cypher_change_backward:
self.cypher_backward.append("MATCH (a)-[n]->(b) "
"WHERE n.grit_id = {0} "
"{1}".format(self._format_id(), cypher))
self.status = self._STATUS_UPDATE
elif not self.is_created and not self.is_changed and self.is_deleted:
# forward: delete
# backward: create
# current_log += "!R !C D Delete Node
change = "Delete Edge {0} \n" \
"\t {1}".format(self.format_edge_diff(),
self._format_diff_properties_before())
self.diff_delete.append(change)
cypher_f = "MATCH n-[r]->(m) " \
"WHERE r.grit_id={0} " \
"DELETE r".format(self._format_id())
self.cypher_forward.append(cypher_f)
cypher_b = "MATCH (n{0} {1}), (m{2} {3}) " \
"CREATE (n)-[r{4} {5}]->(m)".format(self._format_start_node_label(),
self._format_start_node_grit_id(),
self._format_end_node_label(),
self._format_end_node_grit_id,
self._format_edge_type(),
self._format_cypher_create_properties_before())
self.cypher_backward.append(cypher_b)
self.status = self._STATUS_DELETE
elif not self.is_created and not self.is_changed and not self.is_deleted:
# no change to this node
# current_log += "!R !C !D"
pass
else:
# current_log += "???"
pass
| UTF-8 | Python | false | false | 11,849 | py | 50 | edge.py | 47 | 0.46966 | 0.462655 | 0 | 229 | 50.742358 | 123 |
eldosatalov/taskqueue | 7,481,833,070,880 | 2785763ae697fdc2717f992b50d9d1bdf7613b0c | 0d5802008142ef64a9049646f3d813a590cd9931 | /task/tests.py | ac11852e50c6084c62cd24a13c1bd442cb81edb1 | []
| no_license | https://github.com/eldosatalov/taskqueue | 26a08639aefa179bc67cd35b087b34b848c3baf2 | 64e6f9d6d3761b66a60a6b91b8cb058ada729726 | refs/heads/master | 2023-02-08T03:37:31.135627 | 2021-01-04T03:47:38 | 2021-01-04T03:47:38 | 326,562,350 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from task.models import Task
class TaskTests(APITestCase):
def setUp(self):
Task.objects.create(name="hello")
def test_create_task(self):
data = {'name': 'test task'}
url = reverse('task_create')
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Task.objects.filter(name__iexact='test task').count(), 1)
def test_start_task(self):
task = Task.objects.get(name="hello")
url = reverse('task_detail', kwargs={'pk': task.id})
response = self.client.put(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertNotEqual(Task.objects.get(name="hello").start_date, None)
def test_end_task(self):
task = Task.objects.get(name="hello")
data = {'success': True}
url = reverse('task_detail', kwargs={'pk': task.id})
response = self.client.patch(url, data, format='json')
task = Task.objects.get(name="hello")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue(task.success, True)
self.assertNotEqual(task.end_date, None)
| UTF-8 | Python | false | false | 1,331 | py | 9 | tests.py | 6 | 0.656649 | 0.649136 | 0 | 33 | 39.333333 | 82 |
Seventeen17/graph-learn | 11,450,382,842,296 | 866fe932c6b02cf34598a69ef28c3d28bb0c6985 | 220d1bf931234507bf50fa12a54ad9e95e31982b | /graphlearn/examples/tf/ego_sage/train_unsupervised.py | b073cc294b58d47536e4c48f98a9b97a2f29e013 | [
"Apache-2.0"
]
| permissive | https://github.com/Seventeen17/graph-learn | b380c2368dd72ed590993cc992ab203d6e279000 | cd3f6e9de557042598851b14b01ca03e18bd9288 | refs/heads/master | 2022-10-27T12:07:04.014248 | 2022-09-29T07:06:00 | 2022-09-29T07:06:00 | 253,716,063 | 5 | 0 | Apache-2.0 | true | 2022-04-27T09:55:16 | 2020-04-07T07:15:08 | 2022-04-27T09:41:23 | 2022-04-27T09:55:13 | 32,786 | 1 | 0 | 0 | C++ | false | false | # Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
from __future__ import print_function
import datetime
import numpy as np
import graphlearn as gl
import tensorflow as tf
import graphlearn.python.nn.tf as tfg
from ego_sage import EgoGraphSAGE
def load_graph(config):
data_dir = config['dataset_folder']
g = gl.Graph() \
.node(data_dir+'ogbl_collab_node', node_type='i',
decoder=gl.Decoder(attr_types=['float'] * config['features_num'],
attr_dims=[0]*config['features_num'])) \
.edge(data_dir+'ogbl_collab_train_edge', edge_type=('i', 'i', 'train'),
decoder=gl.Decoder(weighted=True), directed=False)
return g
def meta_path_sample(ego, ego_name, nbrs_num, sampler):
""" creates the meta-math sampler of the input ego.
config:
ego: A query object, the input centric nodes/edges
ego_name: A string, the name of `ego`.
nbrs_num: A list, the number of neighbors for each hop.
sampler: A string, the strategy of neighbor sampling.
"""
alias_list = [ego_name + '_hop_' + str(i + 1) for i in range(len(nbrs_num))]
for nbr_count, alias in zip(nbrs_num, alias_list):
ego = ego.outV('train').sample(nbr_count).by(sampler).alias(alias)
return ego
def query(graph, config):
seed = graph.E('train').batch(config['batch_size']).shuffle(traverse=True)
src = seed.outV().alias('src')
dst = seed.inV().alias('dst')
neg_dst = src.outNeg('train').sample(config['neg_num']).by(config['neg_sampler']).alias('neg_dst')
src_ego = meta_path_sample(src, 'src', config['nbrs_num'], config['sampler'])
dst_ego = meta_path_sample(dst, 'dst', config['nbrs_num'], config['sampler'])
dst_neg_ego = meta_path_sample(neg_dst, 'neg_dst', config['nbrs_num'], config['sampler'])
return seed.values()
def train(graph, model, config):
tfg.conf.training = True
query_train = query(graph, config)
dataset = tfg.Dataset(query_train, window=10)
src_ego = dataset.get_egograph('src')
dst_ego = dataset.get_egograph('dst')
neg_dst_ego = dataset.get_egograph('neg_dst')
src_emb = model.forward(src_ego)
dst_emb = model.forward(dst_ego)
neg_dst_emb = model.forward(neg_dst_ego)
# use sampled softmax loss with temperature.
loss = tfg.unsupervised_softmax_cross_entropy_loss(src_emb, dst_emb, neg_dst_emb,
temperature=config['temperature'])
return dataset.iterator, loss
def run(config):
# graph input data
g = load_graph(config=config)
g.init()
# Define Model
dims = [config['features_num']] + [config['hidden_dim']] * (len(config['nbrs_num']) - 1) + [config['output_dim']]
model = EgoGraphSAGE(dims,
agg_type=config['agg_type'],
dropout=config['drop_out'])
# train
iterator, loss = train(g, model, config)
optimizer = tf.train.AdamOptimizer(learning_rate=config['learning_rate'])
train_op = optimizer.minimize(loss)
train_ops = [loss, train_op]
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())
sess.run(iterator.initializer)
step = 0
print("Start Training...")
for i in range(config['epoch']):
try:
while True:
ret = sess.run(train_ops)
print("Epoch {}, Iter {}, Loss {:.5f}".format(i, step, ret[0]))
step += 1
except tf.errors.OutOfRangeError:
sess.run(iterator.initializer) # reinitialize dataset.
g.close()
if __name__ == "__main__":
config = {'dataset_folder': '../../data/ogbl_collab/',
'batch_size': 128,
'features_num': 128,
'hidden_dim': 128,
'output_dim': 128,
'nbrs_num': [10, 5],
'neg_num': 5,
'learning_rate': 0.0001,
'epoch': 1,
'agg_type': 'mean',
'drop_out': 0.0,
'sampler': 'random',
'neg_sampler': 'in_degree',
'temperature': 0.07
}
run(config) | UTF-8 | Python | false | false | 4,601 | py | 19 | train_unsupervised.py | 16 | 0.627038 | 0.617474 | 0 | 121 | 37.033058 | 115 |
dabrze/CheckMyBlob | 13,657,996,026,429 | d6758316f406c2603a1cbff294c66ae391a60b9c | ade10888359c4f25ab9695da190a8aa84b18675b | /GatherData/ignored_res.py | ee82dea4c358d44338ac9ee3bd64f7345d39399b | [
"MIT"
]
| permissive | https://github.com/dabrze/CheckMyBlob | 59bbe3ed225ef2e9b8129c16f13330c1c46b441d | 237587c503a2b0636a397d530b822672e0d10267 | refs/heads/master | 2021-01-23T16:13:22.417796 | 2018-06-14T20:51:47 | 2018-06-14T20:51:47 | 102,726,502 | 12 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
ELEMENTS_ELECTRONS = {
"H":1, "HE":2, "LI":3, "BE":4, "B":5, "C":6, "N":7, "O":8, "F":9, "NE":10, "NA":11, "MG":12,
"AL":13, "SI":14, "P":15, "S":16, "CL":17, "AR":18, "K":19, "CA":20, "SC":21, "TI":22, "V":23, "CR":24,
"MN":25, "FE":26, "CO":27, "NI":28, "CU":29, "ZN":30, "GA":31, "GE":32, "AS":33, "SE":34, "BR":35,
"KR":36, "RB":37, "SR":38, "Y":39, "ZR":40, "NB":41, "MO":42, "TC":43, "RU":44, "RH":45, "PD":46,
"AG":47, "CD":48, "IN":49, "SN":50, "SB":51, "TE":52, "I":53, "XE":54, "CS":55, "BA":56, "LA":57,
"CE":58, "PR":59, "ND":60, "PM":61, "SM":62, "EU":63, "GD":64, "TB":65, "DY":66, "HO":67, "ER":68,
"TM":69, "YB":70, "LU":71, "HF":72, "TA":73, "W":74, "RE":75, "OS":76, "IR":77, "PT":78, "AU":79,
"HG":80, "TL":81, "PB":82, "BI":83, "PO":84, "AT":85, "RN":86, "FR":87, "RA":88, "AC":89, "TH":90,
"PA":91, "U":92, "NP":93, "PU":94, "AM":95, "CM":96, "BK":97, "CF":98, "ES":99, "FM":100, "MD":101,
"NO":102, "LR":103, "RF":104, "DB":105, "SG":106, "BH":107, "HS":108, "MT":109, "DS":110, "RG":111,
'X': 6, 'D': 1
}
IGNORED_RESIDUES = set(
(
# PEPTIDE
'ALA',
'ARG',
'ASN',
'ASP',
'CSH',
'CYS',
'GLN',
'GLU',
'GLY',
'HIS',
'ILE',
'LEU',
'LYS',
'MET',
'MSE',
'ORN',
'PHE',
'PRO',
'SER',
'THR',
'TRP',
'TYR',
'VAL',
# DNA
'DA',
'DG',
'DT',
'DC',
'A',
'G',
'T',
'C',
'U',
#'YG',
#'PSU',
'I',
# ELEMENTS
'FE', # ferrum
'P', # phosphorus
'S', # sulfur
'I', # iodin
'BR', # bromine
'CL', # chlorine
'CA', # calcium
'CO', # cobalt
'CU', # copper
'ZN', # zinc
'MG', # magnesium
'MN', # manganese
'CD', # cadmium
'F', # fluorine
'NA', # sodium
'B', # boron
'HG', # mercury
'V', # vanadium
'PB', # lead
'HOH', # water
#'SO3', #SULFITE ION
#'SO4', #sulphate-(SO4)
#'PO3', #PHOSPHITE ION
#'PO4', #phosphate-(PO4)
#'CH2', #Methylene
#'SCN', #THIOCYANATE ION
#'CYN', #CYANIDE ION
#'CMO', #CARBON MONOXIDE
'GD', #GADOLINIUM ATOM
#'NH4', #AMMONIUM ION
#'NH2', #AMINO GROUP
'OH', #HYDROXIDE ION
'HO', #HOLMIUM ATOM
'DOD', #DEUTERATED WATER
'OXY', #OXYGEN MOLECULE
'C2O', #CU-O-CU LINKAGE
'C1O', #CU-O LINKAGE
'IN', #INDIUM (III) ION
'NI', #NICKEL (II) ION
#'NO3', #NITRATE ION
#'NO2', #NITRITE ION
'IOD', #IODIDE ION
'MTO', #BOUND WATER
'SR', #STRONTIUM ION
'YB', #YTTERBIUM (III) ION
'AL', #ALUMINUM ION
'HYD', #HYDROXY GROUP
'IUM', #URANYL(VI) ION
'FLO', #FLUORO GROUP
'TE', #te
'K', #POTASSIUM ION
'LI', #LITHIUM ION
'RB', #RUBIDIUM ION
'FE2', #FE(II) ION
'NMO', #NITROGEN MONOXIDE
'OXO', #OXO GROUP
'CO2', #CARBON DIOXIDE
'BA', #BARIUM ION
'O', #OXYGEN ATOM
'PER', #PEROXIDE ION
'SM', #SAMARIUM (III) ION
'CS', #CESIUM ION
'MN3', #MANGANESE (III) ION
'CU1', #COPPER (I) ION
'H', #HYDROGEN ATOM
'TL', #THALLIUM (I) ION
'H2S', #HYDROSULFURIC ACID
'BRO', #BROMO GROUP
'IDO', #IODO GROUP
'PT', #PLATINUM (II) ION
'SI', #.
'GE', #.
'SN', #.
'BE', #.
'SC', #.
'Y', #.
'UR', #.
'CR', #.
'MO', #.
'W', #.
'AG', #.
'AU', #.
'AS', #.
'SE', #.
'HE', #.
'NE', #.
'AR', #.
'KR', #.
'XE', #
'GA', #.
'DUM', #dummy atom
)
)
KEEP_RESIDUES = set(
(
# PEPTIDE
'ALA',
'ARG',
'ASN',
'ASP',
'CSH',
'CYS',
'GLN',
'GLU',
'GLY',
'HIS',
'ILE',
'LEU',
'LYS',
'MET',
'MSE',
'ORN',
'PHE',
'PRO',
'SER',
'THR',
'TRP',
'TYR',
'VAL',
# DNA
'DA',
'DG',
'DT',
'DC',
'A',
'G',
'T',
'C',
'U',
)
)
| UTF-8 | Python | false | false | 4,949 | py | 370 | ignored_res.py | 36 | 0.322489 | 0.272984 | 0 | 187 | 25.459893 | 107 |
hadronproject/hadron64 | 1,090,921,702,601 | 80f7d274d2fb2cd4b473acf694172570b9c240ce | efbf54a7778aabb8d5b4f494517fb8871b6a5820 | /sys-apps/tcp-wrappers/tcp-wrappers-7.6-r1.py | f6dcce4a17e28d9843ed1e91bde35e32cc6efbd4 | []
| no_license | https://github.com/hadronproject/hadron64 | f2d667ef7b4eab884de31af76e12f3ab03af742d | 491652287d2fb743a2d0f65304b409b70add6e83 | refs/heads/master | 2021-01-18T11:30:37.063105 | 2013-07-14T04:00:23 | 2013-07-14T04:00:23 | 8,419,387 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | metadata = """
summary @ Monitors and Controls incoming TCP connections
homepage @ ftp://ftp.porcupine.org/pub/security/index.html
license @ tcp_wrappers_license
src_url @ ftp://ftp.porcupine.org/pub/security/tcp_wrappers_$version.tar.gz
arch @ ~x86_64
"""
depends = """
runtime @ sys-libs/glibc app-shells/bash
"""
srcdir = "tcp_wrappers_%s" % raw_version
def prepare():
patch("shared_lib_plus_plus-1.patch", level=1)
patch("01_all_redhat-bug11881.patch", level=1)
patch("04_all_fixgethostbyname.patch", level=1)
patch("07_all_sig.patch", level=1)
patch("09_all_gcc-3.4.patch", level=1)
patch("10_all_more-headers.patch", level=1)
patch("02_all_redhat-bug17795.patch")
patch("03_all_wildcard.patch")
patch("11_inet6_fixes.patch")
patch("tcp-wrappers-7.6-ipv6-1.14.patch", level=2)
def build():
make('REAL_DAEMON_DIR=/usr/sbin STYLE=-DPROCESS_OPTIONS linux')
def install():
for d in ('include', 'lib' ,'sbin'):
makedirs("/usr/"+d)
for m in ('3','5','8'):
makedirs("/usr/share/man/man"+m)
raw_install("DESTDIR=%s" % install_dir)
insfile("%s/hosts.allow" % filesdir, "/etc/hosts.allow")
insfile("%s/hosts.deny" % filesdir, "/etc/hosts.deny")
insdoc("BLURB", "CHANGES", "DISCLAIMER", "README*")
| UTF-8 | Python | false | false | 1,285 | py | 659 | tcp-wrappers-7.6-r1.py | 597 | 0.65214 | 0.61323 | 0 | 42 | 29.595238 | 75 |
areebahmed04/fontbakery | 19,533,511,280,182 | df43bc623321e772f8988baff127d76e5df22a6d | 333c85a75d814fcd9a16b89c8f28a3693c08f7c9 | /Lib/fontbakery/profiles/dsig.py | 69266439d109c7c876b760fb56500a1c9885b572 | [
"Apache-2.0"
]
| permissive | https://github.com/areebahmed04/fontbakery | 3aa0daaaf484373b9d701a7fe24f25ef03ea49e7 | 79290dd942d5571a04639bb097fc6450a5836d4c | refs/heads/master | 2020-09-23T16:43:55.401461 | 2019-11-21T14:44:06 | 2019-11-21T20:51:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from fontbakery.callable import check
from fontbakery.checkrunner import FAIL, PASS
from fontbakery.message import Message
# used to inform get_module_profile whether and how to create a profile
from fontbakery.fonts_profile import profile_factory # NOQA pylint: disable=unused-import
@check(
id = 'com.google.fonts/check/dsig',
rationale = """
Some programs expect fonts to have a digital signature declared in their DSIG table in order to work properly.
This checks verifies that such signature is available in the font.
Typically, even a fake signature would be enough to make the fonts work. If needed, such dummy-placeholder can be added to the font by using the `gftools fix-dsig` script available at https://github.com/googlefonts/gftools
"""
)
def com_google_fonts_check_dsig(ttFont):
"""Does the font have a DSIG table?"""
if "DSIG" in ttFont:
yield PASS, "Digital Signature (DSIG) exists."
else:
yield FAIL,\
Message("lacks-signature",
"This font lacks a digital signature (DSIG table)."
" Some applications may require one (even if only a"
" dummy placeholder) in order to work properly. You"
" can add a DSIG table by running the"
" `gftools fix-dsig` script.")
| UTF-8 | Python | false | false | 1,309 | py | 2 | dsig.py | 2 | 0.693659 | 0.693659 | 0 | 28 | 45.75 | 226 |
kooose38/Tasks-by-bert | 3,161,095,943,714 | 3a9687f96d10e3fc3372df72fcde4d5aba0fd025 | d9113f396c4c833b06303c3571683982052ca110 | /classification/code/model2.py | 910a25cbee2e1a17d50753d9aa971493f9161ded | []
| no_license | https://github.com/kooose38/Tasks-by-bert | 991db5a60e96d8915a914aa3d42ab2bf328228cc | f214932c24b623e5bd7e910d00771ed8e479048f | refs/heads/master | 2023-06-28T04:20:26.456643 | 2021-07-30T06:48:57 | 2021-07-30T06:48:57 | 388,649,660 | 0 | 0 | null | false | 2021-07-30T06:48:57 | 2021-07-23T01:59:19 | 2021-07-30T06:09:14 | 2021-07-30T06:48:57 | 83,932 | 0 | 0 | 0 | Jupyter Notebook | false | false | from transformers import BertForSequenceClassification
import torch
from dataloader import DataLoader_
import torch.nn as nn
class BertForSequenceClassification_(nn.Module):
def __init__(self, model_name: str, num_labels: int):
"""
(文章数, 単語数, 1) 入力層
-> (文章数, 単語数, 768) BertModel
-> (文章数, 768) tokenから[CLS]のベクトルのみを抽出
-> (文章数, num_labels) Linear/ ReLU/ Softmax
"""
super(BertForSequenceClassification_, self).__init__()
self.bert_sc = BertForSequenceClassification.from_pretrained(model_name,
num_labels=num_labels)
def forward(self, x):
output = self.bert_sc(**x)
return output.logits | UTF-8 | Python | false | false | 819 | py | 42 | model2.py | 32 | 0.585657 | 0.576361 | 0 | 19 | 38.684211 | 90 |
HANDS-FREE/handsfree | 5,317,169,557,089 | 7fa9c5ef2f5ae8eb90783dbe08b951becd827bdb | 8b27a0c141eecec0aa142b1fa35c2968ed090206 | /handsfree_smach/script/laser_detection.py | 454a8f719edd28f9a0a5aca340c43839bcaf8a56 | [
"BSD-2-Clause"
]
| permissive | https://github.com/HANDS-FREE/handsfree | 496b00384cd2b7bd5e2ec47305b929eccd9b8645 | c36a02eee46d68c15527f7c8ee98052a410396de | refs/heads/master | 2022-12-22T10:04:23.009146 | 2022-12-13T04:08:01 | 2022-12-13T04:08:01 | 55,843,990 | 140 | 77 | BSD-2-Clause | false | 2021-01-18T04:26:59 | 2016-04-09T12:49:24 | 2021-01-13T15:58:09 | 2021-01-18T04:26:59 | 30,653 | 120 | 82 | 1 | C++ | false | false | #!/usr/bin/env python
import tf
import math
import rospy
import std_msgs.msg as std_msgs
import sensor_msgs.msg as sensor_msgs
class ObstacleDetection(object):
def __init__(self):
self.__angle_check_min = rospy.get_param('~min_angle', -math.pi/12) # the min angle we could to detect obstacle
self.__angle_check_max = rospy.get_param('~max_angle', math.pi/12) # the max angle we could to detect obstacle
self.__obstacle_threshold_dis = rospy.get_param('~obstacle_threshold', 1.0) # the distance we think need to stop robot
self.__topic_laser = rospy.get_param('~topic_name_laser', '/robot_0/base_scan')
self.__suber_laser = rospy.Subscriber(self.__topic_laser,
sensor_msgs.LaserScan,
self.__callback_laser_scan,
queue_size=1)
# publish True when find obstacle in front of robot
self.__puber_stop = rospy.Publisher('/stop_robot',
std_msgs.Bool,
queue_size=1)
self.__puber_start = rospy.Publisher('/start_robot',
std_msgs.Bool,
queue_size=1)
def __callback_laser_scan(self, laser_msg):
"""
the callback function for laser_scan
:param:laser_msg: the laser msg we get from robot
:type: sensor_msgs.msgs.laserScan
:return: none
"""
size_laser_points = len(laser_msg.ranges)
angle_count = 0
pub_data = std_msgs.Bool()
pub_data.data = True
for each_point in range(0, size_laser_points, 1):
point_angle = laser_msg.angle_min + angle_count
# this angle between angle_check_min and angle_check_max is the range we need to check
if self.__angle_check_min <= point_angle <= self.__angle_check_max:
if laser_msg.ranges[each_point] <= self.__obstacle_threshold_dis:
rospy.loginfo('obstacle find!!!!')
self.__puber_stop.publish(pub_data)
return # need not to check out other points
angle_count += laser_msg.angle_increment
self.__puber_start.publish(pub_data)
if __name__ == '__main__':
rospy.init_node('obstacle_detection')
ObstacleDetection()
rospy.spin()
| UTF-8 | Python | false | false | 2,484 | py | 198 | laser_detection.py | 68 | 0.544686 | 0.539452 | 0 | 56 | 43.357143 | 127 |
bscho99/Madcamp_Week3_Server | 12,137,577,591,300 | 96fdfa1198a641580bb0145d154c17c77dc38bb9 | 8eaf4013544f9e58920bfdca20d6c38739db6cf2 | /restfulapi/serializers.py | f2d8dea203c51f12281c117fe46f6cc7a5bce13b | []
| no_license | https://github.com/bscho99/Madcamp_Week3_Server | af9e0ef20424dfe24c29b2c863a6170f6af14340 | 6607c321cd6a6f7f6ce09a6fe31d51fbbf03f0e0 | refs/heads/master | 2023-02-24T05:02:35.909538 | 2021-01-19T19:39:07 | 2021-01-19T19:39:07 | 331,088,981 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from rest_framework import serializers
from .models import User, Playlist
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['userid', 'password']
class PlaylistSerializer(serializers.ModelSerializer):
class Meta:
model = Playlist
fields = ['userid', 'title', 'description', 'songs', 'letter']
| UTF-8 | Python | false | false | 373 | py | 7 | serializers.py | 6 | 0.683646 | 0.683646 | 0 | 14 | 25.642857 | 70 |
Ivan252512/resiliencia | 17,403,207,519,925 | 56a9ccd68b42311eea4ddabc0eb908d8dd3603ad | 35e4efcbb9163101c72ebe02585e8ec7c39c104a | /apps/reflexion/ref_ladera/apps.py | 9a32a020a593166ceb80efa2cfc1c1926312bb2a | []
| no_license | https://github.com/Ivan252512/resiliencia | ff89a30844812fd3916a1d8c31b734745540b9af | e5f9f9cc76f222438476b6c21022fea1d49f41c3 | refs/heads/master | 2020-04-27T15:12:12.266210 | 2019-04-03T08:56:12 | 2019-04-03T08:56:12 | 174,436,765 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.apps import AppConfig
class RefLaderaConfig(AppConfig):
name = 'ref_ladera'
| UTF-8 | Python | false | false | 94 | py | 83 | apps.py | 74 | 0.755319 | 0.755319 | 0 | 5 | 17.8 | 33 |
tymscar/Advent-Of-Code | 14,319,420,974,973 | f091296563259636138aa76da3b1874bcd95dcef | fc9390a7b3edee292e920624706b0e9e04c38603 | /2019/Python/day14/part1.py | 345c8055c4f0cb0fa484ae1fd5743a7b2b39938e | [
"MIT"
]
| permissive | https://github.com/tymscar/Advent-Of-Code | ae19c1fa3e89c245e788ff5252758190799d1eb3 | f8bae1531dc93a97b59752605a38079254611eb3 | refs/heads/master | 2023-01-14T09:44:40.825262 | 2022-12-25T15:23:27 | 2022-12-25T15:23:27 | 159,945,813 | 9 | 10 | null | null | null | null | null | null | null | null | null | null | null | null | null | from collections import defaultdict
from math import ceil
file = open('input.txt', 'r')
makingUpOf = defaultdict(list)
minimumOf = defaultdict(int)
currentlyHave = defaultdict(int)
oreUsed = 0
for line in file:
result = line.split("=>")[1].rstrip().lstrip()
goingIn = []
for elem in line.split("=>")[0].split(","):
goingIn.append(elem.rstrip().lstrip())
makingUpOf[result.split(" ")[1]] = goingIn
minimumOf[result.split(" ")[1]] = int(result.split(" ")[0])
def makeElement(thisElem):
global oreUsed
for neededElem in makingUpOf[thisElem]:
elem = neededElem.split(" ")[1]
qty = int(neededElem.split(" ")[0])
if currentlyHave[elem] >= qty:
currentlyHave[elem] -= qty
else:
if elem == "ORE":
oreUsed += qty
else:
howManyTimes = int(ceil((qty - currentlyHave[elem]) / minimumOf[elem]))
for i in range(0,howManyTimes):
makeElement(elem)
currentlyHave[elem] -= qty
currentlyHave[thisElem] += minimumOf[thisElem]
makeElement("FUEL")
print(oreUsed)
| UTF-8 | Python | false | false | 1,140 | py | 232 | part1.py | 230 | 0.588596 | 0.580702 | 0 | 39 | 28.230769 | 87 |
jourdy345/2016spring | 18,391,049,985,926 | 42ca2602c583dfb5fd463e06832e79cf71f888b5 | fa80eeb89943cd0bfac60d90e656d6ae31d1d23c | /mathForSocialScience/midterm_report/RJpi.py | fa7c352c268d362c81b15dd1e671efb2521486ec | []
| no_license | https://github.com/jourdy345/2016spring | 843b5e37c8ef34b51e7de7773e0603be347c0317 | bc61a8558fc727fbe2e73db80a3e9e36819a56ee | refs/heads/master | 2021-01-21T04:47:14.937340 | 2016-06-09T15:56:51 | 2016-06-09T15:56:51 | 53,733,514 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import math
from __future__ import division
def RJpi(tau):
n = 0.0
k1 = 26390.0
k2 = 1103.0
k3 = 396.0
eps = tau + 1.0
rjpi = 0
epsList = []
while(eps > tau):
eps = math.factorial(4.0*n)/((math.factorial(n))**4.0) * (k1 * n + k2)/(k3**(4.0*n))
epsList.append(eps)
rjpi += eps
n += 1
rjpi = 9801.0/(math.sqrt(8)*rjpi)
return rjpi, epsList
| UTF-8 | Python | false | false | 359 | py | 59 | RJpi.py | 10 | 0.579387 | 0.470752 | 0 | 17 | 19.941176 | 86 |
mianmuri1991/validar-RUC-Ecuador | 9,079,560,870,033 | b753e0ac7c508e154d5332beff67ce69c432d9d6 | 9f4dcc8249d2c88f61351a1cf5930ebf7f9919b6 | /Python/validar_ruc_persona_juridica.py | 233eabdce4f5b97b09c34d3a88b9b4a624bf93c3 | []
| no_license | https://github.com/mianmuri1991/validar-RUC-Ecuador | 3780aa9aef969645e200779ed8dd994e1fe0e809 | 4ff559b0fc5ba4fbe77aa363fc862771f38b623f | refs/heads/main | 2021-07-09T06:14:45.311884 | 2020-12-09T13:13:21 | 2020-12-09T13:13:21 | 208,522,049 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #Validar el RUC de una persona juridica en Ecuador
#Si es persona juridica privada o extranjero no residente (sin cedula) se tiene el caso 1
#Si es persona juridica publica se tiene el caso 2
#Si es persona natural se tiene el caso 3
def validar(numero):
#Valida dimension
if(len(numero)!=13):
return 0
else:
dos_primeros_digitos = int(numero[0:2])
#Valida 2 primeros digitos
if(dos_primeros_digitos < 1 or dos_primeros_digitos > 22):
return 0
tercer_digito = int(numero[2])
#Valida tercer digito (Condicion creada con logica matematica y leyes de De Morgan)
if(tercer_digito != 9 and tercer_digito != 6 and (tercer_digito < 0 or tercer_digito >= 6)):
return 0
#Si tercer digito es 9 se analiza el caso 1
if(tercer_digito==9):
ultimos_tres_digitos = int(numero[10:13])
if(int(ultimos_tres_digitos <= 000)):
return 0
total = 0
nueve_primeros_digitos = numero[0:9]
coeficientes = '432765432'
for i in range(0,9):
num = int(nueve_primeros_digitos[i])
coef = int(coeficientes[i])
valor = num * coef
total+=valor
#Calculamos el residuo y el verificador
residuo = total%11
if(residuo==0):
verificador = 0
else:
verificador = 11 - residuo
if(verificador == int(numero[9])):
return 1
else:
return 0
#Si tercer digito es 6 se analiza el caso 2
elif(tercer_digito==6):
ultimos_cuatro_digitos = int(numero[9:13])
if(int(ultimos_cuatro_digitos <= 0000)):
return 0
total = 0
ocho_primeros_digitos = numero[0:8]
coeficientes = '32765432'
for i in range(0,8):
num = int(ocho_primeros_digitos[i])
coef = int(coeficientes[i])
valor = num * coef
total+=valor
#Calculamos el residuo y el verificador
residuo = total%11
if(residuo==0):
verificador = 0
else:
verificador = 11 - residuo
if(verificador == int(numero[8])):
return 1
else:
return 0
#Si tercer digito es menor a 6 y positivo se analiza el caso 3
else:
ultimos_tres_digitos = int(numero[10:13])
if(int(ultimos_tres_digitos <= 000)):
return 0
total = 0
nueve_primeros_digitos = numero[0:9]
coeficientes = '212121212'
for i in range(0,9):
num = int(nueve_primeros_digitos[i])
coef = int(coeficientes[i])
valor = num * coef
if(valor >= 10):
valor = (valor%10)+1
total+=valor
#Calculamos el residuo y el verificador
residuo = total%10
if(residuo==0):
verificador = 0
else:
verificador = 10 - residuo
if(verificador == int(numero[9])):
return 1
else:
return 0
| UTF-8 | Python | false | false | 3,336 | py | 4 | validar_ruc_persona_juridica.py | 2 | 0.502698 | 0.465528 | 0 | 88 | 36.897727 | 100 |
brianhu0716/LeetCode-Solution | 12,395,275,636,979 | 41d23489bef3e7af0e8183c857715c8cc04e7420 | b96f1bad8a74d31d8ff79bc955813bfcd17d7b26 | /413. Arithmetic Slices.py | a954f6f0bad31cafbed00bdbde4a235b802d134d | []
| no_license | https://github.com/brianhu0716/LeetCode-Solution | e7177af15e84e833ce8ab05027683ed4ac489643 | 158a4359c90b723545b22c4898047274cc1b80a6 | refs/heads/main | 2023-07-11T05:29:56.783795 | 2021-08-28T12:53:14 | 2021-08-28T12:53:14 | 374,991,658 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 9 23:04:50 2021
@author: Brian
"""
'''
Arithmetic的定義為:數列中至少有三個數字,數字以及數字之間的差固定,本題要求計算最多有多少個Arithmetic 子數列
'''
class Solution:
def numberOfArithmeticSlices(self, nums) -> int:
def findend(start,l,nums,ref):
for i in range(start,l - 1):
if (nums[i + 1] - nums[i]) != ref:
return i
return l - 1
if (l := len(nums)) < 3: return 0
elif l == 3: return 1 if (nums[2] - nums[1]) == (nums[1] - nums[0]) else 0
start = 0
self.n = 0
while start + 2 < l:
if (ref := nums[start + 2] - nums[start + 1]) == nums[start + 1] - nums[start]:
i = findend(start + 2,l,nums,ref)
self.n += (1 + (i - start + 1 - 2)) * (i - start + 1 - 2) * 0.5
start = i
else:
start += 1
return int(self.n)
test = Solution()
nums = [[1,2,3,4],
[1],
[1,2,3,8,9,10],
[1,2,3]
]
for n in nums:
print(test.numberOfArithmeticSlices(n)) | UTF-8 | Python | false | false | 1,170 | py | 403 | 413. Arithmetic Slices.py | 403 | 0.469501 | 0.419593 | 0 | 37 | 28.27027 | 91 |
eliyahudev/social_network | 8,177,617,749,367 | d6776586fb9b9980d62863234d2efecdd18b1c75 | 56545a99bf67e0993e292eb88d3eb50d372c9839 | /srt_to_exel.py | 41d83975b45d989fdc5f907e3fd9f8a93984590c | []
| no_license | https://github.com/eliyahudev/social_network | ffab5ca74626c9b2bd7dfb9e726207340f8a3d73 | 07c2f3ea65c0e55a62d18b61b09825d843686462 | refs/heads/master | 2022-12-09T16:25:00.967488 | 2020-09-08T18:38:17 | 2020-09-08T18:38:17 | 285,676,372 | 0 | 0 | null | false | 2020-08-13T06:56:24 | 2020-08-06T21:38:42 | 2020-08-11T12:58:00 | 2020-08-13T06:56:23 | 2,427 | 0 | 0 | 0 | Python | false | false | import pandas as pd
import re
# & functions & #
def getTextBlock(srt_file):
""" make an array from srt file
# input: srt file
# return: list of strings"""
f = open(srt_file, 'r')
x = f.read().split('\n\n')
f.close()
return x
def srt_to_df(srt_file):
"""" make lists for the columns of dataFrame
# input: srt file
# return: 4 list of strings"""
start = list()
end = list()
text = list()
speaker = list()
text_block = getTextBlock(srt_file)
# separate the text to four column
for block in text_block:
if block.__contains__("<b><font"): # mark speaker with @$
temp = re.sub('<b><font face="Rockwell" color="#......">', '', block)
block = re.sub('</font></b>', '@$', temp)
if block.__contains__("<i>" or "</i>"): # delete irelevent data
block = re.sub('<i>|</i>', '', block)
data = block.split('\n') # split the string to time (data[1]) and text (all others)
splt_data1 = re.findall("..:..:..", data[1]) # find the start end the end time
# get start and end column
start.append(splt_data1[0])
end.append(splt_data1[1])
# get text & speaker column
text.append(data[2])
if len(data) > 3: # if the text is longer then one line
for i in range(3,len(data)):
x = text.pop()
text.append(x + " " + data[i])
temp2 = text.pop()
if temp2.__contains__("@$"):
temp3 = temp2.split('@$')
if temp2.__contains__("("):
temp3[0] = re.sub('\(.*\)', '', temp3[0])
speaker.append(temp3[0])
text.append(temp3[1])
else:
speaker.append('')
text.append(temp2)
return start, end, text, speaker
def srt_to_exel(srt_file, exel_file):
"""" make exel file from srt
# input: srt file
# return: None """
start, end, text, speaker = srt_to_df(srt_file)
df_xl = pd.DataFrame()
df_xl['start'] = start
df_xl['end'] = end
df_xl['text'] = text
df_xl['speaker'] = speaker
df_xl.to_excel(exel_file, index=False)
# main
srt_to_exel('srt_files/Batman.Begins.2005.720p.BluRay.x264. YTS.MX-English.srt', 'xl_files/batman1.xlsx')
# srt_to_exel('srt_files/Thor.Ragnarok.2017.WEB-DL.x264-FGT.srt', 'xl_files/thor.xlsx')
| UTF-8 | Python | false | false | 2,367 | py | 13 | srt_to_exel.py | 8 | 0.538657 | 0.52049 | 0 | 73 | 31.424658 | 105 |
cardinalX/First_project | 10,531,259,811,584 | 0a1da1d1b75d0307cde8518b4bd79b531a1ffa76 | 56c6957436d4d7e53067f3d7dcc14800cc54f1e1 | /client.py | 3b423203eabace3270375194185e81d77ddd2fdd | []
| no_license | https://github.com/cardinalX/First_project | cfcd1e08a62874a10d13ffb6fcea1d0fcc78c952 | bcee2241fdef73882806bba86fcdd42b210f8f54 | refs/heads/master | 2021-09-07T21:28:13.615171 | 2018-03-01T10:44:19 | 2018-03-01T10:44:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import socket
from struct import *
sock = socket.socket()
sock.connect(('127.0.0.1', 9090))
sock.send(bytes('hello world!', encoding='utf-8'))
data = sock.recv(1024)
sock.close()
print(data) | UTF-8 | Python | false | false | 193 | py | 3 | client.py | 3 | 0.694301 | 0.61658 | 0 | 11 | 16.636364 | 50 |
TnSoCob/test1 | 14,328,010,926,737 | 0b5b8375baa6bfd02b40d8fa03f6f99dd0b2c46c | 8009a56ce769e0f9a08cd8a17629699c268ef29a | /test1.py | aea9e76ed28b81ade9e0e8a0635bf28c51afb21a | [
"MIT"
]
| permissive | https://github.com/TnSoCob/test1 | ba710e1384b9bd4cbc8ecbeaf11fb5c2d41e26c2 | 226eb6ea84f98fd8c9b5605cc969dce97384d8a4 | refs/heads/master | 2020-04-27T07:51:01.289302 | 2019-03-06T14:02:47 | 2019-03-06T14:02:47 | 174,149,641 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | num1 = 1
num2 = 2
num3 = 3
num4 = 4
| UTF-8 | Python | false | false | 39 | py | 1 | test1.py | 1 | 0.512821 | 0.307692 | 0 | 7 | 4.571429 | 8 |
rongfengliang/rediSQL | 11,811,160,097,826 | 1cf288b84a6834dca5400326bb9408076f91b663 | 12b1efd56355aa773a98e8be58d4c9b5e3747f17 | /test/correctness/test.py | 8c0299e93c16529c4d6480d7a13772c875493f61 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | https://github.com/rongfengliang/rediSQL | 17c531fa716c30d2e9557870062993d04df683eb | 3d44ce63a44789eab77abb63fd490a4b5e08e290 | refs/heads/master | 2020-06-27T12:31:17.942331 | 2019-08-01T11:44:26 | 2019-08-01T11:44:26 | 199,955,231 | 1 | 1 | NOASSERTION | true | 2019-08-01T01:39:15 | 2019-08-01T01:39:15 | 2019-07-31T23:12:20 | 2019-07-31T22:35:13 | 16,506 | 0 | 0 | 0 | null | false | false | #!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import unittest
import os
import tempfile
import shutil
import time
import redis
from rmtest import ModuleTestCase
if "REDIS_MODULE_PATH" not in os.environ:
os.environ["REDIS_MODULE_PATH"] = "../../target/release/libredis_sql.so"
os.environ["RUST_BACKTRACE"] = "full"
class Table():
def __init__(self, redis, name, values, key = ""):
self.redis = redis
self.key = key
self.name = name
self.values = values
def __enter__(self):
create_table = "CREATE TABLE {} {}".format(self.name, self.values)
if self.key:
self.redis.client.execute_command("REDISQL.EXEC", self.key, create_table)
else:
self.redis.client.execute_command("REDISQL.EXEC", create_table)
def __exit__(self, type, value, traceback):
drop_table = "DROP TABLE {}".format(self.name)
if self.key:
self.redis.client.execute_command("REDISQL.EXEC", self.key, drop_table)
else:
self.redis.client.execute_command("REDISQL.EXEC", drop_table)
class DB():
def __init__(self, redis, key):
self.redis = redis
self.key = key
def __enter__(self):
self.redis.client.execute_command("REDISQL.CREATE_DB", self.key)
def __exit__(self, type, value, traceback):
self.redis.client.execute_command("DEL", self.key)
class TestRediSQLWithExec(ModuleTestCase('')):
def setUp(self):
self.disposable_redis = self.redis()
def tearDown(self):
pass
def exec_naked(self, *command):
return self.client.execute_command(*command)
def exec_cmd(self, *command):
return self.client.execute_command("REDISQL.EXEC", *command)
def create_db(self, key):
return self.client.execute_command("REDISQL.CREATE_DB", key)
def delete_db(self, key):
return self.client.execute_command("DEL", key)
class TestRediSQLExec(TestRediSQLWithExec):
def test_ping(self):
self.assertTrue(self.client.ping())
def test_create_table(self):
with DB(self, "A"):
done = self.exec_cmd("A", "CREATE TABLE test1 (A INTEGER);")
self.assertEquals(done, ["DONE", 0L])
done = self.exec_cmd("A", "DROP TABLE test1")
self.assertEquals(done, ["DONE", 0L])
def test_insert(self):
with DB(self, "B"):
with Table(self, "test2", "(A INTEGER)", key = "B"):
done = self.exec_cmd("B", "INSERT INTO test2 VALUES(2);")
self.assertEquals(done, ["DONE", 1L])
def test_select(self):
with DB(self, "C"):
with Table(self, "test3", "(A INTEGER)", key = "C"):
done = self.exec_cmd("C", "INSERT INTO test3 VALUES(2);")
self.assertEquals(done, ["DONE", 1L])
result = self.exec_cmd("C", "SELECT * from test3")
self.assertEquals(result, [[2]])
self.exec_cmd("C", "INSERT INTO test3 VALUES(3);")
result = self.exec_cmd("C", "SELECT * from test3 ORDER BY A")
self.assertEquals(result, [[2], [3]])
self.exec_cmd("C", "INSERT INTO test3 VALUES(4);")
result = self.exec_cmd("C", "SELECT * FROM test3 ORDER BY A")
self.assertEquals(result, [[2], [3], [4]])
def test_single_remove(self):
with DB(self, "D"):
with Table(self, "test4", "(A INTEGER)", key = "D"):
self.exec_cmd("D", "INSERT INTO test4 VALUES(2);")
self.exec_cmd("D", "INSERT INTO test4 VALUES(3);")
self.exec_cmd("D", "INSERT INTO test4 VALUES(4);")
result = self.exec_cmd("D", "SELECT * FROM test4 ORDER BY A")
self.assertEquals(result, [[2], [3], [4]])
self.exec_cmd("D", "DELETE FROM test4 WHERE A = 3;")
result = self.exec_cmd("D", "SELECT * FROM test4 ORDER BY A")
self.assertEquals(result, [[2], [4]])
def test_big_select(self):
elements = 50
with DB(self, "E"):
with Table(self, "test5", "(A INTERGER)", key = "E"):
pipe = self.client.pipeline(transaction=False)
for i in xrange(elements):
pipe.execute_command("REDISQL.EXEC", "E",
"INSERT INTO test5 VALUES({})".format(i))
pipe.execute()
result = self.exec_cmd("E", "SELECT * FROM test5 ORDER BY A")
self.assertEquals(result, [[x] for x in xrange(elements)])
def test_multiple_row(self):
with DB(self, "F"):
with Table(self, "test6", "(A INTEGER, B REAL, C TEXT)", key= "F"):
self.exec_cmd("F", "INSERT INTO test6 VALUES(1, 1.0, '1point1')")
self.exec_cmd("F", "INSERT INTO test6 VALUES(2, 2.0, '2point2')")
self.exec_cmd("F", "INSERT INTO test6 VALUES(3, 3.0, '3point3')")
self.exec_cmd("F", "INSERT INTO test6 VALUES(4, 4.0, '4point4')")
self.exec_cmd("F", "INSERT INTO test6 VALUES(5, 5.0, '5point5')")
result = self.exec_cmd("F", "SELECT A, B, C FROM test6 ORDER BY A")
result = [[A, float(B), C] for [A, B, C] in result]
self.assertEquals(result,
[[1L, 1.0, "1point1"], [2L, 2.0, '2point2'],
[3L, 3.0, '3point3'], [4L, 4.0, '4point4'],
[5L, 5.0, '5point5']])
def test_join(self):
with DB(self, "G"):
with Table(self, "testA", "(A INTEGER, B INTEGER)", key = "G"):
with Table(self, "testB", "(C INTEGER, D INTEGER)", key = "G"):
self.exec_cmd("G", "INSERT INTO testA VALUES(1, 2)")
self.exec_cmd("G", "INSERT INTO testA VALUES(3, 4)")
self.exec_cmd("G", "INSERT INTO testB VALUES(1, 2)")
self.exec_cmd("G", "INSERT INTO testB VALUES(3, 4)")
result = self.exec_cmd("G", "SELECT A, B, C, D FROM testA, testB WHERE A = C ORDER BY A")
self.assertEquals(result, [[1, 2, 1, 2], [3, 4, 3, 4]])
def runTest(self):
pass
class NoDefaultDB(TestRediSQLWithExec):
def test_that_we_need_a_key(self):
with self.assertRaises(redis.exceptions.ResponseError):
self.exec_cmd("SELECT 'foo';")
class TestRediSQLKeys(TestRediSQLWithExec):
def test_create_and_destroy_key(self):
ok = self.create_db("A_REDISQL")
self.assertEquals(ok, "OK")
keys = self.client.keys("A_REDISQL")
self.assertEquals(["A_REDISQL"], keys)
ok = self.delete_db("A_REDISQL")
keys = self.client.keys("A_REDISQL")
self.assertEquals([], keys)
def test_create_table_inside_key(self):
with DB(self, "A"):
done = self.exec_cmd("A", "CREATE TABLE t1 (A INTEGER);")
self.assertEquals(done, ["DONE", 0L])
done = self.exec_cmd("A", "DROP TABLE t1")
self.assertEquals(done, ["DONE", 0L])
def test_insert_into_table(self):
with DB(self, "B"):
with Table(self, "t2", "(A INTEGER, B INTEGER)", key = "B"):
done = self.exec_cmd("B", "INSERT INTO t2 VALUES(1,2)")
self.assertEquals(done, ["DONE", 1L])
result = self.exec_cmd("B", "SELECT * FROM t2")
self.assertEquals(result, [[1, 2]])
class TestMultipleInserts(TestRediSQLWithExec):
def test_insert_two_rows(self):
with DB(self, "M"):
with Table(self, "t1", "(A INTEGER, B INTEGER)", key = "M"):
done = self.exec_naked("REDISQL.EXEC", "M", "INSERT INTO t1 values(1, 2);")
self.assertEquals(done, ["DONE", 1L])
done = self.exec_naked("REDISQL.EXEC", "M", "INSERT INTO t1 values(3, 4),(5, 6);")
self.assertEquals(done, ["DONE", 2L])
done = self.exec_naked("REDISQL.EXEC", "M", "INSERT INTO t1 values(7, 8);")
self.assertEquals(done, ["DONE", 1L])
def test_multi_insert_same_statement(self):
with DB(self, "N"):
with Table(self, "t1", "(A INTEGER, B INTEGER)", key = "N"):
done = self.exec_naked("REDISQL.EXEC", "N", "INSERT INTO t1 values(1, 2); INSERT INTO t1 values(3, 4);")
self.assertEquals(done, ["DONE", 2L])
done = self.exec_naked("REDISQL.EXEC", "N", """BEGIN;
INSERT INTO t1 values(3, 4);
INSERT INTO t1 values(5, 6);
INSERT INTO t1 values(7, 8);
COMMIT;""")
self.assertEquals(done, ["DONE", 3L])
done = self.exec_naked("REDISQL.EXEC", "N", """BEGIN;
INSERT INTO t1 values(3, 4);
INSERT INTO t1 values(5, 6);
INSERT INTO t1 values(7, 8);
INSERT INTO t1 values(3, 4);
INSERT INTO t1 values(5, 6);
INSERT INTO t1 values(7, 8);
COMMIT;""")
self.assertEquals(done, ["DONE", 6L])
class TestJSON(TestRediSQLWithExec):
def test_multiple_insert_on_different_types(self):
with DB(self, "H"):
with Table(self, "j1", "(A text, B int)", key = "H"):
done = self.exec_naked("REDISQL.EXEC", "H", """BEGIN;
INSERT INTO j1 VALUES ('{\"foo\" : \"bar\"}', 1);
INSERT INTO j1 VALUES ('{\"foo\" : 3}', 2);
INSERT INTO j1 VALUES ('{\"foo\" : [1, 2, 3]}', 3);
INSERT INTO j1 VALUES ('{\"foo\" : {\"baz\" : [1, 2, 3]}}', 4);
COMMIT;""")
self.assertEquals(done, ["DONE", 4L])
result = self.exec_naked("REDISQL.EXEC", "H", "SELECT json_extract(A, '$.foo') FROM j1 ORDER BY B;")
self.assertEquals(result, [["bar"], [3], ["[1,2,3]"], ['{"baz":[1,2,3]}']])
class TestStatements(TestRediSQLWithExec):
def test_create_statement(self):
with DB(self, "A"):
with Table(self, "t1", "(A INTEGER)", key = "A"):
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "A", "insert", "insert into t1 values(?1);")
self.assertEquals(ok, "OK")
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "3")
self.assertEquals(done, ["DONE", 1L])
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "4")
self.assertEquals(done, ["DONE", 1L])
result = self.exec_cmd("A", "SELECT * FROM t1 ORDER BY A;")
self.assertEquals(result, [[3], [4]])
def test_multi_statement_single_bind(self):
with DB(self, "A"):
with Table(self, "t1", "(A INTEGER)", key = "A"):
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "A", "insert", "insert into t1 values(?1); insert into t1 values(?1 + 1);")
self.assertEquals(ok, "OK")
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "3")
self.assertEquals(done, ["DONE", 2L])
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "5")
self.assertEquals(done, ["DONE", 2L])
result = self.exec_cmd("A", "SELECT * FROM t1 ORDER BY A;")
self.assertEquals(result, [[3], [4], [5], [6]])
def test_multi_statement_multi_table_single_bind(self):
with DB(self, "A"):
with Table(self, "t1", "(A INTEGER)", key = "A"):
with Table(self, "t2", "(A INTEGER)", key = "A"):
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "A", "insert", "insert into t1 values(?1); insert into t2 values(?1 - 1);")
self.assertEquals(ok, "OK")
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "3")
self.assertEquals(done, ["DONE", 2L])
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "5")
self.assertEquals(done, ["DONE", 2L])
result = self.exec_cmd("A", "SELECT * FROM t1 ORDER BY A;")
self.assertEquals(result, [[3], [5]])
result = self.exec_cmd("A", "SELECT * FROM t2 ORDER BY A;")
self.assertEquals(result, [[2], [4]])
def test_multi_statement_different_bindings(self):
with DB(self, "A"):
with Table(self, "t1", "(A INTEGER)", key = "A"):
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "A", "insert", "insert into t1 values(?1); insert into t1 values(?2 + 1); select * from t1;")
self.assertEquals(ok, "OK")
result = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "3", "8")
self.assertEquals(result, [[3], [9]])
def test_update_statement(self):
with DB(self, "A"):
with Table(self, "t1", "(A INTEGER)", key = "A"):
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "A", "insert", "insert into t1 values(?1);")
self.assertEquals(ok, "OK")
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "3")
self.assertEquals(done, ["DONE", 1L])
ok = self.exec_naked("REDISQL.UPDATE_STATEMENT", "A", "insert", "insert into t1 values(?1 + 10001);")
self.assertEquals(ok, "OK")
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "4")
self.assertEquals(done, ["DONE", 1L])
result = self.exec_cmd("A", "SELECT * FROM t1 ORDER BY A;")
self.assertEquals(result, [[3], [10005]])
def test_rdb_persistency(self):
with DB(self, "A"):
with Table(self, "t1", "(A INTEGER)", key = "A"):
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "A", "insert", "insert into t1 values(?1);")
self.assertEquals(ok, "OK")
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "3")
self.assertEquals(done, ["DONE", 1L])
for _ in self.retry_with_reload():
pass
time.sleep(0.5)
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "4")
self.assertEquals(done, ["DONE", 1L])
result = self.exec_cmd("A", "SELECT * FROM t1 ORDER BY A;")
self.assertEquals(result, [[3], [4]])
def test_rdb_persistency_no_statements(self):
with DB(self, "A"):
with Table(self, "t1", "(A INTEGER)", key = "A"):
done = self.exec_cmd("A", "INSERT INTO t1 VALUES(5)")
self.assertEquals(done, ["DONE", 1L])
for _ in self.retry_with_reload():
pass
time.sleep(0.5)
done = self.exec_cmd("A", "INSERT INTO t1 VALUES(6)")
self.assertEquals(done, ["DONE", 1L])
result = self.exec_cmd("A", "SELECT * FROM t1 ORDER BY A;")
self.assertEquals(result, [[5], [6]])
def test_rdb_persistency_multiple_statements(self):
with DB(self, "A"):
with Table(self, "t1", "(A INTEGER)", key = "A"):
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "A", "insert", "insert into t1 values(?1);")
self.assertEquals(ok, "OK")
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "A", "insert più cento", "insert into t1 values(?1 + 100);")
self.assertEquals(ok, "OK")
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "3")
self.assertEquals(done, ["DONE", 1L])
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert più cento", "3")
self.assertEquals(done, ["DONE", 1L])
for _ in self.retry_with_reload():
pass
time.sleep(0.5)
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert", "4")
self.assertEquals(done, ["DONE", 1L])
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert più cento", "4")
self.assertEquals(done, ["DONE", 1L])
result = self.exec_cmd("A", "SELECT * FROM t1 ORDER BY A;")
self.assertEquals(result, [[3], [4], [103], [104]])
class TestSynchronous(TestRediSQLWithExec):
def test_exec(self):
with DB(self, "A"):
done = self.exec_naked("REDISQL.EXEC.NOW", "A", "CREATE TABLE test(a INT, b TEXT);")
self.assertEquals(done, ["DONE", 0L])
done = self.exec_naked("REDISQL.EXEC.NOW", "A", "INSERT INTO test VALUES(1, 'ciao'), (2, 'foo'), (100, 'baz');")
self.assertEquals(done, ["DONE", 3L])
result = self.exec_naked("REDISQL.EXEC.NOW", "A", "SELECT * FROM test ORDER BY a ASC")
self.assertEquals(result, [[1, 'ciao'], [2, 'foo'], [100, 'baz']])
def test_statements(self):
with DB(self, "A"):
with Table(self, "t1", "(A INTEGER)", key = "A"):
ok = self.exec_naked("REDISQL.CREATE_STATEMENT.NOW", "A", "insert+100", "INSERT INTO t1 VALUES(100 + ?1);")
self.assertEquals(ok, "OK")
done = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "insert+100", 1)
self.assertEquals(done, ["DONE", 1L])
done = self.exec_naked("REDISQL.EXEC_STATEMENT.NOW", "A", "insert+100", 9)
self.assertEquals(done, ["DONE", 1L])
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "A", "query-100", "SELECT A-100 FROM t1 ORDER BY A ASC;")
self.assertEquals(ok, "OK")
result = self.exec_naked("REDISQL.EXEC_STATEMENT", "A", "query-100")
self.assertEquals(result, [[1], [9]])
result = self.exec_naked("REDISQL.EXEC_STATEMENT.NOW", "A", "query-100")
self.assertEquals(result, [[1], [9]])
class TestRead(TestRediSQLWithExec):
def test_read(self):
with DB(self, "A"):
with Table(self, "t1", "(A INTEGER)", key = "A"):
done = self.exec_naked("REDISQL.EXEC", "A", "INSERT INTO t1 VALUES(4);")
result = self.exec_naked("REDISQL.QUERY", "A", "SELECT A FROM t1 LIMIT 1;")
self.assertEquals(result, [[4]])
def test_not_insert(self):
with DB(self, "B"):
with Table(self, "t1", "(A INTEGER)", key = "B"):
with self.assertRaises(redis.exceptions.ResponseError):
self.exec_naked("REDISQL.QUERY", "B", "INSERT INTO t1 VALUES(5);")
done = self.exec_naked("REDISQL.EXEC", "B", "CREATE TABLE test(a INT, b TEXT);")
self.assertEquals(done, ["DONE", 0L])
done = self.exec_naked("REDISQL.EXEC", "B", "INSERT INTO test VALUES(1, 'ciao'), (2, 'foo'), (100, 'baz');")
self.assertEquals(done, ["DONE", 3L])
result = self.exec_naked("REDISQL.QUERY", "B", "SELECT * FROM test ORDER BY a ASC")
self.assertEquals(result, [[1, 'ciao'], [2, 'foo'], [100, 'baz']])
class TestBruteHash(TestRediSQLWithExec):
def testSimple(self):
with DB(self, "B"):
catty = 5
done = self.exec_naked("REDISQL.EXEC", "B", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat TEXT, meow INT)")
self.assertEquals(done, ["DONE", 0L])
for i in xrange(catty):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
result = self.exec_naked("REDISQL.EXEC", "B", "SELECT rowid, cat, meow FROM cats")
self.assertEquals(catty, len(result))
self.assertTrue([0L, "cat:0", "0"] in result)
self.assertTrue([1L, "cat:1", "1"] in result)
self.assertTrue([2L, "cat:2", "2"] in result)
self.assertTrue([3L, "cat:3", "3"] in result)
self.assertTrue([4L, "cat:4", "4"] in result)
def testNullFields(self):
with DB(self, "C"):
done = self.exec_naked("REDISQL.EXEC", "C", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat, meow, kitten)")
for i in xrange(5):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
self.exec_naked("HSET", "cat:0" , "kitten", "2")
self.exec_naked("HSET", "cat:2" , "kitten", "4")
self.exec_naked("HSET", "cat:4" , "kitten", "6")
result = self.exec_naked("REDISQL.EXEC", "C", "SELECT rowid, cat, meow, kitten FROM cats")
self.assertEquals(5, len(result))
self.assertTrue([0L, "cat:0", "0", "2"] in result)
self.assertTrue([1L, "cat:1", "1", None] in result)
self.assertTrue([2L, "cat:2", "2", "4"] in result)
self.assertTrue([3L, "cat:3", "3", None] in result)
self.assertTrue([4L, "cat:4", "4", "6"] in result)
def test100(self):
with DB(self, "A"):
catty = 100
done = self.exec_naked("REDISQL.EXEC", "A", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat TEXT, meow INT)")
self.assertEquals(done, ["DONE", 0L])
for i in xrange(catty):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
time.sleep(0.5)
result = self.exec_naked("REDISQL.EXEC", "A", "SELECT * FROM cats")
self.assertEquals(catty, len(result))
def test_rdb_persistency(self):
with DB(self, "Y"):
done = self.exec_naked("REDISQL.EXEC", "Y", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat, meow)")
for i in xrange(5):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
for _ in self.retry_with_reload():
pass
time.sleep(0.5)
result = self.exec_naked("REDISQL.EXEC", "Y", "SELECT rowid, cat, meow FROM cats")
self.assertEquals(5, len(result))
self.assertTrue([0L, "cat:0", "0"] in result)
self.assertTrue([1L, "cat:1", "1"] in result)
self.assertTrue([2L, "cat:2", "2"] in result)
self.assertTrue([3L, "cat:3", "3"] in result)
self.assertTrue([4L, "cat:4", "4"] in result)
def test_statement(self):
with DB(self, "D"):
done = self.exec_naked("REDISQL.EXEC", "D", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat, meow)")
self.assertEquals(done, ["DONE", 0L])
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "D", "select_all", "SELECT rowid, cat, meow FROM cats")
self.assertEquals(ok, "OK")
for i in xrange(5):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
result = self.exec_naked("REDISQL.EXEC_STATEMENT", "D", "select_all")
self.assertEquals(5, len(result))
self.assertTrue([0L, "cat:0", "0"] in result)
self.assertTrue([1L, "cat:1", "1"] in result)
self.assertTrue([2L, "cat:2", "2"] in result)
self.assertTrue([3L, "cat:3", "3"] in result)
self.assertTrue([4L, "cat:4", "4"] in result)
def test_statement_after_rdb_load(self):
with DB(self, "E"):
done = self.exec_naked("REDISQL.EXEC", "E", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat, meow)")
self.assertEquals(done, ["DONE", 0L])
ok = self.exec_naked("REDISQL.CREATE_STATEMENT", "E", "select_all", "SELECT rowid, cat, meow FROM cats")
self.assertEquals(ok, "OK")
for i in xrange(5):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
for _ in self.retry_with_reload():
pass
time.sleep(0.5)
result = self.exec_naked("REDISQL.EXEC_STATEMENT", "E", "select_all")
self.assertEquals(5, len(result))
self.assertTrue([0L, "cat:0", "0"] in result)
self.assertTrue([1L, "cat:1", "1"] in result)
self.assertTrue([2L, "cat:2", "2"] in result)
self.assertTrue([3L, "cat:3", "3"] in result)
self.assertTrue([4L, "cat:4", "4"] in result)
class TestBruteHashSyncronous(TestRediSQLWithExec):
def testSimpleNow(self):
with DB(self, "B"):
catty = 5
done = self.exec_naked("REDISQL.EXEC.NOW", "B", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat TEXT, meow INT)")
self.assertEquals(done, ["DONE", 0L])
for i in xrange(catty):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
result = self.exec_naked("REDISQL.EXEC.NOW", "B", "SELECT rowid, cat, meow FROM cats")
self.assertEquals(catty, len(result))
self.assertTrue([0L, "cat:0", "0"] in result)
self.assertTrue([1L, "cat:1", "1"] in result)
self.assertTrue([2L, "cat:2", "2"] in result)
self.assertTrue([3L, "cat:3", "3"] in result)
self.assertTrue([4L, "cat:4", "4"] in result)
def testNullFields(self):
with DB(self, "C"):
done = self.exec_naked("REDISQL.EXEC.NOW", "C", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat, meow, kitten)")
for i in xrange(5):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
self.exec_naked("HSET", "cat:0" , "kitten", "2")
self.exec_naked("HSET", "cat:2" , "kitten", "4")
self.exec_naked("HSET", "cat:4" , "kitten", "6")
result = self.exec_naked("REDISQL.EXEC.NOW", "C", "SELECT rowid, cat, meow, kitten FROM cats")
self.assertEquals(5, len(result))
self.assertTrue([0L, "cat:0", "0", "2"] in result)
self.assertTrue([1L, "cat:1", "1", None] in result)
self.assertTrue([2L, "cat:2", "2", "4"] in result)
self.assertTrue([3L, "cat:3", "3", None] in result)
self.assertTrue([4L, "cat:4", "4", "6"] in result)
def test100_now(self):
with DB(self, "A"):
catty = 100
done = self.exec_naked("REDISQL.EXEC.NOW", "A", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat TEXT, meow INT)")
self.assertEquals(done, ["DONE", 0L])
for i in xrange(catty):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
result = self.exec_naked("REDISQL.EXEC.NOW", "A", "SELECT * FROM cats")
self.assertEquals(catty, len(result))
def test_rdb_persistency(self):
with DB(self, "A"):
done = self.exec_naked("REDISQL.EXEC.NOW", "A", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat, meow)")
for i in xrange(5):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
for _ in self.retry_with_reload():
pass
time.sleep(0.5)
result = self.exec_naked("REDISQL.EXEC.NOW", "A", "SELECT rowid, cat, meow FROM cats")
self.assertEquals(5, len(result))
self.assertTrue([0L, "cat:0", "0"] in result)
self.assertTrue([1L, "cat:1", "1"] in result)
self.assertTrue([2L, "cat:2", "2"] in result)
self.assertTrue([3L, "cat:3", "3"] in result)
self.assertTrue([4L, "cat:4", "4"] in result)
def test_statement(self):
with DB(self, "D"):
done = self.exec_naked("REDISQL.EXEC.NOW", "D", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat, meow)")
self.assertEquals(done, ["DONE", 0L])
ok = self.exec_naked("REDISQL.CREATE_STATEMENT.NOW", "D", "select_all", "SELECT rowid, cat, meow FROM cats")
self.assertEquals(ok, "OK")
for i in xrange(5):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
result = self.exec_naked("REDISQL.EXEC_STATEMENT.NOW", "D", "select_all")
self.assertEquals(5, len(result))
self.assertTrue([0L, "cat:0", "0"] in result)
self.assertTrue([1L, "cat:1", "1"] in result)
self.assertTrue([2L, "cat:2", "2"] in result)
self.assertTrue([3L, "cat:3", "3"] in result)
self.assertTrue([4L, "cat:4", "4"] in result)
def test_statement_after_rdb_load(self):
with DB(self, "E"):
done = self.exec_naked("REDISQL.EXEC.NOW", "E", "CREATE VIRTUAL TABLE cats USING REDISQL_TABLES_BRUTE_HASH(cat, meow)")
self.assertEquals(done, ["DONE", 0L])
ok = self.exec_naked("REDISQL.CREATE_STATEMENT.NOW", "E", "select_all", "SELECT rowid, cat, meow FROM cats")
self.assertEquals(ok, "OK")
for i in xrange(5):
self.exec_naked("HSET", "cat:" + str(i), "meow", i)
for _ in self.retry_with_reload():
pass
time.sleep(0.5)
result = self.exec_naked("REDISQL.EXEC_STATEMENT.NOW", "E", "select_all")
self.assertEquals(5, len(result))
self.assertTrue([0L, "cat:0", "0"] in result)
self.assertTrue([1L, "cat:1", "1"] in result)
self.assertTrue([2L, "cat:2", "2"] in result)
self.assertTrue([3L, "cat:3", "3"] in result)
self.assertTrue([4L, "cat:4", "4"] in result)
class TestCopy(TestRediSQLWithExec):
def test_copy_mem_from_mem(self):
done = self.exec_naked("REDISQL.CREATE_DB", "DB1")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.CREATE_DB", "DB2A")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.EXEC", "DB1", "CREATE TABLE foo(a INT);")
self.assertEquals(done, ["DONE", 0L])
for i in xrange(10):
done = self.exec_naked("REDISQL.EXEC", "DB1", "INSERT INTO foo VALUES({})".format(i))
self.assertEquals(done, ["DONE", 1L])
done = self.exec_naked("REDISQL.COPY", "DB1", "DB2A")
result = self.exec_naked("REDISQL.QUERY", "DB1", "SELECT a FROM foo ORDER BY a")
self.assertEquals(result, [[0L], [1L], [2L], [3L], [4L], [5L], [6L], [7L], [8L], [9L]])
result = self.exec_naked("REDISQL.QUERY", "DB2A", "SELECT a FROM foo ORDER BY a")
self.assertEquals(result, [[0L], [1L], [2L], [3L], [4L], [5L], [6L], [7L], [8L], [9L]])
def test_statements_copy_mem_from_mem(self):
done = self.exec_naked("REDISQL.CREATE_DB", "DB1")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.CREATE_DB", "DB2B")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.CREATE_STATEMENT", "DB1", "select1", "SELECT 1;")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.COPY", "DB1", "DB2B")
self.assertEquals(done, "OK")
result = self.exec_naked("REDISQL.QUERY_STATEMENT", "DB1", "select1")
self.assertEquals(result, [[1L]])
result = self.exec_naked("REDISQL.QUERY_STATEMENT", "DB2B", "select1")
self.assertEquals(result, [[1L]])
def test_double_copy(self):
done = self.exec_naked("REDISQL.CREATE_DB", "DB1")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.CREATE_DB", "DB2C")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.CREATE_STATEMENT", "DB1", "select1", "SELECT 1;")
self.assertEquals(done, "OK")
first_copy = self.exec_naked("REDISQL.COPY", "DB1", "DB2C")
self.assertEquals(first_copy, "OK")
result = self.exec_naked("REDISQL.QUERY_STATEMENT", "DB1", "select1")
self.assertEquals(result, [[1L]])
second_copy = self.exec_naked("REDISQL.COPY", "DB1", "DB2C")
self.assertEquals(second_copy, "OK")
result = self.exec_naked("REDISQL.QUERY_STATEMENT", "DB1", "select1")
self.assertEquals(result, [[1L]])
result = self.exec_naked("REDISQL.QUERY_STATEMENT", "DB2C", "select1")
self.assertEquals(result, [[1L]])
class TestCopySyncronous(TestRediSQLWithExec):
def test_copy_now_mem_from_mem(self):
done = self.exec_naked("REDISQL.CREATE_DB", "DB1")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.CREATE_DB", "DB2")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.EXEC", "DB1", "CREATE TABLE foo(a INT);")
self.assertEquals(done, ["DONE", 0L])
for i in xrange(10):
done = self.exec_naked("REDISQL.EXEC", "DB1", "INSERT INTO foo VALUES({})".format(i))
self.assertEquals(done, ["DONE", 1L])
done = self.exec_naked("REDISQL.COPY.NOW", "DB1", "DB2")
result = self.exec_naked("REDISQL.QUERY", "DB1", "SELECT a FROM foo ORDER BY a")
self.assertEquals(result, [[0L], [1L], [2L], [3L], [4L], [5L], [6L], [7L], [8L], [9L]])
result = self.exec_naked("REDISQL.QUERY", "DB2", "SELECT a FROM foo ORDER BY a")
self.assertEquals(result, [[0L], [1L], [2L], [3L], [4L], [5L], [6L], [7L], [8L], [9L]])
def test_statements_copy_now_mem_from_mem(self):
done = self.exec_naked("REDISQL.CREATE_DB", "DB1")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.CREATE_DB", "DB2")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.CREATE_STATEMENT", "DB1", "select1", "SELECT 1;")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.COPY.NOW", "DB1", "DB2")
self.assertEquals(done, "OK")
result = self.exec_naked("REDISQL.QUERY_STATEMENT", "DB1", "select1")
self.assertEquals(result, [[1L]])
result = self.exec_naked("REDISQL.QUERY_STATEMENT", "DB2", "select1")
self.assertEquals(result, [[1L]])
def test_double_copy_now(self):
done = self.exec_naked("REDISQL.CREATE_DB", "DB1")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.CREATE_DB", "DB2")
self.assertEquals(done, "OK")
done = self.exec_naked("REDISQL.CREATE_STATEMENT", "DB1", "select1", "SELECT 1;")
self.assertEquals(done, "OK")
first_copy = self.exec_naked("REDISQL.COPY.NOW", "DB1", "DB2")
self.assertEquals(first_copy, "OK")
result = self.exec_naked("REDISQL.QUERY_STATEMENT", "DB1", "select1")
self.assertEquals(result, [[1L]])
second_copy = self.exec_naked("REDISQL.COPY.NOW", "DB1", "DB2")
self.assertEquals(second_copy, "OK")
result = self.exec_naked("REDISQL.QUERY_STATEMENT", "DB1", "select1")
self.assertEquals(result, [[1L]])
result = self.exec_naked("REDISQL.QUERY_STATEMENT", "DB2", "select1")
self.assertEquals(result, [[1L]])
class TestBigInt(TestRediSQLWithExec):
def test_big_int(self):
with DB(self, "A"):
done = self.exec_naked("REDISQL.EXEC", "A", "CREATE TABLE ip_to_asn(start INT8, end INT8, asn int, hosts int8)")
self.assertEquals(done, ["DONE", 0L])
done = self.exec_naked("REDISQL.EXEC", "A", "insert into ip_to_asn values (2883484276228096000, 2883484280523063295, 265030, 4294967295)")
self.assertEquals(done, ["DONE", 1L])
result = self.exec_naked("REDISQL.EXEC", "A", "SELECT * FROM ip_to_asn;")
self.assertEquals(result, [
[
2883484276228096000,
2883484280523063295,
265030,
4294967295]
])
class TestStreams(TestRediSQLWithExec):
def test_stream_query(self):
with DB(self, "A"):
total_len = 513
done = self.exec_naked("REDISQL.EXEC", "A", "CREATE TABLE foo(a int, b string, c int);")
self.assertEquals(done, ["DONE", 0L])
for i in xrange(total_len):
insert_stmt = "INSERT INTO foo VALUES({}, '{}', {})".format(i, "bar", i+1)
done = self.exec_naked("REDISQL.EXEC", "A", insert_stmt)
self.assertEquals(done, ["DONE", 1L])
result = self.exec_naked("REDISQL.QUERY.INTO", "{A}:1", "A", "SELECT * FROM foo")
self.assertEquals(result[0][0], "{A}:1")
self.assertEquals(result[0][3], 513)
result = self.exec_naked("XRANGE", "{A}:1", "-", "+")
self.assertEquals(len(result), total_len)
for i, row in enumerate(result):
self.assertEquals(row[1], ['int:a', str(i), 'text:b', "bar", 'int:c', str(i+1)])
def test_stream_query_statement(self):
with DB(self, "B"):
total_len = 513
done = self.exec_naked("REDISQL.EXEC", "B", "CREATE TABLE foo(a int, b string, c int);")
self.assertEquals(done, ["DONE", 0L])
for i in xrange(total_len):
insert_stmt = "INSERT INTO foo VALUES({}, '{}', {})".format(i, "bar", i-1)
done = self.exec_naked("REDISQL.EXEC", "B", insert_stmt)
self.assertEquals(done, ["DONE", 1L])
done = self.exec_naked("REDISQL.CREATE_STATEMENT", "B", "select_all", "SELECT * FROM foo;")
self.assertEquals(done, "OK")
result = self.exec_naked("REDISQL.QUERY_STATEMENT.INTO",
"{B}:1", "B", "select_all")
self.assertEquals(result[0][0], "{B}:1")
self.assertEquals(result[0][3], 513)
result = self.exec_naked("XRANGE", "{B}:1", "-", "+")
self.assertEquals(len(result), total_len)
for i, row in enumerate(result):
self.assertEquals(row[1], ['int:a', str(i), 'text:b', "bar", 'int:c', str(i-1)])
class TestStreamsSynchronous(TestRediSQLWithExec):
def test_stream_query(self):
with DB(self, "A"):
total_len = 513
done = self.exec_naked("REDISQL.EXEC.NOW", "A", "CREATE TABLE foo(a int, b string, c int);")
self.assertEquals(done, ["DONE", 0L])
for i in xrange(total_len):
insert_stmt = "INSERT INTO foo VALUES({}, '{}', {})".format(i, "bar", i+1)
done = self.exec_naked("REDISQL.EXEC.NOW", "A", insert_stmt)
self.assertEquals(done, ["DONE", 1L])
result = self.exec_naked("REDISQL.QUERY.INTO.NOW", "{A}:1", "A", "SELECT * FROM foo")
self.assertEquals(result[0][0], "{A}:1")
self.assertEquals(result[0][3], 513)
result = self.exec_naked("XRANGE", "{A}:1", "-", "+")
self.assertEquals(len(result), total_len)
for i, row in enumerate(result):
self.assertEquals(row[1], ['int:a', str(i), 'text:b', "bar", 'int:c', str(i+1)])
def test_stream_query_statement(self):
with DB(self, "B"):
total_len = 513
done = self.exec_naked("REDISQL.EXEC.NOW", "B", "CREATE TABLE foo(a int, b string, c int);")
self.assertEquals(done, ["DONE", 0L])
for i in xrange(total_len):
insert_stmt = "INSERT INTO foo VALUES({}, '{}', {})".format(i, "bar", i-1)
done = self.exec_naked("REDISQL.EXEC.NOW", "B", insert_stmt)
self.assertEquals(done, ["DONE", 1L])
done = self.exec_naked("REDISQL.CREATE_STATEMENT.NOW", "B", "select_all", "SELECT * FROM foo;")
self.assertEquals(done, "OK")
result = self.exec_naked("REDISQL.QUERY_STATEMENT.INTO.NOW",
"{B}:1", "B", "select_all")
self.assertEquals(result[0][0], "{B}:1")
self.assertEquals(result[0][3], 513)
result = self.exec_naked("XRANGE", "{B}:1", "-", "+")
self.assertEquals(len(result), total_len)
for i, row in enumerate(result):
self.assertEquals(row[1], ['int:a', str(i), 'text:b', "bar", 'int:c', str(i-1)])
class TestFilePersistency(TestRediSQLWithExec):
def test_creation_rdb_file(self):
path = tempfile.mkdtemp()
ok = self.exec_naked("REDISQL.CREATE_DB", "A", path + "/foo.sqlite")
self.assertEquals(ok, "OK")
for _ in self.retry_with_reload():
pass
time.sleep(0.5)
shutil.rmtree(path)
self.assertTrue(True)
def test_storage_of_data(self):
path = tempfile.mkdtemp()
ok = self.exec_naked("REDISQL.CREATE_DB", "B", path + "/foo.sqlite")
self.assertEquals(ok, "OK")
done = self.exec_naked("REDISQL.EXEC", "B", "CREATE TABLE bar(a,b);")
self.assertEquals(done, ["DONE", 0L])
done = self.exec_naked("REDISQL.EXEC", "B", "INSERT INTO bar VALUES(1,2);")
self.assertEquals(done, ["DONE", 1L])
for _ in self.retry_with_reload():
pass
time.sleep(0.5)
result = self.exec_naked("REDISQL.QUERY", "B", "SELECT * FROM bar;")
self.assertEquals(result, [[1, 2]])
shutil.rmtree(path)
self.assertTrue(True)
def test_without_file(self):
path = tempfile.mkdtemp()
ok = self.exec_naked("REDISQL.CREATE_DB", "B", path + "/foo.sqlite")
self.assertEquals(ok, "OK")
done = self.exec_naked("REDISQL.EXEC", "B", "CREATE TABLE bar(a,b);")
self.assertEquals(done, ["DONE", 0L])
done = self.exec_naked("REDISQL.EXEC", "B", "INSERT INTO bar VALUES(1,2);")
self.assertEquals(done, ["DONE", 1L])
os.remove(path + "/foo.sqlite")
self.assertFalse(os.path.isfile(path + "/foo.sqlite"))
for _ in self.retry_with_reload():
pass
time.sleep(0.5)
result = self.exec_naked("REDISQL.QUERY", "B", "SELECT * FROM bar;")
self.assertEquals(result, [[1, 2]])
self.assertTrue(os.path.isfile(path + "/foo.sqlite"))
shutil.rmtree(path)
self.assertTrue(True)
class TestNullTerminatedStrings(TestRediSQLWithExec):
def test_null_terminated(self):
with DB(self, "NULL"):
one = self.exec_naked("REDISQL.EXEC", "NULL", "SELECT 1" + b'\x00')
self.assertEquals(one, [[1]])
class TestBlankAfterSemicolon(TestRediSQLWithExec):
def test_whitespace_after_semicolon(self):
with DB(self, "NULL"):
one = self.exec_naked("REDISQL.EXEC", "NULL", "SELECT 1; ")
self.assertEquals(one, [[1]])
def test_newline_after_semicolon(self):
with DB(self, "NULL"):
one = self.exec_naked("REDISQL.EXEC", "NULL", "SELECT 1;\n")
self.assertEquals(one, [[1]])
def test_mix_after_semicolon(self):
with DB(self, "NULL"):
one = self.exec_naked("REDISQL.EXEC", "NULL", "SELECT 1; \n ")
self.assertEquals(one, [[1]])
def test_whitespace_after_semicolon_then_query(self):
with DB(self, "NULL"):
one = self.exec_naked("REDISQL.EXEC", "NULL", "SELECT 1; SELECT 2;")
self.assertEquals(one, [[2]])
def test_newline_after_semicolon_then_query(self):
with DB(self, "NULL"):
one = self.exec_naked("REDISQL.EXEC", "NULL", "SELECT 1;\nSELECT 2;")
self.assertEquals(one, [[2]])
class TestWithNullChars(TestRediSQLWithExec):
def test_with_null_at_the_end(self):
with DB(self, 'A'):
self.assertRaises(redis.ResponseError, self.exec_naked, "REDISQL.EXEC", "A", "SELECT \0 1;")
with DB(self, 'B'):
self.assertRaises(redis.ResponseError, self.exec_naked, "REDISQL.EXEC", "A", "SELECT 1;\0")
if __name__ == '__main__':
unittest.main()
| UTF-8 | Python | false | false | 40,498 | py | 54 | test.py | 20 | 0.580862 | 0.556958 | 0.000025 | 936 | 42.262821 | 150 |
finben/djattendance | 9,526,237,483,787 | af1bef0ed8c49e234c8f596696fc9bbd14bd0c19 | 56b50181fc9b23afd78013c1e7a32be319ad634b | /ap/ap/views.py | 3f1ceb3e0d93f17ce4289c925ca755790ed30927 | []
| no_license | https://github.com/finben/djattendance | c5a7d768251dac60634cf39888683a83a074a2e3 | 0758da4a5e93115a369f7a9f34ea0a0f1a95f9ac | refs/heads/dev | 2021-05-20T09:12:19.147808 | 2019-11-15T19:52:15 | 2019-11-15T19:52:15 | 94,934,059 | 0 | 0 | null | true | 2017-06-20T20:52:39 | 2017-06-20T20:52:38 | 2017-03-25T16:37:18 | 2017-06-18T02:39:35 | 162,896 | 0 | 0 | 0 | null | null | null | import json
from datetime import date
from announcements.notifications import get_announcements, get_popups
from aputils.trainee_utils import is_TA, is_trainee, trainee_from_user
from aputils.utils import WEEKDAY_CODES
from bible_tracker.models import (EMPTY_WEEKLY_STATUS, UNFINALIZED_STR,
BibleReading)
from bible_tracker.views import EMPTY_WEEK_CODE_QUERY
from dailybread.models import Portion
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.http import HttpResponse
from django.shortcuts import render
from house_requests.models import MaintenanceRequest
from services.models import WeekSchedule, Worker
from terms.models import FIRST_WEEK, LAST_WEEK, Term
@login_required
def home(request):
user = request.user
trainee = trainee_from_user(user)
worker = None
# Set default values
current_week = 19
weekly_status = EMPTY_WEEKLY_STATUS
finalized_str = UNFINALIZED_STR
designated_list = []
assigned_list = []
service_day = []
# Default for Daily Bible Reading
current_term = Term.current_term()
term_id = current_term.id
if is_trainee(user):
worker = Worker.objects.get(trainee=user)
if request.GET.get('week_schedule'):
current_week = request.GET.get('week_schedule')
current_week = int(current_week)
current_week = current_week if current_week < LAST_WEEK else LAST_WEEK
current_week = current_week if current_week > FIRST_WEEK else FIRST_WEEK
cws = WeekSchedule.get_or_create_week_schedule(trainee, current_week)
else:
# Do not set as user input.
current_week = Term.current_term().term_week_of_date(date.today())
cws = WeekSchedule.get_or_create_week_schedule(trainee, current_week)
# try:
# # Do not set as user input.
# current_week = Term.current_term().term_week_of_date(date.today())
# cws = WeekSchedule.get_or_create_week_schedule(trainee, current_week)
# except ValueError:
# cws = WeekSchedule.get_or_create_current_week_schedule(trainee)
term_week_code = str(term_id) + "_" + str(current_week)
try:
trainee_bible_reading = BibleReading.objects.get(trainee=user)
except ObjectDoesNotExist:
trainee_bible_reading = BibleReading(
trainee=trainee_from_user(user),
weekly_reading_status={term_week_code: EMPTY_WEEK_CODE_QUERY},
books_read={})
trainee_bible_reading.save()
except MultipleObjectsReturned:
return HttpResponse('Multiple bible reading records found for trainee!')
if term_week_code in trainee_bible_reading.weekly_reading_status:
weekly_reading = trainee_bible_reading.weekly_reading_status[term_week_code]
json_weekly_reading = json.loads(weekly_reading)
weekly_status = str(json_weekly_reading['status'])
finalized_str = str(json_weekly_reading['finalized'])
worker_assignments = worker.assignments.filter(week_schedule=cws)
designated_list = list(service.encode("utf-8") for service in worker_assignments.filter(service__category__name="Designated Services").values_list('service__name', flat=True))
assigned_list = list(service.encode("utf-8") for service in worker_assignments.exclude(service__category__name="Designated Services").values_list('service__name', flat=True))
service_day = list(worker_assignments.exclude(service__category__name="Designated Services").values_list('service__weekday', flat=True))
data = {
'daily_nourishment': Portion.today(),
'user': user,
'worker': worker,
'isTrainee': is_trainee(user),
'trainee_info': BibleReading.weekly_statistics,
'current_week': current_week,
'weekly_status': weekly_status,
'weeks': Term.all_weeks_choices(),
'finalized': finalized_str,
'weekday_codes': json.dumps(WEEKDAY_CODES),
'service_day': json.dumps(service_day),
'assigned_list': json.dumps(assigned_list),
'designated_list': json.dumps(designated_list),
}
notifications = get_announcements(request)
for notification in notifications:
tag, content = notification
messages.add_message(request, tag, content)
data['popups'] = get_popups(request)
if is_trainee(user):
trainee = trainee_from_user(user)
# Bible Reading progress bar
trainee_bible_reading = BibleReading.objects.filter(trainee=trainee).first()
if trainee_bible_reading is None:
data['bible_reading_progress'] = 0
else:
_, year_progress = BibleReading.calcBibleReadingProgress(trainee_bible_reading, user)
data['bible_reading_progress'] = year_progress
# condition for maintenance brothers
elif is_TA(user) and user.has_group(['facility_maintenance']) and user.groups.all().count() == 1:
data['house_requests'] = MaintenanceRequest.objects.all()
data['request_status'] = MaintenanceRequest.STATUS
return render(request, 'index.html', context=data)
def custom404errorview(request):
ctx = {
'image_path': 'img/404error.png',
'page_title': 'Page Not Found'
}
return render(request, 'error.html', context=ctx)
def custom500errorview(request):
ctx = {
'image_path': 'img/500error.png',
'page_title': 'Internal Server Error'
}
return render(request, 'error.html', context=ctx)
def custom502errorview(request):
ctx = {
'image_path': 'img/502error.png',
'page_title': 'Bad Gateway Error'
}
return render(request, 'error.html', context=ctx)
def custom503errorview(request):
ctx = {
'image_path': 'img/503error.png',
'page_title': 'Service Unavailable'
}
return render(request, 'error.html', context=ctx)
def custom504errorview(request):
ctx = {
'image_path': 'img/504error.png',
'page_title': 'Gateway Timeout'
}
return render(request, 'error.html', context=ctx)
def printerinstructions(request):
ctx = {
'image_path': 'img/printer.jpg',
'page_title': 'Printer Instructions',
}
return render(request, 'printer.html', context=ctx)
| UTF-8 | Python | false | false | 6,087 | py | 697 | views.py | 393 | 0.704616 | 0.698702 | 0 | 170 | 34.805882 | 179 |
Amenable-C/Python_practice | 11,982,958,776,729 | 70a91b7c4da4c25b9c0877b56d6585020d9d6e68 | 2bf7e12a5694070938adbba3feb2db6e39443bd5 | /baseballGame.py | 37419ccc5f76dfdce8e4f275e4837513b550e28f | []
| no_license | https://github.com/Amenable-C/Python_practice | 1e8c97e69ce7cbbe0b787340bf5be29894a94e14 | c95ea4f1213b0a678324cc0466701348fb12c54c | refs/heads/master | 2023-06-01T22:47:40.169598 | 2021-06-15T14:33:27 | 2021-06-15T14:33:27 | 369,830,841 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Baseball game
import random
fix = []
n = 0
while n < 3:
fix.append(random.randint(0,9))
n = n + 1
#print(fix)
trial = 0
while True:
trial = trial + 1
guess = input("Guess three numbers: ")
guessS = guess.split(" ")
#print(guessS)
s = 0
b = 0
for i in range(0, 3):
if fix[i] == int(guessS[i]):
s = s + 1
for i in range(0, 3):
for k in range(0, 3):
if fix[i] == int(guessS[k]) and i != k :
b = b + 1
print("%dS %dB" %(s, b))
if s == 3:
break
print("Congratulations!")
print("You won with %d trials" %trial) | UTF-8 | Python | false | false | 568 | py | 43 | baseballGame.py | 43 | 0.535211 | 0.503521 | 0 | 34 | 15.735294 | 46 |
takumiw/AtCoder | 6,846,177,905,449 | f1c3d9aaef09af83bc13e244a464f00acfa5b6d0 | 1885e952aa4a89f8b417b4c2e70b91bf1df887ff | /ABC166/D.py | 16b66cf763e4626445d51b46b7039501778fc81d | []
| no_license | https://github.com/takumiw/AtCoder | 01ed45b4d537a42e1120b1769fe4eff86a8e4406 | 23b9c89f07db8dd5b5345d7b40a4bae6762b2119 | refs/heads/master | 2021-07-10T12:01:32.401438 | 2020-06-27T14:07:17 | 2020-06-27T14:07:17 | 158,206,535 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import sys
readline = sys.stdin.readline
def main():
X = int(readline())
for a in range(-118, 120):
for b in range(-118, 120):
if a ** 5 - b ** 5 == X:
print(a, b)
return
if __name__ == '__main__':
main() | UTF-8 | Python | false | false | 270 | py | 488 | D.py | 486 | 0.444444 | 0.392593 | 0 | 13 | 19.846154 | 36 |
ForeignTrade/ForeignTrade | 6,451,040,909,637 | 60a7e9b444506858c74b4c230985b50c51c14552 | 1d3f2097ea88327c63ed9df6670c6ca8e4f1aa5c | /ForeignTrade/headquarters/finance/adminx.py | 11b57d8d48ede8c24425948525bf463fbf6063fb | []
| no_license | https://github.com/ForeignTrade/ForeignTrade | d2c957a8a953f0933b80c3123cf257d43244d734 | 02f33356c73dd71cdd881e17d8423edf9faf342e | refs/heads/master | 2020-04-16T01:23:02.731106 | 2019-08-07T08:37:24 | 2019-08-07T08:37:24 | 165,171,126 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import xadmin
from finance.models import ExchangeRate
from sales.models import CollectionPlan
class ExchangeRateAdmin(object):
model_icon = 'fa fa-dollar'
list_display = ['currency','type','date','exchange_rate']
search_fields = ['currency','type']
list_filter = ['currency','type','date']
relfield_style = 'fk_ajax'
xadmin.site.register(ExchangeRate,ExchangeRateAdmin)
| UTF-8 | Python | false | false | 401 | py | 159 | adminx.py | 134 | 0.708229 | 0.708229 | 0 | 18 | 21.111111 | 61 |
CarlaSobico/EjerciciosLabo | 15,650,860,827,836 | 78c3055eeeab6a34cbe9114f8646552162b7d4d7 | 11a1bc5971d77c16f5690835c1e3bae74a105df0 | /main2.py | 373e065b504374fd1f412078a3bfc54b7d0cf65e | []
| no_license | https://github.com/CarlaSobico/EjerciciosLabo | 48f28d959133786afd66b2c33601c717d01a39fd | fe593fe18db55f56e2d1f73e4453f38fe0c8e3e6 | refs/heads/master | 2020-05-03T00:06:03.176859 | 2019-06-07T17:47:05 | 2019-06-07T17:47:05 | 178,300,344 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import math as m
import scipy as sci
from scipy import signal
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.fftpack import ifft
from scipy.fftpack import fftshift
import pylab as pl
k1 = 0.19 * 10e12
k2 = -1.9 * 10e6
fi0 = 0
fs = 50e6
#x=np.arange(N) / float(fs)
x=np.r_[0:(10e-6-1/fs):1/(fs)]
print(len(x))
x2=np.r_[0:(50e-6):1/(fs)]
print(len(x2))
x3=np.r_[0:(60e-6):1/(fs)]
print(len(x3))
x4=np.r_[0:(40e-6):1/(fs)]
print(len(x2))
#x=np.linspace(0,10e-6,M)
def theta(t):
return k1*t*t + k2*t + fi0
def chirp(t):
return np.exp(1j*2*np.pi*theta(t))
#**************segunda parte*****************#
"""
c=chirp(x)
plt.plot(x2,np.pad(c,(1000,1000),'constant'))
plt.title("Chirpcorrida")
plt.ylabel("chirp")
plt.xlabel("tiempo")
plt.grid(True)
plt.show()
plt.plot(x,chirp(x))
plt.title("Chirp")
plt.ylabel("chirp")
plt.xlabel("tiempo")
plt.grid(True)
plt.show()
"""
#*******************OCHO************************
c=chirp(x)
c1=chirp(x)
cp=np.pad(c,(1000,1000),'constant')
correlacion=np.correlate(c1,cp, mode='valid')
plt.figure()
plt.plot(x4,correlacion)
plt.title("correlacion python")
plt.grid(True)
plt.show()
#********************NUEVE**********************
c=chirp(x)
c1=chirp(x)
cp=np.pad(c,(1000,1000),'constant')
dftcorrida = fft(cp,3000)/(len(cp)/2.0) # fft de 2048 puntos 8192
dftnegconj = np.conj(fft(c1,3000)/(len(c1)/2.0)) # fft de 2048 puntos 8192
proddft = dftcorrida * dftnegconj
ifftcorrelacion = np.abs(ifft(proddft))
plt.figure()
plt.plot(x3,ifftcorrelacion)
#plt.plot(x2,np.pad(c,(1000,1000),'constant'),dashes=[1, 9])
plt.title("conjugo despues")
plt.grid(True)
plt.show()
#********
plt.figure()
plt.plot(x3,ifftcorrelacion, label="correlacion")
#plt.plot(x2,np.pad(c,(1000,1000),'constant'),dashes=[1, 9])
plt.axis([19.5e-6, 20.5e-6, 0,0.0017])
plt.axvline(x=20e-6+1/(19e6), color='#2ca02c', alpha=0.5, label="1/BW")
plt.axvline(x=20e-6+1/(-19e6), color='#2ca02c', alpha=0.5)
plt.title("jhjh")
plt.legend()
plt.grid(True)
plt.show()
#**************************** | UTF-8 | Python | false | false | 2,185 | py | 4 | main2.py | 4 | 0.588558 | 0.507551 | 0 | 113 | 17.353982 | 75 |
rafavillalta/lispy | 4,655,744,578,651 | 8334f1e7333f492bc9d84773474be7b10a8a8d27 | b30113c34d1b220d4debe33de23a2912c9ef6796 | /mylis/mylis_2/meta_test.py | 3c884d896ae9ac384fc356f2b49a6f4b1fb399cf | [
"MIT"
]
| permissive | https://github.com/rafavillalta/lispy | e6d9625250010979e5bdfc2e61c920742a9dd3fc | 7c2d3625eba07dafb6edc130ac0cb63cffc18591 | refs/heads/main | 2023-08-14T21:58:35.048308 | 2021-10-08T14:25:20 | 2021-10-08T14:25:20 | 414,785,757 | 0 | 0 | MIT | true | 2021-10-07T23:27:52 | 2021-10-07T23:27:52 | 2021-10-07T18:28:53 | 2021-10-07T18:43:32 | 851 | 0 | 0 | 0 | null | false | false | import operator as op
import mylis
env_scm = """
(define standard-env (list
(list (quote not) not)
(list (quote eq?) eq?)
))
standard-env
"""
def test_env_build():
got = mylis.run(env_scm)
assert got == [['not', op.not_], ['eq?', op.is_]]
scan_scm = """
(define l (quote (a b c)))
(define (scan what where)
(cond ((null? where) #f)
((equal? what (car where)) what)
(else (scan what (cdr where)))))
"""
def test_scan():
source = scan_scm + '(scan (quote a) l )'
got = mylis.run(source)
assert got == 'a'
def test_scan_not_found():
source = scan_scm + '(scan (quote z) l )'
got = mylis.run(source)
assert got is False
lookup_scm = """
(define env (list
(list (quote not) not)
(list (quote eq?) eq?)
))
(define (lookup what where)
(cond ((null? where) #f)
((equal? what (car (car where))) (car (cdr (car where))))
(else (lookup what (cdr where)))))
"""
def test_lookup():
source = lookup_scm + '(lookup (quote eq?) env)'
got = mylis.run(source)
assert got == op.is_
def test_lookup_not_found():
source = lookup_scm + '(lookup (quote z) env )'
got = mylis.run(source)
assert got is False
| UTF-8 | Python | false | false | 1,216 | py | 41 | meta_test.py | 12 | 0.561678 | 0.561678 | 0 | 57 | 20.333333 | 67 |
MystMaster/discord-bot | 13,460,427,526,566 | c5decfc985e5ef5b40ae84703d89018f2f27b8c3 | 20812be80eaea48867641cdead44402a581482f7 | /tarakania_rpg/db/postgres.py | 072516f8fb11b6dcb6b925de547017e334121815 | [
"MIT"
]
| permissive | https://github.com/MystMaster/discord-bot | 4b956e5f94e6a0c86afed8cf3220c215388fc2bd | 801d7004589800c6013f32a3289f4b8277b289b2 | refs/heads/master | 2023-05-10T18:17:23.265788 | 2021-03-26T07:34:03 | 2021-03-26T07:34:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from typing import Dict
import asyncpg
async def create_pg_connection(pg_config: Dict[str, str]) -> asyncpg.Connection:
return await asyncpg.create_pool(**pg_config)
| UTF-8 | Python | false | false | 173 | py | 73 | postgres.py | 46 | 0.751445 | 0.751445 | 0 | 7 | 23.714286 | 80 |
ValeriyaShastun/test_demoqa | 15,187,004,409,032 | 9a6c837e56b2f45453d0fb34a4fe7403259ba2ec | 3a3f0249d599cacf2f9c6451ea2ed738cfac19ed | /demo_qa/main.py | 0e8cf835ee0a1ec6c2119b751d8430c998bf2f1d | []
| no_license | https://github.com/ValeriyaShastun/test_demoqa | 1c50bd04522434470c1f0ca5ad853bb3b6a1e9b5 | 9ecdf2aeb3397df8bcf1619f5988bba973cf76ff | refs/heads/main | 2023-06-19T04:29:12.885903 | 2021-07-12T14:38:55 | 2021-07-12T14:38:55 | 385,276,858 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from selenium.webdriver.common.by import By
import demo_qa.parameters as par
import demo_qa.utils as util
class HomePage():
def __init__(self, url=par.url, driver=par.driver):
'''Getting Home page
:param url: url of home page
:param driver: chromedriver call'''
driver.get(url)
def page_verification(self):
'''Verification of correctness of page by
checking presence of main menu --- using utils method'''
try:
menu_el = (By.CLASS_NAME, par.CATEGORY_CARDS_CLASS_NAME)
self.found_menu_el = util.allocate_element(menu_el, 5)
except AssertionError as error:
print(f"Element was not found of the page: {error}")
# def page_verification_duplicate(self):
# '''Verification of correctness of page by
# checking presence of main menu --- using time.sleep and find_by_element'''
# try:
# time.sleep(3)
# self.found_menu_el = par.driver.find_element_by_class_name('category-cards')
# except AssertionError as error:
# print(f"Element was not found of the page: {error}")
| UTF-8 | Python | false | false | 1,146 | py | 5 | main.py | 5 | 0.625654 | 0.623909 | 0 | 30 | 37.2 | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.