text:
Q: VBA Destination Variable Copy issue My copy and paste code works fine when I test it IF there is already data in my destination. I need for it to work from scratch with no data for the department to begin inputing their own data. I notice that if I do not have data, it pastes over the top of my data range, or replaces data that is already there. I need it to start the first paste in cell E7 and then offset to the next row for each new set of data.
It seems to be breaking down at the Destination Variable(The whole code is posted below:
'destination variable
lstrow = Sheet3.Range("E" & Rows.Count).End(xlUp)
If lstrow < 5 Then lstrow = 5
Set DstRng = Sheet3.Range("E" & lstrow).Offset(1, 0)
Set DstRng = DstRng.Resize(SrcRng.Rows.Count, SrcRng.Columns.Count)

Entire Code
Sub CopyCells()
'unprotect all sheets
'Unprotect_All
'dim variables
Dim DstRng As Range 'destination range
Dim SrcRng As Range 'source range
Dim Proceed As Boolean ' do we wish to proceed
Dim checkRng As Variant ' values to check
Dim i As Integer
Dim lstrow As Long

'These are mandatory fields and the error message
checkRng = Array( _
            Array("E3", "Please add the Agent Name"), _
            Array("H3", "The Evaluation Date is missing"), _
            Array("J3", "The Call Date is missing"), _
            Array("M3", "The Call ID is missing"), _
            Array("Q58", "Please score this evaluation before saving") _
            )
'Set proceed to true so this is the case unless it changes
Proceed = True

'source variable
Set SrcRng = Sheet1.Range("Eval_Data")

'destination variable
lstrow = Sheet3.Range("E" & Rows.Count).End(xlUp)
If lstrow < 5 Then lstrow = 5
Set DstRng = Sheet3.Range("E" & lstrow).Offset(1, 0)
Set DstRng = DstRng.Resize(SrcRng.Rows.Count, SrcRng.Columns.Count)

'mandatory fields
For i = 0 To 4
    If Len(Sheet1.Range(checkRng(i)(0))) = 0 Then
        Proceed = False
        MsgBox checkRng(i)(1)
        Sheet1.Range(checkRng(i)(0)).Activate
        Exit For
    End If
Next i

' if proceed is all good then go ahead
If Proceed = True Then
'give the user a chance to exit here
    If MsgBox _
        ("You are about to finalize this Evaluation." _
        & vbCrLf & "Please check everything before you proceed", _
        vbYesNo Or vbExclamation, "Are you sure?") = vbYes Then

        'copy and paste data without selecting
        DstRng.Value = SrcRng.Value

        'add Eval number
        With Sheet1.Range("H4")
            .Value = .Value + 1
        End With

        'confirmation message
        MsgBox "The Evaluation has been saved"

        'clear the invoice
        ClearEval
    End If
End If
'reprotect
'Protect_All
End Sub

A:  lstrow = Sheet3.Range("E" & Rows.Count).End(xlUp)

'start at the bottom and go up until you hit an occupied cell or the top of the spreadsheet
 If lstrow < 5 Then lstrow = 5

'if you hit a row less than 5 then set your pointer to 5
Set DstRng = Sheet3.Range("E" & lstrow).Offset(1, 0)

'in a blank sheet we are now at E6
Set DstRng = DstRng.Resize(SrcRng.Rows.Count, SrcRng.Columns.Count)

'This won't move the top of dstrng from E6
" I need it to start the first paste in cell E7"
Can you spot the problem?

A: This can be effective way to accomplish what you need:
With sheet3
    lstrow = Application.WorksheetFunction.Max(7, .Range("E" & .Rows.Count).End(xlUp).Offset(1).Row)
    Set DstRng = .Range("E" & lstrow).Resize(SrcRng.Rows.Count, SrcRng.Columns.Count)
End With


text:
Q: html5 video onsuspend, onerror attributes not working I have a strange issue I cannot resolve with regards to video playback using html 5 controls specifically with chrome. I have 2 streams audio & video (each one with a different duration as the sound ends 10 seconds earlier), and got it pretty much working to sync and sync with seeking using the video seek bar.
If a video of type x-msvideo is attempted to playback, I expect chrome will not playback and that is exactly what happens (video control grays out as well) but I need to have the onerror function fire in order to ensure the audio does not play. In fact the onplay attribute still gets implemented. But it does not fire onError, and the onsuspend function fires regardless of type so I cannot use that either. Any suggestions on how to catch this occurrence. I cannot access the response content type either.
    vid.onerror = function() {
       aud.style.visibility = "hidden";
       aud.preload="none";
       vid.style.visibility = "hidden";
       aud.pause();
    }

    vid.onplay= function() {
            vid.style.visibility = "visible";
            vid.controls = true;
            if(!aud.ended && vid.currentTime <= aud.duration){
                aud.style.visibility = "visible";
                aud.controls = true;
                aud.play();
            }

A: Used the following work around for now:
    if (vid.readyState < 1) {
                aud.pause();
                return;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are iBeacon major/minor values available when monitoring a region? I am trying to build a test app that would detect a given set of iBeacon deployed in a few physical locations. The detection should be done in the background, and make a call to a server following a certain logic.
Apple's rule of thumb is using the same UUID for all of my physical locations:

The UUID is shared by all locations.
This allows an iOS device to use a single identifier to recognize any of the stores with a single region.
Each specific store, San Francisco, Paris, and London, is then assigned a unique major value, allowing a device to identify which specific store
it is in.

I found the call for setting a region with a given UUID, but did not find what object is returned when the UUID is detected, and what fields are returned.
Where does the app get the major/minor value when iOS detects a beacon with a given UUID?

A: When using monitoring APIs, you only get a CLBeaconRegion object in the enter/exit callback from CoreLocation.  A beacon region defined by this class typically doesn't represent individual beacons, but a range of beacons based on wildcard identifiers.
Because of this, if you use wildcards in your region definition (as is typical) you actually can't see which specific beacon triggered a region entry.  To solve this problem, you must combine both monitoring and ranging APIs at the same time.  If you monitor and range simultaneously, CoreLocation will give you a callback in the didRangeBeacons beacons: [CLBeacon] inRegion region: CLBeaconRegion method with an array of all the CLBeacon objects it saw.
Because the callback with the array of beacons arrives once per second, however, you will need to add custom logic to do something only once when beacon first appears, if necessary.
Since you want background detection, it is important that you do both ranging and monitoring simultaneously.  Even if you don't put anything in your monitoring callback because of the lack of specific beacon information, you need to do monitoring just to get your app woken up in the background on a new beacon detection.  Then, you will get ranging callbacks for approximately 10 seconds before your app is suspended again.


text:
Q: Getting SQLite database and storing it in an array of objects I'm looking at the Notes app example from the Android SDK. What I want to learn how to do is instead of using a CursorAdapter to just pass to a ListAdpater/ListView to sort out, I want to know how I can deal with the data myself; particularly in an ArrayList form.
In the example, a note basically has an id, title, and body. I want to know how I can query the SQLite database and use the cursor it returns to collect the data and create object instances of an object I'll call Note which has parameters for id, title, and body. I ultimately want to store all these objects into an ArrayList for management. I'm just not sure how to deal with a Cursor.
This is a pretty general question but I just need someone to point me in the right direction.

A: I might not get your question but you need to query your db then add cursor data to ArrayList?
    List<String> pointsList = new ArrayList<String>();
    database = openOrCreateDatabase("favorites", SQLiteDatabase.OPEN_READWRITE, null);
    if(database!=null)
    {
        c= database.rawQuery(QUERY, null);
        c.moveToFirst();
        while(c.isAfterLast()==false)
        {
            pointsList.add(c.getInt(c.getColumnIndex("id")); // do the same for other columns
            c.moveToNext();
        }

    }
   database.close();
   c.close();

A: Actually I figured it out myself after playing around. So I realized that using cursor.getColumnIndex("name_of_column") will return the column's index to be used in commands like cursor.getInt(cursor.getColumnIndex("_id"));. All I have to do is just use a for loop to go through the whole list and use cursor.moveToNext() to just iterate through the rows collected. I came up with this minutes after I posted this question. :)

A: This might help you,
   public ArrayList<ArrayList<Object>> getAllRowsAsArrays()
    {
        // create an ArrayList that will hold all the data collected from
        // the database.
        ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();

        // This is a database call that creates a "cursor" object.
        // The cursor object store the information collected from the
        // database and is used to iterate through the data.
        Cursor cursor;

        try
        {
            // ask the database object to create the cursor.
            cursor = db.query(
                    TABLE_NAME,
                    new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO},
                    null, null, null, null, null
            );

            // move the cursors pointer to position zero.
            cursor.moveToFirst();

            // if there is data after the current cursor position, add it
            // to the ArrayList.
            if (!cursor.isAfterLast())
            {
                do
                {
                    ArrayList<Object> dataList = new ArrayList<Object>();

                    dataList.add(cursor.getLong(0));
                    dataList.add(cursor.getString(1));
                    dataList.add(cursor.getString(2));

                    dataArrays.add(dataList);
                }
                // move the cursor's pointer up one position.
                while (cursor.moveToNext());
            }
        }
        catch (SQLException e)
        {
            Log.e("DB Error", e.toString());
            e.printStackTrace();
        }

        // return the ArrayList that holds the data collected from
        // the database.
        return dataArrays;
    }


text:
Q: Checking with Cloud Function if a database node exists in Firebase Realtime Database I have a onUpdate Cloud Function and I need to check if a database node exists.
For my the ideal way to do it would be:
exports.watchTeamMemberUpdates = functions.database
  .ref('/teams/{teamName}')
  .onUpdate((change) => {
     if (!change.before.exists()) {
       console.log('exists error');
       return null;
     }
});

But it requires a snapshot and i'm giving it a promise.
Is it possible to check if the file exists with the promise in any way?
Also is there a better way to make snapshots other than .once.then?

A: I make the assumption that by writing "I need to check if a file exists" you mean checking if a database node exists (i.e. the team member saved under team name). I've taken the liberty to modify your question title and content accordingly.

Note that if you want to detect if the team member didn't exist with an onUpdate() trigger, you will not succeed, because this Cloud Function will only be triggered if the node existed before, since we watch for updates (not for creation).
So you should probably use an onWrite() trigger. Below is the code for the two types of trigger. I would suggest you try several writes and updates in your database (after having deployed theses two functions, of course) and look what is printed to the Cloud Function log.
exports.watchTeamMemberUpdates = functions.database
  .ref('/teams/{teamName}')
  .onUpdate((change, context) => {
    if (!change.before.exists()) {
      console.log('watchTeamMemberUpdates: exists error');
      return null;
    } else {
      console.log('watchTeamMemberUpdates: Team member exists');
      return null;
    }
  });

exports.watchTeamMemberWrites = functions.database
  .ref('/teams/{teamName}')
  .onWrite((change, context) => {
    if (!change.before.exists()) {
      console.log('watchTeamMemberWrites: exists error');
      return null;
    } else {
      console.log('watchTeamMemberWrites: Team member exists');
      return null;
    }
  });

PS: Note that the handler to be passed to the onUpdate(handler) method is a function with two arguments, see https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onUpdate. However the second is optional. This is the same with the onWrite(handler) method.


text:
Q: Default path to install Nexus Docker Container from AWS EC2 Where can I find the default path for Sonatype Nexus (Example: /nexus), MongoDB, Postgres, Jenkins etc. in order to install Docker containers from AWS ECS using Application Load Balancer? I need to create a new Target Group and add the path inside Health Check Settings Path so I can load balance all the applications such as Sonatype Nexus, Jenkins, Centos, Postgres, MongoDB etc.

A: Generally speaking, docker containers with web applications are deployed by convention on "/", and joining the webapp is more a question of port than path.
You can find information about port on official docker hub or store website (nexus, jenkins, etc...)
          |  Path  |  Port  | Docker run example
Nexus 3   |   /    |  8081  | docker run -p8081:8081 --name nexus sonatype/nexus3
Jenkins   |   /    |  8080  | docker run -p8080:8080 --name jenkins jenkins

For your databases, same idea, you don't have a "path" to specify to connect to them. You just need to map ports and either publish them, link containers, or use docker network.
For instance for postgres:
docker run --name some-postgres -p5432:5432 -e POSTGRES_PASSWORD=mysecretpassword -d postgres

Then join the database with something like :
//host:5432/db

Your AWS ELB would balance the trafic for webapps using Target Group (HTTP / HTTPS), but I don't think you can do that for database (TCP only).
I guess databases would use Classic Load Balancer.


text:
Q: Calling PowerShell's where-object from C# How can I call Where-Object (without filter) from C#? I can't parse output, because I want to pass it to pipeline(not in example below).
PS:
Get-MailboxPermission username | Where-Object {$_.AccessRights -match "FullAccess" -and $_.IsInherited -eq $False}

C#:
Collection<PSObject> results = null;

Command command1 = new Command("Get-MailboxPermission");
command1.Parameters.Add("Identity", mailbox);
command1.Parameters.Add("DomainController", _domainController);
//I cannot use Filter. This is not possible in PS also.
//command1.Parameters.Add("Filter", "AccessRights -match \"FullAccess\"");

This question is simmilar to: PowerShell WhereObjectCommand from C# That answer is not enough for my problem.

A: Check the below code sample. I have updated a sample from code project here as per your requirements.
Note:

*

*To add quotes to your command i.e. script text escape quotes by using \"

*To add { or } brace to the script text use double curly braces instead to escape it inside String.Format like {{ or }}
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();

// open it
runspace.Open();

// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();

//Getting all command variables
string computerName = "YourComputerName";
string matchingPattern = "con";

//Create Script command
String customScriptText = String.Format("Get-Process -ComputerName {0} | Where-Object {{$_.ProcessName -match \"{1}\"}}", computerName,matchingPattern);

pipeline.Commands.AddScript(customScriptText);

// add an extra command to transform the script output objects into nicely formatted strings
// remove this line to get the actual objects that the script returns.
pipeline.Commands.Add("Out-String");

// execute the script
Collection<PSObject> results = pipeline.Invoke();

// close the runspace
runspace.Close();

// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
    stringBuilder.AppendLine(obj.ToString());
}

When you apply the above working sample to your problem you will need to change couple of lines like below:
    //Getting all command variables
    string username = "YourUserName";

    //Create Script command
    String customScriptText = String.Format("Get-MailboxPermission {0} | Where-Object {{$_.AccessRights -match \"FullAccess\" -and $_.IsInherited -eq $False}}", username);


text:
Q: Regular expression that defnes the set of all words I'm trying to write a regular expression that defines the set of all words written in lower case characters and digits that contain a binary number.
My idea:
$(\varepsilon |[a-z]^{*})(\varepsilon |(0|1)^{*})(\varepsilon |[a-z]^{*})(\varepsilon |(0|1)^{*})$
Is my solution correct?


text:
Q: Uniform convergence of Taylor series for arcsin(x) After proving $$  \ \arcsin{x}=\sum_{n=0}^{\infty} \frac {c_n}{2n+1}{x^{2n+1}} $$ $\forall x\in(-1,1)$ where $c_n=\frac {(2n)!}{2^{2n}(n!)^{2}}$
Since $\arcsin{x}$ continuous on $[-1,1]$, explain why the Taylor series for $\arcsin{x}$ converges uniformly to $\arcsin{x}$ on $[-1,1]$.

The context of this question is; after deriving $E_n(x)=1/N!\int_{0}^{x}f^{n+1}(t)(x-t)^ndt $.
I let $f_n(x)= \frac {c_n}{2n+1}{x^{2n+1}}\leq\frac {c_n}{2n+1}{k^{2n+1}}=M_n$ where $k\geq x,  \lvert{k}\rvert<1$
Then I used ratio test on $M_n$ for $(0,1)$ and Raabe's test for the endpoints. For uniform convergence I used M-test. This process yields the proof of uniform convergence.

But I have found this solution to be rather unsatisfactory, Is there an alternate proof of this fact without using a convergence test, for example, using $E_n(x)$?

A: It is known that
$$
c_n  \le \frac{1}{{\sqrt {\pi n} }}
$$
for all $n\geq 1$. Hence, for $-1\leq x \leq 1$,
\begin{align*}
\left| {\sum\limits_{n = 0}^\infty  {\frac{{c_n }}{{2n + 1}}x^{2n + 1} } } \right| & \le \sum\limits_{n = 0}^\infty  {\frac{{c_n }}{{2n + 1}}\left| x \right|^{2n + 1} }  \le \sum\limits_{n = 0}^\infty  {\frac{{c_n }}{{2n + 1}}} \\ & \le 1 + \sum\limits_{n = 1}^\infty  {\frac{1}{{\sqrt {\pi n} }}\frac{1}{{2n + 1}}}  \le 1 + \frac{1}{{2\sqrt \pi  }}\sum\limits_{n = 1}^\infty  {\frac{1}{{n^{3/2} }}}  <  + \infty .
\end{align*}
Thus, the series converges absolutely and uniformly for all $-1\leq x \leq 1$.


text:
Q: PHP extract number only from result explode I have explode here is the result of var_dump:

and I want get the result from explode:
7 [remove other string]
0 [if contain "-"]
0 [if contain "-"]
0 [if contain "-"]

Here, I just used comma as delimiter:
var_dump (explode(",", $rowData[0][13]));
die();

Does anyone have the solution to solved this?
Thank You.

A: Use array_map() function and in it use filter_var() to sanitize number value.
Try
$rowData = ['JJ7', 'B-', 'S-', 'M-'];

$result = array_map(function($v) {
    return abs((int) filter_var($v, FILTER_SANITIZE_NUMBER_INT));
}, $rowData );

var_dump( $result );

//output
// array(4) { [0]=> int(7) [1]=> int(0) [2]=> int(0) [3]=> int(0) }

A: <?php
$data_result = explode(",", $rowData[0][13])

for($data_count=0;$data_count<count($data_result);$data_count++)
{
    if(substr($data_result[$data_count], -1) == '-')
    {
        echo $data_result[$data_count]
    }
}
?>


text:
Q: Change function into dependencyproperty I am new to XAML and WPF and I am learning about DependencyProperty and Path. For example, I have a function like this
public byte[] DownloadPicture()
{
    WebClient webClient = new WebClient();
    byte[] data;
    data = webClient.DownloadData("https://graph.facebook.com/4/picture&type=large");
    return data;
}

and I have dependencyproperty like this
public static DependencyProperty DownloadPicProperty =
DependencyProperty.Register("DownloadPic", typeof(byte),
    typeof(ImageControl), new PropertyMetadata(false));

How can I connect the DependencyProperty with the DownloadPicture function I wrote? Any suggestions? What should I write in the CLR wrapper?

A: You can get and set the value of a dependency property by adding a standard property to the control as well.
public static DependencyProperty DownloadPicProperty =
    DependencyProperty.Register("DownloadPic", typeof(byte[]), typeof(ImageControl));

public byte[] DownloadPic
{
    get { return (byte[])GetValue(DownloadPicProperty); }
    set { SetValue(DownloadPicProperty, value); }
}

...
ImageControl imageControl = ...;
imageControl.DownloadPic = DownloadPicture();


text:
Q: From the cluster, cannot download a Python Wheel from the storage account 1) We upload a python wheel to the storage account associated with the workspace successfully.
2) In the second step we submit an experiment which runs in the cluster and needs to download and run the package from step 1.
The experiment is able to download the package and run when the storage account is not associated with any VNet. However, when we associate the storage account in Vnets the experiment hangs and eventually fails. This storage account is in two Vnet's, a, and b. The cluster is also in the Vnet, a.
I don't know why the cluster cannot download the wheel package when the storage account is in a Vnet. It is our policy to have storage accounts in Vnet's.
It there something else we are missing? I also checked the container registry setting and its set to 'allow from everywhere' (we are using std SKU).
Let me know if any further information is required. Thanks.


