text:
Q: Tomcat Connection Pool's attribute setting My web application connect DB by Tomcat jdbc pool.
this is my Tomcat context.xml
<Resource
            factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
            name="jdbc/OracleDB"
            auth="Container"
            type="javax.sql.DataSource"
            initialSize="70"
            maxActive="100"
            maxIdle="30"
            minIdle="10"
            maxWait="5000"
            removeAbandoned="true"
            removeAbandonedTimeout="60"
            username="XXOO"
            password="XXOO"
            driverClassName="oracle.jdbc.driver.OracleDriver"
            validationQuery="SELECT 'OK'"
            testWhileIdle="true"
            testOnBorrow="true"
            numTestsPerEvictionRun="5"
            timeBetweenEvictionRunsMillis="30000"
            minEvictableIdleTimeMillis="60000"
            url="jdbc:oracle:thin:@XXOO:testdb"/>

connection timeout will be happened 1min50sec
If I use JDBC to connect  DB,it would not happen.
So what's setting do I  lose or modify?


text:
Q: Convert Edittext to readonly and Make it editable on Button Press i got this nw. Before clicking on the button, my EditText is just viewable:

After button press, it should convert to an editable field:

I want the EditText field line to disappear and become read only and on button click make it editable. But this just fades the line and also the text inside it loses it visual appearance.
Here's my code:
et1.setEnabled(false);
et1.setFocusable(true);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        et1.setEnabled(true);
        et1.requestFocus();
    }
});

A: Your XML should look like this,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<EditText
    android:id="@+id/et1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name" />

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />

  </LinearLayout>

Now, add the following code to your activity class.
//init the views.
et1.setVisiblity(GONE);
tv1.setVisiblity(VISIBLE);

 //if the textView is shown, the btn click will hide it and show editText
 //instead, and same happens for editText
  btn1.setOnClickListener(new View.OnClickListener(){
  public void onClick(){

  if(et1.getVisiblity() != VISIBLE) {
        et1.setVisbility(VISIBLE);
        tv1.setVisibility(GONE);
   } else {
        et1.setVisbility(GONE);
        tv1.setVisibility(VISIBLE);
  }

  } });

P.S: This isn't executable code, although, hopefully it will get you the idea.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery Ajax call not loading always I have this link that when clicked it pops up a div and collects data from another page through ajax call and loads the data in the div after success. But my problem is this, when I pop up the div and the data loads, then I close the div. When I click the link to pop up the div again and reload the data the data doesn't load, it doesn't sends the ajax call it just shows me the previous data that was loaded in the div before I close it. What I want to achieve is when ever the div is closed and the link is clicked again, the ajax call is sent to the php page and it reloads the new data this is the link that pops up the div <a href="javascript:;" onclick="showLikes('<?php echo $id; ?>')">Likes. And here is the ajax call:
function showLikes(x){
    document.getElementById('#likeDiv').style.display='block';
    $.ajax({
        type: "GET",
        url: "/get_likes.php?id="+x,
        beforeSend: function(){
            document.getElementById('#beforeSendImg').style.display='block';
        },
        success: function(data){
            document.getElementById('#beforeSendImg').style.display='none';
            likes = $(data).fadeIn(800);
            $("#likeDiv").html(likes);
        },
    });
}

Please does anyone knows how to do it better?

