text:
Q: Is it possible to make a higher order function over a typeguard? I have the following fairly basic function:
function isNil<T>(x: T | undefined | null): x is undefined | null {
  return x === undefined || x === null;
}

This works fairly well to infer that x is definitely a typesafe. However, I want to create a higher order function which will be able to invert this operation. Here's my basic implementation so far:
function complement<T extends (...args: unknown[]) => unknown>(fn: T) {
  return (...args: Parameters<T>) => !fn(...args);
}

This allows me to make a function like this:
const isNotNil = complement(isNil);

However, it infers the type slightly strangely:
const isNotNil: (x: unknown) => boolean

This appears to remove the typeguard:

Is there a way in typescript to achieve this?
Playground link

A: As you noticed, TypeScript won't automatically infer a predicate type as a function return this way.  You can manually annotate your complement() function so as to behave possibly reasonably in some circumstances, but it's somewhat brittle:

*

*Type guard function signatures can guard any of their arguments, like (x: any, y: any) => x is string guards the first argument, and (x: any, y: any) => y is string guards the second one.   There is not, as far as I know, a way to programmatically identify a type guard function for all possible locations of the guarded parameter.  In what follows I will assume that we only care about type guard functions where the first parameter is guarded.

*TypeScript does not currently support negated types (see microsoft/TypeScript#29317 for an experiment to support them) which would let you take x is T and turn it into x is not T.  Without a suitable not type operator, we need to make do with such utility types as Exclude<X, T> which only behave properly to pull members out of union types.  This will work for your use case (Exclude<T | null | undefined, T> will be null | undefined), but will fail for many others (e.g., Exclude<string, "a"> is just string; there is no all-strings-except-"a" type).

That said, here it is:
function complement<T, A extends any[], U extends T>(
  fn: (x: T, ...args: A) => x is U): (x: T, ...args: A) => x is Exclude<T, U>;
function complement<A extends any[], R>(fn: (...args: A) => R): (...args: A) => boolean;
function complement(fn: Function) {
  return (...args: any) => !fn(...args);
}

I've added the type-guard-processing signature as an overload.  If a function you pass in doesn't match that signature it should try the second, more general overload, which will just return a boolean-returning thing.

All right, let's try it:
function isNil<T>(x: T | undefined | null): x is undefined | null {
  return x === undefined || x === null;
}

const isNotNil = complement(isNil);
//const isNotNil: <T>(x: T | null | undefined) => x is Exclude<T, null | undefined>

const foo = Math.random() < 0.5 ? "hello" : null;

if (isNotNil(foo)) {
  console.log(foo.toUpperCase()); // HELLO if we reach here
}

Hey, it works.  isNotNil's type signature is automatically the right generic function type due to the support for higher order function type inference from generic functions introduced in TypeScript 3.4.
Playground link to code

A: The problem is that you end up mixing the "is" and the the actual boolean test
Why not simply separate out the actual boolean check and use that?
Here are two different examples that might help:
type Nil = undefined | null;
const nil = (v: unknown) => v === null || v === undefined;

const isNil = <T,>(x: T | Nil): x is Nil => nil(x);
const isNotNil = <T,>(x: T | Nil): x is T => !nil(x);

const data = ['a', 'b', null, undefined];

const a = data.filter(isNil);
const b = data.filter(isNotNil);

// Create both checks based on one function
const checks = <V,U>(isV: (x: U | V) => boolean) => {
    return {
        is: (x: U | V): x is V => isV(x),
        isNot: (x: U | V): x is U => !isV(x),
    }
}

const {is, isNot} = checks<string, Nil>(nil);

const c = data.filter(is);
const d = data.filter(isNot);

data.filter(isNotNil).map(item => item.toUpperCase());


text:
Q: gnuplot how to give column number to plot dynamically? I am automating a task to create small graphs using gnuplot. And I need to pass the column number from the datafile that is to be plotted
pfile=system("echo $file")
colnum=system("echo $colnum")

plot pfile using 4:(column(colnum)) title "slot1"
                     ^^^^^^^^^^^^

colnum is being exported earlier as export colnum=2
I am getting error at the highlighted part. I tried using export/fetch by system command, but it didn't work either
e.g. I tried 4:colnum, got similar error
"./12.gnuplot.helper.pg", line 29: warning: Skipping data file with no valid points
plot pfile using 4:(column(colnum)) title "slot1"
                                                ^
"./12.gnuplot.helper.pg", line 29: x range is invalid

A: You could also pass the column number via command line
gnuplot -e "colnum=$colnum" script.gp

and your script.gp contains
plot pfile using 4:(column(colnum))

A: This is an alternative to @EWCZ's answer. Any variable initialized using the system command is treated as a string: in your case, colnum="2" (with quotes). You can transform it to an integer by adding zero:
# first option
plot pfile using 4:(column(colnum+0))

# second option
colnum = system("echo $colnum") + 0
plot pfile using 4:(column(colnum))

As a side note, your task could be more flexible (easier to automate) by using @Christoph's answer; better if you have gnuplot 5.0 because you can pass arguments to a gnuplot script directly

A: it seems that one has to do colnum=int(system("echo $colnum")) so that the variable colnum is interpreted as an integer and not a string

redpajama_set_name: RedPajamaStackExchange


text:
Q: cURL help with PHP I am playing with cURL, and I am having trouble getting it to work. I want the cURL script to post the data on that form so I can see the posted data in results.txt. Here is my form script and then my cURL script after. I changed the $url before posting here.
Edit: The problem is, it's not posting the data. I ran the cURL script, and checked the results.txt to find the post data "WORKS" and it's absent. Also, if it makes any difference, I am using DreamHost.
UPDATE: I GOT IT! Funny thing. I targeted to the page with the form instead of the page that processes the POST.

    <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"/>
    <title>Test</title>

    <form method="POST" name="TestForm" action="write.php">

      Input anything: <input type="text" name="anything" value="Default"/>

      <input type="submit" value="OK" name="submit" />
    </form>

write.php code source

    $stringData1 = $_POST["anything"];
    $myFile = "results.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = "Bobby Bopper\n";
    fwrite($fh, $stringData);
    fwrite($fh, $stringData1);
    fclose($fh);

?>

My cURL script code source:
<?php

$url = "http://www.domain.com/submit/index.php";

$useragent="YahooSeeker-Testing/v3.9 (compatible; Mozilla 4.0; MSIE 5.5; http://search.yahoo.com/)";

$ch = curl_init();

curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, "anything=WORKS");

$result= curl_exec ($ch);
curl_close ($ch);

print "
 test" . $result;

?>

A: you are passing a string with CURLOPT_POSTFIELDS. Try using an array instead. Ex:
array( 'anything' => 'WORKS' );


text:
Q: Are there general parameters in which a traditional machine learning algorithm will outperform a Neural Network? I know this is a loaded question given the infinite number of circumstances surrounding what kind of machine learning algorithm to implement.  I was just wondering if there is a general framework that can hint at a situation in which "regular" machine learning algorithm will certainly outperform a neural net.

A: In the case of a normally distributed response with normally distributed features, $E(y|x)$ is provably the best minimizer of mean squared predictive error.
See this question.
Or Bickel and Doksum text "Mathematical Statistics."


text:
Q: How to check if my user is from a specific country Ios, Swift In my app I want to take the phone number of my user but I have a restriction of how the phone number starts, this is for Greece but I don't want my users outside of Greece to have this restriction.
So is there any way to accomplish this?
Thanks in advance.

A: After considering what we said in comments I found a way to do it.
I use the country that the user registered when he first open his phone like that:
var localeArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    localeArray = NSLocale.currentLocale().localeIdentifier.componentsSeparatedByString("_")

        }

func takeResult() {

   if localeArray[1] == "GR" {

       //do what you want
   }else {

      //handle if the user isn't in the country you want
   }
}

The first result of localArray (localArray[0]) is the system language that the user has.
EDIT FOR SWIFT 3
This is how you get the same result with swift 3 found it here
let locale = Locale.current
print(locale.regionCode)

A: NSLocale is just a setting about currently used regional settings, it doesn't mean the actual country you're in.
Use CLLocationManager to get current location & CLGeocoder to perform reverse-geocoding. You can get country name from there.


text:
Q: MPI_Testsome and MPI_Iprobe in C I have a piece of MPI C code which looks something like the following:
for(i=0;i<NTask;i++)
{
  got_initial_bit_of_data[i]=0;
  if(need_to_communicate with i)
     MPI_ISend(&bit_of_pre_data_for_i,1,MPI_INT,partner,0,MPI_COMM_WORLD,&pre_requests[i]);
}
while(1)
{
  MPI_Testsome(NTask,pre_requests,&ndone,idxs,MPI_STATUSES_IGNORE)
  if(ndone)
  {
    for(i=0;i<ndone;i++)
    {
      MPI_ISend(&the_main_block_of_data_for_i,size_of_block,MPI_BYTE,idxs[i],1,MPI_COMM_WORLD,&main_requests[idxs[i]]);
    }
  }
  //Other stuff that doesn't matter
  MPI_IProbe(MPI_ANY_SOURCE,0,MPI_COMM_WORLD,&flag,&status);
  if(!flag)
  {
    MPI_IProbe(MPI_ANY_SOURCE,1,MPI_COMM_WORLD,&flag,&status);
  }
  if(flag)
  {
    //Receiving the initial little bit of data
    if(status.MPI_TAG==0)
    {
      //Location 1
      got_initial_bit_of_data[status.MPI_SOURCE]=1;
      MPI_Recv(&useful_location,1,MPI_INT,status.MPI_SOURCE,MPI_STATUS_IGNORE);
    }
    //Receiving the main bit of data
    else if(status.MPI_TAG==1)
    {
      //Location 2
      if(got_initial_bit_of_data[status.MPI_SOURCE]!=1)
        //Something has gone horribly wrong...
      //Receive the main bit of data here...
    }
  }
}

Obviously I've omitted lots of details because the full code is several hundreds of lines long.  If something I've done looks a bit odd, it's probably because it is because of something in the omitted code block.
The idea is that at the start each processor sends an "announcement" message to those processors it wants to talk to.  When it detects that those processors have received this message (that is when MPI_Testsome indicates the "announcement" MPI_Isend is complete), it should send a big chunk of data.
From the point of view of a processor receiving data, it should first receive the announcement message at location 1, which will cause MPI_Testsome to indicate that the Isend is complete and send the big chunk of data.  The receiving processor should then receive the main block of data at location 2.  Following this logic, it should be impossible to reach location 2 with got_initial_bit_of_data[status.MPI_SOURCE] being 0, but this is precisely what does happen very occasionally and I'd like to work out why.
Either I've got the logic of the code wrong, or there's some subtlety of IProbe and Testsome that I'm missing.
I'm also exiting and re-entering this entire block of code, with different processors moving in and out at different points in time, but only when all their ISends have been processed (as determined by Testsome saying that they're completed).
If the above explanation doesn't make any sense, what I want to know is are there any circumstances under which Testsome claim that an ISend is completed without the matching receive completing (or even starting)?  Is a processor making a call to IProbe enough to cause Testsome to consider a request completed for instance?

