text:
Q: How to get all matching items from a array of objects in MongoDB? I have a mongo document like below
{
    "_id" : ObjectId("588adde40fcbbbc341b34e1c"),
    "title" : "Fifa world cup",
    "tags" : [
        {
            "name" : "Football",
            "type" : "Sports"
        },
        {
            "name" : "World cup",
            "type" : "Sports"
        },
        {
            "name" : "Fifa",
            "type" : "Manager"
        }
    ]
}

I wrote the below query to get all the tags with type Sports but I am only getting 1 item instead of 2
db.collection.find(
{
    tags:
    {
        $elemMatch:
        {
                type: "Sports"
        }
    }
},
{
    "tags.$" : 1
})

Is it possible to get all the matching items? What I am missing here?

A: You can use aggregation:
db.collection.aggregate([
{
    $unwind : "$tags"
},
{
    $match : {
        "tags.type" : "Sports"
    }
},
{
    $group : {
        _id : "$_id",
        tags : {$addToSet : "$tags"}
    }
}
])


text:
Q: Calling overridden method in multiple derived ViewModels I'm struggling with a somehow unusual Mvvm implementation. I have a multi-page app where I need to access some properties in multiple views and make sure changes in one view are updated in all of them. I try to achieve this by the following implementation:
public class BaseViewModel : ViewModelBase
{
    public string SharedProperty
    {
        get=>BaseModel.sharedProperty;
        set
        {
            if(CustomSet(ref BaseModel.sharedProperty, value, SharedRaise))
                ReloadStuff();
        }
    }
    public abstract void ReloadStuff();
    public void SharedRaise(string caller) => RaisePropertyChanged(caller);
    private bool CustomSet<T>(ref T prop, T value, Action<string> raise, [CallerMemberName] string caller)
    {
        if ((prop == null && value == null) || (prop != null && prop.Equals(value)))
            return false;

        prop = value;
        raise.Invoke(caller);

        return true;
    }
    public static class BaseModel
    {
        public static string sharedProperty;
    }
}

public class Child1ViewModel : BaseViewModel
{
    private string someData;
    public string SomeData
    {
        get=>someData;
        set=>Set(ref someData, value);
    }
    public override void ReloadStuff()
    {
        SomeData = GetNewData();
    }
}

public class Child2ViewModel : BaseViewModel
{
    private string someOtherData;
    public string SomeOtherData
    {
        get=>someData;
        set=>Set(ref someOtherData, value);
    }
    public override void ReloadStuff() { } //Do nothing, better would be to remove the overriden method in Child2ViewModel at all
}

The desired behavior should be as followed:
When changing the property SharedProperty from Child2View, the method RaisePropertyChanged ("SharedProperty") should be called on any active instance derived from BaseViewModel. Also, every overridden method of ReloadStuff() in any instance derived from BaseViewModel should be called.
Sadly for now, this does not work, but for now, I hope that I only miss something, rather than all of this is rubbish. Any help would be highly appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write QT system tray app without a window class, and integrate it with another process? Here is my setup:

*

*A background process that keeps running and does it's job.

*A launcher which launches the aforementioned process and monitors it, relaunches it if crashed or killed.
I wish to add a system tray access to the launcher process (and the launcher process ideally will contain code for system tray display) and enable basic options (start, stop etc) to be triggered from the system tray context menu. The system tray does not need a window of it's own. Just a windowless system tray with a Context menu that contains 2-3 options.
Since the all code written so far is in C/C++ and I need it to run on Windows and Linux, QT comes across as obvious choice. I have found it quite frustrating to get past basic QT launcher tray display. Nearly every example I have seen of QSystemTrayIcon includes a 'mainwindow' inheritance.
Below is the code I am using to create system tray.
#include <QtWidgets/QApplication>
#include <QtCore/QDebug>
#include <QtGui/QIcon>
#include <QtWidgets/QSystemTrayIcon>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QPixmap oPixmap(32,32);
    //QMenu* menu1 = new QMenu(); // want to get a context menu from system tray
    oPixmap.load ("systemTrayIcon.png");

    QIcon oIcon( oPixmap );

    QSystemTrayIcon *trayIcon = new QSystemTrayIcon(oIcon);
    qDebug() << trayIcon->isSystemTrayAvailable();
    trayIcon->setContextMenu( menu1);
    trayIcon->setVisible(true);
    trayIcon->showMessage("Test Message", "Text", QSystemTrayIcon::Information, 1000);

    return app.exec();
}

The code displays system tray alright, but I haven't been able to get around on how to add menus to it. What I want is:
1) Add the context menu to the system tray above without adding any window class (unless that is not possible)
2) Connect those context menu items to functions in my existing code
3) The app.exec() seems to be an infinite loop that processes QT events. However, since my launcher has it's own event loop, I want to make it so that the QT event loop is integrated with my launcher loop. In other words, add some non-QT tasks to the event loop.

A: Given the clarification from the comments, you have a couple of options on how to get code called for context menu or activation actions.

*

*A receiver object: basically what the examples where using, just that you don't derive your receiver class from any window type.
For macro based signal/slot connections, the base type needs to be QObject or something derived from that, for function pointer based connect it can be any class
class MyReceiver : public QObject
{
    Q_OBJECT
public slots:
    void onActivated(QSystemTrayIcon::ActivationReason reason);
};

// in main()
MyReceiver receiver;

// macro based connect
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
        &receiver, SLOT(onActivated(QSystemTrayIcon::ActivationReason)));

// or function pointer based connect
connect(trayIcon, &QSystemTrayIcon::activated,
        &receiver, &MyReceiver::onActivated);

*Connect to stand-alone functions
void onActivated(QSystemTrayIcon::ActivationReason reason);

connect(trayIcon, &QSystemTrayIcon::activated, &onActivated);

*With a C++11 capable environment, connect to a lambda
connect(trayIcon, &QSystemTrayIcon::activated,
        [](QSystemTrayIcon::ActivationReason reason) {});

For the context menu the same techniques apply, the "sender" objects are the QAction items you add to the menu and their signal is triggered() or toggled(bool) depending on whether the action can be just clicked or toggled between and "on" and "off" state.


text:
Q: Lightning combobox options attribute not showing any options! I am trying to populate the options attribute of the lightning combobox to the values of a component attribute. The channels component attribute has all the values in it, but for some reason it doesn't show up on the combobox. Please advise! Here is the code below:
<aura:attribute name="channels" type="sumchans__Channels__c[]"/>
<lightning:combobox name="channelsCombobox" placeholder="Select channel" options="{! v.channels.Name }" value="{! v.channelName }" variant="label-hidden"/>

A: You're trying to access an attribute that doesn't exist. options must be a list of value-label pairs. You'll need to set up the values in a separate list:
<aura:attribute name="channelOptions" type="Object[]" />

...
var channelOptions =
  component
  .get("v.channels")
  .map(function(channel) { return { value: channel.Id, label: channel.Name } });
component.set("v.channelOptions", channelOptions);


text:
Q: Write column data from csv in to a line / row in a text file im working in a script to read a .csv file , read an specific column and write it in a txt file, the problem is, that the extracted data is written in a column, in this form:
primary_channel
2
1
0
0
2
0
1
2
1

and i need it in a line,like this:
2,1,0,0,2,0,1,2,1

my code is the next,
import sys
import csv
import copy
import os
import random
import fileinput
import sys, glob
from io import StringIO
from collections import OrderedDict
import sys
#scriptname,f1name,f2name=sys.argv

fieldnames=['node_code;node_type;wlan_code;destination_id;x(m);y(m);z(m);primary_channel;min_channel_allowed;max_channel_allowed;cw;cw_stage;tpc_min(dBm);tpc_default(dBm);tpc_max(dBm);cca_min(dBm);cca_default(dBm);cca_max(dBm);tx_antenna_gain;rx_antenna_gain;channel_bonding_model;modulation_default;central_freq (GHz);lambda;ieee_protocol;traffic_load(pkts/s)']

main={}
with open('nodos_cambiados_1.csv','r') as infile,open('lista.txt','w') as outfile:
     reader = csv.DictReader(infile,delimiter=";" )
     writer = csv.DictWriter(outfile,fieldnames=['primary_channel'],delimiter=",",extrasaction='ignore')
     writer.writeheader()
     for row in reader:
         next(reader)
         for values in row:
             if row['node_type']=='0' in row:
                main.update({row['primary_channel']:()})

         writer.writerow(row)

I will be very grateful for the help you can give me

A: In the call to DictWriter, try adding newline=''. As the documentation notes:

Any other optional or keyword arguments are passed to the underlying writer instance.

A: Using DictWriter seems like overcomplicating things, if you just want to write numbers on a row. I think something like this will suffice:
with open('nodos_cambiados_1.csv','r') as infile,open('lista.txt','w') as outfile:
     reader = csv.DictReader(infile,delimiter=';')
     outfile.write(','.join(row.get('primary_channel') for row in reader))


text:
Q: Write file to web application context folder I have a web application running on tomcat. I upload a file to the server using commons-fileupload and commons-io (The apache libraries). The file that i upload is stored in temporary folder somewhere around the system ( i have the path). I want to copy that file to a file within the webapp (context) folder because i need it related to the application, but not the architecture, operation system and etc. So far i know the path to the temporary file.
 ServletFileUpload servletFileUpload = new ServletFileUpload();
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        DiskFileItemFactory factory = new DiskFileItemFactory();

// Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

// Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

// Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);
            System.out.println(items);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

This is what i got in my servlet so far


text:
Q: Get directory path n deph long of a given root path I am looking for a better/safer/more elegant generic method that could give me an n depth long directory from a given path.
I've created something that works but it based on string parsing so I hope you could find a better solution. The method could use a directory info for passed/returned values as well.
public static string GetDirectoryNDepth(string root, string target, int depth)
    {
        string[] splittedRoot = root.Split('\\');
        string[] splittedTarget = target.Split('\\');

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < splittedTarget.Length; i++)

            if (i < splittedRoot.Count() + depth)
                sb.Append(String.Format("{0}\\", splittedTarget[i]));
            else
                break;

        return sb.ToString();
    }

Sample values:
        //For 3 depth long parametr it should return expected value
        //First case filepath
        string root = @"C\Desktop\temp\MSC\IH";
        string target = @"C:\Desktop\temp\MSC\IH\FirstLevel\SecondLevel\ThirdLevel\dsf - Copy (2).xml";
        string expected = @"C:\Desktop\temp\MSC\IH\FirstLevel\SecondLevel\ThirdLevel";

        //Second case target shorter then depth
        string root = @"C\Desktop\temp\MSC\IH";
        string target = @"C:\Desktop\temp\MSC\IH\FirstLevel\SecondLevel";
        string expected = @"C:\Desktop\temp\MSC\IH\FirstLevel\SecondLevel";