text:
Q: How can I control an app on my iOS device from Mac or PC I would like to take control of my app on an iOS device (mostly an iPhone) from my MacBook Pro or Windows, doesn't matter which one.
I know that it can be accomplished via Veency, and that's exactly what I need - but I do NOT want to jailbreak my iPhone.
Is there a similar legal alternative?
If not - is it something I could develop perhaps, or will I run into some SDK limitations for such a thing?

A: All iOS SDK apps work within a security sandbox, and thus have no access or control over any other apps (with a few tiny exceptions for registered URLs). You could take control of you own app, but no others, including Apple's, on a stock OS device.

A: I found solution using TeamViewer QuickSupport. Install quicksupport for ios on iphone and connect using teamviewer.
I can't test, it requires ios11.

A: Turn on Home Sharing using Remote
1.Connect iPhone, iPad, or iPod touch to a Wi-Fi network on the same local network as your Mac, PC, or Apple TV.

*Open the Remote app on your iOS device.

*Turn on Home Sharing from the Remote Settings screen.

*Sign in to the same Apple ID you used on your other devices.


text:
Q: Updating domain instances in beforeUpdate method calling the method infinitely I have a domain class and I need to update some values of other instances of the same domain on updateBofore method. But it is going to be run infinitely. Is there any way to update only once?
Class ABC {

    String name
    String ref

    def beforeUpdate() {
        List abcs = findAllWhere(ref: ref)
        abcs.each {
            it.name = name
            it.save(flush: true)
        }

    }
}

A: You need to modify your beforeUpdate method like:
def beforeUpdate() {
    def currentInstance = this

    ABC.withNewSession {
        List abcs = ABC.withCriteria {
            eq("ref", currentInstance.ref)
            // Make sure we don't again update the same current instance
            ne("id", currentInstance.id)
        }

        abcs.each {
            it.name = currentInstance.name
            it.save(flush: true)
        }
    }
}

The two things are changed in your beforeUpdate method:

*

*Using withNewSession so that the new save() operation should not try to flush the current hibernate session (which would result in infinite  loop)

*Using ne() criteria to exclude the current instance from being updated since you are already updating the current instance.

A: Use the before insert gorm event without iterating all list and calling save.
class ABC {
    //your defs here

    def beforeInsert()
        List abcs = findAllWhere(ref: ref)
        if(abcs){
          this.name = abcs.first().name
        }
    }
}

You have to call save outside the domain class
ABC a = new ABC()
a.save()