A: Try;
function showLikes(x){
    $('#likeDiv').css({'display:'block'}).html("");
    $.ajax({
        type: "GET",
        url: "/get_likes.php,
        data: {id: x},
        beforeSend: function(){
            $('#beforeSendImg').css({'display':'block'});
        },
        success: function(data){
            $('#beforeSendImg').css({'display':'none'});
            likes = $(data).fadeIn(800);
            $("#likeDiv").html(likes);
        },
    });
}


text:
Q: Apache Ignite Application I am building a Java based online application using Java and Ignite. Ignite is used an in memory store/cache and also for data persistence for the application. My question is if I should deploy Ignite in a separate server or should it reside int the same server as the application?

A: You can do it both ways, it's up to you.


text:
Q: How to increase the connection timeout for mysql connection from c# application? I want to increase the connection timeout for mysql connection and I can not modify the timeout settings from administrator panel of mysql server. I want to do it within c# application and I noticed that I can read the property ConnectionTimeout of MySqlConnection class. I would like to know that is there a way to increase the connection time before opening mysql connection.

A: use "default command timeout" in your connection string, it works for me
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
default command timeout=20;

https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/specifying-default-command-timeout/

A: you can change ConnectionString as below:
String connectionString = "Server=myserver; Port=3306; Database=databasename; Uid=userid; Pwd=password;Connection Timeout=30";

in the above Connection String you can specify the number of seconds as value for Connection Timeout

A: Check out the  wait_timeout parameter for my.ini
Here is the link. restart mysql after changing the value.Why, because There may be multiple my.ini's on your system - make sure you're changing the right one
 http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_wait_timeout

or
you can define in your connection string
String myconnstring = "Server=yourservername; Port=portno; Database=yourdatabasename; Uid=yourUSERID; Pwd=yourpassword;Connection Timeout=120";

A: default command timeout=0 in your connection string does the trick.
String connectionString = "Server=myserver; Port=3306; Database=databasename; Uid=userid; Pwd=password;default command timeout=0";


text:
Q: Try exception in tkinter by using messagebox I want to try exception in tkinter. If I do not input anything into entry, it will raise ValueError and the messagebox will pop up. However, when I run my code, it indeed can catch exception, but no messagebox pops up. Can anyone tells me reason and how to correct it? Thank you.
from tkinter import *
from tkinter import messagebox
try:

    root = Tk()

    def function():
        if not entry_test.get():
            raise ValueError
        Label(root, text = entry_test.get()).grid()

    entry_test = Entry(root)
    entry_test.grid()

    button_click = Button(root, text ="click to test", command= function)
    button_click.grid()

    root.mainloop()

except ValueError:
    message.showwarning("ENTRY ERROR", "please input somthing in entry")


text:
Q: Retrieve information from old .plt files without the .dwg? I have received several .plt files dating back to 1995-2002, unfortunately there isn't any .DWG files or other files with them. They have apparently been deleted, so only the .plt files remain.
Is it possible to retrieve information from these files in anyway? They contain information about roads and their drainage systems which I would like to digitize afterwards.
I can upload a sample file if needed.
I have access to a lot of different Bentley and Autodesk software, so feel free to suggest any solution possible.

A: Here's a link from the Autodesk site that may help you.  All versions of AutoCAD should be able to plot the files for you.  Working with PLT files


text:
Q: Codeigniter index method return "index" for GET parameter if there is no parameter? I have this part of code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Blog extends CI_Controller {

    function _remap($page){

            $this->index($page);
    }

    public function index($page = '1')
    {
        var_dump($page); exit;
    }
}

When i hit domain/index.php/blog var_dump returns me string(5) "index" when i hit domain/index.php/blog/2 it returns me 2, which is correct? But why ? I have default parameter $page = '1' ?

A: When you hit domain/index.php/blog/2 this means you are calling blog controller's default method index and passing 2 as parameter. In this scenario it will replace your default parameter $page = '1' to 2.
When you will hit domain/index.php/blog then index function will be called without any parameters and it will take $page as 1.
UPDATED ANSWER (As per comment)

If your controller contains a method named _remap(), it will always get called regardless of what your URI contains. It overrides the normal behavior in which the URI determines which method is called, allowing you to define your own method routing rules.

Documentation Link
Use below code it will resolve your issue.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Blog extends CI_Controller {

    function _remap($page){
        if($page=='index'){
            $this->index($page = 1);
        }
        $this->index($page);
    }

    public function index($page = 1)
    {
        var_dump($page); exit;
    }

}


text:
Q: Jmeter Run Thread Groups Consecutively vs No of Threads What is the difference between following Jmeter test architectures?
--Test Plan(Run Thread Groups Consecutively not checked)
    --Thread Group 1(No of Threads(users) : 1, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 2(No of Threads(users) : 1, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 3(No of Threads(users) : 1, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 4(No of Threads(users) : 1, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 5(No of Threads(users) : 1, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 6(No of Threads(users) : 1, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 7(No of Threads(users) : 1, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 8(No of Threads(users) : 1, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 9(No of Threads(users) : 1, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 10(No of Threads(users) : 1, Ramp up Period(in Seconds) : 1, Loop count: 1)

--Test Plan(Run Thread Groups Consecutively not checked)
    --Thread Group 1(No of Threads(users) : 10, Ramp up Period(in Seconds) : 1, Loop count: 1)

--Test Plan(Run Thread Groups Consecutively not checked)
    --Thread Group 1(No of Threads(users) : 2, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 2(No of Threads(users) : 2, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 3(No of Threads(users) : 2, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 4(No of Threads(users) : 2, Ramp up Period(in Seconds) : 1, Loop count: 1)
    --Thread Group 5(No of Threads(users) : 2, Ramp up Period(in Seconds) : 1, Loop count: 1)

In my scenario, I want to do load test of my solution where I have different test cases executed by different users. Here users have a very little chance to do same operation at a time. So I use different thread groups for my test cases. And with my scenario increase No of Threads(users) in thread group doesn't mean logical to me. So I unchecked Run Thread Groups Consecutively in my Test plan but not sure about does it really makes a concurrency test or not.

A: If you check Run Thread Groups Consecutively then thread groups will fire up consecutively.That means JMeter will start Thread Group 01 first, then Thread Group 02 ,......, and so on. It's an option here to instruct JMeter to run the Thread Groups serially rather than in parallel.
So if you unchecked Run Thread Groups Consecutively in your Test plan, it will make a concurrency in your test.

A: In case 1 you are guaranteed to have a concurrency of 10 threads right from the start of execution.
In case 2 the concurrency of 10 threads is reached after 1 second, with rate of 1 thread per 100ms (provided no threads finished their execution within that time).
Case 3 mixes both options: 5 threads will start immediately, and 5 more after 1 sec, so the concurrency of 10 threads is reached after 1 second.
Note that when I say "concurrency reached" I mean on JMeter side. Depending on the setup of the script, concurrency for the server may be reached later.
What's also important is that you have "Loop count: 1". If all users run that single loop iteration for a long time (minutes/hours), or there's a loop controller inside the thread group, the difference between 3 options is insignificant for statistics. But if that iteration is short (seconds to a few minutes), or each operation within each thread is unique, then in case of options 2 and 3 (especially 2), your statistics will be flawed, since many operations on threads that started earlier will be performed before 10 thread concurrency is reached and vice versa.

A: JMeter acts as follows:

*

*For each Thread Group it starts threads during "ramp-up" period

*Threads start executing samplers upside-down or according to Logic Controllers

*When thread doesn't have a sampler to execute or loop to iterate - it's being shut down

So you can run into a situation where 1st thread has already finished everything and was shut down and 10th thread hasn't been started yet.
If you want to have guaranteed concurrency - provide enough loops at Thread Group level. You can also use i.e. Ultimate Thread Group which has some extra features to flexibly define users arrival rate and visualise anticipated concurrency.
By the way, you can get different virtual users executing different scenarios even in the same Thread Group using Throughput Controller. See Running JMeter Samplers with Defined Percentage Probability article for detailed explanation of the possible approaches.


text:
Q: Accessing Azure Key Vault from Azure Batch I am trying to access secrets in my Azure Key Vault from VMs running in my Azure Batch node pool.
However, I keep running into the exception:
Exception Message: Tried 1 certificate(s). Access token could not be acquired.
Exception for cert #1 with thumbprint MY-THUMBPRINT: Keyset does not exist
So far I have been following the instructions outlined here:
https://learn.microsoft.com/en-us/azure/key-vault/service-to-service-authentication
The article outlines the scenario of Azure Batch, and indicates I should use a Service Principal.  I would like to ensure no secrets or keys are in version control, so I am using the first method of a certificate in a local keystore to sign into Azure AD.
Running all of the below locally as an executable works fine, but fails when run on an Azure Batch pool node.
My steps so far to do the above are:

*

*Create a service principal and associated certificate in keyvault:
az ad sp create-for-rbac --name myserviceprincipal --create-cert --cert mycertname --keyvault mykeyvaultname.  Keep the service principal app id and tenant id for use in the AzureServicesAuthConnectionString.

*Create key vault access policy for the created service principal (done in the azure portal UI).

*Download the created certificate in PFX/PEM format (done in the Azure Portal UI).

*Ensuring a PFX password on the certificate (I am doing this as uploading the cert to azure batch in step 6 requires an associated password): https://coombes.nz/blog/azure-keyvault-export-certificate/
# Replace these variables with your own values
$vaultName = "YOUR-KEYVAULT-NAME"
$certificateName = "YOUR-CERTIFICATE-NAME"
$pfxPath = [Environment]::GetFolderPath("Desktop") + "\$certificateName.pfx"
$password = "YOUR-CERTIFICATE-PASSWORD"

$pfxSecret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $certificateName
$pfxUnprotectedBytes = [Convert]::FromBase64String($pfxSecret.SecretValueText)
$pfx = New-Object Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($pfxUnprotectedBytes, $null, [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$pfxProtectedBytes = $pfx.Export([Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $password)
[IO.File]::WriteAllBytes($pfxPath, $pfxProtectedBytes)

*Installing the certificate locally into my computer's LocalMachine store (for local testing).

*Uploading the certificate into Azure Batch (using the Azure Portal UI upload).

*Associating the certificate with the appropriate Node Pool and rebooting the nodes (using the Azure Portal UI for now).
My application package running on Azure Batch is a simple console executable.  The AzureServicesAuthConnectionString is set to RunAs=App;AppId={AppId};TenantId={TenantId};CertificateThumbprint={Thumbprint};CertificateStoreLocation={LocalMachine} and the remaining key vault code to retreive the secret looks like:
Environment.SetEnvironmentVariable("AzureServicesAuthConnectionString", "RunAs=App;AppId=<MY-APP-ID>;TenantId=<MY-TENANT>;CertificateThumbprint=<MY-THUMBPRINT>;CertificateStoreLocation=LocalMachine");

AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(Environment.GetEnvironmentVariable("AzureServicesAuthConnectionString"));
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var secret = await keyVaultClient.GetSecretAsync("<MY-SECRET>").ConfigureAwait(false);
var message = secret.Value;
Console.WriteLine(message);

Things work fine locally, but fail on the remote node.  I am able to RDP into the Azure Batch node and see that the certificate has been installed for the local machine.
I am wondering how to resolve my error or if my above steps are wrong in some way?

A: In addition to the above, I have followed the instructions from Sam Cogan article here:
https://samcogan.com/secure-credential-access-with-azure-batch-and-keyvault/
However I receive the same issue as the original question.  My error and associated repro steps for the Sam Cogan article are:
Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException: Parameters: Connection String: RunAs=App;AppId=<My Service Principal ID>;TenantId=<My Tenant ID>;CertificateThumbprint=<My cert thumbprint>;CertificateStoreLocation=LocalMachine, Resource: https://vault.azure.net, Authority: https://login.windows.net/<My Tenant ID>. Exception Message: Tried 1 certificate(s). Access token could not be acquired.
Exception for cert #1 with thumbprint <My cert thumbprint>: Keyset does not exist

My repro steps are:

*

*Create the certificate (I added the -a sha256 -len 2048 part as I had the same error outlined and resolved here: How to authenticate with Key Vault from Azure Batch)

C:\Program Files (x86)\Windows Kits\10\bin\x64> .\makecert.exe -sv batchcertificate6.pvk -n "cn=andybatch6.cert.mydomain.org" batchcertificate6.cer -r -pe -a sha256 -len 2048

*Convert the certificate in step 1 to PFX format:

C:\Program Files (x86)\Windows Kits\10\bin\x64> .\pvk2pfx.exe -pvk batchcertificate6.pvk -spc batchcertificate6.cer -pfx batchcertificate7.pfx -po <MyPassword>  -pi <MyPassword>

*Create the ActiveDirectory Application and Service Principal and associate and upload the created cert:

#Point the script at the cer file you created

$cerCertificateFilePath = 'C:\Program Files (x86)\Windows Kits\10\bin\x64\batchcertificate6.cer'
$cer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cer.Import($cerCertificateFilePath)

#Load the certificate into memory
$credValue = [System.Convert]::ToBase64String($cer.GetRawCertData())

#Create a new AAD application that uses this certifcate
$newADApplication = New-AzureRmADApplication -DisplayName "<My display name>" -HomePage "<my url>" -IdentifierUris " <my url>" -certValue $credValue

#Create new AAD service principle that uses this application
$newAzureAdPrincipal = New-AzureRmADServicePrincipal -ApplicationId $newADApplication.ApplicationId

*Grant Key Vault Access for the Service Principal (I added extra permissions in the UI but also ran this via command line):

Set-AzureRmKeyVaultAccessPolicy -VaultName 'myvaultname' -ServicePrincipalName '<my url>' -PermissionsToSecrets 'Get'

*Upload the Cert (pfx) to Azure Batch via the portal.  Associate it with my node pool as LocalMachine and reboot the nodes.  Run the application with a connection string like:

Environment.SetEnvironmentVariable("AzureServicesAuthConnectionString",
                    "RunAs=App;" +
                    "AppId=<the app id of my active directory app registration> ;" +
                    "TenantId=<my subscription tenant id>;" +
                    "CertificateThumbprint=<the thumbprint of my cert>;" +
                    "CertificateStoreLocation=LocalMachine");

                AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(Environment.GetEnvironmentVariable("AzureServicesAuthConnectionString"));
                KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                var secret = await keyVaultClient.GetSecretAsync("https://<my vault name>.vault.azure.net/secrets/<secret name>/<secret id>")
                        .ConfigureAwait(false);
                message = secret.Value;
                Console.WriteLine(message);

My code works with the installed cert locally using the above connection string, but has the above mentioned exception when running on Azure Batch.

A: In order to access the Certificate, it must be associated and installed for the 'Current User.'  It may be that LocalMachine does not have the appropriate level of permissions?
On Azure Batch, ensure that the uploaded certificate is associated with:
Store Name: 'My'
Store Location: 'CurrentUser'
This post was helpful: https://github.com/nabhishek/customactivity_sample/tree/linkedservice
As was this post: X509Certificate - Keyset does not exist
The connection string in the C# exe looks like:
Environment.SetEnvironmentVariable("AzureServicesAuthConnectionString",
                    "RunAs=App;" +
                    "AppId=<the app id of my active directory app registration> ;" +
                    "TenantId=<my subscription tenant id>;" +
                    "CertificateThumbprint=<the thumbprint of my cert>;" +
                    "CertificateStoreLocation=CurrentUser");

                AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(Environment.GetEnvironmentVariable("AzureServicesAuthConnectionString"));
                KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                var secret = await keyVaultClient.GetSecretAsync("https://<my vault name>.vault.azure.net/secrets/<secret name>/<secret id>")
                        .ConfigureAwait(false);
                message = secret.Value;
                Console.WriteLine(message);


text:
Q: Eigenvalues of 3D Laplacian on a spherical segment To study the change in Laplacian eigenvalues on a spherical segment, I constructed a table of spherical segments using the code from here.
I discretized the output using DiscretizeGraphics and obtained a table of discretized spherical segments..
As I try to apply NDEigensystems on the discretized figures, I get the following error:

The code I am using to generate the spherical segments :
sphericalSegment[{r1_,r2_}, {\[Theta]1_, \[Theta]2_}, {\[Phi]1_, \[Phi]2_}]:=
Module[{plot, pts, surf, bdy},plot = ParametricPlot3D[{Cos[\[Theta]] Sin[\[Phi]],Sin[\[Theta]] Sin[\[Phi]],Cos[\[Phi]]}, {\[Theta], \[Theta]1, \[Theta]2}, {\[Phi], \\[Phi]1, \[Phi]2}, Mesh -> None, BoundaryStyle -> Black];
pts = First@Cases[plot, GraphicsComplex[p_, ___] :> p, Infinity];
surf = First@Cases[plot, Polygon[p_] :> p, Infinity];
bdy = First@Cases[plot, Line[p_] :> p, Infinity];
GraphicsComplex[Join[r1*pts, r2*pts], {EdgeForm[], Polygon[surf],  Polygon[Reverse /@ surf + Length@pts],Polygon[Join[#, Reverse@# + Length@pts], VertexNormals -> Cross[Subtract @@ pts[[#]], pts[[First@#]]]] & /@   Partition[bdy, 2, 1, 1]}, VertexNormals -> Join[-pts, pts]]]

Code to calculate the Laplacian Eigenvalues :
r = Flatten[Table[{Graphics3D[sphericalSegment[{1, 1}, {0, 2 Pi}, {Pi/n, Pi}]]}, {n, 1.2, 3, 0.2}]];
dr = DiscretizeGraphics /@ r;
eigs = NDEigensystem[{-Laplacian[f[x, y, z], {x, y, z}] + NeumannValue[0,True]}, f[x, y, z], Element[{x, y, z}, #],1] & /@ dr

A: The missing text is
NDEigensystem::femnfm: The current version of NDSolve cannot solve equations over boundaries or surfaces. Please specify a region where the embedding dimension is the same as the dimension.

So your shells need some thickness.


text:
Q: #2006 - MySQL server has gone away Hola buenas tardes desde ayer estoy notando un problema al intentar acceder a mi base de datos. Al entrar mediante PhpMyAdmin me da el siguiente error.

Ya intente hacer todo lo que decían diferentes foros de aumentar las variables en phpmyadmin de max_allowed_packet y wait_timeout.
Si podrían ayudarme se los agradecería. Uso Ubuntu 20.04

A: Intenta ingresando por terminal. Asumiendo sea un linux, que tengas un usuario llamado root con contraseña admin123 con nombre de la db como db_prueba, haces esto esto:
mysql -u root -padmin123 db_prueba

Una vez dentro ya puedes hacer un select de prueba. Lo que quiere decir que el problema no es mysql, sino que:

*

*la versión de PHP pudo haber sido actualizada

*incorrecta configuración en el php.ini

*si se ha cambiado el php.ini, no se procedió a realizar un reinicio del Apache web server


text:
Q: Custom shipping extension I use Magento 2.4.3.
I created custom shipping extension. It works correct.
But now I would like to add calculating by width, height, length params of product.
I've added these params (width, height, length) to product attribute set. It's easy.
My question - how I can get these these params (width, height, length) in method collectRates() my custom shipping extrension?
I see $request->getPackageWeight(), $request->getBaseSubtotalInclTax(). Is there method(s) to get custom product attribute in $request?
Thanks.

A: Directly in request there is no such value. But you can get quote items $request->getAllItems() . Do foreach, get item, then product from it (or load it by id/sku) and get required values from product.


text:
Q: Database Error - ORA-00904: "UM_MAPPED_ATTRIBUTE_DOMAIN": invalid identifier We are trying to deploy WSO2 GREG 4.6 on Oracle RAC Database. As mentioned in instructions we ran the oracle_rac.sql dbscript to create the schema, but when we are trying to start the application, it fails with multiple database errors
[2014-03-11 21:42:58,366] ERROR {org.wso2.carbon.user.core.util.DatabaseUtil} -  Database Error - ORA-00904: "UM_MAPPED_ATTRIBUTE_DOMAIN": invalid identifier
java.sql.SQLSyntaxErrorException: ORA-00904: "UM_MAPPED_ATTRIBUTE_DOMAIN": invalid identifier
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1046)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3694)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1354)
at org.wso2.carbon.user.core.claim.dao.ClaimDAO.addClaimMapping(ClaimDAO.java:227)
at org.wso2.carbon.user.core.claim.dao.ClaimDAO.addCliamMappings(ClaimDAO.java:140)
at org.wso2.carbon.user.core.common.DefaultRealm.populateProfileAndClaimMaps(DefaultRealm.java:420)
at org.wso2.carbon.user.core.common.DefaultRealm.init(DefaultRealm.java:101)
at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:223)
at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:101)
at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:114)
at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:70)
at org.wso2.carbon.user.core.internal.BundleCheckActivator.start(BundleCheckActivator.java:61)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683)
at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:390)
at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1176)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:559)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:544)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:457)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.doSetStartLevel(StartLevelManager.java:243)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:438)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:1)
at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)

[2014-03-11 21:42:58,373] ERROR {org.wso2.carbon.user.core.common.DefaultRealmService} -  Cannot initialize the realm.
org.wso2.carbon.user.core.UserStoreException: Database Error - ORA-00904: "UM_MAPPED_ATTRIBUTE_DOMAIN": invalid identifier
at org.wso2.carbon.user.core.claim.dao.ClaimDAO.addClaimMapping(ClaimDAO.java:261)
at org.wso2.carbon.user.core.claim.dao.ClaimDAO.addCliamMappings(ClaimDAO.java:140)
at org.wso2.carbon.user.core.common.DefaultRealm.populateProfileAndClaimMaps(DefaultRealm.java:420)
at org.wso2.carbon.user.core.common.DefaultRealm.init(DefaultRealm.java:103)
at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:223)
at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:101)
at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:115)
at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:71)
at org.wso2.carbon.user.core.internal.BundleCheckActivator.start(BundleCheckActivator.java:61)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683)
at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:390)
at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1176)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:559)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:545)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:458)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.doSetStartLevel(StartLevelManager.java:243)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:438)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:1)
at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)

Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "UM_MAPPED_ATTRIBUTE_DOMAIN": invalid identifier
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1046)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3694)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1354)
at org.wso2.carbon.user.core.claim.dao.ClaimDAO.addClaimMapping(ClaimDAO.java:227)
at org.wso2.carbon.user.core.claim.dao.ClaimDAO.addCliamMappings(ClaimDAO.java:140)
at org.wso2.carbon.user.core.common.DefaultRealm.populateProfileAndClaimMaps(DefaultRealm.java:420)
at org.wso2.carbon.user.core.common.DefaultRealm.init(DefaultRealm.java:101)
at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:223)
at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:101)
at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:114)
at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:70)
at org.wso2.carbon.user.core.internal.BundleCheckActivator.start(BundleCheckActivator.java:61)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683)
at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:390)
at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1176)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:559)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:544)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:457)
... 5 more

