instruction stringlengths 0 30k ⌀ |
|---|
I was facing the same issue after some troubleshooting, I was able to fix the issue.
- Check the python version in local machine and Lambda (It should be similar) as few packages are not imported properly when different version is there.
Create Zip file in below mentioned path:
- Create Virtual environment for python3.
```
python3 -m venv venv
source venv/bin/activate
```
- Create a directory with name "python"
```
mkdir python
cd python
```
- Install you packages in this folder.
```
pip3 install tuya-connector-python -t .
```
- Once installed Check the packages.
- Create ZIP file for python directory
```
cd ..
zip -r deployment_name.zip python
```
- Now you can upload the .zip file to you AWS Lambda Layer.
**Make sure the ZIP file is created for all folder available in python folder Don't miss out any files or folders it may be our main package may be dependent on it.**
----------
**For Windows**
- Using power shell or Command Prompt perform following steps (admin privileges):
```
mkdir layers
cd layers
mkdir python
cd python
pip3 install tuya-connector-python -t ./
```
- Now open the python folder in file explorer.
- Zip the python folder along with its child folders.
- Now you are good to go and upload it as layer in AWS.
**It will great if you have Linux Machine or Create an EC2 Instance with Ubuntu AMI and Copy the Content to S3, the you can upload it from S3 bucket to AWS lambda layer directly.**
Update:
- I have Created Similar Scenario in my environment:
- I installed the Crypto library in my local machine(Ubuntu) as per above mentioned steps.
[![Installation Image][1]][1]
- Created a Zip.
[![Zip File][2]][2]
- Uploaded the ZIP file to create layer and added layer to lambda
[![Lambda Function][3]][3]
- It worked as Charm:
[![Output][4]][4]
**Make Sure to add the layer to lambda**
**My Python version was 3.10 for local and Lambda's python**
[1]: https://i.stack.imgur.com/XjbIS.png
[2]: https://i.stack.imgur.com/dYFXF.png
[3]: https://i.stack.imgur.com/TrMrW.png
[4]: https://i.stack.imgur.com/xc6OB.png |
How to prevent installation when application is installed already with Inno Setup? |
When adding the new claim you also needed to do this:
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
So the new full code block is:
public static MvcHtmlString GetUsersFirstAndLastName(this HtmlHelper helper)
{
string fullName = HttpContext.Current?.User?.Identity?.Name ?? string.Empty;
var userIdentity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var nameClaim = identity?.FindFirst("fullname");
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
if (nameClaim != null)
{
fullName = nameClaim.Value;
}
return MvcHtmlString.Create(fullName);
} |
I found that SteamCMD is a clumsy broken tool. And if you only want a quick check for updates when a game server is running. So only a check and decide in code if you want to stop your server and update on the result of your check. Then SteamCMD is not your friend.
So i did write a short powershell script to get more useful info out of SteamCMD.
param(
[Parameter(Mandatory)][string]$SteamCMD, # Path to SteamCMD.exe, path can have spaces. Example: -SteamCMD C:\SteamCMD\steamcmd.exe
[Parameter(Mandatory)][string]$AppID, # Steam AppID. Example for ARK Ascended server: -AppID 2430930
[Parameter(Mandatory)][string]$branch, # Branch you want to check for updates. Example: -branch public
[Parameter(Mandatory)][string]$force_install_dir, # Path of local install you want to check for updates, path cannot have spaces (SteamCMD limitation)
# Example: -force_install_dir C:\SERVERS\ArkAscended\server\
[ValidateSet("update_available","installed_version","latest_version","app_status_json","app_info_json")]
[Parameter(Mandatory)][string]$output="update_available"
# What output do you want.
# -output update_available (will output single line with true or false)
# -output installed_version (will output a single line with a number)
# -output latest_version (will output a single line with a number)
# -output app_status_json (will output what SteamCMD should have output when they would have developed their tooling right)
# -output app_info_json (will output what SteamCMD should have output when they would have developed their tooling right)
)
$exec = @'
& "$SteamCMD" +@ShutdownOnFailedCommand 1 +@NoPromptForPassword 1 +force_install_dir $force_install_dir +login anonymous +app_info_update 1 +app_status $AppID +quit
'@
$App_Status_stdout=Invoke-Expression -Command $exec
$App_Status = [PSCustomObject]@{}
foreach($App_Status_line in $App_Status_stdout){
if($App_Status_line.StartsWith('AppID')){
$Items=$App_Status_line -split "\(",2
$App_Status | Add-Member -MemberType NoteProperty -Name ($Items[0].Trim() -split " ",2)[0] -Value ($Items[0].Trim() -split " ",2)[1]
$App_Status | Add-Member -MemberType NoteProperty -Name 'Name' -Value ($Items[1].Trim() -split "\)",2)[0]
}
if($App_Status_line.StartsWith(' - ') -or $App_Status_line.StartsWith(' ')){
if($App_Status_line.StartsWith(' ')){
#Add-NoteProperty -InputObject $App_Status -Property "mounted_depots.$(($App_Status_line -split ':',2)[0].Replace(' - ','').trim().replace(' ','_'))" -Value ($App_Status_line -split ':',2)[1].trim()
$App_Status.mounted_depots | Add-Member -MemberType NoteProperty -Name ($App_Status_line -split ':',2)[0].Replace(' - ','').trim().replace(' ','_') -Value ($App_Status_line -split ':',2)[1].trim()
}else{
if(($App_Status_line -split ':',2)[0].Replace(' - ','').trim().replace(' ','_') -eq "mounted_depots"){
$App_Status | Add-Member -MemberType NoteProperty -Name ($App_Status_line -split ':',2)[0].Replace(' - ','').trim().replace(' ','_') -Value (New-Object PSCustomObject) -Force:$Force.IsPresent
}else{
$App_Status | Add-Member -MemberType NoteProperty -Name ($App_Status_line -split ':',2)[0].Replace(' - ','').trim().replace(' ','_') -Value ($App_Status_line -split ':',2)[1].trim()
}
}
}
}
$exec = @'
& "$SteamCMD" +@ShutdownOnFailedCommand 1 +@NoPromptForPassword 1 +login anonymous +app_info_update 1 +app_info_print $AppID +logoff +quit
'@
$App_Info_stdout=Invoke-Expression -Command $exec
#Remove unwanted content from the output of App_Info
$App_Info= ($App_Info_stdout | ? {$_.contains('{') -or $_.contains('}') -or $_.contains('"')}) -join "`r`n" | Out-String
$App_Info = $App_Info.SubString($App_Info.IndexOf("{"),$App_Info.LastIndexOf("}")+1-$App_Info.IndexOf("{"))
#Correct the output to be proper json and convert to object
$App_Info = ConvertFrom-Json $App_Info.Replace("`t", "").Replace('""','":"').Replace("`"`r`n{","`":`r`n{").Replace("`"`r`n`"","`",`r`n`"").Replace("}`r`n`"","},`r`n`"")
Switch($output){
"update_available" {
If($($App_Status.size_on_disk.Split(',',2)[1].trim().split(' ',2)[1]) -ne $($App_Info.depots.branches."$($branch)".buildid)){
Write-Host "true"
}else{
Write-Host "false"
}
}
"installed_version" {
Write-Host $($App_Status.size_on_disk.Split(',',2)[1].trim().split(' ',2)[1])
}
"latest_version" {
Write-Host $($App_Info.depots.branches."$($branch)".buildid)
}
"app_status_json" {
Write-Host (ConvertTo-Json $App_Status -Depth 99)
}
"app_info_json" {
Write-Host (ConvertTo-Json $App_Info -Depth 99)
}
}
|
Investigating the topic of Entity Component System, I've faced to an issue of maintaining constant data of components.
For instance, having a movement component I'd like an according system to know the maximum speed of every entity.
Classically, I'd imagine this as the list with descriptions of entities containing speeds (and other such constants) of every type entity, that objects refer to.
But ECS tempts me to use variable description sets, that leads to another ECS for descriptions. And this looks like overhead.
That's regarding initializing components set withing the entity as well.
Maybe I miss something and there're more concise ways to do this?
|
Maintaining constant data in ECS |
|c++|amazon-ecs|entity-component-system| |
null |
I'm currently working on a project where I'm able to generate a sitemap successfully. I've created several sitemaps, and one of them is named "videos". After some research, I discovered that Google recommends using a dedicated sitemap for videos.
Here's an example of the structure recommended by Google for a video sitemap:
````
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
<url>
<loc>https://www.example.com/videos/some_video_landing_page.html</loc>
<video:video>
<video:thumbnail_loc>https://www.example.com/thumbs/123.jpg</video:thumbnail_loc>
<video:title>Lizzi is painting the wall</video:title>
<video:description>
Gary is watching the paint dry on the wall Lizzi painted.
</video:description>
<video:player_loc>
https://player.vimeo.com/video/987654321
</video:player_loc>
</video:video>
</url>
</urlset>
`````
After many hours of research, I couldn't find any documentation regarding generating a video sitemap with Next.js that allows customizing the tags. Currently, my code looks like this:
````
if (id === "videos") {
if (Array.isArray(video)) {
return video.map((video) => ({
url: `${baseUrl}/tv/${video.id}/${helpers.formatTextUrl(video.title)}`,
hello: new Date().toISOString(),
changeFrequency: "daily",
priority: 0.5,
}));
}
}
`````
The resulting output looks like this:
`````
<url>
<loc>http://exemple.com/tv/68/070324-le-journal-de-maritima-tv</loc>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
`````
I would like to know if anyone has managed to modify the tags of the XML sitemap generated by Next.js |
I'm a beginner with Qt Creator. I can't figure out how to center my layout in the window, even when I expand it to full screen size.
Please review my object trees and GUI image. After running the code, the layout appears centered, but when the window is maximized, it shifts to the left.
(Apologies for the long image; I have a wide monitor)
1. Captured GUI, object trees

2. Before fullscreen

3. After fullscreen

I googled, asked to GPT but I couldn't find a way. |
In [Android Studio Iguana | 2023.2.1][1]
Follow these steps:
1) Right click on toolbar
[![enter image description here][2]][2]
2) Choose Add to Main Toolbar > Back / Forward option
[![enter image description here][3]][3]
3) On click on Back / Forward action, buttons will appear in toolbar.
[![enter image description here][4]][4]
[1]: https://developer.android.com/studio/releases?_gl=1*1k1vjvr*_up*MQ..&gclid=Cj0KCQjwncWvBhD_ARIsAEb2HW81H9Sl1GLYKtZWKb2R5dCQFPscCHOKcrdTZbZZUegJ4jyAZSLMdeUaAoIvEALw_wcB&gclsrc=aw.ds
[2]: https://i.stack.imgur.com/ZWJNj.png
[3]: https://i.stack.imgur.com/nud0k.png
[4]: https://i.stack.imgur.com/y6343.png |
I'm unsuccessfully trying to strip grouping (thousands separator) from std::locale.
I need to strip it from locale set in OS (for example sk_SK locale) but retain all others locale dependent formatting characteristics (decimal separator, etc).
Some of my attempts are in the code bellow. Looks like combining locale with *no_separator* strip all numpunct characteristics and reset them all back to "C" locale, instead of modifying just do_grouping characteristic.
(Windows10, VS, SDK 10.0, MSVC v142)
```
#include <iostream>
#include <locale>
#include <sstream>
struct no_separator : std::numpunct<char>
{
protected:
virtual string_type do_grouping() const
{
return "\0";
} // groups of 0 (disable)
};
int main()
{
std::cout.precision(8);
std::cout.width(12);
std::cout << "Test \"C\": " << 1234.5678 << std::endl; // OK - 1234.5678
std::locale skSKLocale("sk_SK");
std::cout.imbue(skSKLocale);
std::cout << "Test skSK: " << 1234.5678 << std::endl; // OK - 1 234,5678
//std::locale::global(skSKLocale);
std::locale localeNoThousandsSeparator = std::locale(skSKLocale, new no_separator());
std::locale finishedLoc = skSKLocale.combine<std::numpunct<char>>(localeNoThousandsSeparator);
std::cout.imbue(localeNoThousandsSeparator);
std::cout << "Test localeNoThousandsSeparator: " << 1234.5678 << std::endl; // BAD - expected 1234,5678, got 1234.5678
std::cout.imbue(finishedLoc);
std::cout << "Test finishedLoc: " << 1234.5678 << std::endl; // BAD - expected 1234,5678, got 1234.5678
}
```
Thank you for your help.
|
Remove grouping from numpunct of std::locale |
|c++|locale|customization| |
null |
I have used recast for my code generation with babel as i have checked it is compatible with babel but recast is removing all my comments
Here is my recast code
const generatedAst = recast.print(ast, {
tabWidth: 2,
quote: 'single',
});
I am passing AST generated from babel parse
and directly if i use babel generate to generate my code then parenthesis are removed
Can anyone help me with this
Thank you in advance
I don't know any other package that is compatible with babel
i used recast because i have checked this [text](https://github.com/babel/babel/issues/8974) and in this it is mentioned that babel removes parenthesis
This is the AST that is generated using babel parse
Node {
type: 'File',
start: 0,
end: 1046,
loc: SourceLocation {
start: Position { line: 1, column: 0, index: 0 },
end: Position { line: 45, column: 0, index: 1046 },
filename: undefined,
identifierName: undefined
},
errors: [],
program: Node {
type: 'Program',
start: 0,
end: 1046,
loc: SourceLocation {
start: [Position],
end: [Position],
filename: undefined,
identifierName: undefined
},
sourceType: 'module',
interpreter: null,
body: [ [Node], [Node], [Node], [Node], [Node] ],
directives: []
},
comments: [
{
type: 'CommentLine',
value: ' eslint-disable-next-line react/no-array-index-key',
start: 191,
end: 243,
loc: [SourceLocation]
}
]
}
and using babel-generate the parenthesis are being removed
Using this i am parsing the code and from where the AST is being generated
const ast = parse(originalCode, {
sourceType: 'module',
plugins: ['jsx'],
}); |
How do I animate values of a Shape with multiple different animation transactions simultaneously? |
|ios|swift|xcode|animation|swiftui| |
I believe the issue is that the CUDA toolkit version of your Pytorch installation is not compatible with the compute capability of your GPU. If you look into the [CUDA support table][1], you see that the `RTX 6000 Ada` has a compute capability version of `8.9`. This compute version only supports CUDA SDK versions **above** `11.8`.
|Compute Capability (CUDA SDK support vs. Microarchitecture)|
|:-:|
|[![enter image description here][2]][2]|
However, the CUDA toolkit version you have installed - according to the image you are using - is `11.3.0` which is lower than the minimum supported version by a `RTX 6000 Ada`. In other words, you should use an image that comes with a higher CUDA toolkit version.
I looked at the available images, from release version [`22-09`][3], and the shipped CUDA toolkit is equal to or higher than `11.8`. The first image that has this requirement is `1.13.0a0+d0d6b1f`.
[1]: https://en.wikipedia.org/wiki/CUDA#GPUs_supported
[2]: https://i.stack.imgur.com/tm7vV.png
[3]: https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-22-09.html |
{"OriginalQuestionIds":[43185605],"Voters":[{"Id":4294399,"DisplayName":"General Grievance"},{"Id":14122,"DisplayName":"Charles Duffy","BindingReason":{"GoldTagBadge":"python"}}]} |
I have three lists
#### Example Data
```
data =list("A-B", "C-D", "E-F", "G-H", "I-J")
data_to_replace = list("A-B", "C-D")
replacement = list("B-A"), "D-C")
```
This is just a minimal examples. I have several of this three-list and the number varies in each list
#### Expected outcome
data_new = list("B-A", "D-C", "E-F", "G-H", "I-J")
#### What i have tried
# function that reverses a string by words
reverse_words <- function(string)
{
# split string by blank spaces
string_split = strsplit(as.character(string), split = "-")
# how many split terms?
string_length = length(string_split[[1]])
# decide what to do
if (string_length == 1) {
# one word (do nothing)
reversed_string = string_split[[1]]
} else {
# more than one word (collapse them)
reversed_split = string_split[[1]][string_length:1]
reversed_string = paste(reversed_split, collapse = "-")
}
# output
return(reversed_string)
}
#Replacemnt
replacement = lapply(data_to_replace, reverse_words)
data_new = rapply(data, function(x) replace(x, x== data_to_replace, replacement )) #This last line did not work
#### Example Data
```
data =list("A-B", "C-D", "E-F", "G-H", "I-J")
data_to_replace = list("A-B", "C-D")
replacement = list("B-A"), "D-C")
```
This is just a minimal examples. I have several sets of these three lists, and the number of elements varies in each list.
#### Expected outcome
data_new = list("B-A", "D-C", "E-F", "G-H", "I-J")
#### What i have tried
# function that reverses a string by words
reverse_words <- function(string)
{
# split string by blank spaces
string_split = strsplit(as.character(string), split = "-")
# how many split terms?
string_length = length(string_split[[1]])
# decide what to do
if (string_length == 1) {
# one word (do nothing)
reversed_string = string_split[[1]]
} else {
# more than one word (collapse them)
reversed_split = string_split[[1]][string_length:1]
reversed_string = paste(reversed_split, collapse = "-")
}
# output
return(reversed_string)
}
#Replacemnt
replacement = lapply(data_to_replace, reverse_words)
data_new = rapply(data, function(x) replace(x, x== data_to_replace, replacement )) #This last line did not work
|
I got inspired by seeing a terminal prompt in my native language, after accidentally running into the computer lab in a new school when I was looking for my class.
It was a weird and sudden realization that the games and apps I was using on my computer weren't just made by some superhuman scientists on the other side of the world, but it can be done anywhere, just like here in the lab, by my peers. |
null |
I've got a problem with running Invoke-Command on remote Computer with WinRM up and running. I've configured and run WinRM, but Invoke-Command with task of Silent Install is not successfully run until I've run it when any User is logged in on remote PC. So without active users session the task simply hangs and nothing happened, but with User session everything works as expected. I've checked everything inside Script Block and it's correct. I've tried to run task with adding User to Local Administrator Group and as Domain Admin, the same... Any suggestions? Thx
Part of my code is below:
# Create Session
$session = New-PSSession -ComputerName $computer
# Install the application on the remote computer
Invoke-Command -Session $session -ScriptBlock {
Start-Process -FilePath "c:\VMware-Horizon-Agent-x86_64-2312-8.12.0-23142606.exe" -ArgumentList "/s /v`"/qn ADDLOCAL=Core,USB,RTAV,VmwVaudio,GEOREDIR,V4V,PerfTracker,HelpDesk,PrintRedir REMOVE=ClientDriveRedirection`"" -Wait
}
I've tried to silent install software by running Invoke Command and expected the command will run successfully |
Invoke-command wotks only whan any user logged |
You can define a new method on `Array` object prototype. E.g:
Array.prototype.IsTrue = function () {
return true;
}
Then use it:
product.attributes.IsTrue()
But this method will exist on every instance of Array object. E.g: `[1,'abc'].IsTrue()` is a valid usage.
You can't define the extension method for only one interface of your choice, because javascript actually don't have the notion of `Interface` or `Type`. It's just a language feature that Typescript bring up to help your developer life easier.
The recommended approach in React world would be some Utility functions, you import and use them on demand. |
By running `adb shell wm size <size>x<size>` the default size of the device is set to `size` . if you want to revert it to the previous default value, you need to know the size value of the screen before you modified it.
If you don't know the default size of the adb screen -
- open android studio
- click on Device Manager in Slidebar
- click on 3 dot menu
- click on Details Or click on Edit
- from there you can get the size of device.
After you get or know the size rerun `adb shell wm size <size>x<size>` with size described above. |
This is my code to read the csv file asynchronoulsy using ReadLineAsync() function from the [StreamReader][1] class but it reads first line only of the [csv file][2]
private async Task ReadAndSendJointDataFromCSVFileAsync(CancellationToken cancellationToken) {
Stopwatch sw = new Stopwatch();
sw.Start();
string filePath = @ "/home/adwait/azure-iot-sdk-csharp/iothub/device/samples/solutions/PnpDeviceSamples/Robot/Data/Robots_data.csv";
using(StreamReader oStreamReader = new StreamReader(File.OpenRead(filePath))) {
string sFileLine = await oStreamReader.ReadLineAsync();
string[] jointDataArray = sFileLine.Split(',');
// Assuming the joint data is processed in parallel
var tasks = new List < Task > ();
// Process joint pose
tasks.Add(Task.Run(async () => {
var jointPose = jointDataArray.Take(7).Select(Convert.ToSingle).ToArray();
var jointPoseJson = JsonSerializer.Serialize(jointPose);
await SendTelemetryAsync("JointPose", jointPoseJson, cancellationToken);
}));
// Process joint velocity
tasks.Add(Task.Run(async () => {
var jointVelocity = jointDataArray.Skip(7).Take(7).Select(Convert.ToSingle).ToArray();
var jointVelocityJson = JsonSerializer.Serialize(jointVelocity);
await SendTelemetryAsync("JointVelocity", jointVelocityJson, cancellationToken);
}));
// Process joint acceleration
tasks.Add(Task.Run(async () => {
var jointAcceleration = jointDataArray.Skip(14).Take(7).Select(Convert.ToSingle).ToArray();
var jointAccelerationJson = JsonSerializer.Serialize(jointAcceleration);
await SendTelemetryAsync("JointAcceleration", jointAccelerationJson, cancellationToken);
}));
// Process external wrench
tasks.Add(Task.Run(async () => {
var externalWrench = jointDataArray.Skip(21).Take(6).Select(Convert.ToSingle).ToArray();
var externalWrenchJson = JsonSerializer.Serialize(externalWrench);
await SendTelemetryAsync("ExternalWrench", externalWrenchJson, cancellationToken);
}));
await Task.WhenAll(tasks);
}
sw.Stop();
_logger.LogDebug(String.Format("Elapsed={0}", sw.Elapsed));
}
Basically, the csv file has 10128 lines. I want to read the latest line which gets added to the csv file.
How do I do it?
Using File.ReadLine(filePath) throws this exception
> Unhandled exception. System.IO.PathTooLongException: The path
> '/home/adwait/azure-iot-sdk-csharp/iothub/device/samples/solutions/PnpDeviceSamples/Robot/-2.27625e-06,-0.78542,-3.79241e-06,-2.35622,5.66111e-06,3.14159,0.785408,0.00173646,-0.0015847,0.000962475,-0.00044469,-0.000247682,-0.000270337,0.000704195,0.000477503,0.000466693,-6.50664e-05,0.00112044,-2.47425e-06,0.000445592,-0.000685786,1.21642,-0.853085,-0.586162,-0.357496,-0.688677,0.230229' is too long, or a component of the specified path is too long.
[1]: https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=net-8.0
[2]: https://github.com/addy1997/azure-iot-sdk-csharp/blob/main/iothub/device/samples/solutions/PnpDeviceSamples/Robot/Data/Robots_data.csv |
In our project we are using asp.net and for database we have cosmos db and i was upserting the data into the database using an upsert API and i came to modifying data with the wrong data but i passed the right data .. can anyone resolve this ..
case UpsertDataEnumtype.SUBCATEGORY:
var jsonSubcategoryAsString = JsonSerializer.Serialize(upsertData);
var SubcategoryList = JsonSerializer.Deserialize<List<BbData<object>>>(jsonSubcategoryAsString);
thats how i am upserting for particular data using a enum value
so previously i was upserting all at a time but after modification we are doing for 1 at a time using switch case and the getting one is working fine but this one is having some issues |
error in upserting data in cosmos db.. results in modifying data in some other data |
|c#|asp.net|.net-core| |
null |
We can solve your problem with the help of a _calendar_ table. In this case, the calendar table can maintain one record with start and end dates for each year which you want to appear in the report.
STARDATE | ENDDATE
2024-01-01 | 2024-12-31
2025-01-01 | 2025-12-31
2026-01-01 | 2026-12-31
Here is the query you may use:
<!-- language: sql -->
SELECT YEAR(C.STARDATE) AS YEAR, A.ID, A.STARDATE, A.ENDDATE
FROM CALENDAR C
LEFT JOIN A
ON A.STARDATE <= C.ENDDATE AND A.ENDDATE >= C.STARDATE
INNER JOIN B
ON B.ID = A.ID
WHERE
A.ISACTIVE = 1 AND
B.CONTRACTID = 572786;
Note that depending on your database, it might not have a `YEAR()` function to extract the year from a date. The syntax might have to change in the first line of my query. |
I am using spring and springboot, and I have case with two tasks, which until now was triggered by ```@Scheduled``` with fixed delay. It is a must condition, that next task won't start if previous did not end. But now I got another requirement, tasks can only be triggered between specific hours and for the rest of the day it must not. I read documentation of ```@Scheduled``` but I do not see such an option. So my question is, if there is simple solution where:
- task will not start before the previous is not ended
- task will be triggered only between 15:00 and 18:00
or I have to do some code gimmick for it? |
Spring scheduled - can I join fixed delay with cron |
|spring|spring-boot|cron|scheduled-tasks|spring-scheduled| |
Why doesn't FutureBuilder execute a condition when the data is not ready yet? I.e. block else where '-------------' is not executed.
Before I used provider, that block would execute, i.e. it would show CircularProgressIndicator.
The provider value (ChangeNotifierProvider) is changed in the PaginationAppBar.
Future<List<ProfileData>> fetchProfiles(int page) {
WebService webService = locator<WebService>();
return webService.fetchProfiles(Gender.female, page); //future
}
@override
Widget build(BuildContext context) {
final pagerModel = context.watch<PagerModel>();
return FutureBuilder<List<ProfileData>>(
future: fetchProfiles(pagerModel.page),
builder: (context, snapshot) {
if (snapshot.hasData) {
final data = snapshot.data;
debugPrint('snapshot data length ${snapshot.data?.length}');
if (data!.isEmpty) {
return const ErrorWithMessage(message: 'data loading error');
}
return Scaffold(
appBar: const PaginationAppBar(Gender.female),
body: ProfileGrid(data),
);
} else if (snapshot.hasError) {
return _processError(snapshot);
} else {
debugPrint('-------------this else does not execute');
return const Scaffold(
appBar: PaginationAppBar(Gender.female),
body: CircularProgressIndicator(),
);
}
},
);
}
} |
null |
I have three lists
#### Example Data
```
data =list("A-B", "C-D", "E-F", "G-H", "I-J")
data_to_replace = list("A-B", "C-D")
replacement = list("B-A", "D-C")
```
This is just a minimal examples. I have several of this three-list and the number varies in each list
#### Expected outcome
data_new = list("B-A", "D-C", "E-F", "G-H", "I-J")
#### What i have tried
# function that reverses a string by words
reverse_words <- function(string)
{
# split string by blank spaces
string_split = strsplit(as.character(string), split = "-")
# how many split terms?
string_length = length(string_split[[1]])
# decide what to do
if (string_length == 1) {
# one word (do nothing)
reversed_string = string_split[[1]]
} else {
# more than one word (collapse them)
reversed_split = string_split[[1]][string_length:1]
reversed_string = paste(reversed_split, collapse = "-")
}
# output
return(reversed_string)
}
#Replacemnt
replacement = lapply(data_to_replace, reverse_words)
data_new = rapply(data, function(x) replace(x, x== data_to_replace, replacement )) #This last line did not work
#### Example Data
```
data =list("A-B", "C-D", "E-F", "G-H", "I-J")
data_to_replace = list("A-B", "C-D")
replacement = list("B-A"), "D-C")
```
This is just a minimal examples. I have several sets of these three lists, and the number of elements varies in each list.
#### Expected outcome
data_new = list("B-A", "D-C", "E-F", "G-H", "I-J")
#### What i have tried
# function that reverses a string by words
reverse_words <- function(string)
{
# split string by blank spaces
string_split = strsplit(as.character(string), split = "-")
# how many split terms?
string_length = length(string_split[[1]])
# decide what to do
if (string_length == 1) {
# one word (do nothing)
reversed_string = string_split[[1]]
} else {
# more than one word (collapse them)
reversed_split = string_split[[1]][string_length:1]
reversed_string = paste(reversed_split, collapse = "-")
}
# output
return(reversed_string)
}
#Replacemnt
replacement = lapply(data_to_replace, reverse_words)
data_new = rapply(data, function(x) replace(x, x== data_to_replace, replacement )) #This last line did not work
|
My Firebase save each user with 4 features:name,email,password and confirm password.
The class of users:
[enter image description here](https://i.stack.imgur.com/pF3M1.png)
The Firebase data that i saved:
[enter image description here](https://i.stack.imgur.com/TPCFf.png)
In my app i have an option to change the current password to new password,its require to put you previous password(the current that the Firebase saved) and then put new password(the user put the data about the passwords on UI 'EditText') .
See here how it looks:
[enter image description here](https://i.stack.imgur.com/xvLcQ.png)
And then the user has to click on 'confirm button' to change the old password to new.But before its change,***the computer need to check if the old password compare to the current password that saved on Firebase*** .I don't know how to do that,please help me!!
I tried to do that code but not sure if i get the access for the variable the i want.
[enter image description here](https://i.stack.imgur.com/gMWla.png)
It always changed even when the previous pass don't compare to the current..
code of database(for one user):
{
"user": {
"alon": {
"confirmPassword": "qwerty",
"email": "ttt@gmail.com",
"password": "qwerty",
"username": "alon"
}
}
}
|
You can use the following transformation specs :
```json
[
{ // set values of the object keys to their accountIds
// while taking out the value of request.body.inputAccountId
"operation": "shift",
"spec": {
"*": {
"request": {
"body": {
"inputAccountId": "inputId"
}
},
"*": {
"@": "@2,accountId.&"
}
}
}
},
{
"operation": "shift",
"spec": {
"inputId": {
"*": {
"@2,&": "[]" // traverse 2 levels to reach
// the value of "inputId" in order
// to match with the value of
// object keys
}
}
}
}
]
``` |
I have the following in the attachment
i tried to use the following macro to obtain the number of row of the first item when i filter this list to "Retail" only. the macro should show a message box with the number "3" according to the firt "retail" is in row 3, but ot keeps sending me the number "1"
```vb
Sub Macro1()
Range("A1").Select
SendKeys "{DOWN}"
FirstRow = ActiveCell.Row
MsgBox (FirstRow)
End Sub
```
the message box should say "3" |
If you enable warnings in your compiler, you'll see something like this:
```
warning: passing argument 1 of 'redim' from incompatible pointer type [-Wincompatible-pointer-types]
41 | if (lista->lungime == lista->capacitate) redim(&lista);
| ^~~~~~
| |
| Lista **
```
That's telling you something very important. What you have right now causes undefined behavior.
Changing the call to `redim(lista)` will fix that.
|
This is a common issue if you have to implement an interface that you can't change. Just remove the async keyword and call `Task.FromResult`. If the synchronous version was a `void`, you would return `Task.CompletedTask`.
You should also wrap the content of your method into a try/catch block. In the catch-block, you should return `Task.FromException`, otherwise you could get unexpected behaviour when you await the method.
public Task<Article> GetArticle(int articleId)
{
try
{
var article = _articles.Where(a => a.ArticleId == articleId).FirstOrDefault();
return Task.FromResult(article);
}
catch (Exception e)
{
return Task.FromException<Article>(e);
}
}
Example if method was void:
public Task DoSomething()
{
try
{
Console.WriteLine("I did something");
return Task.CompletedTask;
}
catch (Exception e)
{
return Task.FromException(e);
}
} |
You can see the extension method that will help you with this here: [RestRequestExtensions AddBody method][1]. If request.RequestFormat == DataFormat.Binary without a Content-Type then that method should work. If the obj parameter has the type byte[], it should do what you desire.
[1]: https://github.com/restsharp/RestSharp/blob/dev/src/RestSharp/Request/RestRequestExtensions.cs#L335 |
I need multiple device in an OR condition for the below query. As of now, only one device "FX16-Non-Coded-Sim3.LT2" is present. How can I add multiple devices (e.g. FX16-Non-Coded-Sim4.LT2, FX16-Non-Coded-Sim5.LT2) in this elastic search query where search will give result even if 1 device is present i.e OR condition for the list of devices present
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/idk6l.png |
Add multiple conditions in match query |
|python|elasticsearch| |
I'm currently upgrading a Laravel 5.4 project to Laravel 10, which involves transitioning from PHP 5.6 to PHP 8.3. The project uses tymon/jwt-auth for JWT authentication and zizaco/entrust for role-based authentication. However, I've encountered compatibility issues with zizaco/entrust in the updated Laravel version, affecting the authentication process.
I explained the steps I plan to take during the migration:
- Upgrade Laravel and PHP Versions: Transition to Laravel 10 and PHP
8.3, addressing syntax changes and compatibility issues. JWT Authentication: Continue using tymon/jwt-auth, configuring tokens
- with role_id and role_name. Role-based Authentication: Replace
zizaco/entrust due to incompatibility. Considering other solutions or
custom implementations involving role_id and role_name in JWT tokens.
- Middleware Updates: Modify middleware to support new role-based
authentication system.
Custom Middleware Example:
```
<?php
namespace App\Http\Middleware;
use Closure;
use Log;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Illuminate\Support\Facades\Response;
use Tymon\JWTAuth\Middleware\BaseMiddleware;
use DB;
class TokenEntrustAbility extends BaseMiddleware
{
public function handle($request, Closure $next, $roles, $permissions, $validateAll = false)
{
if (!$token = $this->auth->setRequest($request)->getToken()) {
return Response::json(array('code' => 201, 'message' => 'Required field token is missing or empty.', 'cause' => '', 'data' => json_decode("{}")));
}
try {
$user = $this->auth->authenticate($token);
//Log::info("Token", ["token :" => $token, "time" => date('H:m:s')]);
if (!$user) {
//Log::error('User not found1.', ['token' => $token,'status_code' =>$user]);
return Response::json(array('code' => 427, 'message' => 'Sorry, We are unable to find you. Please contact the support team.', 'cause' => '', 'data' => json_decode("{}")));
}
// else {
// //if ($user->id != 1) {
// //$is_exist = DB::table('user_session')->where('token', $token)->exists();
// $is_exist = DB::select('SELECT id
// FROM user_session
// WHERE token = ?', [$token]);
// //Log::info('exist session :',['token' => $is_exist]);
//
// if (!$is_exist) {
// //Log::info('session expired data', ['token'=>$token,'id' => $user->id]);
// return Response::json(array('code' => 400, 'message' => 'Your session is expired. Please login.', 'cause' => '', 'data' => json_decode("{}")));
// }
// //}
// }
} catch (TokenInvalidException $e) {
return Response::json(array('code' => 400, 'message' => 'Invalid token.', 'cause' => '', 'data' => json_decode('{}')));
} catch (TokenExpiredException $e) {
try {
$new_token = JWTAuth::refresh($token);
//Log::info("Refreshed Token", ["new_token :" => $new_token, "old_token :" => $token, "time" => date('H:m:s')]);
DB::beginTransaction();
DB::update('UPDATE user_session
SET token = ?
WHERE token = ?', [$new_token, $token]);
DB::commit();
} catch (TokenExpiredException $e) {
//Log::debug('TokenExpiredException Can not be Refresh', ['status_code' => $e->getStatusCode()]);
DB::beginTransaction();
DB::delete('DELETE FROM user_session WHERE token = ?', [$token]);
DB::commit();
return Response::json(array('code' => 400, 'message' => $e->getMessage(), 'cause' => '', 'data' => json_decode('{}')));
} catch (TokenBlacklistedException $e) {
//Log::error('The token has been blacklisted.', ['token' => $token,'status_code' => $e->getStatusCode()]);
DB::beginTransaction();
DB::delete('DELETE FROM user_session WHERE token = ?', [$token]);
DB::commit();
return Response::json(array('code' => 400, 'message' => $e->getMessage(), 'cause' => '', 'data' => json_decode("{}")));
} catch (JWTException $e) {
return Response::json(array('code' => 400, 'message' => $e->getMessage(), 'cause' => '', 'data' => json_decode("{}")));
}
return Response::json(array('code' => 401, 'message' => 'Token expired.', 'cause' => '', 'data' => ['new_token' => $new_token]));
} catch (JWTException $e) {
return Response::json(array('code' => 400, 'message' => $e->getMessage(), 'cause' => '', 'data' => json_decode("{}")));
}
if (!$user) {
//return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
//Log::error('User not found.', ['token' => $token,'status_code' =>$user]);
return Response::json(array('code' => 427, 'message' => 'Sorry, We are unable to find you. Please contact the support team.', 'cause' => '', 'data' => json_decode("{}")));
}
if (!$request->user()->ability(explode('|', $roles), explode('|', $permissions), array('validate_all' => $validateAll))) {
return Response::json(array('code' => 201, 'message' => 'Unauthorized user.', 'cause' => '', 'data' => json_decode("{}")));
//return $this->respond('tymon.jwt.invalid', 'token_invalid', 401, 'Unauthorized');
}
$this->events->fire('tymon.jwt.valid', $user);
return $next($request);
}
}
```
Replace:
`if (!$request->user()->ability(explode('|', $roles), explode('|', $permissions), array('validate_all' => $validateAll))) {
return Response::json(array('code' => 201, 'message' => 'Unauthorised user.', 'cause' => '', 'data' => json_decode("{}")));
}
`
With:
`if (!in_array($request->user()->role_id, explode('|', $roles))) {
return Response::json(array('code' => 201, 'message' => 'Unauthorised user.', 'cause' => '', 'data' => json_decode("{}")));
}
`
and for my route.php file i a using my middelware like this
```
Route::group(['prefix' => '', 'middleware' => ['ability:admin|crm,admin_permission|crm_permission']], function () {
//all transaction api
Route::post('getAllTransactionsForAdmin', 'AdminController@getAllTransactionsForAdmin');
Route::post('searchTransaction', 'AdminController@searchTransaction');
Route::post('verifyTransaction', 'AdminController@verifyTransaction');
// //user api
Route::post('getAllUsersByAdmin', 'AdminController@getAllUsersByAdmin');
Route::post('searchUserForAdmin', 'AdminController@searchUserForAdmin');
Route::post('changeUserRole', 'AdminController@changeUserRole');
Route::post('getUserSessionInfo', 'AdminController@getUserSessionInfo');
Route::post('doUserAllSessionLogout', 'LoginController@doUserAllSessionLogout');
//User Design
Route::post('getDesignFolderForAdmin', 'AdminController@getDesignFolderForAdmin');
Route::post('getVideoDesignFolderForAdmin','AdminController@getVideoDesignFolderForAdmin');
Route::post('getIntroDesignFolderForAdmin','AdminController@getIntroDesignFolderForAdmin');
Route::post('getDesignByFolderIdForAdmin', 'AdminController@getDesignByFolderIdForAdmin');
});
```
here i am creating a group and assign roles and permission that require to access this route.
I'm looking for insights or advice on the migration process, particularly regarding authentication and security. Has anyone faced similar challenges, and how did you address them? |
Migrate Laravel project from old version to new with JWT and Role-Based Authentication |
|php|laravel|amazon-web-services|jwt|roles| |
null |
I am trying to rewrite a URL in WordPress.
The structure is `/car/123/bmw-series-A` where pagename is `car`, carID is `123` and modelName is `bmw-series-A`.
There is a custom template where I will be getting the carID and modelName.
I have the following code:
functions.php
function add_rewrite_rules($aRules) {
$aNewRules = array('car/([^/]+)/?$' => 'index.php?pagename=car&carID=$matches[1]');
$aRules = $aNewRules + $aRules;
return $aRules;
}
// hook add_rewrite_rules function into rewrite_rules_array
add_filter('rewrite_rules_array', 'add_rewrite_rules');
function prefix_register_query_var( $vars ) {
$vars[] = 'carID';
$vars[] = 'modelName';
return $vars;
}
add_filter( 'query_vars', 'prefix_register_query_var' );
I get the carID in the custom template but not the modelName when I try adding modelName it goes to the 404 page.
Code:
$aNewRules = array('car/([^/]+)/([^/]+)/?$' => 'index.php?pagename=car&carID=$matches[1]&modelName=$matches[2]');
|
URL rewriting in WordPress not using htaccess |
## Description:
The issue you are facing is very easy to solve it just needs a little focus.
So you see after every label you are creating a new variable and storing the value of the entry init.
The issue is that, that variable is storing the value before the button is pressed or in other words as soon as you click the `Create New Student Record` button its storing the value init, since the entry is empty when you open the frame its returning none.
## Solution:
In order to get the values after the user has entered the text use the `.get()` function when the button is pressed after the user is done entering his\her data in the entries. You can use the following fixed code:
```
import sys
import tkinter
import customtkinter as ctk
import self
from tkcalendar import *
from datetime import date, datetime
from Student import *
# Theme set-up
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("dark-blue")
# GUI set-up
mainMenu = ctk.CTk()
mainMenu.title("GUI Application")
mainMenu.geometry("800x500")
# Frame set-up
mainMenuFrame = ctk.CTkFrame(master=mainMenu)
mainMenuFrame.pack(pady=20, padx=60, fill="both", expand=True)
ageSelection = tkinter.StringVar()
#Functions
def exitProgram():
sys.exit()
def getAge(today, dob, student):
print(today)
print(dob)
dob_result = str(dob)
dob_data = dob_result.split("-")
year = int(dob_data[0])
month = int(dob_data[1])
day = int(dob_data[2])
print(year)
print(month)
print(day)
age = (today - date(year, month, day)).days
age = age / 365
print(age)
age = round(age)
ageSelection = round(age)
print(round(age))
def createStudentRecord(firstName, lastName, dob, schoolName, schoolId, addressLine, city, zip, language):
s1 = Student(firstName, lastName,dob,schoolName,schoolId,addressLine, city, zip, language)
print(firstName)
print(lastName)
print(dob)
print(schoolId)
print(addressLine)
print(city)
print(zip)
print(language)
def loadStudentInfoView():
# Remove main menu frame
mainMenuFrame.pack_forget()
studentInfoFrame = ctk.CTkFrame(master=mainMenu)
studentInfoFrame.grid(row=0, column=0)
# Student Info set-up
#First & Last Name
firstNameLabel = ctk.CTkLabel(master=studentInfoFrame, text="First Name", font=('Calibri',20))
firstNameLabel.grid(row=0, column=0)
firstNameText = ctk.CTkEntry(master=studentInfoFrame, height=30, width=150)
firstNameText.grid(row=1, column=0, padx=20)
lastNameLabel = ctk.CTkLabel(master=studentInfoFrame, text="Last Name", font=('Calibri', 20))
lastNameLabel.grid(row=0, column=1)
lastNameText = ctk.CTkEntry(master=studentInfoFrame, height=30, width=150)
lastNameText.grid(row=1, column=1, padx=20)
# Birth date (Calendar), automatically calculate age
#DOB drop down
dobLabel = ctk.CTkLabel(master=studentInfoFrame, text="DOB", font=('Calibri', 20))
dobLabel.grid(row=0, column=2)
calPicker = DateEntry(studentInfoFrame, selectmode="day", year=2014, month=2, day=7, date_pattern="yyyy-mm-dd")
calPicker.grid(row=1, column=2)
#School Details
schoolNameLabel = ctk.CTkLabel(master=studentInfoFrame, text="School Name", font=('Calibri', 20))
schoolNameLabel.grid(row=2, column=0)
schoolNameText = ctk.CTkEntry(master=studentInfoFrame, height=30, width=150)
schoolNameText.grid(row=3, column=0, padx=20)
#School ID
schoolIdLabel = ctk.CTkLabel(master=studentInfoFrame, text="School ID", font=('Calibri', 20))
schoolIdLabel.grid(row=2, column=1)
schoolIdText = ctk.CTkEntry(master=studentInfoFrame, height=30, width=70)
schoolIdText.grid(row=3, column=1, padx=20)
#Address Line 1 & 2, City, State, Zip
addressLineLabel = ctk.CTkLabel(master=studentInfoFrame, text="Address Line", font=('Calibri', 20))
addressLineLabel.grid(row=5, column=0)
addressLineText = ctk.CTkEntry(master=studentInfoFrame, height=30, width=300)
addressLineText.grid(row=6, column=0, padx=20)
cityLabel = ctk.CTkLabel(master=studentInfoFrame, text="City", font=('Calibri', 20))
cityLabel.grid(row=5, column=1)
cityText = ctk.CTkEntry(master=studentInfoFrame, height=30, width=120)
cityText.grid(row=6, column=1, padx=20)
stateLabel = ctk.CTkLabel(master=studentInfoFrame, text="State (dropdown)", font=('Calibri', 20))
stateLabel.grid(row=5, column=2)
stateText = ctk.CTkEntry(master=studentInfoFrame, height=30, width=50)
stateText.grid(row=6, column=2, padx=20)
zipLabel = ctk.CTkLabel(master=studentInfoFrame, text="Zip Code", font=('Calibri', 20))
zipLabel.grid(row=5, column=3)
zipText = ctk.CTkEntry(master=studentInfoFrame, height=30, width=50)
zipText.grid(row=6, column=3, padx=20)
#Language
# Create Record Button
createRecordButton = ctk.CTkButton(master=studentInfoFrame, text="Create Student Record", command=lambda : createStudentRecord(firstNameText.get(), lastNameText.get(), calPicker.get_date(), schoolNameText.get(),
schoolIdText.get(), addressLineText.get(), cityText.get(), zipText.get(), language=None))
createRecordButton.grid(row=8, column=1, pady=80)
# Main Menu Layout
# Title Label
title = ctk.CTkLabel(master = mainMenuFrame, text="LSSP Helper", font=('Arial', 32))
title.pack(pady=12, padx=10)
# Text Label
title2 = ctk.CTkLabel(master = mainMenuFrame, text="Can you")
title2.pack(pady=12, padx=10)
# Text Label
title3 = ctk.CTkLabel(master = mainMenuFrame, text="please")
title3.pack(pady=12, padx=10)
# Text Label
title4 = ctk.CTkLabel(master = mainMenuFrame, text="HELLLLLLLLLLLLLLLLLLLLLLLLLLLLLP!?!?!?!?!")
title4.pack(pady=12, padx=10)
# Button 1
button1 = ctk.CTkButton(master = mainMenuFrame, text="Create New Student Record", command=loadStudentInfoView)
button1.pack(pady=12, padx=10)
# Button 2
button2 = ctk.CTkButton(master = mainMenuFrame, text="Resume Student Record")
button2.pack(pady=12, padx=10)
# Button 3
button3 = ctk.CTkButton(master = mainMenuFrame, text="Observation Form")
button3.pack(pady=12, padx=10)
# Exit Button
exitButton = ctk.CTkButton(master = mainMenuFrame, text="Exit", command=exitProgram)
exitButton.pack(pady=12, padx=10)
mainMenu.mainloop()
```
|
The thing is that I need to create a table and export it as a photo. There are some elements that I need them to be aligned to the right, but I want them to have some margin with respect to the end of the cell. What I did is to convert these numbers to a string, and then I added a blank space at the end (representing the margin)
[covert number to string](https://i.stack.imgur.com/x62LV.png)
After I add the margin, I put it in the excel file:
[Append](https://i.stack.imgur.com/2SLCU.png)
However, when I do this, and I export the file, I get the corner marked by the control Green Error Checking Markers of Excel, because it detects that the values are numbers, and thus, the exported image has the markers too:
[Error marks](https://i.stack.imgur.com/D40yk.png)
My question is if there is any other way to leave a margin, or if there is a way to ignore these errors via openpyxl. Thanks |
is there any way to leave margin in excel cells when aligning to one side or the other with Openpyxl? |
|python|openpyxl| |
Control `TMonthCalendar` is just a wrapper for Windows [Month Calendar Control](https://learn.microsoft.com/en-us/windows/win32/controls/month-calendar-control-reference).
While it is possible to translate most of its elements using *Localizer* tool some of them still remain in the default Windows UI language. In order to change this you will have to change the current thread UI language by calling [SetThreadUILanguage](https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-setthreaduilanguage) API function.
You can read more on this in [Delphi 7 application not loading STRINGTABLE resources on Windows 10](https://stackoverflow.com/q/78181647/3636228)
PS: You need to change Thread UI Language before `TMonthCalendar` is created otherwise this will not work. |
I'm trying to get a list of rows in a table as IWebelEments to parse their contents for testing purposes
I'm trying using the following piece of code (the variable has been declared globally for the class as public IList IWebElement Rows):
```
public class SearchResults : Widget
{
public IList<IWebElement> rows;
public SearchResults(IWebDriver driver) : base(driver)
{
rows = driver.FindElements(By.XPath("//table[@id='tblResults']//tr"));
```
The strange thing is that when testing it on selectorshub this Xpath returns the correct value:
[](https://i.stack.imgur.com/4SvIh.jpg)
But when debugging the way it's behaving it appears to be gathering 11 instances of the first row in the IList. Which is strange, since it shows that it's adding the correct number of members to the list, but for some reasons it only gets eleven instances of the first row in the table body.
[![TC debuggin][1]][1]
I have tried multiple versions of the Xpath. Making the variable local instead of global, and testing it live con the browser and with selectorshub. I wasn't able to get anything close to the wanted result.
[1]: https://i.stack.imgur.com/SrCCV.jpg
UPDATE: I have also tried making single element Xpaths using an iterator to build an Xpath for each row and i'm still finding the same problem, for some reason each of these Xpaths catch the same element on the script while on the browser they catch the proper elements:
```
//table[@id='tblResults']//tbody//tr[1]
//table[@id='tblResults']//tbody//tr[2]
//table[@id='tblResults']//tbody//tr[3]
//table[@id='tblResults']//tbody//tr[4]
//table[@id='tblResults']//tbody//tr[5]
```
and so on... |
I have three lists
#### Example Data
```
data =list("A-B", "C-D", "E-F", "G-H", "I-J")
data_to_replace = list("A-B", "C-D")
replacement = list("B-A"), "D-C")
Note: The length(data_to_replace) and length(replacement ) are always equal. Which may range from 1 to 200
```
This is just a minimal example. I have several of these three, and the number varies on each list
#### Expected outcome
data_new = list("B-A", "D-C", "E-F", "G-H", "I-J")
#### What i have tried
# function that reverses a string by words
reverse_words <- function(string)
{
# split string by blank spaces
string_split = strsplit(as.character(string), split = "-")
# How many split terms?
string_length = length(string_split[[1]])
# decide what to do
if (string_length == 1) {
# one word (do nothing)
reversed_string = string_split[[1]]
} else {
# more than one word (collapse them)
reversed_split = string_split[[1]][string_length:1]
reversed_string = paste(reversed_split, collapse = "-")
}
# output
return(reversed_string)
}
#Replacemnt
replacement = lapply(data_to_replace, reverse_words)
data_new = rapply(data, function(x) replace(x, x== data_to_replace, replacement )) #This last line did not work |
I am creating a MLM (multi level marketing) system in PHP and MYSQL database. I want to fetch child user id based on parent id. I have found a solution
https://stackoverflow.com/questions/45444391/how-to-count-members-in-15-level-deep-for-each-level-in-php
but getting errors-
I have created a class -
```
<?php Class Team extends Database {
private $dbConnection;
function __construct($db)
{
$this->dbConnection = $db;
}
public function getDownline($id, $depth=5) {
$stack = array($id);
for($i=1; $i<=$depth; $i++) {
// create an array of levels, each holding an array of child ids for that level
$stack[$i] = $this->getChildren($stack[$i-1]);
}
return $stack;
}
public function countLevel($level) {
// expects an array of child ids
settype($level, 'array');
return sizeof($level);
}
private function getChildren($parent_ids = array()) {
$result = array();
$placeholders = str_repeat('?,', count($parent_ids) - 1). '?';
$sql="select id from users where pid in ($placeholders)";
$stmt=$this->dbConnection->prepare($sql);
$stmt->execute(array($parent_ids));
while($row=$stmt->fetch()) {
$results[] = $row->id;
}
return $results;
}
}
```
Ans using class like that -
```
$depth = 2; // get the counts of his downline, only 2 deep.
$downline_array = $getTeam->getDownline($id, $depth=2);
```
I am getting errors -
Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, int given in
and second
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in
I want to fetch child user id in 5 levels
|
How to get 5 level child users for MLM system? |
|php|mysql|oop| |
null |
I am trying to open a connection to a mySQL Database hosted through IONOS. Using the database aside, at the moment I can't even get a connection going with the error
MySql.Data.MySqlClient.MySqlException: "Unable to connect to any of the specified MySQL hosts."
Currently I'm trying to established the connection through the Oracle MySql Nuget package.
```
using MySql.Data.MySqlClient;
etc.etc.
string server = "db5012345659.hosting-data.io";
string database = "dbs12345640";
string uid = "dbu5000002";
string password = "abc";
string connectionString = $"Server={server}; database={database}; UID={uid}; password={password};";
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
```
I have also tried using Microsofts SqlClient via
```
SqlConnectionStringBuilder test = new SqlConnectionStringBuilder()
{
DataSource = "db5012345659.hosting-data.io",
InitialCatalog = "dbs12345640",
UserID = "dbu5000002",
Password = "abc",
};
SqlConnection awd = new SqlConnection(test.ConnectionString);
awd.Open();
```
which also gives the error that it cannot establish a connection. I also opened port 3306 in the Firewall but that didn't change anything.
I was able to connect to the database and read/write values with a separate php script, so it seems to be accessible. I just need to do it in this C# application.
|
If the element(s) in the first list equal element(s) of the second list, replace with element(s) of the third list |
I'm brand new to JavaScript, so bear with me!
I have a webpage that has a scrollable div element.
I've been trying to find a solution that adds the following functionality:
A user scrolls down the page. Once the scrollable div element reaches the center of the viewport, scrolling input is switched from the page to the div - freezing the page scroll with the div vertically centered.
Once the div element reaches the end of its scrollable content, scroll input is returned to the overall page and the user can scroll past the div element.
Ideally, this mechanic would work when page scrolling down to or up to the scrollable div element.
I've been pulling my hair out trying to get this to work! |
you can use cv2.imdecode() to decode the image.this will help you.
image_path = "FAX注文0004.tif"
with open(image_path, 'rb') as f:
image_bytes = f.read()
image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
ok, heres whats wrong with your code
1. after assigning the `srcObject` of a `video` element you have to call play
2. in the `setInterval` function when you assign the values of `h` and `w` you also set the `width` and `height` of the `canvas`, doing this clears the canvas
notes:
you could do with some clarification that after invoking `face(4)` the `then` function is actually part of the `getUserMedia`, it confused me for a while
its probably the most elaborate way perform a `Math.floor` I have ever seen
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
'use strict';
var timer;
var stream;
document.querySelector('input[value=stop]').onclick = e=>{
clearInterval(timer);
if(stream)stream.getTracks().forEach(track=>track.stop());
}
try {
const w = window,
d = document,
ng = navigator,
id = e => {
return d.getElementById(e)
},
cn = id('lh'),
i = id('i'),
o = id('o'),
cx = cn.getContext('2d', {
willReadFrequently: true
}),
face = r => ng.mediaDevices.getUserMedia({
video: {width:100,height:100}
}).then(s => {
stream=s;
i.srcObject = s;
i.play();
i.onloadedmetadata = e => {
timer=setInterval(() => {
let c = 0,
k = -4,
h = cn.height = i.videoHeight,
w = cn.width = i.videoWidth;
cx.drawImage(i, 0, 0, w, h);
let dt = cx.getImageData(0, 0, w, h),
io = dt.data,
dl = io.length,
R, G, B;
R = G = B = 0;
o.src = cn.toDataURL('image/webp');
while ((k += r*4) < dl) {
++c;
R += io[k];
G += io[k + 1];
B += io[k + 2]
};
['R', 'G', 'B'].forEach(e1 => {
eval(e1 + '=' + `~~(${e1}/c)`)
});
let rgb = `rgb(${R},${G},${B})`;
d.body.style.background = rgb
}, -1)
}
});
face(4)
} catch (e) {
alert(e)
}
<!-- language: lang-css -->
canvas {
border:1px solid lightgray;
}
video {
border:1px solid lightgray;
}
img {
border:1px solid lightgray;
}
input {
font-size:16px;
padding:5px;
}
<!-- language: lang-html -->
<canvas id=lh></canvas>
<video id=i></video>
<img id=o>
<input type=button value=stop>
<!-- end snippet -->
i added a stop feature so it can be turned off without reloading the page
im afraid that it wont actually run in the stackoverflow website, i think they must have webcam access turned off and wont allow video to play
ive created a much neater version for anyone who visits this page at a later date, it needs a canvas element and its derived 2d context
var stream = await navigator.mediaDevices.getUserMedia({video:true});
var video = document.createElement('video');
video.srcObject = stream;
video.play();
(function update(){
ctx.drawImage(video,0,0,canvas.width,canvas.height);
var img = ctx.getImageData(0,0,canvas.width,canvas.height);
var n = img.data.length;
var r = 0;
var g = 0;
var b = 0;
for(var i=0;i<n;i+=4){
r += img.data[i]/n*4;
g += img.data[i+1]/n*4;
b += img.data[i+2]/n*4;
}//for
document.body.style.background = `rgb(${r},${g},${b})`;
if(abort)return;
requestAnimationFrame(update);
})();
i thought this was a nice little project so ive added a working example, i dont think a lot of these sites that allow code generation allow video, anyway heres what all the fuss is about
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var ctx = canvas.getContext('2d');
var balls = ballsmod(10);
var abort = false;
var framerate = 20;
quit.onclick = e=>abort = true;
(function update(){
ctx.clearRect(0,0,canvas.width,canvas.height);
balls();
var data = ctx.getImageData(0,0,canvas.width,canvas.height);
var n = data.data.length;
var r = 0;
var g = 0;
var b = 0;
var s = 4;
for(var i=0;i<n;i+=4*s){
r += data.data[i]/n*4*s;
g += data.data[i+1]/n*4*s;
b += data.data[i+2]/n*4*s;
}//for
document.body.style.background = `rgb(${r},${g},${b})`;
if(abort)return;
setTimeout(update,1000/framerate);
})();
function ballsmod(num){
var cols = ['blue','green','red','yellow','lightblue','lightgray'];
var balls = [];
for(var i=0;i<num;i++)balls.push(ball());
function update(){
balls.forEach(update_ball);
}//update
function rnd(size,offset){return Math.random()*size+(offset||0)}
function ball(){
var col = cols[parseInt(rnd(cols.length))]
var r = rnd(20,20);
var x = rnd(canvas.width-2*r,r);
var y = rnd(canvas.height-2*r,+r);
var dx = rnd(20,-10);
var dy = rnd(20,-10);
var ball = {x,y,r,col,dx,dy,update};
return ball;
}//ball
function update_ball(ball){
ball.x += ball.dx;
ball.y += ball.dy;
if(ball.x-ball.r<0 || ball.x+ball.r>canvas.width){
ball.dx *= -1;
ball.x += ball.dx;
}
if(ball.y-ball.r<0 || ball.y+ball.r>canvas.height){
ball.dy *= -1
ball.y += ball.dy;
}
ctx.beginPath();
ctx.arc(ball.x,ball.y,ball.r,0,2*Math.PI,false);
ctx.fillStyle = ball.col;
ctx.fill();
}//update
return update;
}//ballsmod
<!-- language: lang-css -->
body {
text-align:center;
}
canvas {
border:1px solid lightgray;
}
input {
font-size:16px;
padding:7px;
margin-left:10px;
vertical-align:top;
}
<!-- language: lang-html -->
<input id=quit type=button value=stop>
<canvas id=canvas></canvas>
<!-- end snippet -->
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT
[2]: https://stackoverflow.com/questions/22003491/animating-canvas-to-look-like-tv-noise
|
Check the way your `pages` folder is composed. Managed to fix this by moving out the component from `pages` to `components` and that's it. This helped me a lot - https://nextjs.org/docs/messages/prerender-error |
I've seen some posts about how to dynamically add test fields to a form when a button is clicked. like in this post https://stackoverflow.com/questions/58514788/adding-another-input-field-when-clicking-on-a-button
But, how can I achieve this using nuxt2 and vue2. I use a vuex store for the input data, but how can I identify the new text fields being added so I can update the store accordingly?
Ideally I'd have a v-row with 2 v-cols and when I click the button, another row appears with the 2 v-cols, but Im not understanding where I would put the v-for in this scenario. Small snippet based on the above linked question.
```
<template>
<v-card>
<v-card-text>
<v-row>
<v-col>
<v-text-field
:label="textField.label1"
v-model="textField.value1"
></v-text-field> Im not understanding where I would put the v-for in this scenario.
<v-text-field
:label="textField.label2"
v-model="textField.value2"
></v-text-field>
</v-col>
<v-col>
<v-btn @click="addRow">Add Row</v-btn>
</v-col>
</v-row>
</v-card-text>
</v-card>
</template>
```
|
How to dynamically add two v-text-fields to a form when a button is clicked and uniquely identify them |
|forms|vuejs2|nuxt.js| |
null |
When I run simulation the mouse (the simulate I use it make by Mackorone) did mark the wall I sure about that but after every loop the maze still not update. First I think the mouse not update the wall after mark it but when I log out it did mark wall. Then I check did the flood fill work so every loop flood fill didn't update wall so the mouse keep spinning around after few wall past. But when I mark wall by hand it works fine.
I want ever loop algorithm update the maze. Here is my source code and simulation:(https://github.com/mackorone/mms)
(https://github.com/kinhkong69z/KhoeMach-Micromouse)
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include "API.h"
std::pair<int, int> west_wall[1000];
std::pair<int, int> east_wall[1000];
std::pair<int, int> north_wall[1000];
std::pair<int, int> south_wall[1000];
int w = 0, e = 0, n = 0, s = 0;
std::string direct_mouse[5];
std::string wall_l, wall_r, wall_f;
void log(const std::string& text) {
std::cerr << text << std::endl;
}
void mark_wall(int mx, int my, std::string &direct){
if(direct == "w"){
west_wall[w].first = mx;
west_wall[w].second = my;
w++;
}
else if(direct == "e"){
east_wall[e].first = mx;
east_wall[e].second = my;
e++;
}
else if(direct == "n"){
north_wall[n].first = mx;
north_wall[n].second = my;
n++;
}
else if(direct == "s"){
south_wall[s].first = mx;
south_wall[s].second = my;
s++;
}
}
bool check_wall(int mx, int my, std::string direct){
int k = 0;
if(direct == "w"){
for(int i = 0; i < w; i++)
if(west_wall[i].first == mx && west_wall[i].second == my)
k++;
}
else if(direct == "e"){
for(int i = 0; i < e; i++)
if(east_wall[i].first == mx && east_wall[i].second == my){
k++;
}
}
else if(direct == "n"){
for(int i = 0; i < n; i++)
if(north_wall[i].first == mx && north_wall[i].second == my)
k++;
}
else if(direct == "s"){
for(int i = 0; i < s; i++)
if(south_wall[i].first == mx && south_wall[i].second == my)
k++;
}
if(k == 0)
return false;
else
return true;
}
void mouse_way(int d){
direct_mouse[1] = "n";
direct_mouse[2] = "e";
direct_mouse[3] = "s";
direct_mouse[4] = "w";
if(d == 1)
{
wall_f = "n";
wall_l = "w";
wall_r = "e";
}
else if(d == 2){
wall_f = "e";
wall_l = "n";
wall_r = "s";
}
else if(d == 3){
wall_f = "s";
wall_l = "e";
wall_r = "w";
}
else if(d == 4){
wall_f = "w";
wall_l = "s";
wall_r = "n";
}
}
void bfs(std::vector<std::vector<int>>& maze, int mx, int my){
std::queue<std::pair<int, int>> q;
//base case
if(!check_wall(mx - 1, my, "s")){
maze[mx - 1][my] = 1;q.push({mx - 1, my});
}
if(!check_wall(mx - 1, my + 1, "s")){
maze[mx - 1][my + 1] = 1;q.push({mx - 1, my + 1});
}
if(!check_wall(mx, my + 2, "w")){
maze[mx][my + 2] = 1;q.push({mx, my + 2});
}
if(!check_wall(mx + 1, my + 2, "w")){
maze[mx + 1][my + 2] = 1;q.push({mx + 1, my + 2});
}
if(!check_wall(mx + 2, my + 1, "n")){
maze[mx + 2][my + 1] = 1;q.push({mx + 2, my + 1});
}
if(!check_wall(mx + 2, my, "n")){
maze[mx + 2][my] = 1;q.push({mx + 2, my});
}
if(!check_wall(mx + 1, my - 1, "e")){
maze[mx + 1][my - 1] = 1;q.push({mx + 1, my - 1});
}
if(!check_wall(mx, my - 1, "e")){
maze[mx][my - 1] = 1; q.push({mx, my - 1});
}
while(!q.empty()){
int nx, ny;
nx = q.front().first;
ny = q.front().second;
q.pop();
if(!check_wall(nx + 1, ny, "n") && nx + 1 < 17 && maze[nx + 1][ny] == 0){ // down
q.push({nx + 1, ny});
maze[nx + 1][ny] = maze[nx][ny] + 1;
}
if(!check_wall(nx, ny - 1, "e") && ny - 1 >= 1 && maze[nx][ny - 1] == 0){ // left
q.push({nx, ny - 1});
maze[nx][ny - 1] = maze[nx][ny] + 1;
}
if(nx - 1 >= 1 && maze[nx - 1][ny] == 0 && !check_wall(nx - 1, ny, "s")){ // up
q.push({nx - 1, ny});
maze[nx - 1][ny] = maze[nx][ny] + 1;
}
if(ny + 1 < 17 && maze[nx][ny + 1] == 0 && !check_wall(nx, ny + 1, "w")){ // right
q.push({nx, ny + 1});
maze[nx][ny + 1] = maze[nx][ny] + 1;
}
}
maze[mx][my] = maze[mx + 1][my] = maze[mx + 1][my + 1] = maze[mx][my + 1] = 0;
}
int main(int argc, char* argv[]) {
log("Running...");
API::setColor(0, 0, 'G');
API::setText(0, 0, "Start");
int d = 1;
int mx = 16, my = 1;
std::vector<std::vector<int>> maze(18,std::vector<int>(18, 0));
while (true) {
char str[1000];
sprintf(str, "%d", mx);
log(str);
if(d < 1)
d = 3;
if(d > 4)
d = 1;
mouse_way(d);
if(API::wallFront()) mark_wall(mx, my, wall_f);
if(API::wallLeft()) mark_wall(mx, my, wall_l);
if(API::wallRight()) mark_wall(mx, my, wall_r);
bfs(maze, 8, 8);
if(direct_mouse[d] == "n"){
if(maze[mx][my + 1] <= maze[mx][my] && !check_wall(mx, my, "e") && my + 1 < 17){
my += 1;
API::turnRight();
API::moveForward();
d++;
}
else if(maze[mx][my - 1] <= maze[mx][my] && !check_wall(mx, my, "w") && my - 1 >= 1){
my -= 1;
API::turnLeft();
API::moveForward();
d--;
}
else if(maze[mx - 1][my] <= maze[mx][my] && !check_wall(mx, my, "n") && mx - 1 >= 1){
mx -= 1;
API:: moveForward();
}
else {
API::turnLeft();
API::turnLeft();
d -= 2;
}
}
else if(direct_mouse[d] == "e"){
if(maze[mx + 1][my] <= maze[mx][my] && !check_wall(mx, my, "s") && mx + 1 < 17){
mx += 1;
API::turnRight();
API::moveForward();
d++;
}
else if(maze[mx - 1][my] <= maze[mx][my] && !check_wall(mx, my, "n") && mx - 1 >= 1){
mx -= 1;
API::turnLeft();
API::moveForward();
d--;
}
else if(maze[mx][my + 1] <= maze[mx][my] && !check_wall(mx, my, "e") && my + 1 < 17){
my += 1;
API::moveForward();
}
else{
API::turnLeft();
API::turnLeft();
d -= 2;
}
}
else if(direct_mouse[d] == "s"){
if(maze[mx][my - 1] <= maze[mx][my] && !check_wall(mx, my, "w") && my - 1 >= 1){
my -= 1;
API::turnRight();
API::moveForward();
d++;
}
else if(maze[mx][my + 1] <= maze[mx][my] && !check_wall(mx, my, "e") && my + 1 < 17){
my += 1;
API::turnLeft();
API::moveForward();
d--;
}
else if(maze[mx + 1][my] <= maze[mx][my] && !check_wall(mx, my, "s") && mx + 1 < 17){
mx += 1;
API::moveForward();
}
else{
API::turnLeft();
API::turnLeft();
d -= 2;
}
}
else if(direct_mouse[d] == "w"){
if(maze[mx - 1][my] <= maze[mx][my] && !check_wall(mx, my, "n") && mx - 1 >= 1){
mx -= 1;
API::turnRight();
API::moveForward();
d++;
}
else if(maze[mx + 1][my] <= maze[mx][my] && !check_wall(mx, my, "s") && mx + 1 < 17){
mx += 1;
API::turnLeft();
API::moveForward();
d--;
}
else if(maze[mx][my - 1] <= maze[mx][my] && !check_wall(mx, my, "w") && my - 1 >= 1){
my -= 1;
API::moveForward();
}
else{
API::turnLeft();
API::turnLeft();
d -= 2;
}
}
/* for (const auto& row : maze) {
std::string st = "";
for (int cell : row) {
sprintf(str, "%d", cell);
st = st + str + " ";
}
log(st);
} */
bfs(maze, 8, 8);
for(int i = 0; i < e; i++){
std::string st;
sprintf(str, "%d", north_wall[i].first);
st = st + str;
sprintf(str, "%d", north_wall[i].second);
st = st + " " + str;
log(st);
}
log(".......");
}
} |
I want to compute this integral:
[![enter image description here][1]][1]
I have a data file providing values of cos(theta), phi and g.
I am trying to solve it using the trapezoid method of `scipy.integrate`. But I am unsure if this is the correct way since it is a double integration and g depends on both cos_theta and phi.
The code is as follows :
```
nvz = 256
nph = 256
dOmega = (2.0/nvz) * (2*np.pi / nph)
dphi = (2*np.pi / nph)
dtheta = (2.0/nvz)
cos_theta = file[:,0]
sin_theta = np.sqrt(1-cos_theta**2)
phi = file[:,1]
cos_phi = np.cos(phi)
sin_phi = np.sin(phi)
g = file[:,2]
integrate.trapezoid(sin_theta*cos_phi*g, dx = dOmega)
````
Can someone please suggest me a way to solve it correctly?
[1]: https://i.stack.imgur.com/X5mlI.png |
I passed the dynamic container name to function.json as **%CONTAINERNAME%/{name}** and successfully executed the blob trigger function.
**Code :**
```python
import os
import logging
import azure.functions as func
CONTAINERNAME = os.environ.get("CONTAINERNAME")
def main(blob: func.InputStream):
logging.info(f"Python blob trigger function processed blob \n"
f"Name:{blob.name}\n"
f"Blob Size: {blob.length} bytes")
```
***function.json :***
```json
{
"scriptFile": "__init__.py",
"bindings": [
{
"name": "blob",
"type": "blobTrigger",
"direction": "in",
"path": "%CONTAINERNAME%/{name}",
"connection": "kamblobfuncstr_STORAGE"
}
]
}
```
***local.settings.json :***
```json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "<storage_connec_string>",
"FUNCTIONS_WORKER_RUNTIME": "python",
"kamblobfuncstr_STORAGE": "<storage_connec_string>",
"CONTAINERNAME": "<containe_name>"
}
}
```
**Output :**
The following blob trigger function code successfully triggered the blob as shown below:
```python
* Executing task: .venv\Scripts\activate && func host start
Found Python version 3.10.11 (py).
Azure Functions Core Tools
Core Tools Version: 4.0.5030 Commit hash: N/A (64-bit)
Function Runtime Version: 4.15.2.20177
Functions:
BlobTrigger1: blobTrigger
For detailed output, run func with --verbose flag.
[2024-03-13T06:49:09.828Z] Worker process started and initialized.
[2024-03-13T06:49:23.397Z] Host lock lease acquired by instance ID '00000000xxxxxxxxxxx'.
[2024-03-13T06:49:35.791Z] Executing 'Functions.BlobTrigger1' (Reason='New blob detected(LogsAndContainerScan): samples-workitems/samplekam.txt', Id=143133a3-c1e5xxxxxxxxxxxxx)
[2024-03-13T06:49:35.797Z] Trigger Details: MessageId: dd61e79axxxxxxxxxx, DequeueCount: 1, InsertedOn: 2024-03-13T06:49:34.000+00:00, BlobCreated: 2024-03-13T06:49:27.000+00:00, BlobLastModified: 2024-03-13T06:49:27.000+00:00
[2024-03-13T06:49:35.887Z] Python blob trigger function processed blob
Name:samples-workitems/samplekam.txt
Blob Size: None bytes
[2024-03-13T06:49:35.911Z] Executed 'Functions.BlobTrigger1' (Succeeded, Id=1431xxxxxxxxxxxxxx, Duration=907ms)
```

**Azure Portal :**
*Below is the blob I sent to the samples-workitems container.*
 |
I have wayy too many nested ifs in my code and ive looked up tutorials on how to remove them but they dont seem to work
```
client.on('messageCreate', (message) => {
if (message.channelId === mhc_minor ) {
if (message.author.bot) {
if (message.content.startsWith('[') ) {
if (message.content.startsWith("[+1 Soul Point]")) { return } ;
if (message.content.startsWith("[!]")) { return };
if (message.content.startsWith("[Info]")) { return };
if (message.content.startsWith("[Event]")) { return };
if (message.content.startsWith("[Be sure")) { return };
if (message.content.startsWith("[Sale]")) { return };
if (message.content.includes("➤")) {
if (message.channelId === mhc_minor ) {
const channel = client.channels.cache.get(mhc_mprivate)
channel.send(message.content); } return };
if (message.content.includes('@')) {
const contentWithBackticks = message.content.replace(/@(\S+)/g, '`@$1`');
const channel = client.channels.cache.get(mhc_bfs)
channel.send(contentWithBackticks);
} else {
const channel = client.channels.cache.get(mhc_bfs);
channel.send(message.content);
}}}}})
```
works perfectly fine but the nested if look really bad, how do I could them while still getting the same result |
Unable to connect to IONOS mySQL Database in C# app |
|c#|mysql|database|ionos| |
null |
To make the expansion effect smooth for the circle following the mouse, just adjust these properties in the `.mouseFollowCircle` class:
transition: width 1s ease, height 1s ease, border 1s ease, top 1s ease, left 1s ease;
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
document.addEventListener('DOMContentLoaded', () => {
const interBubble = document.getElementById('circle');
let curX = 0;
let curY = 0;
let tgX = 0;
let tgY = 0;
function move() {
curX += (tgX - curX) / 10;
curY += (tgY - curY) / 10;
interBubble.style.transform = `translate(${Math.round(curX)}px, ${Math.round(curY)}px)`;
requestAnimationFrame(() => {
move();
});
}
window.addEventListener('mousemove', (e) => {
tgX = e.clientX;
tgY = e.clientY;
if (e.target.tagName === 'P' ||
e.target.tagName === 'A' ||
e.target.tagName === 'BUTTON' ||
e.target.parentNode.tagName === 'BUTTON') {
interBubble.classList.add('big');
} else {
interBubble.classList.remove('big');
}
});
move();
});
<!-- language: lang-css -->
Body {
background-color: black;
overflow: hidden;
}
div {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
p {
color: white;
font-size: 30px;
}
.mouseFollowCircle {
width: 50px;
height: 50px;
border: 3px solid white;
border-radius: 999px;
position: absolute;
z-index: 999;
top: -25px;
left: -25px;
box-shadow: 0 0 10px white;
pointer-events: none;
backdrop-filter: blur(2px);
transition: width 1s ease, height 1s ease, border 1s ease, top 1s ease, left 1s ease;
}
.mouseFollowCircle.big {
width: 70px;
height: 70px;
border-width: 1px;
top: -35px;
left: -35px;
}
<!-- language: lang-html -->
<div><p>Hello</p></div>
<section class="mouseFollowCircle" id="circle"></section>
<!-- end snippet -->
|
You need to define the client details correctly both in the Keycloak client and in the angular app. For my app redirect uri is kept as `/` then it gets redirected by my routing startegy, you'll have to update as per your strategy
You should define in this format
[![enter image description here][1]][1]
and for the `silentCheckSsoRedirectUri` I've used the Identity providers RedirectURI which you can get from
(Sidenav)Identity Providers->"your provider"->Redirect URI
Also for Keycloak Init you'll have to use
initOptions: {
flow: 'standard',
onLoad: 'check-sso',
redirectUri: Valid_redirect_url,
silentCheckSsoRedirectUri: valid_sso_redirect_url
}
[1]: https://i.stack.imgur.com/H8P7B.png |
So I have been having issues with printing all columns in a csv file. The data within is set out strange in my opinion however it is not relevant.
I have been using pandas to see trends within a data csv file. I was trying to print out the data as well as showing it graphically with pandas. When I try to print the filtered variable with all the data, because the data spans across many columns with the dates at the top ( I will attach a photo of the code in terminal and the data file so it is not too confusing) **it does not seem to want to print all the data**
I have tried different methods such as changing it to the list() function, Trying to conver it into .to_string or .to_html however they dont work. In the photo attached it is after doing .to_string however it just outputs this at the start "<bound method DataFrame.to_html of" and then prints some collumns dates however not the data under them
[Picture of problem with .to_html][1]
[Picture of problem with only printing data][2]
[Picture of data file.][3]
def region_check(region, startdate, enddate, house_type): # region, startdate, enddate
df1 = df.loc[:, startdate:enddate]
df2 = df.loc[:, 'Region Code':'Rooms']
prop_filter = df["Property_Type"] == house_type
result = pd.concat([df2, df1], axis=1, join='inner').where(df2["Region"] == region).where(prop_filter)
result = pd.DataFrame(result)
result.dropna(inplace=True)
print(result) # This is where it prints the data as text. At the end of result is
where I was adding .to_string/html
ave = df1.mean()
ave.plot()
plt.show()
return result
above is
[1]: https://i.stack.imgur.com/or9nw.png
[2]: https://i.stack.imgur.com/So0dg.png
[3]: https://i.stack.imgur.com/ki9bp.png |
null |
|algorithm|simulation| |
|python|pandas| |
I have a .NET 8 Blazor project using the new Auto rendering mode. I have this page that simply retrieves a forum's data from the `ForumsService`, a gRPC service client, and shows a simple loading screen when the request is being processed:
```html
@page "/Forum/{ForumPermalink}"
@inject ForumsProto.ForumsProtoClient ForumsService
@rendermode InteractiveAuto
<h3>Forum @@ @ForumPermalink</h3>
@if(_forum is not null)
{
<p>@_forum.Name</p>
}
else
{
<Loading/> @* A simple component with only a p tag *@
}
@code {
[Parameter]
public string ForumPermalink { get; init; } = null!;
private ForumReply? _forum;
protected override async Task OnInitializedAsync()
{
try
{
_forum = await ForumsService.GetForumByPermalinkAsync(new()
{
Permalink = ForumPermalink
});
}
catch(RpcException exception)
{
if(exception.StatusCode == StatusCode.NotFound)
{
NotFoundService.NotifyNotFound();
return;
}
throw;
}
}
}
```
The `Loading` component:
```html
<p>Please Wait...</p>
```
As of my knowledge, Blazor Auto render mode also has a feature called "Prerendering", that processes and sends an initial HTML to the client before any interaction starts, to improve the initial page load experience and also be bot-friendly, so Google and other bots can crawl the site.
My problem is simple, it doesn't work properly. When I "View Source" the page, this is what is displayed:
```html
...
<body>
<header>
<--- prerendered correctly -->
</header>
<h3>Forum @ {permalink value is fine}</h3>
<div class="search-overlay" b-5zir38ipii>
...
</div>
<footer b-5zir38ipii>
<--- prerendered correctly -->
</footer>
<script src="/_framework/blazor.web.js"></script>
</body>
</html>
```
Neither the `<p>@_forum.Name</p>`, nor the `<Loading/>` component is even included in the HTML. Again, the page works fine when opened in a normal browser; But I want the forum name (and not even the loading component) to be included in the prerendering so that the site can be indexed as it should.
So my question is, first of all, why nothing, even the loading component is prerendered? The main question is, how can I tell the prerenderer to wait for the forum in the `OnInitializedAsync()` method, so the page is completely displayed to bots? |
Okay so firstly I'm no expert coder (hence the question) but I've managed to change the woocommerce info bar color for desktop viewing, but I cannot for the life of me figure out how to change the color for mobile devices.
```
//This is what works for desktop viewing:
.woocommerce-info {
background-color: #000;
}
//And I tried multiple similar combinations of the below code with no success:
@media (min-width: 992px) {
.woocommerce-info
background-color: #000; !important
}
``` |
Change the woocommerce info bar color on smaller screens? |
|css|mobile|info| |
null |
My Firebase save each user with 4 features:name,email,password and confirm password.
The class of users:
[enter image description here](https://i.stack.imgur.com/pF3M1.png)
The Firebase data that i saved:
[enter image description here](https://i.stack.imgur.com/TPCFf.png)
In my app i have an option to change the current password to new password,its require to put you previous password(the current that the Firebase saved) and then put new password(the user put the data about the passwords on UI 'EditText') .
See here how it looks:
[enter image description here](https://i.stack.imgur.com/xvLcQ.png)
And then the user has to click on 'confirm button' to change the old password to new.But before its change,***the computer need to check if the old password compare to the current password that saved on Firebase*** .I don't know how to do that,please help me!!
I tried to do that code but not sure if i get the access for the variable the i want.
[enter image description here](https://i.stack.imgur.com/gMWla.png)
It always changed even when the previous pass don't compare to the current..
code of database(for one user):
[1]: https://file:///C:/Users/User/Downloads/geography-trivi-new-default-rtdb-export.json |
A better solution to nested ifs |
|discord.js| |
null |
I have this site:
http://dl.dg-site.com/functionmentes/
There is a div with the color `#D9D9D9`
Code of CSS:
``` css
#full_bar {
background: #D9D9D9;
width: 100%;
height: 100px;
}
```
I want my div to be the full width site and to be glued to the footer.
How can I make this?
I use a theme in the `Wordpress`
Thanks in advance! |
|html|css|wordpress| |