text:
Q: How do I concatenate an element of a string array to a string array? #include <stdio.h>
#include <string.h>
int main(){
char a[7]= "car";
char b[7]="yyoug";
strcat(a,b[2]);
puts(a);
  return 0;
}

This won't compile. It says "passing argument 2 of 'strcat' makes pointer from integer without a cast." I haven't been taught the use of pointers.

A: b[2] is of char type but strcat expects its both arguments are of char * type.
Use strncat instead. It will append only one byte, i.e. b[2] to the first string if the third argument passed is 1
strncat(a, &b[2], 1);

A: If you just want to use strncat because you want to learn how it works, then @hacks example is completly perfect. But if you just want to concat on character to a you can also use
a[3] = b[2];
But please keep in mind, either solution only works, if the the destination array, in your case a is large enough.

A: Without using malloc this might help explain what's going in
#include <assert.h>
#include <stdio.h>
#include <string.h>
int main(){
  //positions  0    1    2    3
  //"car" == ['c', 'a', 'r', '\0']
  char a[7] = "car";
  char b[7] = "yyoug";

  //strlen("car") == 3;
  //"car"[3]      == ['\0'];

  a[strlen(a)]    = b[2];
  assert(a[3] == 'o');

  a[strlen(a) + 1] = '\0';
  assert(a[4] == '\0');
  puts(a);
    return 0;
}


text:
Q: Use nginx as proxy with docker I currently try to use nginx as a proxy for elasticsearch engine, all with docker.
My run command for elasticsearch is the following :
docker run --name elasticsearch_5.2.1 \
-d \
elasticsearch:5.2.1

The one for nginx :
docker run --name nginx_1.11.10 \
-p 8200:80 \
-l elasticsearch_5.2.1:elasticsearch \
-v /my.conf:/etc/nginx/nginx.conf:ro \
-d \
nginx:1.11.10

And my nginx config is :
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    upstream elasticsearch_proxy {
        server elasticsearch:9200;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://elasticsearch_proxy;
            proxy_http_version 1.1;
            proxy_set_header Connection "Keep-Alive";
            proxy_set_header Proxy-Connection "Keep-Alive";
        }
    }
}

But, when nginx start, I have this error :
2017/03/01 23:45:47 [emerg] 1#1: host not found in upstream "elasticsearch:9200" in /etc/nginx/nginx.conf:15
nginx: [emerg] host not found in upstream "elasticsearch:9200" in /etc/nginx/nginx.conf:15

I understand that nginx can't found elasticsearch with his alias. But I can't find the problem.
Is there someone who already has this problem ?
Thank you.

A: You need to create a user network.
docker create network my_app

And then run both containers on that network.
docker run --name elasticsearch_5.2.1 \
-d --network my_app \
elasticsearch:5.2.1

docker run --name nginx_1.11.10 \
-p 8200:80 \
-l elasticsearch_5.2.1:elasticsearch \
--network my_app \
-v /my.conf:/etc/nginx/nginx.conf:ro \
-d \
nginx:1.11.10

Then you should be able to resolve names properly as if they were DNS names.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I need a 5 digit string which is incremented automatic (A0001 - Z9999) in SQL Server I want auto-incremented string to generate project code which will start from A0001 - A9999 then it should start from B0001 accordingly till Z9999.

A: Here's what I'd do instead:
create table T (
    _RealID int IDENTITY(1,1) not null,
    ID as
         CHAR(ASCII('A') + _RealID / 10000) +
         RIGHT('0000' + CONVERT(varchar(4),_RealID % 10000),4),
    OtherColumns varchar(10) not null
)

My convention is that columns that start with a _ are not intended to be used by users/applications. If it's important enough to hide, I'll instead create a _T table with the above definition and then a T view which only selects the columns without the _ prefix. users/applications are then only given access to the view.

A: CREATE TABLE StringId (
    [id] INT NOT NULL IDENTITY(0,1) CONSTRAINT [PK_StringId] PRIMARY KEY CLUSTERED,
    CONSTRAINT CK_StringId_id CHECK ([id] >= 0 AND [id] <= 259973), -- 26 * 9999-1
    [StringId] as CHAR(ASCII('A') + [id] / 9999) + RIGHT(CAST( 10000 + [id] % 9999 + 1 as varchar(5)),4) PERSISTED NOT NULL,
    TestValue int NULL);

INSERT INTO StringId (TestValue)
    Values (12345),(23456),(34567);

SElECT * FROM [StringId];


text:
Q: Editing a embed message So I've been working on a bot and i have a embed message and i would to make a command that would edit the previous embed
So I have tried
        let msg2 = msg.channel.messages.fetch('mymessageid').then(
      msg2.edit(yellow)
    )

and didn't work out so if you can help me with this

A: You would need to get the embed from the already sent message, edit that embed, then use Message.edit({ embeds: [newEmbed] }).


text:
Q: Getting the path of a image (ActiveX Control) 0
I'm having trouble to get a file path in Excel VBA.
I created a module to get the file path and load it on an image (ActiveX Control)
Get_image()
Dim img_ As String
img_1 = Application.GetOpenFilename(filefilter:="File Type (*.jpg), *.jpg")
Sheet8.Image1.Picture = LoadPicture(img_1)

Get_Local()

here, I would like to make a function to take the path of "Sheet8.Image1.Picture".

The Get_Local() will call later, so when I exit the Get_image() function, the path "img_1" will be lost.
What can I do to get the local of the image again?


text:
Q: Approximation of binomial coefficient using Stirlings formula We have the approximation: $\ln x! \simeq x \ln x - x + \tfrac{1}{2} \ln (2 \pi x)$.
I want to estimate $\ln \binom{N}{r} = \ln\left(\frac{n!}{(N - r)! r!}\right) = \ln(n!) - \ln((N - r)!) - \ln(r!)$. The result I want to get is $$(N - r) \ln(N / (N - r)) + r \ln(N / r).$$
but I don't get that result, I have got $$N \ln N - r \ln r - (N - r) \ln (N - r) + \tfrac{1}{2} \ln (2 \pi N) - \tfrac{1}{2} \ln (2 \pi r) - \tfrac{1}{2} \ln (2 \pi (N - r))$$
How can I proceed from here to get the desired result?
Thanks.

A: You have:
$\begin{align*}
   \ln \binom{N}{r}
     &\sim (N - r) \ln N - (N - r) \ln (N - r) - r \ln r
              + r \ln N
              + \frac{1}{2} \ln (2 \pi N)
              - \frac{1}{2} \ln (2 \pi r)
              - \frac{1}{2} \ln (2 \pi (N -r)) \\
     &=     (N - r) \ln \frac{N}{N - r} + r \ln \frac{N}{r}
               + O(\ln N)
\end{align*}$
Unless $r$ is very near $0$ or $N$, you can disregard the lower-order terms.


text:
Q: Trying to insert input type date into mysql column of type date throws SQL error I have two fields in my form named from date and to date, both have input type date. I am inserting these two fields in my DB with column type date.
My html looks like:
<form class="" action='a.php' method="POST">
From Date:

<input type="date" name="from_date" maxlength=""   id="fromdate" placeholder="" class="input-xlarge">
To Date:

<input type="date" name="to_date" maxlength=""   id="todate" placeholder="" class="input-xlarge">

My php looks like this:
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'ads');

$link = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
  OR die("could not connect");

$from_date= mysqli_real_escape_string($link,$_POST['from_date']);
$from_date = date("Y-m-d", strtotime($from_date));

$to_date= mysqli_real_escape_string($link,$_POST['to_date']);
$to_date= date("Y-m-d", strtotime($to_date));

In my insert statement I am doing this:
$sql = "INSERT INTO airport_data (From_date,To_date) VALUES ('$from_date','$to_date')";

But this throws me this error:

Could not able to execute INSERT INTO table (From_date,To_date) VALUES (2015-05-27,2015-05-15). You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'From_date,To_date) VALUES ( 2015-05-27,2015-05-15) at line 1

I tried to change the date format from the form:
$to_date = date('Y-m-d', strtotime(str_replace('-','/', $to_date)));
$from_date = date('Y-m-d', strtotime(str_replace('-','/', $from_date)));

But this didn't solved the problem neither.
Where is the problem, that I can't insert the dates received from my form into my database table?

A: I would do something like:
$from_date = new DateTime($_POST['from_date']);
$to_date = new DateTime($_POST['to_date']);

// Insert the following into the database
$from_date = mysqli_real_escape_string($link, $from_date->format('Y-m-d'));
$to_date = mysqli_real_escape_string($link, $to_date->format('Y-m-d'));

// If you want those slashes
$from_date = mysqli_real_escape_string($link, $from_date->format('Y/m/d'));
$to_date = mysqli_real_escape_string($link, $to_date->format('Y/m/d'));

And for your query:
$sql = "INSERT INTO airport_data
(From_date, To_date)
VALUES ('".$from_date."','".$to_date."')
";

A simple yet elegant way to output dates the way you want them to.


text:
Q: How to determine if an image is previewable in current browser with Fine-Uploader? The goal is to generate thumbnails/previews server-side only if it cannot be done client-side.
The Fine-Uploader documentation states:

However, you should take care to not blindly return a thumbnailUrl for
  images that are already previewable in modern browsers unless your
  server intends to orient them correctly first.

How does the server know if Fine-Uploader is able to generate the preview client-side or not?

A: There is no way to reliably determine if a specific preview has generated successfully before the file upload request has been sent, as preview generation is an asynchronous process and may complete after the request has been sent. However, you can determine if the current browser has the ability to generate image preview by checking the imagePreviews feature flag. If qq.supportedFeatures.imagePreviews is true, then the current browser is capable of generating client-side image previews. If this flag is false you can set a parameter with all upload requests that instructs your server to return an image preview URL instead. For example, you can setup your params option to do this:
request: {
   params: isBrowserPreviewPossible: qq.supportedFeatures.imagePreviews
}

The isBrowserPreviewPossible param w/ value will be sent with every upload request to your server. This is demonstrated in the live S3 uploader at FineUploader.com.