[2014-03-11 21:42:58,375] ERROR {org.wso2.carbon.user.core.internal.Activator} -  Cannot start User Manager Core bundle
org.wso2.carbon.user.core.UserStoreException: Cannot initialize the realm.
    at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:231)
    at org.wso2.carbon.user.core.common.DefaultRealmService.(DefaultRealmService.java:101)
    at org.wso2.carbon.user.core.common.DefaultRealmService.(DefaultRealmService.java:114)
    at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:70)
    at org.wso2.carbon.user.core.internal.BundleCheckActivator.start(BundleCheckActivator.java:61)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:390)
    at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1176)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:559)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:545)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:458)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.doSetStartLevel(StartLevelManager.java:243)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:438)
    at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)
Caused by: org.wso2.carbon.user.core.UserStoreException: Database Error - ORA-00904: "UM_MAPPED_ATTRIBUTE_DOMAIN": invalid identifier
at org.wso2.carbon.user.core.claim.dao.ClaimDAO.addClaimMapping(ClaimDAO.java:261)
at org.wso2.carbon.user.core.claim.dao.ClaimDAO.addCliamMappings(ClaimDAO.java:140)
at org.wso2.carbon.user.core.common.DefaultRealm.populateProfileAndClaimMaps(DefaultRealm.java:420)
at org.wso2.carbon.user.core.common.DefaultRealm.init(DefaultRealm.java:103)
at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:223)
at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:101)
at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:115)
at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:71)
... 15 more

Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "UM_MAPPED_ATTRIBUTE_DOMAIN": invalid identifier
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1046)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3694)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1354)
at org.wso2.carbon.user.core.claim.dao.ClaimDAO.addClaimMapping(ClaimDAO.java:227)
at org.wso2.carbon.user.core.claim.dao.ClaimDAO.addCliamMappings(ClaimDAO.java:140)
at org.wso2.carbon.user.core.common.DefaultRealm.populateProfileAndClaimMaps(DefaultRealm.java:420)
at org.wso2.carbon.user.core.common.DefaultRealm.init(DefaultRealm.java:101)
at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:223)
at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:101)
at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:114)
at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:70)
at org.wso2.carbon.user.core.internal.BundleCheckActivator.start(BundleCheckActivator.java:61)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683)
at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:390)
at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1176)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:559)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:544)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:457)
... 5 more

[2014-03-11 21:43:12,809]  INFO {org.apache.catalina.startup.TaglibUriRule} -  TLD skipped. URI: http://tiles.apache.org/tags-tiles is already defined
Are we missing some step?
Thanks.

A: I think, WSO2 product is not shipped with updated oracle_rac.sql script file in that  version that you have mentioned (basically versions after Carbon 4.2.0). There are database schema changes with 4.2.0..  But these changes have not been incorporated with oracle_rac.sql. Therefore you can not use it. But oracle.sql file is working fine... So if you just compare the oracle.sql  and oracle_rac.sql files.  You could edit oracle_rac.sql file and get it works. I suggest 1st get the  oracle.sql file and update it to support for oracle_rac.
Then highlighted different that i have seen
in oracle.sql  file you can find following

START WITH 1 INCREMENT BY 1 NOCACHE

in oracle_rac.sql you can change it as following

START WITH 1 INCREMENT BY 1 CACHE 20 ORDER

Hope this would help you.


text:
Q: Azure CLI SP creation w/ API permissions I'm trying to write a simple script to create an SP that is assigned some Microsoft Graph API permissions. I think what I need to do is create an SP with a Contributor role, then assign it the API permissions I need from Microsoft Graph API, and then grant admin consent. It does run to completion, however then when I look in the portal admin consent hasn't been granted, and when I then try to assign manually, I get the following:
Grant consent failed with error: Claim is invalid: 204e0828-b5ca-4ad8-b9f3-f32a958e7cc4 does not exist on resource application 00000003-0000-0000-c000-000000000000. [zPYKlPo0GJHRzGclFADr9k]
Here's the script, any suggestions are welcome:
#!/bin/bash

## Usage: ./setup-sp.sh <app-name>
set -eou pipefail

getPermissionId () {
  # $1 = name of permission, e.g. User.ReadWrite.All
  echo `az ad sp list \
    --query "[?appDisplayName=='Microsoft Graph'].{permissions:oauth2Permissions}[0].permissions[?value=='$1'].id" \
    --all \
    --output tsv`
}

APP_NAME=$1

echo "Getting subscription ID"
SUBSCRIPTION_ID=$(az account show --query id --output tsv)
echo "Subscription ID is: $SUBSCRIPTION_ID"

echo "Creating an App Registration and associated Service Principal"
SP=$(az ad sp create-for-rbac --role Contributor --name $APP_NAME --scopes /subscriptions/$SUBSCRIPTION_ID)

echo "The following is your Service Principal credentials, store them securely!"
echo $SP

APP_ID=$(echo $SP | jq -r .appId)
echo "Application ID is: $APP_ID"

