text:
Q: Windows 7 Update: 1 out of 30 never completes For the past two days, whenever I want to shut down my laptop, there is the little yellow arrow indicating that while shutting down, Windows 7 will configure/install new updates. No problem, right? Just click shut down, the updates will install and life will go on as usual. Wrong. The update has been stuck at 1 out of 30... and no matter how long I leave it, it never completes and shuts down.
I have been shutting it down manually (by holding down the power button) and whenever I turn it on and want to shut down the update is still there. Any ideas of how to either get it complete or get rid of it?

A: *

*Open your Windows Update under Start -> All Programs.

*Look at your Update-History. There should be one Update failing each time. Double click it.

*In that window that pops up, there is a link that looks like http://support.microsoft.com/kb/anyKbNumber. Click that link.

*The download-page for this update opens. Download it and install it manually (don't forget to right-click it and choose "Run as Administrator")

Manually installing an update is often the solution for stucking updates.
If that update is Win 7 SP1 you SHOULD install it manually to prevent breaking your system if you have had problems with it (SP1 crashed a few PCs over here).
If manually installing that update doesn't work, tell us your error-description (if any).

A: I agree with the manual installation. Also, I have also found that the updates won't configure if you're not online during the process. http://windows.microsoft.com/en-US/windows7/products/features/windows-update


text:
Q: Writing strings with chars like "ñ" to a txt file Im having a strange issue trying to write in text files with strings which contain characters like "ñ", "á".. and so on. Let me first show you my little piece of code:
import java.io.*;

public class test {

public static void main(String[] args) throws Exception {

    String content = "whatever";

    int c;
    c = System.in.read();
    content = content + (char)c;

    FileWriter fw = new FileWriter("filename.txt");
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
    bw.close();

}

}

In this example, im just reading a char from the keyboard input and appending it to a given string; then writting the final string into a txt. The problem is that if I type an "ñ" for example (i have a Spanish layout keyboard), when i check the txt, it shows a strange char "¤" where there should be a "ñ", that is, the content of the file is "whatever¤". The same happens with "ç", "ú"..etc. However it writes it fine ("whateverñ") if i just forget about the keyboard input and i write:
...
String content = "whateverñ";
...

or
...
content = content + "ñ";
...

It makes me think that there might be something wrong with the read() method? Or maybe im using it wrongly? or should i use a different method to get the keyboard input? or..? Im a bit lost here.
(Im using the jdk 7u45 @ Windows 7 Pro x64)

A: So ...

*

*It works (i.e. you can read the accented characters on the output file) if you write them as literal strings.

*It doesn't work when you read them from System.in and then write them.
This suggests that the problem is on the input side.  Specifically, I think your console / keyboard must be using a character encoding for the input stream that does not match the encoding that Java thinks should be used.
You should be able to confirm this tentative diagnosis by outputting the characters you are reading in hexadecimal, and then checking the codes against the unicode tables (which you can find at unicode.org for example).

It strikes me as "odd" that the "platform default encoding" appears to be working on the output side, but not the input side.  Maybe someone else can explain ... and offer a concrete suggestion for fixing it.  My gut feeling is that the problem is in the way your keyboard is configured, not in Java or your application.

A: files do not remember their encoding  format, when you look at a .txt, the text editor makes a "best guess" to the encoding used.
if you try to read the file into your program again, the text should be back to normal.
also, try printing the "strange" character directly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Modifying Email Headers in Mailbox I have a whole heap of emails sitting on my mailbox in an Exchange server that originated from a POP3 download and forward application - which means that the "Received" datestamp reflects the time that it was delivered to Exchange as opposed to when it was sent (which varies up to 3 weeks). I know that you can filter by send date but since the default outlook view is to order the "received on" field, and I'm incredibly stubborn I'm looking for a completely backwards solution to my issue.
I'd like to change the "received on" header information to reflect the datestamp in the "Sent On" part of the header and then apply the change back into the mailbox.
At the moment all I've been able to do is come up with a way to read the header info via Powershell but have been unable to write back to it.
I'm open to any method via PS or PHP.
Any suggestions would be greatly appreciated!

A: What version of Exchange are you using ? Can you access the server using Exchange Web Services ? if you can then you should be able to access the Extended properties for the Sent and Received Time and modify them if necessary eg the following would enumerate all the messages in the Inbox and modify the Received-date if the difference between the Sent and Received time is more then 60 minutes
    ## Get the Mailbox to Access from the 1st commandline argument

$MailboxName = $args[0]

## Load Managed API dll

###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
$EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
if (Test-Path $EWSDLL)
    {
    Import-Module $EWSDLL
    }
else
    {
    "$(get-date -format yyyyMMddHHmmss):"
    "This script requires the EWS Managed API 1.2 or later."
    "Please download and install the current version of the EWS Managed API from"
    "http://go.microsoft.com/fwlink/?LinkId=255472"
    ""
    "Exiting Script."
    exit
    }

## Set Exchange Version
$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2

## Create Exchange Service Object
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)

## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials

#Credentials Option 1 using UPN for the windows Account
$psCred = Get-Credential
$creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())
$service.Credentials = $creds

#Credentials Option 2
#service.UseDefaultCredentials = $true

## Choose to ignore any SSL Warning issues caused by Self Signed Certificates

## Code From http://poshcode.org/624
## Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() {
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert,
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly

## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

## end code from http://poshcode.org/624

## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use

#CAS URL Option 1 Autodiscover
$service.AutodiscoverUrl($MailboxName,{$true})
"Using CAS Server : " + $Service.url

#CAS URL Option 2 Hardcoded

#$uri=[system.URI] "https://casservername/ews/exchange.asmx"
#$service.Url = $uri

## Optional section for Exchange Impersonation

#$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)

# Bind to the Inbox Folder
$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)

$PR_MESSAGE_DELIVERY_TIME = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0E06, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::SystemTime)
$PR_CLIENT_SUBMIT_TIME = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0039, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::SystemTime)

$psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$psPropset.Add($PR_CLIENT_SUBMIT_TIME)
$psPropset.Add($PR_MESSAGE_DELIVERY_TIME)
#Define ItemView to retrive just 1000 Items
$ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
$ivItemView.PropertySet = $psPropset
$fiItems = $null
$type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.Item" -as "Type")
$Items = [Activator]::CreateInstance($type)
do{
    $fiItems = $service.FindItems($Inbox.Id,$ivItemView)
    foreach($Item in $fiItems.Items){
        $ClientSubmitTime = $null
        $DeliveryTime = $null
        [Void]$Item.TryGetProperty($PR_CLIENT_SUBMIT_TIME,[ref]$ClientSubmitTime)
        [Void]$Item.TryGetProperty($PR_MESSAGE_DELIVERY_TIME,[ref]$DeliveryTime)
        if($ClientSubmitTime -ne $null -band $DeliveryTime -ne $null){
            $TimeSpan =  NEW-TIMESPAN –Start $ClientSubmitTime –End $DeliveryTime
            $rptobj = "" | select Action,Subject,DELIVERY_TIME,SUBMIT_TIME,Diff
            $rptobj.Subject = $Item.Subject
            $rptobj.DELIVERY_TIME = $DeliveryTime
            $rptobj.SUBMIT_TIME = $ClientSubmitTime
            $rptobj.Diff = [Math]::Round($TimeSpan.TotalMinutes,0)
            if($TimeSpan.TotalMinutes -lt -60 -bor $TimeSpan.TotalMinutes  -gt 60 ){
                $rptobj.Action = "Processing"
                Write-Output $rptobj
                $Item.SetExtendedProperty($PR_MESSAGE_DELIVERY_TIME,$ClientSubmitTime)
                $Items.Add($Item)
            }
            else{
                $rptobj.Action = "Skip"
                #Write-host ($rptobj)
            }
        }

    }
    $ivItemView.Offset += $fiItems.Items.Count
}while($fiItems.MoreAvailable -eq $true)
$BatchUpdateItems = [Activator]::CreateInstance($type)
foreach($Item in $Items){
    $BatchUpdateItems.Add($Item)
    if($BatchUpdateItems.Count -ge 50){
        Write-Host ("Updating " + $BatchUpdateItems.Count)
        $Result = $null
        $Result = $service.UpdateItems($BatchUpdateItems,$SubFolder.Id,[Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite,[Microsoft.Exchange.WebServices.Data.MessageDisposition]::SaveOnly,[Microsoft.Exchange.WebServices.Data.SendInvitationsMode].SendToNone)
        [INT]$collectionCount = 0
        [INT]$Rcount = 0
        [INT]$Errcount = 0
        if($Result -ne $null){
            foreach ($res in $Result){
                if ($res.Result -eq [Microsoft.Exchange.WebServices.Data.ServiceResult]::Success){
                    $Rcount++
                }
                else{
                    $Errcount++
                }
                $collectionCount++
            }
        }
        else{
            Write-Host -foregroundcolor red ("Update Result Null Exception")
        }
        Write-host ($Rcount.ToString() + " Items Updated Successfully " + "Total Processed " + $nmbProcessed + " Total Folder Items " + $Items.Count)
        if($Errcount -gt 0){
            Write-Host -foregroundcolor red ($Errcount.ToString() + " Error failed Update")
        }
        $BatchUpdateItems.Clear()
    }
}
if($BatchUpdateItems.Count -gt 0){
        Write-Host ("Updating " + $BatchUpdateItems.Count)
        $Result = $null
        $Result = $service.UpdateItems($BatchUpdateItems,$SubFolder.Id,[Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite,[Microsoft.Exchange.WebServices.Data.MessageDisposition]::SaveOnly,[Microsoft.Exchange.WebServices.Data.SendInvitationsMode].SendToNone)
        [INT]$collectionCount = 0
        [INT]$Rcount = 0
        [INT]$Errcount = 0
        if($Result -ne $null){
            foreach ($res in $Result){
                if ($res.Result -eq [Microsoft.Exchange.WebServices.Data.ServiceResult]::Success){
                    $Rcount++
                }
                else{
                    $Errcount++
                }
                $collectionCount++
            }
        }
        else{
            Write-Host -foregroundcolor red ("Update Result Null Exception")
        }
        Write-host ($Rcount.ToString() + " Items Updated Successfully " + "Total Processed " + $nmbProcessed + " Total Folder Items " + $Items.Count)
        if($Errcount -gt 0){
            Write-Host -foregroundcolor red ($Errcount.ToString() + " Error failed Update")
        }
        $BatchUpdateItems.Clear()
}

Cheers
Glen


text:
Q: Google Maps showing orange tiles for satellite view I noticed this morning that the GMSMapView and GoogleMap of our iOS and Android apps are starting to show tiles with an abnormal orange tint. I've attached a screenshot of the app that captures the original tiles being replaced by orange tiles.
I'm wondering whether anyone else is seeing this issue, and whether there is some configuration I missed that can get the map back to pulling the original tiles.
Screenshot

A: Those tiles come from a different (presumably newer) series of sat images, taken from a different angle with a different cam at a different time of day etc.
Under these circumstances, minor differences in tint are not unexpected.


text:
Q: Spring Data JPA - Class-based projections with Specification and Pageable I am trying to identify the best approach for the following scenario. I have few entities in my project where I am applying some concepts of Spring Data JPA in order to have a great service to load entities with DTOs and it is not so difficult to provide maintenance when needed.
@Entity
class Order {
  Long id;
  Datetime createdDate;
  String note;
  List<Item> items;
...
}
@Entity
class Item {
  Long id;
  Order order;
  ...
}

Currently, I have a service method based on the specification and pageable classes to load my objects.
public Page findAll(Specification spec , Pageable pageable) {
    return repository.findAll(spec,pageable);
}

This approach is working fine, however, it has some performance issues. I would like to use class-based projections with the specification and pageable classes. Do you guys have a recommendation or an example using this approach?
Regards,
Caique Ferreira

A: This feature is not yet supported, here is a bug tracker for it.


text:
Q: How do I refer to a word using all variations, no matter the size of the letters within the words? Alright, so I am making a Discord bot, and I'm trying to set parameters for words that aren't allowed to be said in the server (You know the kind, slurs and the like). So, I put a slur (I'll just use the word "dog" as an example), but it was only lowercase. So basically, it's just "dog", and if someone says "dog" in chat, then their message will be deleted, and the bot sends them a message through DMs. But, if someone were to say "Dog", then they wouldn't get their message deleted.  What should I add to the code to make sure that all variations of the slur get picked up?
I'm incredibly new to any form of coding, and I have gotten a ton of help from my friends to make this bot, so I really have no clue about what I'm doing.
(if you want to see the code, here it is.  I replaced all the slurs with words, but I think you get the gist):
   "bannedWords":[
       "apple",
      "dog",
      "bird",
      "cat"
   ],
   "code":""
}

I expect the words "dog", "Dog", "DOg", "DOG", "dOG", "doG", "DoG", "dOg", etc. to be identified instead of just "dog".

A: This is actually a very complex question.
The most simple approach would be creating an array of banned words on lower-case and comparing it to the string after manipulating it completely to lower cause using something like .toLower() or .toLowerCase() in JavaScript.
But that wouldn't stop from users trying to bypass your list by using similar characters and even ASCII characters as a replacement, like dög, d0g or even døg.
Solving that actually is the complex part of the question.
One option is using Regex wildcards like  the . operator.
\d.g\
Will match dog, dög....

But that would be very impractical and time consuming, not to mention the computational cost if your banned list is long.
There are several ways on how this could be accomplished, the easiest ones, like described above would suit just fine some friends-only-server as you just described, but in situations where the detection of those words are critical, using Stemming Algorithms, Fuzzy Matching, Regular Expressions and Machine Learning like described in this article, are all valid options and optimal if combined with each other efficiently.


text:
Q: Proving maps conformal via a scaling factor I'm in a differential geometry class and I just attended a review session where the TA gave an example problem about conformal maps on the board:
Find a constant $k$ such that $x(u,v) = (e^{(kv)}cos(v), e^{(kv)}sin(v), e^{(kv)}$ is a conformal parameterization of the cone $z = \sqrt{(x^2+y^2)}$.
So he computed the $E$, $F$ (which is $0$ for any choice of $k$) and $G-$ metric for $x(u,v)$, and set them equal to some scaling factor $λ^2$ times what I assume is the respective $E$ and $G$ of the space being mapped to? $E(x) = λ^2(<1,0><0,1>)$ and $G(x)=λ^2(<1,0><0,1>)$ is what he put.
The $<1,0>$ and $<0,1>$ look like the partial derivatives in respect to $u$ and $v$ of $(u,v)$, but I'm not sure where he got them from. Any ideas?
Also sorry about the lack of typesetting, I don't have latex or anything and I've never posted here before.

A: $$ x(u,v) = e^{kv}(\cos\ u,\sin\ u,1)$$ Then $$ dx e_1=x_u = e^{kv} (-\sin\ u,\cos\ u,0),\ dx e_2=x_v=k x(u,v) $$
so that $$ E=e^{2kv},\ F=0,\ G=2k^2e^{2kv} $$
That is, if $2k^2=1$ then $$ (dx\ v,dx\ w)=\lambda (v,w)$$ where $$\lambda =E=G=e^{\sqrt{2}v}$$


text:
Q: laravel blade syntaxx not working properly I'm using laravel 9. I have stored data using summer note in the database, but it shows empty or null when I retrieve data from the database.
here is my code.
{!! Str::of($item->product_description)->limit(40) !!}

A: Try this
{!! Str::limit($item->product_description,40) !!}


text:
Q: Limiting results for non-unique eigenvalues and eigenvectors for a sample covariance matrix I am working on the limiting behavior for the eigenvalue and the corresponding eigenvectors, especially the minimum eigenvalues. For instance, let $S_X=\frac{1} {T} \sum_t X_t X_t ^\prime$ be a $p \times  p$ sample covariance matrix, and $p$ is finite. Let $\lambda_i$ be the eigenvalues of $S_X$ such that $\lambda_1 \ge \lambda_2 \ge ...\ge \lambda_p$, and let $e_i$ be the corresponding eigenvector of $\lambda_i$ for $i=1,...,p$. The limiting behavior of both $\lambda_p$ and $e_p$ are well established if $\lambda_i$ is distinct for large $T$.
However, my problem is whether the limiting behavior will change if the eigenvalues are not distinct. For instance, if $\lambda_p =\lambda_{p-1}$, then what's the limiting behavior of $e_p$ and $e_{p-1}$ as $T \to \infty $. Any related reference for this particular issue since my estimator depends on the eigenvectors corresponding the minimum eigenvalue?


text:
Q: Problema ao criar projeto Toda vez que tento criar um projeto no Eclipse Luna para Android no Console da várias mensagens de erros. Eu já instalei o ADT e o SDK normal.
Agora não consigo mais fazer nada porque o projeto fica dando erro e nem compila sem erros mais.

A: Use o Android Studio ele tem suporte total ao Android e é passível da utilização dos plugins da Jetbrains, o Google não fornece mais suporte ao ADT (plugin do eclipse para desenvolver Android), logo o ADT tende a não suportar as novas APIs do Android (que atualmente esta na revisão 22).
Nota sobre ADT:

Note: If you have been using Eclipse with ADT, be aware that Android
  Studio is now the official IDE for Android, so you should migrate to
  Android Studio to receive all the latest IDE updates. For help moving
  projects, see Migrating to Android Studio.

Fonte: http://developer.android.com/tools/help/adt.html

A: Coloque o erro para gente compreender melhor o que está acontecendo.  Mas,  como muitos já disseram,  é recomendado,  praticamente forçado xD ,  o uso do Android Studio para desenvolvimento dos aplicativos.  Eu particularmente recomendo e vejo imensas vantagens sobre o eclipse.

A: Para resolver seu problema teria que ser necessário ler as mensagens de erro que aparecem no seu console. Mas por via das duvidas, se você é um iniciante em desenvolvimento android, recomendo que comece a utilizar o Android Studio, pois o mesmo já a algum tempo é a IDE oficial para desenvolvimento em android e creio que nela não terá esses problemas.


text:
Q: Emulate MyISAM's composite primary key with an autoincrement behavior in InnoDB In MySQL, if you have a MyISAM table that looks something like:
CREATE TABLE `table1` (
`col1` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`col2` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`col2`, `col1`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM;

if you insert rows then the autoincrement base will be unique for every distinct col2 value. If my explanation isn't clear enough, this answer should explain better. InnoDB, however, doesn't follow this behavior. In fact, InnoDB won't even let you put col2 as first in the primary key definition.
My question is, is it possible to model this behavior in InnoDB somehow without resorting to methods like MAX(id)+1 or the likes? The closest I could find is this, but it's for PostgreSQL.
edit: misspelling in title

A: It's a neat feature of MyISAM that I have used before, but you can't do it with InnoDB. InnoDB determines the highest number on startup, then keeps the number in RAM and increments it when needed.
Since InnoDB handles simultaneous inserts/updates, it has to reserve the number at the start of a transaction. On a transaction rollback, the number is still "used" but not saved. Your MAX(id) solution could get you in trouble because of this. A transaction starts, the number is reserved, you pull the highest "saved" number + 1 in a separate transaction, which is the same as that reserved for the first transaction. The transaction finishes and the reserved number is now saved, conflicting with yours.
MAX(id) returns the highest saved number, not the highest used number. You could have a MyISAM table whose sole purpose to to generate the numbers you want. It's the same number of queries as you MAX(id) solution, it's just that one is a SELECT, the other an INSERT.


text:
Q: add row and searchable dropdown is not working together I am trying add row with searchable dropdown list. I can add or delete row and searchable dropdown menu works separately. If I try to add row and normal dropdown list then it works fine. But when I add row then in new row searchable dropdown list is not working. I am trying below code.
So could anyone help my to solve this issue ?
<!DOCTYPE html>

<link href="style.css" rel="stylesheet">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />

     POI
    Quantity
    Price
    Product
    Add Rows

    1
    <input size=25 type="text" id="lngbox" readonly=true/>
    <input size=25 type="text" id="price" readonly=true/>

      <select id="select-state" placeholder="Pick a state...">
        <option value="">Select a state...</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="DE">Delaware</option>
        <option value="DC">District of Columbia</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="HI">Hawaii</option>
        <option value="ID">Idaho</option>
        <option value="IL">Illinois</option>
        <option value="IN">Indiana</option>
      </select>

    <input type="button" id="delProducts" value="Delete" onclick="deleteRow(this)"/>
    <input type="button" id="addmoreProducts" value="AddMore" onclick="insRow()"/>


text:
Q: Linux dynamic alias I am very new to Linux. I just found the alias command which is very useful as I quite often have to dig through log files
So I need to regularly open text files
they are generally stored in the format
...\somename\somename_yyyymmdd.log
how can I create a dynamic alias that can take the current folder name as input as well as the current date to create a command like?
less somename_20121024.log
Thanks

A: The alias command is for making shortcuts for regularly issued commands. The most commonly used linux shell, bash, does not support parameter expansion within aliases, which makes it a little less suitable for your purpose. What you're trying to do is better accomplished using a function. This one is in bash:
lesslog() {
   local dir=$1
   local mydate=${2:-$(date +%Y%m%d)}
   if [[ -f ${dir}/${dir}_${mydate}.log ]]; then
       less ${dir}/${dir}_${mydate}.log
   else
       echo "Could not find log file: ${dir}/${dir}_${mydate}.log"
   fi
}

This function will look for the logfile in the directory passed. If you don't pass in a second parameter, it will default to today's date.

A: If you are using Bash you can use functions in your ~/.bashrc for this. For example:
function less_log() {
  less log-`date +%Y%m%d`
}
export -f less_log

export -f means that you export a function.


text:
Q: How to create HTML table dynamicly using PHP? I am trying to create a simple HTML table dynamically using PHP for loop.
The table will finally need to loop like this

Training Info

Last Training On
<input name="text_1" value="" class="form-control" placeholder="Click here" type="1">
New Field
<input name="text_2" value="" class="form-control" placeholder="Blah Blah" readonly="readonly" type="2">

More To input
<input name="text_4" value="" class="form-control" placeholder="Start Typing ...." type="4">
Your Opinion
<textarea name="textArea_3" value="" class="form-control" rows="3"></textarea>

Unfortunately, the PHP code is not generate the code correctly. Instead of generating the correct syntax listed above, it generate the bottom code

Training Info

Last Training On
<input name="text_1" value="" class="form-control" placeholder="Click here" type="1">
New Field
<input name="text_2" value="" class="form-control" placeholder="Blah Blah" readonly="readonly" type="2">
More To input
<input name="text_4" value="" class="form-control" placeholder="Start Typing ...." type="4">
Your Opinion
<textarea name="textArea_3" value="" class="form-control" rows="3"></textarea>

This is my PHP code that is used to generate the table
private function generateFields(){

    $ds = $this->readSpecs();
    $ds_count = count($ds);
    $table_class = '';

    if(!empty($this->tableClass))
        $table_class = ' class="'.$this->tableClass.'" ';

    $this->output .= '
'. "\n";
    $this->output .= '
'. "\n";
    for($i=0; $i< $ds_count; ++$i){
        $f = $ds[$i];

        //insert new header
        if($i == 0 || ($f['block_id'] != $ds[$i-1]['block_id']  )  )
            $this->output .= '
'.$f['block_title'].'
'. "\n";

        //START NEW ROW IN THE TABLE IF THIS LOOP IS THE FIRST ROUND OR RUN IS EVEN
        //new row if the
        if( $i == 0 || ($i+1 % 2) != 0 )
            $this->output .= '
'. "\n";

        /********* START DISPLAY BLOCKS *********/
        if($f['field_type'] == 'TEXT' || $f['field_type'] == 'NUMBER')
            $this->output .= ''. $f['display_label'].'	'."\n".
                             '' . $this->generateTextField($f['field_id'], $f['css_class'], $f['is_editable'], $f['placeholder']) .'	'. "\n";

        if($f['field_type'] == 'TEXTAREA')
            $this->output .= ''. $f['display_label'].'	'."\n".
                             '' .$this->generateTextAreaField($f['field_id'], $f['css_class'], $f['is_editable'], $f['rows']).'	' . "\n";

        //FIX HTML TABLE
        //add the last 2 cells if the results are odd
        if( $i == $ds_count - 1  && ($i+1 % 2) != 0)
            $this->output .= '		'. "\n";

        /********* END DISPLAY BLOCKS *********/

        //IF THIS RUN IS EVEN THEN CLOSE THE ROW
        if( $i+1 % 2 == 0 || $i == $ds_count - 1 )
            $this->output .= '
'. "\n";
    }
    $this->output .= '
'. "\n";
    $this->output .= '
'. "\n\n";

}

A: $i+1 % 2 == 0

will never be true (well... except if $i == -1), because % has higher precedence than + in the order of operations, which means  this is the same as
$i + (1 % 2)

which is the same as
$i + 1

So change it to ($i + 1) % 2 and it should work.
Edit:  same issue with this part: ($ds_count - 1 % 2)


text:
Q: Update one JSON array element with a second JSON based on third JSON with jq I have four files:
input.json
{
  ".properties.on_demand_service_plans_collection": {
    "type": "collection",
    "value": [
      {
        "plan_name": "my-plan",
        "plan_description": "my-plan",
        "account_name": "vault-supplied-value"
        "account_access_key": "vault-supplied-value"
      },
      {
        "plan_name": "my-plan-test",
        "plan_description": "my-plan-test",
        "account_name": "vault-supplied-value",
        "account_access_key": "vault-supplied-value"
      }
    ],
    "optional": false
  }
}

vault.json
{
  "appd": {
    "account_key": "appd-key",
    "account_name": "appd-user"
  },
  "aws": {
    "access_key_id": "my-key-id",
    "region": "us-east-1",
    "secret_access_key": "my-secret-key"
  }
}

keyfile.json
[
  [[".properties.on_demand_service_plans_collection", "value[0]", "account_name"], ["appd", "account_name"]],
  [[".properties.on_demand_service_plans_collection", "value[0]", "account_access_key"], ["appd", "account_key"]],
  [[".properties.on_demand_service_plans_collection", "value[1]", "account_name"], ["appd", "account_name"]],
  [[".properties.on_demand_service_plans_collection", "value[1]", "account_access_key"], ["appd", "account_key"]]
]

valut.jq
reduce $keyfile[] as $p (.; setpath(($p|.[0]); $vault|getpath($p|.[1])))

This is my jq command:
jq --argfile keyfile keyfile.json --argfile vault vault.json -f vault.jq input.json > desired.json

desired.json
{
  ".properties.on_demand_service_plans_collection": {
    "type": "collection",
    "value": [
      {
        "plan_name": "my-plan",
        "plan_description": "my-plan",
        "account_name": "appd-key",
        "account_access_key": "appd-user"
      },
      {
        "plan_name": "my-plan-test",
        "plan_description": "my-plan-test",
        "account_name": "appd-key",
        "account_access_key": "appd-user",
        "controller_host": "example.com"
      }
    ],
    "optional": false
  }
}

I'm not coding the keyfile.json file correctly, because I am not getting the desired results.
I've tried every iteration of the keyfile.json I can think of, but to no avail.
Does anyone have any ideas?
Thanks in advance.
what-i-get.json
{
  ".properties.on_demand_service_plans_collection": {
    "type": "collection",
    "value": [
      {
        "plan_name": "my-plan",
        "plan_description": "my-plan",
        "account_name": "vault-supplied-value",
        "account_access_key": "vault-supplied-value"
      },
      {
        "plan_name": "my-plan-test",
        "plan_description": "my-plan-test",
        "account_name": "vault-supplied-value",
        "account_access_key": "vault-supplied-value"
      }
    ],
    "optional": false,
    "value[0]": {
      "account_name": "appd-user",
      "account_access_key": "appd-key"
    },
    "value[1]": {
      "account_name": "appd-user",
      "account_access_key": "appd-key"
    }
  }
}

A: I believe it's just the syntax used in your keyfile - It is causing a string literal "value[0]" to be created instead of the array index 0 being referenced in the path substitution.
Try use the syntax
"value",0,"account_name"
Instead of
"value[0]","account_name"
Using the below as keyfile.json:
[
  [["properties.on_demand_service_plans_collection", "value",0, "account_name"], ["appd", "account_name"]],
  [["properties.on_demand_service_plans_collection", "value",0, "account_access_key"], ["appd", "account_key"]],
  [["properties.on_demand_service_plans_collection", "value",1, "account_name"], ["appd", "account_name"]],
  [["properties.on_demand_service_plans_collection", "value",1, "account_access_key"], ["appd", "account_key"]]
]

Produces desired.json:
{
  ".properties.on_demand_service_plans_collection": {
    "type": "collection",
    "value": [
      {
        "plan_name": "my-plan",
        "plan_description": "my-plan",
        "account_name": "appd-user",
        "account_access_key": "appd-key"
      },
      {
        "plan_name": "my-plan-test",
        "plan_description": "my-plan-test",
        "account_name": "appd-user",
        "account_access_key": "appd-key"
      }
    ],
    "optional": false
  }
}

Sidenote:
If it helps, the way I came across the proper syntax after some headscratching was to view the output as a stream in compact format:
jq -c '. | tostream' input.json

[[".properties.on_demand_service_plans_collection","optional"],false]
[[".properties.on_demand_service_plans_collection","type"],"collection"]
[[".properties.on_demand_service_plans_collection","value",0,"account_access_key"],"vault-supplied-value"]
[[".properties.on_demand_service_plans_collection","value",0,"account_name"],"vault-supplied-value"]
[[".properties.on_demand_service_plans_collection","value",0,"plan_description"],"my-plan"]
[[".properties.on_demand_service_plans_collection","value",0,"plan_name"],"my-plan"]
[[".properties.on_demand_service_plans_collection","value",0,"plan_name"]]
[[".properties.on_demand_service_plans_collection","value",1,"account_access_key"],"vault-supplied-value"]
[[".properties.on_demand_service_plans_collection","value",1,"account_name"],"vault-supplied-value"]
[[".properties.on_demand_service_plans_collection","value",1,"plan_description"],"my-plan-test"]
[[".properties.on_demand_service_plans_collection","value",1,"plan_name"],"my-plan-test"]
[[".properties.on_demand_service_plans_collection","value",1,"plan_name"]]
[[".properties.on_demand_service_plans_collection","value",1]]
[[".properties.on_demand_service_plans_collection","value"]]
[[".properties.on_demand_service_plans_collection"]]


text:
Q: Attempted to load class "Spreadsheet" from namespace "PhpOffice\PhpSpreadsheet" - Symnfony4 I have already imported PhpSpreadSheet in my controller.

I do this for calling the lib :

The libs is present in my vendor folder.
(PHP 7.3)
Why I have the error below ??
"Attempted to load class "Spreadsheet" from namespace "PhpOffice\PhpSpreadsheet".↵Did you forget a "use" statement for another namespace"
Thanks

A: I update symfony flex and it's work.
Thanks for you help.


text:
Q: Good date format on x-axis matplotlib I have the following dataframe:
Time    test
0:05    2
0:06    2
0:07    2
0:08    2
0:09    2
0:10    2
0:11    2

This datframe starts at 0:00 and ends at 11:59. I created the following graph with:
x = dftestgraph['Time']
y = dftestgraph['test']
plt.ylabel('Number of tasks')
plt.plot(x, y, color="#00a1e4", label="Number of Tasks")
plt.fill(x, y, '#00a1e4', alpha=0.8)
plt.show()

Why is there a line in the bottom of the graph, that splits my filled graph in half? And I would like to format my x-axis as ( 0:00, 0:30, 1:00 etc.) I tried:
plt.xticks(0:00, 11:59, 30:00))

However this does not work.
My question is:

*

*Why is there a line in my graph and how can I solve this?

*How to set the x-axis in the correct format?

A: plt.fill basically links the first and last point of the time series to build its polygon. I would use fill_between instead.
I've put together a MWE below that shows how it can be done. It also show a way to format the xaxis labels as you wanted, derived from the following posts: Creating graph with date and time in axis labels with matplotlib and Plotting time in Python with Matplotlib.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import dates
import datetime

plt.close('all')

#---- generate some data ----

t = [datetime.datetime(2015, 1, 1, 0) +
     datetime.timedelta(hours=i) for i in np.arange(0,12.1,0.5)]
x = np.random.rand(len(t))

#---- create figure and axe ----

fig = plt.figure()

ax = fig.add_axes([0.1, 0.2, 0.85, 0.75])

#---- format xaxis ----

# position of the labels
xtk_loc = [datetime.datetime(2015, 1, 1, 0) +
           datetime.timedelta(hours=i) for i in np.arange(0,12.1,0.5)]
ax.set_xticks(xtk_loc)
ax.tick_params(axis='both', direction='out', top='off', right='off')

# format of the labels
hfmt = dates.DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(hfmt)
fig.autofmt_xdate(rotation=90, ha='center')

#---- set axes labels ----

ax.set_ylabel('Number of tasks', labelpad=10, fontsize=14)
ax.set_xlabel('Time', labelpad=20, fontsize=14)

#---- plot data ----

ax.plot(t, x, color="#004c99", label="Number of Tasks")
ax.fill_between(t, x, 0, facecolor='#00a1e4', alpha=0.5, lw=0.5)

#---- set axis limits ----

timemin = datetime.datetime(2015, 1, 1, 0)
timemax = datetime.datetime(2015, 1, 1, 12)

ax.axis(xmin=timemin, xmax=timemax)

plt.show()

which results in:


text:
Q: React-semantic-ui with route errors I have a basic menu imported from react semantic-ui

<Menu secondary vertical>
        <Menu.Item
          name='account'
          active={activeItem === 'account'}
          onClick={this.handleItemClick}
        />

I obviously have more items and I modified such that each item from the menu links to a different page:

<Menu secondary vertical>
         <Link to="/account">
         <Menu.Item
          name='account'
          active={activeItem === 'account'}
          onClick={this.handleItemClick}
        />
        </Link>

The code obviously works as expected however I am getting the error
<a> cannot appear as a descendant of <a>

So I modified the code to <Menu.item as='div' and it still works however it loses some functionalities. Basically before I was able to hover on the menu item and it would show the result in the picture. To get on "account" the same result, I have to click twice. If I leave Menu.item as 'a' it works.
Any way I could fix that?
Picture 1

A: You should not be using Link and Menu.Item like that.
You could do something similar to what you already did with as property. You could say
<Menu.Item
   as={Link}
   to={"/account"}
   name='account'
   active={activeItem === 'account'}
   onClick={this.handleItemClick}
>
    Account
</Menu.Item>

This means you need to import {Link} from react-router-dom which I suppose you already did

A: A workaround (if you do not need anchor tag for some reason) is to handle it in method handleItemclick:

handleItemClick = (e) => {
  //..code
  this.props.history.push('/myroute');
}


text:
Q: Input a date and give a date in the future I am letting a user input a date. How should I return a date from their input and add 3 years to it? I tried to use mktime and date but it did not work out very well.
$input_date = 2010-03-28

My solution currently is just basic math for a given date 3 years ahead.
$input_date = $input_date + 3000;

Let's say I would want to give a date 4 years and 4 months 10 days
$future_date1 _datum = mktime(0, 0, 0, date("m")-2, date("d"),   date("Y")+3);
$future_date2 = mktime(0, 0, 0,     date("m"), date("d"),   date("Y")+3);

A: You can use strtotime('+ 3 years') or DateInterval for an object oriented approach.

A: DateTime() offers multiple ways to do this. It's the way PHP recommends doing date math.
You can use DateTime::modify():
$date = new DateTime($input_date);
$date->modify('+3 months');
echo $date->format('Y-m-d');

// one-liner
echo (new DateTime($input_date))->modify('+3 months')->format('Y-m-d');

or with DateInterval()
$date = new DateTime($input_date);
$date->add(new DateInterval('P3M'));
echo $date->format('Y-m-d');

// one-liner
echo (new DateTime($input_date))->add(new DateInterval('P3M'))->format('Y-m-d');

A: Use the strtotime function:
$input_date = '2010-03-28';
$future_date = strtotime("+3 years", strtotime($input_date);

http://www.php.net/manual/en/function.strtotime.php
Returns a timestamp, if you want to return YYYY-mm-dd: $future_date = date("Y-m-d", $future_date);


text:
Q: Como ocultar a scrollbar ao tirar o mouse e torna-la visível ao colocar o mouse? Bem galera, eu fiz uma side-nav com alguns conteúdos e gostaria de deixar uma barra de rolagem visível quando o mouse estiver em cima, porém, também gostaria de oculta-la quando o mouse estiver fora dessa side-nav.

A: Crie um arquivo css com uma classe com o nome da sua side-nav, ou caso seja uma classe, este código já está correto.
.side-nav{
    overflow-y: hidden;
}

.side-nav:hover{
    overflow-y: auto;
}


text:
Q: Example for $\mathbb{N} ^ \mathbb{N}$ linear order I'm not really sure if something like $ \{1,2,3,...\} < \{2,2,3,...\} < \{3,2,3,...\}$ works.
I don't ask about solution with transitive, antisymmetric and total proof, just for working example. Greetings!
EDIT:
Originally the topic was about total order but I had wanted to consider linear order. Sorry for that!

A: Lexicographic order is a total order on $\mathbb{N}^{\mathbb{N}}$.  That is,
$$
(a_1,a_2,a_3,\ldots)<(b_1,b_2,b_3,\ldots)
$$
if and only if $a_j<b_j$ and $a_i=b_i$ for $i<j$ (which is vacuously true if $j=1$).

A: Try lexicographic order. (This will be like alphabetical order, but the alphabet is $\mathbb{N}$ and every word is infinitely long.)


text:
Q: Z-parameters measurement in active circuits What difficulty faced in measuring Z parameters in active circuits, how is it taken care of?,what is limitation at high frequency?
I heard that we use inductor instead of open ckt and capacitor instead of short ckt, but how it works?

A: Some transistors like to oscillate, given some values of inductance and capacitance, without the use of dampening resistors.
Thus S-params were developed, so the transistors get measured in nominally controlled impedance systems, where the L and C gets hidden inside damped Resistive terminations.


text:
Q: Computing values based on multiple fields using Angular JS I'm currently attempting to compute the value of multiple fields using Angular JS (keep in mind, never used Angular before, and thought it would be good for this problem I'm attempting to solve).
So, I have a page with multiple products. Each product has an associated ID, price, upc, etc. The idea is, you select a quantity and the total will be calculated for you as you go. Hence, I thought using the Angular data-binding technique would work well for this.
Here's what I have thus far...
HTML
<!doctype html>

  <meta charset="UTF-8">
  <title>Multiple products – Total calculation</title>

      Total:
      <input type="text" id="txtTotalFx" ng-value="total()" />

            Item: 51001

 Size: 60 caps

 UPC: 759160-51001-9

 Price: $12.00 ea.

          <input id="product_51001" type="hidden" name="product[]" value="51001/" />
          <input id="product_51001" type="hidden" name="product[]" value="759160-51001-9/" />
          <input id="product_51001" type="hidden" name="product[]" value="12.00/" ng-model='price.51001' />
          <input id="product_51001" type="text" onkeydown="return isNumber(event);" name="product[]" value="" ng-model='qty.51001' />
          <input id="product_51001" type="hidden" name="product[]" value="," />

            Item: 51002

 Size: 120 caps

 UPC: 759160-51002-6

 Price: $21.00 ea.

          <input id="product_51002" type="hidden" name="product[]" value="51002/" />
          <input id="product_51002" type="hidden" name="product[]" value="759160-51002-6/" />
          <input id="product_51002" type="hidden" name="product[]" value="21.00/" ng-model='price.51002' />
          <input id="product_51002" type="text" onkeydown="return isNumber(event);" name="product[]" value="" ng-model='qty.51002' />
          <input id="product_51002" type="hidden" name="product[]" value="," />

            Item: 59901

 Size: 60 caps

 UPC: 759160-59901-4

 Price: $12.50 ea.

          <input id="product_59901" type="hidden" name="product[]" value="59901/" />
          <input id="product_59901" type="hidden" name="product[]" value="759160-59901-4/" />
          <input id="product_59901" type="hidden" name="product[]" value="More Milk Special Blend Capsules/" />
          <input id="product_59901" type="text" onkeydown="return isNumber(event);" name="product[]" value="" ng-model='qty.59901' />
          <input id="product_59901" type="hidden" name="product[]" value="," />

            Item: 58002

 Size: 2oz.

 UPC: 759160-58002-9

 Price: $10.00 ea.

          <input id="product_58002" type="hidden" name="product[]" value="58002/" />
          <input id="product_58002" type="hidden" name="product[]" value="759160-58002-9/" />
          <input id="product_58002" type="hidden" name="product[]" value="10.00/" ng-model='price.58002' />
          <input id="product_58002" type="text" onkeydown="return isNumber(event);" name="product[]" value="" ng-model='qty.58002' />
          <input id="product_58002" type="hidden" name="product[]" value="," />

JS
function isNumber(b) {
  if (b) {
    var a = (b.which) ? b.which : b.keyCode;
    if ((a < 48 || a > 57) && (a < 96 || a > 105) && (a < 37 || a > 40) && a != 8 && a != 46) {
      return false
    }
  }
  return true
}

(function(angular) {
  'use strict';
  var products = [];

  $(".product").each(function() {
    products.push($(this).data("item-id"));
  });

  var app = angular.module('wholesaleApp', []);

  app.controller('ItemListController', function($scope) {
    $scope.total = function() {
      var total = 0;
      console.log("entered total function...");

      for (var i = 0; i < products.length; i++) {
        var qty = "price." + products[i];
        var price = "qty." + products[i];
        console.log("qty: " + qty + ", price: " + price + "\n");
        total += ($scope.price * $scope.qty) || 0;
        console.log("total: " + total + "\n")
      }
      return total || 0;
    };

  });
})(window.angular);

And, Plunker setup: http://plnkr.co/edit/tBhm37E0gaWjwC5cIzdT?p=preview

A: Your approach is really working against angular.  You'd be much better off defining the items as javascript objects, and using that to build the html, rather than the other way around:
HTML:

        Item: {{item.id}}

 Size: {{item.size}}

 UPC: {{item.upc}}

 Price: {{item.price | currency}} ea.

Quantity:
        <input type="number" ng-model="item.quantity"/>

JS:
$scope.items = [{
  id: 510001,
  size: '60 caps',
  upc: '759160-51001-9',
  price: 12,
  quantity: 0
}, {
  id: 51002,
  size: '120 caps',
  upc: '759160-51002-6 ',
  price: 21,
  quantity: 0
}, {
  id: 59901,
  size: '60 caps',
  upc: '759160-59901-4',
  price: 12.50,
  quantity: 0
}, {
  id: 58002,
  size: '2oz',
  upc: '759160-58002-9 ',
  price: 10,
  quantity: 0
}, ];
$scope.total = function() {
  var total = 0;
  for (var i = 0; i < $scope.items.length; i++) {
    total += $scope.items[i].price * $scope.items[i].quantity;
  };
  return total;
};

http://plnkr.co/edit/8vSlHnvEkIy5b3wvIXRW?p=preview


text:
Q: Return parent::function in a function class Test extends Parent {
   $a = 1;

   public function changeVarA() {
       $a = 2;
       return parent::changeVarA();
   }

}

Can Anyone please explain what does return parent::function(); it do ?
Thank you...! ;D

A: This will call the function changeVarA in the parent class.
When a class extends another class, and both have the same function name, the parent:: call forces the parent version of the function to be called and used. The return part of it will simply return whatever the parent function returns after it completes:
<?php
class A {
    function example() {
    echo "Hello Again!\n";
    }
}

class B extends A {
    function example() {
    echo "Hello World\n";
    parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>

output:
Hello World
Hello Again!

The example is taken from the PHP documentation which you really should take a look at.


text:
Q: C arrays memcmp trouble I need to write a code for my UNI, in which I have to receive 2 arrays of some data (it may be int array or char array or even float array) and compare n characters from pointers in both of the arrays, so far I am stuck with this
*note in other words - I need to write my own memcmp :
int byte_compare(const void *b1,const void *b2,size_t len)
{
    char *q1 = (char *)p1;
    char *q2 = (char *)p2;
    int i;

    for (i=0; i<=len*sizeof(*q1) ;i++)
    {
      if(*q1++ != *q2++)
           return 1;
    }
    return 0;
}

int main()
{
          char str1[] = "abcheya";
          char str2[] = "gtyheyb";

          printf((byte_compare(str1[3],str2[3],3))?"not equal\n":"equal\n");
          /*the output is equal*/

          int arr1[]={1,2,3,4};
          int arr2[]={1,2,7,59};

          printf((byte_compare(arr1[0],arr2[0],3))?"not equal\n":"equal\n");
          /*the output is also equal although it is not supposed to be*/

          return 0;
}

when I compare strings it works just fine, but when I try to compare int or float it wont work properly, please help me.

A: You should calculate the comparing byte length while passing the len parameter. So, you can use templates for this.
template<typename T>
int byte_compare(const T *b1, const T *b2, size_t len)
{
    return memcmp(b1, b2, len * sizeof(T));
}

Edit note : The question is edited and the answer has no more meaning. And it uses C++, not applicable for C lessons. I'm remaining the answer for whose have no restriction to use C++.

A: Edit: to write own memcmp function
int byte_compare(const void *b1,const void *b2,size_t len)
{
    if (len != 0) {
        register const unsigned char *p1 = b1, *p2 = b2;

        do {
            if (*p1++ != *p2++)
                return (*--p1 - *--p2);
        } while (--len != 0);
    }
    return (0);
}

A: You need to pass the size of the objects, not their length:
int byte_compare(const void *b1, const void *b2, size_t size)
{
   return memcmp(b1, b2, size);
}

A: Your instructor probably does not want you to use a library call. So write a byte by byte comparison (aka memcmp).
Get a copy of K&R C (or another book on C), and you will find examples of how to process char(acter) values in a loop.
int byte_compare(const void *b1,const void *b2,size_t len)
{
    if( !b1 || !b2 ) return 0; //0 represents false
    char* p1=(char*)b1; char* p2=(char*)p2;
    for( ; len --> 0; ) {
        if( *p1++ != *p2++ ) return 0;
    }
    return 1;
}


text:
Q: how install maven on eclipse i want to install maven plug in on eclipse. but when add the maven site in install software section, and beginning to download and install it, an error occurred about dependency. how can fix it?
i want a complete installation guide...

A: first which dependencies are missing?
A good maven plugin for eclipse is the eclipse maven sonatype, m2eclipse.

A:
Install Maven Plugin for Eclipse
Installing a Maven Plugin for Eclipse can be a bit tricky if you want to get the whole spectrum of features. By default you would go to "Eclipse -> Help -> Software Updates -> Find and Install", then "Search for new features to install", then click on "New Remote Site", and enter the Maven Projects name (e.g. Maven2Plugin) and its home URL there "http://m2eclipse.codehaus.org/".
Once you install it at first everything would seem quite right. However, if you try "Import" a Maven Project, you will not see such an option in under the "General" menu, since it would be missing.
The reason for that is that "http://m2eclipse.codehaus.org/" brings in an old version of the plugin. (At the moment of writing) It brings in "Maven 2 Plugin 0.0.9″, whereas what you need is 0.0.12.
Hence you read the "Maven Integration for Eclipse" installation guide and point your "New Remote Site" to "http://m2eclipse.codehaus.org/update/" instead of "http://m2eclipse.codehaus.org/". The one thing to be cautious about is an "update" link will try to also bring "subclipse" and "mylin" projects, hence you will need to "uncheck" them if you do not want to bring them:

⸺ from https://blog.dotkam.com/2008/02/24/install-maven-plugin-for-eclipse/

A:
Steps to install maven plugin into eclipse:
In eclipse :

*

*go to Help->install new software.

*Copy this link http://download.eclipse.org/technology/m2e/releases on "Work With" edit box.

*Select enter and maven link will appear on Name section.

*Select that link and  follow the steps to instal it on eclipse.
You can find more information regarding different maven builds for eclipse here:
  http://eclipse.org/m2e/download/

A: STEPS TO INSTALL MAVEN (in Eclipse):
Maven Eclipse plugin installation step by step:
  1.  Open Eclipse IDE

*Click Help -> Install New Software...

*Click Add button at top right corner

*At pop up: fill up Name as "M2Eclipse" and Location as "http://download.eclipse.org/technology/m2e/releases"
Now click OK After that installation would be started.
Another way to install Maven plug-in for Eclipse:
  1.    Open Eclipse

  2.    Go to Help -> Eclipse Marketplace

  3.    Search by Maven

  4.    Click "Install" button at "Maven Integration for Eclipse" section

  5.    Follow the instruction step by step

After successful installation do the followings in Eclipse:
1.  Go to Window --> Preferences
2.  Observe, Maven is enlisted at left panel

A: Do these steps:

*

*In Eclipse, go to "Help->Install New Software".

*Press "Add" in the upper right button in the opened window.

*Set the name textbox to be "Maven2Eclipse".

*Set the value textbox to be http://download.eclipse.org/technology/m2e/releases
In case the link is not valid, get one from http://www.eclipse.org/m2e/download/

*Press Ok, select the Maven project, and install it.


text:
Q: cannot display image using printf I have the following snippet for calling post author, time and categories
<?php
    printf( __( '%s by %s in %s', 'xxxx' ),
        get_the_time( 'M j' ),
        et_get_the_author_posts_link(),
        get_the_category_list( ', ' )
    );

?>
I would like to replace the "by" (before author) and "in" (befor categories) with an image
I have tried this:
'%s  %s  %s', 'xxxx'

and this:
$img = '';
printf( __( '%s %s %s in %s', 'xxxx' ),
    get_the_time( 'M j' )
    $img,
    et_get_the_author_posts_link(),
    get_the_category_list( ', ' )
);

This one prints out the alt of the image before the author but not the image.
Any help on this would be really appreciated. Thanks

A: printf fills in the arguments in the order you specify them. If you want the  to show up inside the  then you'll have to list the image first in the arguments:
printf('format string here', $img, get_the_time('M j'), etc...
                             ^^^^^^^^^^^^^^^^^^^^^^^^^--- swap these two

e.g.
printf('%s %s %s', $arg1, $arg2, $arg3);
        ^------------^
            ^---------------^
               ^-------------------^

If you mess around with the argument order, e.g. $arg3, $arg2, $arg1, then they'll be printed in that order...


text:
Q: Jest error when setting or assigning 'window.location' I upgraded the Jest library to v25 and all unit tests that were checking location change are failing.
I checked a couple of issues opened on the Jest repository, but I didn't actually understand how can this be fixed.
The code that calls location.assign breaks with the following error:
Error: Not implemented: navigation (except hash changes)

      69 |     // window.location.href = url;
    > 70 |     window.location.assign(url);

I suppose that the Jest jsdom window object shouldn't be treated any more like a real browser window with regards to changing the location.
How can I fix this?

My findings:

*

*Navigation in the tests doesn't work. All these methods that work in the browser are not implemented in the JSDom window:

*

*window.location.href = "https://myapp.com"

*window.location.assign("https://myapp.com")

*window.location.replace("https://myapp.com")

*Object.defineProperty(window.location, "href", { writable: true, value: currentUrl }); window.location has been set as Unforgeable
To fix failing tests I used:

*

*window.history.pushState({}, "title", "/testJest");

*delete window.location; window.location = { assign: jest.fn() };
it("should navigate to the new URL", () => { const myUrl = "http://some.url"; expect(window.location.assign).toHaveBeenCalledWith(myUrl); });

A: To keep it short, "global" is "window" in Jest.
Use:
global.location.assign(url);

I believe that you can find the rest of the answer in How can I mock the JavaScript window object using Jest?.
Also, there is an interesting conversation around this on this issue:
I found window is global in Jest from Stack Overflow, but not mentioned in documentation #3692

A: Just add the following code in your test file.
  Object.defineProperty(window, 'location', {
    writable: true,
    value: { assign: jest.fn() }
  });

A: Following worked for me:
    window.history.replaceState({}, "", decodeURIComponent(url));

happy coding :)


text:
Q: Stop the thread after a particular time I want to stop my thread after particular time. Here with i added my sample code. Any one of the thread takes more than 6 seconds means i want to stop the particular thread. Rest of the thread should not be affected. Do i need to use the Timer or some better way can we achieve? Suppose if i used Timer means do i need to create new timer for each thread and do i need to cancel the timer suppose if the job finished before 6secs?
    class MyRunnableThread implements Runnable{

    public static int myCount = 0;
    private String fname = null;
    public MyRunnableThread(String fname){
         this.fname = fname;
    }
    public void run() {

            try{
                //read the content based on text and peforms the operation
                //File.read(this.fname)
                System.out.println("Run method stuff"+ this.fname);
            } catch (Exception iex) {
                System.out.println("Exception in thread: "+iex.getMessage());
            }
    }

}

public class RunMyThread {

    public static void main(String a[]){
        System.out.println("Starting Main Thread...");

        String[] fname = {"file1.txt","file2.txt","file3.txt","file4.txt","file5.txt"};
         for(int i=0;i<5;i++){
            try{
                MyRunnableThread mrt = new MyRunnableThread(fname[i]);
                Thread t = new Thread(mrt);
                System.out.println("Main Thread start "+i);
                t.start();

                //stop the thread support run method takes more than 6seconds
                System.out.println("Main Thread end "+ i );
            } catch (Exception iex){
                System.out.println("Exception in main thread: "+iex.getMessage());
            }
        }
        System.out.println("End of Main Thread...");
    }
}

A: User a Timer and a flag to tell the thread to stop:
public class MyRunnableThread implements Runnable {

    boolean run = true;

    String fname;

    public MyRunnableThread(String fname) {
        this.fname = fname;
    }

    public void setRun(boolean toSet) {
        run = false;
    }

    public void run() {
        while (run) {
            doStuff();
        }
    }

    private void doStuff() {
//       File.read(fname);
    }
}

How to use it:
import java.util.Timer;
import java.util.TimerTask;

public class Tester {

    public static void main(String args[]) {

        String[] fname = { "file1.txt", "file2.txt", "file3.txt", "file4.txt", "file5.txt" };
        for (int i = 0; i < 5; i++) {
            try {

                MyRunnableThread mrt = new MyRunnableThread(fname[i]);
                Thread t = new Thread(mrt);
                t.start();

                final Timer timer = new Timer();
                timer.scheduleAtFixedRate(new TimerTask() {
                    int i = 6; // Time in seconds

                    public void run() {
                        System.out.println(i--);
                        if (i < 0) {
                            timer.cancel();
                            mrt.setRun(false);
                        }
                    }
                }, 0, 1000);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Change i to whatever time in seconds you want

A: One thought would be you have an ArrayList containing all your threads.
Then you make each thread have an extra field (Timestamp started)
Then you have a timer looping through the Arraylist and stopping the threads where started > 6 seconds ago

A: Well.. there're a lot of ways to do it, I'll explain you one of those.
You can create a custom class that extends Thread and then implement the method run() and CancelCurrentThread(), your run will start the Thread and CancelCurrentThread() will stop it ignoring the exceptions.
Then your code should look like :
mCustomThread thread = new mCustomThread(parametres_if_you_need);
thread.start(); //Start the Thread
thread.join(6000);  //Adding 6 seconds
//You can detect if the 6 seconds have passed or not for example using a timer, then if it joins on this if condition you can call
thread.CancelCurrentThread();


text:
Q: Why hasn't the string been replaced when it is from string resource file in Kotlin? When I use Code A, I get the original string ,why?
Code B can replace string both ${myObject.status} and ${myObject.name}, the result is OK.
Image

Code A
<string name="DetailsOfWiFiDef">The WiFi status is ${myObject.status},
        the name of WiFi is ${myObject.name}\n\n
</string>

val myObject=getIt()
val s=mContext.getString(R.string.DetailsOfWiFiDef)
val sb = StringBuilder()
sb.append(s)  //The string keep original

Code B
val myObject=getIt()
val k="The WiFi status is ${myObject.status},the name of WiFi is ${myObject.name} \n"
val sb = StringBuilder()
sb.append(k)  //It has been replaced

A: Kotlin compiler converts string literals into StringBuilder chain at compile time:
// code in Kotlin
val k = "The WiFi status is ${myObject.status},the name of WiFi is ${myObject.name} \n"

// is converted into equivalent of code in Java
String k = new StringBuilder("The WiFi status is ").append(myObject.getStatus()).append(",the name of WiFi is ").append(myObject.getName()).append(" \n");

If you load through resources there's no conversion, it's used as is. However you can use formattable string resource:
<string name="DetailsOfWiFiDef">The WiFi status is %1$s,
        the name of WiFi is %2$s\n\n
</string>

Then inject arguments when reading string (Android Studio even corrects You if you proide too many arguments or wrong type in real time):
val s=mContext.getString(R.string.DetailsOfWiFiDef, myObject.status, myObject.name)


text:
Q: If I purchased Minecraft for PS3, can I play on PC? I have purchased Minecraft for PS3, however for various reasons I am dissatisfied with the PS3 experience and I would like to continue playing on PC.
Does the PS3 purchase/license allow me full access to the PC version and/or any other versions of Minecraft?

A: No.
Purchasing the PS3 copy gives you the right to use the PS3 version. It does not give you any right to the PC version, nor will it allow your PS3 account to use the PC version.
If you want to play on PC, you'll need to buy the PC version separately.


text:
Q: How do I resume log shipping? I was log shipping. I disabled the jobs, and restored the database on the secondary machine and used them for a bit. Now I want to undo this. I don't care about history or syncing, I simply want to turn log shipping back on and carry on my merry way.
I enabled the jobs, but 'running' them (right click > start job at step, if that's how you run them) just pops up and says success but nothing happens.
I am unsure of how I can start the log shipping going again. I tried deleting the databases from the secondary machine but that didn't help either.
Any ideas? Surely it's a simple thing?
Edit: Still at a loss. Says the job was successful but nothing happens, no database is created. It was working fine before I took the databases out of recovery on the secondary machine.

A: You need to take another full backup from the production database and restore it to the log shipping server in NORECOVERY mode.  Then the log shipping should be able to restart.  You may need to remove the log shipping and put it back by going through the wizard depending on how you set it up.


text:
Q: beforesubmit doesn't appear to be executing at all I trying to get the beforesubmit option to work so I can validate the form before it is submitted.  I must be missing something.  This runs fine but it totally ignores the function.
 $(document).ready(function() {
            var options = {
                    beforesubmit: function() {
                            var subjectTxtVal = $('input[name=subjectTxt]').fieldValue();
                            var messageTxtVal = $('input[name=messageTxt]').fieldValue();

                            if (!subjectTxtVal[0] || !messageTxtVal[0]) {
                                alert('Please enter a value for subject and message');
                                return false;
                            }
                    },
                    target:  '#results',
                    success: showResponse
            };
            $('#results').dialog({autoOpen: false, modal: true, buttons: {
                            Ok: function() {
                                    $( this ).dialog( "close" );
                            }
                    }});
            $('#resemail').submit(function() {
                    $(this).ajaxSubmit(options);
                    $('#results').dialog('open');
                    return false;
            });

    });

Based on my testing with firebug I don't see where it is ever actually calling the function.  I have looked at the docs and the examples but it is somewhat confusing.  Any ideas?
Thanks.

A: Why not just validate it yourself before submit instead of relying on the plugin ?
$(document).ready(function() {
            var options = {
                    target:  '#results',
                    success: showResponse
            };
            $('#results').dialog({autoOpen: false, modal: true, buttons: {
                            Ok: function() {
                                    $( this ).dialog( "close" );
                            }
                    }});
            $('#resemail').submit(function() {
                    if( validate_fields() )
                    {
                        $(this).ajaxSubmit( options );
                    }
                    else
                       return false;
            });

});

function validate_fields()
{
  var subjectTxtVal = $('input[name=subjectTxt]').fieldValue();
  var messageTxtVal = $('input[name=messageTxt]').fieldValue();

  if (!subjectTxtVal[0] || !messageTxtVal[0]) {
      alert('Please enter a value for subject and message');
      return false;
   }
   return true;
}


text:
Q: Unspecified error when calling Word CentimetersToPoints via OLE The following code fails with an OLE 800040005 "unspecified" error on the CentimetersToPoint call when executed in Delphi (XE), the similar VBS or VBA version passes
var w : OleVariant;

w := CreateOleObject('Word.Application');
w.Visible := true;
Writeln(w.CentimetersToPoints(2.0));

FWIW the type library gives
/ [id(0x00000173), helpcontext(0x09700173)]
// single CentimetersToPoints([in] single Centimeters);

By default, Delphi only passes the floating values as Double, so I tried calling IDispatch.Invoke directly and passing the argument as VT_R4, but without better results.
edit: VB version that works (save to .vbs)
set w = CreateObject("Word.Application")
w.Visible = true
msgbox w.CentimetersToPoints(2.0)

Any other suggestions of what could be going wrong?

A: I initially suspected that the issue is that the function expects Single and Delphi converts your float to something else. When I tracked it down in the debugger I find that the variant being passed to Invoke is has VType of varCurrency and a currency value of 2. Quite how that happens I'm not sure!
As I discovered, answering this question, it's surprisingly tricky to get a single precision float into a variant. I initially suspected that you can use the solution I presented there to solve your problem.
function VarFromSingle(const Value: Single): Variant;
begin
  VarClear(Result);
  TVarData(Result).VSingle := Value;
  TVarData(Result).VType := varSingle;
end;

....

w := CreateOleObject('Word.Application');
w.Visible := true;
Writeln(w.CentimetersToPoints(VarFromSingle(2.0)));

But this fails also, in the same way, for reasons I don't yet understand.
Like you, I tried calling the function using IDispatch.Invoke. This is what I came up with:
program SO16279098;

{$APPTYPE CONSOLE}

uses
  SysUtils, Variants, Windows, ComObj, ActiveX;

function VarFromSingle(const Value: Single): Variant;
begin
  VarClear(Result);
  TVarData(Result).VSingle := Value;
  TVarData(Result).VType := varSingle;
end;

var
  WordApp: Variant;
  param: Variant;
  retval: HRESULT;
  disp: IDispatch;
  Params: TDispParams;
  result: Variant;

begin
  try
    CoInitialize(nil);
    WordApp := CreateOleObject('Word.Application');
    disp := IDispatch(WordApp);

    param := VarFromSingle(2.0);
    Params := Default(TDispParams);
    Params.cArgs := 1;
    Params.rgvarg := @param;
    retval := disp.Invoke(
      371,//CentimetersToPoints
      GUID_NULL,
      LOCALE_USER_DEFAULT,
      DISPATCH_METHOD,
      Params,
      @Result,
      nil,
      nil
    );
    // retval = E_FAIL

    Params := Default(TDispParams);
    retval := disp.Invoke(
      404,//ProductCode
      GUID_NULL,
      LOCALE_USER_DEFAULT,
      DISPATCH_METHOD,
      Params,
      @Result,
      nil,
      nil
    );
    // retval = S_OK
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

I cannot call CentimetersToPoints this way, but can call the ProductCode function.
To add to your collection of success/failure indicators, when I call CentimetersToPoints function using PowerShell I have success. When I call using Python's win32com.client, I get E_FAIL.
There is clearly some special magic ingredient that we are missing. It seems that all the MS tools know about this magic.
I conclude that it is not possible to call CentimetersToPoints using variant dispatch as implemented in Delphi. It does not know about the magic, whatever that magic is.
It is clearly possible to call Invoke on the IDispatch and succeed. We can tell that because other environments manage to do so. So, what I do not know yet is what the missing magic is.
If you could use early bound COM, then you could sidestep this issue:
Writeln((IDispatch(w) as WordApplication).CentimetersToPoints(2.0));

OK, with the help of Hans Passant, I have some Delphi code that manages to call this function:
program SO16279098;

{$APPTYPE CONSOLE}

uses
  SysUtils, Variants, Windows, ComObj, ActiveX;

function VarFromSingle(const Value: Single): Variant;
begin
  VarClear(Result);
  TVarData(Result).VSingle := Value;
  TVarData(Result).VType := varSingle;
end;

var
  WordApp: Variant;
  param: Variant;
  retval: HRESULT;
  disp: IDispatch;
  Params: TDispParams;
  result: Variant;

begin
  try
    CoInitialize(nil);
    WordApp := CreateOleObject('Word.Application');
    disp := IDispatch(WordApp);

    param := VarFromSingle(2.0);
    Params := Default(TDispParams);
    Params.cArgs := 1;
    Params.rgvarg := @param;
    retval := disp.Invoke(
      371,//CentimetersToPoints
      GUID_NULL,
      LOCALE_USER_DEFAULT,
      DISPATCH_METHOD or DISPATCH_PROPERTYGET,
      Params,
      @Result,
      nil,
      nil
    );
    Writeln(Result);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

For reasons unknown, you need to include DISPATCH_PROPERTYGET as well as DISPATCH_METHOD.
The question that I asked probably makes this question a duplicate. So, I'm voting to close.


text:
Q: Update-Package : Package 'WebActivator' is not found Error preventing me from updating nuget packages
I have not updated for a while but this has me really stuck
This was installed as part of breeze.
The reference is intact
Not sure what i can do from here.
Any help appreciated before I take on a low level hunt for the cause.

A: As in docs:
PM> Install-Package WebActivatorEx

A package that allows other packages to execute some startup code in web apps. This package should be used over the older WebActivator, which was not strong named.


text:
Q: iOS5 app is not listed in Notification Center My app uses Local Notifications to communicate with the user.  The legacy code for iOS4 is working well, but in iOS5, notifications are not shown.   After reading on the web, I added the following in the didFinishLaunchingWithOptions: method
[[UIApplication sharedApplication]registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |
                                                                      UIRemoteNotificationTypeAlert |
                                                                      UIRemoteNotificationTypeSound];

I still do not see the app in the Notification Center.  Is anything more required to make the app being listed in the Notification Center?
Sam.

A: You also need to have a provisioning profile for your app that allows for push notifications. If something goes wrong when registering for push notifications, your app delegate will get notified via application:didFailToRegisterForRemoteNotificationsWithError:. The error object will contain relevant information. Use it to verify that nothing goes wrong.


text:
Q: Extract data between two characters in multiple text file and rename them I need some assistance to create my first VBA code.
I have thousands of text file in a folder that contain some data between the character "\" which needs to be extracted into excel.
Sample text file will look like
Values are 1.000000 1.000000 9 0 3 1 1 0 \021-03930\ \021-03930\ \C21XBH113-MD
\C21XBH113-MD2\ \A21XBS\ \A21XBS135\ \A21XBS136\ \W21XBS112\ \R21XBS112\ "Value" "Data"
"Included" 1 1 0 0
I need to export all information between "\" from multiple txt file to first column of excel (one by one).
Also once we have this information in column A, we need to replace them with other information that will be entered in column B.
enter code here
Sub FindAllPoints()

Dim filename As String, nextrow As Long, MyFolder As String
Dim MyFile As String, text As String, textline As String, filedate As String
Dim filenum As Integer
Dim idx%

MyFolder = ThisWorkbook.Path & "\"
MyFile = Dir(MyFolder & "*.txt")
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "ListofPoints"

  Range("A1").Value = "ListofOLDPoints"
  Range("B1").Value = "ListofNEWPoints"

nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1

Do While MyFile <> ""

    Open (MyFolder & MyFile) For Input As #1

    Do Until EOF(1)
        Line Input #1, textline

        idx = InStr(textline, "\")
        If idx > 0 Then
            ActiveSheet.Cells(nextrow, "A").Value = Mid(textline, idx)
            nextrow = nextrow + 1
        End If

    Loop

    Close #1

    MyFile = Dir()

Loop
End Sub

My code might be wrong, please help me built a code that can do my task.
Thank you in advance.

A: For example:
Sub GetData()
'Note: this code requires a reference to the Word object model.
'See under the VBE's Tools|References.
Application.ScreenUpdating = False
Dim strFolder As String, strFile As String
Dim WkSht As Worksheet, r As Long
strFolder = GetFolder: If strFolder = "" Then Exit Sub
Dim wdApp As New Word.Application, wdDoc As Word.Document
wdApp.Visible = False: r = 0
Set WkSht = Sheets.Add(After:=Sheets(Sheets.Count))
With WkSht
  .Name = "ListofPoints"
  .Range("A1").Value = "ListofOLDPoints"
  .Range("B1").Value = "ListofNEWPoints"
End With
strFile = Dir(strFolder & "\*.txt", vbNormal)
While strFile <> ""
  r = r + 1
  Set wdDoc = .Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False)
  With wdDoc
    With .Paragraphs.First.Range
      If InStr(.Text, "\") > 0 Then WkSht.Range("A" & r).Value = Split(.Text, "\")(1)
    End With
    .Close SaveChanges:=False
  End With
  strFile = Dir()
Wend
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing
Application.ScreenUpdating = True
End Sub

Function GetFolder() As String
    Dim oFolder As Object
    GetFolder = ""
    Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
    If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
    Set oFolder = Nothing
End Function

That said, it's not clear whether you have multiple such strings each each file. If so, you might replace:
Dim WkSht As Worksheet, r As Long

with:
Dim WkSht As Worksheet, r As Long, c as Long

and replace:
      If InStr(.Text, "\") > 0 Then WkSht.Range("A" & r).Value = Split(.Text, "\")(1)

with:
      For c = 1 To UBound(Split(.Text, "\")) - 1
        WkSht.Cells(r, c).Value = Split(.Text, "\")(c)
      Next


text:
Q: Append Files in Input Type File with Multiple Before Uploading I have a form on my laravel website with a section that allows users to upload multiple image files (with a preview of the selected images). If a user only chooses multiple images once, everything works, and the selected images get uploaded. However, if a user selects multiple images on two separate occasions before submitting the form, only the last bunch of selected images will be uploaded.
For example; a user selects 4 images, then they fill out some other fields on the form, and then they decide to add 3 more images on top of the 4 images they previously selected before submitting the form. The image preview box will contain all 7 images they have selected, but once they submit the form, only the last 3 images they selected will be uploaded.
HTML Multiple File Input:
<input id="gphotos" type="file" name="gphotos[]" multiple>

JavaScript:
function gphoto(input, ImagePreview) {
    if (input.files) {
        var fileAmount = input.files.length;

        for (i = 0; i < fileAmount; i++) {
            var reader = new FileReader();

            reader.onload = function(e) {
                $('.preview').css('margin-top', '4px');
                $($.parseHTML('')).attr('src', e.target.result).appendTo(ImagePreview);
            }

            reader.readAsDataURL(input.files[i]);
        }
    }
};

$('#gphotos').change(function() {
    gphoto(this, 'div.preview');
});

Controller:
if (request('gphotos')) {
        $imageArray['gphotos'] = array();

        foreach (request()->gphotos as $gphoto) {
            $gphotoPath = $gphoto->store('gphotos', 'public');

            $imageArray['gphotos'][] =  $gphotoPath;
        }

        $imageArray['gphotos'] = json_encode($imageArray['gphotos']);
    }

I would like users to be able to select multiple images on multiple separate occasions before submitting the form, and all their images being uploaded. I have tried searching all over the internet, but no one has a simple solution to this seemingly simple problem. I would greatly appreciate it if someone could help me solve this issue.

A: Instead of letting the form handle it's own submission, create your own. Listen for the submit event on the form and whenever you submit, cancel the default behavior and send your data with AJAX. In this case the jQuery ajax function. Send it to a PHP file which handles your incoming request.
You can store files, like images, in a FormData object. It's a container to set key / value pairs to send with an HTTP request. So create one.
In your change event listener you'll want to add each selected image to this FormData container so that the images will be stored there. This way you can select new images every time and add them to the container. And when you submit you only submit that container with the images in them.
Then when images are uploaded successfully loop through the container and delete each key in it so the user can restart the whole process.
<form id="gphotos-form" enctype="multipart/form-data">
  <input id="gphotos" type="file" name="gphotos[]" multiple>

  <button type="submit">Submit</button>
</form>

// Container for the images.
const selectedImages = new FormData();

function gphoto(input, imagePreview) {
  for (const file of input.files) {
    const image = new Image();
    image.classList.add('gphoto');
    image.src = URL.createObjectURL(file);
    image.onload = event => {
      $(imagePreview).append(image);
      URL.revokeObjectURL(event.target.src);
    };

    // Image is added here.
    selectedImages.append('gphotos', file);

  }
}

$('#gphotos').on('change', function() {
  gphoto(this, 'div.preview');
});

$('#gphotos-form').on('submit', function(event) {

  // Get the data from the form, but remove the gphotos[] one,
  // because we want to use our own collection of images.
  const formData = new FormData(event.target);
  formData.delete('gphotos[]');
  for (const file of selectedImages.values()) {
    formData.append('gphotos', file);
  }

  // Send container to your server.
  // Change the url: value to your PHP script.
  $.ajax({
    url: 'http://example.com/script.php',
    data: formData,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data){
      console.log(data);

      // Delete all the images from the container.
      for (let key of selectedImages.keys()) {
        selectedImages.delete(key)
      });

      // Clear the preview.
      $('div.preview').html('');

    }
  });

  event.preventDefault();

});

A: You could add a new <input type="file"> whenever you finished uploading the previous files and hide the previous input. This way you keep adding a new input every time you want to add more files and prevent the previous input from being overwritten.
And it doesn't require you to use AJAX.
<form id="gphotos-form" enctype="multipart/form-data">

    <input class="gphotos" type="file" name="gphotos[]" multiple>

  <button type="submit">Submit</button>
</form>

.ghpotos[hidden] {
  display: none;
}

let $uploads = $('.gphotos-upload');
let $preview = $('div.preview');

$('#gphotos-form').on('change', function(event) {

  let $currentInput = $(event.target);
  let $newInput = $('<input class="gphotos" type="file" name="gphotos[]" multiple>');

  for (const file of event.target.files) {
    const image = new Image();
    image.classList.add('gphoto');
    image.src = URL.createObjectURL(file);
    image.onload = event => {
      $preview.append(image);
      URL.revokeObjectURL(event.target.src);
    };
  }

  // Disabled and hide current input.
  $currentInput.attr('hidden', '');

  // Add new input to do another upload.
  $uploads.append($newInput);

});

A: HTML Multiple File Input:
<input id="gphotos" type="file" name="gphotos[]" multiple>

JavaScript:
function gphoto(input, ImagePreview) {
        var files = input.files;
        var filesArr = Array.prototype.slice.call(files);

        filesArr.forEach(function(f) {
            if (!f.type.match("image.*")) {
                return;
            }
            var reader = new FileReader();
            reader.onload = function(e) {
                $('.preview').css('margin-top', '4px');
                $($.parseHTML('')).attr('src', e.target.result).appendTo(ImagePreview);
                $($.parseHTML('<input type="hidden" name="photos[]">')).attr('value', e.target.result).appendTo($('.store'));
            };
            reader.readAsDataURL(f);
        });
    }

    $('#gphotos').change(function() {
        gphoto(this, 'div.preview');
    });

Controller:
if (request('photos')) {
            $imageArray['gphotos'] = array();

            foreach (request()->photos as $gphoto) {
                $base64_str = substr($gphoto, strpos($gphoto, ",")+1);
                $gphotoPath = 'gphotos/'.\Str::random(11) . '.jpg';
                $gphoto = base64_decode($base64_str);
                \Storage::disk('public')->put($gphotoPath, $gphoto);

               $imageArray['gphotos'][] =  $gphotoPath;
            }

            $imageArray['gphotos'] = json_encode($imageArray['gphotos']);
        }


text:
Q: R gplots heatmap.2 - key is unstable using breaks parameter (warning: unsorted 'breaks' will be sorted before use) I'm visualizing a data set with the heatmap.2 function from the gplots package in R.  Basically I'm performing a hierarchical clustering analysis on the original data, while forcing the heatmap to display a limited version of the data (between -3 and +3) to limit the effect of outliers on the appearance of the heatmap, while still retaining the original clustering.  When I use the full data set (fullmousedatamat), it works just fine.  However, when I use a partial data set (partialmousedatamat), and want to plot it using the same key as the full data set, a couple colors are dropped out of the key and I can't figure out why.
Here is a gist containing the relevant data sets and analyses:
https://gist.github.com/jeffbruce/7412f567ac57fe1721a3
Notice how the 4th color on either side of the centre white color are dropped out.  This feels like a bug to me maybe.  I get the following warning message which I'm not sure how to interpret:
Warning message:
In image.default(z = matrix(z, ncol = 1), col = col, breaks = tmpbreaks,  :
  unsorted 'breaks' will be sorted before use

Thanks for your help!

A: I came across the same issue and I had to go through the code for heatmap.2 to figure it out.
It turns out that symkey=T, which is the default, adds the extreme values of the data at both ends of breaks, rendering it un-sorted:
tmpbreaks <- breaks
  if (symkey) {
    max.raw <- max(abs(c(x, breaks)), na.rm = TRUE)
    min.raw <- -max.raw
    tmpbreaks[1] <- -max(abs(x), na.rm = TRUE)
    tmpbreaks[length(tmpbreaks)] <- max(abs(x), na.rm = TRUE)
  }

Therefore, the simple way to solve this is adding symkey=F if you are providing your own breaks.


text:
Q: Is there a complete Link Invariant for links with N crossing. Are there known examples of pairs $\left(f, N\right)$, where $f$ is a link invariant that is known to be complete when restricted to link diagrams that have at most $N$ crossings?
(Ideally, f should have a publicly available software implementation, but one without is also ok.)


text:
Q: Iterative loop in jade isn't rendering data correctly I've got a table in jade that'll be dynamically generated through express (res.render('index', {classes: results})):
table
  tr
    th Title
    th School
    th Description
- if (classes.length) {
- classes.forEach(function(aClass) {
  tr
    td= aClass.title
    td= aClass.school
    td= aClass.desc
- });}

However, when I render it, the data comes out as one garbled mess.  Looking at the HTML source reveals that the </table> tag is before the content in classes.  How can I solve this?

A: You've almost got it - jade is being finicky here.  When creating an iterative loop, you need to make sure that your JavaScript is indented to the same level as your data:
table
  tr
    th Title
    th School
    th Description
  - if (classes.length) {
  - classes.forEach(function(aClass) {
  tr
    td= aClass.title
    td= aClass.school
    td= aClass.desc
  - });}

If this makes your inner coder cringe at the code style, I'm with you.  However, that's the way it is.  Alternatively, you could use jade's each (documented here)
table
  tr
    th Title
    th School
    th Description
  - if (classes.length) {
  each aClass in classes
    tr
      td= aClass.title
      td= aClass.school
      td= aClass.desc
  - }

Again, this looks a little wonky but is the jade way to iterate.

A: My indentation style is:
table
  tr
    th Title
    th School
    th Description
  if (classes.length)
    each aClass in classes
      tr
        td= aClass.title
        td= aClass.school
        td= aClass.desc


text:
Q: How to permanently set pip index url and host? I installed a new Python3.8 on my Ubuntu besides the original python 3.6 and 2.7 by installing from the python source package.
The Python3.8 is by default installed to /usr/local/bin/ and python3.6 is by default in /usr/bin. So now I can use pip3 and pip3.8 to access both versions. However one new issue arises after this installation. When I want to use pip3.8 install anything, I got this error message:
Could not fetch URL https://pypi.douban.com/simple/six/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.douban.com', port=443): Max retries exceeded with url: /simple/six/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
ERROR: Could not find a version that satisfies the requirement six (from versions: none)

pip3 (for python3.6 by default) isn't having this problem. So now in order to install anything with python3.8, I have to do this:
pip3.8 install xxx  --index-url http://pypi.douban.com/simple/   --trusted-host pypi.douban.com

Is there a way to permanently set up the --index-url and --trusted-host without using it for each installation?


text:
Q: Regular Expression to replace a specific string I have a string of the following format:
tablename.colname > [[2 | prompt and text]] and tabname.colname < [[1000| prompt
 or text]]

I need to replace the text within '[[]]' with the value before the pipe symbol. Right now,
i) i'm splitting the string with the logical operators such as AND and OR (Note: This also splits the 'and' within the square brackets, that i really don't want.)
ii) Then the resultant strings with the mathematical operators.
Can anyone help to find a regular expression to find the texts in between the double square brackets and replace it with the value before pipe symbol...
The value before the pipe can be integer or string.

A: Something like this should work
resultString = Regex.Replace(subjectString, @"(\[\[)(.*?)\|(.*?)(\]\])", "$1$2$4", RegexOptions.Multiline);

Input : [[2 | prompt and text]] and tabname.colname < [[1000| prompt or text]]
Output : [[2 ]] and tabname.colname < [[1000]]

A: Search for
\[\[([a-zA-Z0-9]+) ?\|.*?\]\]

Replace with
[$1]
Check it here
A brief explanation
\[\[                 - The starting [[
([a-zA-Z0-9]+)       - Match any number of letters and digits (made a capturing group)
 ?                   - An optional space
\|                   - Pipe symbol
.*?                  - Match anything without been greedy
\]\]                 - Closing ]]


text:
Q: Adding namespace in JavaScript cause Unexpected token '.' error I follow the instructions in https://stackoverflow.com/a/881556/2704265 to add a namespace, as below:

var theme1 = {
    document.addEventListener('DOMContentLoaded', function() {
    });
};

However, after that, I will get Uncaught SyntaxError: Unexpected token '.' which point to the '.' after 'document', why?

A: Taking a look at the example given in the answer provided you have the following:
var yourNamespace = {

    foo: function() {
    },

    bar: function() {
    }
};

...

yourNamespace.foo();

The code you gave would need to look something more like this:
var themeNamespace = {
   domLoader: function() {
      document.addEventListener('DOMContentLoaded', function() {
    });
   },
}

Then run using themeNamespace.domLoader();


text:
Q: Java Simple Class to Return a Reversed Singly Linked List I am trying to write a simple class that reverse a singly linked list and return a constructed linked list. The code below is working if i make everything public which I dont want to. Anybody interested to address my question? (should I use doubly linked list? or it is possible with single link list?)
What I want is a function reverseList receives a ListNode Object return a ListNode Object (in reverse order).  Like this:
originalNumber=OriginalNumber.reverseList();

//// my code
public class ReverseLinkList {

    public static ListNode originalNumber=new ListNode();
    public static ListNode reversedNumber=new ListNode();

    public static void main(String[] args) {
        //create 1->2->3->null
        originalNumber.add(1);originalNumber.add(2);originalNumber.add(3);
        System.out.print(num1.toString()+"\n");

        //create 3->2->1->null
        reversedNumber=originalNumber.reverseList;

    }

}

class ListNode{
    private class Node{
        Object data;
        Node next;
        Node(int v){
            data=v;
            next=null;
        }
        public Object getData(){
            return data;
        }
        public void setData(int v){
            data=v;
        }
        public Node getNext(){
            return next;
        }
        public void setNext(Node nextValue){
            next=nextValue;
        }
    }

    private Node head;
    public void add(int data){
        if(head==null){
            head=new Node(data);
        }
        Node temp=new Node(data);
        Node current=head;
        if(current !=null){
            while(current.getNext()!=null){
                current=current.getNext();
            }
            current.setNext(temp);
        }
    }
    public String toString(){
        String output="";
        if(head!=null){
            Node current=head.getNext();
            while(current!=null){
                //System.out.println(output);
                output+=current.getData().toString();
                current=current.getNext();
            }
        }
        return output;
    }
    public Node getHead(){
        return head;
    }

    public static Node reverse(Node node) {
        Node prev = null;
        Node current = node;
        Node next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        node = prev;
        return node;
    }

}

The original and working code which I do not want
public class ReversedLinkedList {
    static Node head;
    static class Node {
        int data;
        Node next;
        Node(int d) {
            data = d;
            next = null;
        }
    }
    Node reverse(Node node) {
        Node prev = null;
        Node current = node;
        Node next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        node = prev;
        return node;
    }
    void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + "");
            node = node.next;
        }
    }

    public static void main(String[] args) {
        ReversedLinkedList list = new ReversedLinkedList();
        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);

        list.printList(head);
        head = list.reverse(head);
        System.out.println("");
        list.printList(head);

    }
}

A: You're on the right track. You can make the member variables private & use the appropriate getters & setters:
public ListNode reverseList() {
    Node prev = null;
    Node current = this.getHead();
    Node next = null;
    while (current != null) {
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
    head = prev;
    return this;
}

This allows you print a reversed list:
System.out.println(originalNumber.reverseList());

Note that the originalNumber is itself manipulated. So, subsequent prints (System.out.println(originalNumber);) would still print the reversed list.
If you don't want the original to be modified, then there really isn't any other way apart from collecting all the data & then looping through in the reverse order & adding them into a new list:
public ListNode reverseList() {
    int size = 0;

    // Calculate size
    Node current = this.getHead();
    while (current != null) {
        size++;
        current = current.getNext();
    }
    int[] data = new int[size];

    // Collect all data
    current = this.getHead();
    int index = 0;
    while (current != null) {
        data[index++] = current.getData();
        current = current.getNext();
    }

    // Add to a new list in reverse order
    ListNode reversed = new ListNode();
    for (index = size - 1; index >= 0; index--)
        reversed.add(data[index]);
    return reversed;
}

That first scan to get the size can be skipped if size is tracked while adding elements to the list or by simply switching to an ArrayList instead of an array for data.
Finally there's the elegant recursive approach which also keeps the original ListNode intact:
public ListNode reverseRecursive() {
    return recursive(this.getHead());
}

private ListNode recursive(Node node) {
    if (node == null)
        return new ListNode();
    else {
        ListNode listNode = this.recursive(node.next);
        listNode.add(node.data);
        return listNode;
    }
}

To print:
System.out.println(originalNumber.reverseRecursive());

Here we needn't keep track of size & you make use of the call stack to naturally keep track & pop out the nodes in reverse.