Dataset Viewer
Auto-converted to Parquet Duplicate
section
stringlengths
2
30
filename
stringlengths
1
82
text
stringlengths
783
28M
neubot
main_win32
# neubot/main_win32.py # # Copyright (c) 2012 Simone Basso <[email protected]>, # NEXA Center for Internet & Society at Politecnico di Torino # # This file is part of Neubot <http://www.neubot.org/>. # # Neubot is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Neubot is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Neubot. If not, see <http://www.gnu.org/licenses/>. # """ Win32 main() """ import getopt import sys if __name__ == "__main__": sys.path.insert(0, ".") from neubot import main_common, utils_ctl, utils_version # Reference notifier so py2exe includes 'em if sys.platform == "win32" and not hasattr(sys, "frozen"): from neubot import notifier, raw def subcommand_start(args): """Start subcommand""" try: options, arguments = getopt.getopt(args[1:], "k") except getopt.error: sys.exit("usage: neubot start [-k]") if arguments: sys.exit("usage: neubot start [-k]") kill = False for tpl in options: if tpl[0] == "-k": kill = True # # Wait for the parent to die, so that it closes the listening # socket and we can successfully bind() it. # count = 0 while kill: running = utils_ctl.is_running("127.0.0.1", "9774", quick=1) if not running: break utils_ctl.stop("127.0.0.1", "9774") count += 1 if count > 512: sys.exit("FATAL: cannot stop neubot daemon") # Lazy import from neubot import background_win32 background_win32.main(["neubot"]) def subcommand_status(args): """Status subcommand""" try: options, arguments = getopt.getopt(args[1:], "v") except getopt.error: sys.exit("usage: neubot status [-v]") if arguments: sys.exit("usage: neubot status [-v]") verbose = 0 for opt in options: if opt[0] == "-v": verbose = 1 running = utils_ctl.is_running("127.0.0.1", "9774") if verbose: if not running: sys.stdout.write("Neubot is not running\n") else: sys.stdout.write("Neubot is running\n") if not running: sys.exit(1) def subcommand_stop(args): """Stop subcommand""" try: options, arguments = getopt.getopt(args[1:], "") except getopt.error: sys.exit("usage: neubot stop") if options or arguments: sys.exit("usage: neubot stop") running = utils_ctl.is_running("127.0.0.1", "9774") if not running: sys.exit("ERROR: neubot is not running") utils_ctl.stop("127.0.0.1", "9774") USAGE = """\ usage: neubot -h|--help neubot -V neubot start [-k] neubot status [-v] neubot stop neubot subcommand [option]... [argument]... """ def main(args): """Main function""" if len(args) == 1: sys.stdout.write(USAGE) main_common.print_subcommands(sys.stdout) sys.exit(0) del args[0] subcommand = args[0] if subcommand == "--help" or subcommand == "-h": sys.stdout.write(USAGE) main_common.print_subcommands(sys.stdout) sys.exit(0) if subcommand == "-V": sys.stdout.write(utils_version.PRODUCT + "\n") sys.exit(0) if subcommand == "start": subcommand_start(args) sys.exit(0) if subcommand == "status": subcommand_status(args) sys.exit(0) if subcommand == "stop": subcommand_stop(args) sys.exit(0) main_common.main(subcommand, args) if __name__ == "__main__": main(sys.argv)
gui
propertyEditor
import csv import gui.builtinMarketBrowser.pfSearchBox as SBox import gui.display as d import gui.globalEvents as GE # noinspection PyPackageRequirements import wx # noinspection PyPackageRequirements import wx.propgrid as wxpg from eos.db.gamedata.queries import getAttributeInfo, getItem from gui.auxWindow import AuxiliaryFrame from gui.bitmap_loader import BitmapLoader from gui.marketBrowser import SearchBox from logbook import Logger from service.fit import Fit from service.market import Market pyfalog = Logger(__name__) _t = wx.GetTranslation class AttributeEditor(AuxiliaryFrame): def __init__(self, parent): super().__init__( parent, wx.ID_ANY, title=_t("Attribute Editor"), pos=wx.DefaultPosition, size=wx.Size(650, 600), resizeable=True, ) i = wx.Icon(BitmapLoader.getBitmap("fit_rename_small", "gui")) self.SetIcon(i) self.mainFrame = parent menubar = wx.MenuBar() fileMenu = wx.Menu() fileImport = fileMenu.Append(wx.ID_ANY, _t("Import"), _t("Import overrides")) fileExport = fileMenu.Append(wx.ID_ANY, _t("Export"), _t("Import overrides")) fileClear = fileMenu.Append( wx.ID_ANY, _t("Clear All"), _t("Clear all overrides") ) menubar.Append(fileMenu, _t("&File")) self.SetMenuBar(menubar) self.Bind(wx.EVT_MENU, self.OnImport, fileImport) self.Bind(wx.EVT_MENU, self.OnExport, fileExport) self.Bind(wx.EVT_MENU, self.OnClear, fileClear) i = wx.Icon(BitmapLoader.getBitmap("fit_rename_small", "gui")) self.SetIcon(i) self.mainFrame = parent self.panel = panel = wx.Panel(self, wx.ID_ANY) mainSizer = wx.BoxSizer(wx.HORIZONTAL) leftSizer = wx.BoxSizer(wx.VERTICAL) leftPanel = wx.Panel( panel, wx.ID_ANY, style=wx.DOUBLE_BORDER if "wxMSW" in wx.PlatformInfo else wx.SIMPLE_BORDER, ) self.searchBox = SearchBox(leftPanel) self.itemView = ItemView(leftPanel) leftSizer.Add(self.searchBox, 0, wx.EXPAND) leftSizer.Add(self.itemView, 1, wx.EXPAND) leftPanel.SetSizer(leftSizer) mainSizer.Add(leftPanel, 1, wx.ALL | wx.EXPAND, 5) rightSizer = wx.BoxSizer(wx.VERTICAL) self.btnRemoveOverrides = wx.Button( panel, wx.ID_ANY, _t("Remove Overides for Item"), wx.DefaultPosition, wx.DefaultSize, 0, ) self.pg = AttributeGrid(panel) rightSizer.Add(self.pg, 1, wx.ALL | wx.EXPAND, 5) rightSizer.Add(self.btnRemoveOverrides, 0, wx.ALL | wx.EXPAND, 5) self.btnRemoveOverrides.Bind(wx.EVT_BUTTON, self.pg.removeOverrides) self.btnRemoveOverrides.Enable(False) mainSizer.Add(rightSizer, 1, wx.EXPAND) panel.SetSizer(mainSizer) mainSizer.SetSizeHints(panel) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(panel, 1, wx.EXPAND) self.SetSizer(sizer) self.SetAutoLayout(True) self.SetMinSize(self.GetSize()) self.Bind(wx.EVT_CLOSE, self.OnClose) self.Bind(wx.EVT_CHAR_HOOK, self.kbEvent) def kbEvent(self, event): if event.GetKeyCode() == wx.WXK_ESCAPE and event.GetModifiers() == wx.MOD_NONE: self.Close() return event.Skip() def OnClose(self, event): fitID = self.mainFrame.getActiveFit() if fitID is not None: wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID,))) event.Skip() def OnImport(self, event): with wx.FileDialog( self, _t("Import pyfa override file"), wildcard=_t("pyfa override file") + " (*.csv)|*.csv", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST, ) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() with open(path, "r") as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: if ( len(row) == 0 ): # csvwriter seems to added blank lines to the end sometimes continue itemID, attrID, value = row item = getItem(int(itemID)) attr = getAttributeInfo(int(attrID)) item.setOverride(attr, float(value)) self.itemView.updateItems(True) def OnExport(self, event): sMkt = Market.getInstance() items = sMkt.getItemsWithOverrides() defaultFile = "pyfa_overrides.csv" with wx.FileDialog( self, _t("Save Overrides As..."), wildcard=_t("pyfa overrides") + " (*.csv)|*.csv", style=wx.FD_SAVE, defaultFile=defaultFile, ) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() with open(path, "w", encoding="utf-8") as csvfile: writer = csv.writer(csvfile) for item in items: for key, override in item.overrides.items(): writer.writerow([item.ID, override.attrID, override.value]) def OnClear(self, event): with wx.MessageDialog( self, _t("Are you sure you want to delete all overrides?"), _t("Confirm Delete"), wx.YES | wx.NO | wx.ICON_EXCLAMATION, ) as dlg: if dlg.ShowModal() == wx.ID_YES: sMkt = Market.getInstance() items = sMkt.getItemsWithOverrides() # We can't just delete overrides, as loaded items will still have # them assigned. Deleting them from the database won't propagate # them due to the eve/user database disconnect. We must loop through # all items that have overrides and remove them for item in items: for _, x in list(item.overrides.items()): item.deleteOverride(x.attr) self.itemView.updateItems(True) self.pg.Clear() # This is literally a stripped down version of the market. class ItemView(d.Display): DEFAULT_COLS = ["Base Icon", "Base Name", "attr:power,,,True", "attr:cpu,,,True"] def __init__(self, parent): d.Display.__init__(self, parent) self.activeItems = [] self.searchTimer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.scheduleSearch, self.searchTimer) self.searchBox = parent.Parent.Parent.searchBox # Bind search actions self.searchBox.Bind(SBox.EVT_TEXT_ENTER, self.scheduleSearch) self.searchBox.Bind(SBox.EVT_SEARCH_BTN, self.scheduleSearch) self.searchBox.Bind(SBox.EVT_CANCEL_BTN, self.clearSearch) self.searchBox.Bind(SBox.EVT_TEXT, self.delaySearch) self.update(Market.getInstance().getItemsWithOverrides()) def clearSearch(self, event=None): if event: self.searchBox.Clear() self.update(Market.getInstance().getItemsWithOverrides()) def updateItems(self, updateDisplay=False): if updateDisplay: self.update(Market.getInstance().getItemsWithOverrides()) def delaySearch(self, evt): sFit = Fit.getInstance() self.searchTimer.Stop() self.searchTimer.Start(sFit.serviceFittingOptions["marketSearchDelay"], True) def scheduleSearch(self, event=None): sMkt = Market.getInstance() search = self.searchBox.GetLineText(0) # Make sure we do not count wildcards as search symbol realsearch = search.replace("*", "").replace("?", "") # Show nothing if query is too short if len(realsearch) < 3: self.clearSearch() return sMkt.searchItems(search, self.populateSearch, "everything") def itemSort(self, item): sMkt = Market.getInstance() isFittable = ( item.group.name in sMkt.FIT_GROUPS or item.category.name in sMkt.FIT_CATEGORIES ) return (not isFittable, *sMkt.itemSort(item)) def populateSearch(self, itemIDs): items = Market.getItems(itemIDs) self.update(items) def populate(self, items): if len(items) > 0: self.unselectAll() items.sort(key=self.itemSort) self.activeItems = items d.Display.populate(self, items) def refresh(self, items): if len(items) > 1: items.sort(key=self.itemSort) d.Display.refresh(self, items) class AttributeGrid(wxpg.PropertyGrid): def __init__(self, parent): wxpg.PropertyGrid.__init__( self, parent, style=wxpg.PG_HIDE_MARGIN | wxpg.PG_HIDE_CATEGORIES | wxpg.PG_BOLD_MODIFIED | wxpg.PG_TOOLTIPS, ) self.SetExtraStyle(wxpg.PG_EX_HELP_AS_TOOLTIPS) self.item = None self.itemView = parent.Parent.itemView self.btn = parent.Parent.btnRemoveOverrides self.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChange) self.Bind(wxpg.EVT_PG_SELECTED, self.OnPropGridSelect) self.Bind(wxpg.EVT_PG_RIGHT_CLICK, self.OnPropGridRightClick) self.itemView.Bind(wx.EVT_LIST_ITEM_SELECTED, self.itemActivated) self.itemView.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.itemActivated) def itemActivated(self, event): self.Clear() self.btn.Enable(True) sel = event.EventObject.GetFirstSelected() self.item = item = self.itemView.activeItems[sel] for key in sorted(item.attributes.keys()): override = item.overrides.get(key, None) default = item.attributes[key].value if override and override.value != default: prop = wxpg.FloatProperty(key, value=override.value) prop.SetModifiedStatus(True) else: prop = wxpg.FloatProperty(key, value=default) prop.SetClientData( item.attributes[key] ) # set this so that we may access it later prop.SetHelpString( "%s\n%s" % ( item.attributes[key].displayName or key, _t("Default Value: %0.3f") % default, ) ) self.Append(prop) def removeOverrides(self, event): if self.item is None: return for x in list(self.item.overrides.values()): self.item.deleteOverride(x.attr) self.itemView.updateItems(True) self.ClearModifiedStatus() self.itemView.Select(self.itemView.GetFirstSelected(), on=False) self.Clear() def Clear(self): self.item = None self.btn.Enable(False) wxpg.PropertyGrid.Clear(self) def OnPropGridChange(self, event): p = event.GetProperty() attr = p.GetClientData() if p.GetValue() == attr.value: self.item.deleteOverride(attr) p.SetModifiedStatus(False) else: self.item.setOverride(attr, p.GetValue()) self.itemView.updateItems() pyfalog.debug('{0} changed to "{1}"', p.GetName(), p.GetValueAsString()) def OnPropGridSelect(self, event): pass def OnPropGridRightClick(self, event): pass
scripting
keyboard
# Copyright (C) 2011 Chris Dekter # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Keyboard Functions""" import typing from typing import Callable import autokey.iomediator.waiter import autokey.model.phrase from autokey import iomediator, model class Keyboard: """ Provides access to the keyboard for event generation. """ SendMode = autokey.model.phrase.SendMode def __init__(self, mediator): """Initialize the Keyboard""" self.mediator = mediator # type: iomediator.IoMediator """See C{IoMediator} documentation""" def send_keys( self, key_string, send_mode: typing.Union[ autokey.model.phrase.SendMode, int ] = autokey.model.phrase.SendMode.KEYBOARD, ): """ Send a sequence of keys via keyboard events as the default or via clipboard pasting. Because the clipboard can only contain printable characters, special keys and embedded key combinations can only be sent in keyboard mode. Trying to send special keys using a clipboard pasting method will paste the literal representation (e.g. "<ctrl>+<f11>") instead of the actual special key or key combination. Usage: C{keyboard.send_keys(keyString)} @param key_string: string of keys to send. Special keys are only possible in keyboard mode. @param send_mode: Determines how the string is sent. """ if not isinstance(key_string, str): raise TypeError("Only strings can be sent using this function") send_mode = _validate_send_mode(send_mode) self.mediator.interface.begin_send() try: if send_mode is autokey.model.phrase.SendMode.KEYBOARD: self.mediator.send_string(key_string) else: self.mediator.paste_string(key_string, send_mode) finally: self.mediator.interface.finish_send() def send_key(self, key, repeat=1): """ Send a keyboard event Usage: C{keyboard.send_key(key, repeat=1)} @param key: the key to be sent (e.g. "s" or "<enter>") @param repeat: number of times to repeat the key event """ for _ in range(repeat): self.mediator.send_key(key) self.mediator.flush() def press_key(self, key): """ Send a key down event Usage: C{keyboard.press_key(key)} The key will be treated as down until a matching release_key() is sent. @param key: the key to be pressed (e.g. "s" or "<enter>") """ self.mediator.press_key(key) def release_key(self, key): """ Send a key up event Usage: C{keyboard.release_key(key)} If the specified key was not made down using press_key(), the event will be ignored. @param key: the key to be released (e.g. "s" or "<enter>") """ self.mediator.release_key(key) def fake_keypress(self, key, repeat=1): """ Fake a keypress Usage: C{keyboard.fake_keypress(key, repeat=1)} Uses XTest to 'fake' a keypress. This is useful to send keypresses to some applications which won't respond to keyboard.send_key() @param key: the key to be sent (e.g. "s" or "<enter>") @param repeat: number of times to repeat the key event """ for _ in range(repeat): self.mediator.fake_keypress(key) def wait_for_keypress(self, key, modifiers: list = None, timeOut=10.0): """ Wait for a keypress or key combination Usage: C{keyboard.wait_for_keypress(self, key, modifiers=[], timeOut=10.0)} Note: this function cannot be used to wait for modifier keys on their own @param key: the key to wait for @param modifiers: list of modifiers that should be pressed with the key @param timeOut: maximum time, in seconds, to wait for the keypress to occur """ if modifiers is None: modifiers = [] w = self.mediator.waiter(key, modifiers, None, None, None, timeOut) self.mediator.listeners.append(w) rtn = w.wait() self.mediator.listeners.remove(w) return rtn def wait_for_keyevent( self, check: Callable[[any, str, list, str], bool], name: str = None, timeOut=10.0, ): """ Wait for a key event, potentially accumulating the intervening characters Usage: C{keyboard.wait_for_keypress(self, check, name=None, timeOut=10.0)} @param check: a function that returns True or False to signify we've finished waiting @param name: only one waiter can have this name. Used to prevent more threads waiting on this. @param timeOut: maximum time, in seconds, to wait for the keypress to occur Example: # Accumulate the traditional emacs C-u prefix arguments # See https://www.gnu.org/software/emacs/manual/html_node/elisp/Prefix-Command-Arguments.html def check(waiter,rawKey,modifiers,key,*args): isCtrlU = (key == 'u' and len(modifiers) == 1 and modifiers[0] == '<ctrl>') if isCtrlU: # If we get here, they've already pressed C-u at least 2x try: val = int(waiter.result) * 4 waiter.result = str(val) except ValueError: waiter.result = "16" return False elif any(m == "<ctrl>" or m == "<alt>" or m == "<meta>" or m == "<super>" or m == "<hyper>" for m in modifiers): # Some other control character is an indication we're done. if waiter.result is None or waiter.result == "": waiter.result = "4" store.set_global_value("emacs-prefix-arg", waiter.result) return True else: # accumulate as a string waiter.result = waiter.result + key return False keyboard.wait_for_keyevent(check, "emacs-prefix") """ if name is None or not any( elem.name == name for elem in self.mediator.listeners ): w = self.mediator.waiter(None, None, None, check, name, timeOut) self.mediator.listeners.append(w) rtn = w.wait() self.mediator.listeners.remove(w) return rtn return False def _validate_send_mode(send_mode): permissible_values = "\n".join( "keyboard.{}".format(mode) for mode in map(str, autokey.model.phrase.SendMode) ) if isinstance(send_mode, int): if send_mode in range(len(autokey.model.phrase.SendMode)): send_mode = tuple(autokey.model.phrase.SendMode)[send_mode] # type: model.SendMode else: permissible_values = "\n".join( "{}: keyboard.{}".format(number, str(constant)) for number, constant in enumerate(autokey.model.phrase.SendMode) ) raise ValueError( "send_mode out of range for index-based access. " "Permissible values are:\n{}".format(permissible_values) ) elif isinstance(send_mode, str): try: send_mode = autokey.model.phrase.SendMode(send_mode) except ValueError as v: raise ValueError("Permissible values are: " + permissible_values) from v elif send_mode is None: # Selection has value None send_mode = autokey.model.phrase.SendMode.SELECTION elif not isinstance(send_mode, autokey.model.phrase.SendMode): raise TypeError( "Unsupported type for send_mode parameter: {} Use one of: {}".format( send_mode, permissible_values ) ) return send_mode
migrations
0008_userpreferences
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-23 19:08 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("deposit", "0007_remove_urls_and_add_oairecord"), ] operations = [ migrations.CreateModel( name="UserPreferences", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "last_repository", models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name="last_used_by", to="deposit.Repository", ), ), ( "preferred_repository", models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name="preferrend_by", to="deposit.Repository", ), ), ( "user", models.OneToOneField( on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, ), ), ], ), ]
ui
lineNumberRulerView
import math from AppKit import ( NSBezierPath, NSColor, NSFont, NSFontAttributeName, NSForegroundColorAttributeName, NSMiniControlSize, NSNotificationCenter, NSRectFill, NSRulerView, NSTextStorageDidProcessEditingNotification, NSTextView, NSViewBoundsDidChangeNotification, ) from Foundation import ( NSHeight, NSInvocation, NSLocationInRange, NSMakeRange, NSMakeRect, NSMaxRange, NSMinY, NSNotFound, NSString, NSWidth, ) from objc import super """ Based/translated from NoodleLineNumberView http://www.noodlesoft.com/blog/2008/10/05/displaying-line-numbers-with-nstextview/ """ class LineNumberNSRulerView(NSRulerView): DEFAULT_THICKNESS = 22.0 RULER_MARGIN = 5.0 def init(self): self = super(LineNumberNSRulerView, self).init() self._font = NSFont.labelFontOfSize_( NSFont.systemFontSizeForControlSize_(NSMiniControlSize) ) self._textColor = NSColor.colorWithCalibratedWhite_alpha_(0.42, 1) self._rulerBackgroundColor = None self._lineIndices = None return self def setFont_(self, font): self._font = font def font(self): return self._font def setTextColor_(self, color): self._textColor = color self.setNeedsDisplay_(True) def textColor(self): return self._textColor def textAttributes(self): return { NSFontAttributeName: self.font(), NSForegroundColorAttributeName: self.textColor(), } def setRulerBackgroundColor_(self, color): self._rulerBackgroundColor = color self.setNeedsDisplay_(True) def rulerBackgroundColor(self): return self._rulerBackgroundColor def setClientView_(self, view): oldClientView = self.clientView() if oldClientView != view and isinstance(oldClientView, NSTextView): NSNotificationCenter.defaultCenter().removeObserver_name_object_( self, NSTextStorageDidProcessEditingNotification, oldClientView.textStorage(), ) super(LineNumberNSRulerView, self).setClientView_(view) if view is not None and isinstance(view, NSTextView): NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( self, "textDidChange:", NSTextStorageDidProcessEditingNotification, view.textStorage(), ) NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( self, "textViewBoundsChange:", NSViewBoundsDidChangeNotification, view.enclosingScrollView().contentView(), ) def lineIndices(self): if self._lineIndices is None: self.calculateLines() return self._lineIndices def invalidateLineIndices(self): self._lineIndices = None def textDidChange_(self, sender): self.calculateLines() self.invalidateLineIndices() self.setNeedsDisplay_(True) def textViewBoundsChange_(self, sender): self.setNeedsDisplay_(True) def dealloc(self): # make sure we remove ourselves as an observer of the text storage NSNotificationCenter.defaultCenter().removeObserver_(self) super(LineNumberNSRulerView, self).dealloc() def calculateLines(self): view = self.clientView() if not isinstance(view, NSTextView): return text = view.string() textLength = text.length() if not textLength: self._lineIndices = [1] return lineIndices = [] index = 0 numberOfLines = 0 while index < textLength: lineIndices.append(index) index = NSMaxRange(text.lineRangeForRange_(NSMakeRange(index, 0))) numberOfLines += 1 lineStart, lineEnd, contentEnd = text.getLineStart_end_contentsEnd_forRange_( None, None, None, NSMakeRange(lineIndices[-1], 0) ) if contentEnd < lineEnd: lineIndices.append(index) self._lineIndices = lineIndices oldThickness = self.ruleThickness() newThickness = self.requiredThickness() if abs(oldThickness - newThickness) > 0: invocation = NSInvocation.invocationWithMethodSignature_( self.methodSignatureForSelector_("setRuleThickness:") ) invocation.setSelector_("setRuleThickness:") invocation.setTarget_(self) invocation.setArgument_atIndex_(newThickness, 2) invocation.performSelector_withObject_afterDelay_("invoke", None, 0) def requiredThickness(self): lineCount = len(self.lineIndices()) digits = int(math.log10(lineCount) + 1) sampleString = NSString.stringWithString_("8" * digits) stringSize = sampleString.sizeWithAttributes_(self.textAttributes()) return math.ceil( max([self.DEFAULT_THICKNESS, stringSize.width + self.RULER_MARGIN * 2]) ) def lineNumberForCharacterIndex_inText_(self, index, text): lines = self.lineIndices() left = 0 right = len(lines) while (right - left) > 1: mid = (right + left) // 2 lineStart = lines[mid] if index < lineStart: right = mid elif index > lineStart: left = mid else: return mid return left def drawHashMarksAndLabelsInRect_(self, rect): bounds = self.bounds() view = self.clientView() rulerBackgroundColor = self.rulerBackgroundColor() if rulerBackgroundColor is not None: rulerBackgroundColor.set() NSRectFill(bounds) if not isinstance(view, NSTextView): return layoutManager = view.layoutManager() container = view.textContainer() text = view.string() nullRange = NSMakeRange(NSNotFound, 0) yinset = view.textContainerInset().height visibleRect = self.scrollView().contentView().bounds() textAttributes = self.textAttributes() lines = self.lineIndices() glyphRange = layoutManager.glyphRangeForBoundingRect_inTextContainer_( visibleRect, container ) _range = layoutManager.characterRangeForGlyphRange_actualGlyphRange_( glyphRange, None )[0] _range.length += 1 count = len(lines) index = 0 lineNumber = self.lineNumberForCharacterIndex_inText_(_range.location, text) for line in range(lineNumber, count): index = lines[line] if NSLocationInRange(index, _range): ( rects, rectCount, ) = layoutManager.rectArrayForCharacterRange_withinSelectedCharacterRange_inTextContainer_rectCount_( NSMakeRange(index, 0), nullRange, container, None ) if rectCount > 0: ypos = yinset + NSMinY(rects[0]) - NSMinY(visibleRect) labelText = NSString.stringWithString_("%s" % (line + 1)) stringSize = labelText.sizeWithAttributes_(textAttributes) x = NSWidth(bounds) - stringSize.width - self.RULER_MARGIN y = ypos + (NSHeight(rects[0]) - stringSize.height) / 2.0 w = NSWidth(bounds) - self.RULER_MARGIN * 2.0 h = NSHeight(rects[0]) labelText.drawInRect_withAttributes_( NSMakeRect(x, y, w, h), textAttributes ) if index > NSMaxRange(_range): break path = NSBezierPath.bezierPath() path.moveToPoint_((bounds.origin.x + bounds.size.width, bounds.origin.y)) path.lineToPoint_( (bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height) ) NSColor.grayColor().set() path.stroke()
SCL
Rules
# Copyright (c) 2011-2012, Thomas Paviot ([email protected]) # All rights reserved. # This file is part of the StepClassLibrary (SCL). # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # Neither the name of the <ORGANIZATION> nor the names of its contributors may # be used to endorse or promote products derived from this software without # specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __doc__ = "This module defines EXPRESS rules" class Rule(object): """ This class describes a RULE @TODO: to be implemented """ pass
ui
caa_types_selector
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2007 Oliver Charles # Copyright (C) 2007, 2010-2011 LukΓ‘Ε‘ LalinskΓ½ # Copyright (C) 2007-2011, 2015, 2018-2023 Philipp Wolfer # Copyright (C) 2011 Michael Wiencek # Copyright (C) 2011-2012 Wieland Hoffmann # Copyright (C) 2013-2015, 2018-2023 Laurent Monin # Copyright (C) 2015-2016 Rahul Raturi # Copyright (C) 2016-2017 Sambhav Kothari # Copyright (C) 2017 Frederik β€œFreso” S. Olesen # Copyright (C) 2018 Bob Swift # Copyright (C) 2018 Vishal Choudhary # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from functools import partial from picard.ui import PicardDialog from picard.ui.util import StandardButton, qlistwidget_items from PyQt5 import QtCore, QtGui, QtWidgets class ArrowButton(QtWidgets.QPushButton): """Standard arrow button for CAA image type selection dialog. Keyword Arguments: label {string} -- Label to display on the button command {command} -- Command to execute when the button is clicked (default: {None}) parent {[type]} -- Parent of the QPushButton object being created (default: {None}) """ def __init__(self, icon_name, command=None, parent=None): icon = QtGui.QIcon(":/images/16x16/" + icon_name + ".png") super().__init__(icon, "", parent=parent) if command is not None: self.clicked.connect(command) class ArrowsColumn(QtWidgets.QWidget): """Standard arrow buttons column for CAA image type selection dialog. Keyword Arguments: selection_list {ListBox} -- ListBox of selected items associated with this arrow column ignore_list {ListBox} -- ListBox of unselected items associated with this arrow column callback {command} -- Command to execute after items are moved between lists (default: {None}) reverse {bool} -- Determines whether the arrow directions should be reversed (default: {False}) parent {[type]} -- Parent of the QWidget object being created (default: {None}) """ def __init__( self, selection_list, ignore_list, callback=None, reverse=False, parent=None ): super().__init__(parent=parent) self.selection_list = selection_list self.ignore_list = ignore_list self.callback = callback spacer_item = QtWidgets.QSpacerItem( 20, 20, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding, ) arrows_layout = QtWidgets.QVBoxLayout() arrows_layout.addItem(QtWidgets.QSpacerItem(spacer_item)) self.button_add = ArrowButton( "go-next" if reverse else "go-previous", self.move_from_ignore ) arrows_layout.addWidget(self.button_add) self.button_add_all = ArrowButton( "move-all-right" if reverse else "move-all-left", self.move_all_from_ignore ) arrows_layout.addWidget(self.button_add_all) self.button_remove = ArrowButton( "go-previous" if reverse else "go-next", self.move_to_ignore ) arrows_layout.addWidget(self.button_remove) self.button_remove_all = ArrowButton( "move-all-left" if reverse else "move-all-right", self.move_all_to_ignore ) arrows_layout.addWidget(self.button_remove_all) arrows_layout.addItem(QtWidgets.QSpacerItem(spacer_item)) self.setLayout(arrows_layout) def move_from_ignore(self): self.ignore_list.move_selected_items( self.selection_list, callback=self.callback ) def move_all_from_ignore(self): self.ignore_list.move_all_items(self.selection_list, callback=self.callback) def move_to_ignore(self): self.selection_list.move_selected_items( self.ignore_list, callback=self.callback ) def move_all_to_ignore(self): self.selection_list.move_all_items(self.ignore_list, callback=self.callback) class ListBox(QtWidgets.QListWidget): """Standard list box for CAA image type selection dialog. Keyword Arguments: parent {[type]} -- Parent of the QListWidget object being created (default: {None}) """ LISTBOX_WIDTH = 100 LISTBOX_HEIGHT = 250 def __init__(self, parent=None): super().__init__(parent=parent) self.setMinimumSize(QtCore.QSize(self.LISTBOX_WIDTH, self.LISTBOX_HEIGHT)) self.setSizePolicy( QtWidgets.QSizePolicy.Policy.MinimumExpanding, QtWidgets.QSizePolicy.Policy.Expanding, ) self.setSortingEnabled(True) self.setSelectionMode( QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection ) def move_item(self, item, target_list): """Move the specified item to another listbox.""" self.takeItem(self.row(item)) target_list.addItem(item) def move_selected_items(self, target_list, callback=None): """Move the selected item to another listbox.""" for item in self.selectedItems(): self.move_item(item, target_list) if callback: callback() def move_all_items(self, target_list, callback=None): """Move all items to another listbox.""" while self.count(): self.move_item(self.item(0), target_list) if callback: callback() def all_items_data(self, role=QtCore.Qt.ItemDataRole.UserRole): for item in qlistwidget_items(self): yield item.data(role) class CAATypesSelectorDialog(PicardDialog): """Display dialog box to select the CAA image types to include and exclude from download and use. Keyword Arguments: parent {[type]} -- Parent of the QDialog object being created (default: {None}) types_include {[string]} -- List of CAA image types to include (default: {None}) types_exclude {[string]} -- List of CAA image types to exclude (default: {None}) default_include {[string]} -- List of CAA image types to include by default (default: {None}) default_exclude {[string]} -- List of CAA image types to exclude by default (default: {None}) known_types {{string: string}} -- Dict. of all known CAA image types, unique name as key, translated title as value (default: {None}) """ help_url = "doc_cover_art_types" def __init__( self, parent=None, types_include=None, types_exclude=None, default_include=None, default_exclude=None, known_types=None, ): super().__init__(parent) if types_include is None: types_include = [] if types_exclude is None: types_exclude = [] self._default_include = default_include or [] self._default_exclude = default_exclude or [] self._known_types = known_types or {} self.setWindowTitle(_("Cover art types")) self.setWindowModality(QtCore.Qt.WindowModality.WindowModal) self.layout = QtWidgets.QVBoxLayout(self) self.layout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetFixedSize) # Create list boxes for dialog self.list_include = ListBox() self.list_exclude = ListBox() self.list_ignore = ListBox() # Populate list boxes from current settings self.fill_lists(types_include, types_exclude) # Set triggers when the lists receive the current focus self.list_include.clicked.connect( partial(self.clear_focus, [self.list_ignore, self.list_exclude]) ) self.list_exclude.clicked.connect( partial(self.clear_focus, [self.list_ignore, self.list_include]) ) self.list_ignore.clicked.connect( partial(self.clear_focus, [self.list_include, self.list_exclude]) ) # Add instructions to the dialog box instructions = QtWidgets.QLabel() instructions.setText( _( "Please select the contents of the image type 'Include' and 'Exclude' lists." ) ) instructions.setWordWrap(True) instructions.setSizePolicy( QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding, ) self.layout.addWidget(instructions) self.arrows_include = ArrowsColumn( self.list_include, self.list_ignore, callback=self.set_buttons_enabled_state, ) self.arrows_exclude = ArrowsColumn( self.list_exclude, self.list_ignore, callback=self.set_buttons_enabled_state, reverse=True, ) lists_layout = QtWidgets.QHBoxLayout() include_list_layout = QtWidgets.QVBoxLayout() include_list_layout.addWidget(QtWidgets.QLabel(_("Include types list"))) include_list_layout.addWidget(self.list_include) lists_layout.addLayout(include_list_layout) lists_layout.addWidget(self.arrows_include) ignore_list_layout = QtWidgets.QVBoxLayout() ignore_list_layout.addWidget(QtWidgets.QLabel("")) ignore_list_layout.addWidget(self.list_ignore) lists_layout.addLayout(ignore_list_layout) lists_layout.addWidget(self.arrows_exclude) exclude_list_layout = QtWidgets.QVBoxLayout() exclude_list_layout.addWidget(QtWidgets.QLabel(_("Exclude types list"))) exclude_list_layout.addWidget(self.list_exclude) lists_layout.addLayout(exclude_list_layout) self.layout.addLayout(lists_layout) # Add usage explanation to the dialog box instructions = QtWidgets.QLabel() instructions.setText( _( "CAA images with an image type found in the 'Include' list will be downloaded and used " "UNLESS they also have an image type found in the 'Exclude' list. Images with types " "found in the 'Exclude' list will NEVER be used. Image types not appearing in the 'Include' " "or 'Exclude' lists will not be considered when determining whether or not to download and " "use a CAA image.\n" ) ) instructions.setWordWrap(True) instructions.setSizePolicy( QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding, ) self.layout.addWidget(instructions) self.buttonbox = QtWidgets.QDialogButtonBox(self) self.buttonbox.setOrientation(QtCore.Qt.Orientation.Horizontal) self.buttonbox.addButton( StandardButton(StandardButton.OK), QtWidgets.QDialogButtonBox.ButtonRole.AcceptRole, ) self.buttonbox.addButton( StandardButton(StandardButton.CANCEL), QtWidgets.QDialogButtonBox.ButtonRole.RejectRole, ) self.buttonbox.addButton( StandardButton(StandardButton.HELP), QtWidgets.QDialogButtonBox.ButtonRole.HelpRole, ) extrabuttons = [ (N_("I&nclude all"), self.move_all_to_include_list), (N_("E&xclude all"), self.move_all_to_exclude_list), (N_("C&lear all"), self.move_all_to_ignore_list), (N_("Restore &Defaults"), self.reset_to_defaults), ] for label, callback in extrabuttons: button = QtWidgets.QPushButton(_(label)) self.buttonbox.addButton( button, QtWidgets.QDialogButtonBox.ButtonRole.ActionRole ) button.clicked.connect(callback) self.layout.addWidget(self.buttonbox) self.buttonbox.accepted.connect(self.accept) self.buttonbox.rejected.connect(self.reject) self.buttonbox.helpRequested.connect(self.show_help) self.set_buttons_enabled_state() def move_all_to_include_list(self): self.list_ignore.move_all_items(self.list_include) self.list_exclude.move_all_items(self.list_include) self.set_buttons_enabled_state() def move_all_to_exclude_list(self): self.list_ignore.move_all_items(self.list_exclude) self.list_include.move_all_items(self.list_exclude) self.set_buttons_enabled_state() def move_all_to_ignore_list(self): self.list_include.move_all_items(self.list_ignore) self.list_exclude.move_all_items(self.list_ignore) self.set_buttons_enabled_state() def fill_lists(self, includes, excludes): """Fill dialog listboxes. First clears the contents of the three listboxes, and then populates the listboxes from the dictionary of standard CAA types, using the provided 'includes' and 'excludes' lists to determine the appropriate list for each type. Arguments: includes -- list of standard image types to place in the "Include" listbox excludes -- list of standard image types to place in the "Exclude" listbox """ self.list_include.clear() self.list_exclude.clear() self.list_ignore.clear() for name, title in self._known_types.items(): item = QtWidgets.QListWidgetItem(title) item.setData(QtCore.Qt.ItemDataRole.UserRole, name) if name in includes: self.list_include.addItem(item) elif name in excludes: self.list_exclude.addItem(item) else: self.list_ignore.addItem(item) @property def included(self): return list(self.list_include.all_items_data()) or ["front"] @property def excluded(self): return list(self.list_exclude.all_items_data()) or ["none"] def clear_focus(self, lists): for temp_list in lists: temp_list.clearSelection() self.set_buttons_enabled_state() def reset_to_defaults(self): self.fill_lists(self._default_include, self._default_exclude) self.set_buttons_enabled_state() def set_buttons_enabled_state(self): has_items_include = self.list_include.count() has_items_exclude = self.list_exclude.count() has_items_ignore = self.list_ignore.count() has_selected_include = bool(self.list_include.selectedItems()) has_selected_exclude = bool(self.list_exclude.selectedItems()) has_selected_ignore = bool(self.list_ignore.selectedItems()) # "Include" list buttons self.arrows_include.button_add.setEnabled( has_items_ignore and has_selected_ignore ) self.arrows_include.button_add_all.setEnabled(has_items_ignore) self.arrows_include.button_remove.setEnabled( has_items_include and has_selected_include ) self.arrows_include.button_remove_all.setEnabled(has_items_include) # "Exclude" list buttons self.arrows_exclude.button_add.setEnabled( has_items_ignore and has_selected_ignore ) self.arrows_exclude.button_add_all.setEnabled(has_items_ignore) self.arrows_exclude.button_remove.setEnabled( has_items_exclude and has_selected_exclude ) self.arrows_exclude.button_remove_all.setEnabled(has_items_exclude) def display_caa_types_selector(**kwargs): dialog = CAATypesSelectorDialog(**kwargs) result = dialog.exec_() return ( dialog.included, dialog.excluded, result == QtWidgets.QDialog.DialogCode.Accepted, )
decrypters
HearthisAtFolder
# -*- coding: utf-8 -*- import re import urllib.parse from ..base.decrypter import BaseDecrypter class HearthisAtFolder(BaseDecrypter): __name__ = "HearthisAtFolder" __type__ = "decrypter" __version__ = "0.01" __status__ = "testing" __pattern__ = r"https?://(?:www\.)?hearthis\.at/.*(?<!#pyload)$" __config__ = [ ("enabled", "bool", "Activated", True), ("use_premium", "bool", "Use premium account if available", True), ( "folder_per_package", "Default;Yes;No", "Create folder for each package", "Default", ), ("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10), ("dl_subfolders", "bool", "Download subfolders", False), ("package_subfolder", "bool", "Subfolder as a separate package", False), ] __description__ = """Hearthis.at folder decrypter plugin""" __license__ = "GPLv3" __authors__ = [("GammaC0de", "nitzo2001[AT]yahoo[DOT]com")] def decrypt(self, pyfile): self.data = self.load(pyfile.url) m = re.search(r"intTrackId = (\d+);", self.data) if m is not None: #: Single track self.packages = [ (pyfile.package().name, pyfile.url + "#pyload", pyfile.package().folder) ] else: #: Playlist m = re.search(r"intInternalId = (\d+);", self.data) if m is None: self.fail(self._("Internal Id not found")) self.data = self.load( "https://hearthis.at/user_ajax_more.php", post={"user": m.group(1), "min": 0, "max": 200}, ) links = [ urllib.parse.urljoin(pyfile.url, x) + "#pyload" for x in re.findall( r'<a class="player-link".+?href="(.+?)".+?</a>', self.data, re.S ) ] self.packages = [(pyfile.package().name, links, pyfile.package().folder)]
migrations
0005_twilioaccount_twiliophonecallsender_twiliosmssender_twilioverificationsender
# Generated by Django 3.2.19 on 2023-05-25 15:32 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("twilioapp", "0004_twiliophonecall_twiliosms"), ] operations = [ migrations.CreateModel( name="TwilioAccount", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(max_length=100)), ("account_sid", models.CharField(max_length=64, unique=True)), ( "auth_token", models.CharField(default=None, max_length=64, null=True), ), ( "api_key_sid", models.CharField(default=None, max_length=64, null=True), ), ( "api_key_secret", models.CharField(default=None, max_length=64, null=True), ), ], ), migrations.CreateModel( name="TwilioVerificationSender", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(default="Default", max_length=100)), ( "country_code", models.CharField(default=None, max_length=16, null=True), ), ("verify_service_sid", models.CharField(max_length=64)), ( "account", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="twilioapp_twilioverificationsender_account", to="twilioapp.twilioaccount", ), ), ], options={ "abstract": False, }, ), migrations.CreateModel( name="TwilioSmsSender", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(default="Default", max_length=100)), ( "country_code", models.CharField(default=None, max_length=16, null=True), ), ("sender", models.CharField(max_length=16)), ( "account", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="twilioapp_twiliosmssender_account", to="twilioapp.twilioaccount", ), ), ], options={ "abstract": False, }, ), migrations.CreateModel( name="TwilioPhoneCallSender", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(default="Default", max_length=100)), ( "country_code", models.CharField(default=None, max_length=16, null=True), ), ("number", models.CharField(max_length=16)), ( "account", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="twilioapp_twiliophonecallsender_account", to="twilioapp.twilioaccount", ), ), ], options={ "abstract": False, }, ), ]
PartDesign
SprocketFeature
# *************************************************************************** # * Copyright (c) 2020 Adam Spontarelli <[email protected]> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** import FreeCAD import Part from fcsprocket import fcsprocket, sprocket if FreeCAD.GuiUp: import FreeCADGui from FreeCADGui import PySideUic as uic from PySide import QtCore, QtGui __title__ = "PartDesign SprocketObject management" __author__ = "Adam Spontarelli" __url__ = "http://www.freecad.org" def makeSprocket(name): """ makeSprocket(name): makes a Sprocket """ obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython", name) Sprocket(obj) if FreeCAD.GuiUp: ViewProviderSprocket(obj.ViewObject) # FreeCAD.ActiveDocument.recompute() if FreeCAD.GuiUp: body = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("pdbody") part = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("part") if body: body.Group = body.Group + [obj] elif part: part.Group = part.Group + [obj] return obj class CommandSprocket: """ the Fem Sprocket command definition """ def GetResources(self): return { "Pixmap": "PartDesign_Sprocket", "MenuText": QtCore.QT_TRANSLATE_NOOP("PartDesign_Sprocket", "Sprocket..."), "Accel": "", "ToolTip": QtCore.QT_TRANSLATE_NOOP( "PartDesign_Sprocket", "Creates or edit the sprocket definition." ), } def Activated(self): FreeCAD.ActiveDocument.openTransaction("Create Sprocket") FreeCADGui.addModule("SprocketFeature") FreeCADGui.doCommand("SprocketFeature.makeSprocket('Sprocket')") FreeCADGui.doCommand( "Gui.activeDocument().setEdit(App.ActiveDocument.ActiveObject.Name,0)" ) def IsActive(self): if FreeCAD.ActiveDocument: return True else: return False class Sprocket: """ The Sprocket object """ """ ANSI B29.1-2011 standard roller chain sizes in USCS units (inches) {size: [Pitch, Roller Diameter]} """ SprocketReferenceRollerTable = { "ANSI 25": [0.250, 0.130, 0.110], "ANSI 35": [0.375, 0.200, 0.168], "ANSI 41": [0.500, 0.306, 0.227], "ANSI 40": [0.500, 0.312, 0.284], "ANSI 50": [0.625, 0.400, 0.343], "ANSI 60": [0.750, 0.469, 0.459], "ANSI 80": [1.000, 0.625, 0.575], "ANSI 100": [1.250, 0.750, 0.692], "ANSI 120": [1.500, 0.875, 0.924], "ANSI 140": [1.750, 1.000, 0.924], "ANSI 160": [2.000, 1.125, 1.156], "ANSI 180": [2.250, 1.460, 1.301], "ANSI 200": [2.500, 1.562, 1.389], "ANSI 240": [3.000, 1.875, 1.738], "Bicycle with Derailleur": [0.500, 0.3125, 0.11], "Bicycle without Derailleur": [0.500, 0.3125, 0.084], "ISO 606 06B": [0.375, 5.72 / 25.4, 5.2 / 25.4], "ISO 606 08B": [0.500, 7.75 / 25.4, 7.0 / 25.4], "ISO 606 10B": [0.625, 9.65 / 25.4, 9.1 / 25.4], "ISO 606 12B": [0.750, 11.68 / 25.4, 11.1 / 25.4], "ISO 606 16B": [1.000, 17.02 / 25.4, 16.2 / 25.4], "ISO 606 20B": [1.250, 19.56 / 25.4, 18.5 / 25.4], "ISO 606 24B": [1.500, 25.4 / 25.4, 24.1 / 25.4], "Motorcycle 420": [0.500, 0.3125, 0.227], "Motorcycle 425": [0.500, 0.3125, 0.284], "Motorcycle 428": [0.500, 0.335, 0.284], "Motorcycle 520": [0.625, 0.400, 0.227], "Motorcycle 525": [0.625, 0.400, 0.284], "Motorcycle 530": [0.625, 0.400, 0.343], "Motorcycle 630": [0.750, 0.400, 0.343], } def __init__(self, obj): self.Type = "Sprocket" obj.addProperty( "App::PropertyInteger", "NumberOfTeeth", "Sprocket", "Number of gear teeth" ) obj.addProperty("App::PropertyLength", "Pitch", "Sprocket", "Chain Pitch") obj.addProperty( "App::PropertyLength", "RollerDiameter", "Sprocket", "Roller Diameter" ) obj.addProperty( "App::PropertyEnumeration", "SprocketReference", "Sprocket", "Sprocket Reference", ) obj.addProperty( "App::PropertyLength", "Thickness", "Sprocket", "Thickness as stated in the reference specification", ) obj.SprocketReference = list(self.SprocketReferenceRollerTable) obj.NumberOfTeeth = 50 obj.Pitch = "0.375 in" obj.RollerDiameter = "0.20 in" obj.SprocketReference = "ANSI 35" obj.Thickness = "0.11 in" obj.Proxy = self def execute(self, obj): w = fcsprocket.FCWireBuilder() sprocket.CreateSprocket( w, obj.Pitch.Value, obj.NumberOfTeeth, obj.RollerDiameter.Value ) sprocketw = Part.Wire([o.toShape() for o in w.wire]) obj.Shape = sprocketw obj.positionBySupport() return class ViewProviderSprocket: """ A View Provider for the Sprocket object """ def __init__(self, vobj): vobj.Proxy = self def getIcon(self): return ":/icons/PartDesign_Sprocket.svg" def attach(self, vobj): self.ViewObject = vobj self.Object = vobj.Object def setEdit(self, vobj, mode): taskd = SprocketTaskPanel(self.Object, mode) taskd.obj = vobj.Object taskd.update() FreeCADGui.Control.showDialog(taskd) return True def unsetEdit(self, vobj, mode): FreeCADGui.Control.closeDialog() return def dumps(self): return None def loads(self, state): return None class SprocketTaskPanel: """ The editmode TaskPanel for Sprocket objects """ def __init__(self, obj, mode): self.obj = obj self.form = FreeCADGui.PySideUic.loadUi( FreeCAD.getHomePath() + "Mod/PartDesign/SprocketFeature.ui" ) self.form.setWindowIcon(QtGui.QIcon(":/icons/PartDesign_Sprocket.svg")) QtCore.QObject.connect( self.form.Quantity_Pitch, QtCore.SIGNAL("valueChanged(double)"), self.pitchChanged, ) QtCore.QObject.connect( self.form.Quantity_RollerDiameter, QtCore.SIGNAL("valueChanged(double)"), self.rollerDiameterChanged, ) QtCore.QObject.connect( self.form.spinBox_NumberOfTeeth, QtCore.SIGNAL("valueChanged(int)"), self.numTeethChanged, ) QtCore.QObject.connect( self.form.comboBox_SprocketReference, QtCore.SIGNAL("currentTextChanged(const QString)"), self.sprocketReferenceChanged, ) QtCore.QObject.connect( self.form.Quantity_Thickness, QtCore.SIGNAL("valueChanged(double)"), self.thicknessChanged, ) self.update() if mode == 0: # fresh created self.obj.Proxy.execute(self.obj) # calculate once FreeCAD.Gui.SendMsgToActiveView("ViewFit") def transferTo(self): """ Transfer from the dialog to the object """ self.obj.NumberOfTeeth = self.form.spinBox_NumberOfTeeth.value() self.obj.Pitch = self.form.Quantity_Pitch.text() self.obj.RollerDiameter = self.form.Quantity_RollerDiameter.text() self.obj.SprocketReference = self.form.comboBox_SprocketReference.currentText() self.obj.Thickness = self.form.Quantity_Thickness.text() def transferFrom(self): """ Transfer from the object to the dialog """ self.form.spinBox_NumberOfTeeth.setValue(self.obj.NumberOfTeeth) self.form.Quantity_Pitch.setText(self.obj.Pitch.UserString) self.form.Quantity_RollerDiameter.setText(self.obj.RollerDiameter.UserString) self.form.comboBox_SprocketReference.setCurrentText(self.obj.SprocketReference) self.form.Quantity_Thickness.setText(self.obj.Thickness.UserString) def pitchChanged(self, value): self.obj.Pitch = value self.obj.Proxy.execute(self.obj) FreeCAD.Gui.SendMsgToActiveView("ViewFit") def sprocketReferenceChanged(self, size): self.obj.Pitch = str(Sprocket.SprocketReferenceRollerTable[size][0]) + " in" self.obj.RollerDiameter = ( str(Sprocket.SprocketReferenceRollerTable[size][1]) + " in" ) self.obj.Thickness = str(Sprocket.SprocketReferenceRollerTable[size][2]) + " in" self.obj.SprocketReference = str(size) self.form.Quantity_Pitch.setText(self.obj.Pitch.UserString) self.form.Quantity_RollerDiameter.setText(self.obj.RollerDiameter.UserString) self.form.Quantity_Thickness.setText(self.obj.Thickness.UserString) self.obj.Proxy.execute(self.obj) FreeCAD.Gui.SendMsgToActiveView("ViewFit") def rollerDiameterChanged(self, value): self.obj.RollerDiameter = value self.obj.Proxy.execute(self.obj) def numTeethChanged(self, value): self.obj.NumberOfTeeth = value self.obj.Proxy.execute(self.obj) FreeCAD.Gui.SendMsgToActiveView("ViewFit") def thicknessChanged(self, value): self.obj.Thickness = str(value) self.obj.Proxy.execute(self.obj) def getStandardButtons(self): return ( int(QtGui.QDialogButtonBox.Ok) | int(QtGui.QDialogButtonBox.Cancel) | int(QtGui.QDialogButtonBox.Apply) ) def clicked(self, button): if button == QtGui.QDialogButtonBox.Apply: self.transferTo() self.obj.Proxy.execute(self.obj) def update(self): self.transferFrom() def accept(self): self.transferTo() FreeCAD.ActiveDocument.recompute() FreeCADGui.ActiveDocument.resetEdit() def reject(self): FreeCADGui.ActiveDocument.resetEdit() FreeCAD.ActiveDocument.abortTransaction() if FreeCAD.GuiUp: FreeCADGui.addCommand("PartDesign_Sprocket", CommandSprocket())
code
planet
#!/usr/bin/env python """The Planet aggregator. A flexible and easy-to-use aggregator for generating websites. Visit http://www.planetplanet.org/ for more information and to download the latest version. Requires Python 2.1, recommends 2.3. """ __authors__ = [ "Scott James Remnant <[email protected]>", "Jeff Waugh <[email protected]>" ] __license__ = "Python" import locale import os import socket import sys import time import planet import urlparse from ConfigParser import ConfigParser # Default configuration file path CONFIG_FILE = "config.ini" # Defaults for the [Planet] config section PLANET_NAME = "Unconfigured Planet" PLANET_LINK = "Unconfigured Planet" PLANET_FEED = None OWNER_NAME = "Anonymous Coward" OWNER_EMAIL = "" LOG_LEVEL = "WARNING" FEED_TIMEOUT = 20 # seconds # Default template file list TEMPLATE_FILES = "examples/basic/planet.html.tmpl" def config_get(config, section, option, default=None, raw=0, vars=None): """Get a value from the configuration, with a default.""" if config.has_option(section, option): return config.get(section, option, raw=raw, vars=None) else: return default def main(): config_file = CONFIG_FILE offline = 0 verbose = 0 for arg in sys.argv[1:]: if arg == "-h" or arg == "--help": print "Usage: planet [options] [CONFIGFILE]" print print "Options:" print " -v, --verbose DEBUG level logging during update" print " -o, --offline Update the Planet from the cache only" print " -h, --help Display this help message and exit" print sys.exit(0) elif arg == "-v" or arg == "--verbose": verbose = 1 elif arg == "-o" or arg == "--offline": offline = 1 elif arg.startswith("-"): print >>sys.stderr, "Unknown option:", arg sys.exit(1) else: config_file = arg # Read the configuration file config = ConfigParser() config.read(config_file) if not config.has_section("Planet"): print >>sys.stderr, "Configuration missing [Planet] section." sys.exit(1) # Read the [Planet] config section planet_name = config_get(config, "Planet", "name", PLANET_NAME) planet_link = config_get(config, "Planet", "link", PLANET_LINK) planet_feed = config_get(config, "Planet", "feed", PLANET_FEED) owner_name = config_get(config, "Planet", "owner_name", OWNER_NAME) owner_email = config_get(config, "Planet", "owner_email", OWNER_EMAIL) if verbose: log_level = "DEBUG" else: log_level = config_get(config, "Planet", "log_level", LOG_LEVEL) feed_timeout = config_get(config, "Planet", "feed_timeout", FEED_TIMEOUT) template_files = config_get(config, "Planet", "template_files", TEMPLATE_FILES).split(" ") # Default feed to the first feed for which there is a template if not planet_feed: for template_file in template_files: name = os.path.splitext(os.path.basename(template_file))[0] if name.find('atom')>=0 or name.find('rss')>=0: planet_feed = urlparse.urljoin(planet_link, name) break # Define locale if config.has_option("Planet", "locale"): # The user can specify more than one locale (separated by ":") as # fallbacks. locale_ok = False for user_locale in config.get("Planet", "locale").split(':'): user_locale = user_locale.strip() try: locale.setlocale(locale.LC_ALL, user_locale) except locale.Error: pass else: locale_ok = True break if not locale_ok: print >>sys.stderr, "Unsupported locale setting." sys.exit(1) # Activate logging planet.logging.basicConfig() planet.logging.getLogger().setLevel(planet.logging.getLevelName(log_level)) log = planet.logging.getLogger("planet.runner") try: log.warning except: log.warning = log.warn if feed_timeout: try: feed_timeout = float(feed_timeout) except: log.warning("Feed timeout set to invalid value '%s', skipping", feed_timeout) feed_timeout = None if feed_timeout and not offline: socket.setdefaulttimeout(feed_timeout) log.debug("Socket timeout set to %d seconds", feed_timeout) # run the planet my_planet = planet.Planet(config) my_planet.run(planet_name, planet_link, template_files, offline) my_planet.generate_all_files(template_files, planet_name, planet_link, planet_feed, owner_name, owner_email) if __name__ == "__main__": main()
AppImage-builder
create_appimage
# Copyright (c) 2023 UltiMaker # Cura is released under the terms of the LGPLv3 or higher. import argparse import os import shutil import subprocess from pathlib import Path from jinja2 import Template def prepare_workspace(dist_path, appimage_filename): """ Prepare the workspace for building the AppImage. :param dist_path: Path to the distribution of Cura created with pyinstaller. :param appimage_filename: name of the AppImage file. :return: """ if not os.path.exists(dist_path): raise RuntimeError(f"The dist_path {dist_path} does not exist.") if os.path.exists(os.path.join(dist_path, appimage_filename)): os.remove(os.path.join(dist_path, appimage_filename)) if not os.path.exists("AppDir"): shutil.move(dist_path, "AppDir") else: print(f"AppDir already exists, assuming it is already prepared.") copy_files("AppDir") def build_appimage(dist_path, version, appimage_filename): """ Creates an AppImage file from the build artefacts created so far. """ generate_appimage_builder_config(dist_path, version, appimage_filename) create_appimage() sign_appimage(dist_path, appimage_filename) def generate_appimage_builder_config(dist_path, version, appimage_filename): with open( os.path.join(Path(__file__).parent, "AppImageBuilder.yml.jinja"), "r" ) as appimage_builder_file: appimage_builder = appimage_builder_file.read() template = Template(appimage_builder) appimage_builder = template.render( app_dir="./AppDir", icon="cura-icon.png", version=version, arch="x86_64", file_name=appimage_filename, ) with open( os.path.join(Path(__file__).parent, "AppImageBuilder.yml"), "w" ) as appimage_builder_file: appimage_builder_file.write(appimage_builder) def copy_files(dist_path): """ Copy metadata files for the metadata of the AppImage. """ copied_files = { os.path.join("..", "icons", "cura-icon.svg"): os.path.join( "usr", "share", "icons", "hicolor", "scalable", "apps", "cura-icon.svg" ), os.path.join("..", "icons", "cura-icon_64x64.png"): os.path.join( "usr", "share", "icons", "hicolor", "64x64", "apps", "cura-icon.png" ), os.path.join("..", "icons", "cura-icon_128x128.png"): os.path.join( "usr", "share", "icons", "hicolor", "128x128", "apps", "cura-icon.png" ), os.path.join("..", "icons", "cura-icon_256x256.png"): os.path.join( "usr", "share", "icons", "hicolor", "256x256", "apps", "cura-icon.png" ), os.path.join("..", "icons", "cura-icon_256x256.png"): "cura-icon.png", } # TODO: openssl.cnf ??? packaging_dir = os.path.dirname(__file__) for source, dest in copied_files.items(): dest_file_path = os.path.join(dist_path, dest) os.makedirs(os.path.dirname(dest_file_path), exist_ok=True) shutil.copyfile(os.path.join(packaging_dir, source), dest_file_path) def create_appimage(): appimagetool = os.getenv( "APPIMAGEBUILDER_LOCATION", "appimage-builder-x86_64.AppImage" ) command = [ appimagetool, "--recipe", os.path.join(Path(__file__).parent, "AppImageBuilder.yml"), "--skip-test", ] result = subprocess.call(command) if result != 0: raise RuntimeError(f"The AppImageTool command returned non-zero: {result}") def sign_appimage(dist_path, appimage_filename): command = ["gpg", "--yes", "--armor", "--detach-sig", appimage_filename] result = subprocess.call(command) if result != 0: raise RuntimeError(f"The GPG command returned non-zero: {result}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create AppImages of Cura.") parser.add_argument( "dist_path", type=str, help="Path to where PyInstaller installed the distribution of Cura.", ) parser.add_argument( "version", type=str, help="Full version number of Cura (e.g. '5.1.0-beta')" ) parser.add_argument( "filename", type=str, help="Filename of the AppImage (e.g. 'UltiMaker-Cura-5.1.0-beta-Linux-X64.AppImage')", ) args = parser.parse_args() prepare_workspace(args.dist_path, args.filename) build_appimage(args.dist_path, args.version, args.filename)
lib
strings
""" This file is part of the Stargate project, Copyright Stargate Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. """ from sglib.lib.translate import _ from sglib.lib.util import KEY_ALT, KEY_CTRL audio_viewer_widget_papifx = _( """\ This tab allows you to set effects per-audio file. There will be exactly one instance of these effects per audio file. Use this as a mixing aid for EQ, filter, etc... on a file.""" ) audio_viewer_widget_paifx = _( """\ This tab allows you to set effects per-audio-item. The effects will be unique per instance of an audio file, and not share between instances.""" ) timestretch_modes = { 0: "No stretching or pitch adjustment", 1: ( "Repitch the item, it will become shorter at higher pitches, and " "longer at lower pitches" ), 2: ( "Stretch the item to the desired length, it will have lower pitch " "at longer lengths, and higher pitch at shorter lengths" ), 3: "Adjust pitch and time independently", 4: ( "Same as Rubberband, but preserves formants when pitch shifting. " "Useful on vocal materials, an auto-tune type of pitch shifting" ), 5: ( "Adjust pitch and time independently, also with the ability to " "set start/end pitch/time differently" ), 6: ( "Mostly for stretching items very long, creates a very smeared, " "atmospheric sound. Useful for creative reverb-like effects and " "soundscapes" ), 7: ( "A good timestretching algorithm for many types of materials. " "Optimized for full pieces of music" ), 8: ( "A good timestretching algorithm for many types of materials. " "Optimized for speech" ), } avconv_error = _( """\ Please ensure that ffmpeg (or avconv) and lame are installed. cannot open mp3 converter dialog. Check your normal sources for packages or visit: http://lame.sourceforge.net http://ffmpeg.org Cannot find {}""" ) export_format = _( """File is exported to 32 bit .wav at the sample rate your audio interface is running at. You can convert the format using the Menu->Tools dialogs""" ) pitchbend_dialog = _( """\ Pitchbend values are in semitones. Use this dialog to add points with precision,or double-click on the editor to add points.""" ) PianoRollEditor = f""" Edit MIDI notes. See the "Parameter" combobox, the menu button and the mouse tools in the transport panel. Draw notes holding {KEY_ALT} to move instead of change length """ AudioItemSeq = _( """\ Item editor for audio. Each sequencer item can contain multiple audio items in addition to MIDI. Drag audio files from the file browser onto here. """ ) AudioSeqItem = _( f""" Audio item. Right click: actions. {KEY_CTRL}+{KEY_ALT}+drag: item volume, CTRL+SHIFT+drag: vol. curve, {KEY_ALT}+SHIFT+drag: file vol. {KEY_CTRL}+drag: copy, {KEY_ALT}+click: multi-select """ ) AUDIO_SEQ_HELP = """\ Select 1+ items, CTRL+click+drag up/down/left/right to copy selected items Select 1+ items, ALT+SHIFT+Click and drag up/down: Modify the volume of the file. This is useful for mixing, as it modifies the volume of every instance of the file in the entire project. Select 1+ items, CTRL+ALT+Click and drag up/down: Modify the volume of selected items. Different audio items in the same sequencer item can have different volumes using this technique. Select 1+ items, CTRL+SHIFT+Click and drag up/down: Create a volume line for the selected items. For example, you have the same kick drum sample repeated 4 times in an item, one beat apart from each other. Select all of them, perform this mouse gesture by clicking on the first one and dragging down. The respective values might be -9dB, -6dB, -3dB, 0dB, getting progressively louder. See the menu button above for additional actions""" multiple_instances_warning = _( """\ Detected that there are instances of the Stargate audio engine already running. This could mean that you already have Stargate running, if so you should click 'Cancel' and close the other instance. This could also mean that for some reason the engine did not properly terminate from another session. If so, click 'OK' to kill the other process(es)""" ) routing_graph = _( """\ Audio (click), sidechain(CTRL+click) and MIDI(SHIFT+click) routing between tracks. Click below the dest. to route to lower numbered tracks, above for higher. Double click a track to open plugins """ ) track_panel_dropdown = _( """\ The dropdown menu contains a shortcut to the track plugins (instrument and effects), and controls for selecting parameters for automation. For a global view of track sends, see the routing tab.""" ) """ A track can be any or all of audio, MIDI, send or bus, at the same time. Instrument plugins can be placed before or after effect plugins, and will pass-through any audio from items or sends. """ ENGINE_MON = """\ Shows CPU and memory percentage. Note that the CPU usage is a max of the cores that are in use, not based on the average of CPU load and available logical cores, which is less useful. """ NO_AUDIO_INPUTS_INSTRUCTIONS = """\ No audio inputs available. If you are using an audio device with inputs, press the Hardware Settings button and ensure that the audio inputs control is set to a number greater than 0. """
accounts
UpleaCom
# -*- coding: utf-8 -*- import re import time from ..base.account import BaseAccount class UpleaCom(BaseAccount): __name__ = "UpleaCom" __type__ = "account" __version__ = "0.02" __status__ = "testing" __description__ = """UpleaCom account plugin""" __license__ = "GPLv3" __authors__ = [("GammaC0de", "nitzo2001[AT]yahoo[DOT]com")] LOGIN_URL = r"http://uplea.com" LOGIN_SKIP_PATTERN = r'>DISCONNECT</span> <span class="agbold">ME NOW<' PREMIUM_PATTERN = r"Uplea premium member <" VALID_UNTIL_PATTERN = r"You\'re premium member until .+?>([\d/]+)" def grab_info(self, user, password, data): trafficleft = -1 html = self.load("http://uplea.com/account") if re.search(self.PREMIUM_PATTERN, html): premium = True m = re.search(self.VALID_UNTIL_PATTERN, html) if m is None: premium = False validuntil = -1 else: premium = True validuntil = time.mktime(time.strptime(m.group(1), "%d/%m/%Y")) return { "premium": premium, "trafficleft": trafficleft, "validuntil": validuntil, } def signin(self, user, password, data): html = self.load("http://uplea.com") if self.LOGIN_SKIP_PATTERN in html: self.skip_login() html = self.load( "http://uplea.com", post={"login": user, "password": password, "remember": 0, "login-form": ""}, ) if self.LOGIN_SKIP_PATTERN not in html: self.fail_login()
gui
toolbar
# This file is part of MyPaint. # Copyright (C) 2011-2018 by the MyPaint Development Team. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. """The application toolbar, and its specialised widgets""" ## Imports from __future__ import division, print_function import os from gettext import gettext as _ from lib.gibindings import Gtk from . import widgets ## Module constants FRAMEWORK_XML = "toolbar.xml" MERGEABLE_XML = [ ("toolbar1_file", "toolbar-file.xml", _("File handling")), ("toolbar1_scrap", "toolbar-scrap.xml", _("Scraps switcher")), ("toolbar1_edit", "toolbar-edit.xml", _("Undo and Redo")), ("toolbar1_blendmodes", "toolbar-blendmodes.xml", _("Blend Modes")), ("toolbar1_linemodes", "toolbar-linemodes.xml", _("Line Modes")), ("toolbar1_view_modes", "toolbar-view-modes.xml", _("View (Main)")), ( "toolbar1_view_manips", "toolbar-view-manips.xml", _("View (Alternative/Secondary)"), ), ("toolbar1_view_resets", "toolbar-view-resets.xml", _("View (Resetting)")), ] ## Class definitions class ToolbarManager(object): """Manager for toolbars, currently just the main one. The main toolbar, /toolbar1, contains a menu button and quick access to the painting tools. """ def __init__(self, draw_window): super(ToolbarManager, self).__init__() self.draw_window = draw_window self.app = draw_window.app self.toolbar1_ui_loaded = {} # {name: merge_id, ...} self.init_actions() ui_dir = os.path.dirname(os.path.abspath(__file__)) toolbarpath = os.path.join(ui_dir, FRAMEWORK_XML) self.app.ui_manager.add_ui_from_file(toolbarpath) self.toolbar1 = self.app.ui_manager.get_widget("/toolbar1") self.toolbar1.set_style(Gtk.ToolbarStyle.ICONS) self.toolbar1.set_icon_size(widgets.get_toolbar_icon_size()) self.toolbar1.set_border_width(0) self.toolbar1.set_show_arrow(True) self.toolbar1.connect("popup-context-menu", self.on_toolbar1_popup_context_menu) self.toolbar1_popup = self.app.ui_manager.get_widget("/toolbar1-settings-menu") for item in self.toolbar1: if isinstance(item, Gtk.SeparatorToolItem): item.set_draw(False) self.toolbar2 = self.app.ui_manager.get_widget("/toolbar2") self.toolbar2.set_style(Gtk.ToolbarStyle.ICONS) self.toolbar2.set_icon_size(widgets.get_toolbar_icon_size()) self.toolbar2.set_border_width(0) self.toolbar2.set_show_arrow(False) for toolbar in (self.toolbar1, self.toolbar2): styles = toolbar.get_style_context() styles.add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) # Merge in UI pieces based on the user's saved preferences for action in self.settings_actions: name = action.get_property("name") active = self.app.preferences["ui.toolbar_items"].get(name, False) action.set_active(active) action.toggled() def init_actions(self): ag = self.draw_window.action_group actions = [] self.settings_actions = [] for name, ui_xml, label in MERGEABLE_XML: action = Gtk.ToggleAction.new(name, label, None, None) action.connect("toggled", self.on_settings_toggle, ui_xml) self.settings_actions.append(action) actions += self.settings_actions for action in actions: ag.add_action(action) def on_toolbar1_popup_context_menu(self, toolbar, x, y, button): menu = self.toolbar1_popup def _posfunc(*a): return x, y, True time = Gtk.get_current_event_time() menu.popup(None, None, _posfunc, None, button, time) def on_settings_toggle(self, toggleaction, ui_xml_file): name = toggleaction.get_property("name") merge_id = self.toolbar1_ui_loaded.get(name, None) if toggleaction.get_active(): self.app.preferences["ui.toolbar_items"][name] = True if merge_id is not None: return ui_dir = os.path.dirname(os.path.abspath(__file__)) ui_xml_path = os.path.join(ui_dir, ui_xml_file) merge_id = self.app.ui_manager.add_ui_from_file(ui_xml_path) self.toolbar1_ui_loaded[name] = merge_id else: self.app.preferences["ui.toolbar_items"][name] = False if merge_id is None: return self.app.ui_manager.remove_ui(merge_id) self.toolbar1_ui_loaded.pop(name)
engines
postgresql
# SPDX-License-Identifier: AGPL-3.0-or-later """ PostgreSQL database (Offline) """ # error is ignored because the admin has to # install it manually to use the engine # pylint: disable=import-error import psycopg2 engine_type = "offline" host = "127.0.0.1" port = "5432" database = "" username = "" password = "" query_str = "" limit = 10 paging = True result_template = "key-value.html" _connection = None def init(engine_settings): if "query_str" not in engine_settings: raise ValueError("query_str cannot be empty") if not engine_settings["query_str"].lower().startswith("select "): raise ValueError("only SELECT query is supported") global _connection _connection = psycopg2.connect( database=database, user=username, password=password, host=host, port=port, ) def search(query, params): query_params = {"query": query} query_to_run = query_str + " LIMIT {0} OFFSET {1}".format( limit, (params["pageno"] - 1) * limit ) with _connection: with _connection.cursor() as cur: cur.execute(query_to_run, query_params) return _fetch_results(cur) def _fetch_results(cur): results = [] titles = [] try: titles = [column_desc.name for column_desc in cur.description] for res in cur: result = dict(zip(titles, map(str, res))) result["template"] = result_template results.append(result) # no results to fetch except psycopg2.ProgrammingError: pass return results
ofdm
benchmark_add_channel
#!/usr/bin/env python # # Copyright 2010,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # import math import random import sys from optparse import OptionParser from gnuradio import blocks, channels, eng_notation, gr from gnuradio.eng_option import eng_option class my_top_block(gr.top_block): def __init__(self, ifile, ofile, options): gr.top_block.__init__(self) SNR = 10.0 ** (options.snr / 10.0) time_offset = options.time_offset phase_offset = options.phase_offset * (math.pi / 180.0) # calculate noise voltage from SNR power_in_signal = abs(options.tx_amplitude) ** 2 noise_power = power_in_signal / SNR noise_voltage = math.sqrt(noise_power) print("Noise voltage: ", noise_voltage) frequency_offset = options.frequency_offset / options.fft_length self.src = blocks.file_source(gr.sizeof_gr_complex, ifile) # self.throttle = blocks.throttle(gr.sizeof_gr_complex, options.sample_rate) self.channel = channels.channel_model( noise_voltage, frequency_offset, time_offset, noise_seed=-random.randint(0, 100000), ) self.phase = blocks.multiply_const_cc( complex(math.cos(phase_offset), math.sin(phase_offset)) ) self.snk = blocks.file_sink(gr.sizeof_gr_complex, ofile) self.connect(self.src, self.channel, self.phase, self.snk) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// def main(): # Create Options Parser: usage = "benchmack_add_channel.py [options] <input file> <output file>" parser = OptionParser( usage=usage, option_class=eng_option, conflict_handler="resolve" ) parser.add_option( "-n", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]", ) parser.add_option( "", "--seed", action="store_true", default=False, help="use a random seed for AWGN noise [default=%default]", ) parser.add_option( "-f", "--frequency-offset", type="eng_float", default=0, help="set frequency offset introduced by channel [default=%default]", ) parser.add_option( "-t", "--time-offset", type="eng_float", default=1.0, help="set timing offset between Tx and Rx [default=%default]", ) parser.add_option( "-p", "--phase-offset", type="eng_float", default=0, help="set phase offset (in degrees) between Tx and Rx [default=%default]", ) parser.add_option( "-m", "--use-multipath", action="store_true", default=False, help="Use a multipath channel [default=%default]", ) parser.add_option( "", "--fft-length", type="intx", default=None, help="set the number of FFT bins [default=%default]", ) parser.add_option( "", "--tx-amplitude", type="eng_float", default=1.0, help="tell the simulator the signal amplitude [default=%default]", ) (options, args) = parser.parse_args() if len(args) != 2: parser.print_help(sys.stderr) sys.exit(1) if options.fft_length is None: sys.stderr.write("Please enter the FFT length of the OFDM signal.\n") sys.exit(1) ifile = args[0] ofile = args[1] # build the graph tb = my_top_block(ifile, ofile, options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print("Warning: Failed to enable realtime scheduling.") tb.start() # start flow graph tb.wait() # wait for it to finish if __name__ == "__main__": try: main() except KeyboardInterrupt: pass
radio-crawler
fetch_cast
#!/usr/bin/env python2 # Copyright 2011,2014 Christoph Reiter # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. """ Loads and parses shoutcast/icecast pages and also adds new stream uris. """ import traceback from multiprocessing import Pool import cPickle as pickle from util import ( LISTENERCURRENT, LISTENERPEAK, ParseError, get_cache, get_failed, get_root, parse_icecast, parse_shoutcast1, parse_shoutcast2, set_cache, set_failed, ) PROCESSES = 20 PARSE_FAILED = "cast_failed.txt" def get_parse_failed(path=PARSE_FAILED): try: with open(path, "rb") as h: return set(filter(None, h.read().splitlines())) except IOError: return set() def set_parse_failed(failed_uris, path=PARSE_FAILED): with open(path, "wb") as h: h.write("\n".join(sorted(set(failed_uris)))) def fetch_stream_infos(uri): """Returns a list of Stream objects (can be empty)""" try: return uri, [parse_shoutcast1(uri)] except ParseError: pass except: print(uri) traceback.print_exc() raise try: return uri, parse_icecast(uri) except ParseError: pass except: print(uri) traceback.print_exc() raise try: return uri, parse_shoutcast2(uri) except ParseError: pass except: print(uri) traceback.print_exc() raise return uri, [] def main(): cache = get_cache() failed_uris = get_failed() parse_failed_uris = get_parse_failed() uris = cache.keys() peak_missing = [uri for uri in uris if LISTENERPEAK not in cache[uri]] peak_missing = set(peak_missing) - failed_uris # XXX: fetch_stream_infos is the same for each root url peak_missing = {get_root(uri) for uri in peak_missing} peak_missing = set(peak_missing) - parse_failed_uris pool = Pool(PROCESSES) try: pfunc = fetch_stream_infos for i, res in enumerate(pool.imap_unordered(pfunc, peak_missing)): uri, streams = res # save all 1000 if (i + 1) % 1000 == 0: set_cache(cache) print("%d/%d " % (i + 1, len(peak_missing)) + uri + " -> ", end="") print("%d new streams" % len(streams)) if not streams: parse_failed_uris.add(uri) # add new found uris to cache + listener count for stream in streams: peak = str(int(stream.peak)) current = str(int(stream.current)) uri = stream.stream if uri not in cache: cache[uri] = {} if LISTENERPEAK in cache[uri]: cache[uri][LISTENERPEAK].append(peak) else: cache[uri][LISTENERPEAK] = [peak] if LISTENERCURRENT in cache[uri]: cache[uri][LISTENERCURRENT].append(current) else: cache[uri][LISTENERCURRENT] = [current] except Exception as e: print(e) finally: set_parse_failed(parse_failed_uris) set_cache(cache) pool.terminate() pool.join() if __name__ == "__main__": main()
clientScripts
identify_file_format
#!/usr/bin/env python import argparse import multiprocessing import uuid import django django.setup() from databaseFunctions import getUTCDate, insertIntoEvents from django.db import transaction # archivematicaCommon from executeOrRunSubProcess import executeOrRun # dashboard from fpr.models import FormatVersion, IDCommand, IDRule from main.models import File, FileFormatVersion, FileID, UnitVariable def concurrent_instances(): return multiprocessing.cpu_count() def _save_id_preference(file_, value): """ Saves whether file format identification is being used. This is necessary in order to allow post-extraction identification to work. The replacement dict will be saved to the special 'replacementDict' unit variable, which will be transformed back into a passVar when a new chain in the same unit is begun. """ value = str(value) # The unit_uuid foreign key can point to a transfer or SIP, and this tool # runs in both. # Check the SIP first - if it hasn't been assigned yet, then this is being # run during the transfer. unit = file_.sip or file_.transfer rd = {"%IDCommand%": value} UnitVariable.objects.create( unituuid=unit.pk, variable="replacementDict", variablevalue=str(rd) ) def write_identification_event(file_uuid, command, format=None, success=True): event_detail_text = 'program="{}"; version="{}"'.format( command.tool.description, command.tool.version ) if success: event_outcome_text = "Positive" else: event_outcome_text = "Not identified" if not format: format = "No Matching Format" date = getUTCDate() insertIntoEvents( fileUUID=file_uuid, eventIdentifierUUID=str(uuid.uuid4()), eventType="format identification", eventDateTime=date, eventDetail=event_detail_text, eventOutcome=event_outcome_text, eventOutcomeDetailNote=format, ) def write_file_id(file_uuid, format, output): """ Write the identified format to the DB. :param str file_uuid: UUID of the file identified :param FormatVersion format: FormatVersion it was identified as :param str output: Text that generated the match """ if format.pronom_id: format_registry = "PRONOM" key = format.pronom_id else: format_registry = "Archivematica Format Policy Registry" key = output # Sometimes, this is null instead of an empty string version = format.version or "" FileID.objects.create( file_id=file_uuid, format_name=format.format.description, format_version=version, format_registry_name=format_registry, format_registry_key=key, ) def _default_idcommand(): """Retrieve the default ``fpr.IDCommand``. We only expect to find one command enabled/active. """ return IDCommand.active.first() def main(job, enabled, file_path, file_uuid, disable_reidentify): enabled = True if enabled == "True" else False if not enabled: job.print_output("Skipping file format identification") return 0 command = _default_idcommand() if command is None: job.write_error("Unable to determine IDCommand.\n") return 255 command_uuid = command.uuid job.print_output("IDCommand:", command.description) job.print_output("IDCommand UUID:", command.uuid) job.print_output("IDTool:", command.tool.description) job.print_output("IDTool UUID:", command.tool.uuid) job.print_output(f"File: ({file_uuid}) {file_path}") file_ = File.objects.get(uuid=file_uuid) # If reidentification is disabled and a format identification event exists for this file, exit if ( disable_reidentify and file_.event_set.filter(event_type="format identification").exists() ): job.print_output( "This file has already been identified, and re-identification is disabled. Skipping." ) return 0 # Save whether identification was enabled by the user for use in a later # chain. _save_id_preference(file_, enabled) exitcode, output, err = executeOrRun( command.script_type, command.script, arguments=[file_path], printing=False, capture_output=True, ) output = output.strip() if exitcode != 0: job.print_error(f"Error: IDCommand with UUID {command_uuid} exited non-zero.") job.print_error(f"Error: {err}") return 255 job.print_output("Command output:", output) # PUIDs are the same regardless of tool, so PUID-producing tools don't have "rules" per se - we just # go straight to the FormatVersion table to see if there's a matching PUID try: if command.config == "PUID": version = FormatVersion.active.get(pronom_id=output) else: rule = IDRule.active.get(command_output=output, command=command) version = rule.format except IDRule.DoesNotExist: job.print_error( 'Error: No FPR identification rule for tool output "{}" found'.format( output ) ) write_identification_event(file_uuid, command, success=False) return 255 except IDRule.MultipleObjectsReturned: job.print_error( 'Error: Multiple FPR identification rules for tool output "{}" found'.format( output ) ) write_identification_event(file_uuid, command, success=False) return 255 except FormatVersion.DoesNotExist: job.print_error(f"Error: No FPR format record found for PUID {output}") write_identification_event(file_uuid, command, success=False) return 255 (ffv, created) = FileFormatVersion.objects.get_or_create( file_uuid=file_, defaults={"format_version": version} ) if not created: # Update the version if it wasn't created new ffv.format_version = version ffv.save() job.print_output(f"{file_path} identified as a {version.description}") write_identification_event(file_uuid, command, format=version.pronom_id) write_file_id(file_uuid=file_uuid, format=version, output=output) return 0 def call(jobs): parser = argparse.ArgumentParser(description="Identify file formats.") # Since AM19 the accepted values are "True" or "False" since the ability to # choose the command from the workflow has been removed. Instead, this # script will look up in FPR what's the preferred command. # This argument may be renamed later. parser.add_argument("idcommand", type=str, help="%IDCommand%") parser.add_argument("file_path", type=str, help="%relativeLocation%") parser.add_argument("file_uuid", type=str, help="%fileUUID%") parser.add_argument( "--disable-reidentify", action="store_true", help="Disable identification if it has already happened for this file.", ) with transaction.atomic(): for job in jobs: with job.JobContext(): args = parser.parse_args(job.args[1:]) job.set_status( main( job, args.idcommand, args.file_path, args.file_uuid, args.disable_reidentify, ) )
dissemin
model_gettext
# coding:utf-8 gettext("Computer science, knowledge & systems") gettext("Bibliographies") gettext("Library & information sciences") gettext("Encyclopedias & books of facts") gettext("Magazines, journals & serials") gettext("Associations, organizations & museums") gettext("News media, journalism & publishing") gettext("Quotations") gettext("Manuscripts & rare books") gettext("Philosophy") gettext("Metaphysics") gettext("Epistemology") gettext("Parapsychology & occultism") gettext("Philosophical schools of thought") gettext("Psychology") gettext("Philosophical logic") gettext("Ethics") gettext("Ancient, medieval & eastern philosophy") gettext("Modern western philosophy") gettext("Religion") gettext("Philosophy & theory of religion") gettext("The Bible") gettext("Christianity") gettext("Christian practice & observance") gettext("Christian pastoral practice & religious orders") gettext("Christian organization, social work & worship") gettext("History of Christianity") gettext("Christian denominations") gettext("Other religions") gettext("Social sciences, sociology & anthropology") gettext("Statistics") gettext("Political science") gettext("Economics") gettext("Law") gettext("Public administration & military science") gettext("Social problems & social services") gettext("Education") gettext("Commerce, communications & transportation") gettext("Customs, etiquette & folklore") gettext("Language") gettext("Linguistics") gettext("English & Old English languages") gettext("German & related languages") gettext("French & related languages") gettext("Italian, Romanian & related languages") gettext("Spanish, Portuguese, Galician") gettext("Latin & Italic languages") gettext("Classical & modern Greek languages") gettext("Other languages") gettext("Science") gettext("Mathematics") gettext("Astronomy") gettext("Physics") gettext("Chemistry") gettext("Earth sciences & geology") gettext("Fossils & prehistoric life") gettext("Biology") gettext("Plants (Botany)") gettext("Animals (Zoology)") gettext("Technology") gettext("Medicine & health") gettext("Engineering") gettext("Agriculture") gettext("Home & family management") gettext("Management & public relations") gettext("Chemical engineering") gettext("Manufacturing") gettext("Manufacture for specific uses") gettext("Construction of buildings") gettext("Arts") gettext("Area planning & landscape architecture") gettext("Architecture") gettext("Sculpture, ceramics & metalwork") gettext("Graphic arts & decorative arts") gettext("Painting") gettext("Printmaking & prints") gettext("Photography, computer art, film, video") gettext("Music") gettext("Sports, games & entertainment") gettext("Literature, rhetoric & criticism") gettext("American literature in English") gettext("English & Old English literatures") gettext("German & related literatures") gettext("French & related literatures") gettext("Italian, Romanian & related literatures") gettext("Spanish, Portuguese, Galician literatures") gettext("Latin & Italic literatures") gettext("Classical & modern Greek literatures") gettext("Other literatures") gettext("History") gettext("Geography & travel") gettext("Biography & genealogy") gettext("History of ancient world (to ca. 499)") gettext("History of Europe") gettext("History of Asia") gettext("History of Africa") gettext("History of North America") gettext("History of South America") gettext("History of other areas") gettext("Data processing & computer science") gettext("Military science") gettext("Other Germanic languages") gettext("Public performances") gettext("Stage presentations") gettext("Indoor games & amusements") gettext("Athletic & outdoor sports & games") gettext("Other Germanic literatures") gettext("Germany & neighboring central European countries") gettext("Green Open Access Service") gettext( 'Would you like that the University and State Library Darmstadt publishes your publications green open access for you?\n<br/>\nContact us: <a href="mailto:[email protected]">[email protected]</a>' ) gettext("TUprints contract required!") gettext( "We need the TUprints agreement for all documents uploaded through Dissemin. After authentification with your TU-ID, please fill out the agreement and send it digitally. A signature is not necessary." ) gettext("Fill in agreement") gettext("Contract necessary!") gettext( "Before we can publish your publication, we need the completely filled in and signed publication agreement, which you can send to Braunschweig University Library by e-mail, fax or postal mail." ) gettext("Download Contract") gettext("Creative Commons 1.0 Universal (CC0 1.0) Public Domain Dedication") gettext("Creative Commons Attribution 4.0 International (CC BY 4.0)") gettext("Creative Commons Attribution-ShareAlike 4.0, International (CC BY-SA 4.0)") gettext("Creative Commons Attribution-NonCommerical 4.0 International (CC BY-NC 4.0)") gettext("Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)") gettext( "Free for private use; right holder retains other rights, including distribution" ) gettext("Other open license") gettext("No license") gettext( "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)" ) gettext( "Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)" ) gettext("Zenodo") gettext( "Zenodo is a general-purpose open repository hosted by CERN. If the document does not have a DOI yet, Zenodo will create one." ) gettext("HAL") gettext( "HAL is a multidisciplinary open archive, sustained by the French Research Ministry." ) gettext("OSF preprints") gettext( "Run by the Center for Open Science, OSF lets you share your preprints openly. You can also share supplemental data, materials or code associated with your article." ) gettext("TUprints") gettext( "TUprints is the open access repository for all current and former members of the Technical University Darmstadt." ) gettext("Institutional Repository of TU Braunschweig") gettext( "Researchers at TU Braunschweig can publish their first and second (self archiving) publications Open Access on the official publication server of TU Braunschweig." )
aliceVision
PanoramaPostProcessing
__version__ = "2.0" import json import os from meshroom.core import desc class PanoramaPostProcessing(desc.CommandLineNode): commandLine = "aliceVision_panoramaPostProcessing {allParams}" cpu = desc.Level.NORMAL ram = desc.Level.INTENSIVE category = "Panorama HDR" documentation = """ Post process the panorama. """ inputs = [ desc.File( name="inputPanorama", label="Input Panorama", description="Input panorama image.", value="", uid=[0], ), desc.BoolParam( name="fillHoles", label="Fill Holes Algorithm", description="Fill the non attributed pixels with push pull algorithm if set.", value=False, uid=[0], ), desc.BoolParam( name="exportLevels", label="Export Downscaled Levels", description="Export downscaled panorama levels.", value=False, uid=[0], ), desc.IntParam( name="lastLevelMaxSize", label="Last Level Max Size", description="Maximum width of smallest downscaled panorama level.", value=3840, range=(1, 100000), uid=[0], ), desc.IntParam( name="previewSize", label="Panorama Preview Width", description="The width (in pixels) of the output panorama preview.", value=1000, range=(0, 5000, 100), uid=[0], ), desc.ChoiceParam( name="outputColorSpace", label="Output Color Space", description="The color space of the output image.", value="Linear", values=["sRGB", "rec709", "Linear", "ACES2065-1", "ACEScg"], exclusive=True, uid=[0], ), desc.ChoiceParam( name="compressionMethod", label="Compression Method", description="Compression method for output EXR image.", value="auto", values=[ "none", "auto", "rle", "zip", "zips", "piz", "pxr24", "b44", "b44a", "dwaa", "dwab", ], exclusive=True, uid=[0], ), desc.IntParam( name="compressionLevel", label="Compression Level", description="Level of compression for the output EXR image. The range depends on method used.\n" "For zip/zips methods, values must be between 1 and 9.\n" "A value of 0 will be ignored, default value for the selected method will be used.", value=0, range=(0, 500, 1), uid=[0], enabled=lambda node: node.compressionMethod.value in ["dwaa", "dwab", "zip", "zips"], ), desc.StringParam( name="panoramaName", label="Output Panorama Name", description="Name of the output panorama.", value="panorama.exr", uid=[], group=None, advanced=True, ), desc.StringParam( name="previewName", label="Panorama Preview Name", description="Name of the preview of the output panorama.", value="panoramaPreview.jpg", uid=[], group=None, advanced=True, ), desc.ChoiceParam( name="verboseLevel", label="Verbose Level", description="Verbosity level (fatal, error, warning, info, debug, trace).", value="info", values=["fatal", "error", "warning", "info", "debug", "trace"], exclusive=True, uid=[], ), ] outputs = [ desc.File( name="outputPanorama", label="Output Panorama", description="Generated panorama in EXR format.", semantic="image", value=lambda attr: desc.Node.internalFolder + attr.node.panoramaName.value, uid=[], ), desc.File( name="outputPanoramaPreview", label="Output Panorama Preview", description="Preview of the generated panorama in JPG format.", semantic="image", value=lambda attr: desc.Node.internalFolder + attr.node.previewName.value, uid=[], ), desc.File( name="downscaledPanoramaLevels", label="Downscaled Panorama Levels", description="Downscaled versions of the generated panorama.", value=lambda attr: desc.Node.internalFolder + os.path.splitext(attr.node.panoramaName.value)[0] + "_level_*.exr", uid=[], group="", ), ]
gui
import_network_panel
# -------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer # Homepage: http://www.softwarepublico.gov.br # Contact: [email protected] # License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt) # -------------------------------------------------------------------------- # Este programa e software livre; voce pode redistribui-lo e/ou # modifica-lo sob os termos da Licenca Publica Geral GNU, conforme # publicada pela Free Software Foundation; de acordo com a versao 2 # da Licenca. # # Este programa eh distribuido na expectativa de ser util, mas SEM # QUALQUER GARANTIA; sem mesmo a garantia implicita de # COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM # PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais # detalhes. # -------------------------------------------------------------------------- import sys import invesalius.constants as const import invesalius.gui.dialogs as dlg import invesalius.net.dicom as dcm_net # import invesalius.gui.dicom_preview_panel as dpp import invesalius.reader.dicom_grouper as dcm import wx import wx.gizmos as gizmos # from dicionario import musicdata import wx.lib.mixins.listctrl as listmix import wx.lib.splitter as spl from invesalius.pubsub import pub as Publisher from wx.lib.mixins.listctrl import CheckListCtrlMixin myEVT_SELECT_SERIE = wx.NewEventType() EVT_SELECT_SERIE = wx.PyEventBinder(myEVT_SELECT_SERIE, 1) myEVT_SELECT_SLICE = wx.NewEventType() EVT_SELECT_SLICE = wx.PyEventBinder(myEVT_SELECT_SLICE, 1) myEVT_SELECT_PATIENT = wx.NewEventType() EVT_SELECT_PATIENT = wx.PyEventBinder(myEVT_SELECT_PATIENT, 1) myEVT_SELECT_SERIE_TEXT = wx.NewEventType() EVT_SELECT_SERIE_TEXT = wx.PyEventBinder(myEVT_SELECT_SERIE_TEXT, 1) class SelectEvent(wx.PyCommandEvent): def __init__(self, evtType, id): super(SelectEvent, self).__init__(evtType, id) def GetSelectID(self): return self.SelectedID def SetSelectedID(self, id): self.SelectedID = id def GetItemData(self): return self.data def SetItemData(self, data): self.data = data class Panel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, pos=wx.Point(5, 5)) # , # size=wx.Size(280, 656)) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(InnerPanel(self), 1, wx.EXPAND | wx.GROW | wx.ALL, 5) self.SetSizer(sizer) sizer.Fit(self) self.Layout() self.Update() self.SetAutoLayout(1) # Inner fold panel class InnerPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, pos=wx.Point(5, 5)) # , # size=wx.Size(680, 656)) self.patients = [] self.first_image_selection = None self.last_image_selection = None self._init_ui() self._bind_events() self._bind_pubsubevt() def _init_ui(self): splitter = spl.MultiSplitterWindow(self, style=wx.SP_LIVE_UPDATE) splitter.SetOrientation(wx.VERTICAL) self.splitter = splitter panel = wx.Panel(self) self.btn_cancel = wx.Button(panel, wx.ID_CANCEL) self.btn_ok = wx.Button(panel, wx.ID_OK, _("Import")) btnsizer = wx.StdDialogButtonSizer() btnsizer.AddButton(self.btn_ok) btnsizer.AddButton(self.btn_cancel) btnsizer.Realize() self.combo_interval = wx.ComboBox( panel, -1, "", choices=const.IMPORT_INTERVAL, style=wx.CB_DROPDOWN | wx.CB_READONLY, ) self.combo_interval.SetSelection(0) inner_sizer = wx.BoxSizer(wx.HORIZONTAL) inner_sizer.Add(btnsizer, 0, wx.LEFT | wx.TOP, 5) inner_sizer.Add(self.combo_interval, 0, wx.LEFT | wx.RIGHT | wx.TOP, 5) panel.SetSizer(inner_sizer) inner_sizer.Fit(panel) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(splitter, 20, wx.EXPAND) sizer.Add(panel, 1, wx.EXPAND | wx.LEFT, 90) self.SetSizer(sizer) sizer.Fit(self) self.image_panel = HostFindPanel(splitter) splitter.AppendWindow(self.image_panel, 250) self.text_panel = TextPanel(splitter) splitter.AppendWindow(self.text_panel, 250) self.Layout() self.Update() self.SetAutoLayout(1) def _bind_pubsubevt(self): # Publisher.subscribe(self.ShowDicomPreview, "Load import panel") # Publisher.subscribe(self.GetSelectedImages ,"Selected Import Images") pass def GetSelectedImages(self, pubsub_evt): self.first_image_selection = pubsub_evt.data[0] self.last_image_selection = pubsub_evt.data[1] def _bind_events(self): self.Bind(EVT_SELECT_SERIE, self.OnSelectSerie) self.Bind(EVT_SELECT_SLICE, self.OnSelectSlice) self.Bind(EVT_SELECT_PATIENT, self.OnSelectPatient) self.btn_ok.Bind(wx.EVT_BUTTON, self.OnClickOk) self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnClickCancel) self.text_panel.Bind(EVT_SELECT_SERIE_TEXT, self.OnDblClickTextPanel) def ShowDicomPreview(self, pubsub_evt): dicom_groups = pubsub_evt.data self.patients.extend(dicom_groups) self.text_panel.Populate(dicom_groups) def OnSelectSerie(self, evt): patient_id, serie_number = evt.GetSelectID() self.text_panel.SelectSerie(evt.GetSelectID()) for patient in self.patients: if patient_id == patient.GetDicomSample().patient.id: for group in patient.GetGroups(): if serie_number == group.GetDicomSample().acquisition.serie_number: self.image_panel.SetSerie(group) def OnSelectSlice(self, evt): pass def OnSelectPatient(self, evt): pass def OnDblClickTextPanel(self, evt): group = evt.GetItemData() self.LoadDicom(group) def OnClickOk(self, evt): group = self.text_panel.GetSelection() if group: self.LoadDicom(group) def OnClickCancel(self, evt): # Publisher.sendMessage("Cancel DICOM load") pass def LoadDicom(self, group): interval = self.combo_interval.GetSelection() if not isinstance(group, dcm.DicomGroup): group = max(group.GetGroups(), key=lambda g: g.nslices) slice_amont = group.nslices if (self.first_image_selection != None) and ( self.first_image_selection != self.last_image_selection ): slice_amont = (self.last_image_selection) - self.first_image_selection slice_amont += 1 if slice_amont == 0: slice_amont = group.nslices nslices_result = slice_amont / (interval + 1) if nslices_result > 1: # Publisher.sendMessage('Open DICOM group', (group, interval, # [self.first_image_selection, self.last_image_selection])) pass else: dlg.MissingFilesForReconstruction() class TextPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self._selected_by_user = True self.idserie_treeitem = {} self.treeitem_idpatient = {} self.__init_gui() self.__bind_events_wx() self.__bind_pubsub_evt() def __bind_pubsub_evt(self): # Publisher.subscribe(self.SelectSeries, 'Select series in import panel') Publisher.subscribe(self.Populate, "Populate tree") Publisher.subscribe(self.SetHostsList, "Set FindPanel hosts list") def __bind_events_wx(self): self.Bind(wx.EVT_SIZE, self.OnSize) def __init_gui(self): tree = gizmos.TreeListCtrl( self, -1, style=wx.TR_DEFAULT_STYLE | wx.TR_HIDE_ROOT | wx.TR_ROW_LINES # | wx.TR_COLUMN_LINES | wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_SINGLE, ) tree.AddColumn(_("Patient name")) tree.AddColumn(_("Patient ID")) tree.AddColumn(_("Age")) tree.AddColumn(_("Gender")) tree.AddColumn(_("Study description")) tree.AddColumn(_("Modality")) tree.AddColumn(_("Date acquired")) tree.AddColumn(_("# Images")) tree.AddColumn(_("Institution")) tree.AddColumn(_("Date of birth")) tree.AddColumn(_("Accession Number")) tree.AddColumn(_("Referring physician")) tree.SetMainColumn(0) # the one with the tree in it... tree.SetColumnWidth(0, 280) # Patient name tree.SetColumnWidth(1, 110) # Patient ID tree.SetColumnWidth(2, 40) # Age tree.SetColumnWidth(3, 60) # Gender tree.SetColumnWidth(4, 160) # Study description tree.SetColumnWidth(5, 70) # Modality tree.SetColumnWidth(6, 200) # Date acquired tree.SetColumnWidth(7, 70) # Number Images tree.SetColumnWidth(8, 130) # Institution tree.SetColumnWidth(9, 100) # Date of birth tree.SetColumnWidth(10, 140) # Accession Number tree.SetColumnWidth(11, 160) # Referring physician self.root = tree.AddRoot(_("InVesalius Database")) self.tree = tree def SelectSeries(self, group_index): pass def Populate(self, pubsub_evt): tree = self.tree # print ">>>>>>>>>>>>>>>>>>>>>>>>>>", dir(tree.GetRootItem()) # print ">>>>>>>>>>>>",dir(self.tree) patients = pubsub_evt.data first = 0 self.idserie_treeitem = {} for patient in patients.keys(): # ngroups = patient.ngroups # dicom = patient.GetDicomSample() # title = dicom.patient.name + " (%d series)"%(ngroups) # date_time = "%s %s"%(dicom.acquisition.date, # dicom.acquisition.time) first_serie = patients[patient].keys()[0] title = patients[patient][first_serie]["name"] p = patients[patient][first_serie] p_id = patient age = p["age"] gender = p["gender"] study_description = p["study_description"] modality = p["modality"] date = p["acquisition_date"] time = p["acquisition_time"] institution = p["institution"] birthdate = p["date_of_birth"] acession_number = p["acession_number"] physician = p["ref_physician"] parent = tree.AppendItem(self.root, title) n_amount_images = 0 for se in patients[patient]: n_amount_images = n_amount_images + patients[patient][se]["n_images"] tree.SetItemPyData(parent, patient) tree.SetItemText(parent, "%s" % p_id, 1) tree.SetItemText(parent, "%s" % age, 2) tree.SetItemText(parent, "%s" % gender, 3) tree.SetItemText(parent, "%s" % study_description, 4) tree.SetItemText(parent, "%s" % "", 5) tree.SetItemText(parent, "%s" % date + " " + time, 6) tree.SetItemText(parent, "%s" % str(n_amount_images), 7) tree.SetItemText(parent, "%s" % institution, 8) tree.SetItemText(parent, "%s" % birthdate, 9) tree.SetItemText(parent, "%s" % acession_number, 10) tree.SetItemText(parent, "%s" % physician, 11) for series in patients[patient].keys(): serie_description = patients[patient][series]["serie_description"] n_images = patients[patient][series]["n_images"] date = patients[patient][series]["acquisition_date"] time = patients[patient][series]["acquisition_time"] modality = patients[patient][series]["modality"] child = tree.AppendItem(parent, series) tree.SetItemPyData(child, series) tree.SetItemText(child, "%s" % serie_description, 0) # tree.SetItemText(child, "%s" % dicom.acquisition.protocol_name, 4) tree.SetItemText(child, "%s" % modality, 5) tree.SetItemText(child, "%s" % date + " " + time, 6) tree.SetItemText(child, "%s" % n_images, 7) self.idserie_treeitem[(patient, series)] = child tree.Expand(self.root) # tree.SelectItem(parent_select) tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate) # tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged) """ for patient in patient_list: if not isinstance(patient, dcm.PatientGroup): return None ngroups = patient.ngroups dicom = patient.GetDicomSample() title = dicom.patient.name + " (%d series)"%(ngroups) date_time = "%s %s"%(dicom.acquisition.date, dicom.acquisition.time) parent = tree.AppendItem(self.root, title) if not first: parent_select = parent first += 1 tree.SetItemPyData(parent, patient) tree.SetItemText(parent, "%s" % dicom.patient.id, 1) tree.SetItemText(parent, "%s" % dicom.patient.age, 2) tree.SetItemText(parent, "%s" % dicom.patient.gender, 3) tree.SetItemText(parent, "%s" % dicom.acquisition.study_description, 4) tree.SetItemText(parent, "%s" % dicom.acquisition.modality, 5) tree.SetItemText(parent, "%s" % date_time, 6) tree.SetItemText(parent, "%s" % patient.nslices, 7) tree.SetItemText(parent, "%s" % dicom.acquisition.institution, 8) tree.SetItemText(parent, "%s" % dicom.patient.birthdate, 9) tree.SetItemText(parent, "%s" % dicom.acquisition.accession_number, 10) tree.SetItemText(parent, "%s" % dicom.patient.physician, 11) group_list = patient.GetGroups() for n, group in enumerate(group_list): dicom = group.GetDicomSample() child = tree.AppendItem(parent, group.title) tree.SetItemPyData(child, group) tree.SetItemText(child, "%s" % group.title, 0) tree.SetItemText(child, "%s" % dicom.acquisition.protocol_name, 4) tree.SetItemText(child, "%s" % dicom.acquisition.modality, 5) tree.SetItemText(child, "%s" % date_time, 6) tree.SetItemText(child, "%s" % group.nslices, 7) self.idserie_treeitem[(dicom.patient.id, dicom.acquisition.serie_number)] = child tree.Expand(self.root) tree.SelectItem(parent_select) tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate) tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged)""" def SetHostsList(self, evt_pub): self.hosts = evt_pub.data def GetHostList(self): Publisher.sendMessage("Get NodesPanel host list") return self.hosts def OnSelChanged(self, evt): item = self.tree.GetSelection() if self._selected_by_user: group = self.tree.GetItemPyData(item) if isinstance(group, dcm.DicomGroup): # Publisher.sendMessage('Load group into import panel', # group) pass elif isinstance(group, dcm.PatientGroup): id = group.GetDicomSample().patient.id my_evt = SelectEvent(myEVT_SELECT_PATIENT, self.GetId()) my_evt.SetSelectedID(id) self.GetEventHandler().ProcessEvent(my_evt) # Publisher.sendMessage('Load patient into import panel', # group) else: parent_id = self.tree.GetItemParent(item) self.tree.Expand(parent_id) evt.Skip() def OnActivate(self, evt): item = evt.GetItem() item_parent = self.tree.GetItemParent(item) patient_id = self.tree.GetItemPyData(item_parent) serie_id = self.tree.GetItemPyData(item) hosts = self.GetHostList() for key in hosts.keys(): if key != 0: dn = dcm_net.DicomNet() dn.SetHost(self.hosts[key][1]) dn.SetPort(self.hosts[key][2]) dn.SetAETitleCall(self.hosts[key][3]) dn.SetAETitle(self.hosts[0][3]) dn.RunCMove((patient_id, serie_id)) # dn.SetSearchWord(self.find_txt.GetValue()) # Publisher.sendMessage('Populate tree', dn.RunCFind()) # my_evt = SelectEvent(myEVT_SELECT_SERIE_TEXT, self.GetId()) # my_evt.SetItemData(group) # self.GetEventHandler().ProcessEvent(my_evt) def OnSize(self, evt): self.tree.SetSize(self.GetSize()) def SelectSerie(self, serie): self._selected_by_user = False item = self.idserie_treeitem[serie] self.tree.SelectItem(item) self._selected_by_user = True def GetSelection(self): """Get selected item""" item = self.tree.GetSelection() group = self.tree.GetItemPyData(item) return group class FindPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.sizer = wx.BoxSizer(wx.VERTICAL) sizer_word_label = wx.BoxSizer(wx.HORIZONTAL) sizer_word_label.Add((5, 0), 0, wx.EXPAND | wx.HORIZONTAL) find_label = wx.StaticText(self, -1, _("Word")) sizer_word_label.Add(find_label) sizer_txt_find = wx.BoxSizer(wx.HORIZONTAL) sizer_txt_find.Add((5, 0), 0, wx.EXPAND | wx.HORIZONTAL) self.find_txt = wx.TextCtrl(self, -1, size=(225, -1)) self.btn_find = wx.Button(self, -1, _("Search")) sizer_txt_find.Add(self.find_txt) sizer_txt_find.Add(self.btn_find) self.sizer.Add((0, 5), 0, wx.EXPAND | wx.HORIZONTAL) self.sizer.Add(sizer_word_label) self.sizer.Add(sizer_txt_find) # self.sizer.Add(self.serie_preview, 1, wx.EXPAND | wx.ALL, 5) # self.sizer.Add(self.dicom_preview, 1, wx.EXPAND | wx.ALL, 5) self.sizer.Fit(self) self.SetSizer(self.sizer) self.Layout() self.Update() self.SetAutoLayout(1) self.__bind_evt() self._bind_gui_evt() def __bind_evt(self): Publisher.subscribe(self.SetHostsList, "Set FindPanel hosts list") # Publisher.subscribe(self.ShowDicomSeries, 'Load dicom preview') # Publisher.subscribe(self.SetDicomSeries, 'Load group into import panel') # Publisher.subscribe(self.SetPatientSeries, 'Load patient into import panel') pass def _bind_gui_evt(self): # self.serie_preview.Bind(dpp.EVT_CLICK_SERIE, self.OnSelectSerie) # self.dicom_preview.Bind(dpp.EVT_CLICK_SLICE, self.OnSelectSlice) self.Bind(wx.EVT_BUTTON, self.OnButtonFind, self.btn_find) def OnButtonFind(self, evt): hosts = self.GetHostList() for key in hosts.keys(): if key != 0: dn = dcm_net.DicomNet() dn.SetHost(self.hosts[key][1]) dn.SetPort(self.hosts[key][2]) dn.SetAETitleCall(self.hosts[key][3]) dn.SetAETitle(self.hosts[0][3]) dn.SetSearchWord(self.find_txt.GetValue()) Publisher.sendMessage("Populate tree", dn.RunCFind()) def SetHostsList(self, evt_pub): self.hosts = evt_pub.data def GetHostList(self): Publisher.sendMessage("Get NodesPanel host list") return self.hosts class HostFindPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self._init_ui() self._bind_events() def _init_ui(self): splitter = spl.MultiSplitterWindow(self, style=wx.SP_LIVE_UPDATE) splitter.SetOrientation(wx.HORIZONTAL) self.splitter = splitter # TODO: Rever isso # splitter.ContainingSizer = wx.BoxSizer(wx.HORIZONTAL) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(splitter, 1, wx.EXPAND) self.SetSizer(sizer) self.image_panel = NodesPanel(splitter) splitter.AppendWindow(self.image_panel, 500) self.text_panel = FindPanel(splitter) splitter.AppendWindow(self.text_panel, 750) self.SetSizer(sizer) sizer.Fit(self) self.Layout() self.Update() self.SetAutoLayout(1) def _bind_events(self): self.text_panel.Bind(EVT_SELECT_SERIE, self.OnSelectSerie) self.text_panel.Bind(EVT_SELECT_SLICE, self.OnSelectSlice) def OnSelectSerie(self, evt): evt.Skip() def OnSelectSlice(self, evt): self.image_panel.dicom_preview.ShowSlice(evt.GetSelectID()) evt.Skip() def SetSerie(self, serie): self.image_panel.dicom_preview.SetDicomGroup(serie) class NodesTree( wx.ListCtrl, CheckListCtrlMixin, listmix.ListCtrlAutoWidthMixin, listmix.TextEditMixin, ): def __init__(self, parent): self.item = 0 self.col_locs = [0] self.editorBgColour = wx.Colour(255, 255, 255, 255) wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT | wx.LC_HRULES) listmix.CheckListCtrlMixin.__init__(self) listmix.TextEditMixin.__init__(self) def OnCheckItem(self, index, flag): Publisher.sendMessage("Check item dict", [index, flag]) def OpenEditor(self, col, row): if col >= 1 and col < 4: listmix.TextEditMixin.OpenEditor(self, col, row) else: listmix.CheckListCtrlMixin.ToggleItem(self, self.item) def SetSelected(self, item): self.item = item def SetDeselected(self, item): self.item = item class NodesPanel(wx.Panel): def __init__(self, parent): self.selected_item = None self.hosts = {} wx.Panel.__init__(self, parent, -1) self.__init_gui() self.__bind_evt() def __bind_evt(self): self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.RightButton, self.tree_node) self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.tree_node) self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected, self.tree_node) self.Bind(wx.EVT_BUTTON, self.OnButtonAdd, self.btn_add) self.Bind(wx.EVT_BUTTON, self.OnButtonRemove, self.btn_remove) self.Bind(wx.EVT_BUTTON, self.OnButtonCheck, self.btn_check) self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.EndEdition, self.tree_node) Publisher.subscribe(self.CheckItemDict, "Check item dict") Publisher.subscribe(self.GetHostsList, "Get NodesPanel host list") # Publisher.subscribe(self.UnCheckItemDict, "Uncheck item dict") def __init_gui(self): self.tree_node = NodesTree(self) self.tree_node.InsertColumn(0, _("Active")) self.tree_node.InsertColumn(1, _("Host")) self.tree_node.InsertColumn(2, _("Port")) self.tree_node.InsertColumn(3, _("AETitle")) self.tree_node.InsertColumn(4, _("Status")) self.tree_node.SetColumnWidth(0, 50) self.tree_node.SetColumnWidth(1, 150) self.tree_node.SetColumnWidth(2, 50) self.tree_node.SetColumnWidth(3, 150) self.tree_node.SetColumnWidth(4, 80) self.hosts[0] = [True, "localhost", "", "invesalius"] try: index = self.tree_node.InsertItem(sys.maxsize, "") except (OverflowError, AssertionError): index = self.tree_node.InsertItem(sys.maxint, "") self.tree_node.SetItem(index, 1, "localhost") self.tree_node.SetItem(index, 2, "") self.tree_node.SetItem(index, 3, "invesalius") self.tree_node.SetItem(index, 4, "ok") self.tree_node.CheckItem(index) self.tree_node.SetItemBackgroundColour(index, wx.Colour(245, 245, 245)) # print ">>>>>>>>>>>>>>>>>>>>>", sys.maxint # index = self.tree_node.InsertItem(sys.maxint, "")#adiciona vazio a coluna de check # self.tree_node.SetItem(index, 1, "200.144.114.19") # self.tree_node.SetItem(index, 2, "80") # self.tree_node.SetItemData(index, 0) # index2 = self.tree_node.InsertItem(sys.maxint, "")#adiciona vazio a coluna de check # self.tree_node.SetItem(index2, 1, "200.144.114.19") # self.tree_node.SetItem(index2, 2, "80") # self.tree_node.SetItemData(index2, 0) self.btn_add = wx.Button(self, -1, _("Add")) self.btn_remove = wx.Button(self, -1, _("Remove")) self.btn_check = wx.Button(self, -1, _("Check status")) sizer_btn = wx.BoxSizer(wx.HORIZONTAL) sizer_btn.Add((90, 0), 0, wx.EXPAND | wx.HORIZONTAL) sizer_btn.Add(self.btn_add, 10) sizer_btn.Add(self.btn_remove, 10) sizer_btn.Add(self.btn_check, 0, wx.ALIGN_CENTER_HORIZONTAL) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.tree_node, 85, wx.GROW | wx.EXPAND) sizer.Add(sizer_btn, 15) sizer.Fit(self) self.SetSizer(sizer) self.Layout() self.Update() self.SetAutoLayout(1) self.sizer = sizer def GetHostsList(self, pub_evt): Publisher.sendMessage("Set FindPanel hosts list", self.hosts) def EndEdition(self, evt): index = evt.m_itemIndex item = evt.m_item col = item.GetColumn() txt = item.GetText() values = self.hosts[index] values[col] = str(txt) self.hosts[index] = values def OnButtonAdd(self, evt): # adiciona vazio a coluna de check index = self.tree_node.InsertItem(sys.maxsize, "") self.hosts[index] = [True, "localhost", "80", ""] self.tree_node.SetItem(index, 1, "localhost") self.tree_node.SetItem(index, 2, "80") self.tree_node.SetItem(index, 3, "") self.tree_node.CheckItem(index) def OnLeftDown(self, evt): evt.Skip() def OnButtonRemove(self, evt): if self.selected_item != None and self.selected_item != 0: self.tree_node.DeleteItem(self.selected_item) self.hosts.pop(self.selected_item) self.selected_item = None k = self.hosts.keys() tmp_cont = 0 tmp_host = {} for x in k: tmp_host[tmp_cont] = self.hosts[x] tmp_cont += 1 self.hosts = tmp_host def OnButtonCheck(self, evt): for key in self.hosts.keys(): if key != 0: dn = dcm_net.DicomNet() dn.SetHost(self.hosts[key][1]) dn.SetPort(self.hosts[key][2]) dn.SetAETitleCall(self.hosts[key][3]) dn.SetAETitle(self.hosts[0][3]) if dn.RunCEcho(): self.tree_node.SetItem(key, 4, _("ok")) else: self.tree_node.SetItem(key, 4, _("error")) def RightButton(self, evt): event.Skip() def OnItemSelected(self, evt): self.selected_item = evt.m_itemIndex self.tree_node.SetSelected(evt.m_itemIndex) def OnItemDeselected(self, evt): if evt.m_itemIndex != 0: self.tree_node.SetDeselected(evt.m_itemIndex) def CheckItemDict(self, evt_pub): index, flag = evt_pub.data if index != 0: self.hosts[index][0] = flag else: self.tree_node.CheckItem(0)
minimode
minimode_preferences
# Copyright (C) 2009-2010 Mathias Brodala # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import os.path from xl import providers from xl.nls import gettext as _ from xlgui import icons from xlgui.preferences import widgets name = _("Mini Mode") basedir = os.path.dirname(os.path.realpath(__file__)) ui = os.path.join(basedir, "minimode_preferences.ui") icons.MANAGER.add_icon_name_from_directory( "exaile-minimode", os.path.join(basedir, "icons") ) icon = "exaile-minimode" class AlwaysOnTopPreference(widgets.CheckPreference): name = "plugin/minimode/always_on_top" default = True class ShowInPanelPreference(widgets.CheckPreference): name = "plugin/minimode/show_in_panel" default = False class OnAllDesktopsPreference(widgets.CheckPreference): name = "plugin/minimode/on_all_desktops" default = True class ButtonInMainWindowPreference(widgets.CheckPreference): name = "plugin/minimode/button_in_mainwindow" default = False class DisplayWindowDecorationsPreference(widgets.CheckPreference): name = "plugin/minimode/display_window_decorations" default = True class WindowDecorationTypePreference(widgets.ComboPreference, widgets.CheckConditional): name = "plugin/minimode/window_decoration_type" default = "full" condition_preference_name = "plugin/minimode/display_window_decorations" def __init__(self, preferences, widget): widgets.ComboPreference.__init__(self, preferences, widget) widgets.CheckConditional.__init__(self) class UseAlphaTransparencyPreference(widgets.CheckPreference): default = False name = "plugin/minimode/use_alpha" class TransparencyPreference(widgets.ScalePreference, widgets.CheckConditional): default = 0.3 name = "plugin/minimode/transparency" condition_preference_name = "plugin/minimode/use_alpha" def __init__(self, preferences, widget): widgets.ScalePreference.__init__(self, preferences, widget) widgets.CheckConditional.__init__(self) class SelectedControlsPreference(widgets.SelectionListPreference): name = "plugin/minimode/selected_controls" default = [ "previous", "play_pause", "next", "playlist_button", "progress_bar", "restore", ] def __init__(self, preferences, widget): self.items = [ self.Item(p.name, p.title, p.description, p.fixed) for p in providers.get("minimode-controls") ] widgets.SelectionListPreference.__init__(self, preferences, widget) class TrackTitleFormatPreference(widgets.ComboEntryPreference): name = "plugin/minimode/track_title_format" completion_items = { "$tracknumber": _("Track number"), "$title": _("Title"), "$artist": _("Artist"), "$composer": _("Composer"), "$album": _("Album"), "$__length": _("Length"), "$discnumber": _("Disc number"), "$__rating": _("Rating"), "$date": _("Date"), "$genre": _("Genre"), "$bitrate": _("Bitrate"), "$__loc": _("Location"), "$filename": _("Filename"), "$__playcount": _("Play count"), "$__last_played": _("Last played"), "$bpm": _("BPM"), } preset_items = [ # TRANSLATORS: Mini mode track selector title preset _("$tracknumber - $title"), # TRANSLATORS: Mini mode track selector title preset _("$title by $artist"), # TRANSLATORS: Mini mode track selector title preset _("$title ($__length)"), ] default = _("$tracknumber - $title")
gamedata
metaData
# =============================================================================== # Copyright (C) 2010 Diego Duclos # # This file is part of eos. # # eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # eos is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with eos. If not, see <http://www.gnu.org/licenses/>. # =============================================================================== from eos.db import gamedata_meta from eos.gamedata import MetaData from sqlalchemy import Column, String, Table from sqlalchemy.orm import mapper metadata_table = Table( "metadata", gamedata_meta, Column("field_name", String, primary_key=True), Column("field_value", String), ) mapper(MetaData, metadata_table)
installer
fix_qt5_rpath
"""Methods to fix Mac OS X @rpath and /usr/local dependencies, and analyze the app bundle for OpenShot to find all external dependencies""" import os import re import shutil import subprocess from subprocess import call # Ignore non library/executable extensions non_executables = [ ".py", ".svg", ".png", ".blend", ".a", ".pak", ".qm", ".pyc", ".txt", ".jpg", ".zip", ".dat", ".conf", ".xml", ".h", ".ui", ".json", ".exe", ] def fix_rpath(PATH): """FIX broken @rpath on Qt, PyQt, and /usr/local/ dependencies with no @rpath""" # Cleanup duplicate folder and files (that cx_freeze creates) duplicate_path = os.path.join(PATH, "lib", "openshot_qt") if os.path.exists(duplicate_path): shutil.rmtree(duplicate_path) # Find files matching patterns for root, dirs, files in os.walk(PATH): for basename in files: file_path = os.path.join(root, basename) relative_path = os.path.relpath(root, PATH) # Skip common file extensions (speed things up) if ( os.path.splitext(file_path)[-1] in non_executables or basename.startswith(".") or "profiles" in file_path ): continue # Build exe path (relative from the app dir) executable_path = os.path.join("@executable_path", relative_path, basename) if relative_path == ".": executable_path = os.path.join("@executable_path", basename) # Change ID path of library files # Sometimes, the ID has an absolute path or invalid @rpath embedded in it, which breaks our frozen exe call(["install_name_tool", file_path, "-id", executable_path]) # Loop through all dependencies of each library/executable raw_output = ( subprocess.Popen(["oTool", "-L", file_path], stdout=subprocess.PIPE) .communicate()[0] .decode("utf-8") ) for output in raw_output.split("\n")[1:-1]: if ( output and "is not an object file" not in output and ".o):" not in output ): dependency_path = output.split("\t")[1].split(" ")[0] dependency_base_path, dependency_name = os.path.split( dependency_path ) # If @rpath or /usr/local found in dependency path, update with @executable_path instead if "/usr/local" in dependency_path or "@rpath" in dependency_path: dependency_exe_path = os.path.join( "@executable_path", dependency_name ) if not os.path.exists(os.path.join(PATH, dependency_name)): print( "ERROR: /usr/local PATH not found in EXE folder: %s" % dependency_path ) else: call( [ "install_name_tool", file_path, "-change", dependency_path, dependency_exe_path, ] ) def print_min_versions(PATH): """Print ALL MINIMUM and SDK VERSIONS for files in OpenShot build folder. This does not list all dependent libraries though, and sometimes one of those can cause issues. """ # Use 2 different matches, due to different output from different libraries (depending on compiler) REGEX_SDK_MATCH = re.compile( r".*(LC_VERSION_MIN_MACOSX).*version (\d+\.\d+).*sdk (\d+\.\d+).*(cmd)", re.DOTALL, ) REGEX_SDK_MATCH2 = re.compile(r".*sdk\s(.*)\s*minos\s(.*)") VERSIONS = {} # Find files matching patterns for root, dirs, files in os.walk(PATH): for basename in files: file_path = os.path.join(root, basename) file_parts = file_path.split("/") # Skip common file extensions (speed things up) if os.path.splitext(file_path)[ -1 ] in non_executables or basename.startswith("."): continue raw_output = ( subprocess.Popen(["oTool", "-l", file_path], stdout=subprocess.PIPE) .communicate()[0] .decode("utf-8") ) matches = REGEX_SDK_MATCH.findall(raw_output) matches2 = REGEX_SDK_MATCH2.findall(raw_output) min_version = None sdk_version = None if matches and len(matches[0]) == 4: min_version = matches[0][1] sdk_version = matches[0][2] elif matches2 and len(matches2[0]) == 2: sdk_version = matches2[0][0] min_version = matches2[0][1] if min_version and sdk_version: print( "... scanning %s for min version (min: %s, sdk: %s)" % (file_path.replace(PATH, ""), min_version, sdk_version) ) # Organize by MIN version if min_version in VERSIONS: if file_path not in VERSIONS[min_version]: VERSIONS[min_version].append(file_path) else: VERSIONS[min_version] = [file_path] if min_version in ["11.0"]: print("ERROR!!!! Minimum OS X version not met for %s" % file_path) print("\nSummary of Minimum Mac SDKs for Dependencies:") for key in sorted(VERSIONS.keys()): print("\n%s" % key) for file_path in VERSIONS[key]: print(" %s" % file_path) print("\nCount of Minimum Mac SDKs for Dependencies:") for key in sorted(VERSIONS.keys()): print("%s (%d)" % (key, len(VERSIONS[key]))) if __name__ == "__main__": # Run these methods manually for testing # XXX: This path should be set programmatically, somehow PATH = "/Users/jonathanthomas/apps/openshot-qt/build/exe.macosx-10.15-x86_64-3.7" fix_rpath(PATH) print_min_versions(PATH)
gui
optionspanel
# This file is part of MyPaint. # Copyright (C) 2013-2018 by the MyPaint Development Team. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. """Dockable panel showing options for the current mode""" ## Imports from __future__ import division, print_function import logging import lib.xml from lib.gettext import C_ from lib.gibindings import Gtk from .toolstack import TOOL_WIDGET_NATURAL_HEIGHT_SHORT, SizedVBoxToolWidget logger = logging.getLogger(__name__) ## Class defs class ModeOptionsTool(SizedVBoxToolWidget): """Dockable panel showing options for the current mode This panel has a title and an icon reflecting the current mode, and displays its options widget if it has one: define an object method named ``get_options_widget()`` returning an arbitrary GTK widget. Singletons work well here, and are encouraged. ``get_options_widget()`` can also return `None` if the mode is a temporary mode which has no sensible options. In this case, any widget already displayed will not be replaced, which is particularly appropriate for modes which only persist for the length of time the mouse button is held, and stack on top of other modes. """ ## Class constants SIZED_VBOX_NATURAL_HEIGHT = TOOL_WIDGET_NATURAL_HEIGHT_SHORT tool_widget_icon_name = "mypaint-options-symbolic" tool_widget_title = C_( "options panel: tab tooltip: title", "Tool Options", ) tool_widget_description = C_( "options panel: tab tooltip: description", "Specialized settings for the current editing tool", ) __gtype_name__ = "MyPaintModeOptionsTool" OPTIONS_MARKUP = C_( "options panel: header", "<b>{mode_name}</b>", ) NO_OPTIONS_MARKUP = C_( "options panel: body", "<i>No options available</i>", ) ## Method defs def __init__(self): """Construct, and connect internal signals & callbacks""" SizedVBoxToolWidget.__init__(self) from gui.application import get_app self._app = get_app() self._app.doc.modes.changed += self._modestack_changed_cb self.set_border_width(3) self.set_spacing(6) # Placeholder in case a mode has no options label = Gtk.Label() label.set_markup(self.NO_OPTIONS_MARKUP) self._no_options_label = label # Container for an options widget exposed by the current mode self._mode_icon = Gtk.Image() label = Gtk.Label() label.set_text("<options-label>") self._options_label = label label.set_alignment(0.0, 0.5) label_hbox = Gtk.HBox() label_hbox.set_spacing(3) label_hbox.set_border_width(3) label_hbox.pack_start(self._mode_icon, False, False, 0) label_hbox.pack_start(self._options_label, True, True, 0) align = Gtk.Alignment.new(0.5, 0.5, 1.0, 1.0) align.set_padding(0, 0, 0, 0) align.set_border_width(3) self._options_bin = align self.pack_start(label_hbox, False, False, 0) self.pack_start(align, True, True, 0) self.connect("show", lambda *a: self._update_ui()) # Fallback self._update_ui_with_options_widget( self._no_options_label, self.tool_widget_title, self.tool_widget_icon_name, ) def _modestack_changed_cb(self, modestack, old, new): """Update the UI when the mode changes""" self._update_ui() def _update_ui(self): """Update the UI to show the options widget of the current mode""" mode = self._app.doc.modes.top self._update_ui_for_mode(mode) def _update_ui_for_mode(self, mode): # Get the new options widget try: get_options_widget = mode.get_options_widget except AttributeError: get_options_widget = None if get_options_widget: new_options = get_options_widget() else: new_options = self._no_options_label if not new_options: # Leave existing widget as-is, even if it's the default. # XXX maybe we should be doing something stack-based here? return icon_name = mode.get_icon_name() name = mode.get_name() self._update_ui_with_options_widget(new_options, name, icon_name) def _update_ui_with_options_widget(self, new_options, name, icon_name): old_options = self._options_bin.get_child() logger.debug("name: %r, icon name: %r", name, icon_name) if name: markup = self.OPTIONS_MARKUP.format( mode_name=lib.xml.escape(name), ) self._options_label.set_markup(markup) if icon_name: self._mode_icon.set_from_icon_name( icon_name, Gtk.IconSize.SMALL_TOOLBAR, ) # Options widget: only update if there's a change if new_options is not old_options: if old_options: old_options.hide() self._options_bin.remove(old_options) self._options_bin.add(new_options) new_options.show() self._options_bin.show_all()
v1
notifications
from typing import List from CTFd.api.v1.helpers.request import validate_args from CTFd.api.v1.helpers.schemas import sqlalchemy_to_pydantic from CTFd.api.v1.schemas import APIDetailedSuccessResponse, APIListSuccessResponse from CTFd.constants import RawEnum from CTFd.models import Notifications, db from CTFd.schemas.notifications import NotificationSchema from CTFd.utils.decorators import admins_only from CTFd.utils.helpers.models import build_model_filters from flask import current_app, make_response, request from flask_restx import Namespace, Resource notifications_namespace = Namespace( "notifications", description="Endpoint to retrieve Notifications" ) NotificationModel = sqlalchemy_to_pydantic(Notifications) TransientNotificationModel = sqlalchemy_to_pydantic(Notifications, exclude=["id"]) class NotificationDetailedSuccessResponse(APIDetailedSuccessResponse): data: NotificationModel class NotificationListSuccessResponse(APIListSuccessResponse): data: List[NotificationModel] notifications_namespace.schema_model( "NotificationDetailedSuccessResponse", NotificationDetailedSuccessResponse.apidoc() ) notifications_namespace.schema_model( "NotificationListSuccessResponse", NotificationListSuccessResponse.apidoc() ) @notifications_namespace.route("") class NotificantionList(Resource): @notifications_namespace.doc( description="Endpoint to get notification objects in bulk", responses={ 200: ("Success", "NotificationListSuccessResponse"), 400: ( "An error occured processing the provided or stored data", "APISimpleErrorResponse", ), }, ) @validate_args( { "title": (str, None), "content": (str, None), "user_id": (int, None), "team_id": (int, None), "q": (str, None), "field": ( RawEnum("NotificationFields", {"title": "title", "content": "content"}), None, ), "since_id": (int, None), }, location="query", ) def get(self, query_args): q = query_args.pop("q", None) field = str(query_args.pop("field", None)) filters = build_model_filters(model=Notifications, query=q, field=field) since_id = query_args.pop("since_id", None) if since_id: filters.append((Notifications.id > since_id)) notifications = ( Notifications.query.filter_by(**query_args).filter(*filters).all() ) schema = NotificationSchema(many=True) result = schema.dump(notifications) if result.errors: return {"success": False, "errors": result.errors}, 400 return {"success": True, "data": result.data} @notifications_namespace.doc( description="Endpoint to get statistics for notification objects in bulk", responses={200: ("Success", "APISimpleSuccessResponse")}, ) @validate_args( { "title": (str, None), "content": (str, None), "user_id": (int, None), "team_id": (int, None), "q": (str, None), "field": ( RawEnum("NotificationFields", {"title": "title", "content": "content"}), None, ), "since_id": (int, None), }, location="query", ) def head(self, query_args): q = query_args.pop("q", None) field = str(query_args.pop("field", None)) filters = build_model_filters(model=Notifications, query=q, field=field) since_id = query_args.pop("since_id", None) if since_id: filters.append((Notifications.id > since_id)) notification_count = ( Notifications.query.filter_by(**query_args).filter(*filters).count() ) response = make_response() response.headers["Result-Count"] = notification_count return response @admins_only @notifications_namespace.doc( description="Endpoint to create a notification object", responses={ 200: ("Success", "NotificationDetailedSuccessResponse"), 400: ( "An error occured processing the provided or stored data", "APISimpleErrorResponse", ), }, ) def post(self): req = request.get_json() schema = NotificationSchema() result = schema.load(req) if result.errors: return {"success": False, "errors": result.errors}, 400 db.session.add(result.data) db.session.commit() response = schema.dump(result.data) # Grab additional settings notif_type = req.get("type", "alert") notif_sound = req.get("sound", True) response.data["type"] = notif_type response.data["sound"] = notif_sound current_app.events_manager.publish(data=response.data, type="notification") return {"success": True, "data": response.data} @notifications_namespace.route("/<notification_id>") @notifications_namespace.param("notification_id", "A Notification ID") class Notification(Resource): @notifications_namespace.doc( description="Endpoint to get a specific notification object", responses={ 200: ("Success", "NotificationDetailedSuccessResponse"), 400: ( "An error occured processing the provided or stored data", "APISimpleErrorResponse", ), }, ) def get(self, notification_id): notif = Notifications.query.filter_by(id=notification_id).first_or_404() schema = NotificationSchema() response = schema.dump(notif) if response.errors: return {"success": False, "errors": response.errors}, 400 return {"success": True, "data": response.data} @admins_only @notifications_namespace.doc( description="Endpoint to delete a notification object", responses={200: ("Success", "APISimpleSuccessResponse")}, ) def delete(self, notification_id): notif = Notifications.query.filter_by(id=notification_id).first_or_404() db.session.delete(notif) db.session.commit() db.session.close() return {"success": True}
network
vector_source
#!/usr/bin/env python # # Copyright 2006,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from argparse import ArgumentParser from gnuradio import blocks, gr class vector_source(gr.top_block): def __init__(self, host, port, pkt_size, eof): gr.top_block.__init__(self, "vector_source") data = [i * 0.01 for i in range(1000)] vec = blocks.vector_source_f(data, True) udp = blocks.udp_sink(gr.sizeof_float, host, port, pkt_size, eof=eof) self.connect(vec, udp) if __name__ == "__main__": parser = ArgumentParser() parser.add_argument( "--host", default="127.0.0.1", help="Remote host name (domain name or IP address", ) parser.add_argument( "--port", type=int, default=65500, help="port number to connect to" ) parser.add_argument("--packet-size", type=int, default=1471, help="packet size.") parser.add_argument( "--no-eof", action="store_true", default=False, help="don't send EOF on disconnect", ) args = parser.parse_args() # Create an instance of a hierarchical block top_block = vector_source(args.host, args.port, args.packet_size, not args.no_eof) try: # Run forever top_block.run() except KeyboardInterrupt: # Ctrl-C exits pass
dialogs
detectdialog
# Copyright (C) 2011 Chris Dekter # Copyright (C) 2018 Thomas Hess <[email protected]> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from typing import Tuple from autokey.qtui import common as ui_common from PyQt5.QtWidgets import QWidget logger = ui_common.logger.getChild("DetectDialog") class DetectDialog(*ui_common.inherits_from_ui_file_with_name("detectdialog")): """ The DetectDialog lets the user select window properties of a chosen window. The dialog shows the window title and window class of the chosen window and lets the user select one of those two options. """ def __init__(self, parent: QWidget): super(DetectDialog, self).__init__(parent) self.setupUi(self) self.window_title = "" self.window_class = "" def populate(self, window_info: Tuple[str, str]): self.window_title, self.window_class = window_info self.detected_title.setText(self.window_title) self.detected_class.setText(self.window_class) logger.info( "Detected window with properties title: {}, window class: {}".format( self.window_title, self.window_class ) ) def get_choice(self) -> str: # This relies on autoExclusive being set to true in the ui file. if self.classButton.isChecked(): logger.debug( "User has chosen the window class: {}".format(self.window_class) ) return self.window_class else: logger.debug( "User has chosen the window title: {}".format(self.window_title) ) return self.window_title
extractor
parliamentliveuk
from __future__ import unicode_literals from .common import InfoExtractor class ParliamentLiveUKIE(InfoExtractor): IE_NAME = "parliamentlive.tv" IE_DESC = "UK parliament videos" _VALID_URL = r"(?i)https?://(?:www\.)?parliamentlive\.tv/Event/Index/(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})" _TESTS = [ { "url": "http://parliamentlive.tv/Event/Index/c1e9d44d-fd6c-4263-b50f-97ed26cc998b", "info_dict": { "id": "1_af9nv9ym", "ext": "mp4", "title": "Home Affairs Committee", "uploader_id": "FFMPEG-01", "timestamp": 1422696664, "upload_date": "20150131", }, }, { "url": "http://parliamentlive.tv/event/index/3f24936f-130f-40bf-9a5d-b3d6479da6a4", "only_matching": True, }, ] def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage( "http://vodplayer.parliamentlive.tv/?mid=" + video_id, video_id ) widget_config = self._parse_json( self._search_regex( r"(?s)kWidgetConfig\s*=\s*({.+});", webpage, "kaltura widget config" ), video_id, ) kaltura_url = "kaltura:%s:%s" % ( widget_config["wid"][1:], widget_config["entry_id"], ) event_title = self._download_json( "http://parliamentlive.tv/Event/GetShareVideo/" + video_id, video_id )["event"]["title"] return { "_type": "url_transparent", "title": event_title, "description": "", "url": kaltura_url, "ie_key": "Kaltura", }
femexamples
constraint_centrif
# *************************************************************************** # * Copyright (c) 2021 Bernd Hahnebach <[email protected]> * # * * # * This file is part of the FreeCAD CAx development system. * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * This program is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * # * GNU Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library General Public * # * License along with this program; if not, write to the Free Software * # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # * USA * # * * # *************************************************************************** import Fem import FreeCAD import ObjectsFem from BasicShapes import Shapes from Draft import clone from FreeCAD import Vector as vec from Part import makeLine from . import manager from .manager import get_meshname, init_doc def get_information(): return { "name": "Constraint Centrif", "meshtype": "solid", "meshelement": "Tet10", "constraints": ["centrif", "fixed"], "solvers": ["calculix", "ccxtools"], "material": "multimaterial", "equations": ["mechanical"], } def get_explanation(header=""): return ( header + """ To run the example from Python console use: from femexamples.constraint_centrif import setup setup() See forum topic post: https://forum.freecad.org/viewtopic.php?f=18&t=57770 constraint centrif, concerning CENTRIF label from ccx's *DLOAD card """ ) def setup(doc=None, solvertype="ccxtools"): # init FreeCAD document if doc is None: doc = init_doc() # explanation object # just keep the following line and change text string in get_explanation method manager.add_explanation_obj( doc, get_explanation(manager.get_header(get_information())) ) # geometric objects # ring stiffener = doc.addObject("Part::Box", "Stiffener") stiffener.Length = 10 stiffener.Width = 200 stiffener.Height = 10 stiffener.Placement.Base = (-5, -100, 0) circumference = Shapes.addTube(doc, "Circumference") circumference.Height = 10.0 circumference.InnerRadius = 97.5 circumference.OuterRadius = 102.5 doc.recompute() fusion = doc.addObject("Part::MultiFuse", "Fusion") fusion.Shapes = [stiffener, circumference] doc.recompute() centerhole = doc.addObject("Part::Cylinder", "CenterHole") centerhole.Radius = 3 centerhole.Height = 20 doc.recompute() ring_bottom = doc.addObject("Part::Cut", "RingBottom") ring_bottom.Base = fusion ring_bottom.Tool = centerhole doc.recompute() # standard ring ring_top = clone(ring_bottom, delta=vec(0, 0, 20)) ring_top.Label = "RingTop" # compound of both rings geom_obj = doc.addObject("Part::Compound", "TheRingOfFire") geom_obj.Links = [ring_bottom, ring_top] doc.recompute() if FreeCAD.GuiUp: geom_obj.ViewObject.Document.activeView().viewAxonometric() geom_obj.ViewObject.Document.activeView().fitAll() # line for centrif axis sh_axis_line = makeLine(vec(0, 0, 0), vec(0, 0, 31)) axis_line = doc.addObject("Part::Feature", "CentrifAxis") axis_line.Shape = sh_axis_line doc.recompute() if FreeCAD.GuiUp: axis_line.ViewObject.LineWidth = 5.0 axis_line.ViewObject.LineColor = (1.0, 0.0, 0.0) # analysis analysis = ObjectsFem.makeAnalysis(doc, "Analysis") # solver if solvertype == "calculix": solver_obj = ObjectsFem.makeSolverCalculix(doc, "SolverCalculiX") elif solvertype == "ccxtools": solver_obj = ObjectsFem.makeSolverCalculixCcxTools(doc, "CalculiXccxTools") solver_obj.WorkingDir = "" else: FreeCAD.Console.PrintWarning( "Unknown or unsupported solver type: {}. " "No solver object was created.\n".format(solvertype) ) if solvertype == "calculix" or solvertype == "ccxtools": solver_obj.AnalysisType = "static" solver_obj.GeometricalNonlinearity = "linear" solver_obj.ThermoMechSteadyState = False solver_obj.MatrixSolverType = "default" solver_obj.IterationsControlParameterTimeUse = False solver_obj.SplitInputWriter = False analysis.addObject(solver_obj) # materials material_obj_scotty = ObjectsFem.makeMaterialSolid(doc, "Steel_Scotty") mat = material_obj_scotty.Material mat["Name"] = "Steel_Scotty" mat["YoungsModulus"] = "210000 MPa" mat["PoissonRatio"] = "0.30" mat["Density"] = "4000 kg/m^3" material_obj_scotty.Material = mat material_obj_scotty.References = [(ring_bottom, "Solid1")] analysis.addObject(material_obj_scotty) material_obj_std = ObjectsFem.makeMaterialSolid(doc, "Steel_Std") mat = material_obj_std.Material mat["Name"] = "Steel_Std" mat["YoungsModulus"] = "210000 MPa" mat["PoissonRatio"] = "0.30" mat["Density"] = "8000 kg/m^3" material_obj_std.Material = mat material_obj_std.References = [(ring_top, "Solid1")] analysis.addObject(material_obj_std) # constraint fixed con_fixed = ObjectsFem.makeConstraintFixed(doc, "ConstraintFixed") con_fixed.References = [(geom_obj, ("Face4", "Face12"))] analysis.addObject(con_fixed) # constraint centrif con_centrif = ObjectsFem.makeConstraintCentrif(doc, "ConstraintCentrif") con_centrif.RotationFrequency = "100 Hz" con_centrif.RotationAxis = [(axis_line, "Edge1")] analysis.addObject(con_centrif) # mesh from .meshes.mesh_constraint_centrif_tetra10 import create_elements, create_nodes fem_mesh = Fem.FemMesh() control = create_nodes(fem_mesh) if not control: FreeCAD.Console.PrintError("Error on creating nodes.\n") control = create_elements(fem_mesh) if not control: FreeCAD.Console.PrintError("Error on creating elements.\n") femmesh_obj = analysis.addObject(ObjectsFem.makeMeshGmsh(doc, get_meshname()))[0] femmesh_obj.FemMesh = fem_mesh femmesh_obj.Part = geom_obj femmesh_obj.SecondOrderLinear = False femmesh_obj.CharacteristicLengthMax = "5.0 mm" doc.recompute() return doc
components
filepath
#!/usr/bin/env python # coding:utf-8 import os from PySide2.QtCore import QFileInfo, QObject, QUrl, Slot class FilepathHelper(QObject): """ FilepathHelper gives access to file path methods not available from JS. It should be non-instantiable and expose only static methods, but this is not yet possible in PySide. """ @staticmethod def asStr(path): """ Accepts strings and QUrls and always returns 'path' as a string. Args: path (str or QUrl): the filepath to consider Returns: str: String representation of 'path' """ if not isinstance(path, (QUrl, str)): raise TypeError("Unexpected data type: {}".format(path.__class__)) if isinstance(path, QUrl): path = path.toLocalFile() return path @Slot(str, result=str) @Slot(QUrl, result=str) def basename(self, path): """Returns the final component of a pathname""" return os.path.basename(self.asStr(path)) @Slot(str, result=str) @Slot(QUrl, result=str) def dirname(self, path): """Returns the directory component of a pathname""" return os.path.dirname(self.asStr(path)) @Slot(str, result=str) @Slot(QUrl, result=str) def extension(self, path): """Returns the extension (.ext) of a pathname""" return os.path.splitext(self.asStr(path))[-1] @Slot(str, result=str) @Slot(QUrl, result=str) def removeExtension(self, path): """Returns the pathname without its extension (.ext)""" return os.path.splitext(self.asStr(path))[0] @Slot(str, result=bool) @Slot(QUrl, result=bool) def isFile(self, path): """Test whether a path is a regular file""" return os.path.isfile(self.asStr(path)) @Slot(str, result=bool) @Slot(QUrl, result=bool) def exists(self, path): """Test whether a path exists""" return os.path.exists(self.asStr(path)) @Slot(QUrl, result=str) def urlToString(self, url): """Convert QUrl to a string using 'QUrl.toLocalFile' method""" return self.asStr(url) @Slot(str, result=QUrl) def stringToUrl(self, path): """Convert a path (string) to a QUrl using 'QUrl.fromLocalFile' method""" return QUrl.fromLocalFile(path) @Slot(str, result=str) @Slot(QUrl, result=str) def normpath(self, path): """Returns native normalized path""" return os.path.normpath(self.asStr(path)) @Slot(str, result=str) @Slot(QUrl, result=str) def globFirst(self, path): """Returns the first from a list of paths matching a pathname pattern.""" import glob fileList = glob.glob(self.asStr(path)) fileList.sort() if fileList: return fileList[0] return "" @Slot(QUrl, result=int) def fileSizeMB(self, path): """Returns the file size in MB.""" return QFileInfo(self.asStr(path)).size() / (1024 * 1024)
End of preview. Expand in Data Studio