# Microsoft Graph API Id
API_ID="00000003-0000-0000-c000-000000000000"

# IDs for various Application Roles
echo "Getting API permission IDs"
USER_READWRITE_ALL_ID=$(getPermissionId User.ReadWrite.All)
GROUP_READWRITE_ALL_ID=$(getPermissionId Group.ReadWrite.All)
APPLICATION_READWRITE_ALL_ID=$(getPermissionId Application.ReadWrite.All)

# Add permissions to SP
echo "Adding API permissions to SP"
az ad app permission add \
  --id $APP_ID \
  --api $API_ID \
  --api-permissions \
      $USER_READWRITE_ALL_ID=Role \
      $GROUP_READWRITE_ALL_ID=Role \
      $APPLICATION_READWRITE_ALL_ID=Role

echo "Granting access for Microsoft Graph API"
az ad app permission grant --id $APP_ID --api $API_ID

echo "Granting admin-consent for API permissions"
az ad app permission admin-consent --id $APP_ID

echo "Done. Check out your SP at: https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/$APP_ID"

A: There were two issues in the code.
First, the code to find the API permission IDs that was based on the query from here https://learn.microsoft.com/en-us/graph/permissions-reference#retrieving-permission-ids was actually returning the ID for AD graph, not Microsoft Graph.
Second, az ad app permission admin-consent is deprecated and the az ad sp permission grant only works for Delegated permissions, not Application permissions (https://github.com/Azure/azure-cli/issues/12137#issuecomment-596567479). The solution is to first pull the Object ID of the SP and Microsoft Graph API, and then use az rest to POST the grant directly. Here's the working copy:
#!/bin/bash

## Usage: ./setup-sp.sh <app-name>
set -eou pipefail

APP_NAME=$1

# Microsoft Graph API Id
API_ID="00000003-0000-0000-c000-000000000000"

USER_READWRITE_ALL_ROLE="User.ReadWrite.All"
GROUP_READWRITE_ALL_ROLE="Group.ReadWrite.All"
APPLICATION_READWRITE_ALL_ROLE="Application.ReadWrite.All"

getPermissionId () {
  # $1 = name of permission, e.g. User.ReadWrite.All
  echo `az ad sp show --id $API_ID --query "appRoles[?value=='$1'].id" --output tsv`
}

grantPermission () {
  # $1 = SP objectId
  # $2 = resourceId
  # $3 = permissionId

  az rest \
    --method POST \
    --uri "https://graph.microsoft.com/v1.0/servicePrincipals/$1/appRoleAssignments" \
    --headers '{"Content-Type": "application/json"}' \
    --body "{\"principalId\": \"$1\", \"resourceId\": \"$2\", \"appRoleId\": \"$3\"}" \
    --only-show-errors
}

echo "Getting subscription ID"
SUBSCRIPTION_ID=$(az account show --query id --output tsv)
echo "Subscription ID is: $SUBSCRIPTION_ID"

echo "Creating an App Registration and associated Service Principal"
SP=$(az ad sp create-for-rbac --role Contributor --name $APP_NAME)

echo "The following is your Service Principal credentials, store them securely!"
echo $SP

APP_ID=$(echo $SP | jq -r .appId)
echo "Application ID is: $APP_ID"

echo "Getting your users' Object ID"
USER_ID=$(az ad signed-in-user show --query objectId --output tsv)
echo "Object ID: $USER_ID"

echo "Adding you as owner of the Service Principal"
az ad app owner add --id $APP_ID --owner-object-id $USER_ID

# IDs for various Application Roles
echo "Getting API permission IDs"
USER_READWRITE_ALL_ID=$(getPermissionId $USER_READWRITE_ALL_ROLE)
GROUP_READWRITE_ALL_ID=$(getPermissionId $GROUP_READWRITE_ALL_ROLE)
APPLICATION_READWRITE_ALL_ID=$(getPermissionId $APPLICATION_READWRITE_ALL_ROLE)

echo "$USER_READWRITE_ALL_ROLE = $USER_READWRITE_ALL_ID"
echo "$GROUP_READWRITE_ALL_ROLE = $GROUP_READWRITE_ALL_ID"
echo "$APPLICATION_READWRITE_ALL_ROLE = $APPLICATION_READWRITE_ALL_ID"

# Add permissions to SP
echo "Adding API permissions to SP"
az ad app permission add \
  --id $APP_ID \
  --api $API_ID \
  --api-permissions \
      $USER_READWRITE_ALL_ID=Role \
      $GROUP_READWRITE_ALL_ID=Role \
      $APPLICATION_READWRITE_ALL_ID=Role

# NOTE: az cli does not have a command to consent for application permissions
# see here: https://github.com/Azure/azure-cli/issues/12137#issuecomment-596567479
# and here: https://learn.microsoft.com/en-us/graph/api/serviceprincipal-post-approleassignments?view=graph-rest-1.0&tabs=http
echo "Granting consent for API permissions"
APP_OBJECT_ID=$(az ad sp show --id $APP_ID --query "objectId" --output tsv)
API_OBJECT_ID=$(az ad sp show --id $API_ID --query "objectId" --output tsv)
grantPermission $APP_OBJECT_ID $API_OBJECT_ID $USER_READWRITE_ALL_ID
grantPermission $APP_OBJECT_ID $API_OBJECT_ID $GROUP_READWRITE_ALL_ID
grantPermission $APP_OBJECT_ID $API_OBJECT_ID $APPLICATION_READWRITE_ALL_ID

echo "Done. Check out your SP at: https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/Overview/appId/$APP_ID"


text:
Q: Insert Value on recordset to SQL Server table I have a problem that I have tried to work through and have hit a brick wall on and hoping that someone can help me out. I need to write from an unbound form to a SQL Server table but also pull the int primary key as part of the data for a Unique Number. Below is my code:
Option Compare Database
Option Explicit

Private Sub btnSCRID_Click()

Dim db As DAO.Database
Dim rstSCR As DAO.Recordset
Dim SQL As String

SQL = "SELECT [dbo_Master Shared Compliance Review].* FROM [dbo_Master Shared Compliance Review]"

Set db = CurrentDb
Set rstSCR = db.OpenRecordset(SQL, dbOpenDynaset, dbSeeChanges)

If VerifyFields Then

    rstSCR.AddNew
    rstSCR![User ID] = Me.txtUSERID.Value
    rstSCR![Report Date] = Me.txtDate.Value
    rstSCR![Partner Name] = Me.txtPartner.Value
    rstSCR![Relationship] = Me.cboRelationship.Value
    rstSCR![Entity] = Me.cboEntity.Value
    rstSCR![Entry Number] = Me.txtEntryNum.Value
    rstSCR![ENTRY DATE] = Me.txtEntryDt.Value
    rstSCR![Vendor] = Me.txtVendor.Value
    rstSCR![PO Number] = Me.txtPO.Value
    rstSCR![UPC] = Me.txtUPC.Value
    rstSCR![VPN or Style Number] = Me.txtStyle.Value
    rstSCR![Item Description] = Me.txtItemDesc.Value
    rstSCR![Document Issues] = Me.cboDocIs.Value
    rstSCR![Valuation Issue] = Me.cboValIs.Value
    rstSCR![OGA Issues(Missing Forms)] = Me.cboOGAis.Value
    rstSCR![HTS Issue] = Me.cboHTSis.Value
    rstSCR![Comments] = Me.txtComm.Value
    rstSCR![Broker Email] = Me.chkBroker.Value
    rstSCR![PreAlert Shipment] = Me.chkPreAlert.Value
    rstSCR![HTS 1] = Me.txtHTS1.Value
    rstSCR![HTS 2] = Me.txtHTS2.Value
    rstSCR![HTS 3] = Me.txtHTS3.Value
    rstSCR![HTS 4] = Me.txtHTS4.Value
    rstSCR![HTS 5] = Me.txtHTS5.Value
    rstSCR![HTS 6] = Me.txtHTS6.Value
    rstSCR![HTS 7] = Me.txtHTS7.Value
    rstSCR![HTS 8] = Me.txtHTS8.Value
    rstSCR![HTS 9] = Me.txtHTS9.Value
    rstSCR![HTS 10] = Me.txtHTS10.Value
    rstSCR![Cost] = Me.txtCost.Value
    rstSCR![Assist] = Me.txtAssist.Value
    rstSCR![COO] = Me.txtCOO.Value
    rstSCR![Manufacturer Name] = Me.txtMFGNM.Value
    rstSCR![Manufacturer Address] = Me.txtMFGAD.Value
    rstSCR![HTS Description] = Me.txtHTSDESC.Value
    rstSCR![Vendor] = Me.txtVendor.Value
    rstSCR![SCR ID] = "SCR" & "-" & DatePart("yyyy", Date) & rstSCR![AutoNumber]

    rstSCR.Update
    rstSCR.Close

    Set rstSCR = Nothing

    DoCmd.Close acForm, "Batch PO SCR Form"

    Forms("Record Search").Controls("btnSavePDF").Visible = True

Else
    MsgBox "Cannot create SCR ID becuase required fields are missing. Please see items highlighted in red!", vbOKOnly, "ERROR - CANNOT CREATE ID!"
End If

My issue is that on the last line below is not getting the SQL int auto number to put in the field:
rstSCR![SCR ID] = "SCR" & "-" & DatePart("yyyy",Date) & rstSCR![AutoNumber]

The SCR-2018 shows in the field SCRID as expected it is just not pulling in the int primary key (AutoNumber) from the SQL Server table.
AutoNumber is a Identity (1,1) field. I am not getting any error messages.

A: As noted, to get auto number and other fields as a result of triggers, code etc., you need to save the record. Also, one strange "quirk" of DAO is that when adding a record, the record pointer moves OFF of the current record (this does NOT occur when using DAO to edit existing).
Regardless, simply force the update, and then re-set the record pointer, and then pull + grab the auto number(s) etc.
This code will work:
' all of you code goes here
rstRecords.Update
rstRecords.Bookmark = rstRecords.LastModified
lngNext = rstRecords!ID
' grab any other values from columns such as those set by triggers etc.

rstRecords.Close


text:
Q: Put Data from dataSet in a chart rdlc report i need your help !
I'm actually on a project, i got csv files with data, the first column is the date and others columns is data from different sensor. I actually put theses data in a DataTable and after that on a DataSet.xsd
I got an RDLC report and i want to display chart with the data from my DataSet. I tried many times but this does not work, i cant see my data on my chart !
Hoping that you can help me !
Have a great Day, and sorry if my english is not perfect.

A: i put my data in my DataSet like this :
foreach (DataRow row in DTTrends.Rows)
        {
            //On créer une nouvelle ligne
            dr = Ds_Impression.Courbes1.NewRow();
            //On rempli la ligne
            dr["Date"] = row[0].ToString();
            dr["Capteur1"] = row[1].ToString();
            dr["Capteur2"] = row[2].ToString();
            dr["Capteur3"] = row[3].ToString();
            dr["Capteur4"] = row[4].ToString();
            dr["Capteur5"] = row[5].ToString();
            dr["Capteur6"] = row[6].ToString();
            dr["Capteur7"] = row[7].ToString();
            dr["Capteur8"] = row[8].ToString();

            Ds_Impression.Courbes1.Rows.Add(dr);
        }

I verify, the data in my DataSet is the same as my datatable and i'm trying to display my values according to the date in a chart in my RDLC report : https://ibb.co/LnPC1YV
Iwant the Date on X axis and Value from "Capteur2" on Y Axis


text:
Q: Big R frame conversion - connection error Biginsights v4 I am trying to proceed with the bluemix tutorial " analyzing big data with R".  When connecting to BigSQL,I am getting a generic error message (" Error: BigR[bigr.connect]: Connection could not be established. Verify connection parameters"), however the when checking connection ("is.bigR.connected") it returns true.
When proceeding with the tutorial, when trying to execute a bigR frame conversion I am getting a series of error messages, partly copied here (" Error: BigR[.bigr.jdbc.query.helper]: Error code : 15, SQLState : 58004
Caused by : The stack trace :java.sql.SQLException  at com.ibm.biginsights.bigsql.jdbc.BigSQLStatement.executeQuery(BigSQLStatement.java:91)").
I am not sure if they could be related to the connection-issue mentioned above, but I am unable to proceed.
I have searched the internet for solutions, but without results (I am very new to Hadoop/SQL/bigR). Hoping for some feedback. Thank you.

A: After thorough investigation I adjusted the bigr.connect statement (especially double checked the password parameter as well as truststore path).  Error messages dissapeared.


text:
Q: Installing PyCuda package shows cl.exe error in PyCharm error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2

I'm trying to install PyCuda package for my program and I get the above error. The IDE I use is Pycharm.
My pip version is 10.0.1. What could be the possible issue?

A: From pycharm,
goto settings -> project Interpreter
Click on + button on top right corner and you will get pop-up window of Available packages. Then search for pycuda python package.
Then click on Install package to install the package.

A: I solved it using these steps:

*

*Install Cuda Toolkit from NVIDIA website

*Open This link and download appropriate PyCuda whl file for your python version and system

*Install the  downloaded package using Anaconda

*Open PyCharm and install the package using Interpreter settings

*Enjoy PyCuda

Thanks


text:
Q: How to prevent a button from going to original state when refreshed I have a button #first which upon click is replaced with #second. After getting the second button and if I refresh the page I am going back to the first button. If I want my button to be the second button even after refresh how can I achieve this?
Thank in advance
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $("button").click(function() {
          $("#first").replaceWith('<button id="second">Second Button</button>');
        });
      });
    </script>
  </head>
  <body>
    <button id="first">firstbutton</button>
  </body>
