text:
Q: What is my bottleneck when cloning a git repository from a virtual machine with a fast network connection? I have a situation with a relatively large git repository located in a virtual machine on an elderly, slow host on my local network where it takes quite a while to do the initial clone.
ravn@bamboo:~/git$ git clone gitosis@gitbox:git00
Initialized empty Git repository in /home/ravn/git/git00/.git/
remote: Counting objects: 89973, done.
remote: Compressing objects: 100% (26745/26745), done.
remote: Total 89973 (delta 50970), reused 85013 (delta 47798)
Receiving objects: 100% (89973/89973), 349.86 MiB | 2.25 MiB/s, done.
Resolving deltas: 100% (50970/50970), done.
Checking out files: 100% (11722/11722), done.
ravn@bamboo:~/git$

There is no git specific configuration changes in gitosis.
Is there any way of speeding up the receiving bit up to what the network is capable of?

I need the new repositories to be properly connected with the upstream repository.  To my understanding, this requires git to do the cloning, and thus raw bit copying outside of git will not work.

A: The git clone --depth=1 ... suggested in 2014 will become faster in Q2 2019 with Git 2.22.
That is because, during an initial "git clone --depth=..." partial clone, it is
pointless to spend cycles for a large portion of the connectivity
check that enumerates and skips promisor objects (which by definition is all objects fetched from the other side).
This has been optimized out.

clone: do faster object check for partial clones

For partial clones, doing a full connectivity check is wasteful; we skip
promisor objects (which, for a partial clone, is all known objects), and
enumerating them all to exclude them from the connectivity check can
take a significant amount of time on large repos.
At most, we want to make sure that we get the objects referred to by any
wanted refs.
For partial clones, just check that these objects were transferred.
Result:
 Test                          dfa33a2^         dfa33a2
 -------------------------------------------------------------------------
 5600.2: clone without blobs   18.41(22.72+1.09)   6.83(11.65+0.50) -62.9%
 5600.3: checkout of result    1.82(3.24+0.26)     1.84(3.24+0.26) +1.1%

62% faster!

With Git 2.26 (Q1 2020), an unneeded connectivity check is now disabled in a partial clone when fetching into it.
See commit 2df1aa2, commit 5003377 (12 Jan 2020) by Jonathan Tan (jhowtan).
(Merged by Junio C Hamano -- gitster -- in commit 8fb3945, 14 Feb 2020)

connected: verify promisor-ness of partial clone
Signed-off-by: Jonathan Tan
Reviewed-by: Jonathan Nieder

Commit dfa33a298d ("clone: do faster object check for partial clones", 2019-04-21, Git v2.22.0-rc0 -- merge) optimized the connectivity check done when cloning with --filter to check only the existence of objects directly pointed to by refs.
But this is not sufficient: they also need to be promisor objects.
Make this check more robust by instead checking that these objects are promisor objects, that is, they appear in a promisor pack.

And:

fetch: forgo full connectivity check if --filter
Signed-off-by: Jonathan Tan
Reviewed-by: Jonathan Nieder
If a filter is specified, we do not need a full connectivity check on the contents of the packfile we just fetched; we only need to check that the objects referenced are promisor objects.
This significantly speeds up fetches into repositories that have many promisor objects, because during the connectivity check, all promisor objects are enumerated (to mark them UNINTERESTING), and that takes a significant amount of time.

And, still with Git 2.26 (Q1 2020), The object reachability bitmap machinery and the partial cloning machinery were not prepared to work well together, because some object-filtering criteria that partial clones use inherently rely on object traversal, but the bitmap machinery is an optimization to bypass that object traversal.

There however are some cases where they can work together, and they were taught about them.

See commit 20a5fd8 (18 Feb 2020) by Junio C Hamano (gitster).
See commit 3ab3185, commit 84243da, commit 4f3bd56, commit cc4aa28, commit 2aaeb9a, commit 6663ae0, commit 4eb707e, commit ea047a8, commit 608d9c9, commit 55cb10f, commit 792f811, commit d90fe06 (14 Feb 2020), and commit e03f928, commit acac50d, commit 551cf8b (13 Feb 2020) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 0df82d9, 02 Mar 2020)

pack-bitmap: implement BLOB_LIMIT filtering
Signed-off-by: Jeff King

Just as the previous commit implemented BLOB_NONE, we can support BLOB_LIMIT filters by looking at the sizes of any blobs in the result and unsetting their bits as appropriate.
This is slightly more expensive than BLOB_NONE, but still produces a noticeable speedup (these results are on git.git):
Test                                         HEAD~2            HEAD
------------------------------------------------------------------------------------
5310.9:  rev-list count with blob:none       1.80(1.77+0.02)   0.22(0.20+0.02) -87.8%
5310.10: rev-list count with blob:limit=1k   1.99(1.96+0.03)   0.29(0.25+0.03) -85.4%

The implementation is similar to the BLOB_NONE one, with the exception that we have to go object-by-object while walking the blob-type bitmap (since we can't mask out the matches, but must look up the size individually for each blob).
The trick with using ctz64() is taken from show_objects_for_type(), which likewise needs to find individual bits (but wants to quickly skip over big chunks without blobs).

Git 2.27 (Q2 2020) will simplify the commit ancestry connectedness check in a partial clone repository in which "promised" objects are assumed to be obtainable lazily on-demand from promisor remote repositories.
See commit 2b98478 (20 Mar 2020) by Jonathan Tan (jhowtan).
(Merged by Junio C Hamano -- gitster -- in commit 0c60105, 22 Apr 2020)

connected: always use partial clone optimization
Signed-off-by: Jonathan Tan
Reviewed-by: Josh Steadmon

With 50033772d5 ("connected: verify promisor-ness of partial clone", 2020-01-30, Git v2.26.0-rc0 -- merge listed in batch #5), the fast path (checking promisor packs) in check_connected() now passes a subset of the slow path (rev-list) > - if all objects to be checked are found in promisor packs, both the fast path and the slow path will pass;

*

*otherwise, the fast path will definitely not pass.

This means that we can always attempt the fast path whenever we need to do the slow path.
The fast path is currently guarded by a flag; therefore, remove that flag.
Also, make the fast path fallback to the slow path - if the fast path fails, the failing OID and all remaining OIDs will be passed to rev-list.
The main user-visible benefit is the performance of fetch from a partial clone - specifically, the speedup of the connectivity check done before the fetch.
In particular, a no-op fetch into a partial clone on my computer was sped up from 7 seconds to 0.01 seconds. This is a complement to the work in 2df1aa239c ("fetch: forgo full connectivity check if --filter", 2020-01-30, Git v2.26.0-rc0 -- merge listed in batch #5), which is the child of the aforementioned 50033772d5. In that commit, the connectivity check after the fetch was sped up.
The addition of the fast path might cause performance reductions in these cases:

*

*If a partial clone or a fetch into a partial clone fails, Git will fruitlessly run rev-list (it is expected that everything fetched would go into promisor packs, so if that didn't happen, it is most likely that rev-list will fail too).

*Any connectivity checks done by receive-pack, in the (in my opinion, unlikely) event that a partial clone serves receive-pack.
I think that these cases are rare enough, and the performance reduction in this case minor enough (additional object DB access), that the benefit of avoiding a flag outweighs these.

With Git 2.27 (Q2 2020), the object walk with object filter "--filter=tree:0" can now take advantage of the pack bitmap when available.
See commit 9639474, commit 5bf7f1e (04 May 2020) by Jeff King (peff).
See commit b0a8d48, commit 856e12c (04 May 2020) by Taylor Blau (ttaylorr).
(Merged by Junio C Hamano -- gitster -- in commit 69ae8ff, 13 May 2020)

pack-bitmap.c: support 'tree:0' filtering
Signed-off-by: Taylor Blau

In the previous patch, we made it easy to define other filters that exclude all objects of a certain type. Use that in order to implement bitmap-level filtering for the '--filter=tree:<n>' filter when 'n' is equal to 0.
The general case is not helped by bitmaps, since for values of 'n > 0', the object filtering machinery requires a full-blown tree traversal in order to determine the depth of a given tree.
Caching this is non-obvious, too, since the same tree object can have a different depth depending on the context (e.g., a tree was moved up in the directory hierarchy between two commits).
But, the 'n = 0' case can be helped, and this patch does so.
Running p5310.11 in this tree and on master with the kernel, we can see that this case is helped substantially:
Test                                  master              this tree
--------------------------------------------------------------------------------
5310.11: rev-list count with tree:0   10.68(10.39+0.27)   0.06(0.04+0.01) -99.4%

And:
See commit 9639474, commit 5bf7f1e (04 May 2020) by Jeff King (peff).
See commit b0a8d48, commit 856e12c (04 May 2020) by Taylor Blau (ttaylorr).
(Merged by Junio C Hamano -- gitster -- in commit 69ae8ff, 13 May 2020)

pack-bitmap: pass object filter to fill-in traversal
Signed-off-by: Jeff King
Signed-off-by: Taylor Blau

Sometimes a bitmap traversal still has to walk some commits manually, because those commits aren't included in the bitmap packfile (e.g., due to a push or commit since the last full repack).
If we're given an object filter, we don't pass it down to this traversal.
It's not necessary for correctness because the bitmap code has its own filters to post-process the bitmap result (which it must, to filter out the objects that are mentioned in the bitmapped packfile).
And with blob filters, there was no performance reason to pass along those filters, either. The fill-in traversal could omit them from the result, but it wouldn't save us any time to do so, since we'd still have to walk each tree entry to see if it's a blob or not.
But now that we support tree filters, there's opportunity for savings. A tree:depth=0 filter means we can avoid accessing trees entirely, since we know we won't them (or any of the subtrees or blobs they point to).
The new test in p5310 shows this off (the "partial bitmap" state is one where HEAD~100 and its ancestors are all in a bitmapped pack, but HEAD~100..HEAD are not).
Here are the results (run against linux.git):
Test                                                  HEAD^               HEAD
-------------------------------------------------------------------------------------------------
[...]
5310.16: rev-list with tree filter (partial bitmap)   0.19(0.17+0.02)     0.03(0.02+0.01) -84.2%

The absolute number of savings isn't huge, but keep in mind that we only omitted 100 first-parent links (in the version of linux.git here, that's 894 actual commits).
In a more pathological case, we might have a much larger proportion of non-bitmapped commits. I didn't bother creating such a case in the perf script because the setup is expensive, and this is plenty to show the savings as a percentage.

With Git 2.32 (Q2 2021), handling of "promisor packs" that allows certain objects to be missing and lazily retrievable has been optimized (a bit).
See commit c1fa951, commit 45a187c, commit fcc07e9 (13 Apr 2021) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 13158b9, 30 Apr 2021)

revision: avoid parsing with --exclude-promisor-objects
Signed-off-by: Jeff King

When --exclude-promisor-objects is given, before traversing any objects we iterate over all of the objects in any promisor packs, marking them as UNINTERESTING and SEEN.
We turn the oid we get from iterating the pack into an object with parse_object(), but this has two problems:

*

*it's slow; we are zlib inflating (and reconstructing from deltas) every byte of every object in the packfile

*it leaves the tree buffers attached to their structs, which means our heap usage will grow to store every uncompressed tree simultaneously.
This can be gigabytes.

We can obviously fix the second by freeing the tree buffers after we've parsed them.
But we can observe that the function doesn't look at the object contents at all! The only reason we call parse_object() is that we need a "struct object" on which to set the flags.
There are two options here:

*

*we can look up just the object type via oid_object_info(), and then call the appropriate lookup_foo() function

*we can call lookup_unknown_object(), which gives us an OBJ_NONE struct (which will get auto-converted later by object_as_type() via calls to lookup_commit(), etc).

The first one is closer to the current code, but we do pay the price to look up the type for each object.
The latter should be more efficient in CPU, though it wastes a little bit of memory (the "unknown" object structs are a union of all object types, so some of the structs are bigger than they need to be).
It also runs the risk of triggering a latent bug in code that calls lookup_object() directly but isn't ready to handle OBJ_NONE (such code would already be buggy, but we use lookup_unknown_object() infrequently enough that it might be hiding).
I went with the second option here.
I don't think the risk is high (and we'd want to find and fix any such bugs anyway), and it should be more efficient overall.
The new tests in p5600 show off the improvement (this is on git.git):
Test                                 HEAD^               HEAD
-------------------------------------------------------------------------------
5600.5: count commits                0.37(0.37+0.00)     0.38(0.38+0.00) +2.7%
5600.6: count non-promisor commits   11.74(11.37+0.37)   0.04(0.03+0.00) -99.7%

The improvement is particularly big in this script because every object in the newly-cloned partial repo is a promisor object.
So after marking them all, there's nothing left to traverse.

An earlier optimization discarded a tree-object buffer that is still in use, which has been corrected with Git 2.38 (Q3 2022).
See commit 1490d7d (14 Aug 2022) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 01a30a5, 25 Aug 2022)