Dataset Card for "awesome-python-apps"

This contains .py files for the following repos taken from awesome-python-applications (on GitHub here)

abilian-sbe                  clone_repos.sh   invesalius3   photonix       sk1-wx
ambar                        CONTRIBUTING.md  isso          picard         soundconverter
apatite                      CTFd             kibitzr       pi-hole        soundgrain
ArchiveBox                   Cura             KindleEar     planet         stargate
archivematica                deluge           Lector        plover         streamlink
autokey                      dissemin         lucaschess    pol            Sunflower
awesome-python-applications  drawbot          mackup        posthog        supysonic
babybuddy                    exaile           meshroom      projects.yaml  syncserver
beancount                    flaskbb          mopidy        puddletag      templates
beets                        flowblade        music-player  PyBitmessage   term2048
bleachbit                    fofix            mylar         Pyfa           thumbor
bookwyrm                     formspree        mypaint       pyload         TODO.md
borg                         FreeCAD          neubot        pynocchio      tribler
buku                         frescobaldi      newspipe      pyvideo        vidcutter
Bup                          friture          nfoview       qis            whipper
BY_PLATFORM.md               gaphor           notebooks     quodlibet      you-get
Cactus                       -github          nyaa          qutebrowser    youtube-dl
canto-curses                 gnuradio         ocropy        README.md      ZeroNet
canto-next                   gpodder          OctoPrint     reddit
cartoonify                   hangups          oncall        revisit.yaml
CDDA-Game-Launcher           hosts            openshot-qt   sabnzbd
ckan                         httpie           PhotoCollage  searx