</html>

A: set a cookie to persist the state of button and on document.ready,fetch the saved state and display it as such.

A: Use local storage and on window load just get the button state from there.
Example from : http://www.w3schools.com/html/html5_webstorage.asp
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

You could change this to :
      // Store
      localStorage.setItem("buttonState", "Second");
      // Retrieve
      var buttonState = localStorage.getItem("buttonState");

So in your case :
      var buttonState = localStorage.getItem("buttonState");
      $(document).ready(function() { //on document ready
        if(buttonState){ //check if buttonState exists
            if(buttonState === 'Second'){ //if button state = second
              //logic to change state to second
              $("#first").replaceWith('<button id="second">Second Button</button>');
            }
    }
        $("button").click(function() {
          $("#first").replaceWith('<button id="second">Second Button</button>');
          localStorage.setItem("buttonState", "Second");
        });
        }

So in your example, if you change state to second, save the state like about (setItem) and then retrieve that on document ready or window load.
Here is an example fiddle of it working : https://jsfiddle.net/wg7xL4sa/2/
Notice I have commented out the localStorage.clear(). Use this to reset your local storage.


text:
Q: Print pdf like a book - 2 pages per sheet double sided I have a pdf of a book, I wan't to print it, 2 pages per sheet double sided, so that I can cut the final in half, put the left part above the right part and get the book sorted by order.
How do I do this? Is there a standard way to do it, or a way to change the order of pages in a pdf by a mathematical formula?

A: 1. Open the PDF file in LibreOffice Draw
Each page will show up as a slide. Use Page Down and Page Up keys to navigate between pages. If the book looks OK to print, then proceed to the next step.
2. Use the File> Print> Page Layout Tab > Brochure button.

3. Then go to the General Tab > Properties Button

4. Paper Tab > Set the Duplex to Short Edge and then press OK

5. Press OK at the bottom of the Print window to print the book.
Hope this helps


text:
Q: Detect PnPEntity insertion I'm using a ManagementEventWatcher in C# to monitor WMI PnPEntity events.  My query is this:
"SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_PnPEntity'"
When I plug in a specific device that has already been inserted into the PC the event is raised and everything is fine.  However, if I insert a new piece of hardware of the same type (ie. PID and VID are the same, but a new DeviceID) the event is raised immediately, but the ConfigManagerErrorCode == 1 ("Device is not configured correctly").
The driver will then be installed for the device and if I remove the device and reinsert, everything is fine.
How do I detect when the driver has finished installing?  Is there a better event to watch besides __InstanceCreationEvent?
Thanks

A: Have you tried __InstanceModificationEvent instead and throw out the first ones when configuring a new device?
if you are looking at a specific device like a NIC or Hard Drive you may want to look for events on a different class since the one you are looking at is rather broad.
There are also some other P/Invoke Options here and here(have to convert the c++ to c#)


text:
Q: How can i append a an item only if it meets certain rules in python i would like to append an item into list_b only if it is one above '5H'  which is '6H'
list_a = ('2A','4A','8H','6H')
list_b = ['5H']

list_a.pop() gives a '6H'
therefore if i append the '6H' it should be able to be added to list_b since its just one above '5H'.
i tried to compare the first values but it gives an error because the 1 in the code below is an int and list_b[-1][0] is a str.
if list_b[-1][0] + 1 != list_a.pop()[0]:
    print('Error')

Therefore i cannot use list_b[-1][0] + 1

A: It should suffice to turn the character into the integer it represents by using int:
if int(list_b[-1][0]) + 1 != int(list_a.pop()[0]):
    print('Error')

A: First off, your list_a is a tuple, not a list. Check the parentheses.
If
list_a = ['2A','4A','8H','6H']
list_b = ['5H']

you can do something like:
while list_a:
    t = list_a.pop()
    if int(t[0]) == int(list_b[-1][0]) + 1:
        list_b.append(t)
    else:
        print 'Error'

to process the elements of list_a iteratively.

A: Presuming that list_a really is a list, not a tuple, otherwise list_a.pop() won't work ...
You need to do TWO things:
(1) convert the first characters to int so that you can compare them properly
(2) check that the second characters are the same ... from your problem description, it would appear that '6G' and '6I' (amongst many others) are not OK
b_value = list_b[-1]
a_value = list_a.pop()

ok = int(b_value[0]) + 1 == int(a_value[0]) and b_value[1] == a_value[1]

A: Use a list comprehension:
list_b.extend([i for i in list_a if int(i[0]) == (int(list_b[-1][0]) + 1)])


text:
Q: VBA Canceling SaveAs I've got part of the code:
Workbooks.Add
ActiveWorkbook.SaveAs filename:=Application.GetSaveAsFilename(fileFilter:="Excel Workbook (*.xlsx), *.xlsx")

So the user selects where and what name the workbook should have. However, if he clicks "Cancel" or tries to close the window, the workbook still saves under the name "False". How to stop that? The best solution would be to exit sub if the user clicks "Cancel" or closes the window

A:  Dim s as Variant
 s = Application.GetSaveAsFilename(fileFilter:="Excel Workbook (*.xlsx), *.xlsx")
 if s =  False then

else
     ActiveWorkbook.SaveAs filename:=s
end if

A: The method returns false when the user clicks Cancel, so you have to check for this case. Something like this should work for you:
fileSaveName = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
If fileSaveName <> False Then
   ActiveWorkbook.SaveAs filename := fileSaveName
End If

A: I recommend not to use ActiveWorkbook at all. Instead reference the newly added workbook directly.
Option Explicit

Public Sub SaveEample()
    Dim NewWb As Workbook
    Set NewWb = Workbooks.Add 'set the new added workbook to a variable so we can access it later

    Dim FileLocation As Variant
    FileLocation = Application.GetSaveAsFilename(fileFilter:="Excel Workbook (*.xlsx), *.xlsx")
    If Not FileLocation = False Then
        NewWb.SaveAs FileName:=FileLocation
    End If
End Sub

A: Using @Pᴇʜ code I modified my to work like I want to:
Set NewWb = Workbooks.Add
genpath = Application.GetSaveAsFilename(fileFilter:="Excel Workbook (*.xlsx), *.xlsx")
If Not genpath = False Then
NewWb.SaveAs filename:=genpath
Else
NewWb.Close
Exit Sub
End If


text:
Q: QuickBlox integration causes exception I could not find any good material for QuickBlox integration. I am coding for metro app and following official docs. that's written for WP7 but somewhere I also read its equivalent to windows 8.
Following is the code and error!
private const int AppID = 150;
private const int OwnerID = 4331;
private const string AuthKey = "8vXrOPEEXFacuEa";
private const string AuthSecret = "Up3AjdkjEDAzraL";

public QuickBloxSDK_Silverlight.QuickBlox QBlox
{ get; set; }

public MainPage()
{
     // QBlox is receive null and cause for exception
     this.QBlox = new QuickBloxSDK_Silverlight.QuickBlox(AppID, OwnerID,   AuthKey, AuthSecret);
     InitializeComponent();
 }

Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies wp7

A: QuickBlox doesn't support WP SDK yet
It's open sourced now, check it here https://github.com/QuickBlox/SDK-wp7
You can use it as is and try to port to Windows 8


text:
Q: How do You Hack the Enthought Canopy Editor Background Color? I use Enthought Canopy sometimes for writing python and I like the option to change the background of the interactive interpreter, but there is not an option for changing the background color of the editor.
I'd like to change the color to black(ish), if possible.  I think you could set it in the preferences.ini file, but I don't know the keywords and can't find any documentation on what arguments canopy accepts.  I think the setting would be in a file called preferences.ini, but I'm not sure, by any means.
Preferences.ini - Windows
C:\Users\\AppData\Roaming\Enthought\Canopy\preferences.ini
Preferences.ini - Mac
~/.canopy/preferences.ini
Here is an example of what the preferences.ini file looks like:
[sessions]
startup_mode = show_last_window
[python_frontend]
theme = linux
prompt_on_exit = True
[code_editor]
right_margin_enabled = True
right_margin_column = 80
smart_parenthesis_enabled = False
tab_completion_enabled = True
[accounts]
first_name = Brave
last_name = SirRobin
authenticated = True
[main]
font = 9 point Inconsolata Light

Has anyone done this or does anyone have any suggestions?

A: ConfigParser is made for that
it reads config file like you expect
for example
import configparser
config = configparser.ConfigParser()
config.read('preferences.ini')
['preferences.ini']
a=config.get('sessions','startup_mode')
print (a) # -> "show_last_window" show_last_window
b=config.get('python_frontend','theme')
print (b) # -> "linux" linux

A: I don't know a ton so this might be useless depending on what you mean by editor, but I know you can at least change the "kernel" window by going to edit > preferences > python tab and select dark background.
I prefer to work with it like this, even if I can't have it dark in the editor screen.


text:
Q: How to make gridview text align to middle and more fluid? Sorry, i am noob here. I tried to make my text to align to middle and not sticking to the border of the table. However, i tried numerous code horizontal align, cssclass in the properties and content keep not align in the middle.
So, how i fluid my gridview or make gridview the text align and not make it so cramp?

<asp:GridView ID="gvViewFeed" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True" CellPadding="4" style="align-items:center;" CssClass="table-bordered" DataKeyNames="FeedbackID" ForeColor="#333333" GridLines="None" Width="100%" OnSelectedIndexChanged="gvViewFeed_SelectedIndexChanged" HeaderStyle-CssClass="centerHeaderText" BorderStyle="Solid" CellSpacing="2" HorizontalAlign="Justify">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:BoundField DataField="FeedbackID" HeaderText="FeedbackID" >
                <ItemStyle Wrap="True" HorizontalAlign="Right" />
                </asp:BoundField>
                <asp:BoundField DataField="MemberID" HeaderText="MemberID" />
                <asp:BoundField DataField="DateTimePosted" HeaderText="DateTimePosted" />
                <asp:BoundField DataField="Title" HeaderText="Title" />
                <asp:BoundField DataField="Text" HeaderText="Text" />
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>
    </p>
    <asp:GridView ID="gvResponse" runat="server" AutoGenerateColumns="False" CellPadding="4" CssClass="Table" ForeColor="#333333" GridLines="None" Width="80%" style="align-items:center;">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
            <asp:BoundField DataField="ResponseID" HeaderText="ResponseID" />
            <asp:BoundField DataField="DateTimePosted" HeaderText="DateTimePosted" />
            <asp:BoundField DataField="Text" HeaderText="Text" />
        </Columns>
        <EditRowStyle BackColor="#999999" />
        <EmptyDataTemplate>
            No Record Found!
        </EmptyDataTemplate>
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#E9E7E2" />
        <SortedAscendingHeaderStyle BackColor="#506C8C" />
        <SortedDescendingCellStyle BackColor="#FFFDF8" />
        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:GridView>

A: Try this code:
<RowStyle HorizontalAlign="Center"></RowStyle>

<ItemStyle HorizontalAlign="Center"></ItemStyle>

For more information check MSDN GridView examples.

A: Add your controls in center rag in templatefield:
<ItemTemplate>
    <center>
        <asp:Button ID="btnEdit" runat="server" CssClass="btn btn-primary btn-sm" Text="EDIT" />
        <asp:Button ID="btnDelete" runat="server" CssClass="btn btn-danger btn-sm" Text="DELETE" />
    </center>
</ItemTemplate>


text:
Q: Trying to skip over several lines but the skipped lines are still being worked on My program takes an input file, reads the file using whitespace as the delimiter and puts the data into an array, then I want to iterate over each line and if certain strings are found write that info to another file.
When a specific string is found, I want to skip over several lines, meaning that these lines are NOT iterated over.  I thought that if I increased the 'line' variable (i) that would do it, but despite the fact that i is increased by 50, those 50 lines are still being worked on, which is not what I want.
Hopefully I have explained this problem well.  Thank you in advance for your feedback.
def create_outfile(infile):

    gto_found = 0
    outfile = "output.txt" # Output file
    outfile = open(outfile,'w') # Open output file for writing
    for i in range(len(infile)): # iterate over each line
        if len(infile[i]) == 6:
            if (infile[i][4][1:-1]) == "GTO" and gto_found == 0: # now skip
                print (i)
                print (infile[i])
                debugPause = input("\nPausing to debug...\n")
                i = i + 50 # Skip over the GTO section
                gto_found = 1
                print (i)
                debugPause = input("\nPausing to debug...\n")
                print (infile[i])

        for j in range(len(infile[i])): # iterate over each element

            # Command section
            if (infile[i][j])[:5] == "@ACS_":
                # Do some work

A: Unfortunately, python does not allow a for loop to jump up like that. The variable i cannot be edited inside the loop. This is same as this question here, so check it out. This other topic shows some work around that you could use.


text:
Q: execlp time doesn't show anything int main(int argc, char* argv[]){

   execlp("time", "time", NULL);

   return 0;
}

Nevertheless, if I add an argument to time like ls, it does work:
int main(int argc, char* argv[]){

   execlp("time", "time", "ls", NULL);

   return 0;
}

Output:
LICENCIA                main.c                  msh                     parser.y                prueba.c                scanner.o               y.tab.h
Makefile                main.o                  parser.o                prueba                  scanner.l               tempCodeRunnerFile.c
        0,00 real         0,00 user         0,00 sys

Any idea?

A: This works as expected. execlp("time", "time", NULL); is equivalent to executing /usr/bin/time (assuming that is what it resolves to; it could be different environments different from mine), and executing /usr/bin/time (again on my system, macOS 10.14.6) with no arguments does not print anything. I suppose other implementations of the time utility could print a message that no command to time was given and/or exit with an error code.
In contrast, execlp("time", "time", "ls", NULL); is equivalent to executing /usr/bin/time ls, in which case the time program executes ls and reports its times.

in the linux terminal if you type time it shows you the shell and child processes times…

When you type time in a command-line shell, it executes the shell's built-in time function, not the system time program. To reproduce this using execlp, you must use execlp to start a shell, not time, and you must pass the shell arguments to give it a time command to execute.


text:
Q: Pydev Debugger not working with breakpoints I have a simple test module:
print("fish")
print("sticks")

It runs pretty fast as expected, wether i use Run as or Debugg as does not matter.
But as soon as I enter a Breakpoint the Debugger starts (pydev debugger: starting (pid: 2696)) but does not reach the breakpoint nor finish the program(>5min).
I suddenly had this problem in a bigger project and created this test module to see if the debugger works. I did not change any settings in the prefrences menu of eclipse. I'm using python 3.x with the anaconda interpreter.
I restarted the computer and updated eclipse and pydev.

A: I found that deleting .metadata from the workspace solves the problem. But I have no clue what caused the issue.


text:
Q: Strict Standards: Non-static method modJumiHelper::getCodeWritten() should not be called statically I having these errors on my website:
Strict Standards: Non-static method modJumiHelper::getCodeWritten() should not be called statically in /home/kmxsiksf/www/modules/mod_jumi/mod_jumi.php on line 17
Strict Standards: Non-static method modJumiHelper::getStorageSource() should not be called statically in /home/kmxsiksf/www/modules/mod_jumi/mod_jumi.php on line 18
Here is the mod_jumi.php (line 17 and 18 start respectively with $code_written and $storage_source)
defined('_JEXEC') or die('Restricted access');
if(!defined('DS')){
    define('DS',DIRECTORY_SEPARATOR);
}
// Include the functions only once
require_once(dirname(__FILE__).DS.'helper.php');

$code_written   = modJumiHelper::getCodeWritten($params); //code written or ""
$storage_source = modJumiHelper::getStorageSource($params); //filepathname or record id or ""

if(is_int($storage_source)) { //it is record id
    $code_stored = modJumiHelper::getCodeStored($storage_source); //code or null(error]
}

require(JModuleHelper::getLayoutPath('mod_jumi'));

I found many solution for this problem to transform the function into a non static one but because I don't know much about PHP, I couldn't find a way to make them work.
Thanks a lot for your help!

A: This error is caused because the functions getCodeWritten and getStorageSource are not static functions.
i.e.
Instead of being declared like so:
public static function getCodeWritten()

They are being declared like this:
public function getCodeWritten()

Be warned that "fixing" this might cause other issues. Your best bet is to contact the people who created the extension.


text:
Q: Drop Down Alignment I am working on a supposedly simple drop down menu using HTML and CSS, and have encountered an issue. After scouring google and the forums to no avail, figured it was time to ask. I am trying to get the drop down menu to line up with it's parent element.
I have experimented with a few different methods, so far the most hopeful seems to be setting the "left:" value to the necessary percentage.
This brings up another issue though:
Issue: when I set the left value, I end up with a bunch of blank space to the right of the item that I can't seem to get rid of. Can't get the width right.
Code located here: https://jsfiddle.net/c6mz3t08/5/
HTML

Home

About

Menu 1

Menu 2

Header

Header

Header

CSS for dropdown
.horizontal li ul {
opacity:0;
visibility:hidden;
text-align:left;
position:absolute;
top:50px;
left:-38%;  //end up with blank space on right?
}

.horizontal li ul li {
position:relative;
background-color:#BBB;
display:block;
width:100%;
}

It seems the alignment problem happens because the
 starts after the word "About" in the second
.

A: a.) for positioning adjust the leftparameter in .horizontal li ul (-39px seems to work well).
b.) for the width of the submenus adjust the width parameter in .horizontal li ul li (70px worked well here, but depends on the content)