A:
If the above explanation doesn't make any sense, what I want to know is are there any circumstances under which Testsome claim that an ISend is completed without the matching receive completing (or even starting)? Is a processor making a call to IProbe enough to cause Testsome to consider a request completed for instance?

All that MPI_Testsome guarantees is that the buffer you were using from ISend is no longer needed by MPI.  If you want to guarantee that the recipient has started the receive, use the synchronous form, ISSend.


text:
Q: Creating a link field in  a custom content type I have several custom content types and in one specific one I need to offer two fields, one for the href for a link, and one for the text of a link this way I can build and style it with minimal user involvement of the HTML/CSS. I also have a custom node.tpl for this content type. My problem is that drupal throws divs around each field I create that aren't in my template file for this content type (node-custom.tpl) and I can't put the href for a link with divs around it inside  See my problem. Maybe I'm doing this all wrong so any other ideas are welcome.
Please note I'm trying to create this site with minimum involvement of HTML/CSS access for the user. I'm aware I could hand code the link in the field.

A: The easiest way to do this would be to use a preprocess function in your template.php file and build the link up manually:
function mytheme_preprocess_node(&$vars) {
  $node = $vars['node'];
  if ($node->type = 'my_type') {
    $uri = $node->field_name_of_link_field[LANGUAGE_NONE][0]['value'];
    $text = $node->field_name_of_display_text_field[LANGUAGE_NONE][0]['value'];
    $vars['my_link'] = l($text, $uri); // Using Drupal's l() function to render a link
  }
}

Then in your node template file you'll have access to the variable $my_link which you can output anywhere, and will contain the correct HTML for the link. Finally, go to the "Manage Display" page for your content type and set the display of the two fields you no longer need to output to 'Hidden'.
There are other ways so if that's no good let me know
EDIT
Just to add, I think the easiest way to do this would actually be to install the Link module and use the provided field type instead of the two other fields you're currently using.


text:
Q: Change user for invocation of postfix transport script I am trying to pipe emails received to a script for processing. I have a custom Postfix transport defined in master.cf, as per the following.
transpire unix  -       n       n       -       -       pipe
  flags=Rq user=implantd argv=/opt/transpire/bin/implantproc.py $recipient > /dev/null 2>&1

This works, the emails defined in the local_recipient_map are piped to the script, however I have a permissions issue. It seems as though the script (implantproc.py) does not have write permission to a file, which it will need to run. For example, an NDR showing the permission error.
<test@company.com>: Command died with status 1:
    "/opt/transpire/bin/implantproc.py". Command output: Traceback (most recent
    call last):   File "/opt/transpire/bin/implantproc.py", line 11, in
    <module>     open("log.txt", 'a').write("test!") IOError: [Errno 13]
    Permission denied: 'log.txt'

Final-Recipient: rfc822; test@company.com
Original-Recipient: rfc822;test@company.com
Action: failed
Status: 5.3.0
Diagnostic-Code: x-unix; Traceback (most recent call last):   File
    "/opt/transpire/bin/implantproc.py", line 11, in <module>
    open("log.txt", 'a').write("test!") IOError: [Errno 13] Permission
    denied: 'log.txt'

It is/was my understanding that by default postfix runs under nobody/nogroup, but I have tried chowning the log.txt file with nobody. Also, you will note I have created a specific user, implantd, which should be used to invoke the transport script.
Can anyone advise what I am doing wrong?


text:
Q: Comparing words with scandinavian characters My program reads with Scanner class few words from a file and compare them to users output. My editor is NetBeans and OS Windows 7. I first ran the program in NetBeans and had no problems. When I ran it in the command prompt, scandinavian characters (ä, ö, å, Ä, Ö, Å) didn't display correctly. Well, I tested and gave different parameters for Scanner, like ISO-8859-1 but it didn't help. Finally, I gave UTF-8 for it and characters also display well. But I got a new problem. I use equals method to compare two words. But now it doesn't "work". Though the words should be equals method returns false. If I haven't any character set for Scanner the program works well in NetBeans but not in the command prompt. So what can I do and why doesn't equals method work? Should I create my own comparing method or something?
public void readingWordsFromFile(String textfile){

try{
    File f = new File("WordLists\\" + textfile + ".txt" );
    Scanner l = new Scanner(f, "UTF-8");

    try{

    int i = 1;
    while( l.hasNext() ){

        String temp = l.nextLine();

        words.put(i, temp);

        i++;
    }
    }
    catch (Exception e){
    }
    finally{
    l.close();
    }
}
catch (Exception e){
}
}

Edit: "Solved". The answer doesn't relate to character sets. Files contained BOM because I had accidentally saved them with Notepad. So now I use again Notepad++ and everything is fine. : )

A: *

*equals will not work when comparing two strings in different encondings - in terms of internal string representation - they are absolutelly different pieces of data

*you should try set proper encoding for scanner, when using it in windows cmd. Try use command chcp in cmd to see which codepage is used inside it.

A: The Windows cmd is not UTF8 by default. The netbeans console is UTF8, so it works properly.
In fact, if you type chcp in the console and press enter, you should see
Current active code table is: 850

Which is the ASCII Latin 1 charset.

A: Whenever possible use UTF-8, often one can pass StandardCharsets.UTF_8. For Swedish ISO-8859-4 is more suitable than the mentioned ISO-8859-1.
However one problem with Unicode is that an accented letter occurs as one Unicode code point (letter inclusive the accent), and as separate Unicode code points: ASCII letter and "combining diacritical mark" (the accent). For a text normalisation one might use java.text.Normalizer.
Usage of encodings in java suffer from many method and constructor signatures having an overloaded version without encoding defaulting to the operating system (or set) encoding.
In your case it looks like the latter. A Scanner without specified encoding, a FileReader/FileWriter, InputStreamReader, new String.


text:
Q: Force an object to be passed as copy to a function receiving a universal reference I'm trying to pass a local lambda function to a std::bind (for passing to a connect function of a signal):
void f()
{
    auto signal_f = [this](int, int) { /* ... */ };

    namespace ph = std::placeholders;
    signal.connect(std::bind(signal_f, ph::_1, ph::_2));
}

But the function parameter of std::bind is received as a universal reference:
template<class F, class... Args>
/* unspecified */ bind(F&& f, Args&&... args);

So, since my lambda object is a named object, it's passed as a lvalue reference , but my lambda object will be destroyed after f() exists, potentially causing memory leaks when the signal is emited.
What is the simplest way of passing that object by copy?
Of course, I could do always things like:
signal.connect(std::bind<std::decay<decltype(signal_f)>::type>
   (signal_f, ph::_1, ph::_2));

of other tricky ways but they are too cumbersome, so, what is the simplest way of doing it?
NOTE: Is there any function from the standard library to create a copy, something like std::make_rvalue(o) or a std::copy version for objects instead of for containers?

A: If you read the docs for std::bind() you'll see that:

The return type of std::bind holds a member object of type std::decay<F>::type constructed from std::forward<F>(f)

It doesn't hold a reference to signal_f, it holds a copy of it. There is no dependency on the lifetime of signal_f. The only dependency is on the lifetime of this, which signal_f captures.

Note that this:
signal.connect(std::bind<std::decay<decltype(signal_f)>::type>(signal_f, ph::_1, ph::_2));