A: From your comment, instead of using \ as the separator, you can use Path.DirectorySeparatorChar instead like this
public  string GetDirectoryNDepth(string root, string target, int depth)
{
    string[] splittedRoot = root.Split(Path.DirectorySeparatorChar);
    string[] splittedTarget = target.Split(Path.DirectorySeparatorChar);

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < splittedTarget.Length; i++)

         if (i < splittedRoot.Length + depth)
            sb.Append(String.Format("{0}{1}", splittedTarget[i], Path.DirectorySeparatorChar));
         else
            break;

    return sb.ToString();
}

From the Path.DirectorySeparatorChar doc:

Provides a platform-specific character used to separate directory
  levels in a path string that reflects a hierarchical file system
  organization...
...The value of this field is a slash ("/") on UNIX, and a backslash
  ("\") on the Windows and Macintosh operating systems.

A: I found input set very particular that root doesn't start with C: it is C\
don't know whether it is purposefully like that
string root = @"C\Desktop\temp\MSC\IH";
string target = @"C:\Desktop\temp\MSC\IH\FirstLevel\SecondLevel\ThirdLevel\dsf - Copy (2).xml";
string expected = @"C:\Desktop\temp\MSC\IH\FirstLevel\SecondLevel\ThirdLevel";

Based upon input sample & code this would be efficient code
    public static string GetDirectoryNDepth(string root, string target, int depth)
    {
        var separatorChar = Path.DirectorySeparatorChar;

        int rootSlashCount = root.Split(separatorChar).Length;
        int totalSlashCount = rootSlashCount + depth;

        var iCnt = root.Length;
        while(iCnt < target.Length  && rootSlashCount <= totalSlashCount)
        {
            if (target[iCnt] == separatorChar)
                rootSlashCount++;
            iCnt++;
        }

        var retVal = target.Substring(0, iCnt);
        if (retVal.EndsWith(separatorChar+"") == false)
            retVal += separatorChar;
        return retVal;

    }


text:
Q: In bash, is there a way I can make shorter (if or) statements? if [ foo = bar -o foo = car -o foo = jar -o foo = foo ]
  then
    echo yes
fi

To keep things more organized, I would like to try to match it to a list, such as
if [ foo = {bar,car,jar,foo} ] ; then

Obviously the curly brace expansion method didn't work or else I wouldn't be here!
But I would like to know if something like this is possible at all.

A: Even shorter:
[[ $foo =~ ^([bcj]ar|foo)$ ]] && echo yes

This way $foo is matched against a regex either starting with b, c or j followed by ar or matching exactly foo.
This uses the && operator as a short-circuit to run echo yes only if the [[ $foo =~ ^([bcj]ar|foo)$ ]] expression evaluates to true.
If this is too compact in order to be read with ease, you can still use the full if construct, which does exactly the same but is more readable:
if [[ $foo =~ ^([bcj]ar|foo)$ ]]
then
    echo yes
fi

A: It looks like a bug in your code, but we can refactor it down really small...
If you had really written your expression with [ foo = bar -o foo = car -o foo = jar -o foo = foo ], then it could've been simplified to:
echo yes

This test is always true because foo = foo is always true, which in turn is because the literal string foo is always the same as itself.
Though you've clarified this syntax didn't appear in code you were really using, I've kept this introductory section as it's a common mistake to do so, especially among novices. Attempting to check the value of foo this way doesn't work in any Bourne-style shell--to examine the value of a variable with [, you must perform parameter expansion with $ (see below). This particular aspect of the problem is not shell-specific; for example, here's a test in 7 Bourne-style shells.
Fixing the Original Code
Perhaps instead you meant to check the value of the foo variable (i.e., its contents, rather than its name) against those strings. In that case, your original code would become like:
if [ "$foo" = bar -o "$foo" = car -o "$foo" = jar -o "$foo" = foo ]; then
    echo yes
fi

This can be shortened slightly with the short-circuit && operator:
[ "$foo" = bar -o "$foo" = car -o "$foo" = jar -o "$foo" = foo ] && echo yes

But it's still longer and more complicated and repetitive than you probably prefer. So, moving on...
Shorter Forms via Pattern Matching
You can use the [[ facility's built-in regular expression matching operator:
[[ $foo =~ ^(bar|car|jar|foo)$ ]] && echo yes

While using case is probably the most common way, [[ with =~ is:

*

*the same length as a compact use of case (see below)

*arguably truer to the logic of your original code, in that it uses [[, which works much like a test expression.

So you might prefer that. It's the method I would probably use, to do this in bash.
If you wanted to do something like that but match using grep instead of [[ with =~, this is similar:
grep -Eq '^(bar|car|jar|foo)$' <<< "$foo" && echo yes

Or this:
grep -Fqe{bar,car,jar,foo} <<< "$foo" && echo yes

A One-Liner with case
As Serg says, can be simplified using case instead of if and [. That's the classic and probably the most common way.
The method in Serg's answer works perfectly well, but for the particular code you're refactoring, we can write something simpler, by using only one pattern for case. There is no need to have a catch-all *) match at the end. If the string doesn't match any of the patterns, control simply falls through the case construct and no commands are executed, which is equivalent to your if construct with no else.
case $foo in bar|car|jar|foo) echo yes;; esac

That makes it short and simple enough to easily fit--and be readable--on a single line (which seems to be what you're looking for). This method is also portable to Bourne-style shells other than bash.

A: I suggest using case structure. Something like:
case $foo in
    foo|car|bar|jar) echo yes ;;
    *) ;;
esac

If you like, you can add a command between *) and ;; to be executed when $foo doesn't match foo, car, bar, or jar. For example, you could print a message with echo 'wrong input' or something like that.


text:
Q: Story about a designer baby I'm trying to remember a story about a couple who have a designer baby.
The story is written in the first person as a series of letters or possibly e-mails from the baby's mother to a friend. It starts quite innocently with the mother saying how great it is that genetic diseases can be eliminated before birth. However, with subsequent letters it becomes clear that the baby is being treated as a pet or plaything rather than a human being. For example, the parents have the baby treated to retard growth so they can have a cute baby for longer rather than a stroppy two year old.
It's a horrifying story because the callousness of the parents only becomes apparent gradually. It's only towards the end you realise how appalling the situation is.
I read this in an anthology, and it was in the last thirty years. However I'm afraid I can't remember anything else about it. I was reminded of the story by the question A short story about baby on/off switch and it's possible it's the same story. However I don't remember anything about an on-off switch in the story I'm thinking of.

A: "Pursuit of Excellence" by Rena Yount is about two parents who already have a natural child and want to engineer the second.  But considering the costs, the parents eventually become divided on what extent they'll go to make it happen.  The story plays out the pros and cons of engineered children in this future society through a series of scenes (not letters).  It includes discussion with a sister, but again, not in letter format.  Sounded very similar to what you were describing, and I first read it in an anthology SCIENCE FICTION, SCIENCE FACT, AND YOU.

A: Peter Hamilton's pithy "The Forever Kitten" is not a story of letters, but is told in the first person. It uses many of the same themes you are talking about. The story is available on line from Nature


text:
Q: Dark matter annihilation cross section What is the meaning of upper limit of annihilation cross section? Sometimes I have seen that $\langle\sigma v\rangle = 3.0 \times 10^{-26}\,{\rm cm}^{3}\,{\rm s}^{-1}$ or $2.0 \times 10^{-25}\,{\rm cm}^{3}\,{\rm s}^{-1}$.
Which is the better value and why?

A: By "which is better" I assume that you mean "which is most constraining".
First, $\langle\sigma v\rangle$ refers to the cross section per unit velocity. This is important because it is conjectured that dark matter scattering with a velocity independent cross section has several problems that it seems to be possible to resolve by assuming the cross section changes with velocity. This explains the units of $\langle\sigma v\rangle$: it relates how big a target the particle represents (${\rm cm}^{2}$) and how fast it is traveling (${\rm cm}\,{\rm s}^{-1}$).
The scattering/annihilation cross section of DM (work on both types of interactions uses similar language) has never been measured, which is a bit of a given since DM scattering/annihilation have never been detected (well, there are claims, but none generally accepted at the moment). A smaller upper limit represents a more constraining non-detection. Basically, the limit says "if the scattering/annihilation cross section were larger than $<{\rm value}>$, we would have seen it in our detector, so it must be smaller". The limit only applies to the types of interactions the detector is designed to be sensitive to, and the design is motivated by some theoretical candidate particle, such as a WIMP.


text:
Q: How android span act on input characters in EditText I want to implement a effect that control input characters in edittext whether use span.
For example, in EditText can use
getEditableText().setSpan(new StyleSpan(Typeface.NORMAL), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

make selected characters be BOLD.Is There have solutions that when user enable Bold setting, every character input since then will be bold, and once user disable Bold setting, characters input after that will not be bold.
I tried use Spanned.SPAN_EXCLUSIVE_INCLUSIVE as flags in SpannableStringBuilder.setSpan(), but I just can control when span's effect start, and can't control end.
Also tried use TextWatcher to listen every character input, and set Span to every character.
 @Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter)
{
    setTextSpan(start, lengthBefore, lengthAfter);
}

private void setTextSpan(int start, int lengthBefore, int lengthAfter)
{
    if (isBold) {
        getEditableText().setSpan(new StyleSpan(Typeface.BOLD), start, start + lengthAfter, Spanned
                .SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

but when use Html.toHtml(), every character be wrapped by .
Like
111111

I read some source code in SpannableStringBuilder.java, but do not find any method to change span's effect scope.
Hope someone can give me some suggestions. Thanks in advance.

A: Some useful advices have been found, you can check 'Android EditText: how to apply spans when composing?'.
But, there is also another question:The flag 'SPAN_INCLUSIVE_INCLUSIVE' setting font BOLD works well. But, when I switch to set the font NOT BOLD(just return to normal), the text insertted is still BOLD. I don't know how to resolve this problem.

A: First of all,set TextWatcher for EditText. Then there are two solutions.
1. when text changed, if input character, use removeSpan(), then use setSpan() reset the span's range.
2. Use reflect. SpannableStringBuilder has member call mSpanEnds, this array record position information for all span in the SpannableStringBuilder,use reflect change it's value.
I have a sample for solution 2,this sample may have some bugs,but it works well in apply spans.


text:
Q: sh: psql: command not found in Zabbix template There is a template for monitoring PostgreSQL
Zabbix v3.2
Zabbix_agent is installed on another server and monitors PostgreSQL 9.6 there. The host is active in the Zabbix server in the web interface, there are no errors.
Partially zero values from the database are output to the template on the Zabbix server and there are
sh: psql: command not found

enter image description here

A: You are attempting to execute /usr/pgsql-9.6/bin/psql.
If that postgres directory is not in the $PATH env var, then trying just psql
won't work and will produce a "command not found" diagnostic.
Either tell Zabbix to execute the full pathname,
or put the postgres directory in Zabbix's PATH,
or choose a directory already in Zabbix's PATH
and add a symlink to it.
For example:
$ cd /usr/bin
$ sudo ln -s /usr/pgsql-9.6/bin/psql


text:
Q: Pander with ftable and quotation marks in output im trying to get a lovely 3-way crosstable using ftable with pander. In general output is ok, but row and column names are all in quotation marks which isnt ideal.
example:
library(pander)
varA <-c("a","a","a","a","b","b")
varB <-c(1,2,1,2,1,2)
varC <-c(1,2,3,4,5,6)

tab1<-ftable(table(varA,varB,varC))
pander(tab1)

Im not sure how i can insert formated table so it wouldnt look awful (copy paste does some wierd things with it), but after knitring it looks like on screenshot below:

Thank in advance for your help.

A: I think this was a bug, so thanks for reporting this -- hopefully fixed now:
> pander(tab1)

---- ---- ---- - - - - - -
          varC 1 2 3 4 5 6

varA varB

 a    1        1 0 1 0 0 0

      2        0 1 0 1 0 0

 b    1        0 0 0 0 1 0

      2        0 0 0 0 0 1
---- ---- ---- - - - - - -

Please try the development version installed from GitHub and feel free to report similar issues or any suggestion you may have in the GitHub issue tracker.


text:
Q: Why does assigning to one element of a list result in two mutations? This code block is giving me unexpected results, and I am not sure why:
grid = [[0] * cols] * rows
grid[0][1] = 1
print(grid) # [[0, 1], [0, 1]]

I expected the grid to be [[0, 1], [0, 0]], not [[0, 1], [0, 1]]. What causes grid[1][1] to be mutated as well?
Thank you.


text:
Q: Append cookies and sending to next request using cookie manager in jmeter I am doing load test for my application. For login i am getting set-cookie in response headers. Is it possible to append all cookies using cookie manager and sending it in request header for another request

A: Just add cookie manager to you thread group.
Jmeter will automatically transfer the cookies to the further request correspondingly

A: Add HTTP Cookie Manager to your Thread Group, it should handle cookies automatically.
If it doesn't pick up all the cookies, there should be an issue with one or more cookies, i.e. Domain or Path mismatch or expiration date is in the past or whatever. If this is the case and you still want JMeter to consider the invalid cookies you can try adding the next line to user.properties file (located in JMeter's "bin" folder)
CookieManager.check.cookies=false

Given this property set to false JMeter won't check cookies before storing them and you should see "missing" ones, however I would recommend raising a defect against your application as the fact you are not seeing the cookies added by the HTTP Cookie Manager indicates that something is wrong with them


text:
Q: Data binding doesn't update the property when pressing Enter on a dialog with a default button My setting is as described below:

*

*WPF 4 application

*MVVM Lite framework

*An "Add Item" window is shown on top of the main window in dialog mode (using view.ShowDialog();)

*The dialog has a number of input fields, and the "Save" button that has it IsDefault property set to True

*"Save" button is handled using a binding to a Command

*Data binding is defined between the input fields in view's XAML and the corresponding properties in the ViewModel (one way, for the UI to update the ViewModel, with Mode=OneWayToSource)

The problem is that when I press Enter on the keyboard, the value that I provided in the last input field is not pushed to the underlying property of the ViewModel.
I suspect that this has something to do with the fact that the input field hasn't lost the focus before the window is closed (and thus all the bindings are "dissolved").
For comparison, if I click the "Save" button (instead of letting its Click being handled by the window on Enter), the value is updated in the property.
Moreover, if I add (horror! horror!) an event handler to the button's Click event, and call button.Focus() in code-behind, everything works!
What can be the remedy?
I obviously don't want to handle any window closing events, and "manually" fetch the missing values... This would violate the whole MVVM concept :-(
Any better suggestions?
Thank you,
Alex

A: Try this.
{Binding Property,UpdateSourceTrigger=PropertyChanged,Mode=OneWayToSource}

A: By default, a TextBox only notifies it's source that its value has changed once it loses focus. You can change that in your binding by setting UpdateSourceTrigger=PropertyChanged. This will make the TextBox send an update notification to its source its Text gets changed instead of only when it loses focus.
If you don't want to send an update notification anytime a key is pressed, you can create an AttachedProperty to update the source if the Enter key is pressed.
Here's the AttachedProperty that I use for situations like this:
// When set to True, Enter Key will update Source
#region EnterUpdatesTextSource DependencyProperty

// Property to determine if the Enter key should update the source. Default is False
public static readonly DependencyProperty EnterUpdatesTextSourceProperty =
    DependencyProperty.RegisterAttached("EnterUpdatesTextSource", typeof (bool),
                                        typeof (TextBoxHelper),
                                        new PropertyMetadata(false, EnterUpdatesTextSourcePropertyChanged));

// Get
public static bool GetEnterUpdatesTextSource(DependencyObject obj)
{
    return (bool) obj.GetValue(EnterUpdatesTextSourceProperty);
}

// Set
public static void SetEnterUpdatesTextSource(DependencyObject obj, bool value)
{
    obj.SetValue(EnterUpdatesTextSourceProperty, value);
}

// Changed Event - Attach PreviewKeyDown handler
private static void EnterUpdatesTextSourcePropertyChanged(DependencyObject obj,
                                                          DependencyPropertyChangedEventArgs e)
{
    var sender = obj as UIElement;
    if (obj != null)
    {
        if ((bool) e.NewValue)
        {
            sender.PreviewKeyDown += OnPreviewKeyDownUpdateSourceIfEnter;
        }
        else
        {
            sender.PreviewKeyDown -= OnPreviewKeyDownUpdateSourceIfEnter;
        }
    }
}

// If key being pressed is the Enter key, and EnterUpdatesTextSource is set to true, then update source for Text property
private static void OnPreviewKeyDownUpdateSourceIfEnter(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        if (GetEnterUpdatesTextSource((DependencyObject) sender))
        {
            var obj = sender as UIElement;
            BindingExpression textBinding = BindingOperations.GetBindingExpression(
                obj, TextBox.TextProperty);

            if (textBinding != null)
                textBinding.UpdateSource();
        }
    }
}

#endregion //EnterUpdatesTextSource DependencyProperty

A: A simple trick is to move the focus away from the control e.g. to the button itself. You can do this in the Click handler of the button, as it will be executed before the bound command:
    public MyView()
    {
        InitializeComponent();

        _button.Click += delegate
        {
            _button.Focus();
        };
    }

If you don't like code behind in your view, you can also do this in a behavior you add to your button.

A: It is simply a WPF bug. (Design or implementation, I don't know.) TextBox update on focus lost is the expected behavior in most of the cases and also default button should  work in dialogs.
For workaround, I think it is a wrong direction to temper with the the TextBox. Better solution is to force focus to the default button.


text:
Q: Populate dropdown menu based on groupnumber and MySQL answer I am building an webapplication for retailers to register purchased products in PHP/MySQL.
What I like to do now is to populate a dropdown menu in a form with the products the specific retailer sells.
The retailer is assigned a value for each product that they are selling, and then the values are summed up and putten into the database in the colum Group.
The group memberships can be determined by coverting the number in the Group column to binary and then check the specific position for a specific group in the string returned.
Example: 5 is 101 in binary, this value is assigned to the Group column in the database. By checking if the first position is a 1 I'll determine if the retailer is selling Product 1. Noting that the second character is a 0 I thereby know they ar'nt selling Product 2.
And since the last position is a 1 I also know they sell Product 3.
So for the retailer to register they've sold a Product 1, I want to populate a dropdownbox with only the prducts that retailer is selling.
I do understand I have to get the groupvalue (the binary value is set when loggin in using the $_SESSION['group']) loop it through to check wich products the retailer sells and in the same time populate the dropdownbox. I'm guessing a while loop inside the -tag, but how? The names (Product 1 and so on) are in a separate table with their values. Example:| 1 | "Product 1" | (the | are representing columns start/end).
Any idea on how to do this? Or is it someway better to do this? A string in the table with the names wont work since the fields are limited to a number of chars and with many products that will be a problem.

A: Nevermind, remade the groupsystem into using separate tables instead.
Now working like a charm with a table frou groups, a table for users and a table to link them together.


text:
Q: Grafana graph share without requiring login I'm trying to use a direct link to a graph in grafana to save the png image to disk.
This requires cookies with saved data so the user doesn't have to log in (if they've accessed it before), but does have to log in otherwise.
I can't use the auth.anonymous settings in the grafana.ini file, because it will make everything available, which is not good.
Any hints on how to handle this situation?
Thanks in advance


text:
Q: I am having a lot of troubles of how to use the scanner So this is what I need to do. I have a specific file with a specific format to it: https://pastebin.com/rL3jxZAF. The 4 at the beginning is the number of houses. I need to read this file in a later assignment, but in this assignment I have to say how it needs to read it. It needs to read whether the house is for rent, for sale, rented or sold. It needs to have an address(which consists of a street, number, zipcode and city). It needs to see the sale price and what kind of heating system it has.
So I am stuck here:
When I scan the first line including if the house is sold or rented etc. I don't know how to do this, because it needs to be a boolean and because sold is one word and for sale is 2 words, so I don't know how to show java that there is a difference between them. I need to scan it as a string and do somethings with it to give the constructor a boolean and I don't know how to do this all.
Second problem
Obviously java can't read objects, so I need to say that this object is a string and than later need to convert it to an object. This is not a big deal but the problem is that I don't know how to implement them into the constructor. I am very stressed right now, so if my explanations didn't do any justice, here is the assignment. I also don't know what do with the owneroccupied and rentalhouse class. What do I need to do in them. I am totally confused. Please help. Here is the assignment: https://imgur.com/a/FwCbz
And here is the code I have. Like you can see many things are in comments because they don't work:
public static House read(Scanner sc) throws IOException {
    //BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
    //String statuss =buffer.readLine();
    Scanner ss = new Scanner(System.in).useDelimiter("\\s");
    //String statuss = sc.next();

    //  boolean status = statuss.equals("FOR RENT") | statuss.equals("FOR SALE");

    Address address = Address.read(sc);

    int nRooms = sc.nextInt();
    sc.next();
    sc.next();

    int salePrice = sc.nextInt();

    String heatingsystemstring = sc.next();

    if (heatingsystemstring.equals("boiler")) {
        HeatingSystem heatingsystem = new Boiler();
    }
    if (heatingsystemstring.equals("Centralheating")) {
        HeatingSystem heatingsystem = new CentralHeating();
    }

    if (statuss.equals("FOR RENT") | statuss.equals("RENTED")) {
        if ()
            RentalHouse house = new RentalHouse(statuss, address, nRooms, salePrice, HeatingSystem);
    }

    if (statuss.equals("FOR SALE") | statuss.equals("SOLD")) {
        OwnerOccupiedHouse house = new OwnerOccupiedHouse(statuss, address, nRooms, salePrice, heatingsystem);
    }
}


text:
Q: How to automatically turn off external hard-drive connected to Time Capsule when idle? I have a 5th generation AirPort Time Capsule (3TB) with an additional G-DRIVE GEN4 (3TB) external hard-drive attached to it. The external hard-drive has an on/off switch.
Is it possible- and how can I make it so that the external hard-drive turns off or hibernates after a period of being idle, without turning off the power switch? I don't want it to be always active.
The external hard-drive is not used as a Time Machine backup drive; I'm only using it as a network share/network-attached storage, so that we can share files more easily within the household.

A: Not possible. The Time Capsule does not supported that feature.


text:
Q: Hbase rest API of adding new data in table dont work Truying to put some data inside the table (table is already exist) here is code (C#):
async Task AddData(HttpClient httpClient, string tableName, string columnName, string columnFamilyName, string key, string data)
{
    using (var request = new HttpRequestMessage(new HttpMethod("PUT"), $"http://localhost:8080/{tableName}/{key}"))
    {
        request.Headers.TryAddWithoutValidation("Accept", "application/json");

        var keyInBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(key));
        var columnInBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(columnName));
        var dataInBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
        var columnFamilInBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(columnFamilyName));
        var FamilyAndColumnInBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(columnFamilyName + ":" + columnName));

        request.Content = new StringContent($"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><CellSet><Row key=\"{keyInBase64}=\"><Cell column=\"{FamilyAndColumnInBase64}=\">{dataInBase64}==</Cell></Row></CellSet>");
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml");

        var response = await httpClient.SendAsync(request);

        Console.WriteLine(response);
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}

using (var httpClient = new HttpClient())
{
    await AddData(httpClient, "players", "nicknames", "playerData", "somekey", "CoolGuy");
}

And here is what i got:
I already search thru google and saw a lot of github repositories but didn't find an answer.
Request of creating table and deleting it works fine.
Any ideas? Is my request correct?
Thanks.

A: <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><CellSet><Row key=\"{keyInBase64}=\"><Cell column=\"{FamilyAndColumnInBase64}=\">{dataInBase64}==</Cell></Row></CellSet>
need to be
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><CellSet><Row key=\"{keyInBase64}\"><Cell column=\"{FamilyAndColumnInBase64}=\">{dataInBase64}</Cell></Row></CellSet>
I miss to delete "="....


text:
Q: How to define message? const args = message.content.slice(prefix.length).trim().split(/ +/g);
             ^ReferenceError: message is not defined

anybody knows how to difine message? ask for more code if its necessary. Thanks

A: seems like your code is not inside the message event
client.on("message", message => {
*code here*
});

you need to put args variable inside this event.

A: message is a parameter in the message event, therefore, I'm assuming you either do not have a message event or you have one but you did not place const args = message.content.slice(prefix.length).trim().split(/ +/g); inside of it.
client.on('message', message => {
  const args = message.content.slice(prefix.length).trim().split(/ +/g);
})


text:
Q: ValueError: Input contains NaN, infinity or a value too large for dtype('float64') ( fiz a verificação e nenhuma dessas procede) estou trabalhando em um projeto de regressão linear em python, mas está havendo um problema no modelo.fit().
acontece  os seguintes erros:
no código que eu coloquei aqui:
ValueError: Input contains NaN, infinity or a value too large for dtype('float64').
quando eu tento ajeitar:
ValueError: could not convert string to float: 'e'
eu já procurei na internet, mas nada fala desse específico "e"
já tentei converter int(float(x)) e os números são todos floats no formato número.0, sem casas decimais. Alguns dos números são 0.0 e outros são valores altos. aqui está o código para análise:
mport pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#imports
dataset = pd.read_csv('movies_metadata.csv')
data = dataset.columns
data =dataset[['title','budget','revenue','vote_average']]
#seleção dos dados
custo = []
for i in data['budget']:
    try:
        custo.append(int(i))
    except ValueError:
        custo.append(0)
custo = pd.Series(custo)
data['custo'] = custo
data.drop(['budget'],axis = 1)
data.dropna()
#modelo de machine learning
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import sklearn.metrics
X = data['custo'].values.reshape(-1,1)
Y =data['revenue'].values.reshape(-1,1)
treino_x, teste_x, treino_y, teste_y = train_test_split(X,Y,random_state = 101,train_size = 0.27)
lista = [treino_x, teste_x, treino_y, teste_y]
modelo = LinearRegression()
modelo.fit(teste_x,teste_y)

A: Sem acesso aos dados não consigo testar para ver se é isso, mas note que as linhas
data.drop(['budget'],axis = 1)
data.dropna()

não são operações in-place. Tanto DataFrame.drop quanto DataFrame.dropna são métodos que retornam um novo DataFrame, o qual você não está assinalando a nenhuma variável.
Simplesmente assinale o DataFrame retornado de volta a uma variável, ex:
data = data.drop(['budget'],axis = 1)
data = data.dropna()

Ou adicione o argumento inplace=True para mudar o comportamento dos métodos, ex:
data.drop(['budget'],axis = 1, inplace=True)
data.dropna(inplace=True)


text:
Q: How can I convert lambda from Python2 to Python3? Now I am rewriting Python2 scripts to Python3 scripts.
In the Python2 script, the code below was successfully launched.
But in the Python3 script, it had an syntax error.
If somebody knows why it happens, please tell me why and how can I fix it.
hash = []
for root, dirs, files in os.walk(directory):
    for names in files:
        if not names.endswith( '.py' ):
            continue
        filepath = os.path.join(root,names)
        try:
            f1 = open(filepath, 'rb')
        except:
            # You can't open the file for some reason
            f1.close()
            continue
        hash.append( (names, hashlib.sha256(f1.read()).hexdigest() ) )

hash.sort( key=lambda tup: tup[ 1 ])
digest = reduce( lambda d, (x,y): d + '\n' + y, hash, '')


text:
Q: maximum records in access table I recently run into the problem of reaching the maximum amount of records in my table, somewhere around 32567. I got an overflow error trying to access the records. I figured out how it could happen since I have only around 2000 actual records in the table. It was the autonumber Id which reached 32567.
It happens because I use two tables. Documents and Archive. Documents is daily filled with all files in a folder on the harddrive. It is then compared with the table Archive and all double records are deleted from the Documents table. After that the new files are added to the Archive table and the Documents table is emptied again.
All the deleted records from Documents however used an autonumber which makes it increase fast. What should I do to prevent this from happening?
Regards
Marco

A: Neither Autonumber nor #records are limited to 32567 (2^15 - 1).
You probably have the ID column in Archive defined as Integer (16 bit) instead of Long (32 bit).
Change it to Long and you will have a long time to go. :)

A: From your description, it looks like you are using [Documents] as a temporary table. You can extend the

"Documents table is emptied again."

function to recreate your document table, delete the old one. This will reset the Autonumber issue.
DoCmd.TransferDatabase acImport, "Microsoft Access", currentproject.Path & "\" & currentproject.Name,acTable,"Documents","DocumentsFresh",structureonly:=true

docmd.DeleteObject acTable,"Documents"
Docmd.rename "Documents", acTable, "DocumentsFresh"

Also beware, if you are relaying on documents.autonumber identity you should not follow this process. Do this only if you require temporary table function.


text:
Q: Function produces output alphabetically, order by average score instead This function shows the average score for each person in database from 3 most recent results. The output is ordered by name, how can I get it to order by average, highest to lowest.
def averagescore():
    allnames = []
    itr = cursor.execute("SELECT name FROM "+group+" GROUP BY name;").fetchall()#lists names in database
    for x in itr:
        if x not in allnames:
            allnames.append(x[0])
        else:
            False
    allnames.sort()
    avg = 0
    number = 0

    for name in allnames:
        cursor.execute("SELECT total FROM "+group+" WHERE (\""+name+"\") = NAME ORDER BY DATE DESC LIMIT 3;")#3 most recent scores
        scores =(cursor.fetchall())

        scores = [i[0] for i in scores]
        avg = sum(scores)/len(scores)
        print(name,"'s average is: ",avg,". From (up to) 3 most recent scores which were: ",scores,)
        avg = 0

The output is:
AZ 's average is:  0.0 . From (up to) 3 most recent scores which were:  [0]
ED 's average is:  0.6666666666666666 . From (up to) 3 most recent scores which were:  [0, 1, 1]
JAKE 's average is:  2.0 . From (up to) 3 most recent scores which were:  [0, 4]
SAM 's average is:  0.0 . From (up to) 3 most recent scores which were:  [0]
ZAC 's average is:  0.0 . From (up to) 3 most recent scores which were:  [0]

I would like it to be:
JAKE 's average is:  2.0 . From (up to) 3 most recent scores which were:  [0, 4]
ED 's average is:  0.6666666666666666 . From (up to) 3 most recent scores which were:  [0, 1, 1]

ETC

A: You mean something like this?
(please see here: https://wiki.python.org/moin/HowTo/Sorting )
#!/usr/bin/python

# datastruct
# name, avg, [scores]

datastruct = [
    ['AZ', 0.0, [0]],
    ['ED', 0.6666666666666666, [0, 1, 1]],
    ['JAKE', 2.0, [0, 4]],
    ['SAM', 0.0, [0]],
    ['ZAC', 0.0, [0]]
]

print('before')
for item in datastruct:
    print(item)

print('after')
for item in sorted(datastruct, key=lambda k: k[1], reverse=True):
    print("{}'s avg is: {}. From (up to 3) most recent scores which were: {}".format(item[0], item[1], item[2]))

A: You can build a list of combined records from the two sql queries and then sort them by average as answered by @davejagoda.
In relation to your needs, the first for loop, I would use a set for allnames then convert that into a sorted list. After that I would build a list of records which is just [{'name': 'foo'}, {'name': 'bar'}, ...]. Then I would do the second DB query using each of these names as you did and update that record in-place with avg and scores.
After that is achieved, I would then sort records records list by avg in descending order and print out the results.
For this, your code would look like this:
from operator import itemgetter

# ... your other code goes here

def averagescore():
    names_sql = "SELECT name FROM {0} GROUP BY name;".format(group)
    # lists names in database
    itr = cursor.execute(names_sql)
    allnames = sorted(list({x[0] for x in itr}))

    records = [{'name': name} for name in allnames]

    scores_sql = """
        SELECT total
          FROM {0}
         WHERE ("{1}") = NAME
      ORDER BY DATE DESC
         LIMIT 3;
    """

    for record in records:
        name = record['name']
        # 3 most recent scores
        itr = cursor.execute(scores_sql.format(group, name))
        scores = [i[0] for i in itr]
        avg = sum(scores) / len(scores)
        record.update({'avg': avg, 'scores': scores})

    tally.sort(key=itemgetter('avg'), reverse=True)

    for record in records:
        print(
            record['name'],
            "'s average is: ",
            record['avg'],
            ". From (up to) 3 most recent scores which were: ",
            record['scores']
        )


text:
Q: Changing CSS values with checkbox and javascript I am trying to hide and display a div based on the state of a checkbox using javascript but I don't seem to be getting it right. I am not very experienced with js so I could be missing something very obvious. Any advice would be much appreciated. the target div is the on-toggle div in the second half of the html code.

var checkbox = document.querySelector("input[name=toggle]");

checkbox.addEventListener( 'change', function() {
    if(this.checked) {
        document.getElementById("on-toggle").style.display = "block";
        document.getElementById("on-toggle").style.height = "auto";
    } else {
        document.getElementById("on-toggle").style.display = "none";
        document.getElementById("on-toggle").style.height = "0";
    }

Turn creativity on

                 <input type="checkbox" name="toggle">

REFERENCE SITES

A: You'll need to grab an actual element so your javascript code works. The id "on-toggle" does not currently exist on any element on your html code.


text:
Q: TTTAttributedLabel and popover for link Is it possible to detect CGRect of link text or CGPoint of position, to show popover (on ipad) for clicked link in TTTAttributedLabel?
I need to show popover on clicked link with TTTAttributedLabel.
Thanks!

A: You can only do this by modifying the TTTAttributedLabel to support this behavior.
1) Modify the delegate method:
- (void)attributedLabel:(TTTAttributedLabel *)label
   didSelectLinkWithURL:(NSURL *)url
                atPoint:(CGPoint)point;

2) In the TTTAttributedLabel.m source, modify the touchesEnded:withEvent: and grab the touch point and pass this onto the delegate method.
    switch (result.resultType) {
        case NSTextCheckingTypeLink:
            if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithURL:atPoint:)]) {
                UITouch *touch = [touches anyObject];
                CGPoint touchPoint = [touch locationInView:self];
                [self.delegate attributedLabel:self didSelectLinkWithURL:result.URL atPoint:touchPoint];
                return;

3) In the view controller, you will need to convert that touch point to be in relative coordinates to the view controller's view:
#pragma mark TTTAttributedLabelDelegate
- (void)attributedLabel:(TTTAttributedLabel *)label
   didSelectLinkWithURL:(NSURL *)url
                atPoint:(CGPoint)point
{
        CGPoint normalizedPoint = [self convertPoint:point fromView:label];

        UIActionSheet *actionSheet = [[UIActionSheet alloc] ...
        [actionSheet showFromRect:CGRectMake(normalizedPoint.x, normalizedPoint.y-kSensibleOffset, 10, 10)
                           inView:label
                         animated:YES];
    }
#pragma mark -

A: You don't want to do this at the gesture level by trying to keep track of position. Since you have a link, just override openURL and do whatever you want when you intercept the link click. More details are here.


text:
Q: I found Calling Semaphoreslim.Wait and Semaphoreslim.WaitAsync at the same time cause a deadlock? Why? Did I misunderstand something?
Run the following code, you will find that the final result is never output, which seems to cause a deadlock.
update: Please run TestSemaphoreSlimForMixUse()
a few more times, as I find it occasionally works fine.
Define a method to call SemaphoreSlim.Wait:
static void TestMethod(SemaphoreSlim sp, Action worker)
{
    sp.Wait();
    try
    {
        worker();
    }
    finally
    {
        sp.Release();
    }
}

Define a method to call SemaphoreSlim.WaitAsync:
static async Task TestMethodAsync(SemaphoreSlim sp, Func<Task> worker)
{
    await sp.WaitAsync().ConfigureAwait(false);
    try
    {
        await worker();
    }
    finally
    {
        sp.Release();
    }
}

Method used for testing:
Testing found that if you use one alone, you don't have a problem, and if you use both (mixed), you do.
public static async Task TestSemaphoreSlimForMixUse()
{
    var taskList = new List<Task>();
    var countList = new List<int>();
    SemaphoreSlim sp = new SemaphoreSlim(1, 1);

    for (int i = 0; i < 1000; i++)
    {
        var t = Task.Run(async () =>
        {

         //Note: The following two lines of code, if enabled together, cause the problem described. If only one of them is enabled, there is no problem.

            //await TestMethodAsync(sp, async () => { countList.Add(Environment.CurrentManagedThreadId); await Task.FromResult(0); });
            //TestMethod(sp, () => { countList.Add(Environment.CurrentManagedThreadId); });

        });
        taskList.Add(t);
    }
    await Task.WhenAll(taskList);

    Console.WriteLine($"Count:{countList.Count}");
}

A: My theory is that when the number of tasks is higher than the maximum number of threads using for running task parallelly, it can cause deadlock in this case.
For example, if you have 1000 tasks but only 4 threads to run all tasks. It is possible that all 4 threads are waiting at TestMethod for the lock to be released, while the lock is already released for TestMethodAsync in some other task but there is no thread available to continue that task because they are all waiting for the lock, hence deadlock.


text:
Q: Mongo zoned sharding with a single value We have a database with around 50 collections, and 70 million records. All records belong to specific customers and have a customerId property. Currently all clients are in the USA. However, we're in the process of adding EU clients and would like to host their data in an EU datacenter.
Since all records have a customerId (which is a string) and virtually all of our queries also specify this customerId this makes it a good choice for a shard key for us - we're only going to have one shard per zone, and we'd like all of a customers data to be in that one shard.
My question is, given that the customerId's are strings, how do we specify a minimum and maximum for the sh.updateZoneKeyRange() function? Obiously minimum will be the customerId (e.g., "customer-somename") but how do we specify a maximum of "customer-somename" + 1? The issue here is that maximum is exclusive, so it can't be the same as minimum

A: Assuming your customerId does not have any obvious mapping to location, it would be best to add a location field and create a compound shard key. The location field should be a prefix of the shard key, otherwise you will have an administrative headache trying to maintain zones for small ranges of customerID values (which could end up as granular as a single customer).
With a compound shard key of  {location: 1, customerId:1} your zone ranges would be straightforward to define.
For example:
sh.updateZoneKeyRange(
  "mydb.mycollection",
  { "location" : "US", "customerId" : MinKey },
  { "location" : "US", "customerId" : MaxKey },
  "US"
)

The MongoDB manual includes a similar example in Segmenting Data by Location and this is the same approach used for MongoDB Atlas' Global Clusters feature. Both of these examples suggest two-character country codes (ISO 3166-1 Alpha-2) for the location field, but you could choose any values which provide suitable granualarity for your future use cases. For example, ISO 3166-2 would provide for countries and subdivisions (administrative regions like state or province).
Starting in MongoDB 4.2, you can also change a document's shard key value if you need to move existing user data between zones. You presumably would never want to change your customerId values, but could update a location field.


text:
Q: Why are JSON value updates several keys deep Duplicating? SUMMARY: A write operation to a single value in a JS Object (JSON format) modifies two values. (probably a copy vs reference bug).
UPDATE: JSFiddle with basic version of bug: https://jsfiddle.net/J_withfeeling/vmhx95yL/
FULL QUESTION:
I want to prep some data client side before writing it to a server.
I create my object like so:
let number = {};
let category = {};
number = {
   "numbers":{
      "num1":0,
      "num2":0,
      "num3":0
   }
};
console.log(categories);//confirming that categories is "{"category1":true,"category2":true}"
for(let m in majorList){//initialize the JSON object
   category[m] = Object.assign({}, number);
}
data = {major};

I now have a nice JS object, constructed in a JSON format:
   {
   "category":{
      "category1":{
         "numbers":{
            "num1":0,
            "num2":0,
            "num3":0
         }
      },
      "category2":{
         "numbers":{
            "num1":0,
            "num2":0,
            "num3":0
         }
      }
   }

I'm able to console.log(data) properly at this point with no problems.
Then with some JS I want to update the "num" values. I do this right now:
//some stuff up here to figure out which "category" and "number" to increment

      console.log(cat);
      console.log(num);
      console.log(JSON.stringify(data));
      data['category'][cat]['numbers'][num] = data['category'][cat]['numbers'][num] + 1;
      console.log(JSON.stringify(data));
//the above 5 lines are executed multiple times in a loop

What I expect to print out of those console.log statements is something like this:
category1
num2
"myJSON":{
   "category":{
      "category1":{
         "numbers":{
            "num1":0,
            "num2":0,
            "num3":0
         }
      },
      "category2":{
         "numbers":{
            "num1":0,
            "num2":0,
            "num3":0
         }
      }
   }
}
"myJSON":{
   "category":{
      "category1":{
         "numbers":{
            "num1":0,
            "num2":1,
            "num3":0
         }
      },
      "category2":{
         "numbers":{
            "num1":0,
            "num2":0,
            "num3":0
         }
      }
   }
}

What actually prints out is this:
category1
num2
"myJSON":{
   "category":{
      "category1":{
         "numbers":{
            "num1":0,
            "num2":0,
            "num3":0
         }
      },
      "category2":{
         "numbers":{
            "num1":0,
            "num2":0,
            "num3":0
         }
      }
   }
}
"myJSON":{
   "category":{
      "category1":{
         "numbers":{
            "num1":0,
            "num2":1,
            "num3":0
         }
      },
      "category2":{
         "numbers":{
            "num1":0,
            "num2":1,
            "num3":0
         }
      }
   }
}

The "num2" value is getting incremented in both of the "category" keys, in just a single pass of the innermost for loop. Why?
Admittingly above this code snippet there is a little more going on, but it's a bit much to include in a stackoverflow question. What is definitely the case is  those 4 console.logs() with the one line of code in between. Those 5 lines are copied as-is, and I don't understand how one write operation can edit multiple values in the JSON object.

A: When you do category[m] = {score}; you are creating a new object with a single property, which references the same object score every time. So when you update one of the score values, you update them all since they all refer to the same object.
You could do category = { score: {...score} } instead, that will create a new object.

A: So, with @charlietfl pointing the way, I came up with a fix (if inelegant).
What is happening is indeed as @charlietfl and @leftclickben suggest, the JS Object is getting created using pass-by-reference, so multiple parts of the object have the same reference. Thus when one value gets updated, all the other values with the same reference also get updated.
To fix this, I moved these two lines of code:
let number = {};
number = {
   "numbers":{
      "num1":0,
      "num2":0,
      "num3":0
   }
};

from just above to inside of the loop, right before
category[m] = Object.assign({}, number);

This way, the 'number' object is destroyed and recreated between loop iterations, and so we can be sure that the next time it is used to build up the 'categories' object it is definitely a different reference. This eliminates the double-write problem. I've also updated the JSFiddle in the question with the working code snippet, plus some comments to serve as an abbreviated version of this explanation.
Shout out again to @charlietfl, if you want to post a more detailed answer I'd gladly endorse that.
Related posts:
Is JavaScript a pass-by-reference or pass-by-value language? (as mentioned by @jhpratt).
Also found this helpful: JavaScript: How to pass object by value?


text:
Q: Add tooltips to eric hynds multi select dropdown I am using the Jquery based multi select dropdown provided by Eric Hynds.
I would like to add tooltip to the selection button and also each item in the dropdown list. The reason - I truncate the text in both the display and the selection list and tooltip is supposed to show the full text. But I cannot find any documentation on how to add this. Any help appreciated. Thanks.

A: your option will get converted to li tags when you use this plugin so give them attribute title this
$('li').attr('title','tooltip text');

A: Thanks Rahul. I didnt directly use li, but that did give me an idea. The control internally converts each li item to have a checkbox and a span with text. I gave a class to that particular span control. Before truncating the text, I updated the title property with the text.
$(".truncate").each(function(){
  $(this).attr('title', $(this).html());
});

Thanks for your pointer.


text:
Q: how to off sql server owner name that dbo? whenever we expand the table list from sql server 2005 then table name shows with owner name. is there anyway out to off the owner name as a result only table name will display in sql server 2005.
thanks

A: First, it's not the owner. It's the schema. Since the 2005 version came out, these are distinct concepts.
Second, no, I do not believe it's possible to prevent the schemas being shown alongside the table names in Management Studio's Object Explorer (presumably, where you're looking). The Object Explorer Details pane does show them in separate columns, so if you just want an alphabetical list of tables without schema names, then you can look/sort the tables there.

Thomas - Open Tools -> Options, and select "SQL Server Object Explorer" in the left hand pane. This is the only obvious place where such an option would exist, and it does not exist

A: You can use schema Filter Tables->LeftClick->Filter


text:
Q: How to import multiple Excel files to a single Google Sheet spreadsheet without creating intermediate files? I have several Excel files in a shared Google Drive.
I want to import their content inside a single Google Sheet spreadsheet.
I found this sample code and tried to adapt it to my use case.
Here is my implementation for a single test file :
function importFile() {
  // Log the name of every file in the user's Drive.
  var folders = DriveApp.getFoldersByName("myFolderName")

  if (folders.hasNext()) {
    files = folders.next().getFiles()
  } else {
    return null
  }

  var file = files.next();
  Logger.log(file.getName());

  let spreadsheetId = convertExcelToGoogleSheets(file.getName())
}

function convertExcelToGoogleSheets(fileName) {
  let files = DriveApp.getFilesByName(fileName);

  let excelFile = null;
  if (files.hasNext()) {
    excelFile = files.next();
  } else {
    return null;
  }

  let blob = excelFile.getBlob();

  let config = {
    title: "[Google Sheets] " + excelFile.getName(),
    parents: [{ id: excelFile.getParents().next().getId() }],
    mimeType: MimeType.GOOGLE_SHEETS
  };

  Logger.log(config);

  let spreadsheet = Drive.Files.insert(config, blob);
  return spreadsheet.id;
}

This however crashes :
3:50:45 PM  Notice  Execution started
3:50:46 PM  Info    2021_Salariés appartenant à une entreprise extérieure.xlsx
3:50:46 PM  Info    {parents=[{id=1mxYU55TOX1gp2ABzmSpB_lEWSw2FGa7v}], mimeType=application/vnd.google-apps.spreadsheet, title=[Google Sheets] 2021_Salariés appartenant à une entreprise extérieure.xlsx}
3:50:47 PM  Error
GoogleJsonResponseException: API call to drive.files.insert failed with error: File not found: 1mxYU55TOX1gp2ABzmSpB_lEWSw2FGa7v
convertExcelToGoogleSheets  @ Code.gs:37
importFile  @ Code.gs:14

The error message comes from the Drive.Files.insert(config, blob); instruction. I think this is because the app script refuses to create the file in a shared folder.
Anyway, I have tens of very short Excel files that I want to read and concatenate in a single Sheet, So I don't think creating that many intermediate Sheet files is efficient.
Is it possible to directly convert the blob to a Google Sheet without creating a new file?

A: Try import this way:
function importFile() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0")
  const folders = DriveApp.getFoldersByName("myFolderName");
  let fA = [];
  while (folders.hasNext()) {
    let files = folders.next().getFiles();
    while (files.hasNext()) {
      let file = files.next()
      fA.push([file.getName(),file.getId()])
    }
  }
  sh.getRange(sh.getLastRow() + 1, 1,fA.length,fA[0].length).setValues(fA);

}

Try something like this:
Note I did not test this and I'm not going to.
function importFile() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0")
  const dsh = ss.getSheetByName("Sheet1");
  const folders = DriveApp.getFoldersByName("myFolderName");
  let fA = [];
  let dA = [];
  while (folders.hasNext()) {
    let files = folders.next().getFiles();
    while (files.hasNext()) {
      let file = files.next();
      let ss = SpreadsheetApp.openById(file.getId());
      ss.getSheets().forEach(sh => {
        dA.push(sh.getDataRange().getValues())
      })

      fA.push([file.getName(),file.getId()])
    }
  }
  sh.getRange(sh.getLastRow() + 1, 1,fA.length,fA[0].length).setValues(fA);
  dA.forEach(a => {
    dsh.getRange(dsh.getLastRow() + 1, 1, a.length, a[0].length).setValues(a);
    SpreadsheetApp.flush();
  })

}

If it doesn't work figure it out for yourself


text:
Q: Recursive Functions in Python vs C It seems as if C allows for a function to reference itself (in a recursive manner) when executing, for example, the Collatz conjecture.
int collatz(int n);

int main(void)
{
    int result = collatz(9);
    printf("Steps: %i\n", result);
}

int collatz(int n)
{
    if (n == 1)
        return 0;
    else if ((n % 2) == 0)
        return 1 + collatz(n / 2);
    else
        return 1 + collatz(3 * n + 1);
}

Python gives me an error when I try this:
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

when I reference the same function within itself:
def collatz_recursive(n):

    while n != 1:
        if n % 2 == 0:
            return 1 + collatz_recursive(n/2)
        else:
            return 1 + collatz_recursive(n * 3 + 1)

However, when I place collatz in its own function and reference it from the outside with collatz_recursive I don't have that problem:
def collatz(n):
    while n != 1:
        if n % 2 == 0:
            n = n/2
        else:
            n = n * 3 + 1

def collatz_recursive(n):
    while n != 1:
        if n % 2 == 0:
            return 1 + collatz(n/2)
        else:
            return 1 + collatz(n * 3 + 1)

A: The 'int' and 'NoneType' can not be added through + operation.
Here is my console for running your very last code:
 line 13, in collatz_recursive
    return 1 + collatz(n * 3 + 1)
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

I think the problem is that you forgot to handle the edge-case n=1 for your collatz_recursive function, you can easily log n by putting a print function before and after while loop and observe the bug.
Try to return a default value for your function, this is also named base-case.
You can read more about recursion and base case in here

A: "Python gives me an error when ... I reference the same function within itself"
No, Python gives you an error because collatz_recursive doesn't return a value for n == 1. The return value of a function is None if no value was returned with a return statement.
Your Python code should look like
def collatz_recursive(n):

    if n == 1:
        return 0
    if n % 2 == 0:
        return 1 + collatz_recursive(n/2)
    else:
        return 1 + collatz_recursive(n * 3 + 1)


text:
Q: How to clone a single specific file from Bitbucket I have a bitbucket repo with huge sources, but need to edit only one file.
Its taking more time and size to clone to local.
Can some one say the git command to clone a specific file from bitbucket

A: Considering a BitBucket server now (since 2018) has inline editing, you could consider modifying that file directly through the browser.
That way, no clone is necessary.

A: VonC's answer is great; I'd do that in most situations.
There are ways to get one file from Bitbucket:
$ curl --user <your_bitbucket_username> -O  https://bitbucket.org/<your_bitbucket_username>/<repo_name>/<filename>

You'll be able to edit the file, but it will be outside the context of .git, which doesn't seem to support your end goal of updating the repo.
Another option that still lets you clone the repo locally (for bigger edits, stuff you'd like to do with a text editor) is to clone it with less history:
$ git clone --depth=<a low number> <your_repo_url>

This can reduce the size of your total Git repo by a fraction of the total.
Checking man git-clone for more options, such as the --shallow* commands.


text:
Q: Reading from a file with Python For quite a while I have been trying to make a quiz game, that will read questions and answers from a text file and display them on a screen. I used the following function:
def start_quiz() :
    text_file = open("quiz_python.txt", "r", encoding = "utf-8")
    for lines in text_file :
        print(lines)

I make a .txt file through a standart Notepad word processor and save the file (in the same directory) with an "Utf-8" encoding. However, when I launch the program, it crashes at the very beginning. And what is more suprising, that when I run that program with F5 in IDLE, it works perfectly! At that moment I don't know what to think about all this, because it's quite strange. Any suggestions?
Thanks,
Victor.

A: You didnt say which version of python. Im using 2.x
I think its because you are using the encoding line.
Python 2.7.8 (default, Dec  6 2014, 13:17:43)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def start_quiz() :
...     text_file = open("quiz_python.txt", "r", encoding = "utf-8")
...     for lines in text_file :
...         print(lines)
...
>>> start_quiz()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in start_quiz
TypeError: 'encoding' is an invalid keyword argument for this function
>>> def start_quiz() :
...     text_file = open("quiz_python.txt", "r")
...     for lines in text_file :
...         print(lines)
...
>>> start_quiz()
stuff in a file
>>>

I personally use with open when dealing with files.
>>> with open('workfile', 'r') as f:
...     read_data = f.read()

If you need to encode; read all or each line to a variable str and run str.encode(encoding='UTF-8',errors='strict') on it.


text:
Q: How to improve timeout value dynamically? I'm working on an application where I want to keep a timeout value computed dynamically using a moving average of say 100 previous response times for service A.
This value + some buffer (~3 seconds) will be used as a timeout for network requests to service A.
The problem here is, I want this timeout to improve with network characteristics- this is not a problem when user switches from a slow network to a faster network, but in the opposite case, the timeout should increase 'gradually', EXCEPT in scenarios where connection was spotty (like in a parking garage), in which case I don't want this timeout to increase since this is transient.
I'm not sure if it's even possible to distinguish between the 2 cases mentioned above.
Even if not, what should I record as the response time when a request times-out?
I was thinking of recording (currentTimeoutValue + 2) seconds, this works well for parking garage case (doesn't push the average up dramatically) but if someone's going to be on a slower network for a while, this will take many more timed-out requests to catch up with current network speed.
Any pointers are appreciated.

A: With the moving average, you can't identify easily the quick variations.  By construction, the curve of the moving average always flatten/smoothen the reality. It will react to change trends with a time shift.  The longer the moving average span, the longer the shift.
Here how your timeout based on moving average could evolve in two situations: 1) with a slow increase and 2) with a quick change, as for example when you pass a tunnel with your phone, or if you're in an elevator:

There will be a timeout, only if your response time increases fast enough to burn the buffer time.  But it's not possible with one moving average to notice if the increase of response time is fast or not, because it's averaged.
You can make your timeout adaptation more aware of brutality of change by using a second moving average: the first would average the 100 last response times and the second would only take the 10 or 20 last ones. By comparing the two you can get an idea of how brutal the change is and adapt the reaction :

*

*apply algorithm consistently for slow degradation (fig 1)

*suspend the update of the first moving average and use a fallback strategy (fig 2) You could for example use a fixed value in case of garage or tunnel, or switch temporarily to the second moving average and add a higher buffer.

Of course you'll have to fine tune what difference between both moving average would be relevant to make the switch.

A: I assume this is an application on a mobile device which tries to call the service. If your mobile device can detect the difference between "no network available" and "network available (though slow)", then you are in a much better situation, since if the network is not available, you simply do not change the timeout.
For the other, "standard" case, you could try something like
 newTimeout = (currentTimeout + 1) * c

where c is a value somewhere between 1 and 2, whenever the response time gets exceeded, and apply the "moving average" only when the response time gets not exceeded. Moreover, it should be clear that you should keep the maximum timeout below a reasonable upper limit to prevent it converging to infinity.


text:
Q: Grep a value from array in terraform and the occurence as a count in terraform Trying to setup multiple subnets in multiple vpcs
What is the interpolation syntaz for filtering the number of occurences of a keyword and setting that up as a count in terraform
tfvars file format is
"subnets"
        "0:10.3.0.0/24:private",
        "0:10.3.1.0/24:private",
        "1:10.3.2.0/24:public",
        "1:10.3.3.0/24:private"

*

*2 private subnets in VPC 0

*1 public, 1 private in VPC 1

Plan is to have one module for private subnet and the other for public subnet.
VPC is created by another module.
In public_subnet/main.tf file - Plan is initiate a counter to grep for public var.subnets in the tfvars file and start the counter ( In our case 1) and loop through the vpc_id generated by the VPC modules (Another challenge is how to correlate which ID is which vpc).
In private_subnet/main.tf - Grep for private keyword in var.subnets, start the counter and loop through the vpc_id.
How do I format the interpolation sequence for such a need?
Thanks

A: Here's a way to do this using terraform 0.12.x
variable "subnets" {
  default = [
    "0:10.3.0.0/24:private",
    "0:10.3.1.0/24:private",
    "1:10.3.2.0/24:public",
    "1:10.3.3.0/24:private"
  ]
}

locals {
  # return the second element in the array which is the IP/CIDR if the vpc is "0"
  subnets_zero = [
    for subnet in var.subnets:
      split(":", subnet)[1]
      if split(":", subnet)[0] == "0"
  ]
  # return the second element in the array which is the IP/CIDR if the vpc is "1"
  subnets_one = [
    for subnet in var.subnets:
      split(":", subnet)[1]
      if split(":", subnet)[0] == "1"
  ]
}

output "subnets_zero" {
  value = local.subnets_zero
}

output "subnets_one" {
  value = local.subnets_one
}

$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

subnets_one = [
  "10.3.2.0/24",
  "10.3.3.0/24",
]
subnets_zero = [
  "10.3.0.0/24",
  "10.3.1.0/24",
]


text:
Q: What is the use of alert-dismissible I am creating an alert box using bootstrap
<!DOCTYPE html>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

            Alert  Read this message<button class="close" data-dismiss="alert"> Close </button>

This code works in same way if I remove alert-dissmissible class for the div. If there is no change even after removing alert-dissmissible class declaration then What is the use of alert-dissmissible class? The alert box is dissmissible even if the alert box does'nt has alert-dissmissible class.Why?

A: The following is from the Bootstrap website

Using the alert JavaScript plugin, it's possible to dismiss any alert
inline. Here's how:

*

*Be sure you've loaded the alert plugin, or the compiled Bootstrap

*JavaScript. If you're building our JavaScript from source, it requires
util.js. The compiled version includes this.

*Add a dismiss button and
the .alert-dismissible class, which adds extra padding to the right of
the alert and positions the .close button.

*On the dismiss button, add
the data-dismiss="alert" attribute, which triggers the JavaScript
functionality. Be sure to use the  element with it for proper
behavior across all devices.

*To animate alerts when dismissing them,
be sure to add the .fade and .show classes.


text:
Q: Prolog : get the opposite result I have the following code :
neighbor(C1, C2, [C1, C2|L]).
neighbor(C1, C2, [C2, C1|L]).
neighbor(C1, C2, [H|L]) :- neighbor(C1, C2, L).

not_neighbors(C5, C2, E, R) :-
    not_neighbor(C5, C2, E).

not_neighbors(C5, C2, E, R) :-
    not_neighbor(C5, C2, R).

/* THIS DON'T WORK */
not_neighbor(C5, C2, E) :-
    \+ neighbor(C5, C2, E).

Or :
same_position(I, J, [I|U], [J|V]).
same_position(I, J, [M|U], [N|V]) :-
    I \== M,   % optimisation
    J \== N,   % optimisation
    same_position(I, J, U, V).

/* THIS DON'T WORK */
not_under(C4, C1, R, E) :-
    \+ same_position(C4, C1, R, E).

I know the problem is the negation and I want to get the opposite result of same_position for example.
M. @CapelliC suggested me to use dif/2 but I don't know how to apply this on my specific example.

A: Let us first think logically about what it means to be "neighbours" in a list: In what cases are A and B neighbouring elements in a list?
Answer: If the list is of the form [...,X,Y,...] and at least one of the following holds:

*

*A = X and B = Y

*A = Y and B = X.

In logical terms: ( A = X ∧ B = Y) ∨ (A = Y ∧ B = X).
We want to state the opposite of this, which is the negated formula:
   ¬ ( ( A = X ∧ B = Y) ∨ (A = Y ∧ B = X) ) ≡
≡ ¬ ( A = X ∧ B = Y) ∧ ¬ (A = Y ∧ B = X) ≡
≡ (¬ A = X ∨ ¬ B = Y) ∧ (¬ A = Y ∨ ¬ B = X) ≡
≡ (A ≠ X ∨ B ≠ Y) ∧ (A ≠ Y ∨ B ≠ X)
Who would have thought that De Morgan's laws had any practical application, right?
To state X ≠ Y in Prolog, we use the powerful dif/2 constraint, exactly as @CapelliC has already suggested. dif/2 is true iff its arguments are different terms. It is a pure predicate and works correctly in all directions. If your Prolog system does not yet provide it, make sure to let your vendor know that you need it! Until then, you can approximate it with iso_dif/2, if necessary.
In Prolog, the above thus becomes:

( dif(A, X) ; dif(B, Y) ), ( dif(A, Y) ; dif(B, X) )

because (',')/2 denotes conjunction, and (;)/2 denotes disjunction.
So we have:

not_neighbours(_, _, []).
not_neighbours(_, _, [_]).
not_neighbours(A, B, [X,Y|Rest]) :-
        ( dif(A, X) ; dif(B, Y) ),
        ( dif(A, Y) ; dif(B, X) ),
        not_neighbours(A, B, [Y|Rest]).

A few test cases make us more confident about the predicate's correctness:

?- not_neighbours(a, b, [a,b]).
false.

?- not_neighbours(A, B, [A,B]).
false.

?- not_neighbours(A, B, [_,A,B|_]).
false.

?- not_neighbours(A, B, [_,B,A|_]).
false.

?- not_neighbours(a, b, [_,a,c,_]).
true .

Note that this definition works correctly also if all arguments are variables, which we call the most general case.
A drawback of this solution is that (;)/2 creates many alternatives, and many of them do not matter at all. We can make this significantly more efficient by another algebraic equivalence that lets us get rid of unneeded alternatives:
¬ A ∨ B ≡ A → B
So, in our case, we can write (¬ A = X ∨ ¬ B = Y) as A = X →B≠Y.
We can express implication in Prolog with the powerful if_/3 meta-predicate:
impl(A, B) :- if_(A, B, true).

And so we can declaratively equivalently write our solution as:

not_neighbours(_, _, []).
not_neighbours(_, _, [_]).
not_neighbours(A, B, [X,Y|Rest]) :-
        impl(A=X, dif(B, Y)),
        impl(B=X, dif(A, Y)),
        not_neighbours(A, B, [Y|Rest]).

Sample query:

?- not_neighbours(a, b, [x,y]).
true ;
false.

And a more general case:

?- not_neighbours(a, b, [X,Y]).
X = a,
dif(Y, b) ;
X = b,
dif(Y, a) ;
dif(X, b),
dif(X, a) ;
false.

You can use this predicate for checking and generating answers. Try for example iterative deepening to fairly enumerate all answers:
?- length(Ls, _), not_neighbours(A, B, Ls).

Remarkably, pure logical reasoning has thus led us to a general and efficient Prolog program.
dif/2 may at first appear unusual to you, because it appeared in the very first Prolog system and was then for a time ignored by some vendors. Nowadays, dif/2 is becoming available (again) in an increasing number of implementations as an important built-in predicate that allows you to declaratively state that two terms are different. The massive confusion that its impure alternatives usually cause in Prolog courses can be avoided with dif/2.

A: If you want to generate the not-neighbors, \+ won't do as it is by definition semidet and never binds a variable.  You need something that
constructs answers.  One option is to generate all pairs and then use your \+ neighbor(...) to filter the non-neighbors.  A direct constructive approach isn't that hard either, although the need to have both orderings complicate the code a little:
not_neighbor(C1, C2, List) :-
    append(_, [C10,_|Postfix], List),
    member(C20, Postfix),
    swap(C1,C2, C10,C20).

swap(X,Y, X,Y).
swap(X,Y, Y,X).

See http://swish.swi-prolog.org/p/njssKnba.pl


text:
Q: how to map 1V - 10V to 1.6V to 3.2V for voltage regulation using TL494 I am trying to design the given circuit where pin 1 is the non inverting terminal of comparator where I want to use a ref voltage of 1V - 10V but IC TL494 is accepting a voltage of 1.6V to 3.2V....and pin 2 m trying to give an o/p voltage feedback which varies from 10V - 100V through resistor divider circuit.. So how could i can map (1- 10V) to (1.6 to 3.2)V through resistor divider circuit..

A: When you're mapping one voltage range to another there's a scaling factor and an offset.
Take the range of the voltages you're converting from, you've stated two different ranges, 10-100 and 1-10, we'll use the former.
100 - 10 = 90
And the range you're converting to
3.2 - 1.6 = 1.6
to scale 90 to 1.6 you would divide:
90 / 1.6 = 56.25
That's the division ratio you need. Now you need the offset.
Take the low value you're converting from, divide by the scaling factor, and the see how much off that is from the low value you're converting to:
10 / 56.25 = 0.1777...
1.6 - 0.1777... = 1.4222...
So you need to add 1.4222... V to whatever you get out of your divider.
Let's check that with 100 V.
100 / 56.25 = 1.777...
1.777... + 1.4222... = 3.2
So you need to divide by 56.25, and add 1.4222..., the division can be done with a voltage divider, the addition can be done with an opamp.


text:
Q: How do I open a file for edit as root with Aquamacs? I'm using Aquamacs to do most of my text editing, and would like to, selectively, open some files as root when editing them.
Is there a way for me to open some files as root with Aquamacs (and not the rest)?
I know that I can just start Aquamacs with a sudo command, but that's a bit too risky for me - I'd rather only have root permissions for editing files which absolutely require it.

A: You can open a file as root using TRAMP (bundled with Emacs since version 22.1):
C-x C-f /sudo:root@localhost:/path/to/file RET
If you don't insert the username@host part, TRAMP defaults to root@localhost when using /sudo, so you can shorten the syntax to
C-x C-f /sudo::/path/to/file RET


text:
Q: CreateProcess returns handle different than launched Chrome.exe I am using CreateProcess and giving Chrome.exe as the argument.
I am getting the handle of the process I created using PROCESS_INFORMATION which internally has hProcess
When I print the PID using GetProcessId(handle) I am getting a different PID than the ones showing in the task manager.
I have tried setting callback function to trigger after Chrome.exe exists, but it triggers anyway. This is expected (not desired) since Chrome.exe PID is different.
It seems like when I use CreateProcess on Chrome.exe, chrome takes liberty to start its own new process and render all my control useless.
I have tried using it with FireFox.exe and it worked well, I got the handle it pointed to the correct process.
Is it not possible to get handles to Chrome processes I spawn?

A: The Chrome process you are spawning with CreateProcess() is, in turn, spawning its own child process(es) and then terminating itself.  Your Firefox is not doing that, at least not initially (Firefox does use child processes for  browser tabs - most modern browsers do, for security and stability).
So, the Chrome PID/handle you get from CreateProcess(), albeit valid, is short-lived and clearly useless for your needs.
But, all is not lost. You can get notified about the child PID(s) that Chrome itself spawns. Add your spawned Chrome process to a job object, then use SetInformationJobObject() to assign that job to an I/O completion port, then use GetQueuedCompletionStatus() to receive events from the job, in particular JOB_OBJECT_MSG_NEW_PROCESS whenever a new process is created in the job, and JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO when all processes in the job have ended.  See How do I wait until all processes in a job have exited? for more details.


text:
Q: Resolving SQL "The network path was not found" error I have built a very small ASP.NET site using MS Access 2010 as the database, which works in test mode. This is for an offline intranet application, so I'm not concerned about security - hardware access is the route for hacking here. This is all being built in VS WebExpress 2012.
When I try to publish to IIS 7.5, open the website's splash page and then proceed to page two, I'm being given two top-tier error messages:

[Win32Exception (0x80004005): The network path was not found]
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]

My connection string is:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="C:\inetpub\wwwroot\App_Data\PersonalArt Version 0055.accdb";Persist Security Info=True

I don't know why this is creating a SQL Server error, as I'm not trying to use SQL Server.
I've tried looking into the SQL Server side of things here. I have checked that SQL Server is running, that SQL Browser is enabled and running, and that the appropriate ports are open in the firewall.
I have added a connection string to IIS 7.5 that at least points to ACE.OLEDB.12.0, but I cannot remove the default connection string for SQL Server Express.
I've looked here about the construction of connection strings, and I've seen instructions about removing bad connections strings and replacing them here (but I'm afraid of this because I don't understand it).
I intend to use a WIFI tablet controller, and I've established that IIS is working well enough that I can see an index page on the controller.
So I've been bouncing around trying to figure out if this is an IIS problem, a SQL install/manage problem, or a firewall/security problem.

A: For Error 0x80004005:
Idea #1: try removing the double quotes around the directory listing and re-test your code (I mention this even though you may have already tried it):
"C:\inetpub\wwwroot\App_Data\PersonalArt Version 0055.accdb"

Idea #2: The error does say The network path was not found. Try creating a local share and give the IIS account at least read permissions to that share changing the directory listing to something like
\\MyServer\MyShare\PersonalArt Version 0055.accdb

Idea: #3: As a DBA I do cater towards SQL Server so I'd personally try testing the connection string itself to see if it does return data--using SQL Server. If it doesn't work here, I wouldn't expect it to work with ASP.NET either:
Try running this within SQL Server to see if you even get data back querying  to a table name within Access (unless you have a better way to test the connection string):
SELECT * FROM  OPENROWSET('Microsoft.ACE.OLEDB.12.0',
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="C:\inetpub\wwwroot\App_Data\PersonalArt Version 0055.accdb";Persist Security Info=True, 'SELECT * FROM <your table>')

But before you do, you may need to run the following in SQL Server so it recognizes ACE.OLEDB.12.0 and distributed queries:
exec sp_configure 'Show Advanced Options', 1;
RECONFIGURE;
GO

exec sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO

EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

For SqlException (0x80131904):
The SQL error sounds like another issue altogether. Try enabling SQL for remote connectivity on the production SQL box (or wherever production is connecting) within SQL Server Configuration Manager:


text:
Q: Second @media query triggers error I can't figure out where there's an error in the following CSS:
@media all and (min-width: 570px) and (max-width: 970px) {
    .contain {
        padding: 0 0 0;
    }

    .two {
        display: none;
        width: 0;
        margin-right: 0;
    }

    .two .tube {
        padding: 0 0 0;
    }

    nav#primary .contain {
        padding: 0 240px 0 0;
        margin: 0 auto;
    }

    nav#primary .contain .two {
        display: inherit;
        width: 240px;
        margin-right: -240px;
    }
}

/*
 *  Keep headers in proportion
 */

@media all and (min-width: 971px) and (max-width: 1060) {
    header#mast h1 {
        font-size: 3.2em;
    }
}