A: Do not guess on the left. The reason it is pushed to the right is because the ul has by default some padding.
Setting the padding to 0 and the left to 0 will fix this.
The space on the right is added because you set the width to 100%. If you remove the width it will fit its container. But that might not be what you want because the text will wrap, it might be better to set white-space:nowrap on it.
.horizontal li ul {
    opacity:0;
    visibility:hidden;
    text-align:left;
    position:absolute;
    top:50px;
    padding:0;
    left:0;   //using the LEFT parameter to get it in to alignment--end up with "blank" space on right?
}

.horizontal li ul li {
    position:relative;
    background-color:#BBB;
    display:block;
    white-space:nowrap;
}

Updated demo at https://jsfiddle.net/c6mz3t08/6/


text:
Q: How to sort list of string with number by grammar and number sequence? now i have a list of string with numbers which the string is a thai language like below.
mylist = ['เชียงใหม่_10_เขต', 'เชียงใหม่_1_เขต', 'เชียงใหม่_2_เขต', 'พะเยา', 'ภูเก็ต', 'กรุงเทพ']

And when i sort the list by grammar key with this code...
import pyuca
sort_key = sorted(mylist, key=pyuca.Collator().sort_key)

the character is sorted correctly but the string that have the same character but different number that not sorted by number like the output below.
['กรุงเทพ', 'เชียงใหม่_1_เขต', 'เชียงใหม่_10_เขต', 'เชียงใหม่_2_เขต', 'พะเยา', 'ภูเก็ต']