details

There are different configs for different languages and one for 'dcoumentation' type stuff.

All of them should have the same column names, so if you want to use all of them for training it should be easy to aggregate them, just use the concatenate_datasets function + shuffle

by config

python (default)

  • all of them have been formatted with ruff

counts:

(ki) ➜  primerdata-for-LLMs python
Python 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datasets import load_dataset
>>> 
>>> # If the dataset is gated/private, make sure you have run huggingface-cli login
>>> dataset = load_dataset("BEE-spoke-data/awesome-python-apps")
>>> dataset
DatasetDict({
    train: Dataset({
        features: ['section', 'filename', 'text'],
        num_rows: 12394
    })
    validation: Dataset({
        features: ['section', 'filename', 'text'],
        num_rows: 689
    })
    test: Dataset({
        features: ['section', 'filename', 'text'],
        num_rows: 689
    })
})
token counts

Llama (use_fast=False):

           token_len
count        12394.0
mean     7863.521704
std    266330.944961
min            254.0
25%            727.0
50%           1417.0
75%           3083.5
max       27741612.0

NeoX:

          token_len
count        12394.0
mean     6615.093432
std    213090.741642
min            234.0
25%            677.0
50%           1326.0
75%          2883.75
max       22081563.0

javascript

INFO:__main__:Looking for files with extensions: ['js', 'ts', 'tsx']
Processing js files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1441/1441 [00:00<00:00, 2232.28it/s]
Processing ts files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1717/1717 [00:01<00:00, 1343.75it/s]
Processing tsx files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1072/1072 [00:00<00:00, 3929.08it/s]
INFO:__main__:Found 4230 text files.
INFO:__main__:Performing train-test split...
INFO:__main__:Performing validation-test split...
INFO:__main__:Train size: 3807
INFO:__main__:Validation size: 211
INFO:__main__:Test size: 212
INFO:__main__:Pushing dataset to Huggingface hub (BEE-spoke-data/awesome-python-apps)...
INFO:__main__:Using repo id:	BEE-spoke-data/awesome-python-apps, config name:	javascript