And the beforeInsert make the trick


text:
Q: fundamental group of quotient (singular) tori What we know about fundamental group of quotient singular manifold?
I'm particularly interesting in the case of quotient given by $X:=T/G$ where $T$ is a complex torus and $G$ is finite.
Since $\pi_1$ is a topological objet how the singular of $X$ can affect it? I mean $X$ is endowed with the quotient topology so the loop are defined in the usual way?
But then if I take any resolution $\widetilde{X}$ how $\pi_1(\widetilde{X})$ is related with $\pi_1(X)$? Does this relation depend of the type of singularities (canonical, terminal..)? But I wanna to know it not only in the case of isolated singularities but in the general case.. so maybe it depends only on the codimension of the locus of points with non trivial stabilizer (?)
I know that it can be related with the notion of orbifold, but I don't have too much background on it so if it is necessarily can anyone suggest me a good reference on it?
Thanks!


text:
Q: Require that part of regex range must be present while other is optional I have data like so:
01Jun18 324567645
01Jun18 Addfd
01Jun18 112 Word
01Jun18 fjfs7dfsfj
01Jun18 kdkd
01Jun18 0sdfnefk
01Jun18 skfks7sfsff
01Jun18 sfrfsf8srfsr

I want all lines except the first to match. The string can contain numbers, but it cannot except just numbers alone - there MUST be a letter present too.
So far I am using, but this matches all rows:
([\d]{2}[A-Za-z]{3}[\d]{2}) ([A-Za-z\d ]{1,})

Any ideas on how or if this can be achieved? I have tried using + to mark the A-Z as required

A: ^([\d]{2}[A-Za-z]{3}[\d]{2}) [0-9 ]*[a-zA-Z]+[0-9a-zA-Z ]*$

A: You may use
preg_match_all('~^(\d{2}[A-Za-z]{3}\d{2})\h+(?!\d+$)([A-Za-z\d\h]+)$~m', $s, $matches)

You may even replace ([A-Za-z\d\h]+) with (.*) if you just want to match the rest of the line without caring about what chars there may be.
See the regex demo
Details

*

*^ - start of the line (due to m modifier)

*(\d{2}[A-Za-z]{3}\d{2}) - Group 1: two digits, three ASCII letters, two digits

*\h+ - 1 or more horizontal whitespaces

*(?!\d+$) - a negative lookahead that fails the match if there are only digits to the end of the line

*([A-Za-z\d\h]+) - Group 2: one or more chars that are letters, digits, or horizontal whitespaces

*.* - matches any 0+ chars other than line break chars as many as possible

*$ - end of the line.


text:
Q: How can i get variable's value from servlet in jsp? I've read a lot about the same question, I tried to follow the answers but it never work.
I have a servlet name: get_import.java
I have a jsp name: import.jsp
First, in processRequest(), i initiated a String s = "abcdef", then i wrote:
s=request.setAttribute("validate", s);
RequestDispatcher rd = getServletContext().getRequestDispatcher("import.jsp");
rd.forward(request,response);