The first @media query works, the second @media block is ignored. The W3C CSS Validator complaints that "only 0 can be a length. You must put a unit after your number  ) { header#mast h1 { font-size: 1em; } }".
Am I missing something really obvious?

A: Where is the HTML ?
Well... Here is a version of what you wrote without all of the unnecessary or redundant parts. But I can't test it without the HTML.
@media (min-width: 570px) { /* =========START=== */

    .contain {
        padding: 0;
    }

    .two {
        display: none;
        width: 0;
        margin-right: 0;
    }

    .two .tube {
        padding: 0;
    }

    .primary .contain {
        padding: 0 240px 0 0;
        margin: 0 auto;
    }

    .primary .contain .two {
        width: 240px;
        margin-right: -240px;
    }

} /* =====================================END=== */

@media (min-width: 971px) { /* =========START=== */

    .mast h1 {
        font-size: 3.2em;
    }

} /* =====================================END=== */


text:
Q: OracleDatareader seems to execute an update statement I am using oracle client 11.2.0
Dll version 4.112.3.0
We have a page in our application where people can give a sql statement and retreive results. basically do an oracle command.executereader
Recently one of my team members gave an update statement as a test and it actually performed an update on a record!!!!
Anyone who has encountered this?
Regards
Sid.

A: It is a normal (albeit a bit unsettling) behavior. ExecuteReader is expected to execute the sql command provided as CommandText and build a DbDataReader that you use to loop over the results.
If the command doesn't return any row to read is not something that the reader should prevent in any case. And so it is not expected that it checks if your command is really a SELECT statement.
Think for example if you pass a stored procedure name or if you have multiple sql batch to execute. (INSERT followed by a SELECT)
I think that the biggest problem here is the fact that you allow an arbitrary sql command typed by your users to reach the database engine. A very big hole in security. You should, at least, execute some analysis on the query text before submitting the code to the database engine.