the output that i want is like this.
['กรุงเทพ', 'เชียงใหม่_1_เขต', 'เชียงใหม่_2_เขต', 'เชียงใหม่_10_เขต', 'พะเยา', 'ภูเก็ต']

So are there any way to do that.

A: You will need to extract the digits from the end of the string and cast them to int, otherwise the sorting will be lexicographic. You could use a regex to extract the alphabetical and decimal parts separately, and sort with a tuple of extracted (word, digit) pairs:
import pyuca
import re

def sorter(s, c):
    dig = 0
    l = re.split('(\d+)', s)
    alpha = []
    for i in l:
        try:
            dig = int(i)
        except ValueError:
            alpha.append(i)
    return c.sort_key(''.join(alpha)), dig

Now if we sort using the above transformation function:
c = pyuca.Collator()
sorted(mylist, key=lambda s: sorter(s, c))

['กรุงเทพ',
 'เชียงใหม่_1_เขต',
 'เชียงใหม่_2_เขต',
 'เชียงใหม่_10_เขต',
 'พะเยา',
 'ภูเก็ต']


text:
Q: Enviar e-mail por java Estou tentando enviar e-mail por java mas estou tendo um erro com o smtp. Meu código:
try {
        SimpleEmail mail = new SimpleEmail();

        mail.setFrom("teste.email.send@gmail.com", "Teste");
        mail.setSubject("E-mail exemplo");
        mail.setMsg("E-mail de exemplo");
        email.setStartTLSEnabled(true);
        mail.setAuthentication("teste.email.send@gmail.com", "********");
        mail.setHostName("smtp.gmail.com");

        mail.addTo("meu.email@gmail.com", "Lucas Souza");
        mail.setSmtpPort(587);
        mail.send();

    } catch (EmailException ex) {
        Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
    }

O erro que da é na linha do mail.send():
org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:467

Queria saber por que meu erro é no smtp 465 se estou colocando 587.

A: Você deve setar TLS ao invés de SSL:
try {
        SimpleEmail mail = new SimpleEmail();

        mail.setFrom("teste.email.send@gmail.com", "Teste");
        mail.setSubject("E-mail exemplo");
        mail.setMsg("E-mail de exemplo");
        mail.setStartTLSEnabled(true);
        mail.setAuthentication("teste.email.send@gmail.com", "********");
        mail.setHostName("smtp.gmail.com");

        mail.addTo("meu.email@gmail.com", "Lucas Souza");
        mail.setSmtpPort(587);
        mail.send();

    } catch (EmailException ex) {
        Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
    }

A: Tenho um exemplo que funciona perfeitamente, segue abaixo:
   public static void sendEmail() throws EmailException {

        SimpleEmail email = new SimpleEmail();
        // Utilize o hostname do seu provedor de email
        System.out.println("alterando hostname...");
        email.setHostName("smtp.gmail.com");

        // Quando a porta utilizada não é a padrão (gmail = 465)
        email.setSmtpPort(465);

        // Adicione os destinatários
        email.addTo("karanalpe@hotmail.com");

        // Configure o seu email do qual enviará
        email.setFrom("karanalpe@gmail.com", "Karan User");

        // Adicione um assunto
        email.setSubject("Lembrete de senha");

        // Adicione a mensagem do email
        email.setMsg("Lembrete de senha karanalpe ");

        // Para autenticar no servidor é necessário chamar os dois métodos abaixo
        System.out.println("autenticando...");
        email.setSSL(true);
        email.setAuthentication("seuEmail@gmail.com", "suaSenha");
        System.out.println("enviando...");
        email.send();
        System.out.println("Email enviado!");
    }

No pom.xml:
   <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.5.6</version>
        </dependency>
    </dependencies>

Vide post: http://karanalpe.com.br/tecnologia/back-end/enviando-email-com-o-java/


text:
Q: Python, Selenium : not able to find the fourth nested iFrames I am using Selenium in Python to automate some tasks on a webpage. The webpage has some nested iFrames, and I need to go deep into the fourth nested iFrame to click on a button. the first three nested iFrame can be fast switch to, but when it come to the fourth iFrame, I always get timeout error, even I've set the wait time up to 120s . Below is the Python code and HTML. iframe name="portalDisplay">is the third nested iframe and iframe name="ECMCOs" is the one I want to switch to and click a button inside it. Thanks!
browser.switch_to_default_content()
WebDriverWait(browser, 60).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,'//iframe[@id="content"]')))
WebDriverWait(browser, 60).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,'//div[@id="unique1"]/iframe[1]')))
WebDriverWait(browser, 60).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,'//div[@id="divPageBody"]/iframe[1]')))
WebDriverWait(browser, 120).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,'.//iframe[@name="ECMCOs"]')))

<iframe name="portalDisplay" src="emxPortalDisplay.jsp?portal=ECMEnterpriseChangeMgtPortal&header=EnterpriseChangeMgt.Label.ECMChangeCOsCAsLeagcySummaryPageHeading&emxSuiteDirectory=enterprisechangemgt&treeLabel=91852699+001&suiteKey=EnterpriseChangeMgt&StringResourceFileId=emxEnterpriseChangeMgtStringResource&SuiteDirectory=enterprisechangemgt&objectId=20336.41905.42762.46685" width="100%" height="100%" frameborder="0" border="0" cd_frame_id_="ca6315bf2f2783f6030dd845f480d61d">
#document

..

          ....

           <iframe name="ECMCOs" src="../common/emxIndentedTable.jsp?
 sortColumnName=Name&PrinterFriendly=true&SuiteDirectory=enterprisechangemgt&treeLabel=91852699+001&parentOID=20336.41905.42762.46685&emxSuiteDirectory=enterprisechangemgt&HelpMarker=emxhelpchangeordersection&program=enoECMChangeUtil%3AgetConnectedChanges&functionality=isChangeOrderTab&portalMode=true&StringResourceFileId=emxEnterpriseChangeMgtStringResource&toolbar=ECMChangeOrderManagementToolbar&sortDirection=ascending&selection=multiple&portalCmdName=ECMCOs&jsTreeID=null&suiteKey=EnterpriseChangeMgt&header=EnterpriseChangeMgt.Label.ECMChangeCOsCAsLeagcySummaryPageHeading&portal=ECMEnterpriseChangeMgtPortal&table=ECMChangeSummary&objectId=20336.41905.42762.46685" frameborder="0" width="100%">

TML snippetenter code here:

A: I think you were pretty close. Change the Locator Strategy from:
(By.XPATH,'.//iframe[@name="ECMCOs"]')
       ^ remove the dot

To:
(By.XPATH,"//iframe[@name='ECMCOs'][contains(@src,'/common/emxIndentedTable.jsp')]")

A: I finally manage to fit it by using the following code:
browser.switch_to_default_content()
iframe1 = WebDriverWait(browser,
120).until(EC.presence_of_element_located((By.XPATH,'//iframe[@id="content"]')))
browser.switch_to.frame(iframe1.get_attribute('id'))
iframe2 = WebDriverWait(browser,120).until
(EC.presence_of_element_located((By.XPATH,'//div[@id="unique1"]/iframe[1]')))
browser.switch_to.frame(iframe2.get_attribute('name'))
iframe3 = WebDriverWait(browser,120).until
(EC.presence_of_element_located((By.XPATH,'//div[@id="divPageBody"]/iframe[1]')))
browser.switch_to.frame(iframe3.get_attribute('name'))
time.sleep(20)
iframe4 = WebDriverWait(browser, 120).until
(EC.presence_of_element_located((By.XPATH,'//iframe[@name="ECMCOs"]')))
browser.switch_to.frame(iframe4.get_attribute('name'))

*

*use the frame name to switch (according to the advice here)