Then, in import.jsp, i wrote:
<%  String st = (String)request.getAttribute("validate");
    out.println("
Result: " +st+ "
");
%>

Then output was:   Result: null
I can't explain why the variable's value is null in jsp, please help me to solve this problem or find other way out. Thanks a lot!!

A: You have a number of options:
1.Store it in the session.
String username = request.getParameter("username");
if (username != null && username.length() > 0)
{
 session.setAttribute("username", username);
}

2.Store it as a hidden field in the form.
<input name="filter" type="hidden" value=""/>

3.Store it in a cookie.
username = getCookie(userCookieName);

// Get from cookie.
 function getCookie(name) {
    if (document.cookie) {
           index = document.cookie.indexOf(name);
           if (index !== -1) {
           f = (document.cookie.indexOf("=", index) + 1);
           t = document.cookie.indexOf(";", index);
             if (t === -1) {
               t = document.cookie.length;
               }
             return(document.cookie.substring(f, t));
           }
      }
 return ("");
}

4.Not really another option but a mechanism - pass it in the URL:
.... onclick="window.location = 'details.jsp?filter=...'

A: try storing the value in session like this way
session.setAttribute("validate", s);

Then, in import.jsp, :
<%  String st = (String)session.getAttribute("validate");
    out.println("
Result: " +st+ "
");
%>

One side note try avoiding writing java in jsp pages.Best alternate is JSTL/EL


text:
Q: React JS | Render Multiple Elements I am trying to create a email in React using the MJML email library. It runs off react and I have it all working but I need to render 2 sections rather than 1. When I render 1 it doesn't appear properly on the webpage as I need them to be different sizes.
When I try and wrap the elements within a array the return become null, take out one of the sections and it gets returned.
Any help would be appreciated, here is the code.
render() {
    const { mjAttribute } = this.props
    const content = [this.renderEmailOverhead()]
    const innerContent = [this.renderEmailBanner(), this.renderEmailTitle(), this.renderEmailText(), this.renderEmailDivider]

    return ([

            { content }

,

            { innerContent }

    ])
}

A: Well, render method of a component can only return one element. so you'll have to wrap it in a divas Zargold mentioned.
Note that MJML component are more than a standard React component.
It has some internal logic not available in a React context. IMO you should generate MJML as standard HTML element and render it with a renderToStaticMarkup then pass it to mjml2html function as a string and mjml will compiles
 return (
   <mjml>
     <mj-body>
       <mj-container>
         ... // your sections goes here
       </mj-container>
     </mj-body>
   </mjml>
 )

Note that I don't think React is the best suited for this kind of work, I would recommend you to use a templating language such as mustache/handlebars which fit better.

A: You cannot use JSX interspersed with JavaScript like that... you could either do (you must have only one parent/root element).

    { content }

    { innerContent }

Or You could if you insist on using an array for some reason:
renderSection(content, fullWidth){
return (

  {content}

)
}
render(){
 let contents = [content, innerContent]
return(

    {contents.map(section, i => renderSection(section, i % 2 === 0))

)


text:
Q: Resource to improve ability to interpret and understand formulas and algorithms I wasn't sure whether this belonged here or on StackOverflow but here goes:
I've been doing a lot of research into algorithms recently and I've found that my inability to properly interpret and understand some of the formulas and algorithms is starting to impede my ability to get anything meaningful enough to go off and write a program to implement the algorithms described.
Is there any resource (online prefered but books are ok) you could recommend I use that is for total beginners? Even though I'm (mainly) a programmer, I don't think knowing 5+ languages are worth anything unless I can change the simple fact that my mathematical abilities are merely average.
I'd prefer something that starts off utterly simple and builds up to the more complex/abstract stuff. If it had Pseudo code or an actual implementation, even better. Any recommendations?

A: I think "Introduction to Algorithms" by Cormen is the standard reference for this. Also, I found "Concrete Mathematics - A Foundation for Computer Science" to be very enjoyable. The first one really concentrates on the theory of algorithms while the second one is more about mathematics.


text:
Q: How to disable swiping on click in Swiper.js? I'm trying to disable Swiper.js functionality on a certain carousel in Elementor (Wordpress). I need it not to move slides on grab/click of a mouse.
jQuery(document).ready(function($) {
            $(window).on('load', function () {
                    const swiper_target = jQuery ( '#shiplion_swiper .swiper-container' );
                    const swiperInstance = swiper_target.data('swiper');
                    swiperInstance.slideTo(3);
                    swiperInstance.allowTouchMove(false);

            });
});

Here is what I used to control parameters of Swiper.js instance within Elementor. For example swiperInstance.slideTo(3); definitely works. While .allowTouchMove does not, giving me console error "Uncaught TypeError: swiperInstance.allowTouchMove is not a function"


text:
Q: Why do pro Zerg players build their Lair at their natural? Lately in LotV, I've seen professional Zerg players build their lair at their natural (at least, against Terran) rather than in their main base. Why? Wouldn't the main be a safer choice?

A: Safer but not Stronger
According to this Reddit Post:

Most people that lair at the nat in ZvP and ZvT do it because it's easier to defend and less likely to be dropped, which is also why many people don't throw all their tech buildings in the main either. Side benefits are that it also punishes a terran that scans the main instead of the natural.


text:
Q: Apply strip() to all cells in dataframe with multiple data types I have a dataframe that has multiple data types. Part of my processing code is to apply the strip() function before I work on the df.
My example df:
Unnamed: 1      Unnamed: 2      Unnamed: 3  Unamed: 4
Protocol Number NaN             NaN         5
xyz-4134        NaN             3           NaN
Section FINANCE Cost Category   Major Tasks # of Units
NaN             1325            some string NaN

Here is my code:
df.applymap(lambda x: x.strip() if type(x) == str else x)

It doesn't seem to be processing for all strings though. I'm still seeing spaces before and after in some of my output cells.
Question
Is there a better way to apply strip() to my entire raw dataframe? In the above input dataframe, the # of Units  has a trailing white space and the  some string has a leading white space

A: Incorporating the suggestions by both IgnatiusReilly & Rabinzel, this worked for me:
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)

Also worth noting, the reason the # of Units was keeping the trailing space was because I used used applymap after I already assigned that row as the headers. I moved the cleaning before the header assignment and it worked.


text:
Q: Css3 transform not applying I m trying to achieve this.
The smooth hover animation is not applied and the image goes up beyond the div (as shown in pic) in Chrome.

ASPX:

      <asp:Image ID="img" runat="server" width="100%" height="150px"
       Imageurl="~/abc.jpg"/>

Test

CSS:
.favDiv
{
//to centre div in the page
display:inline-block;
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
width:65%;
height:65%;
margin:auto;
}
.grid
{
border:1px solid gray;
height:150px;
}
figure
{
padding:0;
margin:0;
position:relative;
}
figCaption
{
position:absolute;
    top:0;
    left:0;
    width:100%;
    background:#2c3f52;
    color:#ed4e6e;
}
figCaption h5
{
    margin:0;
    padding:0;
    color:#fff;
}
.effect figure
{
    overflow:hidden;
}
.effect figure:hover img
{
    -webkit-transform:translateY(-50px);
    -moz-transform:translateY(-50px);
}
.effect figCaption
{
    height:50px;
    width:100%;
    top:auto;
    bottom:0;
    opacity:0;
    -webkit-transform:translateY(100%);
    -moz-transform:translateY(100%);
    -webkit-transition:transform 0.4s, opacity 0.1s 0.3s;
    -moz-transition:transform 0.4s, opacity 0.1s 0.3s;
}
.effect figure:hover figCaption
{
    opacity:1;
    -webkit-transform:translateY(0px);
    -moz-transform:translateY(0px);
    -webkit-transition:transform 0.4s, opacity 0.1s 0.3s;
    -moz-transition:transform 0.4s, opacity 0.1s 0.3s;
}

What am i missing here?

A: Your code is not working because Tympanus wrote styles for non-touch devices. Its defined by mordernizr (Automatically add class to body).
I have modified the fiddle. Now its working fine.
Working Demo
HTML

test

CSS
.grid {
    padding: 20px 20px 100px 20px;
    max-width: 1300px;
    margin: 0 auto;
    list-style: none;
    text-align: center;
}

.grid li {
    display: inline-block;
    width: 440px;
    margin: 0;
    padding: 20px;
    text-align: left;
    position: relative;
}

.grid figure {
    margin: 0;
    position: relative;
}

.grid figure img {
    max-width: 100%;
    display: block;
    position: relative;
}

.grid figcaption {
    position: absolute;
    top: 0;
    left: 0;
    padding: 20px;
    background: #2c3f52;
    color: #ed4e6e;
}

.grid figcaption h3 {
    margin: 0;
    padding: 0;
    color: #fff;
}

/* Caption Style 3 */
.cs-style-3 figure {
    overflow: hidden;
}

.cs-style-3 figure img {
    -webkit-transition: -webkit-transform 0.4s;
    -moz-transition: -moz-transform 0.4s;
    transition: transform 0.4s;
}

.cs-style-3 figure:hover img {
    -webkit-transform: translateY(-30px);
    -moz-transform: translateY(-30px);
    -ms-transform: translateY(-30px);
    transform: translateY(-30px);
}

.cs-style-3 figcaption {
    height: 30px;
    width: 100%;
    top: auto;
    bottom: 0;
    opacity: 0;
    -webkit-transform: translateY(100%);
    -moz-transform: translateY(100%);
    -ms-transform: translateY(100%);
    transform: translateY(100%);
    -webkit-backface-visibility: hidden;
    -moz-backface-visibility: hidden;
    backface-visibility: hidden;
    -webkit-transition: -webkit-transform 0.4s, opacity 0.1s 0.3s;
    -moz-transition: -moz-transform 0.4s, opacity 0.1s 0.3s;
    transition: transform 0.4s, opacity 0.1s 0.3s;
}

.cs-style-3 figure:hover figcaption {
    opacity: 1;
    -webkit-transform: translateY(0px);
    -moz-transform: translateY(0px);
    -ms-transform: translateY(0px);
    transform: translateY(0px);
    -webkit-transition: -webkit-transform 0.4s, opacity 0.1s;
    -moz-transition: -moz-transform 0.4s, opacity 0.1s;
    transition: transform 0.4s, opacity 0.1s;
}

.cs-style-3 figcaption a {
    position: absolute;
    bottom: 20px;
    right: 20px;
}


text:
Q: Pandas select rows where a value in a columns does not starts with a string I have a data where I need to filter out any rows that do start with a certain values - emphasis on plural:
Below the data exactly as it appears in file data.xlsx
Name                Remains
GESDSRPPZ0161       TRUE
RT6000996           TRUE
RT6000994           TRUE
RT6000467           TRUE
RT6000431           TRUE
MCOPSR0034          FALSE
MCOPSR0033          FALSE

I need to be able to return a dataframe where name DOES NOT start with MCO, GE,etc.
import pandas as pd
import numpy as np

### data
file = r'C:\Users\user\Desktop\data.xlsx'

data  = pd.read_excel(file, na_values = '')
data['name'] = data['name'].str.upper()

prefixes = ['IM%','JE%','GE%','GV%','CHE%','MCO%']

new_data = data.select(lambda x: x not in prefixes)

new_data.shape

the last call returns exactly the same dataset as I started with.
I tried:
pandas select from Dataframe using startswith
but it excludes data if the string is elsewhere (not only starts with)
df = df[df['Column Name'].isin(['Value']) == False]

The above answer would work if I knew exactly the string in question, however it changes (the common part is MCOxxxxx, GVxxxxxx, GExxxxx...)
The vvery same happens with this one:
How to implement 'in' and 'not in' for Pandas dataframe
because the values I have to pass have to be exact. Is there any way to do with using the same logic as here (Is there any equivalent for wildcard characters like SQL?):
How do I select rows where a column value starts with a certain string?
Thanks for help! Can we expand please on the below?
@jezrael although I've chosen the other solution for simplicity (and my lack of understanding of your solution), but I'd like to ask for a bit of explanation please. What does '^' + '|^' do in this code and how is it different from Wen's solution? How does it compare performance wise when you have for loop construct as oppose to operation on series like map or apply? If I understand correctly contains() is not bothered with the location whereby startswith() specifically looks at the beggining of the string. Does it mean the
 ^indicates to contains() to do what? Start at the beginning?
 And | is it another special char for the method or is it treated like logical OR? I'd really want to learn this if you don't mind sharing. Thanks

A: Use str.contains with ^ for start of string and filter by boolean indexing:
prefixes = ['IM','JE','GE','GV','CHE','MCO']

pat = '|'.join([r'^{}'.format(x) for x in prefixes])
df = df[~df['Name'].str.contains(pat)]
print (df)
        Name  Remains
1  RT6000996     True
2  RT6000994     True
3  RT6000467     True
4  RT6000431     True

Thanks, @Zero for another solution:
df = df[~df['Name'].str.contains('^' + '|^'.join(prefixes))]
print (df)
        Name  Remains
1  RT6000996     True
2  RT6000994     True
3  RT6000467     True
4  RT6000431     True

A: You can using startswith , the ~ in the front will convert from in to not in
prefixes = ['IM','JE','GE','GV','CHE','MCO']

df[~df.Name.str.startswith(tuple(prefixes))]
Out[424]:
        Name  Remains
1  RT6000996     True
2  RT6000994     True
3  RT6000467     True
4  RT6000431     True


text:
Q: Simplify/RESTify my routes! Here is a sample of my routes.rb
Basically I have users that have pictures and that can rate other people's pictures
This is not very RESTful at all, but I cannot figure out how to turn this around?
  resources :users do
    member do
      post :reset_password
    end
  end
  # to list images
  get 'images/list/:order/:page/:per_page/:category', :to => 'images#list_filtered'
  # to rate images
  post 'images/rate', :to => 'images#rate'
  # to list a user's images
  get 'images/user/:user_id/:category/:order/:page/:per_page', :to => "images#user"
  # to list users that rated an image
  get 'users/rated/:image_id', :to => 'users#rated'

A: Why don't you treat images and ratings as resources? Nest images under their users and add a Rating model that belongs to an image and a user (the user giving the rating, not the owner of the rated image)
resources :users do
  resources :images do
    resources :ratings, :only => [:create, :destroy]
  end
  post :reset_password, :on => :member
end

then you can set up your cotroller like this
# ratings_controller.rb
class RatingsController < ApplicationController
  before_filter :find_image

  # POST /users/26/images/351/ratings
  def create
    @image.ratings.create(params[:rating])
    redirect_to image_path(@image), :notice => "You just rated this image"
  end

  # DELETE /users/26/images/351/ratings/35477
  def destroy
    @image.ratings.find(params[:id]).destroy!
    redirect_to image_path(@image), :notice => "Deleted rating"
  end

  private

  def find_image
    @image = Image.where(:user_id => params[:user_id], :id => params[:image_id])
  end
end

A: Here are a couple of things I would recommend:

*

*Use images#index instead of images#list_filtered and pass order, page, per_page and category as parameter: /images?order=...&per_page=...&page=...

*Make images nested under users as resources and then make images a top level resource that is independent of user (so that you can view all images or you can view user specific images).

resources :users do
  member do
    post :reset_password
  end
  resources :images
end

resources :images do
  post :rate
  get :rated
end

You should then be able to view images using /images.
You should be able to rate an individual image using /images/:id/rate.
You should be able to view users who rated an image using /images/:id/rated.
You should be able to list a user's images using /user/:id/images.


text:
Q: how to change the color of an svg image in xml file(in geoserver)?is it possible to change in geoserver? this is my code.i want to change color of svg image here itself. even though I change the color code it is not working.i am getting the black and white color. what is the error in my code?
<se:PointSymbolizer>
<se:Graphic>
<!--Parametric SVG-->
<se:ExternalGraphic>
<se:OnlineResource xlink:href="ForServer/DRY.svg?fill=%23e01987&fill-opacity=1&outline=%23e01987&outline-opacity=1&outline-width=0" xlink:type="simple"/>
<se:Format>image/svg+xml</se:Format>
</se:ExternalGraphic>
<!--Plain SVG fallback, no parameters-->
<se:ExternalGraphic>
<se:OnlineResource xlink:href="ForServer/DRY.svg" xlink:type="simple"/>
<se:Format>image/svg+xml</se:Format>
</se:ExternalGraphic>
<!--Well known marker fallback-->
<se:Mark>
<se:WellKnownName>square</se:WellKnownName>
<se:Fill>
<se:SvgParameter name="fill">#e01987</se:SvgParameter>
</se:Fill>
<se:Stroke>
<se:SvgParameter name="stroke">#e01987</se:SvgParameter>
<se:SvgParameter name="stroke-width">0.5</se:SvgParameter>
</se:Stroke>
</se:Mark>
<se:Size>11</se:Size>
</se:Graphic>
</se:PointSymbolizer>

A: You could try this:-
<?xml version="1.0" encoding="ISO-8859-1"?>
<StyledLayerDescriptor
  version="1.0.0"
  xmlns="http://www.opengis.net/sld"
  xmlns:ogc="http://www.opengis.net/ogc"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:gml="http://www.opengis.net/gml"
  xsi:schemaLocation="http://www.opengis.net/sld
    http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd
">
  <NamedLayer>
    <Name>redflag</Name>
        <UserStyle>
        <Name>burg</Name>
        <Title>A small red flag</Title>
        <Abstract>A sample of how to use an SVG based symbolizer
        </Abstract>
      <FeatureTypeStyle>
       <Rule>
          <PointSymbolizer>
              <Graphic>
                <ExternalGraphic>
                    <OnlineResource xlink:type="simple" xlink:href="burg02.svg" />
                    <Format>image/svg+xml</Format>
                </ExternalGraphic>
                <Size>
                 <ogc:Literal>30</ogc:Literal>
                </Size>
            </Graphic>
         </PointSymbolizer>
        <PolygonSymbolizer>
          <Fill>
            <CssParameter name="fill">#1eff00</CssParameter> <CssParameter name="fill-opacity">0.6</CssParameter>
          </Fill>
          <Stroke>
            <CssParameter name="stroke">#000000</CssParameter> <CssParameter name="stroke-width">0.5</CssParameter>
          </Stroke>
        </PolygonSymbolizer>
      </Rule>
     </FeatureTypeStyle>
    </UserStyle>
    </NamedLayer>
</StyledLayerDescriptor>

And let me know if you face any issues

A: It's possible using composition. I made a svg picture with only black colors to use as an alpha mask. Then I made a square Mark bigger than the picture just to apply the color.
<?xml version="1.0" encoding="ISO-8859-1"?>
<StyledLayerDescriptor version="1.0.0" xmlns="http://www.opengis.net/sld"
                       xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink"
                       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gml="http://www.opengis.net/gml"
                       xsi:schemaLocation="http://www.opengis.net/sld">
  <NamedLayer>
    <UserStyle>
      <FeatureTypeStyle>
        <Rule>
          <PointSymbolizer>
            <Graphic>
              <ExternalGraphic>
                <OnlineResource xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple" xlink:href="YOUR_SVG_FILE.svg"/>
                <Format>image/svg+xml</Format>
              </ExternalGraphic>
              <Size>45</Size>
            </Graphic>
            <VendorOption name="composite-base">true</VendorOption>
          </PointSymbolizer>
          <PointSymbolizer>
            <Graphic>
              <Mark>
                <Fill>
                  <CssParameter name="fill">#1e9e1e</CssParameter>
                  <CssParameter name="fill-opacity">1</CssParameter>
                </Fill>
              </Mark>
              <Size>50</Size>
            </Graphic>
            <VendorOption name="composite">source-in</VendorOption>
          </PointSymbolizer>
        </Rule>
      </FeatureTypeStyle>
    </UserStyle>
  </NamedLayer>
</StyledLayerDescriptor>

See also https://docs.geoserver.org/stable/en/user/styling/sld/extensions/composite-blend/syntax.html

A: GeoServer doesn't (AFAIK) support the colouring of SVG symbols via the SLD file, it will always be the colours that are set in the SVG.

A: Instead of giving an image as .svg, I have converted SVG to png and gave .png image, It perfectly works!!!


text:
Q: Formatting the JSON output from an ASP.Net MVC 4 Web API I have a Web API project with models that look like this:
public class Account{

string FirstName{get;set;}
string LastName{get;set;}
}

I would like the JSON response to use a different format and casing for the properties, like this:
first_name
last_name

Is there a way to perform this globally through some sort of json formatter, or is it best to create separate ViewModel classes with appropriate casing?

A: You should create separate viewmodel classes for a number of reasons.
It is best to use separate viewmodel classes so that you do not overexpose your model. In the case where you use an entity class with 10 fields as a view model, and you only want to expose 5 of them, a malicious user may post the extra data with a querystring and the automatic bind may fuse that in without you realizing it.
In your example case, you may want to use entirely different names for the fields. This is a perfect candidate for making a custom viewmodel for your entity class.
Separating these concerns will help your application be more re-usable in the future, and easier to test / debug in the present. If you find yourself in the situation where there are too many view models, consider factoring out these different controllers, views, and models, into separate areas ( blog on areas ).
As a side note, if you want to format the JSON it may be easier to do it after the fact in javascript rather than before hand because usually editing the JSON serializer class is a large endeavor. You could write a script which went through and automatically converted camel case to _ separated lower case. A downside to doing that would be that it could have unintended affects in the future if you did not expect the functionality to perform like that.


text:
Q: I am trying to change the adminbro text and logo, I tried using company name but the text is still there Branding :(
Company name : Ai finance
)
I am trying to change the adminbro text and logo,
I tried the code above, it didn't work but the title of the page changed alone


text:
Q: Contour Integral of $\oint_{|z|=1}\frac{\sin(z)}{z^2}\,dz$ Find the integral $$\oint_{|z|=1}\frac{\sin(z)}{z^2}\,dz$$
I can see that there is a pole at $z = 0$. But I don't know how to solve that integral over that way.

A: We know
$$\sin z = z - \frac{z^3}{3!} + \frac{z^5}{5!} - \dots$$
In fact, operations on Power/Laurent series end up being exactly what we expect in the naive fashion:
$$\frac{\sin z}{z^2} = \frac{1}{z} - \frac{z}{3!} + \frac{z^3}{5!} - \dots$$
So by the Residue Theorem: $$\oint_{S^2} \frac{\sin z}{z^2} dz = 2\pi i$$


text:
Q: React Hooks state update applies only once when called from callbacks in an array of components
I'm having trouble to lift the state up in that case:
I have a button which on each click adds element to 'mylist' through 'setMyList'. These elements are 'Child' components (the div className "site" is just a CSS square), and I want that each time I click on one of those components/elements it increments 'count' thanks to 'setCount' in the callback that is given to the 'Child' component in 'setMyList'.
But what happen is that, for instance, I create a square then click on it, 'count' doesn't go further than 1, then with another square created, clicking on it makes 'count' goes up to 2 but not more, and so on.
And when I click back on the first square 'count' is 1, it looks like the state is saved for each 'Child' components instead of incrementing it.
Here are my components:
import React, { useState } from 'react'
import Child from './Child.js'

function Parent() {
    const [count, setCount] = useState(0);
    const [mylist, setMyList] = useState([])

    function increment() {
        console.log("TEST")
        setCount(count + 1)
    }

    return (

        <button onClick={() => setMyList([...mylist, <Child onClick={increment}></Child>])}> </button>

count {count}

        {mylist}
        (count should be updated from child)

    );
  }

export default Parent

Note that each time a square is clicked on, It does go in 'increment' function because the console log displays, but it goes through setCount withtout doing anything.
import React, { useState } from 'react'
import "./Site.css"

function Child(props) {
    return (

    )
}

export default Child

Thanks in advance

A: You should use setCount((count) => count + 1);
This will ensure that setCount can get the latest count value every time.
This is because every time you push Child, the increment function will be recreated, and then the count in the increment function is actually the value when the increment function was created.
In addition, you can use React.useCallback to optimize this.
const increment = React.useCallback(() => {
  setCount((count) => count + 1);
}, []);


text:
Q: INSERT INTO SQL With c++ error 1064 42000 I am facing the error code while i want to insert into the sql data base

error :1064  sqlstate :42000

Here is my code:
string* DB(string barcode)
{
    try {
        sql::Driver *driver;
        sql::Connection *con;
        sql::Statement *stmt;
        sql::ResultSet *res;
        /* Create a connection */
        driver = get_driver_instance();
        con = driver->connect("sql14.main-hosting.eu", "u103222348_user", "newsystem");
        /* Connect to the MySQL test database */
        con->setSchema("u103222348_read");

        stmt = con->createStatement();

        res = stmt->executeQuery("INSERT INTO 'Conveyor-BELT' ('BARCODE', 'TIM121') VALUES('5555','5555')");
        while (res->next()) {

            /* Access column data by alias or column name */

        }
        delete res;
        delete stmt;
        delete con;

    }
    catch (sql::SQLException &e) {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }

    return EXIT_SUCCESS;
}

A: In MySQL use backticks to escape column and table names and quotes to escape strings
INSERT INTO `Conveyor-BELT` (`BARCODE`, `TIM121`)
VALUES('5555', '5555')


text:
Q: RuntimeError: The specified pointer resides on host memory and is not registered with any CUDA device My code is here
                with cp.cuda.Device(cp_device):
                    candidates = cp.zeros((point_idxs.shape[0], num_rots, 3), cp.float32)

                    block_size = (point_idxs.shape[0] + 512 - 1) // 512
                    rot_voting_kernel(
                        (block_size, 1, 1),
                        (512, 1, 1),
                        (
                            cp.asarray(pc), cp.asarray(preds_tr[0].cpu().numpy()), cp.asarray(direction[0].cpu().numpy()), candidates, cp.asarray(point_idxs).astype(cp.int32), cp.asarray(corners[0]).astype(cp.float32), cp.float32(cfg.res),
                            point_idxs.shape[0], num_rots, grid_obj.shape[0], grid_obj.shape[1], grid_obj.shape[2]
                        )
                    )
                    sph_cp = torch.tensor(sphere_pts.T, dtype=torch.float32).cuda()
                    start = np.arange(0, point_idxs.shape[0] * num_rots, num_rots)
                    np.random.shuffle(start)
                    sub_sample_idx = (start[:10000, None] + np.arange(num_rots)[None]).reshape(-1)
                    candidates = torch.as_tensor(candidates, device='cuda').reshape(-1, 3)
                    candidates = candidates[torch.LongTensor(sub_sample_idx).cuda()]
                    cos = candidates.mm(sph_cp)
                    counts = torch.sum(cos > np.cos(angle_tol / 180 * np.pi), 0).cpu().numpy()
                best_dir = np.array(sphere_pts[np.argmax(counts)])

when i run the code in wsl, i got this traceback:
Traceback (most recent call last):
  File "nocs/inference.py", line 298, in <module>
    candidates = torch.as_tensor(candidates, device='cuda').reshape(-1, 3)
RuntimeError: The specified pointer resides on host memory and is not registered with any CUDA device.

how to solve the question?
i tried google but didn't get any idea.


text:
Q: PySpark error "An illegal reflective access operation has occurred" happens when I try to start a SparkSession Using Jupyter Notebooks on mac. Python3 Kernel.
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/Users/jaredchapman/opt/anaconda3/lib/python3.9/site-packages/pyspark/jars/spark-unsafe_2.12-3.2.1.jar) to constructor java.nio.DirectByteBuffer(long,int)
WARNING: Please consider reporting this to the maintainers of org.apache.spark.unsafe.Platform
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
22/03/29 13:33:00 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable


text:
Q: Discord.py | Adding reactions to message Code:
@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    author = message.author
    channel_id = message.channel.id
    if channel_id == suggestions_channel_id:
        await message.add_reaction(":white_check_mark:")
        await message.add_reaction(":x:")
    await bot.process_commands(message)

I am getting error:
discord.errors.HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji
Why is this an unknown emoji? It is a public emoji :white_check_mark: ?

A: Fixed. Forgot has to be unicode
Go to any discord channel and do
\:emoji_name:
Will give you the unicode.


text:
Q: fetch api cannot load, url scheme 'file' is not supported i tried to use fetch on localhost, but it didn't work.
here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>

        fetch("hi.txt").then(function(response){
            response.text().then(function(text){
                alert(text)
            })
        })
    </script>
</body>
</html>

hi.txt file is in same folder with the script file.
below error is shown in console:
index.html:12 Fetch API cannot load file:///C:/~~~~/hi.txt. URL scheme "file" is not supported.
(~~~) is path

A: Since your URL is relative (it's just "hi.txt"), it's resolved against the URL of the page the code is running in. In your case, that appears to be file:///something — that is, a file you've loaded directly from your file system, not by requesting it from a server. Chrome doesn't allow fetching from the file scheme. The file scheme's origin is null. The Chrome team's interpretation of the Same Origin Policy is that no origin, not even itself, should match null. (A reasonable interpretation in my view, but opinions can vary.)
When doing web development, you want to be working through a server process because pages loaded directly from the file system behave differently in several sometimes-subtle ways vs. pages loaded from servers.
There are a couple of ways to do that:

*

*Use the features of your IDE, if you use one, and/or extensions to it. For instance, for VSCode there's the "live server" extension which makes it very easy to run your code from a minimal server.

*Use an actual web server process running locally. There are simple ones that are easy to install.

*Use one of various "quick start" scaffolding tools that set up simple projects for you, often via npm (and Node.js), with a command you can use to build and run the project locally in development mode.

A: hi you are running your file like this way
-you are right clicking on your html file-opening with it browser. This way you are telling to browser to open your html file from your file location where you have saved it.Check in Your browser url bar you will get something like this C:/xampp/htdocs/xyz.html so this is your local directory file system. so now you have to first start your sever such as xampp or whatever server you have installed and then you type this localhost/filename or /subfolder name and / file name  if you have stored it in subfolder...and hit enter.inshort you have to query to a server like you does in php file calling.....

A: You can just create a local web server (XAMPP) and upload there your hi.txt file. If you did that, replace
fetch("hi.txt")

with
fetch("http://127.0.0.1/hi.txt")


text:
Q: How to store only certain number of document versions in mongodb? Let's assume I would like to track computers on my network storing information about mac-address with the device name, port name, vlan number and timestamp.
I could grab mac-address-table from all switches in regular intervals, parse it and dump that data into mongodb.
The problem is: how to STORE only last 100 unique entries for each mac-address.
Capped collections is no-go, because to do that I would have to create separate collection for each mac, which is bad idea.
The number of switches and mac-addresses may change over time, and new data might be inserted at irregular intervals.
The other idea I have is to write some query which looks for the timestamp of 100th oldest entry for each mac-address and remove all older entries, and run this queries after each batch of inserts. It may work, but doesn't seem very efficient.
Do you have any better ideas?

A: Hmm... found something interesting:
how about storing each version in an array using $push operator with $slice modifier?
there are some examples in the docs:
http://docs.mongodb.org/manual/reference/operator/update/slice/

A:
The other idea I have is to write some query which looks for the timestamp of 100th oldest entry for each mac-address and remove all older entries, and run this queries after each batch of inserts. It may work, but doesn't seem very efficient.

That sounds good to me. It might be cleaner to use cyclic buffer for this:
{
   mac : "AA:AA:AA:AA:AA",
   entryPointer : 2, // pointer of the next entry to be written
   lastEntries : [
      { "ip" : "127.0.0.1", "service" : "foo", ts : ISODate(...), ... },
      { "ip" : "127.0.0.1", "service" : "foo", ts : ISODate(...), ... },
      { "ip" : "255.255.255.255", "service" : "longestProbableServiceName",
        ts : ISODate(0001-01-01), ... }
      ...
      { "ip" : "255.255.255.255", "service" : "longestProbableServiceName",
        ts : ISODate(0001-01-01), ... }
   ]
}

An update would have to increase the pointer and overwrite the position in the array given by pointer % 100. It will be helpful to preallocate the memory in the array as demonstrated to avoid fragmentation and reallocation overhead.
As you pointed out, the modulo-update can be done using $slice and $push:
db.foo.update(
   { mac : "AA:AA:AA..." },
   {
     $push: {
       lastEntries : {
         $each: [ { "ip" : "012.002.003.012", ... } ],
         $slice: -100
       }
     }
   }
)

Pre-populating the array also comes with the advantage that the most recent entry is always at the last position.


text:
Q: Changing the case within Snipmate.vim snippets? Is it possible to change the case of variable values within Snipmate snippets?
For example:
snippet dc
  def create
    @${1} = $1.new
  end

Should output:
def create
  @product = Product.new
end

I tried to use backticks to call a custom function:
snippet dc
  def create
    @${1} = `ToUpperCase('$1')`.new
  end

And defined this function in Vim:
function! ToUpperCase(str)
    let result = substitute(a:str, '\(\w\)', '\u\1', '')
    return result
endfunction

This doesn't work as it seems that Snipmate expands its $n variables after it has executed the backticks.

A: The current release of snipMate is not capable of performing transformations on the mirrored text. Look up :help snipMate-disadvantages where it says:

Regex cannot be performed on variables, such as "${1/.*/\U&}"

If you really want this feature, you might want to try one of the other snippet plugins out there. UltiSnips uses the same syntax for defining snippets, and claims to have all of the same features as TextMate.

A: I made a little hack to snipMate to allow the functionality I was looking for.
Put this code in autoload/snipMate.vim to the end of the s:RemoveSnippet() function (after the line #14):
let linecount = len(getline("1", "$"))
for linenum in range(1, linecount)
    let line = getline(linenum)
    let line = substitute(line, '\v\%uc\(([^)]+)\)', '\U\1\E', 'g')
    let line = substitute(line, '\v\%ucfirst\(([^)]+)\)', '\u\1', 'g')
    call setline(linenum, line)
endfor

Now you can define snippets like this:
snippet dc
  def create
    @${1:product} = %ucfirst($1).new
    %uc($1) = "This is Ruby %uc(constant) example."
  end

Output:
def create
  @product = Product.new
  PRODUCT = "This is Ruby CONSTANT example."
end

Notice that the replacement is not done in real time but after you "quit" the snippet.

A: Disclaimer: I am the main author of UltiSnips.
For your interest and rollin-the-drum purposes, I present two snippet definitions for UltiSnips which has been mentioned here before. Both do what the OP wants. The first one uses transformations (TextMate syntax):
snippet dc "create" b
def create
   @$1 = ${1/.*/\u$0/}.new
end
endsnippet

The second uses python code interpolation. For my tastes this is easier to read but it is a little more verbose.
snippet dc "create" b
def create
   @$1 = `!p snip.rv = t[1].title()`.new
end
endsnippet

Since version 1.3 UltiSnips comes with a script that can convert snipMate snippets, switching should therefore be easy.


text:
Q: getContentResolver().delete doesn't work I'm trying to delete a specific contact! I've searched a lot, but every code I try doesn't work!
public void delete(String name,String numero)
{
Cursor cur = getContentResolver().query(Contacts.CONTENT_URI,null, null, null, null);

while (cur.moveToNext())
{
    try
    {
        String[] selectionArgs=new String[]{String.valueOf(numero)};
        String lookupKey = cur.getString(cur.getColumnIndex(Contacts.LOOKUP_KEY));
        Uri uri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
        getContentResolver().delete(uri, Phone.NUMBER +"=?", selectionArgs);
    }
    catch(Exception e)
    {
       System.out.println(e.getStackTrace());
    }
}

}
I also tried this instead of specifying selectionArgs but nothing
getContentResolver().delete(uri, Contacts.DISPLAY_NAME +"="+ name, null);

and tried to change Contacts. with ContactsContract.Contacts. but nothing
and yet tried deleting with the Contact displayname instead of number.
It seems that selection doesnt work! The uri value is Uri$HierarchicalUri is this right?
What's the issue?

A: Change
getContentResolver().delete(uri, Contacts.DISPLAY_NAME +"="+ name, null);

to
String[] names = {name};
getContentResolver().delete(uri, Contacts.DISPLAY_NAME +"=?", names);


text: Q: MLP, logistic regression with very badly prediction on training data set I have a problem with my MLP model (one hidden layer, wrote from scratch in python). When I'm trying to solve logistic regression problem with 3 (1, 2, 3) classes, and first train on training data set, next try to make prediction, and when I'm predicting on the test dataset, acurracy is >90%, but when I'm trying to make prediciton on the training dataset, acurracy is very bad. I also tried to append test and training datasets and train on this summary data set and after that try to predict apart test and training data set and results was very good. I tried on many different hyperparameter settings, but the result was similar. Does anyone have any advice?


text:
Q: Error in building FFMPEG-3.4 with Android-NDK-16.1 Trying to compile the FFMPEG-3.4 with Android-NDK-16.1.
Compiling the source on Mac.
Getting below Warnings/Errors:

*

*WARNING: /Users/strehan/Library/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/bin/arm-linux-androideabi-pkg-config not found, library detection may fail.

*Error: In file included from libavdevice/avdevice.c:19:0:./libavutil/avassert.h:30:20: fatal error: stdlib.h: No such file or directory

*Error: /Users/strehan/Library/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/lib/gcc/arm-linux-androideabi/4.9.x/include/stdint.h:9:26: fatal error: stdint.h: No such file or directory

*Error: /libavutil/common.h:33:19: fatal error: errno.h: No such file or directory
Below is the build_script.sh using for build:
#!/bin/bash
NDK=/Users/strehan/Library/Android/sdk/ndk-bundle
SYSROOT=$NDK/platforms/android-21/arch-arm/
TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64
function build_one
{
./configure \
--prefix=$PREFIX \
--enable-shared \
--disable-static \
--disable-doc \
--disable-ffmpeg \
--disable-ffplay \
--disable-ffprobe \
--disable-doc \
--disable-symver \
--enable-protocol=concat \
--enable-protocol=file \
--enable-muxer=mp4 \
--enable-demuxer=mpegts \
--cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- \
--target-os=linux \
--arch=arm \
--enable-cross-compile \
--sysroot=$SYSROOT \
--extra-cflags="-Os -fpic $ADDI_CFLAGS" \
--extra-ldflags="$ADDI_LDFLAGS" \
$ADDITIONAL_CONFIGURE_FLAG
make clean
make -j3
make install
}
CPU=arm
PREFIX=$(pwd)/android/$CPU
ADDI_CFLAGS="-marm"
build_one

Terminal output:
Enabled indevs:
lavfi

Enabled outdevs:

License: LGPL version 2.1 or later

WARNING: /Users/strehan/Library/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/bin/arm-linux-androideabi-pkg-config not found, library detection may fail.
config.h is unchanged
libavutil/avconfig.h is unchanged
libavcodec/bsf_list.c is unchanged
libavformat/protocol_list.c is unchanged
ffbuild/config.sh is unchanged
GEN libavutil/libavutil.version
GEN libswscale/libswscale.version
GEN libswresample/libswresample.version
GEN libavcodec/libavcodec.version
GEN libavformat/libavformat.version
GEN libavfilter/libavfilter.version
GEN libavdevice/libavdevice.version
CC  libavdevice/alldevices.o
CC  libavdevice/avdevice.o
CC  libavdevice/lavfi.o
In file included from libavdevice/avdevice.c:19:0:
./libavutil/avassert.h:30:20: fatal error: stdlib.h: No such file or directory
 #include <stdlib.h>
                    ^
compilation terminated.
make: *** [libavdevice/avdevice.o] Error 1
make: *** Waiting for unfinished jobs....
In file included from ./libavutil/avutil.h:296:0,
                 from ./libavutil/log.h:25,
                 from libavdevice/avdevice.h:48,
                 from libavdevice/alldevices.c:23:
./libavutil/common.h:33:19: fatal error: errno.h: No such file or directory
 #include <errno.h>
                   ^
compilation terminated.
In file included from ./libavutil/avstring.h:25:0,
                 from ./libavutil/bprint.h:27,
                 from libavdevice/lavfi.c:30:
/Users/strehan/Library/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/lib/gcc/arm-linux-androideabi/4.9.x/include/stdint.h:9:26: fatal error: stdint.h: No such file or directory
 # include_next <stdint.h>
                          ^
make: *** [libavdevice/alldevices.o] Error 1
compilation terminated.
make: *** [libavdevice/lavfi.o] Error 1
INSTALL doc/examples/avio_dir_cmd.c
INSTALL doc/examples/avio_reading.c
INSTALL doc/examples/decode_audio.c
INSTALL doc/examples/decode_video.c
INSTALL doc/examples/demuxing_decoding.c
INSTALL doc/examples/encode_audio.c
INSTALL doc/examples/encode_video.c
INSTALL doc/examples/extract_mvs.c
INSTALL doc/examples/filter_audio.c
INSTALL doc/examples/filtering_audio.c
INSTALL doc/examples/filtering_video.c
INSTALL doc/examples/http_multiclient.c
INSTALL doc/examples/hw_decode.c
INSTALL doc/examples/metadata.c
INSTALL doc/examples/muxing.c
INSTALL doc/examples/qsvdec.c
INSTALL doc/examples/remuxing.c
INSTALL doc/examples/resampling_audio.c
INSTALL doc/examples/scaling_video.c
INSTALL doc/examples/transcode_aac.c
INSTALL doc/examples/transcoding.c
INSTALL doc/examples/vaapi_encode.c
INSTALL doc/examples/README
INSTALL doc/examples/Makefile
INSTALL doc/examples/avio_dir_cmd.c
INSTALL doc/examples/avio_reading.c
INSTALL doc/examples/decode_audio.c
INSTALL doc/examples/decode_video.c
INSTALL doc/examples/demuxing_decoding.c
INSTALL doc/examples/encode_audio.c
INSTALL doc/examples/encode_video.c
INSTALL doc/examples/extract_mvs.c
INSTALL doc/examples/filter_audio.c
INSTALL doc/examples/filtering_audio.c
INSTALL doc/examples/filtering_video.c
INSTALL doc/examples/http_multiclient.c
INSTALL doc/examples/hw_decode.c
INSTALL doc/examples/metadata.c
INSTALL doc/examples/muxing.c
INSTALL doc/examples/qsvdec.c
INSTALL doc/examples/remuxing.c
INSTALL doc/examples/resampling_audio.c
INSTALL doc/examples/scaling_video.c
INSTALL doc/examples/transcode_aac.c
INSTALL doc/examples/transcoding.c
INSTALL doc/examples/vaapi_encode.c
INSTALL doc/examples/README
INSTALL doc/examples/Makefile
CC  libavdevice/alldevices.o
In file included from ./libavutil/avutil.h:296:0,
                 from ./libavutil/log.h:25,
                 from libavdevice/avdevice.h:48,
                 from libavdevice/alldevices.c:23:
./libavutil/common.h:33:19: fatal error: errno.h: No such file or directory
 #include <errno.h>
                   ^
compilation terminated.
make: *** [libavdevice/alldevices.o] Error 1

Please help to fix these errors. Due to these errors/warnings compilation is getting terminated.
Note:
Android directory is getting created even after these errors. But I think library is not compiled properly due to above errors.
Let me know if anything else needed. Please help.

A: Your build script is out of date and not compatible with modern NDKs (it doesn't follow https://android.googlesource.com/platform/ndk/+/master/docs/UnifiedHeaders.md#supporting-unified-headers-in-your-build-system).
I'd recommend saving yourself some trouble and using a standalone toolchain to handle the organizational bits for you.


text:
Q: pywintypes.com_error: (-2147024882, 'Not enough memory resources are available to complete this operation.', None, None) When I try to fetch around 250k rows from pgsql to excel  using pythons pywin32 package
I get the following error

pywintypes.com_error: (-2147024882, 'Not enough memory resources are available to complete this operation.', None, None)

A: I met the same problem while loading a sheet of 92,875 X 60 in size. It worked just fine before this sheet grew so large.
I figured out a way to fix this problem, which is quite simple. Instead of loading the whole range of data, read a single row and then another.
For example, my code was originally like this:
finalrow = ws.Cells(ws.Rows.Count, "A").End(win32com.client.constants.xlUp).Row
finalcell = '$%s$%s' % (finalcolumn, finalrow)
r = ws.Range('$A$1:' + finalcell).Value
rows = list(r)

where finalcolumn is a constant value, say 'BH'.
Changed to:
finalrow = ws.Cells(ws.Rows.Count, "A").End(win32com.client.constants.xlUp).Row
finalcell = '$%s$%s' % (finalcolumn, finalrow)
rows = []
for i in range(finalrow):
    r = ws.Range('$A$%s:$%s$%s' % (i+1, finalcolumn, i+1)).Value
    rows += list(r)

No significant performance hit was observed.


text:
Q: How do I get the sha-256 hash of a section which contains code in a Portable Executable file, in Delphi? I would like to get the sha-256 hash for a section which contains code(.text, CODE) in a Portable Executable file, in Delphi.
So far, I've tried to get the start and end address of the section to which the AddressOfEntryPoint points to, but if I load the same file several times, I get different start and end addresses.
Can anyone please help me?
This is the code:
procedure TForm1.Button1Click(Sender: TObject);
var x:TJCLPEImage;
aoep,cs,ce: cardinal;
pise: Pimagesectionheader;
nos : integer;
i : integer;
begin

x := TJCLPEImage.Create();
x.FileName:=edit1.Text;
aoep := x.OptionalHeader32.AddressOfEntryPoint;
pise := Pointer(PByte(@(x.LoadedImage.FileHeader.OptionalHeader)) + x.LoadedImage.FileHeader.FileHeader.SizeOfOptionalHeader);

for i:=0 to x.ImageSectionCount-1 do
begin
if (pise.VirtualAddress <= aoep) and (aoep < (pise.VirtualAddress + pise.Misc.VirtualSize)) then
    break;

end;

inc(pise);

cs := DWORD(x.LoadedImage.MappedAddress) + DWORD(pise.PointerToRawData);
ce := cs + pise.Misc.VirtualSize;

Label1.caption:='Code start: '+Inttostr(cs);
Label2.caption:='Code end: '+inttostr(ce);

end;

Thank you.

A: I cant comment to your question yet, so i am trying to reply here, but not sure if i am thinking right about what you are asking.
Seems you want a way to assure no one changed your file after it loaded in memory.
That's why you want a sha-256 hash of that section, and probably you need to get that section and then hash it.
I never used JCL classes to do that. But found this unit that maybe help for you. It allow you to edit PE files. Was written in 2007, so maybe you will need upgrade some code. But i am most sure you will find the bases to what you want.
http://www.coderprofile.com/networks/source-codes/71/portable-executable-file-unit
I could not test it at all. But till what i tested, the start address did not changed here..
To get the Sha-256, will find many VCL components (or at least ActiveX) to do that. I could advise you to use LIBEAY32.DLL, but that would probably add one more dll to your application. Unless you already use it.
Hope that help in anyway.


text:
Q: Android: Show options menu in navigation drawer I have a menu defined in an XML file such a "home_menu.xml" like this:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Should always be in the overflow -->
<item
    android:id="@+id/action_settings"
    android:showAsAction="never"
    android:title="@string/action_settings"/>
<item
    android:id="@+id/action_user_preferences"
    android:showAsAction="never"
    android:title="@string/action_user_preferences"/>
<item
    android:id="@+id/action_logout"
    android:showAsAction="never"
    android:title="@string/action_logout"/>

</menu>

In my "Home" activity, I can access this menu by pushing the menu button in a device that has a physical button, but I don't want to use action bar so I want to add a Navigation Drawer for this purpose as Google Maps does.
It would be great if I could use the same  onOptionsItemSelected() method defined in my Home activity to handle menu actions.

A: You won't be able to do that.
You'll have to do it manually.
Or semi-manually. You could in onCreateOptionsMenu get all the menu items with title, icon and id and generate the view (listview for instance) for the drawer.
And use a shared method to handle the click that takes the id in parameter.
But if you want to hide/show some elements in the menu, you'll have to update your listview manually since onCreateOptionsMenu won't be called. And if you have multiple fragment with menus you'll also have to do something.
So I would recommend to use the drawer even when there is a hardware menu key.


text:
Q: Quarkus - specify own hibernate dialect to use Vlad Mihalcea's Json Hibernate Extension I am currently trying to use some json types in my database.
I tried as per this article:
https://vladmihalcea.com/sql-server-json-hibernate/
After including this I got the following excetion:
2021-07-13 11:08:07,235 ERROR [io.qua.run.Application] (Quarkus Main Thread) Failed to start application (with profile dev): org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111
    at org.hibernate.dialect.TypeNames.get(TypeNames.java:71)
    at org.hibernate.dialect.TypeNames.get(TypeNames.java:103)
    at org.hibernate.dialect.Dialect.getTypeName(Dialect.java:404)
    at org.hibernate.mapping.Column.getSqlType(Column.java:238)
    at org.hibernate.mapping.Table.sqlAlterStrings(Table.java:479)
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.migrateTable(AbstractSchemaMigrator.java:299)
    at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:75)
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:207)
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:192)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:81)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:327)
    at io.quarkus.hibernate.orm.runtime.boot.FastBootEntityManagerFactoryBuilder.build(FastBootEntityManagerFactoryBuilder.java:73)
    at io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.createEntityManagerFactory(FastBootHibernatePersistenceProvider.java:67)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:80)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    at io.quarkus.hibernate.orm.runtime.JPAConfig$LazyPersistenceUnit.get(JPAConfig.java:149)
    at io.quarkus.hibernate.orm.runtime.JPAConfig$1.run(JPAConfig.java:58)
    at java.base/java.lang.Thread.run(Thread.java:834)