c_and_cpp

INFO:__main__:Looking for files with extensions: ['c', 'h', 'i', 'cc', 'cpp', 'cxx', 'hpp', 'hxx', 'inl', 'ino', 'ixx', 'jxx', 'lxx', 'yxx']
Processing c files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 450/450 [00:00<00:00, 2741.92it/s]
Processing h files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 3616/3616 [00:00<00:00, 4250.46it/s]
Processing i files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 197.47it/s]
Processing cc files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1386/1386 [00:00<00:00, 4209.33it/s]
Processing cpp files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 3015/3015 [00:00<00:00, 3254.90it/s]
Processing cxx files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 10/10 [00:00<00:00, 1203.77it/s]
Processing hpp files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 268/268 [00:00<00:00, 3523.76it/s]
Processing hxx files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 257/257 [00:00<00:00, 3406.82it/s]
Processing inl files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 56/56 [00:00<00:00, 2770.02it/s]
Processing ino files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 195.83it/s]
Processing ixx files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 200.43it/s]
Processing jxx files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 187.72it/s]
Processing lxx files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 185.00it/s]
Processing yxx files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 192.69it/s]
INFO:__main__:Found 9064 text files.
INFO:__main__:Performing train-test split...
INFO:__main__:Performing validation-test split...
INFO:__main__:Train size: 8157
INFO:__main__:Validation size: 453
INFO:__main__:Test size: 454
INFO:__main__:Pushing dataset to Huggingface hub (BEE-spoke-data/awesome-python-apps)...
INFO:__main__:Using repo id:	BEE-spoke-data/awesome-python-apps, config name:	c_and_cpp