is_promisor_object(): fix use-after-free of tree buffer
Reported-by: Andrew Olsen
Signed-off-by: Jeff King

Since commit fcc07e9 (is_promisor_object(): free tree buffer after parsing, 2021-04-13, Git v2.32.0-rc0 -- merge listed in batch #13) (is_promisor_object(): free tree buffer after parsing, 2021-04-13), we'll always free the buffers attached to a "struct tree" after searching them for promisor links.
But there's an important case where we don't want to do so: if somebody else is already using the tree!
This can happen during a "rev-list --missing=allow-promisor" traversal in a partial clone that is missing one or more trees or blobs.
Even a trivial use of "--missing=allow-promisor" triggers this problem, as the included test demonstrates (it's just a vanilla --blob:none clone).

A: After realizing that the upper limit to the transfer speed of data, is the ssh connection which is established "outside" of git I did some experiments, and found that the upper limit of using pcsp (Putty scp) was 3,0 MB/s as the blowfish encryption scheme was properly chosen.  A control experiment with raw ftp showed that the transfer speed was 3.1 MB/s, so it indicated that this was the upper bound of the network.
This runs inside a vmware hypervisor, and as the process doing network I/O utilized almost 100% cpu it indicated that the bottleneck was the Ubuntu network card driver.  I then found that even though vmware tools were installed, for some reason the kernel still used the vlance driver (emulating a 10 MBps network card with IRQ's and all) instead of the vmxnet driver (which speaks directly to the hypervisor).  This now awaits a service window to be changed.
In other words, the problem was not with git but the underlying "hardware".

A:
PS. Fair warning:
git is generally considered blazingly fast. You should try cloning a full repo from darcs, bazaar, hg (god forbid: TFS or subversion...). Also, if you routinely clone full repos from scratch, you'd be doing something wrong anyway. You can always just git remote update and get incremental changes.
For various other ways to keep full repos in synch see, e.g.

*

*"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones

*How to update a git clone --mirror?
(The contain links to other relevant SO posts)

Dumb copy
As mentioned you could just copy a repository with 'dumb' file transfer.
This will certainly not waste time compressing, repacking, deltifying and/or filtering.
Plus, you will get

*

*hooks

*config (remotes, push branches, settings (whitespace, merge, aliases, user details etc.)

*stashes (see Can I fetch a stash from a remote repo into a local branch? also)

*rerere cache

*reflogs

*backups (from filter-branch, e.g.) and various other things (intermediate state from rebase, bisect etc.)

This may or may not be what you require, but it is nice to be aware of the fact

Bundle
Git clone by default optimizes for bandwidth. Since git clone, by default, does not mirror all branches (see --mirror) it would not make sense to just dump the pack-files as-is (because that will send possibly way more than required).
When distributing to a truly big number of clients, consider using bundles.
If you want a fast clone without the server-side cost, the git way is bundle create. You can now distribute the bundle, without the server even being involved. If you mean that bundle... --all includes more than simple git clone, consider e.g. bundle ... master to reduce the volume.
git bundle create snapshot.bundle --all # (or mention specific ref names instead of --all)

and distribute the snapshot bundle instead. That's the best of both worlds, while of course you won't get the items from the bullet list above. On the receiving end, just
git clone snapshot.bundle myclonedir/

Compression configs
You can look at lowering server load by reducing/removing compression.
Have a look at these config settings (I assume pack.compression may help you lower the server load)

core.compression
An integer -1..9, indicating a default compression level. -1 is the zlib default. 0 means no compression, and 1..9 are various speed/size tradeoffs, 9 being slowest. If set, this provides a default to other compression variables, such as
  core.loosecompression and pack.compression.
core.loosecompression
An integer -1..9, indicating the compression level for objects that are not in a pack file. -1 is the zlib default. 0 means no compression, and 1..9 are various speed/size tradeoffs, 9 being slowest. If not set, defaults to
  core.compression. If that is not set, defaults to 1 (best speed).
pack.compression
An integer -1..9, indicating the compression level for objects in a pack file. -1 is the zlib default. 0 means no compression, and 1..9 are various speed/size tradeoffs, 9 being slowest. If not set, defaults to core.compression. If that
  is not set, defaults to -1, the zlib default, which is "a default compromise between speed and compression (currently equivalent to level 6)."
Note that changing the compression level will not automatically recompress all existing objects. You can force recompression by passing the -F option to git-repack(1).

Given ample network bandwidth, this will in fact result in faster clones. Don't forget about git-repack -F when you decide to benchmark that!

A: Use the depth to create a shallow clone.
git clone --depth 1 <repository>

A: I'm bench marking git clone.
It can be faster with --jobs options if the project include submodules
ex:
git clone --recursive --shallow-submodules --depth 1 --branch "your tag or branch" --jobs 5 --  "your remote repo"

A: From the log it seems you already finished the clone, if your problem is that you need to do this process multiple times on different machines, you can just copy the repository directory from one machine to the other. This way will preserve the relationship (remotes) between each copy and the repository you cloned from.


text:
Q: Passar Array String por parâmetro public List<String> Matriz(){

    String CaminhoArquivo=("C:\\Users\\jessica borges"
            + "\\Downloads\\CalculadoraMatrizes-20190315T112959Z-001"
            + "\\CalculadoraMatrizes-20190315T112959Z-001"
            + "\\CalculadoraMatrizes\\src\\ArquivosMatriz\\matrix.txt");

    List<String> conteudo = new ArrayList<>();
        try {
        BufferedReader in = new BufferedReader(new FileReader(CaminhoArquivo));
        String linha;
        while ((linha = in.readLine()) != null) {
            conteudo.addAll(Arrays.asList(linha.split(" ")));
        }
         in.close();
        } catch (IOException ioe) {
            System.out.println(ioe);
            }

        System.out.println(conteudo);
        return conteudo;
}

Esse método acima adiciona o que eu quero na array, quero tratar o retorno dele em outro método que segue abaixo:
public void Matriz22(){

}

Já tentei vários modos porém não conseguir.

A: Para o método Matriz22 receber uma lista de String é assim:
public void Matriz22(List<String> lista){

}

Você não mostrou a classe ao qual pertence o método Matriz() então improvisei, para passar a lista de retorno do método Matriz() faz assim:
public static void main(String[] args) {
    Classe classe = new Classe();
    List<String> lista = classe.Matriz();
    classe.Matriz22(lista);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP: insert array with seperate lines into database as values I am passing an array through ajax to PHP where I want to insert them as a row in mysql. Is there a way i can do that?
Javascript:
var textarray = [];
for(var i = 0; i<data.length; i++){
  var sms = $('#TxtMessage').val();
  var brand = data[i].brand;
  var type = data[i].type;
  var csvLine = `${sms}, ${brand}, ${type} `;
  textarray.push(csvLine)
}

var resultCSV = textarray.join('\n');

//Pass the array to PHP
$.ajax({
  type: "POST",
  url: "../php/functions.php",
  data: { results: resultCSV },
  success: function(data) {
       console.log(data);
  }
});

In PHP i would like to insert each row into mysql database.
The values I pass to PHP look like this
sample text, Toyota, 30/10/2008 10:00:00
sample text, Nissan, 17/02/2021 14:00:00

so each row of the text should go in as a row into the database.
PHP:
$myArray = $_POST['results'];
$columns = implode(" ",array_keys($myArray));
$escaped_values = array_map('mysql_real_escape_string', array_values($myArray));
$values  = implode(", ", $escaped_values);
$sql = "INSERT INTO `databasetable`($columns) VALUES ($values)";

A: What people usually do is use something like json to encode and decode their data they pass.  It is much easier than what you are doing.
You encode like
$myVar = json_encode($dataArray);

You decode like
$myReturn = json_decode($_POST['csvDataArray']);

If you want to convert csv to array you can use
$mycsvArray = array_map("str_getcsv", explode("\n", $csv));

You may have to stripslashes.
Then it is as simple as looping to build your query. Something like this.
$myQuery = array();
foreach($myCSVArray as $rowArray) {
  $myQuery[] = INSERT INTO `databasetable`($columns) VALUES ($escaped_values);
}


text:
Q: Using Networked-Aframe with aframe-react I'm trying to make a multiplayer game using the Networked-Aframe library with aframe-react. The big roadblock I've run into is I can't simultaneously run:
react-scripts start

to run react and
node ./src/vendor/easyrtc-server.js

to run my server.
Maybe create a production build of my react app, then run the server?
How do I get these two working together?
My easyrtc-server.js: https://pastebin.com/PJ0UchSi

A: You can add new scripts to your package.json file to run different commands.
Example
{
  "name": "someapp",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
     // some dependecies
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "custombuild": "npm build && node ./src/vendor/easyrtc-server.js"
  }
}

Then when you can run,
npm custombuild

This command will first build your app and then start your server.


text:
Q: error updating ubuntu 18.04.2 LTS I've got an error "The repository 'http://us.archive.ubuntu.com/ubuntu artful-updates Release' no longer has a Release file" while running Update Manager.
Thanks.

A: you should open "Software and Updates", go to the "Other Software" tab, then find that line and delete it. then exit Software and sources and allow soures to reload.
after that yupdates will work  once again.

A: I took advice about  How do I restore the default repositories? and created empty /etc/apt/sources.list and set "Software&Updates" options.
Now system updates runs with no errors.
  But I have no idea where did previous release repository 'http://us.archive.ubuntu.com/ubuntu artful-updates' come from in /etc/apt/sources.list. I didn't make any changes in /etc/apt/sources.list and my previous system updates were successful.
I've found useful these articles.
All series Ubuntu
Releases
Repositories/Ubuntu
Repositories/CommandLine


text:
Q: Significance of accumulation points in complex analysis? What is the significance of accumulation points in complex analysis.
For example, the Identity Theorem, and the Principle of Analytic Continuation, both refer to accumulation points.
I have failed to understand why they are important in these theorems.


text:
Q: Excel VBA loop through a string of numbers until a letter is found I have a string in a cell, lets say it says "Client Ref: F123456PassPlus".
It's possible the string not have a letter before the numbers, it's possible there is a symbol in the numbers and it's possible there is a space between the letter and the numbers.
I need to extract only the numbers as a variable. I have the code to do it, but it doesn't know when to stop looping through the string. It should stop when there is something other than a number or symbol but it carries on instead.
IsNumber = 1
ref = ""
If branch = "" Then
    e = b
Else
    e = b + 1
End If
f = 1
While IsNumber = 1
    For intpos = 1 To 15
        ref = Mid(x, e, f)
        f = f + 1
        Select Case Asc(ref)
            Case 45 To 57
                IsNumber = 1
            Case Else
                IsNumber = 0
                Exit For
        End Select
    Next
    IsNumber = 0
Wend

Any variable letters there that don't have definitions have been previously defined, e tells the code where to start copying and x is the cell that contains the string. For now, it all works fine, it starts at the number and copies them and builds them into a bigger and bigger string, but it will only stop when intpos reaches 15.

A: There is nothing wrong with how your trying to accomplish this task but I can't help myself from suggesting regex :-)
This example will strip all non-digits from the string located in A1 and present the result in a message box.  The pattern used is [^0-9]
Sub StripDigits()
    Dim strPattern As String: strPattern = "[^0-9]"
    Dim strReplace As String: strReplace = vbnullstring
    Dim regEx As New RegExp
    Dim strInput As String
    Dim Myrange As Range

    Set Myrange = ActiveSheet.Range("A1")

    If strPattern <> "" Then
        strInput = Myrange.Value
        strReplace = ""

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        If regEx.test(strInput) Then
            MsgBox (regEx.Replace(strInput, strReplace))
        Else
            MsgBox ("Not matched")
        End If
    End If
End Sub

Make sure you add a reference to "Microsoft VBScript Regular Expressions 5.5"
For more information on how to use regex in Excel, including examples of looping through ranges check out this post.
Results:

A: I got rid of the Asc check and added a check against each character as you pass it before building the numerical "string".
IsNumber = 1
ref = ""
If branch = "" Then
    e = b
Else
    e = b + 1
End If
f = 1
While IsNumber = 1
    For intpos = 1 To 15
        char = Mid(x, e + intpos, 1)
        f = f + 1
        If IsNumeric(char) Then
            ref = Mid(x, e, f)
            IsNumber = 1
        Else
            IsNumber = 0
            Exit For
        End If
    Next
    IsNumber = 0
Wend

A: This code, loosely based on your, works (produces "12345"). For large strings or more complex extraction needs, I would consider learning about the regex COM object.
Function ExtractNumber(ByVal text As String) As String

  ExtractNumber = ""

  foundnumber = False

  For e = 1 To Len(text)
    ref = Mid(text, e, 1)
        Select Case Asc(ref)
            Case 45 To 57   'this includes - . and /, if you want only digits, should be 48 to 57
                foundnumber = True
                ExtractNumber = ExtractNumber & ref
            Case Else
                If foundnumber = True Then Exit For
        End Select
  Next

End Function


text:
Q: Is there any difference between cpython and python I want to know the difference between CPython and Python because I have heard Python is developed in C - then what is the use of CPython?

A: Python is a language.
CPython is the default byte-code interpreter of Python, which is written in C.
There is also other implementation of Python such as IronPython (for .NET), Jython (for Java), etc.

A:
CPython is Guido van Rossum's
  reference version of the Python
  computing language. It's most often
  called simply "Python"; speakers say
  "CPython" generally to distinguish it
  explicitly from other implementations.


text:
Q: Is there a way to order posts in a category with a button? [Wordpress] I wish to put a drop-down button on my WordPress category page. This drop-down button will have two choices; 'Ascending' and 'Descending'. After clicking the choice, posts on that page will re-order accordingly.
Can anyone help? Right now, the theme is using years. But it doesn't work properly.
Below, the theme is displaying post years in a drop-down menü.

                                        Sırala

                                            <?php
                                                $terms_year = array(
                                                    'post_type'         => array('post'),
                                                );
                                                $years = array();
                                                $query_year = new WP_Query( $terms_year );
                                                if ( $query_year->have_posts() ) :
                                                    while ( $query_year->have_posts() ) : $query_year->the_post();
                                                        $year = get_the_date('Y');
                                                        if(!in_array($year, $years)){
                                                            $years[] = $year;
                                                        }
                                                    endwhile;
                                                    wp_reset_postdata();
                                                endif;
                                                foreach ($years as $year) {
                                            ?>

<a class="nav-link dropdown-item" data-bs-toggle="tab" data-bs-target="#year-<?php echo $year; ?>" type="button" role="tab"><?php echo $year; ?>

                                            <?php } ?>

I want to change that, as I have mentioned.
And here is how posts are displayed (but it doesn't work).
<?php
                        foreach( $years as $year ) {
                    ?>
                    <div class="tab-pane fade" id="year-<?php echo $year; ?>">

                                    <?php wp_reset_query(); if (have_posts()) : while (have_posts()) : the_post(); $date = get_the_date('Y'); ?>
                                    <?php if($date == $year) { ?>

                                            <a href="<?php the_permalink(); ?>" style="color: <?php echo $rl_category_color; ?>;" class="d-flex align-items-center">

                                                            <?php
                                                                $author = get_post_meta( get_the_ID(), 'postAuthor', true );
                                                                if(!empty($author)) {
                                                                    foreach ($author as $author_item => $item) {
                                                                        echo get_the_title($item).'
';
                                                                    }
                                                                }
                                                            ?>

                                                            <?php
                                                                $konu = get_the_category( get_the_ID() );
                                                                foreach ($konu as $item) {
                                                                    $konu_name = $item->name;
                                                                }
                                                                echo $konu_name;
                                                            ?>

<?php echo title_limit(40); ?>

<?php echo icerik_limit(get_the_content(), 150); ?>

                                    <?php } ?>
                                    <?php endwhile; endif; ?>

                    <?php } ?>

Related Page: https://www.mgc.com.tr/haberler/
image


text:
Q: Datastructure to represent hierarchial structure I recently had an interview question that asked how to represent an organizational structure with data structures. Queries like list all employees under a manager should be efficiently queried.
I was answering on the lines of a N-way tree, though I was not very sure what should be the key and how to implement it. Curious to know what is the best way this can be done.

A: An oriented graph with adjacency list representation seems to be the best solution.

A: You've got a choice - custom containers that are slightly more efficient for this exact need, or working out which STL containers are going to do a pretty good job.  In an interview, I'd definitely start by saying - "let's explore what the STL containers would do, then see if there's inefficiencies (either in scalability or in support of concurrency) justifying a custom container".
So, typically you'd have a unique employee_id for each employee.  You want to be able to search for employees using that id, and probably by name, and get reasonably fast results.  So, if you want fast arbitrary insert/delete you could use a std::map or unordered_map (C++11) of employee id to employee name and other details, and another map going from name to employee_id.  If the data doesn't change (often), either or both could be a sorted vector - a little better packed and memory/cache-efficient, but still allowing O(log2n) lookup.  Given that basic model, we can extend it to reflect the relationships between employees by having each employee object contain the employee_id of their manager, and a vector of the employee_ids of their direct reports.  As the number of direct reports is unlikely to ever be too large, a vector is quite practical.  This does mean that to list all employees you have to "walk the tree" of direct reports and their direct reports etc., but that's pretty efficient anyway and saves a lot of memory compared to redundantly recording all direct and indirect reports against every employee.
In all probability, the STL approach above will suit your needs.  With a little locking it can be thread safe albeit perhaps not optimally performant.  Still, when there is demand for more scalability, persistence, cross-process transactional semantics, etc. the data's probably better moved off into a commercial database anyway unless you're a specialist in in-memory databases (e.g. when I worked in Bloomberg's Ticker Plant - inserting hundreds of thousands of financial records per second - we did specialise, but few HR programs require it).


text:
Q: Build spring integration release strategy using spring DSL I am new to Spring integration. I am trying to split the message from a file using file splitter and then use .aggregate() to build a single message and send to output channel.
I have markers as true and hence apply-sequence is false by default now.
I have set correlationId to a constant "1" using enrichHeaders. I have trouble setting the realease strategy as I do not have a hold on the sequence end. Here is how my code looks.
    IntegrationFlows
                .from(s -> s.file(new File(fileDir))
                                .filter(getFileFilter(fileName)),
                        e -> e.poller(poller))

                .split(Files.splitter(true, true)
                                .charset(StandardCharsets.US_ASCII),
                        e -> e.id(beanName)).enrichHeaders(h -> h.header("correlationId", "1"));

 IntegrationFlow integrationFlow = integrationFlowBuilder
            .<Object, Class<?>>route(Object::getClass, m -> m
                    .channelMapping(FileSplitter.FileMarker.class, "markers.input")
                    .channelMapping(String.class, "lines.input"))
            .get();

@Bean
    public IntegrationFlow itemExcludes() {
        return flow -> flow.transform(new ItemExcludeRowMapper(itemExcludeRowUnmarshaller)) //This maps each line to ItemExclude object
                .aggregate(aggregator -> aggregator
                        .outputProcessor(group -> group.getMessages()
                        .stream()
                        .map(message -> ((ItemExclude) message.getPayload()).getPartNumber())
                        .collect(Collectors.joining(","))))
                .transform(Transformers.toJson())
                .channel(customSource.itemExclude());
    }

    @Bean
    public IntegrationFlow itemExcludeMarkers() {
        return flow -> flow
                .log(LoggingHandler.Level.INFO)
                .<FileSplitter.FileMarker>filter(m -> m.getMark().equals(FileSplitter.FileMarker.Mark.END))
                .<FileHandler>handle(new FileHandler(configProps))
                .channel(NULL_CHANNEL);
    }

Any help appreciated.

A: I would move your header enricher for the correlationId before splitter and make it like this:
 .enrichHeaders(h -> h
        .headerFunction(IntegrationMessageHeaderAccessor.CORRELATION_ID,
                   m -> m.getHeaders().getId()))

The constant correlationId is absolutely not good in the multi-threaded environment: different threads splits different files and send different lines to the same aggregator. So, with the "1" as correlation key you'd have always one group to aggregate and release. The default sequence behavior is to populate the original message id to the correlationId. Since you are not going to rely on the applySequence from the FileSplitter I suggest that simple solution to emulate that behavior.
As Gary pointed in his answer you need to think about custom ReleaseStrategy and send FileSplitter.FileMarker to the aggregator as well. The FileSplitter.FileMarker.END has lineCount property which can be compared with the MessageGroup.size to decide that we are good to release the group. The MessageGroupProcessor indeed has to filter FileSplitter.FileMarker messages during building the result for output.

A: Use a custom release strategy that looks for the END marker in the last message and, perhaps, a custom output processor that removes the markers from the collection.


text:
Q: Elasticsearch Nest client Search I try to compose a dynamic query with NEST (Elastichsearc library for dotnet 5.0) but only the first code work:
Case 1: (Work)
var response1 = await client.SearchAsync<VideoManifestElasticDto>(s =>
                s.Query(q => q
                    .Bool(b => b
                        .Must(mu => mu
                                .Wildcard(f => f.Title, '*' + dtoSearch.Title + '*')
                ))));
                var aaa1 = response1.Documents;

Return 4 documents.  It's OK
Case  2: (Not Work)
var response2 = await client.SearchAsync<VideoManifestElasticDto>(s =>
                s.Query(q => q
                    .Bool(b => b
                        .Must(mu => new WildcardQuery() { Field = nameof(VideoManifestElasticDto.Title), CaseInsensitive = true, Value = '*' + dtoSearch.Title + '*' }
                ))));
                var aaa2 = response2.Documents;

Return 0 documents.  Why?
Case 3: (Not Work)
Last case, this is my goal i wan't create a dynamic query
var response3 = await client.SearchAsync<VideoManifestElasticDto>(Blah(dtoSearch));
var aaa3 = response3.Documents;
public static SearchDescriptor<VideoManifestElasticDto> Blah(VideoManifestElasticDto videoManifestElasticDto)
        {
            return new SearchDescriptor<VideoManifestElasticDto>().Query(b => b.Bool( c => c.Must(Orso(videoManifestElasticDto))));
        }

        public static QueryContainer[] Orso(VideoManifestElasticDto videoManifestElasticDto)
        {
            List<QueryContainer> queryContainerList = new List<QueryContainer>();
            if (videoManifestElasticDto == null)
            {
                return queryContainerList.ToArray();
            }

            if (!string.IsNullOrWhiteSpace(videoManifestElasticDto.Title))
            {
                var orQuery = new WildcardQuery() { Field = nameof(VideoManifestElasticDto.Title), CaseInsensitive = true, Value = '*' + videoManifestElasticDto.Title + '*' };
                queryContainerList.Add(orQuery);
            }
            else if (!string.IsNullOrWhiteSpace(videoManifestElasticDto.Description))
            {
                var orQuery = new MatchQuery() { Field = "Description", Query = videoManifestElasticDto.Description };
                queryContainerList.Add(orQuery);
            }
            else if (!string.IsNullOrWhiteSpace(videoManifestElasticDto.VideoId))
            {
                var orQuery = new MatchQuery() { Field = "VideoId", Query = videoManifestElasticDto.VideoId };
                queryContainerList.Add(orQuery);
            }

            return queryContainerList.ToArray();
        }


text: Q: Number of items specifying image in Adaptive Cards I'm trying to design an adaptive card, but I'm stuck at a point. Like if an order has multiple items, how can I show it in the same way as the attached image shows? Can someone help me out with this. Thanks in Advance.enter image description here


text:
Q: return one value from database with mysql php pdo Im not trying to use a loop. I just one one value from one column from one row. I got what I want with the following code but there has to be an easier way using PDO.
try {
        $conn = new PDO('mysql:host=localhost;dbname=advlou_test', 'advlou_wh', 'advlou_wh');
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }

$userid = 1;

$username = $conn->query("SELECT name FROM `login_users` WHERE username='$userid'");
$username2 = $username->fetch();
$username3 = $username2['name'];

echo $username3;

This just looks like too many lines to get one value from the database. :\

A: You can use fetchColumn():
$q= $conn->prepare("SELECT name FROM `login_users` WHERE username=?");
$q->execute([$userid]);
$username = $q->fetchColumn();

A: You could create a function for this and call that function each time you need a single value. For security reasons, avoid concatenating strings to form an SQL query. Instead, use prepared statements for the values and hardcode everything else in the SQL string. In order to get a certain column, just explicitly list it in your query. a fetchColumn() method also comes in handy for fetching a single value from the query
function getSingleValue($conn, $sql, $parameters)
{
    $q = $conn->prepare($sql);
    $q->execute($parameters);
    return $q->fetchColumn();
}

Then you can simply do:
$name = getSingleValue($conn, "SELECT name FROM login_users WHERE id=?", [$userid]);

and it will get you the desired value.
So you need to create that function just once, but can reuse it for different queries.
This answer has been community edited addressing security concerns

A: Just like it's far too much work to have to get into your car, drive to the store, fight your way through the crowds, grab that jug of milk you need, then fight your way back home, just so you can have a milkshake.
All of those stages are necessary, and each subsequent step depends on the previous ones having been performed.
If you do this repeatedly, then by all means wrap a function around it so you can reuse it and reduce it down to a single getMyValue() call - but in the background all that code still must be present.


text:
Q: iOS 10 video tag with "autoplay muted playsinline" stops background music (spotify) I am trying to keep playing background music like Spotify playing with playing a inline video with attributs: "autoplay muted playsinline".
<video id="video" muted="muted" autoplay loop muted playsinline >
     <source src="video.mp4" type="video/mp4">
</video>

<script>
window.onload = function () {
    var element = document.getElementById('video');
    element.muted = "muted";
}
</script>

But when I run this the video is plays inline and autoplaying. But as soon as the video start the background music app is pausing.

A: Simple answer. You can't.
One solution:
is if you remove the sound track from the video. The background music like Spotify DO NOT stop playing.


text:
Q: Html canvas video streaming I have this code which playing my camera's view in a video tag and then into canvas element at the same page, the page has 2 squares one for the video tag(playing camera's view) and the other is for canvas(playing the same video of the video tag). How I can edit my code to make the video play in a canvas at another page to let my user watch it live, and if there is a method to let users watch it at the same page not another page and see the canvas only, it's also accepted.
here is my html file:
<html>
    <head>
        <meta charset="UTF-8">
        <title>With canvas</title>
    </head>
    <body>
        <div class="booth">
            <video id="video" width="400" height="300" autoplay></video>
            <canvas id="canvas" width="400" height="300" style="border: 1px solid black;"></canvas>
        </div>
        <script src="video.js"></script>
    </body>
</html>

And here is my js file:
(function() {
    var canvas= document.getElementById('canvas'),
    context = canvas.getContext('2d'),
    video = document.getElementById('video'),
    vendorUrl = window.URL || window.webkitURL;

    navigator.getMedia = navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia ||
                         navigator.msGetUserMedia;

    navigator.getMedia ({
        video: true,
        audio: false
    }, function(stream) {
        //video.src = vendorUrl.createObjectURL(stream);
        if ('srcObject' in video) {
            video.srcObject = stream;
          } else {
            video.src = vendorUrl.createObjectURL(stream);
          }
        video.play();
    }, function(error) {
        // An error occured
        //error.code
    });

    video.addEventListener('play', function() {
        setInterval(() => {
        draw(this, context, 400, 300);
        }, 100);

    }, false );
    function draw(video, context, width, height) {
        context.drawImage(video, 0, 0, width, height);
    }

}) ();

A: use MediaRecorder to get live data in chunks as media recorder records from camera and give chunks that can be send over other end of user
then use mediasource to append chunks on other side of user to append it and play it live as it recieves new chunks
i know its a complicated thing but believe me when i was experimenting this i have  spent good amount of time to understand i believe you will get some benefit from my experiment code below
here is a working demo
var mediasource = new MediaSource(),video = document.querySelector("video"),
    mime = 'video/webm;codecs=vp9,opus'
video.src = URL.createObjectURL(mediasource)

mediasource.addEventListener("sourceopen",function(_){
    var source = mediasource.addSourceBuffer(mime)
    navigator.mediaDevices.getUserMedia({video: true,audio: true}).then(stream=>{
        var recorder = new MediaRecorder(stream,{mimeType:mime})
        recorder.ondataavailable = d =>{
// creating chunks of 5 seconds of video continiously
            var r = new Response(d.data).arrayBuffer() // convert blob to arraybuffer
            r.then(arraybuffer=>{
                source.appendBuffer(arraybuffer)
            })
        }
        recorder.start(5000)
    })
})

<video class="video" controls autoplay></video>

separated version for gathering live data and playing it demo
// gathering camera data to liveData array
var vid = document.querySelector(".video"),
    mime = 'video/webm;codecs=vp9,opus',
    liveData = []

    navigator.mediaDevices.getUserMedia({video:true,audio:true}).then(stream=>{
        var recorder = new MediaRecorder(stream,{mimeType:mime})
        recorder.ondataavailable = d =>{
            console.log("capturing")
            new Response(d.data).arrayBuffer().then(eachChunk=>{
            // recording in chunks here and saving it to liveData array
                liveData.push(eachChunk)
            })
        }
        recorder.start(5000)
    })
//--------------------------------------------------------------------------------

// playing from liveData in video
var ms = new MediaSource()
vid.src =URL.createObjectURL(ms)

ms.onsourceopen = function(){
    var source = ms.addSourceBuffer(mime),chunkIndex = 0
    setInterval(function(){
        if(liveData.length > 0){
            var currentChunk = liveData[chunkIndex]
            source.appendBuffer(currentChunk)
            console.log("playing")
            chunkIndex++
        }
    },5000)
}


text:
Q: Is a SQL Server IDENTITY auto-incremented field thread-safe? I've some questions regarding the SQL Server IDENTITY auto-incremented column.
Does someone know if that field is thread-safe?
Can I use SQL Server IDENTITY column in a multitask application that attempt to parallel insert some records with an IDENTITY auto-incremented column?
Do you have any docs link about that?

A: It is thread-safe in the sense that every number will be handed out at most once. Numbers can be skipped, though.
This is a well-accepted fact. SQL Server would be garbage if this was not so. It is the point of identity fields to hand out unique values.
Be aware that you can circumvent these guarantees by reseeding the column. That way you can have it hand out whatever you want.
Also note, that an IDENTITY constraint does not enforce uniqueness of values in that column.


text:
Q: Krusader & Xfce - Wastebin is full I've just installed Krusader and have annoying problem. Whenever I try to delete a file (move to trash) I've got a message:

The wastebin has reached its maximum size!
  Cleanup the wastebin manually.

My trash is totally empty so... I have no idea why it says that its full.
How to solve it?


text:
Q: iOS: Programmatically calling Container View Before the Main View Controller is called, through a delegate I'll notify Main View Controller whether to call TVC1 or TVC2 in Container View.
Question: How can I programmatically tell the Container View in Main View Controller to call TVC1  or TVC2?
TVC1 *tvc1 = [self.storyboard instantiateViewControllerWithIdentifier:@"TVC1"];
TVC2 *tvc2 = [self.storyboard instantiateViewControllerWithIdentifier:@"TVC2"];

Where and how do I tell the Container View to load one of these controllers upon loading Main View Controller?

A: through delegate u can know which view will be added so u can manage it by using any bool value n in viewDidLoad you can load that view by putting one condition
in mainController:
bool isFirstView;

-(void)delegate:(bool)isFirst
{
  isFirstView = isFirst;
}

// in viewDidLoad
)
(void)viewDidLoad
{
  if(isFirstView)
  {
    TVC1 *tvc1 = [self.storyboard instantiateViewControllerWithIdentifier:@"TVC1"];
  }
  else
  {
    TVC2 *tvc2 = [self.storyboard instantiateViewControllerWithIdentifier:@"TVC2"];
  }
}

A: You can do this by using custom Container View Controller which will manage child view controllers.

There is a good tutorial for that:
http://sandmoose.com/post/35714028270/storyboards-with-custom-container-view-controllers


text:
Q: Having some trouble with php mail on localhost with XAMPP I'm trying to work locally so I installed XAMPP and need help resolving an issue while sending mail via a php script on localhost. I've tested everything on a web-facing server and it works fine.
I'm getting the error 'Cannot POST /php/mail.php' from http://localhost:3000/php/mail.php.
I've changed the php.ini and sendmail.ini files and believe they are correctly configured for it to work.
Getting some errors in the DevTools console related to inline scripts but I think they are related to the error page.
Is there somewhere else I can look to debug this error?


text:
Q: How to respond with a stream in a Sveltekit server load function Below I try to respond with a stream when I receive ticker updates.
+page.server.js:
import YahooFinanceTicker from "yahoo-finance-ticker";

const ticker = new YahooFinanceTicker();
const tickerListener = await ticker.subscribe(["BTC-USD"])

const stream = new ReadableStream({
  start(controller) {
    tickerListener.on("ticker", (ticker) => {
      console.log(ticker.price);
      controller.enqueue(ticker.price);
    });
  }
});

export async function load() {

    return response????
};

Note: The YahooFinanceTicker can't run in the browser.
How to handle / set the response in the Sveltekit load function.

A: To my knowledge, the load functions cannot be used for this as their responses are JS/JSON serialized. You can use an endpoint in +server to return a Response object which can be constructed from a ReadableStream.

A: Solution: H.B. comment showed me the right direction to push unsollicited price ticker updates the client.
api route: yahoo-finance-ticker +server.js
import YahooFinanceTicker from "yahoo-finance-ticker";

const ticker = new YahooFinanceTicker();
const tickerListener = await ticker.subscribe(["BTC-USD"])

/** @type {import('./$types').RequestHandler} */
export function GET({ request }) {
  const ac = new AbortController();

  console.log("GET api: yahoo-finance-ticker")
  const stream = new ReadableStream({
    start(controller) {
      tickerListener.on("ticker", (ticker) => {
        console.log(ticker.price);
        controller.enqueue(String(ticker.price));
      }, { signal: ac.signal });
    },
    cancel() {
      console.log("cancel and abort");
      ac.abort();
    },
  })

  return new Response(stream, {
    headers: {
      'content-type': 'text/event-stream',
    }
  });
}

page route: +page.svelte

{@html result}


text:
Q: Powershell: Can I change the Color in a richTextBox with an click event? I am looking to change the background color of a richTextBox when a user clicks on it. I figure I will need a click event. the colors should be specific, so they don't make the text hard to read. I figure I will need a list or array to choose the colors from. I don't think I will need a random function but just a way to change the richTextBox color. any Ideas?
Thanks
 #Generated Form Function
function GenerateForm {
#######################################################################
# Generated On: 8/30/2016 4:54 PM
# Generated By: christnerw
########################################################################

#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
#endregion

#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$richTextBox4 = New-Object System.Windows.Forms.RichTextBox
$richTextBox3 = New-Object System.Windows.Forms.RichTextBox
$richTextBox2 = New-Object System.Windows.Forms.RichTextBox
$richTextBox1 = New-Object System.Windows.Forms.RichTextBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 262
$System_Drawing_Size.Width = 284
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.Name = "form1"
$form1.Text = "Primal Form"

$richTextBox4.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 140
$System_Drawing_Point.Y = 150
$richTextBox4.Location = $System_Drawing_Point
$richTextBox4.Name = "richTextBox4"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 100
$System_Drawing_Size.Width = 100
$richTextBox4.Size = $System_Drawing_Size
$richTextBox4.TabIndex = 3
$richTextBox4.Text = ""

$form1.Controls.Add($richTextBox4)

$richTextBox3.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 32
$System_Drawing_Point.Y = 150
$richTextBox3.Location = $System_Drawing_Point
$richTextBox3.Name = "richTextBox3"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 100
$System_Drawing_Size.Width = 100
$richTextBox3.Size = $System_Drawing_Size
$richTextBox3.TabIndex = 2
$richTextBox3.Text = ""

$form1.Controls.Add($richTextBox3)

$richTextBox2.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 32
$System_Drawing_Point.Y = 37
$richTextBox2.Location = $System_Drawing_Point
$richTextBox2.Name = "richTextBox2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 98
$System_Drawing_Size.Width = 100
$richTextBox2.Size = $System_Drawing_Size
$richTextBox2.TabIndex = 1
$richTextBox2.Text = ""

$form1.Controls.Add($richTextBox2)

$richTextBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 140
$System_Drawing_Point.Y = 37
$richTextBox1.Location = $System_Drawing_Point
$richTextBox1.Name = "richTextBox1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 98
$System_Drawing_Size.Width = 100
$richTextBox1.Size = $System_Drawing_Size
$richTextBox1.TabIndex = 0
$richTextBox1.Text = ""

$form1.Controls.Add($richTextBox1)

#endregion Generated Form Code

#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null

} #End Function

#Call the Function
GenerateForm

A: I'd use a Hashtable to store your color pairs (back/fore), and then execute the color change on the GotFocus and LostFocus event.
$Colors = @{
    'Black'='White'
    'White'='Black'
}
Function ColorSwap = {
Param([string]$Ctrl)
    Invoke-Expression ('${0}.BackColor = $Colors.(${0}.BackColor)' -f $Ctrl)
    Invoke-Expression ('${0}.ForeColor = $Colors.(${0}.ForeColor)' -f $Ctrl)
}
$richTextBox1.add_GotFocus({ColorSwap richTextBox1})
$richTextBox1.add_LostFocus({ColorSwap richTextBox1})
$richTextBox2.add_GotFocus({ColorSwap richTextBox2})
$richTextBox2.add_LostFocus({ColorSwap richTextBox2})
$richTextBox3.add_GotFocus({ColorSwap richTextBox3})
$richTextBox3.add_LostFocus({ColorSwap richTextBox3})
$richTextBox4.add_GotFocus({ColorSwap richTextBox4})
$richTextBox4.add_LostFocus({ColorSwap richTextBox4})

That should make it so when you click in the box it sets the background to black and font to white, and swaps it back when you click outside the box. You could add color pairs to the hashtable if desired.


text:
Q: GET/POST requests missing parameters on form submit This one is driving me crazy. I've tried several different solutions to no avail. Basically what is happening is that, when I submit a form, the request is being sent with no parameters.  I've tried both POST and GET and have monitored the requests with Firebug. Here's some sample code:
<form action="/year/" id="year-form" method="get">
    <select class="dropdown" id="year" onchange="this.form.submit()">
        <option value="all">All</option>
        <option value="2011">2011</option>
        <option value="2010">2010</option>
        <option value="2009">2009</option>
    </select>
</form>

Perhaps I should note that this is on a WordPress based site and I am directing the request back to the page  from which it came.  Any insight on this would be greatly appreciated.

A: It's not submitted because it is missing a name attribute:
<select class="dropdown" id="year" onchange="this.form.submit()" name="year">

So it has nothing to do with Wordpress.


text:
Q: How can I implement a lookup table in PowerShell for a 2-dimensional dataset? I'm writing a financial app and need to implement a lookup table (for the rate table shown) that when given a term and deposit, returns an interest rate
How can I implement this lookup table in PowerShell?

A: A hash table of hash tables meets my needs
Note: I  used ordered hashtables so the table will appear in order by term (top to bottom) and minimum (left to right) if I choose to output the table for the user
class Rates
{
    $ratesTable=[ordered]@{}

    Rates()
    {
        $this.ratesTable.add(12,[ordered]@{1000=.02;10000=.021;20000=.022;50000=.023;100000=.024})
        $this.ratesTable.add(24,[ordered]@{1000=.03;10000=.031;20000=.032;50000=.033;100000=.034})
        $this.ratesTable.add(36,[ordered]@{1000=.04;10000=.041;20000=.042;50000=.043;100000=.044})
        $this.ratesTable.add(48,[ordered]@{1000=.05;10000=.051;20000=.052;50000=.053;100000=.054})
        $this.ratesTable.add(60,[ordered]@{1000=.06;10000=.061;20000=.062;50000=.063;100000=.064})
    }

    [double] GetRate([int]$term, [int] $deposit)
    {
        $relevantMin = 0
        $found = $false
        $mins = $this.ratesTable.$term

        if ($mins)
        {

            ForEach ($min in $mins.GetEnumerator())
            {
                if ($deposit -gt $min.Name)
                {
                    $relevantMin = $min.Name
                    $found = $true
                }
                else
                {
                    break
                }
            }
        }

        if ($found)
        {
            return [double](($this.ratesTable.$term).$relevantMin)
        }
        else
        {
            return [double](-1)
        }
    }
}

cls

$rate = [Rates]::new()

#example - valid term and deposit
$rate.GetRate(36,32000)

#example - valid term and deposit
$rate.GetRate(12,24000)

#example - valid term and invalid deposit
$rate.GetRate(36,500)

#example - invalid term and valid deposit
$rate.GetRate(72,16000)

#example - valid term and valid deposit
$rate.GetRate(60,10000000)

Output
0.042
0.022
-1
-1
0.064


text:
Q: How can i add some custom text to Cart Page? Right when we click the cart icon we are taken to cart page where all product or products added to cart are shown.
On this page I want to add some custom text and icons below the cart summary by removing Estimated Shipping Tax and placing my text instead of Estimated Shipping Tax.
Please just tell where I can add these changes ?

A: Magento has something called template path hints. Template path hints are little tags which would lie on top of your shop frontend. These little tags enable you to view where exactly the code of a specific element is stored within your file structure.
To activate template path hints:

*

*Log into the magento back-end admin

*Go to System -> Configuration in the main menu

*Go to Developer on the bottom left under ADVANCED

*Switch to the store view on the top left to your current website or
store view.

*Under the Debug tab of the same Developer config page you will see a
new option appear that will allow you to turn on/off template path
hints.

Source

A: To remove Estimated Shipping
In File
app/design/frontend/[YOUR THEME]/[YOUR PACKAGE]/template/checkout/cart.phtml

Comment out below code
<?php //if (!$this->getIsVirtual()): echo $this->getChildHtml('shipping');
        endif;
        ?>

or
In file
app/design/frontend/[YOUR THEME]/[YOUR PACKAGE]/layout/local.xml

add below code
<checkout_cart_index>
        <reference name="content">
            <remove name="checkout.cart.shipping" />
        </reference>
    </checkout_cart_index>

To Add custom cms static block at the same location as of shipping block
Create a CMS Static block and add below code in file app/design/frontend/[YOUR THEME]/[YOUR PACKAGE]/template/checkout/cart.phtml just before closing div class="cart-forms"
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('your_static_block_id')->toHtml(); ?>

A: In Magento CE 1.9.2.1 the Estimated Shipping Tax is loaded in the following template file.
[your magento install dir]/app/design/frontend/YOURPACKAGE/YOURTHEME/template/checkout/cart.phtml

If your theme does not contain this file then you can copy it from the
  /base/default/ theme and add it to your own theme.

Open this file and look for the following line of code
<?php if (!$this->getIsVirtual()): echo $this->getChildHtml('shipping'); endif; ?>

replace this line with the following lines of code
<!-- <?php if (!$this->getIsVirtual()): echo $this->getChildHtml('shipping'); endif; ?> -->
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block_identifier')->toHtml(); ?>

The first line comments the Estimated Shipping Tax preventing it from rendering. So it will no longer be displayed. The second line will insert a CMS Static block to the cart page with identifier block_identifier, but only if this static block is active.
In your Magento Admin Panel go to CMS > Static Block and click on the Add New Block button.

*

*Fill in your new block title

*Fill in your new block identifier (this is important and should match the identifier that you have used in the cart.phtml file)

*Choose the proper store view(s)

*Enable the block

*Add the code for the custom text and icons that you want to display

*Save the block

Now refresh all cache and go to your cart page. The Estimated Shipping Tax block should be replaced by your new text and icons.


text:
Q: Add custom properties to ABP UserFriendlyException I am using aspnetboilerplate and I want to add additional data while throwing UserFriendlyException. ex. ErrorReferenceNumber
I have created my own exception class that inherits UserFriendlyException (also tried AbpException and Exception) then I added my custom properties.
but I am unable to get the new custom properties available with the response. after investigation, I found that I have to replace IExceptionToErrorInfoConverter with my own implementation.
I did but still not working so I want to know how can I override the configuration and force it to run my custom implementation? or I'm missing something?
Code
public class BusinessException : AbpException, IHasLogSeverity, IHasErrorCode
    {
        public string Details { get; private set; }

        public int Code { get; set; }

        public string ReferenceNumber { get; set; }

        public string MessageArabic { get; set; }

        public LogSeverity Severity { get; set; }

        public BusinessException()
        {
            Severity = LogSeverity.Warn;
        }

        public BusinessException(string message)
            : base(message)
        {
            Severity = LogSeverity.Warn;
        }

        public BusinessException(string message, LogSeverity severity)
            : base(message)
        {
            Severity = severity;
        }

        public BusinessException(int code, string message)
            : this(message)
        {
            Code = code;
        }

        public BusinessException(string message, string details)
            : this(message)
        {
            Details = details;
        }

        public BusinessException(int code, string message, string details)
            : this(message, details)
        {
            Code = code;
        }

        public BusinessException(int code, string referenceNumber, string message, string messageArabic)
            : this(code, message)
        {
            ReferenceNumber = referenceNumber;
            MessageArabic = messageArabic;
        }

        public BusinessException(int code, string referenceNumber, string message, string messageArabic, string details)
            : this(code, message, details)
        {
            ReferenceNumber = referenceNumber;
            MessageArabic = messageArabic;
        }

        public BusinessException(string message, Exception innerException)
            : base(message, innerException)
        {
            Severity = LogSeverity.Warn;
        }

        public BusinessException(string message, string details, Exception innerException)
            : this(message, innerException)
        {
            Details = details;
        }
    }

public class MyErrorInfoConverter : IExceptionToErrorInfoConverter
    {
        public IExceptionToErrorInfoConverter Next { set; private get; }

        public ErrorInfo Convert(Exception exception)
        {
             return new MyErrorInfo(5000,"ABC100022545", "My SpecificMessage 1", "My Specific Message 2");

        }
    }

In PreInitialize for the Core Project, I added
Configuration.ReplaceService<IExceptionToErrorInfoConverter, MyErrorInfoConverter>(Abp.Dependency.DependencyLifeStyle.Transient);

My application still not able to use the customized class and it throws "An internal error occurred during your request!" exception message. What am I missing?


text:
Q: Android Notification Action to Start service, intent extra not included I have a notification that has two actions, Accept and Decline, and the PendingIntent that start a service, RequestUpdaterService. I put extras into the Intent that the PendingIntent gets made from (via PendingIntent#getService). The problem is that when the service is started, the extras aren't in the intent that is passed into Service#onStartCommand.
Notification issuer:
NotificationCompat.Builder n = new NotificationCompat.Builder(context)
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.logo_small)
                .setContentTitle(notification.getText())
                .setContentText(context.getString(R.string.app_name))
                .setContentIntent(getOpenAppPendingIntent())
                .setOngoing(false)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(text));

Intent actionAccept = new Intent(context, UpdateRequestUpdater.class);
actionAccept.putExtra(KeysAndCodes.UPDATE_REQUEST_ID, notificationRequestId);
actionAccept.putExtra(KeysAndCodes.UPDATE_REQUEST_NOTIFICATION_ID, notificationId);
actionAccept.setAction(KeysAndCodes.UPDATE_REQUEST_UPDATER_ACCEPT);

PendingIntent acceptPendingIntent = PendingIntent.getService(context, 0, actionAccept, 0);

Intent actionDecline = new Intent(context, RequestUpdater.class);

actionDecline.putExtra(KeysAndCodes.UPDATE_REQUEST_ID, notificationRequestId);

actionDecline.putExtra(KeysAndCodes.UPDATE_REQUEST_NOTIFICATION_ID, notificationId);
actionDecline.setAction(KeysAndCodes.UPDATE_REQUEST_UPDATER_DECLINE);

PendingIntent declinePendingIntent = PendingIntent.getService(context, 0, actionDecline, 0);

n.addAction(R.drawable.ic_action_accept, getString(R.string.accept_request), acceptPendingIntent);
n.addAction(R.drawable.ic_action_cancel, getString(R.string.decline_request), declinePendingIntent);

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notification.getId(), n.build());

RequestUpdaterService.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Integer requestId = intent.getIntExtra(KeysAndCodes.UPDATE_REQUEST_ID, 0);
    Integer notificationId = intent.getIntExtra(KeysAndCodes.UPDATE_REQUEST_NOTIFICATION_ID, 0);
...
}

Whenever the RequestUpdaterService is started the requestId and notificationId are always 0. What am I doing wrong?

A: Try changing this line:
PendingIntent acceptPendingIntent = PendingIntent.getService(context, 0, actionAccept, 0);

To this:
PendingIntent acceptPendingIntent = PendingIntent.getService(context, 0, actionAccept, PendingIntent.FLAG_UPDATE_CURRENT);


text:
Q: How to uninstall and/or manage multiple versions of python in OS X 10.10.3 I have installed the Python IDE Spyder. For me it's a great development environment.
Some how in this process I have managed to install three versions of Python on my system.These can be located as following:

*

*Version 2.7.6 from the OS X Terminal;

*Version 2.7.8 from the Spyder Console; and

*Version 2.7.9rc1 from an IDL window.

The problem I have is (I think) that the multiple versions are preventing Spyder from working correctly.
So how do I confirm that 2.7.6 is the latest version supported by Apple and is there a simple way ('silver bullet') to remove other versions from my system.
I hope this is the correct forum for this question. If not I would appreciate suggestions where I could go for help.

I want to keep my life simple and to develop python software in the Spyder IDE. I am not an OS X guru and I really don't want to get into a heavy duty command line action. To that end I just want to delete/uninstall the 'unofficial versions' of Python. Surely there must be an easy way to do this - perhaps 'pip uninstall Python-2.7.9rc1' or some such. The problem is that I am hesitant to try this due to the fear that it will crash my system.
Help on this would be greatly appreciated.

A: (Spyder dev here) There is no simple way to do what you ask for, at least for the Python version that comes with Spyder.
I imagine you downloaded and installed our DMG package. That package comes with its own Python version as part of the application (along with several important scientific packages), so it can't be removed because that would imply to remove Spyder itself :-)
I don't know how you installed IDL(E?), so I can't advise you on how to remove it.


text:
Q: Dart - Parse Nested Json Arrays Getting errors after trying to convert nested JSON data using dart's factory concept.
Here I have two classes to handle the json data, but still getting this error:

Exception has occurred.
  _TypeError (type 'FormatException' is not a subtype of type 'Map')

Here is the code:

    class BodyResponse {
      final Map<String, dynamic> message;
      BodyResponse({
        this.message
      });
      factory BodyResponse.fromJson(Map<String, dynamic> json) {
        return BodyResponse(message: json['message']);
      }
    }

    class ErrorResponse {
      final BodyResponse body;
      final int status;
      final String contentType;
      final bool success;

      ErrorResponse({
        this.body, this.status, this.contentType, this.success
      });

      factory ErrorResponse.fromJson(Map<String, dynamic> json) {
        return ErrorResponse(
          body: BodyResponse.fromJson(json['body']),
          status: json['status'],
          contentType: json['content_type'],
          success: json['success']
        );
      }
    }

    ErrorResponse errors = ErrorResponse.fromJson("""
      {
        "body": {
          "message": "Some one has already taken this username(fooBar), please try again with a new username."
        },
        "status": 500,
        "content_type": "application\/json",
        "success": false
      }
    """);

    print(errors);

What could go wrong here?

A: Modified most of your code here. Hope that this is what you tried to achieve.
import 'dart:convert';

class BodyResponse {
  final String message;
  BodyResponse({this.message});

  BodyResponse.fromJson(Map<String, dynamic> json):
    message = json['message'];

  factory BodyResponse.fromString(String encodedJson) {
    return BodyResponse.fromJson(json.decode(encodedJson));
  }

  Map<String, dynamic> toJson() => {
    "message": message,
  };

  String toString() => json.encode(this.toJson());

}

class ErrorResponse {
  final BodyResponse body;
  final int status;
  final String contentType;
  final bool success;

  ErrorResponse({this.body, this.status, this.contentType, this.success});

  ErrorResponse.fromJson(Map<String, dynamic> json):
    body = BodyResponse.fromJson(json['body']),
    status = json['status'],
    contentType = json['content_type'],
    success = json['success'];

  factory ErrorResponse.fromString(String encodedJson) {
    return ErrorResponse.fromJson(json.decode(encodedJson));
  }

  Map<String, dynamic> toJson() => {
    "body": body.toJson(),
    "status": status,
    "contentType": contentType,
    "success": success,
  };

  String toString() => json.encode(this.toJson());

}

void main() {
  ErrorResponse errors = ErrorResponse.fromString("""
      {
        "body": {
          "message": "Some one has already taken this username(fooBar), please try again with a new username."
        },
        "status": 500,
        "content_type": "application\/json",
        "success": false
      }
    """);
  print(errors);
}

Let me know if this helped.


text:
Q: Geometric interpretation of Divergence of $\vec{f} = \frac{1}{r^2} \hat{r}$ I know that the mathematics tells me that the divergence is zero for the below vector field:
$\vec{f} = \frac{1}{r^2} \hat{r}$
But I am more interested in the geometric intuition of it. Here is what I am looking at. The vector length is decreasing as I am increasing the radii of the sphere around origin in 3D space.  Now divergence is defined as $\partial {v_x}/\partial x +\partial {v_y}/\partial y+\partial {v_z}/\partial z$ in cartesian coordinates.
Now lets think about a point other than the origin. Lets take $\partial {v_x}/\partial x$. Now as the vector is decreasing in length as we are increasing the radii, this slope must be less than zero, i.e., $\partial {v_x}/\partial x < 0$ as the value is decreasing as we are increasing the $x$.  The same logic can be applied to other dimensions, i.e.,
$\partial {v_y}/\partial y < 0$
$\partial {v_z}/\partial z < 0$
Now given all these inequalities, how can $\partial {v_x}/\partial x +\partial {v_y}/\partial y+\partial {v_z}/\partial z=0 $ ?

A: Note that we have
$$\frac{\hat r}{r^2}=\frac{\vec r}{r^3}$$
So, the Cartesian components are $\displaystyle \frac{x}{(x^2+y^2+z^2)^{3/2}}$, $\displaystyle \frac{y}{(x^2+y^2+z^2)^{3/2}}$, and $\displaystyle \frac{z}{(x^2+y^2+z^2)^{3/2}}$.
Therefore, the partial derivative with respect to the $i$'th Cartesian coordinate  of the $i$'th component of $\displaystyle \frac{\hat r}{r^2}$ is
$$\frac{\partial }{\partial x_i}\frac{\hat x_i\cdot \vec r}{r^3}=\frac{r^2-3x_i^2 }{r^5}\tag1$$
for $r\ne 0$.  Clearly these partial derivatives are not negative for all $(x,y,z)$.
However, summing $(1)$ over $i$ reveals for $r\ne0$
$$\nabla\cdot \left(\frac{\vec r}{r^3}\right)=\frac1{r^5}\sum_{j=1}^3 ( r^2-3x_i^2)=0$$
as expected!

A: Actually, it's $\vec{\nabla}\cdot\vec{f}=4\pi\delta^{(3)}(\vec{r})$. The geometric-cum-physical intuition is that$$\int_{r\le R}\vec{\nabla}\cdot\vec{f}\mathrm{d}^3\vec{x}=\int_{r=R}\vec{f}\cdot\mathrm{d}\vec{S}$$equates a "charge" enclosed within a ball to a field's surface integral at its edge. Here the charge density $\vec{\nabla}\cdot\vec{f}$ is $0$ except at $r=0$, because of a point charge $4\pi$. Meanwhile, since $f=1/R^2$ at the surface $r=R$ of area $4\pi R^2$, the surface integral on the right-hand side is the enclosed charge of density $4\pi\delta^{(3)}(\vec{r})$.


text:
Q: Automating the installation using SSH I am running a bash script from a remote host to run a binary file which installs 64 bit JDK 6 update 29 on multiple VMs across the Environment.
It is installing the file but, at the last line i have to hit a enter to complete the installation. I want to fully automate the script where i do not have to hit the enter at the last line. This is what i am using
ssh ${V_TIERS}@${V_TIERS} 'cd JDK; sh jdk-6u29-solaris-sparcv9.sh'

It updates as desired, but during install i have to hit enter to continue and complete the installation. Can anybody please help to fully automate the update process.

A: Try
ssh ${V_TIERS}@${V_TIERS} 'cd JDK; echo | sh jdk-6u29-solaris-sparcv9.sh'


text:
Q: SharePoint (ASP.NET) Application works fine until morning, only an IISRESET fixes problem A colleague has developed a SharePoint web-part application (which was developed in VS2005), and deployed on MOSS 2007. We use an .ASCX file for deployment.
This application works fine all day, but something happens overnight whereby we need to do an IISRESET every-morning before it starts working again. (It is basically driving us nuts!)
The error we get is:

the type specified in the TypeName
  property of ObjectDataSource
  'ObjectDataSource2' could not be found

The relevant 'ObjectDataSource2' in the ascx file has this code:
<asp:ObjectDataSource ID="ObjectDataSource2" runat="server" InsertMethod="Insert"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetDataByEnquiryType"
TypeName="crmDatasetTableAdapters.Lookup_tableTableAdapter">
<InsertParameters>
    <asp:Parameter Name="Domain" Type="String" />
    <asp:Parameter Name="code" Type="String" />
    <asp:Parameter Name="meaning" Type="String" />
    <asp:Parameter Name="enabled" Type="Int32" />
    <asp:Parameter Name="Link" Type="String" />
</InsertParameters>
</asp:ObjectDataSource>

The dropdownlist using the above datasource is:
<asp:DropDownList ID="ddlEnquiryType" runat="server" AutoPostBack="True" DataSourceID="ObjectDataSource2"
DataTextField="meaning" DataValueField="meaning" Width="256px">

The TypeName entry is referring to a dataset that was created (.xsd file).
We have a web.config connection string that looks like:
<add name="crmConnectionString" connectionString="Data Source=myservername;Initial Catalog=CRM;User Id=xyz123;Password=***************;Integrated Security=False;Connect Timeout=30;" providerName="System.Data.SqlClient" />

As I mentioned, this application works fine in VS2005, VS2008, and also when within SharePoint. - Until overnight, and the sharePoint server 'loses' whatever it needs regarding 'ObjectDataSource2'.
Can anyone shed light on this puzzle? If you need more information, then let me know.
Thanks in advance!

A: We saw similar behavior a few years ago. It had to do with how the .NET runtime loads assemblies after it gets unloaded from memory (after a period of non-use, which sounds like what could happen with your application). This can be related to not using the fully qualified name of the assembly. If you have a SafeCode entry for a business layer DLL you are using, make sure it's fully qualified.
DLLName, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
as opposed to
DLLName
Also verify references in ASCX are fully qualified.
Interested if that's the issue. Took us FOREVER to resolve that one. In the interim to work around the problem we created a command line application to ping the server every 5 minutes so users did not see an error in the morning in case what is outlined above does not resolve.

A: Can you check the 12 hive logs,  EventViewer to see any issues pertaining to the web application.
if it is sure that this is caused by the new application i suggest you write a custom log to find if there are any issues

A: Are you seeing a persistent error where IIS shuts down the web app because of the persistent error, or just the single error and it doesn't work again?
I'd almost wonder if there's a nightly backup (or some other operation) on that data source that's interrupting your connection and it's simply failing after the connection gets interrupted.
Is the error time fairly consistent in your logs from night to night?


text:
Q: Extended large deviation principle on product space My question is how to prove the large deviation property in a product space if at each coordinate there is a large deviation property. I will explain what I mean in detail as below:
Let me start with some notation and definition I use:
Consider metric space $(\mathcal{S},d)$, and also a probability measure $P$ on it w.r.t the Borel sigma-algebra. I mean a sequence of random object $X_n$ taking value in $\mathcal{S}$ satisfies a large deviation if there exists a lower-semicontinuous rate function $I:\mathcal{S}\rightarrow \mathbb{R}_+$, and a positive sequence $a_n\rightarrow\infty$(called speed) such that for any open set $G$ and closed set $F$,
\begin{equation}
-\inf_{x\in G} I(x) \leq \liminf_{n\rightarrow\infty}\frac{\log P(X_n\in G)}{a_n} \text{ and } \limsup_{n\rightarrow\infty}\frac{\log P(X_n\in F)}{a_n} \leq -\inf_{x\in F} I(x)
\end{equation}
This is the most common large deviation principle on most textbooks, though most likely in a more general setting. To compare with some other weaker large deviation statement, I would call the above a full LDP. Below is one of the weaker large deviation, and I will call it extended LDP: $X_n$ taking value in $\mathcal{S}$ satisfies the extended large deviation if there exists a lower-semicontinuous function $I:\mathcal{S}\rightarrow \mathbb{R}_+$, and a positive sequence $a_n\rightarrow\infty$ such that for any open set $G$ and closed set $F$,
\begin{equation}
-\inf_{x\in G} I(x) \leq \liminf_{n\rightarrow\infty}\frac{\log P(X_n\in G)}{a_n} \text{ and } \limsup_{n\rightarrow\infty}\frac{\log P(X_n\in F)}{a_n} \leq -\lim_{\delta\downarrow 0}\inf_{x\in F_\delta} I(x)
\end{equation}
where $F_\delta = \{x\in\mathcal{S}: d(x,F)\leq \delta\}$.
Now if we have $d$ spaces $\mathcal{S}^{(i)}$  and on each space we have a sequence $X^{(i)}_n$ that satisfies extended LDP with rate function $I^{(i)}$ and they share the same speed $a_n$'s. Also assume $X^{(i)}_n$'s and $X^{(j)}_m$'s are independent. My question is, does the random object $X_n = (X^{(1)}_n,\cdots,X^{(d)}_n)$ on  $\prod_{i=1}^d \mathcal{S}^{(i)}$ endowed with the product topology satisfies an extended LDP?
My thought and findings:
If the large deviation principle w.r.t $X^{(i)}_n$ on each coordinate is a full LDP and the rate function is good (the level sets of $I^{(i)}$ are compact), then there is a corresponding result that could be found as theorem 4.14 on https://link.springer.com/book/10.1007/978-3-540-39889-9. In that proof, the goodness of the rate functions play an important role.
Now my situations is: on each coordinate,  $X^{(i)}_n$ only satisfies an extended LDP which is weaker than the full LDP, and rate function is not good (since if it is good, than extended LDP becomes full LDP automatically). If the result is not true in general, what could be a counterexample.
Many thanks in advance!


text:
Q: ASP.NET Conflict Detection in Admin System I'm trying to implement conflict detection in an admin system i.e. Alice is editing a page; Bob edits the same page and saves before Alice. To prevent Alice overwriting Bob's changes, I need to make her aware that a change has occurred, and the exact fields she would be overwriting and what Bob had saved them as. (This is all using SQL).
I've tried storing the object concerned on Page_Load, but this disappears when the page is posted back. Is there a way of persisting the object without having to write out nasty serialization code? Or indeed a better way of doing it.

A: If the object isn't very complicated, just mark it as [Serializable] and shove it into ViewState or SessionState, then it will survive postbacks (Although if you put it into ViewState, you need to put it back into viewstate after a postback, before the page is rendered again).
Another option, if the object is a bit complicated, or you don't really want to save that data there is ensure the table in question has fields along the lines of LastUpdated and LastUpdatedBy, and ensure those are written to whenever it is updated. Then what you can do, is when rendering Alice's page, write out the LastUpdated date into a hidden field (or viewstate).
Then upon an attempted save, compare the record in the database's LastUpdated to the one that was attached when the page was rendered. If they are the same, go ahead and perform your update. If they're different, you have the values Alice wanted to enter, by way of you having them from postback, and you have Bob's changes, from doing the date check. You can then display whatever UI you want from that.
EDIT: Some other options if you want to show the original values Alice had when loading the page.
The first, lowest tech one would be to have a HiddenField corresponding to each editable field. You load those at the same time as you're populating the controls, and then use that to show the original values.
Another option, if you're using ObjectDataSource would be to use it's ConflictDetection feature:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.conflictdetection.aspx
Between this and the OldValuesParameterFormatString property, the control will then pass the original values to the Update function, as well as the updated values.


text: Q: How do I enable scrolling in the integrated terminal in Visual Studio Code? I am running Visual Studio Code 1.41.1 on Manjaro. I can't scroll in the integrated terminal with the scroll wheel on my mouse nor using two fingers on my trackpad. I have to navigate my cursor to the scroll bar on the right side of the terminal to be able to scroll at all. How do I enable scrolling with my mouse's scroll wheel or my trackpad?


text:
Q: Apache authentication with kerberos, file and ldap i try to configure the apache for authentication to use at first kerberos, second file and at last ldap but it doesn't work.
Kerberos with ldap fallback works fine. Only file-auth with ldap work too. But Kerberos with ldap and file fallback doesn't work.
Kerberos/Ldap:
<Location "/">
Require ldap-group <MY-DLAP-GROUP>
Order allow,deny
Allow from all
AuthType Kerberos
AuthName "test"
AuthzLDAPAuthoritative on
AuthLDAPDereferenceAliases never
AuthLDAPURL "ldaps://<MY-LDAPS-URL>?userPrincipalName?sub?(objectCategory=Person)"
AuthLDAPBindDN "<MY-LDAP-USER>"
AuthLDAPBindPassword <MY-LDAP-USER-PASSWORD>
</Location>
KrbMethodNegotiate on
KrbMethodK5Passwd on
KrbAuthoritative on
KrbAuthRealms <MY-REALM>
Krb5Keytab <MY-KERBEROS-KEYTAB>
KrbVerifyKDC on
KrbServiceName <MY-KERBEROS-SERVICE-NAME>
KrbSaveCredentials off

File/Ldap:
<Location "/">
Require ldap-group <MY-DLAP-GROUP>
Order allow,deny
Allow from all
AuthType Basic
AuthName "test"
AuthBasicProvider file ldap
AuthUserFile /etc/httpd/.htpasswd
AuthzLDAPAuthoritative on
AuthLDAPDereferenceAliases never
AuthLDAPURL "ldaps://<MY-LDAPS-URL>?userPrincipalName?sub?(objectCategory=Person)"
AuthLDAPBindDN "<MY-LDAP-USER>"
AuthLDAPBindPassword <MY-LDAP-USER-PASSWORD>
</Location>
KrbMethodNegotiate on
KrbMethodK5Passwd on
KrbAuthoritative on
KrbAuthRealms <MY-REALM>
Krb5Keytab <MY-KERBEROS-KEYTAB>
KrbVerifyKDC on
KrbServiceName <MY-KERBEROS-SERVICE-NAME>
KrbSaveCredentials off

Any Ideas?


text:
Q: llvm - Pass arguments to a pass I need to tell the pass to look out for a specific function in the file. And I want to specify which function to look out for 'on the go' i.e when I run the pass. Any idea how I can do that? It's sort of like passing arguments to a function in theory.

A: Add a command line option using cl::opt<string> and set it when running your pass.
Alternatively, if you are producing an IR from C or C++ using clang, you can utilize __attribute((__annotate__(("foo")))) to mark functions you are interested in.


text:
Q: Sometimes I get a mistake in the compiler "Unable to create initial connections of pool." I have an application written in Spring, which works generally. However, there is such a problem that sometimes when compiling it throws me a mistake https://pastebin.com/kUjDFq16
It is a part of
  2017-10-03 22:24:10.195  WARN 300 --- [ost-startStop-1] o.a.tomcat.jdbc.pool.PooledConnection    : Not loading a JDBC driver as driverClassName property is null.
2017-10-03 22:24:10.240 ERROR 300 --- [ost-startStop-1] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.

java.sql.SQLException: The url cannot be null
    at java.sql.DriverManager.getConnection(DriverManager.java:649) ~[na:1.8.0_144]

Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at ...

This is the project https://github.com/JonkiPro/REST-Web-Services
This application works without any problems, but during some compilation it ejects this error during compilation.Sometimes I have to compile the application several times so that the error doesn't jump out, and sometimes I have to turn off the IDE and restart it.
EDIT: Now it doesn't compile at all and still makes a mistake.


text:
Q: trigger on the buttons in the slider slick I need to click on the custom arrows, what would the slider work. I know that there is a trigger in JQuery or something, but what can i do in react ?
You can see api slick-slider on this link https://react-slick.neostack.com/docs/example/custom-arrows

..................................................................................................................................................................
import React, { Component } from "react";
import Slider from "react-slick";

function SampleNextArrow(props) {
  const { className, style, onClick } = props;
  return (

  );
}

function SamplePrevArrow(props) {
  const { className, style, onClick } = props;
  return (

  );
}

export default class CustomArrows extends Component {
  render() {
    const settings = {
      dots: true,
      infinite: true,
      slidesToShow: 3,
      slidesToScroll: 1,
      nextArrow: <SampleNextArrow />,
      prevArrow: <SamplePrevArrow />
    };
    return (

Custom Arrows

        // CLICK HERE

arrowsarrows

        <Slider {...settings}>

1

2

3

4

5

6

        </Slider>

    );
  }
}

A: I found this solution
document.getElementsByClassName('slick-next')[0].click()

but I do not know if it is good to use in react


text:
Q: How to create managed object in unmanaged C++ while wrapping it for JNA between Java and C#? I am trying to make a callback interface between C# and Java using JNA.
C#  <--CLI-->  Visual C++ 2010  <--JNA-->  Java
Between Java and C++ I am using unmanaged structures to get callback functionality. In C++ I am trying to wrap structure, that has callback pointers, into managed object.
Between Java and C++ everything works until I'm trying to use gcroot for managed object generation in unmanaged code.
UPDATE it even fails without gcroot. Just with "Logger^ logger = gcnew Logger(logStruct);"
My current solution is as follows:
Java
LoggerStruct.java
package jnatest;

import com.sun.jna.Callback;
import com.sun.jna.Structure;
import java.util.logging.Logger;

public class LoggerStruct extends Structure {
    private Logger logger;

    public interface GetLevelCallback extends Callback {
        int callback();
    }

    public GetLevelCallback getLevel;

    public LoggerStruct(Logger log) {
        super();
        this.log = log;

        getLevel = new GetLevelCallback() {
            public int callback() {
                return logger.getLevel().intValue();
            }
        }

        setFieldOrder(new String[] {"getLevel"});
    }
}

ITestLib.java
package jnatest;

import com.sun.jna.Library;
import com.sun.jna.Native;

public interface ITestLib extends Library {
    ITestLib INSTANCE = (ITestLib) Native.loadLibrary("JNATestC", ITestLib.class);
    int callbackTest(LoggerStruct logStruct);
}

Main.java
package jnatest;

import com.sun.jna.NativeLibrary;
import java.util.logging.Logger;
import java.util.logging.FileHandler;

public class MainClass {
    public static void main(String[] args) throws Exception  {
        NativeLibrary.addSearchPath("JNATestC", "C:\\JNATest");

        Logger log = Logger.getLogger("Test");
        FileHandler fileTxt = new FileHandler("Logging.txt");
        log.addHandler(fileTxt);

        LoggerStruct logStruct = new LoggerStruct(log);

        ITestLib.INSTANCE.callbackTest(logStruct);
    }
}

C++
JNATestC.h
#pragma once

extern "C" {
    struct LoggerStruct {
        int (*getLevel)();
    }
    __declspec(dllexport) void callbackTest(LoggerStruct * logStruct);
}

namespace JnaWrapperTypes {
    public ref class Logger { // "public ref" because I have to use it in C# as well
        private:
            LoggerStruct * logStruct;
        public:
            Logger(LoggerStruct * logStruct);
            ~Logger() {}
            int getLevel();
    };
}

JNATestC.cpp
#include "stdafx.h"
#include <vcclr.h>
#include "JNATestC.h"

namespace JnaWrapperTypes {
    Logger::Logger(LoggerStruct * logStruct) {
        this->logStruct = logStruct;
    }
    Logger::getLevel() {
        return logStruct->getLevel();
    }
}

using namespace JnaWrapperTypes;
using namespace StaticCSharpNamespace; // Just an example. Not existing C# lib.

extern "C" {
    __declspec(dllexport) void callbackTest(LoggerStruct * logStruct) {
        int level = logStruct->getLevel();

        gcroot<Logger^> logger = gcnew Logger(logStruct); // IF I ADD "gcroot" FOR "Logger" THEN WHOLE INVOKE FAILS
        level = logger->getLevel();

        StaticCSharpClass::staticMethod(logger); // I want to pass Managed object to C# later

        gcroot<System::String^> str = gcnew System::String(""); // This doesn't generate error
    }
}

I wrote these on the fly. I hope these validate as well.
What am I doing wrong? For example if I use...

gcroot<System::String^> str = gcnew System::String("");

...everything works just fine.
Is there another way to pass managed object to C#?
Log for this error LOG
UPDATE
It seems that anykind of my own Class usage will head me to failure.
UPDATE
Anykind of my own Managed object or function use heads me to failure.
UPDATE
StaticCSharpClass::staticMethod(); fails as well. Looks like all operations related to Managed objects fail.
UPDATE
If I invoke the same method from .NET, everything works fine.
just to make this problem more findable
Internal Error (0xe0434352)

A: Should have googled for error "Internal Error (0xe0434352)".
http://jira.talendforge.org/browse/TDI-19427
It leads to point that I have to register the dll for GAC (Global Assembly Cache), because Java searches only GAC and Application Base directories for dll. And because Java.exe paths aren't configurable.
== Solution ==
Use post build event to register assembly for GAC:
gacutil /i "$(TargetPath)"

Great monologue! =)