*the tricky is use time.sleep() instead of browser.implicitly_wait(). I've tried browser.implicitly_wait() previously, but even I've set browser.implicitly_wait(70), still didn't work, and I've tried to print out the first iframe from the current note(.//iframe[0] ) I got iframe @id="content", it feel like I did't switch the frame. My guess is using implicit wait, WebDriver kind of go out of the iframe when it poll the DOM  trying to locate an element. While using sleep, WebDriver will stay in the iframe


text:
Q: CANNOT PASS DEFAULT ARGUMENT C++, error: 'square' function does not take 0 argument //The header file
#include<iostream>
using namespace std;
int square(int);

//The actual code in square.cpp
int square(int x=10) {
    return x * x;
}

//The function call in mainapp.cpp
int main(){

    cout<< "Square is "<< square()<<"\n";
    return 0;
}


text:
Q: Two ways to execute a Stored procedure in VBA, Which one is better? Background: Work on frontend Ms-Access 2010 and backend SQL server 2008 Managment Studio
For executing stored procedures I have been using a pretty lengthy process as seen here: in VBA
    Set Conn = New ADODB.connection
    Conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;....."
    Conn.Open

    Set cmd = New ADODB.Command
    cmd.ActiveConnection = Conn
    cmd.CommandType = adCmdStoredProc
    cmd.CommandText = "upGetTestIdForAnalyte"

    cmd.Parameters.Append cmd.CreateParameter("@WOID", adVarChar, adParamInput, 60, MySampleName)
    cmd.Parameters.Append cmd.CreateParameter("@Analyte", adVarChar, adParamInput, 60, MyAnalyte)
    cmd.Parameters.Append cmd.CreateParameter("@SampleID", adVarChar, adParamInput, 60, MyConcentration

    cmd.Execute
    Conn.Close

Someone told me there was a better way to execute a stored procedure and the correct way would be something like this: in VBA
strsql = "Exec upGetTestIdForAnalyte(WOID, Analyte, SampleID)"
test = ExecuteNonQuery(strsql)

But I got a lot of errors for this process and I looked up ExecuteNonQuery and it said it was only for VB (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx). One of the advantages of this process would be its conciseness and the fact that it connects automatically to the current database.  I would have to change the connection string in my current sp process because it is set to link to a test database not the actual one.  Another advantage would be that it returns a value when executed.  I would like my current process to do that because I want to somehow verify it ran and other stored procedures I need to make, need to return the number of records affected.
My questions are:  Is the second method a legitimate process and is that the correct syntax?  Also is there any difference in what each process accomplishes?  Also is there a way for the first process to return a value when executed?  Thank you for your time.
UPDATE: This is my stored procedure I'm currently working on.  My sp sees if a testID exists or not, I will continue with the program after calling the sp if variable ThisTestId >0 else I will raise an error testid not found
CREATE PROCEDURE upGetTestIDForAnalyte @WOID nvarchar(60), @SampleID nvarchar(60),@Analyte nvarchar(60), @Test var(20) output
AS

  SELECT TestID = t1.TestID
  FROM tblWOSampleTest t1
  JOIN tblTest t2
  ON t1.TestID=t2.TestID;
  WHERE @WOID = t1.WOID AND @SampleID = t1.SampleID AND @Analyte = t2.Analyte

GO

A: The examples posted here have way too much code.
The original question is the poster has seen some examples where only one or two lines of code is required.
In fact this code works and passes a parameter to a store procedure.
With CurrentDb.QueryDefs("MyPass")
  .SQL = "exec MySproc" & ProducutID
  .Execute
End If

The above is only two lines of code.
The advantages of this approach?
Note how we did not have to mess (or pass) with a connection string.
Note how we did not have to declare any connection object in code.
Note how we did not have to store or have the user name or password anywhere in the code.
Note how we don't have to create a query def object in code either.
In fact the whole thing works without declaring ANY variables.
And the above could have been written on two lines of code, but I decided to post a massive 4 lines of code for increased readability.
The advantages of this setup are many, but the main reason is such an approach is MOST simple and easy to maintain.
The other posted solutions here serve only to force one to write many lines of code – this simply increases development costs for their employers.

A: I'll stay with first process and add an output parameter like this:
ccmd.parameters.Append ccmd.CreateParameter("OutParam", adInteger, adParamOuput, , NULL)   ' output parameter

You need to add this parameter in stored procedure as well like this:
@OutParam int OUTPUT

EDIT Added OUT parameter, changed to integer in VBA code. See how @@ROWCOUNT work
CREATE PROCEDURE upGetTestIDForAnalyte @WOID nvarchar(60), @SampleID nvarchar(60),@Analyte nvarchar(60), @RecordsAfected int OUT
AS

SELECT TestID = t1.TestID
FROM tblWOSampleTest t1
JOIN tblTest t2
ON t1.TestID=t2.TestID;
WHERE @WOID = t1.WOID AND @SampleID = t1.SampleID AND @Analyte = t2.Analyte
set @recordsAfected = @@ROWCOUNT
GO

A: From Microsoft help site:
   Function ExecuteSPT (sqltext As String, connectstring As String)

   ' Purpose: Run a temporary pass-through query.
   ' Accepts: sqltext: SQL string to run.
   '          connectstring: Connection string, which must be at least
   '          "ODBC;".
   ' Returns: nothing.

   Dim mydb As Database, myq As QueryDef
   Set mydb = DBEngine.Workspaces(0).Databases(0)

   ' Create a temporary QueryDef object that is not saved.
   Set myq = mydb.CreateQueryDef("")

   ' Set the ReturnsRecords property to False in order to use the
   ' Execute method.
   myq.returnsrecords = False

   myq.connect = connectstring
   myq.sql = sqltext

   myq.Execute
   myq.Close

   End Function

It can be easily altered to return as DAO.Recordset. DAO is still the "native" data access in MS Access.


text:
Q: Explanation of vector notation $x^Ty$ Its a pretty commonly used notation in Boyd's book: $x^Ty \leq b$ or $x^Ty \geq d$. Now since my linear algebra skills are not that good, I get confused with the term always.
How should I interprete the term $x^Ty \leq b$? For example, if $x = [1 , -2]$ and $y = [22 ,1]$, does $x^Ty > 0$ means every element of the new vector will be positive?

A: Usually vectors are represented as columns matrices, so:
$$
x=\begin{bmatrix}
1\\-2
\end{bmatrix} \qquad
 y=\begin{bmatrix}
22\\1
\end{bmatrix}
$$
so $x^T$ is a row matrix $x=[1,-2]$ and the product $x^Ty$ represents (in  the usual row-column product of matrices) the dot product of the two vectors
$$
[1,-2]\begin{bmatrix}
22\\1
\end{bmatrix} =22-2=20
$$
that is a number, so that make sense to have an inequality as $x^Ty \le b$

A: $x^Ty$ stands for a standard inner (scalar) product of two vectors.

A: Use a simple example, say $x=\begin{bmatrix}1 \\ 0\end{bmatrix}$ and $y=\begin{bmatrix}0 \\ 1\end{bmatrix}$. Cleary, they are orthogonal, i.e. $x^{\top}y=0$. Then for example $H:=\{z\in \mathbb{R}^2 | z^{\top}y>0$} denotes a certain set such that all vectors $z$ have a positively valued inner product with $y$, that means, $H$ is the upper half plane. Now if your vector $y$ is more "creative" this division of the space can be a "tilted" line. For the intuition, make some basics sketches!

A: It means:

*

*transposed x (from column matrix to row matrix)

*multiply (dot product)

*y (column matrix)

the result is a scalar value of the formula $x_1×y_1 + x_2×y_2 + x_3×y_3 + ... + x_n×y_n$
Hint:
vectors $x$ and $y$ are uses as column matrix (a matrix with exactly on column and N Rows)


text:
Q: getting used to my new job Are there good phrases to sound like a native speaker when you want to say you are getting used to your new job?

A: How's your new job?
B: _________________

A: MacMillan Dictionary
settle into
to become familiar with a new way of life, place, or job, or to make someone do this
adjust
to get used to a new situation by changing your ideas or the way you do things
grow into
if you grow into a situation or activity, you gradually start knowing what to do because you have more experience
slot in
to fit well with a group of people or a way of life
acclimate
American: to gradually become more comfortable in a new place, especially where physical conditions are very different
accustom yourself to something
formal: to gradually start to feel that something is normal or natural
get to know
to start to be familiar with someone or something
settle in
to become familiar with a new way of life, place, or job, or to make someone do this;
to make yourself comfortable in a place because you are going to stay there for a long time
get into the swing (of something)
to become used to a new situation and to feel confident that you can deal with it


text:
Q: What sorting algorithm would this be named? I have been asked to implement a Quick Sort algorithm however I may have failed to do so and implemented something else (that still sorts). However while searching for its name I have not been able to find its real name.
Complexity seems to be O(n*ln(n)) is O(n) if the list is already sorted and O(n*n) at worst.
Here is the code :
def sort(L):
    S = [L[0]]
    for i in range(1,len(L)):
        addEnd = True
        for j in range(len(S)):
            if L[i] < S[j]:
                addEnd = False
                S.insert(j, L[i])
                break
        if addEnd:
            S.insert(len(S), L[i])
    return S

Thank you for helping me !

A: Your function fails if the length of the input is empty. But apart from that (whose fix is trivial), a quick Hypothesis test could not find a counterexample.
It is a not-in-place insertion sort.
A single-element list is already sorted, so your initial result is the first element of the input.
Then you iterate over each remaining element of the input, and search its position in the always-sorted result and insert it there.


text:
Q: Replacing numbers in a string with a modified number using regex - Javascript I'm new to javascript so apologies if I've missed something simple. I'm working on a script to take a string from one cell in Sheets, add VAT at 5% to any applicable numbers and output the amended string in a new cell. I'm happy with the regex capturing the numbers I need, but getting the amended string correct is proving tricky.
So far the script looks like this:
function strReplace() {
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheet = ss.getActiveSheet();
   var str = sheet.getRange(4,2).getValue(); // A cell with a string like this: "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87"

   var regex = /\d{1,8}(?:\.\d{1,8})/g  // Regex to ignore numbers greater than 8 digits, including decimals

   var newStr = str.match(regex);

   for (var x = 0; x < newStr.length; x++) {

    var newRates = newStr[x]*1.05;
    var output = str.replace(newStr, newRates)

    sheet.getRange(4,3).setValue(output);

    }
  }

I've tried a bunch of variations but with no success. I feel there is an easier way to achieve what I'm looking for from what I already have. Any recommendations would be much appreciated.
Thanks!

A: To do this kind of thing, you use the function callback version of replace:

var str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
var regex = /\d{1,8}(?:\.\d{1,8})/g;  // Regex to ignore numbers greater than 8 digits, including decimals
var output = str.replace(regex, function(match) {
    return 1.05 * match;
});
console.log(output);

You might choose to use parseFloat(match) rather than just using match, which relies on * coercing the string to number.
And you might consider .toFixed(2) on the result to round and format to two places (depending on whether you want to round the way it rounds). For instance:

var str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
var regex = /\d{1,8}(?:\.\d{1,8})/g;  // Regex to ignore numbers greater than 8 digits, including decimals
var output = str.replace(regex, function(match) {
    return (1.05 * match).toFixed(2);
});
console.log(output);

A: basically your solution is very close, you just needed tot assign the str.replace, use the newStr[x] and also wait to end the for to assign it into the cell.
check the sample below.

function strReplace() {

  let str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
  var regex = /\d{1,8}(?:\.\d{1,8})/g

  var newStr = str.match(regex);

  for (var x = 0; x < newStr.length; x++) {
    var newRates = parseFloat(newStr[x]) * 1.05;
    str = str.replace(newStr[x], newRates)
  }

  return str;
}

var replaced = strReplace();

console.log(replaced)