I then tried to create my own dialect as per this article:
https://vladmihalcea.com/hibernate-no-dialect-mapping-for-jdbc-type/
but I still get the same excetion. I tried adding my own class to the dialect property in the application properties. But this didn't seem to do the trick.
Is there a way to configure this with quarkus? I am concerned, that I really cannot do it, as there is a disclaimer at the property concerning its limitation.
Edit: I intially fixed it, because I removed the auto generation of the database schema. I get this error now again, after I added quarkus-quartz with the DB storage of triggers (Cluster mode with quarkus.quartz.store-type=JDBC_TX). The application tries to update the trigger in the database (changed schedule time) and throws this error.
I have added the following class:
package emilfrey.backend;
import com.vladmihalcea.hibernate.type.json.JsonNodeBinaryType;
import org.hibernate.dialect.SQLServer2012Dialect;

import java.sql.Types;

public class SQLServer2012JsonDialect extends SQLServer2012Dialect {
    public SQLServer2012JsonDialect(){
        super();
        this.registerHibernateType(Types.OTHER, JsonNodeBinaryType.class.getName());

    }
}

and added the following property in the application.properties
quarkus.hibernate-orm.dialect = somepackage.backend.SQLServer2012JsonDialect

The error still persists. I guess it has something to do with the availablity of that new class and its loading. But I am not sure. Can somebody help me with this issue?
Thank you already.