which is actually the same as this (the decay is pointless since the closure type isn't a reference type):
signal.connect(std::bind<decltype(signal_f)>(signal_f, ph::_1, ph::_2));

is actually the same as:
signal.connect(std::bind(std::move(signal_f), ph::_1, ph::_2));

which you could also do.

A: bind does not actually store a reference to the lambda.  All the parameters are either copied(if lvalue) or moved(if rvalue) into the object returned by bind.
This reason is why you need to use std::ref when passing parameters to bind when the callable takes its parameters by reference.


text:
Q: How to remove plus button using javascript I am getting input fields with values from database. See below code:
<input type="text" class="input-medium" name="demoname" id="demo_1" value="txt1"/>
<button type="button" class="btn id="plus_1">Plus </button>
<input type="text" class="input-medium" name="demoname" id="demo_2" value="txt2"/>
<button type="button" class="btn id="plus_2">Plus</button>
<input type="text" class="input-medium" name="demoname" id="demo_3" value="txt3"/>
<button type="button" class="btn id="plus_3">Plus</button>

Now, I need the first plus button to show whenever a page opens. I want the rest of the plus buttons to hide.
The input am getting form database will be n number. So, whenever any new data comes from database also it has to show only first plus button.Other buttons has to hide.
The input fields are dynamically created.

A: You're missing " to close the class of your buttons:
<button type="button" class="btn" id="plus_1">
// ---------------------------  ^ here

then you can apply CSS to hide all of your button with class btn by default:
.btn {
    display: none;
}

then use .first() to show the first button:
$('.btn').first().show();

or :first selector:
$('.btn:first').show();

If you prefer pure jQuery solution, you can use:
$('.btn').hide().first().show();

If you want to use pure CSS approach, then:
.btn:not(:first-of-type) {
    display: none;
}

A: Use css
.btn {
    display: none;
}
.btn:first-of-type {
    display: inline;
}

http://jsfiddle.net/7kyCL/

A: First you need to close off the class quote. And i've created a div with and ID to place these within.
Here you go, with html and script

<input type="text" class="input-medium" name="demoname" id="demo_1" value="txt1"/>
<button type="button" class="btn" id="plus_1">Plus </button>
<input type="text" class="input-medium" name="demoname" id="demo_2" value="txt2"/>
<button type="button" class="btn" id="plus_2">Plus</button>
<input type="text" class="input-medium" name="demoname" id="demo_3" value="txt3"/>
<button type="button" class="btn" id="plus_3">Plus</button>


text:
Q: How to record/get memory requests that Last-Level Cache sends to Memory Controller? When there is a LLC miss, the memory request is sent to the MC to get data from memory.
Are there any tools that can get information (address/[read or write]/accurate timing) of the memory request sent by the LLC to the MC?
I want this information to be an input for my MC simulator, so that I can schedule them.
I used a tool called pin before. But it only records virtual memory addresses and can't get accurate timing.

A: As far as I know, there are no tools to get information from the memory requests sent by the Last-Level Cache (LLC) to the Memory Controller (MC) in a physical processor. Intel processors have hardware counters that allow for monitoring requests to DRAM, but no information about the address is available, its purpose is to count the number of requests.
You can use full system simulators like Simics or M5 to generate memory request traces with timing information. You can also get back to Pin and attach a cycle-accurate CPU simulator, but you will have to model the logical-physical address translation.


text:
Q: Get an Error when use IoThub as the Job input I create an IotHub and create an eventprocesshost to receive the events from the hub in a console application, then I create an ASA job and make the Iothub as the input with the default consumer group, but when I start the job, I get the exception:
There is more than one receiver with different epoch value connected to the same Event Hub. Please ensure Service Bus Explorer or an EventProcessorHost application is not connected while Stream Analytics job is running.
So the job input and the event processor host use the same consumer group make this happen???
The input and host cannot use the same consumer group???

A: You can't have EPH and ASA job running side by side due to Epoch conflict. Please close your EPH application and then restart ASA job.


text:
Q: Increment string value from AAA to AAB to AAC and so on Given a string AAB, how can I return a string AAC? I have tried using some of the methods on this answer but am getting an error trying to convert int to char or vice-versa.
public string GetNextPrefix(string prefixToIncrement)
{
    char[] digits = prefixToIncrement.ToCharArray();

    for (int i = previousPrefix.Length - 1; i >= 0; --i)
    {
        if (digits[i] == 'Z')
        {
            digits[i] = 'A';
        }
        else
        {
            digits[i] = digits[i] + 1;  //error here
            break;
        }
    }
    return new String(digits);
}

Update: Duh. Sometimes as soon as I post on here, the answer comes to me just as I post it. The error was:
Cannot covert source type 'int' to target type 'char'.
And I solved it by changing that line to:
digits[i] = (char) (digits[i] + 1);

A: You can cast to int and then back to char:
digits[i] = (char)((int)digits[i] + 1);

Update:
It also works without casting to int:
digits[i] = (char)(digits[i] + 1);

A: public string GetNextPrefix(string prefix, string format = "000")
{
    const string Charset = "ABCDEF";

    //remove the ToUpper() if you want to expand the charset to contains both cases
    var values = prefix.ToUpper().Select(c => Charset.IndexOf(c));
    if (values.Any(v => v == -1))
        throw new Exception("Invalid Prefix : " + prefix);

    var value = values.Aggregate(0, (acc,v) => acc = acc * Charset.Length + v) + 1;
    var result = String.Empty;

    while(value != 0)
    {
        var remainder = value % Charset.Length;

        result = Charset[remainder] + result;
        value = (value - remainder) / Charset.Length;
    }

    return result.PadLeft(format.Length, Charset[0]);
}

A: Indeed, this results in a type clash:
digits[i] = digits[i] + 1;

As does this:
digits[i] += 1;

But this works fine:
digits[i]++;

Thanks go to: Incrementation of char


text:
Q: How/where do I register the IDbPerTenantConnectionStringResolver Trying to run core api host.  i have this in the EntityFrameworkModule
    public override void PreInitialize()
{
    Configuration.MultiTenancy.IsEnabled = true;`

   // CONNECTION STRING RESOLVER
    Configuration.ReplaceService<IConnectionStringResolver, DbPerTenantConnectionStringResolver>(DependencyLifeStyle.Transient);

    Configuration.DefaultNameOrConnectionString = MyConsts.DefaultConnectionStringName;

    if (!SkipDbContextRegistration)
    {
        //DEFAULT
        Configuration.Modules.AbpEfCore().AddDbContext<MyContext>(options =>
        {
            if (options.ExistingConnection != null)
                MyContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
            else
                MyContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
        });

    }
}

ERROR
 Mvc.ExceptionHandling.AbpExceptionFilter - Can't create component 'Ccre.EntityFrameworkCore.AbpZeroDbMigrator' as it has dependencies to be satisfied.

'Ccre.EntityFrameworkCore.AbpZeroDbMigrator' is waiting for the following dependencies:
- Service 'Abp.MultiTenancy.IDbPerTenantConnectionStringResolver' which was not registered.

How/where  do I register the IDbPerTenantConnectionStringResolver?
I have this line in the PreInitialize of the Migrator.MigratorModule
Configuration.ReplaceService<IConnectionStringResolver, DbPerTenantConnectionStringResolver>(DependencyLifeStyle.Transient);

as well as in the EntityFrameworkModule


text:
Q: ConversationCallback.onConversation() is late to be called When failing in OUTGOING INVITE (due to TwilioConversationsClient.CONVERSATION_PARTICIPANT_NOT_AVAILABLE),
it's rarely too late that ConversationCallback.onConversation() is called.
Normally it's called in 1-2sec, but in the case it takes more than 10sec.
I cannot have the steps to reproduce.
Please help me.
Details:

*

*SDK0.12.2 (July 6, 2016), Conversations Library 0.12.2, Twilio Common 0.6.1

*ASUS ZenPad 8.0 (Z380KL), Android 5.0.2


text:
Q: If two Borel measures coincide on all open sets, are they equal? Let $X$ be a topological space and let $\mathcal{B}(X)$ be its Borel $\sigma$-algebra. That is, $\mathcal{B}(X)$ is the smallest $\sigma$-algebra on $X$ containing all the open sets. Let $\mu, \eta : \mathcal{B}(X) \to [0,\infty]$ be two Borel measures.

Question: If $\mu(U) = \eta(U)$ for all open sets $U \subset X$, does it necessarily follow that $\mu = \eta$?

I suspect that the answer is "no". Obviously it would suffice to prove

$\{ S : \mu(S)=\eta(S)\}$ is a $\sigma$-algebra,

but I don't see why this should hold. In general, the sets where two measures agree does not seem to be a $\sigma$-algebra. For example, consider two trivial measures on $2^X$, one which assigns zero measure to all sets, one which assigns infinite measure to all nonempty sets. They agree only on the empty set which is not a $\sigma$-algebra.

A: Here is an alternative, perhaps slightly easier  proof using Dynkin's π−λπ−λ Theorem:
https://math.stackexchange.com/a/813414/283164
Although it is sketched for $\mathbb R$, it works more generally.
BTW, Lemma 7.1.2. (p. 68) of Measure Theory, volume 1, Vladimir I. Bogachev:
If two finite signed Borel measures on any topological space
 coincide on all open sets, they coincide on all Borel sets.
Its simple proof uses:
Lemma 1.9.4. If two probability measures on a measurable space $(X,A)$
 coincide on some class $E\subset A$ that is closed with respect to finite
 intersections, then they coincide on the $\sigma$-algebra generated by $E$.
Link to Lemma 7.1.2

A: Hint: what's the collection of all set where the 2 measures agree? Does that collection form a monotone class? Does it contains all open set?

A: Your guess is correct : the answer is "No" in general;
For example, let $\mu_1$ be the counting measure on $\mathbb R$, and let $\mu_2$ be the measure defined by $\mu_2(\emptyset)=0$ and $\mu_2(A)=\infty$ if $A\neq\emptyset$.
On the other hand, if the space $X$ is the union of an increasing sequence of open sets on which the two measures are finite, the the answer is "Yes". This follows from the monotone class theorem.


text:
Q: How to convert a png file from from 600 x 800 into 600 x 400? Get info on my source  png file.
file  old.png
old.png: PNG image data, 600 x 800, 8-bit colormap, non-interlaced

I want to convert old.png from 600 x 800  into  600 x 400.
convert -resize 600x400  old.png  new.png

Check my output.
file new.png
new.png: PNG image data, 300 x 400, 8-bit/color RGB, non-interlaced

A: convert -resize 600x400!  old.png  new.png


text:
Q: Android - Change `BottomNavigationView` `state_checked` color is it possible to change state checked color for each tab?
i am able to change the BottomNavigation state_checked color by adding the selector to BottomNavigation.
what i need is to change the state_checked color on each tab.
ie;
if i click the first icon on my BottomNavigation i need to change the icon state_checked color to green, on second icon change color to red etc..
BottomNavigationView
    <android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_gravity="bottom"
    app:itemIconTint="@drawable/selector"
    app:itemTextColor="@drawable/selector"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation" />

selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="@color/green" />
<item android:color="@android:color/darker_gray"  />
</selector>

now the state_checked color is Green and default color is gray.

A: You can do this dynamically as -
public static StateListDrawable selectorForColor (int normalColor,int pressedColor) {
        StateListDrawable states = new StateListDrawable ();
        states.addState (new int[]{ android.R.attr.state_pressed },
           new ColorDrawable(pressed));
        states.addState (new int[]{ }, new ColorDrawable(normal));
        return states;
    }

Call this method inside your onClick() of BottomNavigation item and pass the colors you want to set for this item. You can create an array of colors which will have colors for the item at each index of BottomNavigation.
This method will return a drawable object which you can set to your item view.


text:
Q: Css select: when style is applied doesn't display a picked dropdown option I have a dropdown list that I added a little of CSS styles to.
After it the picked dropdow options stopped being displayed:
<select class="form-dropdown form-input"
        id="genders" name="gender" >
  <option value="">Choose gender</option>

  <option value="male">Male</option>
  <option value="female">Female</option>
  <option value="other">Other</option>
</select>

.form-input  {
    height: 2vw;
    width: 50%;
    background-color: silver;
    border-radius: 10px;
    border: none;
    padding: 20px;
    margin: 15px;
 }

JSFiddle.
How do I fix it?


text:
Q: Return String in DataHandler I've created a web service in Java that returns a DataHandler.
This has to be able to return a File, which works fine.
But it should also be able to return a String.
Any idea how I can transfer a String with a DataHandler?

A: JavaMail has a ByteArrayDataSource that you can use for this purpose:
DataSource ds = new ByteArrayDataSource(theString, "text/plain; charset=UTF-8");
DataHandler handler = new DataHandler(ds);

The charset in the mime type determines what encoding it will use to convert the string to bytes.


text:
Q: Generalising 4 methods in java Suppose we have the following methods:
private boolean elephantExists(String name){
    for (Elephant e : elephantList) {
        if (e.getElephantName().equals(name)) {
            return true;
        }
    }
    return false;
}

private boolean elephantIDExists(String elephantID){
    for (Elephant e : elephantList) {
        if (e.getElephantID().equals(elephantID)) {
            return true;
        }
    }
    return false;
}

private boolean tigerIDExists(String tigerID){
    for (Tiger t : tigerList) {
        if (t.getTigerID().equals(tigerID)) {
            return true;
        }
    }
    return false;
}

private boolean dogIDExists(String dogID){
    for (Dog d : dogList) {
        if (d.getDogID().equals(dogID)) {
            return true;
        }
    }
    return false;
}

How are we able to generalise all these methods into one method?
I thought about doing something like this:
private boolean ifExists(String s, ArrayList<Object> arrList) {
    for (Object o : arrList) {
        if (something) {
            return true;
        }
    }
    return false;
}

However I am not sure what the if statement would be. I am having trouble generalising this and would appreciate the help :)

A: The most straightforward would be to define an interface like IdAware:
public interface IdAware { public String getId(); }

Then make all your animal classes implement this interface. This will require renaming methods like getTigerId() to getId(), but that's a small sacrifice.
Then you could use this method to search in a list of animals. Something like:
private <T extends IdAware> boolean ifExists(String id, Collection<T> animals) {
    return animals.stream().anyMatch(animal -> id.equals(animal.getId()));
}

Alternatively if you for some reason don't want to (or cannot) have a common interface, you can additionally pass a lambda which extracts the id.
private <T> boolean ifExists(String id, Collection<T> animals, Function<T, String> getId) {
    return animals.stream().map(getId).anyMatch(animalId -> id.equals(animalId));
}

Then call it like ifExists("Scott", tigers, Tiger::getTigerId);.

A: I would create an Animal base class like this:
abstract class Animal {
    abstract String getId();
    abstract String getName();
}

Then make all the others extend it:
class Elephant extends Animal {

    @Override
    String getId() {
        // do logic
    }

    @Override
    String getName() {
          // do logic
    }
}

class Tiger extends Animal{

    @Override
    String getId() {
         // do logic
    }

    @Override
    String getName() {
          // do logic
    }
}

class Dog extends Animal {

    @Override
    String getId() {
        // do logic
    }

    @Override
    String getName() {
          // do logic
    }
}

now you can add any object of type Animal into the ArrayList<Animal> and pass it to the ifExists method along with the criteria.
private static boolean ifExists(Predicate<Animal> predicate, List<Animal> arrList) {
        for (Animal animal : arrList) {
            if (predicate.test(animal)) {
                return true;
            }
        }
        return false;
}

now you can do:
ifExists(tiger -> tiger.getId().equals("007464"), arrList);
ifExists(elephant -> elephant.getId().equals("00D37464"), arrList);
ifExists(elephant -> elephant.getName().equals("Bo-Tat"), arrList);
ifExists(dog -> dog.getId().equals("008483"), arrList);
....
....
....

A: In case you are not too acquainted with Java 8 and you are looking for a simplistic answer. Here's the code:
class AnimalId{
private String id;
public String getId(){ return this.id; }
}

class Elephant extends AnimalId{
//Other variables and function
}
class Tiger extends AnimalId{
//Other variables and function
}
class Dog extends AnimalId{
//Other variables and function
}

This covers the generalisation that you need. Now coming to your actual code, it would be something like this:
private boolean ifExists(String s, ArrayList<AnimalId> arrList) {
    for (AnimalId o : arrList) {
        if (o.getId.equals(s)) {
            return true;
        }
    }
    return false;
}


text:
Q: MySQL hogging memory An installation of MySQL 5.6.10 on a virtualized Ubuntu 12.04 is exhibiting massive memory hogging. The mysqld process claims the entire available memory within a couple of hours of uptime and forces the host to swap:
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
16229 mysql     20   0 26.8g  21g 8736 S   42 93.4  37:23.22 mysqld

It has grown as large as 50 GB once and by thus has significantly outgrown the data set itself:
Current InnoDB index space = 5.25 G
Current InnoDB data space = 23.07 G

Usually, I am able to free ~ 3 GB  by issuing FLUSH TABLES, although it is considerably faster to just kill -9 the mysql process, have it re-started and have recovery run for InnoDB. The tables used are nearly exclusively InnoDB, the innodb_buffer_pool_size has been set to 5 GB (after setting it to 16 GB quickly depleted the available physical memory and swapped out more than 18 GB of it).
While the system was swapping, I could observe rather high numbers for "swap out" counters (vmstat is showing ~1k pages/second during bursts) and hardly anything at all swapped back in (few dozens of pages per minute). I first suspected memory leakage but have not found anything supporting this hypothesis so far.
SHOW INNODB STATUS indicates that the buffer pool is only partially filled:
----------------------
BUFFER POOL AND MEMORY
----------------------
Total memory allocated 5365825536; in additional pool allocated 0
Dictionary memory allocated 2558496
Buffer pool size   320000
Free buffers       173229
Database pages     142239
Old database pages 52663
Modified db pages  344
Pending reads 1
Pending writes: LRU 0, flush list 1 single page 0
Pages made young 34, not young 0
0.00 youngs/s, 0.00 non-youngs/s
Pages read 141851, created 387, written 41126
81.16 reads/s, 0.00 creates/s, 0.39 writes/s
Buffer pool hit rate 998 / 1000, young-making rate 0 / 1000 not 0 / 1000
Pages read ahead 0.00/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 142239, unzip_LRU len: 0
I/O sum[0]:cur[464], unzip sum[0]:cur[0]

The server has a total of 80-90 connections most of which are reported to be in "Sleep" state by SHOW PROCESSLIST.
The memory-sensitive options set are
max_allowed_packet      = 16M
thread_stack            = 192K
thread_cache_size       = 8
max_connections         = 1000

innodb_file_format      = Barracuda
innodb_buffer_pool_size = 5000M
innodb_log_file_size    = 256M
innodb_flush_method     = O_DIRECT

query_cache_limit       = 1M
query_cache_size        = 256M

join_buffer_size        = 256k
tmp_table_size          = 2M
max_heap_table_size     = 64M

The tuning-primer.sh script calculates sane values for memory usage:
MEMORY USAGE
Max Memory Ever Allocated : 5.27 G
Configured Max Per-thread Buffers : 1.92 G
Configured Max Global Buffers : 5.15 G
Configured Max Memory Limit : 7.07 G
Physical Memory : 22.98 G
Max memory limit seem to be within acceptable norms

Binlog is enabled and the host has a replication slave attached to it (although results were not all that different at the time this has not been the case). Innodb_file_per_table is enabled by default in 5.6 and the databases are hosting a total of ~ 1,300 tables.
What means do I have to identify the possible causes for the apparently unlimited growth?
After reading "How MySQL uses memory" I had the suspicion that temporary tables might be the culprit. If they are not being released correctly for whatever reason, they could accumulate pretty quickly. The application querying the database issues a lot of nested, complicated queries, so temporary tables would be heavily in use according to the referenced docs. I tried checking if killing / resetting existing (idle) connections would significantly reduce memory usage when mysqld has reached ~20 GB - it would not, so this is either not related to connection states or the memory is leaking from there in a way which would be unaffected by closing the connection.
How would I verify if in-memory temporary tables are occupying a significant amount of memory? The STATUS variables and the INFORMATION_SCHEMA do not seem to have this information.
MySQL's memory usage appears hard to debug - the counters available seem not to account for the larger part of the usage I am seeing. I might be missing something, though.
I also have a MyISAM-based replication slave attached to the InnoDB master taking similar (read-only) loads - it does not show any signs of excessive memory usage (mysqld RSS is continuously < 1GB) , so the problem appears to be specific to the InnoDB configuration.

A: A bug filed here (http://bugs.mysql.com/bug.php?id=68287) looks like it is potentially relevant - check what table_definition_cache is set to by running:
SHOW GLOBAL VARIABLES LIKE '%table_definition_cache%';

A: Testing with the current GA release MySQL 5.6.19 revealed that the issue is gone.
Reading through the release notes of intermediate releases, I noted this particular note in 5.6.14 which I suspect to be related to our problem since it explicitly refers to subquery clauses which are in excessiveuse in our case:

For some statements, memory leaks could result when the optimizer removed unneeded subquery clauses. (Bug #16807641)
References: This bug is a regression of Bug #15875919.

Oracle unfortunately is not publishing bugs, so this is all the technical detail we can get on the issue.


text:
Q: How to run arquillian-jms-mdb? I am pretty green at arquillian and have some problem with it.
Could you please try out this (probably great) arquillian example for MDB:s?
https://github.com/mcs/arquillian-jms-mdb
I also downloaded the JBoss 7.2.0 from:
https://www.redpill-linpro.com/products/jboss/downloads-jboss-and-wildfly
I do not think you need any more setup actually, I bet you have a JDK installed already.
How ever, when I build it with mvn clean install, the container seems to start but the test is never executed. I just get:
Running com.github.mcs.arquillian.mdb.example.ExampleMDBBadTest
apr 17, 2018 3:20:37 EM org.jboss.as.arquillian.container.managed.ManagedDeployableContainer startInternal
INFO: Starting container with: ["C:\Program Files (x86)\Java\jdk1.8.0_92\bin\java", -Xmx768m, -XX:MaxPermSize=384m, -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y, -ea, -Djboss.home.dir=C:\Fredrik\Applications\jboss-as-7.2.0.Final, -Dorg.jboss.boot.log.file=C:\Fredrik\Applications\jboss-as-7.2.0.Final\standalone\log\boot.log, -Dlogging.configuration=file:/C:/Fredrik/Applications/jboss-as-7.2.0.Final/standalone/configuration/logging.properties, -Djboss.bundles.dir=C:\Fredrik\Applications\jboss-as-7.2.0.Final\bundles, -jar, C:\Fredrik\Applications\jboss-as-7.2.0.Final\jboss-modules.jar, -mp, C:\Fredrik\Applications\jboss-as-7.2.0.Final\modules, -jaxpmodule, javax.xml.jaxp-provider, org.jboss.as.standalone, -server-config, standalone-full.xml]
Listening for transport dt_socket at address: 8787

...nothing more happens.
Second, if I stop it and run again the port 8787 seems to still be in use, I need to kill the process from the task manger after finding out the PID.
I bet the example is great.
What do you think guys, what I'm I doing wrong?
Best regards
Fredrik

A: The message Listening for transport dt_socket at address: 8787 means that the JVM is suspended waiting for a debugger to connect to port 8787. If you take a look at the command which starts the JVM you'll see this system property:
-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y
This is what tells the JVM to "suspend" and wait for a connection on 8787.
This system property is configured in the project's arquillian.xml

A: I got in touch with the author himself and he pointed out that I need to run with Java 7, so in my cmd I set:
set MAVEN_OPTS=-Xms512m -Xmx1024m
set PATH=%PATH%;C:\Fredrik\Applications\Maven\apache-maven-3.3.9\bin
set M2_HOME=C:\Fredrik\Applications\Maven\apache-maven-3.3.9
set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_75
cd C:\dev\git\test\arquillian-jms-mdb-master

I also noticed that I needed to add this property in the arquillian.xml
<property name="jbossHome">C:\Fredrik\Applications\jboss-as-7.2.0.Final</property>

Second I noticed that it seems like I have to set "suspend=n", else it just behave like before, it just stops and "Listening for transport dt_socket at address: 8787"
Third I noticed that I needed to add these lines to the pom, else I got
"Error assembling EJB: META-INF/ejb-jar.xml is required for ejbVersion 2.x"
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-ejb-plugin</artifactId>
    <configuration>
        <ejbVersion>3.0</ejbVersion>
    </configuration>
</plugin>

Please comment if you disagree to my "workarounds" above.
How ever I think this arquillian example is great and helped me a lot!
Best regards
Fredrik


text:
Q: Commutative unitary ring A such that the quotient A/fA is finite for each prime element f of A We say that A is a residual ring if A is a commutative unitary ring such that the quotient A/fA  is finite for each prime element f of A. For example : Z, Z[i], the set of polynomials with coefficients in a finite field.
I am looking for other examples.


text:
Q: SQL server html table color only on single column using t-sql I'm working on the below script. I have successfully made an HTML table from table. But the requirement is that the column NEED_TO_BE_Checked should be the RED color but not all of the rows.
I used the condition case when NEED_TO_BE_CHECKED = 'YES' then '#F78181' end AS [@bgcolor], to color all rows in the output but the column Need_to_be_checked only should be highlighted. Kindly help.
Thanks in advance.

A: Here is an example of how I have created an HTML table and made individual cells in the table a certain color.
You need to define a class for your TD tag something like this:
<head>
<style>
td {
    border-width: 1px;
    padding: 5px;
    border-style: solid;
    border-color: #666666;
    background-color: #ffffff;
}
td.red {
    border-width: 1px;
    padding: 5px;
    border-style: solid;
    border-color: #666666;
    background-color: #FF0000;
}
</style>
</head>

When you build your HTML table, concatenate a special string, such as [class_red], with your data value. In the example I am making even numbered system type ids have a background of red.
declare @table varchar(max)
select @table = (
   select td = name
        , td = case when system_type_id % 2 = 0 then '[class_red]' else '' end
             + cast(system_type_id as varchar)
   from   sys.types
 order by name
 for xml raw('tr'), elements
)

Once the table has been created, replace the TD tag and [class_red] with the correctly formatted TD tag.
set @table = replace(@table, '<td>[class_red]', '<td class = "red">')

Hope this helps.


text:
Q: How to replace several Strings in a file at once using HashMap in Java I'm trying to replace several strings in one method using a HashMap but currently I can just get it to work with the first string in Map.
Previously I was using a "replaceAll" method for each String, which is hard to maintain because I'm trying to replace a changing list of Strings.
Can you give me any ideas?
Here's my code:
private static void string_change(String args[])
 {
 try
 {
 File file = new File("input_file.txt");
 BufferedReader reader = new BufferedReader(new FileReader(file));
 String line = "", oldtext = "";
 while((line = reader.readLine()) != null)
     {
     oldtext += line + "\r\n";
 }
 reader.close();

 Map<String, String> ReplacementMap = new HashMap<String, String>();
 ReplacementMap.put("STRING1", "TEXT1");
 ReplacementMap.put("STRING2", "TEXT2");
 ReplacementMap.put("STRING3", "TEXT3");

 String originalString = oldtext;

 for (Map.Entry<String, String> entry : ReplacementMap.entrySet()) {
   StringBuilder builder =  new StringBuilder(originalString.replaceAll(entry.getKey(), entry.getValue()));

   String newtext = builder.toString();

 FileWriter writer = new FileWriter("output_file.txt");
 writer.write(newtext);
 writer.close();
 }

 }
 catch (IOException ioe)
 {
 ioe.printStackTrace();
 }
}

A: The problem is, that you try to write the file for every entry in the map. So only the last entry is beeing applied to the target file.
The better solution would be to apply all replacements before you write the file.
File file = new File("input_file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuffer buffer = new StringBuffer();
String line;
while((line = reader.readLine()) != null) {
    buffer.append(line);
    buffer.append("\r\n");
}
reader.close();

Map<String, String> replacementMap = new HashMap<String, String>();
replacementMap.put("STRING1", "TEXT1");
replacementMap.put("STRING2", "TEXT2");
replacementMap.put("STRING3", "TEXT3");

String toWrite = buffer.toString();
for (Map.Entry<String, String> entry : replacementMap.entrySet()) {
    toWrite = toWrite.replaceAll(entry.getKey(), entry.getValue()));
}

FileWriter writer = new FileWriter("output_file.txt");
writer.write(toWrite);
writer.close();

A: You're overwriting your output file each time through the loop. How about this?
String temp = originalString;
for (Map.Entry<String, String> entry : ReplacementMap.entrySet()) {
    temp = temp.replaceAll(entry.getKey(), entry.getValue()));
}
FileWriter writer = new FileWriter("output_file.txt");
writer.append(temp);
writer.close();


text:
Q: WPF Bind different commands to button/menuitem I would like to ask you for an advice.
The application that I am working on has a docking control and should support working with different "documents". Therefore there can be multiple windows(tabs) opened at the same time.
Each can host a different content. The "documents" that I referred to could be a text file,
an excel style sheet or the main control that this app is being developed for (a geographical data visualization).
I am using the MVVM pattern and MVVM Light library. Note: I have a third party control for the excel spreadsheets.
Now I have a menu bar and a toolbar where I have common menuitems (in menubar) / buttons (in toolbar) like 'save', 'cut', 'copy' etc...  When you switch between between the tabs, the 'save' button should call the appropriate save functionality.
The same goes for cut/copy/paste:

*

*When in a tab with text document - cut/copy/paste should operate with text (there are wpf built-in commands for this).

*When in the main control - It should work with the graphical elements (I will have to implement these)

*When in the spreadsheet - It should work with the enclosed third party commands for the spreadsheet control.
Furthermore, there can be a tab that has some text selected - thus the menuitem/button for cut/copy should be enabled when switched to this tab, while some other tab has no graphical elements selected  thus the menuitem/button for cut/copy should be disabled when switched to this tab.
With the save command I can imagine one possible way to do it, but still, I am not sure whether it is a good way to implement it: Have a RelayCommand in MainWindowViewModel
public ICommand SaveCommand
{
    get
    {
        if (_saveCommand == null)
        {
            _saveCommand = new RelayCommand(() => this.SaveFile());
        }
        return _saveCommand;
    }
}

and the SaveFile() method would call some other 'save method' on the datacontext of the selected tab (which would be a viewmodel for the according "document" type).
However I don't know how to do the enabling/disabling of the save button/menuitem and I am clueless about how to achieve the different cut/copy/paste functionality.
I apologize for the length of the question. Maybe I could have just asked:
"How do you bind different cut/copy/paste commands to the buttons depending on which part of application is selected/active?".
But I felt the added context of what I am trying to achieve would help answer the question.

A:
and the SaveFile() method would call some other 'save method' on the
  datacontext of the selected tab (which would be a viewmodel for the
  according "document" type).

The SaveFile should be implemented by the ViewModel without going back to the View.
Create several ViewModels to represent different kind of documents and let each implement its Save functionality.
The CanExecute method of a command can be used by the View to decide whether or not the menu item or button should be enabled. All you need is to implement the CanExecute method in the ViewModel. In most cases a Save command's CanExecute would use an IsDirty or similar property.
EDIT
For menu items that should be context/active tab item aware you could create a main ViewModel with the commands for the menu and a collection of ViewModels (one for each tab item)
In the command handlers of the context aware menu items get the active ViewModel and pass the command on.
To get the current TabItem, bind the SelectedItem to a property of the main ViewModel (the type of the property could be a base class of the ViewModels).
That way you do not need to get back to the View to get the current tab item.


text:
Q: Unnesting and reforming a big query array seems to destroy null SELECT ARRAY(SELECT foo FROM UNNEST(CAST(NULL as ARRAY<STRING>)) as foo) is null

returns false
vs.
SELECT CAST(NULL as ARRAY<STRING>) is null

returns true
My specific situation is that I'd like to sort an array using
SELECT ARRAY(SELECT foo from UNNEST(bar) as foo Order by foo) as arr

and keep the array as null if it was originally null. I'm open to alternatives for sorting the array but preserving null (meaning I'm not hung up on my implementation).

A: An empty array is different from a NULL with an array type.  An empty array is an array with no elements.  That is what you get from the UNNEST().  So, the comparison to NULL is false.
The second is returning NULL typed as an array.  This is equivalent to NULL, so the comparison is true.


text:
Q: How to select range in Pandas using a row I have a Pandas dataframe.
I have in another process selected a row from that dataframe.
At another method, I now need to select a range from that dataframe where the row is and going back 55 rows, if there is so many.
Here is some pseudo code, hope it helps:
df = DataFrame from csv

row = df[3454]

index = row.index
start = max(0, index - 55)
end = max(1, index)
dfRange = df[start:end]

A: This should do it
integer_location = np.where(df.index == 3454)[0][0]
start = max(0, integer_location - 55)
end = max(1, integer_location)
dfRange = df.iloc[start:end]

This link has more info
Getting the integer index of a Pandas DataFrame row fulfilling a condition?


text:
Q: Board review: is this PIC16F877 RS232+ICSP board correct/robust? I want to make my own development board based on a PIC, to make a RS232 bootloader from scratch. It's been a while I haven't used a PIC, and it was on a ready made development board.
I've looked around on the web and designed what I think is a minimalistic RS232 and ICSP board based on a 16F877. Could you review it and tell me if it'll work, if it can be made more robust (for future projects as well)?
Sorry if the symbols look funny, I use DesignSpark PCB and I usually go first with the models in the ModelSource database.

In particular, the ICSP is going to be a ICD3 which is apparently high voltage... Not good for the MAX233 and the LM340.
P.S: Those are SMD components, therefore my "breadboard" will actually be a draft PCB from a PCB house

A: You need to look at the datasheet for the MAX232 and add the capacitors that are missing.  There should be 4 capacitors PLUS the bypass cap for a total of 5 capacitors near the MAX232.
I don't have the datasheet for the 16f877 in front of me right now but there should be two sets of Vdd & Vss pins.  I see only one set connected.  The chip is NOT reliable if you don't have both sets connected.
You should have a bypass cap right beside each of those sets of power pins.
[Edit]
I see now that you are using the MAX233, not the 232 like I had thought.  What you have looks okay.
Possibly the only potential problem is when you are programming the chip with your ICD3.
You show a 4k7 pull-up from !MCLR to Vdd.  If you don't have sufficient load on your 5V supply, the programming voltage will raise the 5V rail higher than allowed.
There are several easy options to fix this.

*

*Increase the value of R4 to 39k as per Microchip's datasheet

*Ensure that there is sufficient load on the 5V rail to ensure that Vpp being raised to +13V does not cause the 5V rail to increase.

*put a diode in series with R4 (cathode towards !MCLR)

Your schematic looks good and should get you going quickly.


text:
Q: What are the best practices regarding paths? I've been confused by this topic several times and been bitten by it. I've looked up many best practices articles and definitions but it seems to me that paths aren't exactly defined and what is an absolute and relative path seems to vary a lot depending on the context.
Short version of the question: Always carry around (and convert into) Absolute Paths in code? But always write them out as relative.
As a hobbyist I switch context constantly due to working on backend and frontend at the same time and I haven't come up with rules to be consistent and create portable code if paths are involved.
Essentially there seem to be to types of paths. Absolute Path and Relative Path. But I constantly come upon a third type which to me would probably be named Absolute Relative Path. The challenge for me is to know which one I should store and what complications could arise.
This is an Absolute Path:
/home/me/css/style.css

But not on Windows. What would the above do on Windows? It has to be this:
C:/home/me/css/style.css

What the Absolute Path that would work on Linux refers to using Windows is something completely different. It becomes relative to the current partition.
/home/me/css/style.css

becomes
C:/home/me/css/style.css

This is correct in this case, but might not be if the actual application is running on a different partition. Using Absolute Paths "Unix style" is therefore problematic if portability is required.
This is an Absolute Path to a directory:
/home/me/css/

But this is also an Absolute Path to a directory:
/home/me/css

Adding another slash is therefore purely conveying additional information to the writer, is it?
This is a Relative Path:
css/style.css

And to a directory:
css/

This is an Absolute Relative Path if used in an HTML document:
Link

While it refers to topmost css directory irregardless of where the address is currently pointing to, it still refers to the directory the webserver is handing out. As such it is absolute in use, but relative regarding the actual filesystem. Or in many cases, to the current working directory. The same is true for pure Relative Paths. If I create such paths I therefore have to keep in mind that even though they look like Absolute Paths, they are in fact not. Confusing.
If the application itself is moved to a different directory I therefore have to come up with a solution. And this is where I wonder if it is a bad idea to ever store Relative Paths. Say we write a static blog generator called blogger which is downloaded via git to some directory.
/home/me/blogger

All paths in the application are relative, we therefore call something akin to create_dir('output') in pseudocode. Now we might think it is a good idea to move the application to somewhere else and give the user the chance to supply the output directory himself. Suddenly all path definitions will break. They become create_dir(absolute($output_dir) + 'output').
I find this kind of calculation to become very long and complicated at some point. Especially if there are still some files or directories which stay relative to the application, like templates or similar. But they might also move in the future so I find myself writing code like copy_dir(cwd() + 'templates', absolute($output_dir) + 'output').
But wait, the current working dir is not necessarily the place where the application resides, especially on unix-like systems.
And how does absolute generate an absolute path if the application doesn't know whether it's absolute to the application directory or absolute to the current directory? We must assume the latter, so calling absolute() is not a good idea, rather cwd() + $output_dir. Thankfully cwd() usually returns an already absolute path. We can only do this if the path the user provided is actually relative, but not if it's absolute. Thankfully standard libraries have ways to deal with that, but the naive approach would blow up and we would end up with something like "C:/C:/css".
Assuming the user never provides absolute paths we could use:
copy_dir(absolute(app_dir()) + 'output', cwd() + $output_dir)
Then I say to myself, well, I have to do this everytime I work with those files, so why not do it once and carry around $abs_output_dir instead? Suddenly I come across the problem that I have to output an Absolute Relative Path into an HTML document and I can't use $abs_output_dir because I then somehow have to cut out the Absolute Part so it is relative to the user supplied $output_dir. At this point my mind usually brakes down and I either hardcode every path, or I carry around $output_dir $abs_output_dir and $rel_abs_output_dir as well as $abs_app_dir and try to keep all up to date.
As such the idea to only carry around Absolute Paths seems to be a good one, unless we every come to the point where we have to output Relative Paths or Absolute Relative Paths to a file. Is that how programmers usually do it?


text:
Q: Evaluation metric for named entity recognition I was watching Manning's lecture on evaluation of NER models, and I'm confused why between 4:07 and 5:13, he states that the error in not labeling one word in a sequence while correctly labeling the rest is considered as both a false positive (fp) and a false negative (fn). Based on my understanding, a fp is when you label a word as an entity when it is not actually that entity and a fn is when you don't label a word as an entity when it is truly is an entity. For those unable to watch the video, the example was:

Sentence: First Bank of Chicago
  True label: ORG ORG ORG ORG
  Model: O ORG ORG ORG

Questions:

*

*In the example, the model's prediction fails to label an entity that is truly an entity. Why is this not considered only a fp?

*Manning states that it is better not to have labeled any of the words as entities rather than naming part of the sequence correctly. Why is this true?

A: (1) That simply depends on the applied evaluation strategy, which should match your application requirements; Strict evaluations (as used, e.g., for the NER tasks in BioCreative) indeed require you find the exact cutoff, and would count your example as both a FP and FN.
(2) Because by only extracting a sub-string, it can become impossible to link the detected mention to the entity's identifier. Just imagine there might be several "Bank[s] of Chicago". (Which therefore explains why we [also] use the strict evaluation mode in BioCreative, in the first place.)
Therefore, depending on your use-case(s), you rather might want to evaluate the following:

*

*your NER system's ability to correctly group the detected strings by entities (if you need to report all mentions found),

*if each mention for a unique entity in the document has a non-strict labeling overlap with the relevant NER detections (if you need to detect/highlight all mentions for your use-case),

*and/or that at least one instance in the string set extracted for a given entity can be properly linked to the entity's official identifier, i.e., your system at least once extracted "First Bank of Chicago" (if you need to link the mentions to some kind of identifier).

This is a far more use-case appropriate approach that we use today (in industry), but I am not sure you can find an academic paper doing NER evaluations that way. But it nicely explains why you might need both strict and non-strict label detection evaluations.
Also, note that most NER evaluation strategies/corpora do not take coreferences ("The bank said...") into account...

A: I'd like to quote from Speech and Language Processing: An introduction to natural language processing:

For named entities, the entity rather than the word is the unit of response.

In your case, the First Bank of Chicago should count as a single response, and it should be predicted as ORG ORG ORG ORG as a whole, otherwise the whole is wrong/false(either false positive or false negative).
If the predicted BIO tags are O B-ORG I-ORG I-ORG, it indicates a boundary error, and the whole is false and then O is false positive and B-ORG I-ORG I-ORG is false negative, two demerits.
However, if the guess tags are O O O O it is just a labeling error and there is only one demerit: one false positive.
In this article: Doing Named Entity Recognition? Don't optimize for F1, Christ Manning stated that the F1 encourages the model to guess all as O if it is not sure because boundary errors and label-boundary errors are more costly.
Side note:
An implementation of entity-level F1 score:  https://github.com/jantrienes/nereval


text:
Q: Android jellybean with Phonegap click not working We are developing a Android Hybrid application using phonegap 3.2.2.
In one of the html page, we are rendering an 'svg' element with 'path' elements inside the svg. Each path element is bind to a click event using the jquery.
The issue we are facing is the "onclick event will not be triggered only for some of the path elements and for rest it is working fine" and also this we are getting only in the devices with Android OS 4.2 and 4.3 (All "Jelly Bean").
If anyone has faced the similar issue, kindly help.
HTML:

<svg width="600" height="634"><g transform="scale(1.3333333333333333) translate(-141.60559099033824, 17.39684462793349)"><path d="M652.71,228.85l-0.04,1.38l-0.46,-0.21l-0.42,0.3l0.05,0.65l-0.17,-1.37l-0.48,-1.26l-1.08,-1.6l-0.23,-0.13l-2.31,-0.11l-0.31,0.36l0.21,0.98l-0.6,1.11l-0.8,-0.4l-0.37,0.09l-0.23,0.3l-0.54,-0.21l-0.78,-0.19l-0.38,-2.04l-0.83,-1.89l0.4,-1.5l-0.16,-0.35l-1.24,-0.57l0.36,-0.62l1.5,-0.95l0.02,-0.49l-1.62,-1.26l0.64,-1.31l1.7,1.0l0.12,0.04l0.96,0.11l0.19,1.62l0.25,0.26l2.38,0.37l2.32,-0.04l1.06,0.33l-0.92,1.79l-0.97,0.13l-0.23,0.16l-0.77,1.51l0.05,0.35l1.37,1.37l0.5,-0.14l0.35,-1.46l0.24,-0.0l1.24,3.92Z" data-code="BD" fill="#B8E186" fill-opacity="1" stroke="none" stroke-width="0" stroke-opacity="1" fill-rule="evenodd" class="jvectormap-region jvectormap-element"/><path d="M429.28,143.95l1.76,0.25l0.13,-0.01l2.16,-0.64l1.46,1.34l1.26,0.71l-0.23,1.8l-0.44,0.08l-0.24,0.25l-0.2,1.36l-1.8,-1.22l-0.23,-0.05l-1.14,0.23l-1.62,-1.43l-1.15,-1.31l-0.21,-0.1l-0.95,-0.04l-0.21,-0.68l1.66,-0.54Z" data-code="BE" fill="#B8E186" fill-opacity="1" stroke="none" stroke-width="0" stroke-opacity="1" fill-rule="evenodd" class="jvectormap-region jvectormap-element"/><path d="M413.48,260.21l-1.22,-0.46l-0.13,-0.02l-1.17,0.1l-0.15,0.06l-0.73,0.53l-0.87,-0.41l-0.39,-0.75l-0.13,-0.13l-0.98,-0.48l-0.14,-1.2l0.63,-0.99l0.05,-0.18l-0.05,-0.73l1.9,-2.01l0.08,-0.14l0.35,-1.65l0.49,-0.44l1.05,0.3l0.21,-0.02l1.05,-0.52l0.13,-0.13l0.3,-0.58l1.87,-1.1l0.11,-0.1l0.43,-0.72l2.23,-1.01l1.21,-0.32l0.51,0.4l0.19,0.06l1.25,-0.01l-0.14,0.89l0.01,0.13l0.34,1.16l0.06,0.11l1.35,1.59l0.07,1.13l0.24,0.28l2.64,0.53l-0.05,1.39l-0.42,0.59l-1.11,0.21l-0.22,0.17l-0.46,0.99l-0.69,0.23l-2.12,-0.05l-1.14,-0.2l-0.19,0.03l-0.72,0.36l-1.07,-0.17l-4.35,0.12l-0.29,0.29l-0.06,1.44l0.25,1.45Z" data-code="BF" fill="#B8E186" fill-opacity="1" stroke="none" stroke-width="0" stroke-opacity="1" fill-rule="evenodd" class="jvectormap-region jvectormap-element"/><path d="M477.63,166.84l0.51,0.9l0.33,0.14l0.9,-0.21l1.91,0.47l3.68,0.16l0.17,-0.05l1.2,-0.75l2.78,-0.67l1.72,1.05l1.02,0.24l-0.97,0.97l-0.91,2.17l0.0,0.24l0.56,1.19l-1.58,-0.3l-0.16,0.01l-2.55,0.95l-0.2,0.28l-0.02,1.23l-1.92,0.24l-1.68,-0.99l-0.27,-0.02l-1.94,0.8l-1.52,-0.07l-0.15,-1.72l-0.12,-0.21l-0.99,-0.76l0.18,-0.18l0.02,-0.39l-0.17,-0.22l0.33,-0.75l0.91,-0.91l0.01,-0.42l-1.16,-1.25l-0.18,-0.89l0.24,-0.27Z" data-code="BG" fill="#B8E186" fill-opacity="1" stroke="none" stroke-width="0" stroke-opacity="1" fill-rule="evenodd" class="jvectormap-region jvectormap-element"/><path d="M468.39,164.66l0.16,0.04l0.43,-0.0l-0.43,0.93l0.06,0.34l1.08,1.06l-0.28,1.09l-0.5,0.13l-0.47,0.28l-0.86,0.74l-0.1,0.16l-0.28,1.29l-1.81,-0.94l-0.9,-1.22l-1.0,-0.73l-1.1,-1.1l-0.55,-0.96l-1.11,-1.3l0.3,-0.75l0.59,0.46l0.42,-0.04l0.46,-0.54l1.0,-0.06l2.11,0.5l1.72,-0.03l1.06,0.64Z" data-code="BA" fill="#B8E186" fill-opacity="1" stroke="none" stroke-width="0" stroke-opacity="1" fill-rule="evenodd" class="jvectormap-region jvectormap-element"/><path d="M707.34,273.57l0.76,-0.72l1.59,-1.03l-0.18,1.93l-0.9,-0.06l-0.28,0.14l-0.31,0.51l-0.68,-0.78Z" data-code="BN" fill="#B8E186" fill-opacity="1" stroke="none" stroke-width="0" stroke-opacity="1" fill-rule="evenodd" class="jvectormap-region jvectormap-element"/></g><g/></svg>
+

−

JQUERY:
$('#world-map').on('click','svg path', function (e) {

    var $this = $(e.target);
    alert($this.is('path'));
});

A: Please remove overflow attribute  from style ,this conflicts with click event in phonegap


text:
Q: Call JSON API from within PHP Cron Job I have a large system with an API.
On the frontend, JavaScript uses AJAX to talk to the API.
I have a PHP file that runs every 5-min as a CRON job.
I want this PHP code to interact with the API.
All it has to submit is query-vars.
All that is sent back is a single number.
For Example:
https://examplesite.com/api/create?id=1&data=2
This replies with a simple number that is the SQL last-insert-id.
EXTRA:
The API also needs two Session variables (user-id and system-id)
Can I just start session and set them before calling the API I guess?
I need the PHP script, ran by the CRON system, to talk to this API.
I have tried using cURL but no luck yet:
        //Need to add a user-id to session, does this work?
        session_start();
        $_SESSION['user-id'] = 1;

        //HOW TO CALL API FROM CRON?
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_URL, 'https://example.com/api/create?id=1&gid=2');
        //curl_setopt($ch, CURLOPT_URL, 'http://example.com/api/create?id=1&gid=2');
        curl_setopt($ch, CURLOPT_URL, 'file://../framework/api/create.php?id=1&data=2');

        $result = curl_exec($ch);
        curl_close($ch);

        $result = str_replace("\n", '', $result); // remove new lines
        $result = str_replace("\r", '', $result); // remove carriage returns

        //Expect Result to be a number only
        file_put_contents("curl.log", "[".date('Y-m-d H:i:s')."] $result\n\n", FILE_APPEND);

The file method doesn't seem to work...  maybe path issue with ../
The http method doesn't seem to work...  server loopback issue?
Any advice on how to best have my PHP CRON robot use my API will be much appreciated.
I have simply copied API code into the CRON, but then I am duplicating code, and not allowing the robot to test the real API.
Thanks.

A: Assuming you still wanted to use a session.  Your first curl should be a request that to a script that will create the SESSION then respond.
I created this get_cookie.php this to test this concept:
<?php
session_start();
$_SESSION['time'] = time();
echo 'Time=' . $_SESSION['time'];
?>

I called this script to get the PHPSESSID from the response cookie
$ch = curl_init('http://example.com/get_cookie.php');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

$skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE));
$head = substr($response,0,$skip);
$data = substr($response,$skip);
$end = 0;
$start = strpos($head,'Set-Cookie: ',$end);
$start += 12;
$end = strpos($head,';',$start );
$cookie = substr($head,$start ,$end-$start );
file_put_contents('cookie.txt',$cookie);
echo "\ncookie=$cookie";
echo "\n$data\n";

RESPONSE:
cookie=PHPSESSID=bc65c95468d08dd02cc5ab8ab87bbd39
Time=1664237484

The CRON job URL, session.php:
<?php
session_start();
echo 'Time=' . $_SESSION['time'];
?>

This is the CRON job script.
$cookie = file_get_contents('cookie.txt');
$ch = curl_init('http://example.com/session.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, $cookie );
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
echo $response;

RESPONSE:
Time=1664237484

The result "Time" ($_SESSION['TIME']) is always the same as the time from the get_cookie.php.

A: Thanks for the help, but in the end my alternate approach will be easiest and work best.  Here is the answer for others in need...
To have an external PHP (run via CRON) test an internal PHP API (that the frontend JavaScript usually talks to via AJAX), this is the easiest solution, including passing query-variables and session-vars.
STEP 1:  Don't worry about start_session() or passing any query variables, just add what you need to the arrays ahead of time.
STEP 2:  Capture the output buffer and simply include the PHP API file:
        $_SESSION['user-id'] = ' works! ';
        $_REQUEST['var']     = ' too ';

        ob_start();
        include '/var/www/sitename.com/framework/api/create.php';
        $result = ob_get_contents();
        ob_end_clean();

        file_put_contents("/var/www/sitename.com/cron/curl.log", "[".date('Y-m-d H:i:s')."] Result: $result\n\n", FILE_APPEND);

        /* OUTPUT in curl.log:
        [2022-09-26 22:30:01] Result:  works! / too
        */

        /* create.php API
        $user = $_SESSION['user-id']??' did not work ';
        $req  = $_REQUEST['var'    ]??' novar ';
        echo $user.'/'.$req;
        */

(obviously the CRON has to be on the same server as the website/api, otherwise you will have to use cURL with Cookie/Session/QueryVar-Arrays)


text:
Q: C# Reports tablix keeps pushing controls under it Hello i have a problem with tablix in reports. I have a report with image (template) and in that image i have tablix and under it some textboxes with other data.
I put tablix into Rectangle (tablix has parent connection to that rectangle), but my textboxes below are still getting pushed down by expanding tablix.
It also expands my rectangle that cointains tablix as you can see in the images below.
1st image
2nd image
Any idea why this keeps happening even when i used rectangles as containers?
Thanks for any advices.


text:
Q: Is there other ways of passing a php $_GET variable from url to a js variable?
Possible Duplicate:
Get query string values in JavaScript

I know you could do this by echoing the variable $_GET['whatevervariable'] to a js variable.i was just wondering if there are other methods that can also do this?

A: This will provide the entire $_GET array to your JavaScript app:
<script type="text/javascript"><!--
_GET = <?php echo json_encode($_GET); ?>;
--></script>

A: The $_GET superglobal is just an array of the querystring.
You can fetch the querystring in javascript with window.location.search, but to use it like $_GET will need some sort of parsing and usually a few regular expressions to handle difficult characters etc.
Just try var qs = window.location.search; and then figure out exactly what you need, and how you will get it.
The easy solution if doing it inline is just echoing $_GET into a variable, like in danorton's answer.


text:
Q: Excel 2013 - formula to hide a series in a chart based on cell value Is it possible to hide a series in a chart automatically depending on another cell's value.
Edit:
I am building a dashboard for social media analytics with charts for different metrics (impressions, engagements, etc.). I would like to allow the chart to be formatted (show different values, i.e. hide Twitter) based on the value in a drop down menu in the top column that will allow you to select and view metrics for either Twitter, LinkedIn, or both at the same time.
Example showing Impressions chart for Twitter & LinkedIn when dropdown selected should only be showing Twitter data in Q2:

Right now, my back end has the static data for each platform for the year, and then smaller 3x3 tables with data from only the months that are in the quarter selected. The charts are built using this dynamic table.
I can hide a chart using macros, but the problem is that I'll have to create and include 3 separate charts (Twitter, LinkedIn, Both) instead of using just the one in that image that shows both, and hiding the series that is not selected.
To make this worse, I also have a feature that compares to the previous quarter results, so that would mean 3 more charts, for a total of 6, which will just weigh down the spreadsheet and create more work to build and format.
Open to any suggestions on how to have 1 chart that will dynamically hide either Twitter or LinkedIn when the dropdown menu is changed.
My closest solution is dynamically changing LinkedIn values to 0 when Twitter is selected, but this causes the bar graph to be off center from the label - it's minor, but still looking for a better solution.

A: Assuming you chart is something like this:

*

*Select cell A1

*Click to Data -> Sort & Filter -> Filter your chart should now look like this:

*Use the dropdowns at the top to filter out whatever series you want.

The chart should automatically stop displaying the hidden series

If it still displays the series, right click on the chart an choose "Select Data" from the dropdown menu, then click on "Hidden and Empty Cells in the resulting dialog box and make sure "Show data in hidden rows and columns is unchecked:


text:
Q: Use bit.dev on codesandbox Someone know how to use a bit.dev component on a codesandbox or stackblitz?
I have added it to the package.json but it still doesn't work
Here is the codesandbox for test

A: bit.dev is going to add a 'publish to npm' step in their tag/export.
For components without publishing, I'm hoping codesandbox will allow more repositories :)


text:
Q: Define constant and use in Excel 2010 formula A quick question. What would be the Excel 2010 equivalent of the programming define
#define YES 1
#define NO 0

So if I enter in a cell =YES+YES+NO for example, it return 2.
Thanks!

A: Concerning equivalency to #define, I can't say.
BUT
If the goal is to sum YES+NO entries you might try
Function addYesNo(rng As Range)
 Dim x As String
 x = Replace(Replace(rng, "YES", 1), "NO", 0)
 addYesNo = Evaluate("=SUM(" & x & ")")
End Function

A: That would be ugly, but you can put those values in cells and then make named ranges that point to those cells. Then you can just reference the named ranges in your formulas.


text:
Q: Batch UPDATES sleep(10) Im writing an update statement that affects a number of rows in one table on my database.
To accomplish this, I want to break that up into manageable chunks.
Initially, I thought using CONCAT would help,
SELECT CONCAT("UPDATE table SET foo=bar WHERE ID=", id, ";") FROM
I want to batch all these up, otherwise there will potentially cause replication lag. Preferably with do sleep(10); in between each batch
How can I accomplish this? How can I do sleep (10) between queries?
My queries right now look like this:
UPDATE table SET created_at = NOW() WHERE id IN (?,?,?...);

A: Resolved
Adding DO SLEEP(10) before each UPDATE is what I needed

A:
How can I do sleep (10) between queries?

Simply add SELECT SLEEP(10); between your queries.
https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_sleep


text:
Q: What is the fluent object model to make this work? As practice for writing fluent APIs, I thought I'd make the following compile and run:
static void Main(string[] args)
{
    Enumerable.Range(1, 100)
        .When(i => i % 3 == 0).Then(i => Console.WriteLine("fizz"))
        .When(i => i % 5 == 0).Then(i => Console.WriteLine("buzz"))
        .Otherwise(i => Console.WriteLine(i))
        .Run();

    Console.ReadLine();
}

The idea is .When will test each element in the enumeration, and if it passes the predicate, to have the action run.  If the predicate fails, the item is passed down the chain.
The graph I came up with was:
public static class EnumerableExtensions
{
    public static IConditionalEnumerable<T> When<T>(this IEnumerable<T> items, Predicate<T> test, Action<T> action)
    {
    }

    public static IResolvedEnumerable<T> Then<T>(this IConditionalEnumerable<T> items, Predicate<T> test, Action<T> action)
    {
    }

    public static void Run<T>(this IEnumerable<T> items)
    {
        foreach (var item in items) ;
    }
}

public interface IConditionalEnumerable<T> : IEnumerable<T>
{
    IResolvedEnumerable<T> Then<T>(IConditionalEnumerable<T> items, Action<T> action);
}

public interface IResolvedEnumerable<T> : IEnumerable<T>
{
    IEnumerable<T> Otherwise(Action<T> behavior);
}

I am running into an issue -- When can't foreach / yield return inside of it, because the return type isn't directly IEnumerable<T> (although it inherits from it).  That has thrown a mental wrench into the gears.  What would the implementation of the extension methods look like?

A: Here is my attempt. I renamed the interfaces just for my understanding as I hacked it together.
public interface IWhen<T> {
    IThen<T> Then(Action<T> action);
}

public interface IThen<T> : IRun {
    IWhen<T> When(Func<T, bool> test);
    IRun Otherwise(Action<T> action);
}

public interface IRun {
    void Run();
}

public interface IRule<T> {
    Func<T, bool> Predicate { get; }
    Action<T> Invoke { get; }
}

And created the following implementations.
public class Rule<T> : IRule<T> {
    public Rule(Func<T, bool> predicate, Action<T> action) {
        this.Predicate = predicate;
        this.Invoke = action;
    }
    public Func<T, bool> Predicate { get; private set; }
    public Action<T> Invoke { get; private set; }
}

public class Then<T> : IThen<T> {
    private Queue<IRule<T>> rules = new Queue<IRule<T>>();
    private IEnumerable<T> source;

    public Then(IEnumerable<T> source, Queue<IRule<T>> rules) {
        this.source = source;
        this.rules = rules;
    }

    public IWhen<T> When(Func<T, bool> test) {
        var temp = new When<T>(source, test, rules);
        return temp;
    }

    public void Run() {
        foreach (var item in source) {
            var rule = rules.FirstOrDefault(r => r.Predicate(item));
            if (rule == null) continue;
            rule.Invoke(item);
        }
    }

    public IRun Otherwise(Action<T> action) {
        var rule = new Rule<T>(s => true, action);
        rules.Enqueue(rule);
        return new Then<T>(source, rules);
    }
}

public class When<T> : IWhen<T> {
    private Queue<IRule<T>> rules;
    private Func<T, bool> test;
    private IEnumerable<T> source;

    public When(IEnumerable<T> source, Func<T, bool> test, Queue<IRule<T>> rules = null) {
        this.source = source;
        this.test = test;
        this.rules = rules ?? new Queue<IRule<T>>();
    }

    public IThen<T> Then(Action<T> action) {
        var rule = new Rule<T>(test, action);
        rules.Enqueue(rule);
        var then = new Then<T>(source, rules);
        return then;
    }
}

The extension method then looked like this to get started.
public static class EnumerableExtensions {
    public static IWhen<T> When<T>(this IEnumerable<T> source, Func<T, bool> test) {
        var temp = new When<T>(source, test);
        return temp;
    }
}

And with that the following example in .Net Fiddle
public class Program {
    public static void Main() {
         Enumerable.Range(1, 10)
              .When(i => i % 3 == 0).Then(i => Console.WriteLine("fizz"))
              .When(i => i % 5 == 0).Then(i => Console.WriteLine("buzz"))
              .Otherwise(i => Console.WriteLine(i))
              .Run();
    }
}

produced
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz

A: Don't worry about sequences. Just do it on values.
You can do this entirely with extension methods. Here's the thing:

*

*Somehow Otherwise needs to know whether any previous Then executed.

*Therefore somehow every When needs to know whether every previous Then executed.

*Every Then needs to know whether the previous When was true or false.

Here's the skeleton:
static class X
{
    public enum WhenState { DoIt, DoNot }
    public enum ThenState { DidIt, DidNot }
    public static (T, ThenState) Begin<T>(this T item) { ... }
    public static (T, WhenState, ThenState) When<T>(
      this (T item, ThenState then) tuple,
      Func<T, bool> p) { ... }
    public static (T, ThenState) Then<T>(
      this (T item, WhenState when, ThenState then) tuple,
      Action<T> a) { ... }
    public static void Otherwise<T>(
      this (T item, ThenState then) tuple,
      Action<T> a) { ... }

Once you implement those extension methods then you can do:
3.Begin().When(x => x % 3 == 0).Then( ... )

and so on.
Once you've got that implemented then it is easy to lift the operation to sequences. We have a device which turns values into actions; what is a device which turns a sequence of values into a sequence of actions?  It is built in to the language: foreach(var item in items) item.Begin()....
Similarly, it is easy to lift the operation to any other monad. Say, nullable. We have a device which turns values into actions. What is a device to turn a nullable value into an action, or no action?  It is built into the language:  x?.Begin()...
Say you wish to apply your operation to a Task<int>; what is a device which turns a future value into a future action? async Task DoIt(Task<T> task) { (await task).Begin()....
And so on. Implement your operation on values, not on lifted values; use the built-in lifting operations of the language to apply your operation to the lifted value to produce a lifted action.


text:
Q: AVAudioPlayer Not playing Mp3 File I tried But no luck Hi I am using below code to play my local mp3 file. but no error came. but mp3 is not playing.
AVAudioPlayer  *audioPlayer ;
NSString *sound_file;
if ((sound_file = [[NSBundle mainBundle] pathForResource:@"mpthreetest" ofType:@"mp3"])){

    NSURL *url = [[NSURL alloc] initFileURLWithPath:sound_file];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    audioPlayer.delegate = self;

    [audioPlayer prepareToPlay];
    [audioPlayer play];

}

A: Check Following steps.

*

*Your AppDelegate.m
#import <AVFoundation/AVAudioSession.h>`<AVFoundation/AVAudioSession.h>

*Your application:didFinishLaunchingWithOptions: method
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
}

*In Your ViewController.h
@property (nonatomic,retain) AVAudioPlayer  *audioPlayer ;

*In Your ViewController.m
@synthesize audioPlayer;

Then
NSString *sound_file;
if ((sound_file = [[NSBundle mainBundle] pathForResource:@"mpthreetest" ofType:@"mp3"])){

    NSURL *url = [[NSURL alloc] initFileURLWithPath:sound_file];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    audioPlayer.delegate = self;

    [audioPlayer prepareToPlay];
    [audioPlayer play];
}

The mistake you did is that you did not set Property.


text:
Q: Using functions for creating an index in MongoDB? I have a blog that allow users to vote for articles. The documents of an article looks like:
{
  title: "title of post",
  body: "text text text text text text",
  votes: [
    {user: "user1",  points:  2},
    {user: "user13", points:  1},
    {user: "user30", points:  1},
    {user: "user2",  points: -1},
    {user: "user51", points:  3},
  ],
  sum_of_votes: 6
}

I'd like to sort by the number of votes the post received. At the moment I added a field sum_of_votes that needs to be updated every time somebody voted. Since votes already contains the raw-data for sum_of_votes I thought there might be a more elegant way. I came up with two ideas:

*

*Using a function while creating an index, for example:
db.coll.ensureIndex({{$sum: votes.points}: 1})

*Having a dynamic field. The document could look like this:
{
  title: "title of post",
  body: "text text text text text text",
  votes: [
    {user: "user1",  points:  2},
    {user: "user13", points:  1},
    {user: "user30", points:  1},
    {user: "user2",  points: -1},
    {user: "user51", points:  3},
  ],
  sum_of_votes: {$sum: votes.points}
}

In those cases I only had to update the votes-array. Is something like this possible in MongoDB?

A: Depending on how you do the update on the votes array, either as updating the document by inserting a new vote in the votes array or updating an existing vote, an approach you could take is use the $inc operator on the sum_of_votes with the value you are using to update the votes.points with. For example, in the case where you are inserting a new vote for a user with value in variable userId and the actual vote points in variable points (which must be a number), you could try:
db.articles.update(
    {"_id" : article_id},
    {
        "$addToSet": {
            "votes": {
                "user": userId,
                "points" : points
            }
        },
        "$inc": { "sum_of_votes": points }
    }
)

And you will need to factor in Neil Lunn's point where you wouldn't want the same user to vote more than once in your updates.


text:
Q: dplyr::select - programatically rearrange columns using character variable for column name I want to re-arrange the columns of a df using dplyr::select programatically
A non R user is going to execute the code and this person will provide two inputs as follows:
report.month <- "Jul"
report.year  <- 2017

Only the month will change, all other names in the df will be the same
df that I want to re-arrange looks as follows:
df1 <- data.frame(
     country = "AU",
    Jul_2017 = 500,
    Customer = "some guy")

This is the output that I want
  country Customer Jul_2017
       AU some guy      500

This is what I tried, which does not work and I have run out of ideas:
    reporting.month.name <- as.symbol(paste(report.month, report.year, sep = "_"))

    df1 %>% select(country, Customer, reporting.month.name)
Error: `reporting.month.name` must resolve to integer column positions, not a symbol

Any advice/help is very much appreciated

A: Remove the as.symbol() from your code, like this:
reporting.month.name <- paste(report.month, report.year, sep = "_")

df1 %>% select(country, Customer, reporting.month.name)

Output:
  country Customer Jul_2017
1      AU some guy      500


text:
Q: Apache 2.4 - Forbidden: You don't have permission to access / on this server I've been trying to find a solution to this but with no avail.
I'm using wamp and running apache 2.4. Whenever I try to access a document located in my www/drupal/website directory I get that Forbidden error.
My httpd.conf file had the following configuration:
<Directory />
    AllowOverride none
    Require all denied
</Directory>

#   onlineoffline tag - don't remove
    Require local
</Directory>

I changed it to the below but I had no luck in making it work.
<Directory />
    #Options FollowSymLinks
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Require all granted
</Directory>

#   onlineoffline tag - don't remove
    Require all granted
</Directory>

I have tried the below as well - same result:
<Directory />
    #Options FollowSymLinks
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Order deny,allow
    Allow from all
</Directory>

I have also tried to modify the vhosts.conf. My default settings were: (I do not know why I have that twice)
<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot "c:/Apache24/docs/dummy-host.example.com"
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error.log"
    CustomLog "logs/dummy-host.example.com-access.log" common
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "c:/Apache24/docs/dummy-host2.example.com"
    ServerName dummy-host2.example.com
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

I have tried changing the first vhost tags to:
<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot "d:/wwwRoot/file"
    SetEnv APPLICATION_ENV "development"
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error.log"
    CustomLog "logs/dummy-host.example.com-access.log" common
</VirtualHost>

Any idea what I might be doing wrong?
Many thanks,
Vlad.


text:
Q: fetch all elements dom jquery I have 2 classes and I want to fetch them all in the DOM of a page to compare their content text with jQuery. I believe that in JS it is something like:

function myFonction() {
  var item = document.getElementsByClassName("title")[0];
  if (item) {
    for (var i = 0; i < document.getElementsByClassName("title2").length; i++) {
      var content = document.getElementsByClassName("title2")[i].innerHTML.trim();
      if (content == item.innerHTML.trim()) {
        console.log("OK");
      }
    }
  }
}
myFonction();

A: Since you have tagged jQuery in your answer, I will provide a jQuery-based solution. Things are a little more straightforward because you don't need to make messy for loops.
What you want to do is:

*

*Cache/store the inner HTML of the first occurring .title element

*If the .title element exists, iterate through all .title2 elements and compare their inner HTML against the cached one in point #1

I have provided a proof-of-concept example below. Matching elements are highlighted in yellow simply for visual indication.

$(function() {
  var compareTitle = function() {
    var $title = $('.title').first(),
        titleContent = $title.html().trim();

    if ($title.length) {
      $('.title2').each(function() {
        if ($(this).html().trim() === titleContent) {
          console.log('OK');
          $(this).css('background-color', 'yellow');
        }
      });
    }
  }
  compareTitle();
});

This is a title.

This is not a title.

This is not a title.

This is not a title.

This is a title.

This is not a title.

This is not a title.

This is a title.

This is not a title.

This is not a title.

This is not a title.

This is not a title.

If you want it in native JS, that is also not a problem. It's just a bit hairier when doing the for loops ;) also, you can always leverage document.querySelectorAll().

var compareTitle = function() {
  var title = document.querySelectorAll('.title')[0],
      titleContent = title.innerHTML.trim();

  if (title) {
    var title2 = document.querySelectorAll('.title2');
    for (var i=0; i<title2.length; i++) {
      if (title2[i].innerHTML.trim() === titleContent) {
        console.log('OK');
        title2[i].style.backgroundColor = 'yellow';
      }
    }
  }
}
compareTitle();

This is a title.

This is not a title.

This is not a title.

This is not a title.

This is a title.

This is not a title.

This is not a title.

This is a title.

This is not a title.

This is not a title.

This is not a title.

This is not a title.

A: use .getElementsByClassName for each class. Iterate over the .get results and just do if groupA[i] == groupB[i] then do whatever. If you too lazy let me frikin do it for you for a "point". lol