text:
Q: Clean PCH files in Xcode 6.1.1 I have the same problem reported here:
How to fix PCH error?
But as Product > Clean Build Folder... (with Option key pressed) does not work for me I try to delete the files manually, but in the log file I am not able to see any "SharedPrecompiledHeaders" (Adam's answer), only "PrecompiledHeaders", shall I delete this ones ?
log file :
ProcessPCH /Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Intermediates/PrecompiledHeaders/BlinkyBle-Prefix-hgtaudjsezkfjghkrtslxkdnrhrc/BlinkyBle-Prefix.pch.pch BlinkyBle/BlinkyBle-Prefix.pch normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler

    cd /Users/nullpointer/Documents/bluetooth/NORDIC/iOS-master/BlinkyBle

    export LANG=en_US.US-ASCII

    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"

    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c-header -arch x86_64 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu99 -fobjc-arc -fmodules -fmodules-cache-path=/Users/nullpointer/Library/Developer/Xcode/DerivedData/ModuleCache -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -Wno-trigraphs -fpascal-strings -O0 -Wno-missing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wno-implicit-atomic-properties -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-receiver-is-weak -Wno-arc-repeated-use-of-weak -Wduplicate-method-match -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wundeclared-selector -Wno-deprecated-implementations -DDEBUG=1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk -fexceptions -fasm-blocks -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -g -Wno-sign-conversion -fobjc-abi-version=2 -fobjc-legacy-dispatch -mios-simulator-version-min=6.1 -iquote /Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Intermediates/BlinkyBle.build/Debug-iphonesimulator/BlinkyBle.build/BlinkyBle-generated-files.hmap -I/Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Intermediates/BlinkyBle.build/Debug-iphonesimulator/BlinkyBle.build/BlinkyBle-own-target-headers.hmap -I/Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Intermediates/BlinkyBle.build/Debug-iphonesimulator/BlinkyBle.build/BlinkyBle-all-target-headers.hmap -iquote /Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Intermediates/BlinkyBle.build/Debug-iphonesimulator/BlinkyBle.build/BlinkyBle-project-headers.hmap -I/Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Products/Debug-iphonesimulator/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Intermediates/BlinkyBle.build/Debug-iphonesimulator/BlinkyBle.build/DerivedSources/x86_64 -I/Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Intermediates/BlinkyBle.build/Debug-iphonesimulator/BlinkyBle.build/DerivedSources -F/Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Products/Debug-iphonesimulator -MD -MT dependencies -MF /Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Intermediates/PrecompiledHeaders/BlinkyBle-Prefix-hgtaudjsezkfjghkrtslxkdnrhrc/BlinkyBle-Prefix.pch.d -c /Users/nullpointer/Documents/bluetooth/NORDIC/iOS-master/BlinkyBle/BlinkyBle/BlinkyBle-Prefix.pch -o /Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Intermediates/PrecompiledHeaders/BlinkyBle-Prefix-hgtaudjsezkfjghkrtslxkdnrhrc/BlinkyBle-Prefix.pch.pch --serialize-diagnostics /Users/nullpointer/Library/Developer/Xcode/DerivedData/BlinkyBle-cjtjgkbouuqudyhjloicfilbwptx/Build/Intermediates/PrecompiledHeaders/BlinkyBle-Prefix-hgtaudjsezkfjghkrtslxkdnrhrc/BlinkyBle-Prefix.pch.dia


text:
Q: Is it possible to use Index and Match in Excel VBA? I use this method to find result in multiple criteria.
INDEX(Sheet2!F:F,MATCH(1,(Sheet2!$D:$D=$A$6)*(Sheet2!$E:$E=$B$6),0))

And in vba, It is not working...

Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
Set wf = WorksheetFunction

data = wf.Index(ws2.Range("F:F", wf.Match(1,(ws2.Range("$D:$D")=ws1.Range("$A$6"))*(ws2.Range(
$E:$E=$B$6")),0))

How to fix it?
Of course, i know it is not efficient, but i want to do it.


text:
Q: F# explicit match vs function syntax Sorry about the vague title, but part of this question is what these two syntax styles are called:
let foo1 x =
    match x with
    | 1 -> "one"
    | _ -> "not one"

let foo2 = function
    | 1 -> "one"
    | _ -> "not one"

The other part is what difference there is between the two, and when I would want to use one or the other?

A: The pro for the second syntax is that when used in a lambda, it could be a bit more terse and readable.
List.map (fun x -> match x with | 1 -> "one" | _ -> "not one") [0;1;2;3;1]

vs
List.map (function 1 -> "one" | _ -> "not one") [0;1;2;3;1]

A: function only allows for one argument but allows for pattern matching, while fun is the more general and flexible way to define a function. Take a look here: http://caml.inria.fr/pub/docs/manual-ocaml/expr.html

A: The match version is called a "pattern matching expression".  The function version is called a "pattern matching function".  Found in section 6.6.4 of the spec.
Using one over the other is a matter of style.  I prefer only using the function version when I need to define a function that is only a match statement.

A: The two syntaxes are equivalent. Most programmers choose one or the other and then use it consistently.
The first syntax remains more readable when the function accepts several arguments before starting to work.

A: The function version is a short hand for the full match syntax in the special case where the match statement is the entire function and the function only has a single argument (tuples count as one).  If you want to have two arguments then you need to use the full match syntax*.  You can see this in the types of the following two functions.
//val match_test : string -> string -> string
let match_test x y = match x, y with
                        | "A", _ -> "Hello A"
                        | _, "B" -> "Hello B"
                        | _ -> "Hello ??"

//val function_test : string * string -> string
let function_test = function
                        | "A", _ -> "Hello A"
                        | _, "B" -> "Hello B"
                        | _ -> "Hello ??"

As you can see match version takes two separate arguments whereas the function version takes a single tupled argument.  I use the function version for most single argument functions since I find the function syntax looks cleaner.
*If you really wanted to you can get the function version to have the right type signature but it looks pretty ugly in my opinion - see example below.
//val function_match_equivalent : string -> string -> string
let function_match_equivalent x y = (x, y) |> function
                                                | "A", _ -> "Hello A"
                                                | _, "B" -> "Hello B"
                                                | _ -> "Hello ??"

A: This is an old question but I will throw my $0.02.
In general I like better the match version since I come from the Python world where "explicit is better than implicit."
Of course if type information on the parameter is needed the function version cannot be used.
OTOH I like the argument made by Stringer so I will start to use function in simple lambdas.

A: They do the same thing in your case -- the function keyword acts like a combination of the fun keyword (to produce an anonymous lambda) followed by the match keyword.
So technically these two are the same, with the addition of a fun:
let foo1 = fun x ->
    match x with
    | 1 -> "one"
    | _ -> "not one"

let foo2 = function
    | 1 -> "one"
    | _ -> "not one"

A: Just for completeness sake, I just got to page 321 of Expert FSharp:

"Note, Listing 12-2 uses the expression form function pattern-rules -> expression. This is equivalent to (fun x -> match x with pattern-rules -> expression) and is especially convenient as a way to define functions working directly over discriminated unions."


text:
Q: Batch script to generate a random date to be integrated into a command that applies to a batch of files If anyone can help me, I'm having a hard time
I am using timestomper to change the date of my files, I would like to randomize the date for each file to get random sorting.
This is what I've done so far, the script is definitely very bad, but I've tried...
    @echo off & setlocal EnableDelayedExpansion
    Set /a _day=(!RANDOM!*25/32768)+1
    Set /a _month=(!RANDOM!*12/32768)+1
    Set /a _hours=(!RANDOM!*22/32768)+1
    Set /a _minutes=(!RANDOM!*60/32768)+1
for /r %%v in (*.jpg) do (
    timestomper -z %_month%-%_day%-2022 %_hours%:%_minutes%:01 -p "%%v"

)

the output of my script:
a.jpg 04/12/2010 10:20
b.jpg 04/12/2010 10:20
c.jpg 04/12/2010 10:20
d.jpg 04/12/2010 10:20

What I want is a randomly generated date for each file:
a.jpg 04/12/2010 10:20
b.jpg 10/02/2001 22:02
c.jpg 01/02/2004 15:27
d.jpg 12/20/2008 08:13

What timstomper needs is a date and a path to the file:
timestomper -z 10-20-1994 14:2:01 -p C:\full\path

I hope to be clear in my request

A: Ok. This is your original code:
    @echo off & setlocal EnableDelayedExpansion
    Set /a _day=(!RANDOM!*25/32768)+1
    Set /a _month=(!RANDOM!*12/32768)+1
    Set /a _hours=(!RANDOM!*22/32768)+1
    Set /a _minutes=(!RANDOM!*60/32768)+1
for /r %%v in (*.jpg) do (
    timestomper -z %_month%-%_day%-2022 %_hours%:%_minutes%:01 -p "%%v"

)

In my advice I said: "You must move the for /r %%v in (*.jpg) do ( command before the first Set /a _day= command and change the percents in timestomper invocation by exclamation marks, excepting in the "%%v" part, of course!"
Let's follow these instructions step by step:
"You must move the for /r %%v in (*.jpg) do ( command before the first Set /a _day= command"
That is:
    @echo off & setlocal EnableDelayedExpansion
                                              to here <----+
    Set /a _day=(!RANDOM!*25/32768)+1                      |
    Set /a _month=(!RANDOM!*12/32768)+1                    |
    Set /a _hours=(!RANDOM!*22/32768)+1                    |
    Set /a _minutes=(!RANDOM!*60/32768)+1                  |
for /r %%v in (*.jpg) do (                    from here >--+
    timestomper -z %_month%-%_day%-2022 %_hours%:%_minutes%:01 -p "%%v"

)

... giving:
    @echo off & setlocal EnableDelayedExpansion
for /r %%v in (*.jpg) do (
    Set /a _day=(!RANDOM!*25/32768)+1
    Set /a _month=(!RANDOM!*12/32768)+1
    Set /a _hours=(!RANDOM!*22/32768)+1
    Set /a _minutes=(!RANDOM!*60/32768)+1
    timestomper -z %_month%-%_day%-2022 %_hours%:%_minutes%:01 -p "%%v"

)

Then "change the percents in timestomper invocation by exclamation marks, excepting in the "%%v" part"
    @echo off & setlocal EnableDelayedExpansion
for /r %%v in (*.jpg) do (
    Set /a _day=(!RANDOM!*25/32768)+1
    Set /a _month=(!RANDOM!*12/32768)+1
    Set /a _hours=(!RANDOM!*22/32768)+1
    Set /a _minutes=(!RANDOM!*60/32768)+1
    timestomper -z !_month!-!_day!-2022 !_hours!:!_minutes!:01 -p "%%v"

)


text:
Q: How to remove an event listener in Hammer.js 2.0 and bind the recognizer to a new function I am a bit confused on how to correctly remove an event listener in Hammer.js 2.0
Following the advice in this question it seems I just need to use
mc.off(eventString, functionEvent);
However I can't seem to get this to work, when I have 2 functions which I need to call with the same recognizer. My example is I need someone to panleft, then I need to remove this listener and listen for another panleft.
As you can see in my simplified codepen example I try to call mc.off in the first function, then set up the next event, but it runs both simultaneously.
So what I want in my example is for the first panleft to trigger the first function, then the second panleft to trigger a new function
var myElement = document.getElementById('myElement');

var mc = new Hammer(myElement);

mc.on("panleft", function(ev) {
  selectFirst('first')
});

function selectFirst (text) {
    myElement.textContent = text;
    mc.off('panleft', selectFirst);

    mc.on("panleft", function(ev) {
      selectSecond('second')
    });
}

function selectSecond (text) {
    myElement.textContent = text;
}

A: As indicated in the question I linked to above and its jsfiddle
As was mentioned in that answer, you can fix the issue by not using an anonymous function.
hammertime.on("touch", callback);
However it didn't seem to fix my issue of trying to remove the initial function and bind to a new one with the same recognizer.
I ended up just adding a new element and binding this to the second function. I suggest the same as you probably should only have 1 panleft event for the element and if it needs to do something different just add another hammer element with the panleft on it.


text:
Q: Stop instascan alert to phone after QR code scan in android I have an application that is using instascan to scan QR codes but every time you scan a QR code on an android phone an alert pops up with the decoded result. For example, if I generated a QR code with the text "I like bananas" then the alert would say "https://mywebsite.com says I like bananas".
Is there any way to stop this alert from showing? It doesn't happen on my laptop or tablet only my phone. Here is my code if you would like to see it:
    <video id="preview" visible="true"></video>
    <script type="text/javascript">
        let scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
        //When a QR code is detected
        scanner.addListener('scan', function (content) {
            //If it is a url
            if (content.match(/^http?:\/\//i)) {
                //Redirect to new page
                window.open(content);
            } else {
                var options = {};
                options.url = "CameraList.aspx/GetContent";
                options.type = "POST";
                options.data = JSON.stringify({ content });
                options.dataType = "json";
                options.contentType = "application/json";
                options.success = function (result) { };
                options.error = function (err) { };

                $.ajax(options);
            }
        });
    </script>

Any help is appreciated.

A: I figured it out based on this post: Stop alert javascript popup in webbrowser c# control
I wanted to return a string from a method called GetContent and alert that to the user only if the string was not empty:
        //write a new function for alert that expects a boolean value
        var fnAlert = alert;
        alert = function (message, doshow) {
        //only if you pass true show the alert
            if (doshow === true) {
                fnAlert(message);
            }
        }
        let scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
        //When a QR code is detected
        scanner.addListener('scan', function (content) {
            //If it is a url
            if (content.match(/^http?:\/\//i)) {
                //Redirect to new page
                window.open(content);
            } else {
                var options = {};
                options.url = "CameraList.aspx/GetContent";
                options.type = "POST";
                options.data = JSON.stringify({ content });
                options.dataType = "json";
                options.contentType = "application/json";
                options.success = function (result) {
                    //If my c# method GetContent returns a value
                    if (result != "") {
                        //then alert the user by passing true
                        alert(result, true);
                    }
                };
                options.error = function (err) { };

                $.ajax(options);
            }
        });


text:
Q: In TabView, disable tabs but enable dynamic content Is it possible to have a TabView where the tabs are disabled but the dynamic contents are still responsive?
In the following, all dynamic content seems to be disabled. I would like the Manipulate to remain active but the tabs not clickable.
TabView[{Manipulate[x, {x, 1, 10}], 2}, Enabled -> False]

A: Ok, so without additional info, here's what you can use:
TabView[{Manipulate[x, {x, 1, 10}], 2}, Dynamic[1, None]]

TabView second argument determines the active tab but None action for Dynamic prevents from changing it.


text:
Q: Temporarily disable segmentation fault Ubuntu 14.04 I am doing some homework for University and the book I am working from (Secure coding in C and C++ by Robert Seacord) has the following example in it;
You write a simple enter password program and do a stack smash on the program to make the terminal display a calendar snapshot. It's really simple and straightforward as an example of stack smashing. Except I think the book we have to work through was written a long time ago, before Segmentation faults covered this sort of activity.
I have searched a lot of sites (I've added -fno-stach-protector to the g++ compiler, and also set kernel.randomize_va_space=0, neither of these were allowed the exploit code to execute.
Here is the password c++ code;
#include <cstring>
#include <stdio.h>
#include <iostream>

bool isPasswordOkay(void);

int main(void)
{
    bool PwStatus;

    puts("Enter password:");
    PwStatus = isPasswordOkay();
    if (PwStatus == false)
    {
        puts("Access denied");
        return 0;
    }
    else puts("Access granted");
    return 0;
}

bool isPasswordOkay(void)
{
    char Password[12];

    gets(Password);
    if (!strcmp(Password, "goodpass"))
    return true;
    else return(false);
}

and here is the exploit code (exploit.bin);
000  31 32 33 34 35 36 37 38–39 30 31 32 33 34 35 36 "1234567890123456"
010  37 38 39 30 31 32 33 34–35 36 37 38 E0 F9 FF BF "789012345678a. +"
020  31 C0 A3 FF F9 FF BF B0–0B BB 03 FA FF BF B9 FB "1+ú . +≠+. +≠v"
030  F9 FF BF 8B 15 FF F9 FF–BF CD 80 FF F9 FF BF 31 ". +ï§ . +−ç . +1"
040  31 31 31 2F 75 73 72 2F–62 69 6E 2F 63 61 6C 0A "111/usr/bin/cal "

Once the password code has been compiled I execute by entering ./a.out < exploit.bin
When executed, the terminal returns "Segmentation fault (core dumped)". What it should show is a snapshot of the calendar found at "111/usr/bin/cal ".
My question is, is there a way to temporarily disable this segmentation fault in order to allow the exploit code to execute? This would allow me to then go on to do the section as I'm a bit stumped at the moment.
Thank you,
Jon
EDIT: Unfortunatly I can't upload images yet as I'm new, but here is a link to a breakdown of the exploit.bin code; http://imgur.com/lpz9eY4


text:
Q: Means to draw attention to old questions with new answers My request is really an expansion on some meta-questions that have already been asked:

*

*Is it worth my time answering old posts?

*Is it worth posting an answer after answers have already been posted?

*Is it worth answering a question for which an answer has already been accepted?
However these questions don't really address what I am wondering. Specifically, I came across a three-year-old, security-related question which already had 22 (!) answers. I felt that none of those really provided the best advice on what to do in the situation posed by the asker.
So I provided my own answer, and waited, hoping perhaps foolishly for it to be recognised by the community as providing something valuable. Instead, it appears to have been largely ignored, I presume because there are already up-voted answers above it. Basically then, my complaint is that on questions which were previously highly trafficed, but now have little to no traffic, and where most answers have at least one up-vote, StackExchange values old, quite poor answers, to the detriment of newer, unverified but potentially better answers.
I would like people's ideas on how this could be improved.

A: If the question somehow no longer applies

*

*then you could pose a new question.  (The question you linked to is very subjective to begin with, so there are definitely some better, more specific related questions.  Those may have been asked already, though.)

If the question is fine but something has happened to make the previous answers no longer correct or less correct and those answers are so highly-voted that a new one is unlikely to gain any traction

*

*it seems reasonable to pose a new question.  Otherwise readers will keep being fed poor answers. In the new question be sure to include a link to the old one and the reason you think the topic needs to be revisited, though.  Make the case that it should not be closed as a duplicate, but be ready for people to think it is a duplicate and close it as one anyway.

If the question is fine and the answers are no less good than they were originally, even if they are just OK (though with high vote counts) and you think you can improve on them

*

*unfortunately I think there is less appetite to allow re-posting the question.  In that case, the only hope of readers getting the best answers is for them to note the timestamps on the answers and at least give newer low-vote answers a read.

To support that (giving new answers to ancient questions a chance), it might be good to highlight when there is a big difference in answer ages.  Maybe someone will consider exactly how that should be done and propose it as a feature request...

A: The traffic that came from question appearing on the top of questions/tag pages is long gone.
The traffic from google comes mostly from the users that have no SE account.
The registered users that come to the question in most cases won't see your answer because they won't go through all pages.
However, there are some means to draw attention to the old questions. One of them is the post to meta ;) The second possibility is the chat. The third are bounties. The edit or new answer would push the question up to active questions tab (however, it won't appear to users browsing by newest questions).


text:
Q: Iphone SDK selector or abstract class I am developing a special type of view controller for an iPhone component library.
I have got the who view controller working well, but I need to change it so that it works in one of two ways:
Either it is an abstract class which you must subclass and provider the implementation for a specific method which the controller will call whenever it needs its data.
Or it needs to be a useable class which has a property which is a selector... when you set the selector it specifies the method which should be called to collect the data.
I would like to know how I can implement either of these and which you would recommend

A: The standard way of doing this in Objective-C and the iPhone is through delegation.
Normally you provide a property in your view controller called delegate that is typed for a particular protocol you create. Then who ever is using your view controller will set the delegate property with their delegate for your view controller. You can then call the methods in your protocol on their delegate.
See the answer at this SO question for a full example.
Also read the Cocoa Fundamentals Guide for information on what delegates are and why they are used in Cocoa. There is also an example there of how to create delegates for your own custom classes.


text:
Q: Ranking with LIKE keyword in SQL Server I have table like
╔═══════════════════╗
║     Title         ║
╠═══════════════════╣
║     Blogroll      ║
║     Bottom Menu   ║
║     Business      ║
║     Entertainment ║
║     extend        ║
╚═══════════════════╝

and my search criteria is like
WHERE title LIKE '%blogroller%'

obviously I will have no result here but can I find the count where the like clause ended, like here in this case its beyond 8 that made like clause fail??
Any hint would be appreciated.
Thank you

A: You can do this but only with lots of manual effort:
select title,
       (case when title like '%blogroller%' then 10
             when title like '%blogrolle%' then 9
             when title like '%blogroll%' then 8
             . . .
             else 0
        end) as MatchLen
from table t
order by MatchLen desc;

(Note:  in some versions of SQL Server, you might need a subquery to refer to MatchLen.)

A: You don't have ability to do it at once, so you have to try all options one by one, but you can significantly optimize this process - that's what SQL for.
First, convert pattern into all possible patterns, then just find MAX from all possible LIKEs. Not sure if SQL will be able to really optimize it now, but maybe in future it will.
-- test data

DECLARE @token NVARCHAR(100)
SET @token = 'Blogroller'

DECLARE @titles TABLE (Title NVARCHAR(100))

INSERT @titles VALUES
('Blogroll'),
('Bottom Menu'),
('Business'),
('Entertainment'),
('extend')

-- solution

DECLARE @patterns TABLE (part NVARCHAR(100) PRIMARY KEY, tokenLen int)

WHILE (LEN(@token) > 0)
BEGIN
    INSERT @patterns VALUES (@token, LEN(@token))
    SET @token = SUBSTRING(@token, 1, LEN(@token) - 1)
END

SELECT MAX(patterns.tokenLen)
FROM @titles titles
INNER JOIN @patterns patterns ON titles.Title LIKE '%' + patterns.part + '%'

A: If you don't mind declaring a couple of variables and running a simple loop, you can do it this way:
declare @phrase as varchar(100) = 'blogroller'
declare @match_length as int = 0

while len(@phrase) > 0
begin
    if (select count(title) from titles where title like '%' + @phrase + '%') > 0
    begin
        set @match_length = len(@phrase)
        break
    end

    set @phrase = LEFT(@phrase, len(@phrase) - 1)
end

print @match_length

A: You can use some table with numbers (master..spt_values used in example) to break your search term into all possible shorter terms, and then join on it to find how many characters have matched:
setup:
CREATE TABLE Something (Title NVARCHAR(MAX));
INSERT Something (Title)
VALUES ('Blogroll')
,('Bottom Menu')
,('Business')
,('Entertainment')
,('extend')

query:
DECLARE @SearchTerm NVARCHAR(MAX);
SET @SearchTerm = 'Blogroller';

WITH CTE_SearchBroken AS
(
    SELECT LEFT(@SearchTerm, number) BrokenTerm
    FROM master..spt_values n
    WHERE n.type = 'P' AND n.number <= LEN(@SearchTerm)
)
, CTE_PreliminaryResults AS
(
    SELECT *, LEN(BrokenTerm) AS BrokenAt
    FROM Something s
    LEFT JOIN CTE_SearchBroken b ON s.Title LIKE '%' + b.BrokenTerm + '%'
)
SELECT Title
    , MAX(BrokenAt) AS BrokenAt
    , CASE WHEN LEN(@SearchTerm) = MAX(BrokenAt) THEN 1 ELSE 0 END AS Found
FROM CTE_PreliminaryResults
GROUP BY Title

A: Based on Gordon's answer, you can write a function that automatically loops through all the possibilities. Also similar to Lanorkin's answer; his might have better performance because it makes good use of inner join; you may want to do some tests there.
CREATE FUNCTION dbo.MatchLen(@needle AS varchar(max), @haystack AS varchar(max)) RETURNS int
AS
BEGIN
    DECLARE @len AS int = LEN(@needle)
    WHILE @len > 0 AND @haystack NOT LIKE '%' + REPLACE(REPLACE(REPLACE(LEFT(@needle, @len), '[', '[[]'), '%', '[%]'), '_', '[_]') + '%'
        SET @len = @len - 1
    RETURN @len
END

Example:
SELECT dbo.MatchLen('blogroller', 'This blog has no blogroll, sir!')

returns 8.

A: Please try:
select
    *,
    LEN(Title) MatchLength
From YourTable
where 'Blogroller' like Title+'%'

OR
select
    *,
    LEN(Title) MatchLength
From YourTable
where 'Blogroller' like '%'+Title+'%'


text:
Q: glmmTMB summary table full of NaN for z-values- cant find solution in troubleshooting vignette All,
I am running a generalised mixed effects model. My data has loads of zeroes and quite large values, it is count data. I am trying to test a treatment by date interaction and to see the effect of trt for all treatments.

glmmTMB(counts ~ trt * date + (1|ID), data, family = "nbinom1, ziformula = ~0)

however when I run the summary I obtain NaNs under the z-values and this warning message

Model convergence problem; extreme or very small eigenvalues detected.


text:
Q: Hyperledger private data collection and confidentiality I'm new to Hyperledger fabric and I want have some data confidential in my blockchain..
In fact I read about private data collection provided by HL , and I read that the private data is shared only among authorized peers and saved in peer's private state database using couchDB.
My question is, is PDC is a good alternative for protecting data? I mean is the peers private state could be accessible by any unauthorized peer on the network?
If yes, how? And how i can protect my data without using any form of encryption?

A: Welcome to the Hyperledger community!
Private data collections are ideal if you have several participants on the network that should not see the whole state of each other. Only authorized peers can access that information, if all peers follow the protocol (in particular, Fabric's private data collection definition, namely its policy). However, since a peer could deviate from the expected behavior, in theory, it could send the private data via an off-chain channel.
If you trust the network, private data is enough for your requirements. If you suspect some of the peers might misbehave (typically this is against a Fabric's network security assumptions), then encrypting data could be a good option.


text:
Q: Chapel sum reduce: unresolved call 'sum(eltType=type int(64))' I'm experimenting with Chapel to solve a simple problem:

Find the sum of multiples of 3 or 5 below 1000 (ProjectEuler001)

This is my code:
module Main {

    const topValue = 1000;
    var mostWanted : [0..#topValue] int;

    proc main() {

        forall (elem,i) in zip(mostWanted, 0..) {
            if(i % 3 == 0 || i % 5 == 0) {
                elem = i;
            }
        }

        var total = sum reduce mostWanted;
        writeln(total);
  }
}

Then I receive the message:
001.chpl:6: In function 'main':
001.chpl:14: error: unresolved call 'sum(eltType=type int(64))'

But if I change the word sum to max, it gives me the right answer:  999.
What am I missing? I can't understand why max work and sum doesn't.

A: Because the only reduce operator in the paper I was reading was max, I mistakenly assumed that all reduce operator were written like their description in the paper.

Chapel provides a number of standard reduction and scan operators,
  such as sum, product, logical and bitwise operations, and max/min
  (with or without location information).
  http://chapel.cray.com/papers/BriefOverviewChapel.pdf

Actually, the reduce operators are written like the normal operators. The correct code should be:
var total = + reduce mostWanted;

Reduce is an operator that combines a set of values to produce a single value. Reduce is useful because in parallel computation it is
  almost always necessary at some point to compare or combine results
  produced by different threads. The syntax for reduce is:
var varName = reduce_operator reduce iterator_expression;
In the code
  above, valid reduce_operators are: +, *, &, |, ^, &&, ||, min, max,
  minloc, and maxloc. Furthermore, iterator_expression can be an
  expression of any type that can be iterated over, provided the
  reduction operator can be applied to the values yielded by the
  iteration. For example, the bitwise-and operator can be applied to
  arrays of boolean or integral types to compute the bitwise-and of all
  the values.
To sum up all the elements of an array A of size 10, you write: var
  sum = + reduce A;
http://faculty.knox.edu/dbunde/teaching/chapel/#Reduce


text:
Q: Regarding diffusion in p-n Junction I know that in p-n junction there is p type semiconductor in one side where there are majority holes and n-type semiconductor in another side where the majority charge carriers are electrons. Now during diffusion, electrons move from n-type to p-type and holes from p-type to n-type. My argument is I admit that since atom loses electron it becomes immovable positively charged ion and creates a region of positively charged ion in the near side of n type semiconductor. But it is found that nearby p-type semiconductor region of negative ions accumulate creating barrier voltage. I am confused how can there be region of negatively charged ions near p-type semiconductor as holes(positively charged) get neutralized by the electron. Please help.

A: Electrons of the conduction band of n side of the joint can lower its energy by migrating to the p-side, where there are available states (holes) in the valence band, with lower energy.
But the existence of that available states doesn't mean that p-side of the joint was positive charged. It was neutral before the electron migration.
After the migration, there is an excess of electrons at the p-side of the joint and a lack of electrons at the n-side.
So, there is an electrical field that balances the band structure tendency to migrating. When that E-field is strong enough, the migrating process is no more energetically favorable and the process stops, leaving what is called a depletion zone.


text:
Q: .NET 7 application prompts for both Microsoft.NETCore.App and Microsoft.WindowsDesktop.App I've created a WinForms application using .NET 7 ("framework-dependent"). After installation to a computer without .NET 7, the user is prompted to first install the Microsoft.NETCore.App framework when first running the application, but when trying to run the application after this they get another prompt to install the Microsoft.WindowsDesktop.App framework. The application then runs fine after the second install.
Why are there 2 separate prompts? Some users seem to be getting confused since the prompts look similar and they think they are being asked to install the same thing again.
Is there a way to reduce this to just one prompt?
The application is composed of a single WinForms project: TargetFramework is net7.0-windows
The install files are produced with 'dotnet publish':
-r win-x64 --self-contained false -p:Configuration=Release -p:PublishSingleFile=true -p:Platform=x64
The install is created with InnoSetup. My install doesn't attempt to install .NET 7 - this is left to the default Windows behavior (which prompts twice instead of just once).

A: There is not enough info at the moment to give a definite answer but here are several possibilities that can in theory result in this behaviour (assuming you have WinForms app):

*

*One of the referenced nugets requires the ASP.NET Core runtime (like in this answer)

*The .csproj has FrameworkReference element with Include="Microsoft.AspNetCore.App" (as can be done to reference ASP.NET Core in library project - see this)

A: According to the Official page to download .NET 7
If you only install .NET 7.0 runtime, it may ask you to install the related .NET 7.0 Desktop runtime to support WPF and Windows Forms.


text:
Q: Are POI colors limited to IndexedColors? I'm trying to set Excel cell colors using Apache POI in Java. I played around in Excel itself and chose the colors I wanted - but I can't figure out how to use those colors with POI. I'm using the font.setColor method, which takes a short that's the index of a color... Which seems to indicate that I'm limited to the constants in IndexedColors. Is there any way to set a cell to a hex color value? Or can I only use the predefined constants?

A: You can use the HSSFPalette class to query the defined colors and define your own colors as well (using setColorAtIndex()).

A: I'm working with HWPF, not HSSF and I'm too lazy to go looking, but do the cell/character format classes you're working with have an attribute named "ico24" or something similar? In HWPF, that's the int representation of a 24 bit (A)RGB color spec which can be used to specify any color you like.


text:
Q: MVVM: Force ComboBox labels to refresh I have a ComboBox bound to an ObservableCollection<IDrive>
The problem is that IDrive does not support INotifyPropertyChange nor should it.
While the number of elements in my ComboBox is fixed and does not change, the labels shown in the ComboBox can and will change.
How do I get these labels to update?
Firing PropertyChanged on my ObservableCollection does not refresh the content of the labels but it does reset the SelectedItem which is a side-effect I don't even want.
Here's my current XAML:
<ComboBox Grid.Column="1" Grid.Row="0" Grid.ColumnSpan="4"
          ItemsSource="{Binding Drives}" SelectedItem="{Binding SelectedDrive}"
          IsSynchronizedWithCurrentItem="True" DisplayMemberPath="Label"
          Margin="5,5,5,5" VerticalAlignment="Center" />

Label being the property in my IDrive interface

A: You will need to wrap the items in a DriveViewModel : INotifyPropertyChanged and have that repeat the relevant properties. And somehow trigger the changed event from that.
On second thought, I'm not sure if DisplayMemberPath picks up on this. You'll probably need an ItemTemplate as well.


text:
Q: Randomly Generate Multiple Files From Directory with PHP I am building a website where people can go and upload images, gifs, and videos. On the home page, I want to list files at random from the upload directory.

<?php echo $file_title;?>

    <a href="<?php echo $randomImage ?>"><img src="<?php echo $randomImage ?>" alt="">

<?php echo $file_title;?>

    <a href="<?php echo $randomImage ?>"><img src="<?php echo $randomImage ?>" alt="">

And it does that for a total of five times. $randomImage is generated from the code:
<?php
   $imagesDir = 'uploads/';
   $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
   $randomImage = $images[array_rand($images)];
   $file_title = $randomImage;
?>

I want to be able to add a feature to where as the user scrolls down, more and more of these articles containing images show up, each containing a random but not previously shown file. How can I display files at random without having to manually enter unique variables?
P.S. Right now I do not have any files stored in a database.

A: Remove randomly selected image from $images before you select another.
loop for 5 images
<?php
// get all files

$imagesDir = 'uploads/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$imagesCount = count($images);

for($i = 0 ; $i < $imagesCount ; $i++) {

    // select image

    $randomIndex = array_rand($images); // select image index

    $file_title = $randomImage = $images[$randomIndex]; // use selected image

    unset($images[$randomIndex]); // remove selected image
    // print_r($images); // you can see what left in $images

    // show image

    ?>

<?php echo $file_title;?>

        <a href="<?php echo $randomImage ?>"><img src="<?php echo $randomImage ?>" alt="">

    <?php
}
?>


text:
Q: Print stdout in Python without shell escape sequences I'm using sh to run git commands inside a Python script.
In [1]: from sh import git

In [2]: s = git("log", "-1", pretty="format:%h %s")

In [3]: print s
4f14a66 basic debug page

This seems to work as expected. However, using this in a Django template gives [?1h= 4f14a66 basic debug page[m [K[?1l>. I tried to see what characters were in this string using repr(), to no avail:
In [4]: print repr(s)
4f14a66 basic debug page

It turns out commands in sh return a RunningCommand that has a .stdout attribute:
In [5]: type(s)
Out[5]: sh.RunningCommand

In [7]: s.stdout
Out[7]: '\x1b[?1h\x1b=\r4f14a66 basic debug page\x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>'

How do I get "4f14a66 basic debug page" i.e. the string without the escapes? Running the command from Bash is fine:
$ git log -1 --pretty="format:%h %s"
4f14a66 basic debug page

A: According to this GitHub issue, correct solution to the problem is to use _tty_out=False:
>>> str(git('show', format='%cN', s=True))
'\x1b[?1h\x1b=\rHonza Javorek\x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>'

>>> str(git('show', format='%cN', s=True, _tty_out=False))
'Honza Javorek\n'

This is also solution for my duplicate question: Using sh, git show returns special characters - how to get plain output?

A: s.stdout in the REPL will not print it but display its repr(). Use print s.stdout to get what you are looking for.
If you do not want any escape codes consider executing it using subprocess.call() - with stdout not being a tty most programs do not output any escape sequences.


text:
Q: Piecewise function with transformed random variable as an input The volume of the overlap between 2 spheres is given by the piecewise function:
$$
V = \left\{ \begin{array}{cl}
\frac{4\,\pi \,r^3 }{3} & : \ 0≤d\lt R-r \\
\frac{\pi \,{{\left(R-d+r\right)}}^2 \,{\left(-3\,R^2 +2\,R\,d+6\,R\,r+d^2 +2\,d\,r-3\,r^2 \right)}}{12\,d} & : \ R-r≤d≤R+r
\end{array} \right.
$$
Where d is the separation of the sphere centres, r is the radius of the smaller sphere, R is the radius of the bigger sphere. If d has a distribution defined by a uniform random variable U on (0,1):
$$
d=R\,U^{1/3}
$$
Is there a closed form expression for the mean value of V without specifying values of R and r?
If d wasn't defined by a distribution I was just going to use the mean of function formula but split the integral to obtain an explicit form like:
$$
V_{mean}=\frac{1}{b-a}(\int_{a}^{c} f(x) \,dx +\int_{c}^{b} f(x) \,dx)
\\
V_{mean}=...
$$
But since d is defined by a transform of a uniform random variable I thought to apply the random variable transformation, obtain the cumulative distribution function, obtain the density function and find the mean from that. As in the equation for V defines a cumulative distribution function like $F_{d}(x)=P(d\le x), F_{d}(x)=P(R\,U^{1/3}\le x)$ but I wasn't sure how to continue given the volume equation is a piecewise function with other inputs r and R.


text:
Q: Obtener primer,segundo y tercer lugar de una tabla MYSQL,JSP JAVASCRIPT Buen dia.
estoy teniendo incoveniente al obtener el equipo en primera,segunda y tercera posicion mas su puntaje,la data es obtenida de una tabla llamada score en mysql y se muestra en pagina.jsp,adjunta imagenes.

Ahora cuando ejecuto la siguiente la siguiente funcion no me arroja el resultado adecuado.

function calculartp(){

            var pts = document.querySelectorAll("td[data-title='PTS']");
            var equipo = document.querySelectorAll("td[data-title='Equipo']");
            var arreglo= [];

            for (let i = 0; i < pts.length; i++) {
                arreglo.push({"equipo":equipo[i].innerHTML,"pts":pts[i].innerHTML});
            }

            arreglo.sort(function (a, b) {
                if (a.pts < b.pts) {
                    return 1;
                }
                if (a.pts > b.pts) {
                    return -1;
                }

                return 0;
            });

                contenido ='Primer Lugar: ' + arreglo[0].equipo + ' PTS: ' + arreglo[0].pts + '\n';
                contenido+='Segundo Lugar: ' + arreglo[1].equipo + ' PTS: ' + arreglo[1].pts + '\n';
                contenido+='Tercer Lugar: ' + arreglo[2].equipo + ' PTS: ' + arreglo[2].pts + '\n';
                alert(contenido);

   }

espero su gentil apoyo.


text:
Q: Integrating a frontend js framework (Vue) for django I am a Laravel developer and used Vue as my frontend framework in the past.
However, I got interested in learning Python, specially its web framework equivalent - Django. Compared to Laravel, Django is pretty much way better in all aspects  - it's fast, it's one of those 'all-in-one' type of framework, plus it's PYTHON. A 15-minute task in Laravel can be accomplished in Django for 5 minutes.

One thing that's just bugging me is how to integrate Vue on its templates. I tried the normal CDN method but it doesn't actually work. I figured maybe because django's syntax -{{ sample variable here }} and Vue's are the same. I tried writing delimiters like delimiters: ['[[', ']]'], but it just made it more complex and still will not work.
I tried doing the webpack method which install a separate vue project within the django project, then used several (like a lot of third-party plugins) to somewhat connect the vue project, to the django project. It is so tedious on its process and it seems like it's not the why it should be. I kinda miss it on Laravel where you could just create an app.blade.php main template, import app.js on it, then just take it from there.
Is there a way to just integrate Vue on django's templates quickly like you can on Laravel?

A: We use Vue with Django via cdn, and it is pretty easy to set up as you can do everything in the template file.
You have to be sure to import Vue via script tag somewhere on the page and then either define your own delimiters (as you've done) or use the {% verbatim %} {% endverbatim %} tags around any variables you do not want django to try and evaluate. You can either write your Vue function in a script tag on the page or import an external file via script tag the way you would import any other js file into a django template. If you posted your template code, I might be able to provide more guidance.


text:
Q: How do you create a base class with a weak delegate that conforms to a generic protocol? I want to create a base class for UIViews that require that a delegate conform to a specific protocol defined by the View.
class BaseView<P>: UIView {
    weak var delegate: P?
}

protocol MyProtocol {}

class MyView: BaseView<MyProtocol> {}

This gives me the error: "'weak' must not be applied to non-class-bound 'T'; consider adding a protocol conformance that has a class bound".
How do I fix this error? Or is there some work around? Or is it not so necessary to make the delegate variable weak in the first place? Thanks in advance.

A: Since weak is a property assigned to anything that is of class type and not struct, you have to explicitly constraint your generic parameter to be of class type and you do that this way:
class BaseView<P: AnyObject>: UIView {
    weak var delegate: P?
}

@objc protocol MyProtocol {

}

class MyView: BaseView<MyProtocol> {

}

Only one need of clarification. Usually to make a protocol be of class type usally you would make it conform to class this way:
protocol MyProtocol: class { }

However, for some reason the compiler throws an error if you were to do it that way. I learned that this is a bug that could be learned about more here:
How to require that a protocol can only be adopted by a specific class
So adding the @objc helps silence the warning and error both.

A: You should add type constraint to your generic by adding MyProtocol and create a class that conforms MyProtocol.
You can find more info here.
Updated code:
class BaseView<P: MyProtocol>: UIView {
    weak var delegate: MyProtocol?
}

protocol MyProtocol: class {}

class MyProtocolImp: MyProtocol {

}

class MyView: BaseView<MyProtocolImp> {

}

But I don't know why you use P parameter in class.
You can write without this:
class BaseView: UIView {
    weak var delegate: MyProtocol?
}

protocol MyProtocol: class {}

class MyView: BaseView {

}


text:
Q: C# while copying a file, allow another process to exclusively lock the file? I'm currently copying the archive files of our oracle server, the one that i'm preventing to happen is while i'm copying the file server  will have an error when it tried to update the file.
At first i tried
File.Copy(source, Destination, true);

But it seems like this method is locking the file, the server throw an error in the log:
OSD-04002: unable to open file
O/S-Error: (OS 32) The process cannot access the file because it is being used by another process.

I change my method to
FileStream rStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

But when i try to open the file using a test program with FileShare. Now it throws an error also that another process is locking the file.
Is it possible to let go or release the file once another process wants to access/write to it?

A: what about
var stream = System.IO.File.Open(
                 source, System.IO.FileMode.Open, System.IO.FileAccess.Read
             );

Does this lock the file?
The best solution would be to use VSS to prevent locking (your server is a windows box, right?)

*

*create a snapshot

*copy files from snapshot

*delete snapshot

You can automate this with .NET
http://www.codeproject.com/Articles/22745/Volume-Shadow-Copies-from-NET


text:
Q: Declaring Array in VBA class I have several classes containing details about an onsite switchboard. I am using a Userform to store data in the variables declared in each class. I am struggling to store the data in any of my arrays. Am I going the right way about declaring these variables? Here's an example of one of my classes:
Dim pEquipID(3) As String
Dim pIr(3) As Integer
Dim pIm(3) As Integer
Dim pTripCurrent(3) As Integer
Dim pTripTime(3) As Integer
Dim pIsc(3) As Integer

Public Property Let EquipID(index As Integer, value As String)
    pEquipID(index) = value
End Property

Public Property Let Ir(index As Integer, value As Integer)
    pIr(index) = value
End Property

Public Property Let Im(index As Integer, value As Integer)
    pIm(index) = value
End Property

Public Property Let TripCurrent(index As Integer, value As Integer)
    pTripCurrent(index) = value
End Property

Public Property Let TripTime(index As Integer, value As Integer)
    pTripTime(index) = value
End Property

Public Property Let Isc(index As Integer, value As Integer)
    pIsc(index) = value
End Property

Public Property Get EquipID(index As Integer) As String
    EquipID(index) = pEquipID(index)
End Property

Public Property Get Ir(index As Integer) As Integer
    Ir(index) = pIr(index)
End Property

Public Property Get Im(index As Integer) As Integer
    Im(index) = pIm(index)
End Property

Public Property Get TripCurrent(index As Integer) As Integer
    TripCurrent(index) = pTripCurrent(index)
End Property

Public Property Get TripTime(index As Integer) As Integer
    TripTime(index) = pTripTime(index)
End Property

Public Property Get Isc(index As Integer) As Integer
    Isc(index) = pIsc(index)
End Property

And this is how I am storing the data:
Private Sub Enter1_Click()
    'create class variables
    Dim Transformer1 As cTransformer
    Set Transformer1 = New cTransformer
    Dim Fuse1 As cFuse
    Set Fuse1 = New cFuse
    Dim CircuitBreaker1 As cCircuitBreaker
    Set CircuitBreaker1 = New cCircuitBreaker
    Dim Pump1 As cPump
    Set Pump1 = New cPump
    Dim Cable1 As cCable
    Set Cable1 = New cCable
'store circuit breaker entries
    CircuitBreaker1.EquipID(0) = CB1ID1.value
    CircuitBreaker1.EquipID(1) = CB2ID1.value
    CircuitBreaker1.Ir(0) = Cb1Ir1.value
    CircuitBreaker1.Ir(1) = CB2Ir1.value
    CircuitBreaker1.Im(0) = CB1Im1.value
    CircuitBreaker1.Im(1) = CB2Im1.value
    CircuitBreaker1.Isc(0) = CB1Isc1.value
    CircuitBreaker1.Isc(1) = CB2Isc1.value
    CircuitBreaker1.TripCurrent(0) = CB1trip1.value
    CircuitBreaker1.TripCurrent(1) = CB2trip1.value
    CircuitBreaker1.TripTime(0) = CB1time1.value
    CircuitBreaker1.TripTime(1) = CB2time1.value

When I debug.print the CircuitBreaker array the terminal prints blank values. I use a loop like this to print each array:
        Dim count As integer
        For count = 0 To 1 Step 1
        Debug.Print CircuitBreaker1.EquipID(count)
        Next count

Note that this print statement is inside Enter1_click()

A: Your Property Get is incorrect.  Instead of:
Public Property Get EquipID(index As Integer) As String
    EquipID(index) = pEquipID(index)
End Property

... it should be:
Public Property Get EquipID(index As Integer) As String
    EquipID = pEquipID(index)
End Property


text:
Q: My Ruby on rails DELETE function do not work? This is Controller file
def destroy
@day = Day.find(params[:id])
@day.destroy

redirect_to days_path
end

This is index file
<%= link_to 'Delete', day_path(day), method: :delete, data: { confirm: 'Are you sure?' } %>

This is application.html.erb
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>

<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

<%= javascript_include_tag 'bootstrap.min.js', 'data-turbolinks-track' => true %>

<%= javascript_include_tag 'default', 'data-turbolinks-track' => true %>

<%= csrf_meta_tags %>

This is application.js
//= require jquery
//= require jquery_ujs
//= require ajax_setup
//= require ajax_modal
//= require bootstrap
//= require flash_message
//= require visibility_map
//= require modal
//= require select2
//= require select2_init

My Problem is When i SET UP EVERYTHING, there is no error in the terminal, but i can not delete this from database. When I click Delete link, nothing changed, no error. It does not work? Thanks for help!!

A: Try
<%= link_to 'Delete', day, method: :delete, data: { confirm: 'Are you sure?' } %>
def destroy
    @day.destroy
    respond_to do |format|
      format.html { redirect_to days_url, notice: 'Day was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

A: Try adding //= require jquery_ujs in application.js.
Check this out for its explanation.


text:
Q: How can I evaluate an equation of the first degree that contains parentheses? I try to evaluate an equation with first order parentheses in order to get the result.
In this equation it contains certain numbers and a variable x.
fmts = (
  '-{}x - (-{} - x) = {}',
  '-{}x - (-{} + x) = {}',
  '-{}x - ({} + x) = {}',
  '-{}x + ({} + x) = {}',
  '{}x + ({} + x) = {}',
  '-{}x - {}(-x - {}) = {}',
  '-{}x - {}(-x + {}) = {}',
  '-{}x - {}(x + {}) = {}',
  '-{}x + {}(x + {}) = {}',
  '{}x + {}(x + {}) = {}',
  '-{}x - (-x - {}) = {}',
  '-{}x - (-x + {}) = {}',
  '-{}x - (x + {}) = {}',
  '-{}x + (x + {}) = {}',
  '{}x + (x + {}) = {}',
  '-{}x - {}(-x - {}) = {}',
  '-{}x - {}(-x + {}) = {}',
  '-{}x - {}(x + {}) = {}',
  '-{}x + {}(x + {}) = {}',
  '{}x + {}(x + {}) = {}',

)

In the previous tuple I manually create all the possible combinations of said equation.
With that I make sure that these equations can be obtained correctly.
I create the regular expressions with the random variables that will take a random number:
w,x,y,z = randint(1,40), randint(1,40), randint(1,40), randint(1,40)
expr = choice(fmts).format(w,x,y,z)

But I can't evaluate it because I don't know how to do it. I have tried sympy, but it has not worked for me.
I tried print(f" {expr} = {eval (expr)} "), but it obviously doesn't work. Does anyone have any way to be able to evaluate these kinds of equations? Tahnks very much.

A: from sympy import symbols, Eq, solve
from random import randint, choice

fmts = {

  '-{}x - (-{} - x) = {}' : '-{}*x - (-{} - x) - {}',
  '-{}x - (-{} + x) = {}' : '-{}*x - (-{} + x) - {}',
  '-{}x - ({} + x) = {}' : '-{}*x - ({} + x) - {}',
  '-{}x + ({} + x) = {}' : '-{}*x + ({} + x) - {}',
  '{}x + ({} + x) = {}' : '{}*x + ({} + x) - {}',
  '-{}x - {}(-x - {}) = {}' : '-{}*x - {}*(-x - {}) - {}',
  '-{}x - {}(-x + {}) = {}' : '-{}*x - {}*(-x + {}) - {}',
  '-{}x - {}(x + {}) = {}' : '-{}*x - {}*(x + {}) - {}',
  '-{}x + {}(x + {}) = {}' : '-{}*x + {}*(x + {}) - {}',
  '{}x + {}(x + {}) = {}' : '{}*x + {}*(x + {}) - {}',
  '-{}x - (-x - {}) = {}' : '-{}*x - (-x - {}) - {}',
  '-{}x - (-x + {}) = {}' : '-{}*x - (-x + {}) - {}',
  '-{}x - (x + {}) = {}' : '-{}*x - (x + {}) - {}',
  '-{}x + (x + {}) = {}' : '-{}*x + (x + {}) - {}',
  '{}x + (x + {}) = {}' : '{}*x + (x + {}) - {}',
  '-{}x - {}(-x - {}) = {}' : '-{}*x - {}*(-x - {}) - {}',
  '-{}x - {}(-x + {}) = {}' : '-{}*x - {}*(-x + {}) - {}',
  '-{}x - {}(x + {}) = {}' : '-{}*x - {}*(x + {}) - {}',
  '-{}x + {}(x + {}) = {}' : '-{}*x + {}*(x + {}) - {}',
  '-{}x - (-{} - x) = -{}' : '-{}*x - (-{} - x) + {}',
  '-{}x - (-{} + x) = -{}' : '-{}*x - (-{} + x) + {}',
  '-{}x - ({} + x) = -{}' : '-{}*x - ({} + x) + {}',
  '-{}x + ({} + x) = -{}' : '-{}*x + ({} + x) + {}',
  '{}x + ({} + x) = -{}' : '{}*x + ({} + x) + {}',
  '-{}x - {}(-x - {}) = -{}' : '-{}*x - {}*(-x - {}) + {}',
  '-{}x - {}(-x + {}) = -{}' : '-{}*x - {}*(-x + {}) + {}',
  '-{}x - {}(x + {}) = -{}' : '-{}*x - {}*(x + {}) + {}',
  '-{}x + {}(x + {}) = -{}' : '-{}*x + {}*(x + {}) + {}',
  '{}x + {}(x + {}) = -{}' : '{}*x + {}*(x + {}) + {}',
  '-{}x - (-x - {}) = -{}' : '-{}*x - (-x - {}) + {}',
  '-{}x - (-x + {}) = -{}' : '-{}*x - (-x + {}) + {}',
  '-{}x - (x + {}) = -{}' : '-{}*x - (x + {}) + {}',
  '-{}x + (x + {}) = -{}' : '-{}*x + (x + {}) + {}',
  '{}x + (x + {}) = -{}' : '{}*x + (x + {}) + {}',
  '-{}x - {}(-x - {}) = -{}' : '-{}*x - {}*(-x - {}) + {}',
  '-{}x - {}(-x + {}) = -{}' : '-{}*x - {}*(-x + {}) + {}',
  '-{}x - {}(x + {}) = -{}' : '-{}*x - {}*(x + {}) + {}',
  '-{}x + {}(x + {}) = -{}' : '-{}*x + {}*(x + {}) + {}',
  '{}x + {} = {}x + {}' : '{}*x + {} - {}*x - {}',
  '{}x + {} = {}x - {}' : '{}*x + {} - {}*x + {}',
  '{}x + {} = -{}x - {}' : '{}*x + {} + {}*x + {}',
  '{}x - {} = -{}x - {}' : '{}*x - {} + {}*x + {}',
  '{}x - {} = {}x + {}' : '{}*x - {} - {}*x - {}',
  '-{}x - {} = {}x - {}' : '-{}*x - {} - {}*x + {}',
  '-{}x + {} = {}x - {}' : '-{}*x + {} - {}*x + {}',
  '-{}x + {} = {}x + {}' : '-{}*x + {} - {}*x - {}',
  '-{}x - {} = {}x + {}' : '-{}*x - {} - {}*x - {}',
  '-{}x - {} = -{}x + {}' : '-{}*x - {} + {}*x - {}',
  '-{}({}x + {}) + {}(-{}x - {}) = {}' : '-{}*({}*x + {}) + {}(-{}*x - {}) - {}',
  '-{}x - (-{} + x) = {}' : '-{}*x - (-{} + x) - {}',
  '-{}x - ({} + x) = {}' : '-{}*x - ({} + x) - {}',
  '-{}x + ({} + x) = {}' : '-{}*x + ({} + x) - {}',
  '{}x + ({} + x) = {}' : '{}*x + ({} + x) - {}',
  '-{}x - {}(-x - {}) = {}' : '-{}*x - {}*(-x - {}) - {}',
  '-{}x - {}(-x + {}) = {}' : '-{}*x - {}*(-x + {}) - {}',
  '-{}x - {}(x + {}) = {}' : '-{}*x - {}*(x + {}) - {}',
  '-{}x + {}(x + {}) = {}' : '-{}*x + {}*(x + {}) - {}',
  '{}x + {}(x + {}) = {}' : '{}*x + {}*(x + {}) - {}',
  '-{}x - (-x - {}) = {}' : '-{}*x - (-x - {}) - {}',
  '-{}x - (-x + {}) = {}' : '-{}*x - (-x + {}) - {}',
  '-{}x - (x + {}) = {}' : '-{}*x - (x + {}) - {}',
  '-{}x + (x + {}) = {}' : '-{}*x + (x + {}) - {}',
  '{}x + (x + {}) = {}' : '{}*x + (x + {}) - {}',
  '-{}x - {}(-x - {}) = {}' : '-{}*x - {}*(-x - {}) - {}',
  '-{}x - {}(-x + {}) = {}' : '-{}*x - {}*(-x + {}) - {}',
  '-{}x - {}(x + {}) = {}' : '-{}*x - {}*(x + {}) - {}',
  '-{}x + {}(x + {}) = {}' : '-{}*x + {}*(x + {}) - {}'

  }

a,b,c,d,e,x,y,z = randint(1,40), randint(1,40), randint(1,40), randint(1,40), randint(1,40), randint(1,40), randint(1,40), randint(1,40)

view_expr, expr = choice(list(fmts.items()))
expr = expr.format(a,b,c,d,e,x,y,z)
view_expr = view_expr.format(a,b,c,d,e,x,y,z)

x = symbols('x')

eq1 = Eq(eval(expr,{"x":x}), 0)
sol = solve(expr)
try:
  print(view_expr)

  raw_expr = expr

  eq1 = Eq(eval(expr,{"x":x}), 0)
  sol = solve(expr)
  print(f"{sol[0]}")
except:
  print('No tiene solución\n\n')


text:
Q: Hooks necessary to create module in drupal I want to create registration module in Drupal. I have created registration.info and wanted to create *.module for this. What are the hooks necessary to create this module?

A: You need at least those hooks:

*

*hook_permission() if you want to limit access to URLs or pages, etc.

*hook_menu() if you want to provide some pages. For example, settings page or form.

Additional hooks:

*

*hook_theme() if you need to build custom HTML or override existing theming.

*hook_form(), hook_form_submit() and hook_form_validate() to build and manage forms

*hook_form_alter() to override existing forms.

*hook_menu_alter() to override existing menu items.

*other hook_*_alter() to change anything in Drupal.


text:
Q: Should the Supplier, Client and User tables be combined I currently have 3 table and I am unsure if they should be merged or not. They do have similar fields, and a supplier would need to login at some point or another, and even clients
User

*

*Username

*Password

*Name

*Surname

*Mobile

*Telephone

*Email

Client

*

*Name

*Telephone

*Email

*Fax

*VatNo

Supplier

*

*Name

*Telephone

*Email

*Fax

*VATNo

*LastRefreshDate

*OpeningHoursId

Can somebody give me a suggestion as he best way to go forward.

A: The tables should probably not be merged. However, that's a judgement call based on guesses about what the tables mean.
It looks like clients and suppliers can be corporate entities (VAT numbers, for example), but users should be individuals rather than collective accounts.  You may well have a list of users associated with a given supplier; similarly, you may well have a list of users associated with a given client.  In some circumstances, a supplier may also be a client. You would need a User ID number in the Users table; you would need a Client ID number in the Clients table and a Supplier ID number in the Suppliers table. You would have simple mapping tables to list the Users associated with a Client and another to list the Users associated with the Suppliers.
However, a lot depends on whether the guesses I've made (plausible ones, but nonetheless guesses) are remotely on target.


text:
Q: filter on xml file loaded into jquery I am trying to filter an xml file, which contains an dateFrom and dateTo. the records i want to show must be between the to dates.
Here is what I have in my script:

And my xml file looks like this:
<?xml version="1.0" standalone="yes"?>
<infotainmentContent>
  <mediaFiles>
    <mediaFile file="1.jpg" fileType="PICTURE" durationInSeconds="10" validFrom="2014-04-23" validTo="2017-12-31" />
    <mediaFile file="2.jpg" fileType="PICTURE" durationInSeconds="10" validFrom="2014-04-23" validTo="2017-12-31" />
    <mediaFile file="3.jpg" fileType="PICTURE" durationInSeconds="10" validFrom="2014-04-23" validTo="2017-12-31" />
    <mediaFile file="4.jpg" fileType="PICTURE" durationInSeconds="10" validFrom="2014-04-23" validTo="2017-12-31" />
    <mediaFile file="5.jpg" fileType="PICTURE" durationInSeconds="10" validFrom="2014-04-23" validTo="2017-12-31" />
  </mediaFiles>
</infotainmentContent>

Please help and explain, or provide links to help
thanks in advance
Martin


text:
Q: Server rendering React app behind a URL prefix with react-router I'm using react-router, React 0.14 and nginx to render a universal JS app. Because I'm in the middle of transitioning an existing app, I need to put the new 'react' code behind a url prefix, say /foo
However, I'd ideally like nginx config to handle the proxy_pass to the react server running on a local port (say 8080).
nginx conf
location /foo/ {
    proxy_pass http://localhost:8080/;
    proxy_set_header Host $host;
}

React-router routes.jsx
import HomePage from 'components/pages/HomePage';
import AboutPage from 'components/pages/AboutPage';
import NotFoundPage from 'components/pages/NotFoundPage';

export default (
    <Route path="/">
        <IndexRoute component={HomePage} />
        <Route path="about" component={AboutPage} />
        <Route path="*" status={404} component={NotFoundPage} />
    </Route>
);

Nothing special on the server. The server-side rendering seems to work fine, but when it gets to the client, since the path doesn't match up it shows the following Warning in the console:
Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
 (client) <div class="NotFoundPage" data-r
 (server) <div class="HomePage" data-react

Which I guess makes sense since the URL is actually http://localhost:80801/foo instead of http://localhost:8081/ which react-router is expecting on the client.
Any ideas of ways around this other than putting the /foo prefix in the top-level Route? The reason I don't want to do that is I don't want to have /foo prefixes everywhere (in the <Link /> components for example).
MTIA!

A: You can configure a baseURL when setting up the history object.
import { createHistory, useBasename } from 'history'

const history = useBasename(createHistory)({
  basename: '/foo'
})


text:
Q: How to refresh image view immediately In my android app, I download an image from the cloud. The download is performed in a thread and in that same thread I also set an image view with the newly downloaded image. After setting the image, I then call postinvalidate().
However the image does not immediately show up. Is there a way to make the redraw happen immediately? I need a way to trigger a drawing cycle.

A: Each class which is derived from the View class has the invalidate() and the postInvalidate() method. If invalidate() gets called it tells the system that the current view has changed and it should be redrawn as soon as possible. As this method can only be called from your UIThread another method is needed for when you are not in the UIThread and still want to notify the system that your View has been changed. The postInvalidate() method notifies the system from a non-UIThread and the View gets redrawn in the next eventloop on the UIThread as soon as possible.
In your case you can achieve what you want with the help of AsyncTask (an intelligent backround thread).AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations (download image in background in your case) and publish results (set your bitmap to your ImageView) on the UI thread without having to manipulate threads and/or handlers.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called begin, doInBackground, processProgress and end.
The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface before downloading the image from cloud and that's used to provide a good user experience .
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter in that method you can set the bitmap to your imageView and invalidate your views

A: Invalidate doesn't work. Changing the uri or url or the path of the image temporarily and changing back to the required path works. For example, if i have
image_url="myhost/img.png";
himg.setImageURI(image_url, imageLoader);

I can refresh this as:
 himg.setImageURI(null, imageLoader);
 himg.setImageURI(image_url, imageLoader)

A: Did you try using invalidate()? It forces the view to be redrawn immediately and not during the next cycle

A: new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                while (!socket.isClosed()) {
                    imgArray = receiveImagebytes();
                }
            }
        }).start();

        try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

while (!socket.isClosed()) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    imageView.setImageBitmap(BitmapFactory.decodeByteArray(imgArray, 0, imgArray.length));
                    imageView.invalidate();
                }
            });


text:
Q: Laravel Get Count Based on Subordinate Model I'm doing my best to figure out how to make this work, but I am uncertain of the right way to go about this. I want to track a pharmacy's metrics, specifically how many patients a pharmacy fills or refills during a month. Ideally, this could happen by counting the amount of patients or scripts that were filled by the fill_date in the prescription model.
For example, patient John Smith could be written a script on 1/1/18, but receive prescriptions on 1/1/18, 2/1/18, and 3/1/18. I would want these refills to be tracked in my metrics - but done by patient or script. So that we can know how many patients (original fills or refills) went through each month.
Here is a breakdown of my models and relationships:
Patients/Scripts
patients have many scripts, where scripts can only have 1 patient. A patient is what you expect: a patient of a doctor. They go in to a doctor's office usually once and has a script written for them. Scripts are the documents that doctors write for patients. They will write this for the patient and send it to the pharmacy. Each script has a prescribe_date to show when the patient had a script written for them.
Scripts/Prescriptions
scripts have many prescriptions, where prescriptions can only have 1 script. When the pharmacy receives a script, they will see what the patient's insurance can cover, then fill a prescription. Prescriptions are what the patient is approved for and received, and will likely receive multiple months in a row if they have refills for their prescriptions. Each prescription has a fill_date to show when they received their fill/refill.
Pharmacies
pharmacies have many scripts, where scripts can only have 1 pharmacy. The pharmacy is an identifier tagged to the script written so that we can track a pharmacy's metrics.
Here is my code:
Pharmacy Model (linking prescriptions through scripts relationship)
// Pharmacies have many Scripts relationship
public function prescriptions() {
    $this->load(['scripts.prescriptions' => function($query) use (&$relation) {
        $relation = $query;
    }]);

    return $relation;
}

Variable
$patients_current_month = $pharmacy
    ->prescriptions()
    ->whereBetween('fill_date', [$first_day_current_month, $last_day_current_month])
    ->count();

Using this will give me the total count of prescriptions by pharmacy for the month, but I have tried multiple scenarios and can't find a way to make it display the count of the number of patients that had a fill_date (from their prescriptions) that month.

A: Script and Prescription mean the same thing. You don't need to have two tables for that. However you will need a "drug" table and "coverage" pivot table if you are trying to find out what drugs a patients drug plan will allow for. You will also need an "inventory" pivot table.
I'm not going to tell you all of the relations, as I feel you can figure those out yourself and it would make the answer way too long. Almost all of my code will be pseudocode.
Here's what I came up with:
Patient
id|name
Prescription
id|patient_id|doctor_id|is_filled|pharmacy_id|drug_id|reason|timestamps|
Drug
id|name|timestamps
Pharmacy
id|name
Inventory
drug_id|pharmacy_id
Coverage
patient_id|drug_id
Note, you can use tables as a pivot table by adding extra stuff to be out put withPivot. This may come handy for you Prescriptions table.
//Patient.php
public function drugs()
{
    return $this->belongsToMany(Pharmacy::class, 'prescription')->withPivot('pharmacy_id');
}

//Gets how many prescriptions a patient has at pharmacy between dates
Patient::withCount(['prescription.drugs '=> function($query) use ($first_day_current_month, $last_day_current_month, $pharmacy_id){
    $query->where('pharmacy_id', $pharmacy_id);
    $query->whereBetween('created_at',[$first_day_current_month, $last_day_current_month]) //You can use whereBetween for dates
}])->get();

//Counts prescriptions filled by Pharmacy for a drug

Pharmacy::withCount(['drug' => function($query) use ($drug_id){
    $query->where('drug_id', $drug_id);
    //You can also count haw many drugs were sold at a pharmacy here
    //and between what dates.
}])->get();

The boolean field is_filled on prescriptions gives you the ability to see what a patient is getting filled or not. If you want you can make that a column where not filled = 0, filled = 1, refill = 3.
I'm using a lot of constraint eager loading to accomplish things you want.


text:
Q: In bytecode add a method to a particular line in a class using BCEL I am new to BCEL for manipulating Java bytecode. I need to insert a new method into a particular line in a .class file using BCEL. The result should be a new .class file which contains the class with the newly inserted method.
I searched a lot online, but could not find a suitable code to follow. Can you please help me with this?
Thanks in advance!

A: I used GeekyArticles to figure out BCEL, maybe it helps you to? http://www.geekyarticles.com/search/label/BCEL
Anyway, the following code works for me (Java 1.7)
Test.java:
public class Test {}

AddMain.java:
import java.io.IOException;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.*;
import org.apache.bcel.*;

public class AddMain {

    static public void main(String args[]) {
        String className = (args.length >= 1) ? args[0] : "";
        JavaClass mod = null;
        try {
            mod = Repository.lookupClass(className);
        }
        catch (Exception e) {
            System.err.println("Could not get class " + className);
        }

        ClassGen modClass = new ClassGen(mod);
        ConstantPoolGen cp = modClass.getConstantPool();

        InstructionList il = new InstructionList();

        il.append(new GETSTATIC(cp.addFieldref("java.lang.System","out","Ljava/io/PrintStream;")));
        il.append(new PUSH(cp, "Hello World!"));
        il.append(new INVOKEVIRTUAL(cp.addMethodref("java.io.PrintStream","println","(Ljava/lang/String;)V")));
        il.append(new RETURN());

        MethodGen methodGen = new MethodGen(
            Constants.ACC_PUBLIC|Constants.ACC_STATIC,
            Type.VOID,
            new Type[]{new ArrayType(Type.STRING, 1)},
            new String[]{"args"},
            "main",
            className,
            il,
            cp);

        methodGen.setMaxLocals();
        methodGen.setMaxStack();

        modClass.addMethod(methodGen.getMethod());
        modClass.update();

        try {
            JavaClass newClass = modClass.getJavaClass();
            String className2 = className.replace(".","/");
            newClass.dump(className2 + ".class");
            System.out.println("Class " + className + " modified");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Then use these commands in your terminal:
Generate AddMain.class:
javac -cp bcel-5.2.jar:. AddMain.java;

Generate Test.class:
javac Test.java;

Inject method named "main" in class Test.class:
java -cp bcel-5.2.jar:. AddMain Test;

Run Test.class to test:
java Test

And of course make sure you've got the bcel-5.2.jar file in that directory as well.
As far as I know you can't control the position of the injected method, but I'm not sure about that..


text:
Q: What is an elegant / efficient way of storing the status of 100 lessons for multiple users? I'm working on an app in JavaScipt, jQuery, PHP & MySQL that consists of ~100 lessons. I am trying to think of an efficient way to store the status of each user's progress through the lessons, without having to query the MySQL database too much.
Right now, I am thinking the easiest implementation is to create a table for each user, and then store each lesson's status in that table. The only problem with that is if I add new lessons, I would have to update every user's table.
The second implementation I considered would be to store each lesson as a table, and record the user ID for each user that completed that lesson there - but then generating a status report (what lessons a user completed, how well they did, etc.) would mean pulling data from 100 tables.
Is there an obvious solution I am missing? How would you store your users progress through 100 lessons, so it's quick and simple to generate a status report showing their process.
Cheers!

A: If reporting is restricted to one user at a time - that is, when generating a report, it's for a specific user and not a large clump of users - why not consider javascript object notation stored in a file? If extensibility is key, it would make it a simple matter.
Obviously, if you're going to run reports against an arbitrarily large number of users at once, separate data files would become inefficient.
Discarding the efficiency argument, json would also give you a very human-readable and interchangeable format.
Lastly, if the security of the report output isn't a big sticking point, you'd also gain the ability to easily offload view rendering onto the client.

A: Use relations between 2 tables.  One for users with user specific columns like ID, username, email, w/e else you want to store about them.
Then a status table that has a UID foreign key.  ID UID Status etc.
It's good to keep datecreated and dateupdated on tables as well.
Then just join the tables ON status.UID = users.ID

A: A good option will be to create one table with an user_ID as primary key and a status (int) each row of the table will represent a user. Accessing to its progress would be fast a simple since you have an index of user IDs.
In this way, adding new leassons would not make you change de DB

A: The table structure I would recommend would be to keep a single table with non-unique fields userid and lessonid, as well as the relevant progress fields. When you want the progress of user x on lesson y, you would do this:
SELECT * FROM lessonProgress WHERE userid=x AND lessonid=y LIMIT 1;

You don't need to worry about performance unless you see that it's actually an issue. Having a table for each user or a table for each lesson are bad solutions because there aren't meant to be a dynamic number of tables in a database.


text:
Q: What is a good C/C++ CSS parser? What is a good C/C++ CSS parser?  All that I can find is CSSTidy, and it seems to be more of an application than a parsing library.

A: I googled for:
 "CSS Parser" C++
The first result is http://sourceforge.net/projects/htmlcxx. It's a CSS/HTML API for C++.

A: libcss seems also a common google hit and it looks good
http://www.netsurf-browser.org/projects/libcss/

A: A pretty good bet would be to read through the Mozilla or Safari code-base. If you need something a little more accessible for another program, there's an ANTLR grammar (which you can use to create C++ code) at http://www.antlr3.org/grammar/1214945003224/csst3.g. The W3 validator is located at http://dev.w3.org/cvsweb/2002/css-validator/, but it is Java.


text:
Q: система логирования изменений BIND(dns) Есть простой сервер BIND, который поддерживает несколько внутренних зон. Админы правят зоны руками через консоль. Необходимо сделать так, что бы при эксплуатации можно было бы увидеть старые записи. Т.е. записи со старыми serial,... кто и что именно исправил (дописал)...
Можно ли это реализовать на самом BIND, если внешними средствами, то какими?
UPD:
готового решения не нашли.
пришлось "костылять" на ходу.
вариант 1:

*

*организуем локальный репозитарий git в папке с зонами.

*sudo pip install inotify

написан скрипт (переписан example inotify), который мониторит изменения лога bind сервера и при перезаписи лога, делает в папке зон
git add .

git commit -m "update comment..."

(в комментарий коммита добавляем последнего ssh пользователя из лога auth (secure), но это не является панацеей... как определить пользователя, который перезапустил сервис (при условии, что сервис перезапускается от root) я не нашел)
Итого: можно откатиться на любой из рабочих конфигов зон.
вариант 2:
все изменения зон делаются на локальном gitLab сервере.
папка зон, на сервере DNS, имеет лишь копию репозитария git.
Те кто имеет доступ к репозитарию в gitLab комитят изменения (добавляют, изменяют записи днс), после чего создают тикет unix-администратору на обновление зон до последнего коммита.
Для администратора написан скрипты update и downgrade., которые обновляют до последнего коммита, и откатывает до выбранного коммита в случае не удачи.

A: программа bind — это dns-сервер, а не система управления версиями, которая вам требуется.
для отслеживания изменений в файлах вы можете использовать любую удобную систему управления версиями.

A: В идеально варианте, конечно, использовать git, да ещё и с какой-нибудь системой управления конфигурациями (ansible, puppet, chef и т.д.).
Однако если изменять нынешний процесс внесения изменений не представляется возможным, то с помощью auditd можно отслеживать кто делал изменения в файл(ы), выставленные этим же самым auditd на отслеживание.
Начать отслеживать файл, например, /etc/nginx/nginx.conf:
auditctl -w /etc/nginx/nginx.conf -p war -k nginx-config
Теперь после внесения правок в файл можно посмотреть кто их делал:
ausearch -f /etc/nginx/nginx.conf -i
----
type=CONFIG_CHANGE msg=audit(07/26/2016 11:22:07.376:1076160) : auid=paul ses=6466 op="updated_rules" path=/etc/nginx/nginx.conf key=(null) list=exit res=yes
----
type=CONFIG_CHANGE msg=audit(07/26/2016 11:22:07.376:1076161) : auid=paul ses=6466 op="updated_rules" path=/etc/nginx/nginx.conf key=(null) list=exit res=yes
----
type=CONFIG_CHANGE msg=audit(07/26/2016 11:22:07.376:1076162) : auid=paul ses=6466 op="updated_rules" path=/etc/nginx/nginx.conf key=nginx-conf list=exit res=yes


text:
Q: How can I insert in the middle of a multilayered nested list? I am trying to create a program that inserts a list in the middle of another nested list. Like a sandwich sandwiching another sandwich and so on. I am trying to approach this recursively but I have no idea how.
for example
layer1 = [1,2,3,4]
layer2 = [1,2,3,4,5,6]
layer3 = [1,2,3]

output = [1,2,[1,2,3,[1,2,3],4,5,6],3,4]

Here's my code for context
def lasagna(N,i):
  mainLayers = formLayer(i)
  midpoint = len(mainLayers) // 2
  if i == N:
    return mainLayers
  elif i < N:
    mainLayers = mainLayers.insert(midpoint, formLayer(i))
  return lasagna(N,i+1)

A: You can use *args that accepts any number of arguments and then write a recursive function like so.
layer1 = [1,2,3,4]
layer2 = [1,2,3,4,5,6]
layer3 = [1,2,3]
layer4 = [1,2,3,4,5,6,7,8]
layer5 = [1,2,3,4]

def sandwhich(*seq):
    res = []
    if len(seq) == 1:
        return seq[0]
    res.extend(seq[0])
    res.insert(len(res) // 2, sandwhich(*seq[1:]))

    return res

output = [1,2,[1,2,3,[1,2,3],4,5,6],3,4]

print(sandwhich(layer1, layer2, layer3))
print(sandwhich(layer1, layer2, layer3, layer4, layer5))

Output
[1, 2, [1, 2, 3, [1, 2, 3], 4, 5, 6], 3, 4]
[1, 2, [1, 2, 3, [1, [1, 2, 3, 4, [1, 2, 3, 4], 5, 6, 7, 8], 2, 3], 4, 5, 6], 3, 4]

A: Slightly shorter recursive solution:
layer1 = [1,2,3,4]
layer2 = [1,2,3,4,5,6]
layer3 = [1,2,3]
def nest(vals):
  a, *b = vals
  return a[:len(a)//2]+([] if not b else [nest(b)]) + a[len(a)//2:]

print(nest([layer1, layer2, layer3]))

Output:
[1, 2, [1, 2, 3, [1, 2, 3], 4, 5, 6], 3, 4]


text:
Q: How to read CSV where data start stored in one of the columns only? I have CSV file like below:
So first row contains all the columns without comma separation and second row has the data in the first column with comma separation
COLID                 TEMP1        TEMP2        TEMP3  .....
1,20.1,40.2,8.5

how to read and bring it in
COLID TEMP1  TEMP2  TEMP3
1      20.1  40.2    8.5

dataframe format .

A: Here, I have named file to be read as text.csv.
Important thing is 'sep' argument where we are telling pandas to read csv which is separated by spaces(\s+) or comma or a tab(\t).
pd.read_csv('test.csv', engine='python', sep='\s+|,|\t')

Output
    COLID   TEMP1   TEMP2   TEMP3
0   1       20.1    40.2    8.5


text:
Q: ABAC with Monorepo Microservices: What is the best approach? At my work, I have a task to search and find solutions to implement the ABAC authorization in our microservices organized in a monorepo. We have some products and we use the concept of realms to organize the different client's data in the same database.  Here our requirements are likely:

*

*An user, which is a manager of his company, can only see data from your company and from your employees.

*The same company can have N places, where each can have a manager. The manager of each place can only see the data from there.

First I thought to build some code to be used in every router of every API to verify the authorization and allow or deny the request. Something like this:

The other thing I thought was to create an API instead of a lib.

So, based on this question, I discovered that ABAC can be externalized from the apps (APIs) and make a lot of sense to me, see the image below.

But then I have some questions.

*

*Is bad to do what I thought in the first image or in the second?

*How the PDP will know what the user wants to do? Based on the route he is calling? But with this approach, the single responsibility will be hurt as the PDP needs to internalize (step 2) what other apps do, right?

*The PIP needs to call the database for the PDP validates the authorization. So this can be slow as the same query will be done 2x, one for checking the policy and the other inside the service with business logic.

A: *

*The modern way of doing this is by decoupling your policy and code - i.e. having a seperate microservice for Authorization - here's a part in a talk I gave at OWASP DevSlop about it.
You'd want you code in the middleware to be as simple as possible - basically just querying the Authorization microservice. That service basically becomes your PDP (in XACML terms).  This is true for both monolith and microservices (the assumption is you'll end up having more microservices next to your monolith anyhow).
To implement the Authorization microservice / PDP you can use something like OPA (OpenPolicyAgent.org) and then use OPAL as a PAP and manager for PIPs. (Full disclosure I'm a contributor to both OPA and OPAL)

*The query to the PDP should include what the user is doing (but not what the rules are). You can do this based on the Route (common when doing service-mesh), but often it's better to define a resource/action layout which becomes part of the query and is independent directly of the application route. Take a look at the Permit.io Policy-Editor which does exactly that kind of mapping. (Permit also uses both OPA and OPAL internally; Full disclosure I'm  one of the founders of Permit.io )

*Very good point. You don't want your PDP to constantly be querying other sources per incoming query to it (though its okay if you do it for a few edge cases) - What you want is to load data gradually in the background in an asynchronous fashion. Ideally in an event-driven fashion (i.e. have events propagate in realtime from the data sources into the PDP). This is exactly what you can do with OPAL.