A: I don't know about fixing this when schema generation is enabled.
But to anyone with this problem when schema generation is disabled, in Quarkus Dev mode, it's a bug that was fixed in Quarkus 2.4.1: https://github.com/quarkusio/quarkus/issues/21122


text:
Q: Problems opening Bootstrap Modal after using (.reportValidity) I am using the what i think is the relatively new .reportValidity function to validate my required fields on a form. This works great, what i would like to achieve is after validation my bootstrap Thank You Modal opens up. I have removed the data-toggle="modal" data-target="#confirm-submit" from my submit button to stop the thank you modal from opening before validation i,m just stuck with the javascript to open it after validation. Here is my code -
For the Validation -
    <script>
    document.forms['formfield'].addEventListener('submit', function() {
    document.forms['formfield'].reportValidity();
    }, false);
    </script>

For my Bootstrap Modal -
    (function(){
    $('##confirm-submit').on('show.bs.modal', function(){
    var myModal = $(this);
    clearTimeout(myModal.data('hideInterval'));
    myModal.data('hideInterval', setTimeout(function(){
        myModal.modal('hide');
    }, 3000));
    });
    });

How do i call the Modal after validation and not before?

A: Answer was i was over complicating it with a timed Modal, which i didnt need so the final code was -
    <script>
    document.forms['formfield'].addEventListener('submit', function() {
    document.forms['formfield'].reportValidity();
    }, false);
    </script>
    <script>
    $('#formfield').on('submit', function(e){
    $('#confirm-submit').modal('show');
    });
    </script>