A: I agree with Steve. Your reader will execute any command, and might get a bit confused if it's not a select and doesn't return a result set.
To prevent people from modifying anything, create a new user, grant select only (no update, no delete, no insert) on your tables to that user (grant select on tablename to seconduser). Then, log in as seconduser, and, create synonyms for your tables (create synonym tablename for realowner.tablename). Have your application use the seconduser when connecting to the DB. This should prevent people from "hacking" your site. If you want to be of the safe side, grant no permissions but create session to the second user to prevent him from creating tables, dropping your views and similar stuff (I'd guess your executereader won't allow DDL, but test it to make sure).


text:
Q: Does this simple inequality have a name? Let $x_{1},\ldots,x_{n}$ be nonnegative numbers such that $m \leq x_{i} \leq M$. Let
$$
S=\sum_{i=1}^{n}{x_{i}}
$$
and
$$
Q=\sum_{i=1}^{n}{x_{i}^{2}}.
$$
Then
$$
Q \leq S(M+m)-nMm.
$$
This has been recently discovered by at least two different people (including myself) but I am sure that it has come up many times before. Does it have a standard name or reference?

A: As @J.E.Pascoe notes the question reduces to the case $n=1$. The fact that $m\leq x$ and $x\leq M$ imply that $x^2+Mm \leq mx + xM$ is a special case of the rearrangement inequality.

