Extend automatically Panel with Tabs in Powershell - tabs

I have a frame which contains one panel with Tabs. When I extend the main frame, I vould like my panel was extended too. Can you tell me what can I do for, please ?
function Show-tabcontrol_psf {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$tabcontrol1 = New-Object 'System.Windows.Forms.TabControl'
$tabpage1 = New-Object 'System.Windows.Forms.TabPage'
$tabpage2 = New-Object 'System.Windows.Forms.TabPage'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
$form1_Load={
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$form1.remove_Load($form1_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch { Out-Null }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
$tabcontrol1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($tabcontrol1)
$form1.AutoScaleDimensions = '6, 13'
$form1.AutoScaleMode = 'Font'
$form1.ClientSize = '453, 517'
$form1.Name = 'form1'
$form1.Text = 'Form'
$form1.add_Load($form1_Load)
#
# tabcontrol1
#
$tabcontrol1.Controls.Add($tabpage1)
$tabcontrol1.Controls.Add($tabpage2)
$tabcontrol1.Alignment = 'top'
$tabcontrol1.Location = '12, 12'
$tabcontrol1.Multiline = $True
$tabcontrol1.Name = 'tabcontrol1'
$tabcontrol1.SelectedIndex = 0
$tabcontrol1.Size = '429, 478'
$tabcontrol1.TabIndex = 0
#
# tabpage1
#
$tabpage1.Location = '42, 4'
$tabpage1.Name = 'tabpage1'
$tabpage1.Padding = '3, 3, 3, 3'
$tabpage1.Size = '583, 442'
$tabpage1.TabIndex = 0
$tabpage1.Text = 'tabpage1'
$tabpage1.UseVisualStyleBackColor = $True
#
# tabpage2
#
$tabpage2.Location = '23, 4'
$tabpage2.Name = 'tabpage2'
$tabpage2.Padding = '3, 3, 3, 3'
$tabpage2.Size = '602, 442'
$tabpage2.TabIndex = 1
$tabpage2.Text = 'tabpage2'
$tabpage2.UseVisualStyleBackColor = $True
#
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
} #End Function
Call the form
Show-tabcontrol_psf | Out-Null
----------------------------------------------
function Show-tabcontrol_psf {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$tabcontrol1 = New-Object 'System.Windows.Forms.TabControl'
$tabpage1 = New-Object 'System.Windows.Forms.TabPage'
$tabpage2 = New-Object 'System.Windows.Forms.TabPage'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
$form1_Load={
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$form1.remove_Load($form1_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch { Out-Null }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
$tabcontrol1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($tabcontrol1)
$form1.AutoScaleDimensions = '6, 13'
$form1.AutoScaleMode = 'Font'
$form1.ClientSize = '453, 517'
$form1.Name = 'form1'
$form1.Text = 'Form'
$form1.add_Load($form1_Load)
#
# tabcontrol1
#
$tabcontrol1.Controls.Add($tabpage1)
$tabcontrol1.Controls.Add($tabpage2)
$tabcontrol1.Alignment = 'top'
$tabcontrol1.Location = '12, 12'
$tabcontrol1.Multiline = $True
$tabcontrol1.Name = 'tabcontrol1'
$tabcontrol1.SelectedIndex = 0
$tabcontrol1.Size = '429, 478'
$tabcontrol1.TabIndex = 0
#
# tabpage1
#
$tabpage1.Location = '42, 4'
$tabpage1.Name = 'tabpage1'
$tabpage1.Padding = '3, 3, 3, 3'
$tabpage1.Size = '583, 442'
$tabpage1.TabIndex = 0
$tabpage1.Text = 'tabpage1'
$tabpage1.UseVisualStyleBackColor = $True
#
# tabpage2
#
$tabpage2.Location = '23, 4'
$tabpage2.Name = 'tabpage2'
$tabpage2.Padding = '3, 3, 3, 3'
$tabpage2.Size = '602, 442'
$tabpage2.TabIndex = 1
$tabpage2.Text = 'tabpage2'
$tabpage2.UseVisualStyleBackColor = $True
#
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
} #End Function
Call the form
Show-tabcontrol_psf | Out-Null

I have an incomplete solution
$TabControl.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom
$TabControl.Anchor = [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
I have to gather this two lines and the problem will be solved.

I had the solution :
$TabControl.Anchor = [System.Windows.Forms.AnchorStyles]::Top
-bor [System.Windows.Forms.AnchorStyles]::Bottom
-bor [System.Windows.Forms.AnchorStyles]::Left
-bor [System.Windows.Forms.AnchorStyles]::Right

Related

How to add an user input to to an URL with Tkinter?

I'm trying to create a program in which currency conversion is crucial. I have an API URL to which I want to add user input (amount that is supposed to be converted) not to display it in a label but to work with it later on.
input = Entry(root)
URL = "https://www.myawesomeurl.com/exchangerate/amout="
payload = {}
headers = {"apikey": "awjdwahduwahdwauduw"}
response = requests.request("GET", URL, headers=headers, data = payload)
status_code = response.status_code
result = response.text
I'm new to programming so any help and tips would be much appreciated.
You can use a submit function to process your data. Ex.
import tkinter
import requests
root = tkinter.Tk()
def submitamount():
amounttext = amount.get()
URL = f"https://www.myawesomeurl.com/exchangerate/amout={amounttext}"
payload = {}
headers = {"apikey": "awjdwahduwahdwauduw"}
response = requests.request("GET", URL, headers=headers, data=payload)
status_code = response.status_code
result = response.text
# Do stuff here / call another function to do stuff
#
# If you want to make some variables accessible to other parts of
# the code, simply define them before this function is declared;
# Ex.
#
# Instead of:
# root = tkinter.Tk()
# ...
# def submitamount():
# ...
#
# Do:
# root = tkinter.Tk()
# ...
# response = None
# status_code = None
# result = None
#
# def submitamount():
# ...
#
amount = tkinter.Entry(root)
amount.pack()
submit = tkinter.Button(text="Submit", command=submitamount)
submit.pack()
root.mainloop()
If you need a more thorough explanation, please let me know!

Try to track down Blazor Client side Exception

We have been using RadzenBlazor for a while now with good success. Recently, the Filtering is causing an exception. The actual exception is not forthcoming to me so I am wondering how to better read it. I know Blazor client side errors are not so great. Most of the time, when it is code I have written you get a variable or something to point me in the direction of the cause, but not in this case as near as I can tell. I can select items and unselect items with no issue. The second I type in a letter to filter down the list, I get the exception below. I am just trying to figure out if it is Radzen or something else.
I have tried implementing this from the Microsoft Docs but no extra info was shown.
First, here is the code, for the DropDown
<RadzenDropDown Multiple="true"
AllowClear="true"
AllowFiltering="true"
FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive"
Placeholder="Select Claim(s)..."
#bind-Value="SelectedClaimIds"
Data="availablePerformanceClaims"
TextProperty="Name"
ValueProperty="Id"
TValue="IEnumerable<int>"
Class="w-100 items-inline">
</RadzenDropDown>
[Inject]
private ISomeService someService { get; set; }
[Inject]
private IMapper mapper { get; set; }
public IEnumerable<PerformanceClaimMinimalModel> availablePerformanceClaims { get; set; } = new List<PerformanceClaimMinimalModel>();
public IEnumerable<int> SelectedClaimIds = Array.Empty<int>();
protected override async Task OnInitializedAsync()
{
availablePerformanceClaims = mapper.Map<IEnumerable<SelectablePerformanceClaimMinimalModel>>(
await someService .GetPerformanceClaimsAsync(new PerformanceClaimSearchModel
{
ValidUntilEnd = null,
})
)
.OrderBy(x => x.Issuer)
.ThenBy(x => x.Name)
.ThenBy(x => x.Version);
}
And here is the exception
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Linq.Dynamic.Core.Parser.KeywordsHelper..ctor(ParsingConfig config)
at System.Linq.Dynamic.Core.Parser.ExpressionParser..ctor(ParameterExpression[] parameters, String expression, Object[] values, ParsingConfig parsingConfig)
at System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(Type delegateType, ParsingConfig parsingConfig, Boolean createParameterCtor, ParameterExpression[] parameters, Type resultType, String expression, Object[] values)
at System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(ParsingConfig parsingConfig, Boolean createParameterCtor, ParameterExpression[] parameters, Type resultType, String expression, Object[] values)
at System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(ParsingConfig parsingConfig, Boolean createParameterCtor, Type itType, Type resultType, String expression, Object[] values)
at System.Linq.Dynamic.Core.DynamicQueryableExtensions.Where(IQueryable source, ParsingConfig config, String predicate, Object[] args)
at System.Linq.Dynamic.Core.DynamicQueryableExtensions.Where(IQueryable source, String predicate, Object[] args)
at Radzen.DropDownBase`1[[System.Collections.Generic.IEnumerable`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].get_View()
at Radzen.Blazor.RadzenDropDown`1[[System.Collections.Generic.IEnumerable`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].BuildRenderTree(RenderTreeBuilder __builder)
at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
window.Module.s.printErr # blazor.webassembly.js:1
Te._internal.dotNetCriticalError # blazor.webassembly.js:1
Rt # blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor # dotnet.6.0.4.dckq00jdfr.js:1
$func219 # 00970c26:0x1a0fb
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1619 # 00970c26:0x6ffa2
$mono_wasm_invoke_method # 00970c26:0x969b
Module._mono_wasm_invoke_method # dotnet.6.0.4.dckq00jdfr.js:1
managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_EndInvokeJS # managed__Microsoft_A…time_EndInvokeJS:16
endInvokeJSFromDotNet # blazor.webassembly.js:1
(anonymous) # blazor.webassembly.js:1
Promise.then (async)
beginInvokeJSFromDotNet # blazor.webassembly.js:1
Rt # blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor # dotnet.6.0.4.dckq00jdfr.js:1
$func219 # 00970c26:0x1a0fb
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1619 # 00970c26:0x6ffa2
$func3213 # 00970c26:0xc4abd
$mono_background_exec # 00970c26:0x93f6d
Module._mono_background_exec # dotnet.6.0.4.dckq00jdfr.js:1
pump_message # dotnet.6.0.4.dckq00jdfr.js:1
setTimeout (async)
_schedule_background_exec # dotnet.6.0.4.dckq00jdfr.js:1
$func2387 # 00970c26:0x93f1e
$func3212 # 00970c26:0xc4a4d
$func219 # 00970c26:0x1a163
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1619 # 00970c26:0x6ffa2
$mono_set_timeout_exec # 00970c26:0xc49ba
Module._mono_set_timeout_exec # dotnet.6.0.4.dckq00jdfr.js:1
mono_wasm_set_timeout_exec # dotnet.6.0.4.dckq00jdfr.js:1
mono_wasm_set_timeout_exec # dotnet.6.0.4.dckq00jdfr.js:1
setTimeout (async)
_mono_set_timeout # dotnet.6.0.4.dckq00jdfr.js:1
$func3211 # 00970c26:0xc4a45
$func219 # 00970c26:0x1a030
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1613 # 00970c26:0x6f8a7
$func966 # 00970c26:0x502f8
$func219 # 00970c26:0x1a0b4
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1613 # 00970c26:0x6f8a7
$func966 # 00970c26:0x502f8
$func219 # 00970c26:0x1a0b4
$func167 # 00970c26:0xcac9
$func166 # 00970c26:0xb9dc
$func2810 # 00970c26:0xabb22
$func1615 # 00970c26:0x6f935
$func1619 # 00970c26:0x6ffa2
$mono_wasm_invoke_method # 00970c26:0x969b
Module._mono_wasm_invoke_method # dotnet.6.0.4.dckq00jdfr.js:1
managed__Microsoft_AspNetCore_Components_WebAssembly__Microsoft_AspNetCore_Components_WebAssembly_Services_DefaultWebAssemblyJSRuntime_BeginInvokeDotNet # managed__Microsoft_A…eginInvokeDotNet:19
beginInvokeDotNetFromJS # blazor.webassembly.js:1
b # blazor.webassembly.js:1
invokeMethodAsync # blazor.webassembly.js:1
(anonymous) # blazor.webassembly.js:1
invokeWhenHeapUnlocked # blazor.webassembly.js:1
S # blazor.webassembly.js:1
C # blazor.webassembly.js:1
dispatchGlobalEventToAllElements # blazor.webassembly.js:1
onGlobalEvent # blazor.webassembly.js:1
Turns out it was BlazorApplicationInsights that was giving me an issue. I may be doing it wrong, but we have an HttpService and I was trying to catch errors, which it does. But clearly Radzen has issues with it. I have no issues with the BAI, but I will have to circle back on figure out what the issue is.
private async Task<bool> HandleResponseFailure(HttpVerbs verb, HttpResponseMessage responseMessage)
{
if (!responseMessage.IsSuccessStatusCode)
{
await appInsights.TrackException(
new Error
{
Message = responseMessage.ReasonPhrase,
Name = $"{verb.ToString().ToUpper()} Request Exception: StatusCode: {responseMessage.StatusCode} - {responseMessage.RequestMessage.RequestUri}",
}
);
Utils.HideSpinner();
Utils.WriteError(jsRuntime, $"Error during {verb.ToString().ToUpper()}, Status Code: {responseMessage.StatusCode}, Uri: {responseMessage.RequestMessage.RequestUri}");
// TODO: Do we want this -> Utils.ShowErrorNotification($"{verb.ToString().ToUpper()} Exception", $"Status Code: {responseMessage.StatusCode}\n{responseMessage.RequestMessage.RequestUri}");
}
return responseMessage.IsSuccessStatusCode;
}

Open and Save as Json configurations files of the user settings in an app made with tkinter

When the json file is saved it works, but when the same file is open, won't load the user settings in to the app.
def save_as():
data = {
'win left': left_w.get(),
'win top': top_w.get(),
'win width': width_w.get(),
'win height': height_w.get()
}
with open('{}'.format(filedialog.asksaveasfilename(initialdir="/",
title="Select file", filetypes=(("json files",
"*.json"), ("all files", "*.*")))), 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.close()
print(data)
def open_file():
open_config = filedialog.askopenfilename(initialdir="/", title="Select
file", filetypes=(("json files", "*.json"),
("all files", "*.*")))
config = open(open_config)
json_file = json.load(config)
config.close()
print(json_file)
# Menu
filemenu.add_command(label="Open", command=open_file)
filemenu.add_command(label="Save as...", command=save_as)
# Entry fields
left_w = IntVar()
top_w = IntVar()
width_w = IntVar()
height_w = IntVar()
wl = Entry(master=page2, textvariable=left_w, width=6).grid(column=1, row=1)
wt = Entry(master=page2, textvariable=top_w, width=6).grid(column=3, row=1)
ww = Entry(master=page2, textvariable=width_w, width=6).grid(column=5, row=1)
wh = Entry(master=page2, textvariable=height_w, width=6).grid(column=7, row=1)
I want to be enable to save and load the user settings of the entry fields on the App.
Right now only save, when the file is loaded, the App print the user settings of the file but don't load the user settings, and don't give any error.
On the def open_file() I just add:
left_w.set(data['win left'])
top_w.set(data['win top'])
Now when the json file is load, the app replace the values for the ones that are on the file.

How to Build Config Files in python?

As I'm new and learning python, exploring different ways to build a config file for python based framework.
I have come across using-built-in-data-structure-complicated-py , couldn't understand main.py . Could you help me with how main.py should look like and how the variables from config.py can be accessed in main.py.
# config.py
class Config:
APP_NAME = 'myapp'
SECRET_KEY = 'secret-key-of-myapp'
ADMIN_NAME = 'administrator'
AWS_DEFAULT_REGION = 'ap-northeast-2'
STATIC_PREFIX_PATH = 'static'
ALLOWED_IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'gif']
MAX_IMAGE_SIZE = 5242880 # 5MB
class DevelopmentConfig(Config):
DEBUG = True
AWS_ACCESS_KEY_ID = 'aws-access-key-for-dev'
AWS_SECERT_ACCESS_KEY = 'aws-secret-access-key-for-dev'
AWS_S3_BUCKET_NAME = 'aws-s3-bucket-name-for-dev'
DATABASE_URI = 'database-uri-for-dev'
class TestConfig(Config):
DEBUG = True
TESTING = True
AWS_ACCESS_KEY_ID = 'aws-access-key-for-test'
AWS_SECERT_ACCESS_KEY = 'aws-secret-access-key-for-test'
AWS_S3_BUCKET_NAME = 'aws-s3-bucket-name-for-test'
DATABASE_URI = 'database-uri-for-dev'
class ProductionConfig(Config):
DEBUG = False
AWS_ACCESS_KEY_ID = 'aws-access-key-for-prod'
AWS_SECERT_ACCESS_KEY = 'aws-secret-access-key-for-prod'
AWS_S3_BUCKET_NAME = 'aws-s3-bucket-name-for-prod'
DATABASE_URI = 'database-uri-for-dev'
class CIConfig:
SERVICE = 'travis-ci'
HOOK_URL = 'web-hooking-url-from-ci-service'
# main.py
import sys
import config
...
if __name__ == '__main__':
env = sys.argv[1] if len(sys.argv) > 2 else 'dev'
if env == 'dev':
app.config = config.DevelopmentConfig
elif env == 'test':
app.config = config.TestConfig
elif env == 'prod':
app.config = config.ProductionConfig
else:
raise ValueError('Invalid environment name')
app.ci = config.CIConfig
What is app.config and app.ci ? How is it being used ?
And also, what all other best possible pythonic way to manage config files ?
If I have multiple set of profiles/credentials (username-password), how do i manage them ?
Any possible encryption to files containing credentials ?
Will be of great learning to me.
Here is a small example of how you could use config files
class Config:
APP_NAME='myapp'
ADMIN='admin'
class DevelopmentConfig(Config):
DEBUG = True
ADMIN = 'dev_admin'
class ProductionConfig(Config):
DEBUG = False
def main():
config = ProductionConfig # Change to DevelopmentConfig to experiment
# You may now use your config where you want
print(config.DEBUG)
print(config.ADMIN)
if __name__ == "__main__":
main()
This example does not use command line arguments like your example but should give you a good idea of building config files and using them.
In your example app.ci refers to configuration for continuous integration(CI) environment.

ROS service failed to save files

I want to have a service 'save_readings' that automatically saves data from a rostopic into a file. But each time the service gets called, it doesn't save any file.
I've tried to run those saving-file code in python without using a rosservice and the code works fine.
I don't understand why this is happening.
#!/usr/bin/env python
# license removed for brevity
import rospy,numpy
from std_msgs.msg import String,Int32MultiArray,Float32MultiArray,Bool
from std_srvs.srv import Empty,EmptyResponse
import geometry_msgs.msg
from geometry_msgs.msg import WrenchStamped
import json
# import settings
pos_record = []
wrench_record = []
def ftmsg2listandflip(ftmsg):
return [ftmsg.wrench.force.x,ftmsg.wrench.force.y,ftmsg.wrench.force.z, ftmsg.wrench.torque.x,ftmsg.wrench.torque.y,ftmsg.wrench.torque.z]
def callback_pos(data):
global pos_record
pos_record.append(data.data)
def callback_wrench(data):
global wrench_record
ft = ftmsg2listandflip(data)
wrench_record.append([data.header.stamp.to_sec()] + ft)
def exp_listener():
stop_sign = False
rospy.Subscriber("stage_pos", Float32MultiArray, callback_pos)
rospy.Subscriber("netft_data", WrenchStamped, callback_wrench)
rospy.spin()
def start_read(req):
global pos_record
global wrench_record
pos_record = []
wrench_record = []
return EmptyResponse()
def save_readings(req):
global pos_record
global wrench_record
filename = rospy.get_param('save_file_name')
output_data = {'pos_list':pos_record, 'wrench_list': wrench_record }
rospy.loginfo("output_data %s",output_data)
with open(filename, 'w') as outfile: # write data to 'data.json'
print('dumping json file')
json.dump(output_data, outfile) #TODO: find out why failing to save the file.
outfile.close()
print("file saved")
rospy.sleep(2)
return EmptyResponse()
if __name__ == '__main__':
try:
rospy.init_node('lisener_node', log_level = rospy.INFO)
s_1 = rospy.Service('start_read', Empty, start_read)
s_1 = rospy.Service('save_readings', Empty, save_readings)
exp_listener()
print ('mylistener ready!')
except rospy.ROSInterruptException:
pass
Got it. I need to specify a path for the file to be saved.
save_path = '/home/user/catkin_ws/src/motionstage/'
filename = save_path + filename