I also added onsubmit="openModal()" into my form name header tag. Now works like a dream.


text:
Q: Augmented reality: Rendering function My question builds up on this thread: Computer Vision / Augmented Reality: how to overlay 3D objects over vision? and on its first answer. I want to build an application that projects on real time the position of a fictional 3D object into a video feed, but the first step I have to take is: How can I do this over a single image?
What I am going for at the moment is having some kind of function that given a picture, its 6D pose (position + orientation), a 3D object (on fbx, 3ds, or something easily convertable to or from others), and its own position and orientation, returns me the projection of the 3D object over the image. Once I have that, I should be able to apply it over every frame of the video feed (how will I get the 6D information of the camera is a problem I'll deal with later)
My problem is that I am unsure where to find such a function, if it even exists. It should be offered like some kind of script or API so an external program can make use of it. Where should I look? Unity? Some kind of OpenCL functionality? So far my reading has not given me any conclusive answers, and as I am a novice in the topic, I'm sure a steep learning curve is ahead and I'd rather put my efforts on the right direction. Thank you

A: Indeed there's an API for that.
https://developer.vuforia.com
read the GetStarted page.
On this site, there is a "Target Manager", you'll want to upload your target images. Those will allow you to display the 3D object that you want.
On the same "page" you can have several target images.
Example : One that display your 3D object when visible, one that makes it rotates when hided. etc ...
For the real time projection video part, I will make the assumption that, on Unity, you can have a movie texture running on a plane in background and sort your layers in a way that your 3D object is above.
Please update the topic whenever you find a way.
Bye


text:
Q: Patterns for phone number prefixes - validation I have looked up patterns for the following: 1300, 1-300-, 1800, 1-800- followed by 10 digits and 13, 1-3- followed by 6 digits.  They all look pretty long winded, was wondering if any one had any solutions using regular expressions only

A: You can use the libphonenumber and let it take care of validation, formatting etc. Form their website

What is it?
Google's common Java, C++ and Javascript library for parsing,
  formatting, storing and validating international phone numbers. The
  Java version is optimized for running on smartphones, and is used by
  the Android framework since 4.0 (Ice Cream Sandwich).


text:
Q: Passing values to global variables Does someone has a plausible explanation why javascript does not the pass the object literal as a value to the global variable that is passed via function parameter?
Do I overlook some fundamental rules?
(function(global) {
    var id = "3543a1354";
    global = {
        name: 'global',
        getId: function() {
            return id;
        }
    };
})(this.global = this.global || {})

So essentially the value of the parameter 'global' after executing the code is an empty object. Very strange: if setting a breakpoint for example on the last line and execute the object literal assignment in the console, then the value is correctly passed to 'global'.
BTW this would work as expected:
(function(global) {
    var id = "3543a1354";
    global.name = "global";
    global.getId = function() {
        return id;
    }
}(this.global = this.global || {}))

A: In both functions, global is a local variable, because it's a function parameter.
In the first case, you're creating a new object with the literal notation, and assigning this to the local variable. This has no effect on the variable that was used in the function call.
In the second case, you're modifying the properties of the object that the local variable refers to. This is the same object that the variable used in the function call refers to, so it's visible to the caller.

A: You are passing this.global to the function and inside the function global is the parameter which refers to the global global.
When you say,
global = {...}

you are now changing what global refers to. Since you have changed the reference, the global global is left unchanged and the local global refers to the newly assigned object.
In the second case,
global.name = "global";
global.getId = function () {..}

you are altering the local global object, which actually refers to the global global. So, you are indirectly changing global global. That is why, this mutates the global global and the first one didn't.


text:
Q: Android force-close on Google maps: java.lang.NoSuchFieldException: loading_tile_android One of my Android users is getting a force-close when launching Google Map (MapActivity class) inside my application. He gets a MissingResourceException. He's the only one complaining so far, and he is using Vanilla Tazz phone. The Google maps application itself works well on his device. It looks like it's something specific to Vanilla Tazz. I tried to find a fix online but have not been successful. Here's the Android error log:
java.lang.ExceptionInInitializerError
 at ...
 at android.view.View.performClick(View.java:2449)
 at android.view.View$PerformClick.run(View.java:9027)
 at android.os.Handler.handleCallback(Handler.java:587)
 at android.os.Handler.dispatchMessage(Handler.java:92)
 at android.os.Looper.loop(Looper.java:123)
 at android.app.ActivityThread.main(ActivityThread.java:4627)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:521)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
 at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ExceptionInInitializerError
 at com.google.android.maps.MapActivity.<clinit>(MapActivity.java:295)
 ... 14 more