A: I first came across this inequality (n=1 case) from the short note  http://www.ams.org/journals/proc/1965-016-05/S0002-9939-1965-0180561-X/S0002-9939-1965-0180561-X.pdf
which says that if $m\le A\le M$, then $(M-A)(A-m)$ is again positive semidefinite. This inequality has intimate connection with the Kantrovich inequality.


text:
Q: access query for repeated records that that have one criteria but not other i have 2 tables in msaccess that one have multiple repeated records, and i want to filter this for the same field (date) but different criteria, i only want to see the records that exist in table2 and too in table1 and the date is less than some "dd/mm/yyy" but at the same time this record does not have any entry greater than the same date in the table1. something like this
------------SQL TABLE1 -----------
date            | IDkey        | user_name       | address
04/15/2015      | 111111       | Jean Gray       | 555 Bergen St.
15/04/2015      | 112233       | Homer Simposn   | 123 Main St.
10/04/2015      | 112233       | Homer Simpson   | 455 XYZ Ave.
04/03/2015      | 123456       | Peter Griffin   | 780 111th St.
04/02/2015      | 654321       | Charles Xavier  | 555 Bergen St.
04/12/2014      | 112233       | Homer Simpson   | 123 Main St.
04/11/2014      | 654321       | Charles Xavier  | 555 Bergen St.
04/11/2014      | 111111       | Jean Gray       | 555 Bergen St.