docs and configs

INFO:__main__:Looking for files with extensions: ['md', 'mdx', 'rst', 'txt', 'env', 'yml', 'yaml', 'toml', 'cfg', 'conf', 'config', 'gitignore', 'MD', 'mkd']
Processing md files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 741/741 [00:00<00:00, 3664.75it/s]
Processing mdx files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 8/8 [00:00<00:00, 1168.29it/s]
Processing rst files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 699/699 [00:00<00:00, 3901.65it/s]
Processing txt files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 646/646 [00:00<00:00, 3348.51it/s]
Processing env files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 188.49it/s]
Processing yml files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 650/650 [00:00<00:00, 4145.67it/s]
Processing yaml files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 62/62 [00:00<00:00, 2146.06it/s]
Processing toml files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 13/13 [00:00<00:00, 1934.71it/s]
Processing cfg files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 618/618 [00:00<00:00, 3866.66it/s]
Processing conf files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 21/21 [00:00<00:00, 2169.95it/s]
Processing config files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 20/20 [00:00<00:00, 2146.14it/s]
Processing gitignore files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 6/6 [00:00<00:00, 890.83it/s]
Processing MD files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1/1 [00:00<00:00, 197.70it/s]
Processing mkd files: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 3/3 [00:00<00:00, 3669.56it/s]
INFO:__main__:Found 3489 text files.
INFO:__main__:Performing train-test split...
INFO:__main__:Performing validation-test split...
INFO:__main__:Train size: 3140
INFO:__main__:Validation size: 174
INFO:__main__:Test size: 175
INFO:__main__:Pushing dataset to Huggingface hub (BEE-spoke-data/awesome-python-apps)...
INFO:__main__:Using repo id:	BEE-spoke-data/awesome-python-apps, config name:	docs_and_configs
Downloads last month
-