Caused by: java.util.MissingResourceException: Could not find required resource
  com.android.internal.R$drawable.loading_tile_android    (java.lang.NoSuchFieldException:   loading_tile_android)
 at com.google.android.maps.InternalR.getField(InternalR.java:65)
 at com.google.android.maps.InternalR.get(InternalR.java:39)
 at com.google.android.maps.InternalR.access$000(InternalR.java:28)
 at com.google.android.maps.InternalR$drawable.get(InternalR.java:112)
 at com.google.android.maps.InternalR$drawable.<clinit>(InternalR.java:119)
 ... 15 more

I would appreciate if anyone can suggest anything to fix this.

A: Not sure you'll find a fix for this: it sounds like the ROM was built without that resource as part of the OS image. They'll probably need a new ROM to get around that.


text:
Q: Setup.exe can't find the .msi file I have a link to a "setup.exe" file that's on a website, and I would like for someone to be able to install an application off of the website by clicking on the link.  However, when I try testing this, a window comes up with an error message saying: An error occurred while attempting to install [Application Name].  A small log file for the setup.exe is created during this process, and the last line in the file reads: Unable to locate application file [filename].msi.  I must have done something wrong...
Some additional information:

*

*The msi file is for a Windows WPF application that I want to allow the user to install on his/her computer.

*When writing the Windows application, I noticed that there was a field in the properties for the Setup Project labeled Installation Url.  So I entered the url for the directory on the website which contains the .msi file.

At any rate, I'm sure I'm just missing a setting or something.  Any ideas are welcome!
Thanks!
Andrew

A: I don't know for sure, but you could try removing the setup.exe, and putting the .msi up on the website for users to download and run.  .msi's are runnable on their own.

A: I would put the MSI file on the web page as a link to a file and then the user can be prompted to download or install it right away.

A: Okay, this solution works:

*

*In the website, use Response.Redirect ("~/[Virtual File Path for setup.exe]");

*When compiling the setup project in Visual Studio, make sure that the Installation Url (right-click on the setup project in the solution explorer and go to properties) is pointing to the Url for the website folder containing the .msi file.  Also, I think this field is either case-sensitive, or it doesn't like a trailing forward slashes.  Until I changed these two things, it wasn't able to find my .msi file.

At any rate, maybe someone else won't be quite as frustrated by this as me:)
Andrew

A: Why not simply include everything in a zip or rar?  That seems far less complicated and comes out to do the exact same thing.  Also as for the comments about what Setup.exe does, it checks for the required version of .NET and (if properly configured) will install it if it is missing.  Just having the MSI will not.

A: *

*Press windows key + r

*Type cmd.exe, press enter

*cd \to\the\folder\containing\the\problem\file

*dir /x

*Note the short filename of the problem file. It will look for example like BLAH~1.

*del BLAH~1


text:
Q: EF Code First 1:0..1 relationship error: Multiplicity is not valid in Role 'EFEmployee_Identity_Source' in relationship 'EFEmployee_Identity' Full error:

One or more validation errors were detected during model generation:
EFEmployee_Identity_Source: : Multiplicity is not valid in Role 'EFEmployee_Identity_Source' in relationship 'EFEmployee_Identity'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

I am dealing with three types of entities: EFEmployee, EFPerson, and EFOffice. It's kind of weird that I'm getting this error because the code I'm testing only creates an instance of an EFOffice entity. Anyway, here is the EFEmployee entity class:
[Table("employee_entity")]
public class EFEmployee : EFBusinessEntity
{
    [ForeignKey("Office")]
    public Guid OfficeID { get; set; }

    [ForeignKey("Identity")]
    public Guid PersonID { get; set; }

    [Column("hire_date")]
    public DateTime HireDate { get; set; }

    [Column("job_title")]
    public byte[] JobTitle { get; set; }

    [Column("salary")]
    public int Salary { get; set; }

    [Column("certifications")]
    public byte[] Certifications { get; set; }

    [Column("vacation_time")]
    public int VacationTime { get; set; }

    [Column("sick_time")]
    public int SickTime { get; set; }

    public virtual EFOffice Office { get; set; }

    public EFPerson Identity { get; set; }

    public virtual EFEmployee ReportingTo { get; set; }
}

And this is my EFPerson entity class:
[Table("person_entity")]
public class EFPerson : EFBusinessEntity
{
    [Column("first_name")]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Column("last_name")]
    [StringLength(50)]
    public string LastName { get; set; }

    [Column("phone_num")]
    public uint? PhoneNum { get; set; }

    [Column("date_of_birth")]
    public DateTime DateOfBirth { get; set; }

    public EFEmployee Employee { get; set; }
}

You can see that they both inherit from EFBusinessEntity, which is here:
[Table("business_entity")]
public abstract class EFBusinessEntity : IBusinessEntity
{
    [Column("tenant_id")]
    public Guid TenantId
    {
        get;
        set;
    }

    [Column("id")]
    [Key]
    public Guid Id
    {
        get;
        set;
    }
}

As you can see, there is a one-to-zero-or-one relationship between EFEmployee and EFPerson, with EFEmployee being the dependent side since there can be a person who is not an employee, but there can't be an employee who is not a person too. Since EFEmployee is the dependent side, I have added a PersonID in EFEmployee with the data annotation (attribute?) above denoting that it's the foreign key to Person:
[ForeignKey("Identity")]
public Guid PersonID { get; set; }

I think I've made it pretty clear for Entity Framework that this is a 1:0..1 relationship. Does anyone know how to solve this error using data annotations (or attributes, whatever those square bracket things above properties are). I can't use fluent API for reasons I'm not getting into.

A: Generally, with 1:0..1 relationships in Entity Framework, the dependent side needs to use its primary key as the foreign key. Fortunately, for your case, this doesn't seem like it would be a bad idea. You would need to:

*

*Remove the EFEmployee.PersonID property

*Add [ForeignKey("Id")] to EFEmployee.Identity
Edit: May not work because key and navigation property are on separate classes. See this.
Having EFEmployee inherit from EFPerson seems like it might be a viable option as well. Inheritance uses TPH by default, but if you want to use TPT (table-per-type), add the [Table] attribute to your type.

A: I did some more playing around with the models and found out what was wrong. So I kept the foreign key attribute with EFPerson.Identity like jjj suggested:
[ForeignKey("PersonID")]
public virtual EFPerson Identity { get; set; }

Then the other change I had to make was in the EFPerson class. In my EFPerson class I had the navigation property to EFEmployee:
public virtual EFEmployee Employee { get; set; }

However, since this is a 1:0..1 relationship with EFEmployee being the dependent side (i.e. the non-essential side), I removed that navigation property, and when I ran my test it worked.