------------SQL TABLE2 -----------
 IDkey        | user_name       | address
 112233       | Homer Simposn   | 123 Main St.
 123456       | Peter Griffin   | 780 111th St.
 654321       | Charles Xavier  | 555 Bergen St.
 111111       | Jean Gray       | 555 Bergen St.

SELECT table2.idkey, table1.idkey, table1.date, table1.username
  From table1,table2
  Where table2.idkey=table1.idkey
    And table1.date < DateValue('01/04/2015')
    AND table1.date IS NOT > DateValue('01/04/2015');

must be not repeated values in the result
the result for this query must be:
------------RESULT-----------
 IDkey        | user_name       | address
 123456       | Peter Griffin   | 780 111th St.
 654321       | Charles Xavier  | 555 Bergen St.

A: Use NOT EXISTS, like this:
  SELECT table2.idkey, table1.idkey, table1.date, table1.username
  From table1 INNER JOIN table2 ON table2.idkey=table1.idkey
  Where table1.date < DateValue('01/04/2015')
    AND NOT EXISTS (SELECT 1 FROM table1 t1 WHERE t1.date > DateValue('01/04/2015'));

And use joins

A: i might have syntax issues here but, try this:
SELECT Distint t2.IDKey, t2.user_name, t2.address
from table2 t2
join table1 t1
on t1.IDkey = t2.IDKey
where
( t1.[date] < DateValue('01/04/2015') and  t1.[date] !> DateValue('01/04/2015'))