Q:

Proof that $[0,1]^{\Bbb R}$ is not sequentially compact

Can anyone please help me with this proof:

Prove that  $[0, 1]^\mathbb{R}$, where $[0, 1]$ is the unit interval in the standard topology, is NOT sequentially compact.

I need to create a sequence which has a converging subsequence, I think it is compact and therefore it is countably compact and limit point compact, correct me if I am wrong.
Thank you

A:

An observation which makes my life easier: the infinite power like $[0,1]^{\mathbb{R}}$ (in the product topology) only "depends" on the size of the index set: if $\phi: I \rightarrow J$ is a bijection then $[0,1]^I$ is homeomorphic to $[0,1]^J$ by "shuffling coordinates" : for $f \in [0,1]^I$ define $h(f) \in [0,1]^J$ (recall that elements of the power are just functions from $I$ or $J$ into $[0,1]$) by $h(f)(j) = f(\phi^{-1}(j))$, so that $\pi_j \circ h = \pi_{\phi^{-1}(j)}$. The last identity shows that $h$ is continuous (the compositions with projections are continuous) and $h$ has an obvious inverse $\hat{h}(f)(i) = f(\phi(i))$ for all $i \in I, f \in [0,1]^J$, also continuous for the same reasons.
So, as $|\mathbb{R}| \simeq |\{0,1\}^\mathbb{N}|$, we might as well use the latter set as the index set for the power.
Define a sequence $f_n \in [0,1]^{\{0,1\}^\mathbb{N}}$ by $f_n(\omega) = \omega_n$, where $\omega \in \{0,1\}^\mathbb{N}$,( so just a sequence of $0$'s and $1$'s). This sequence has no convergent subsequence by a standard diagonal argument:
Suppose it has a convergent subsequence, so that there are $n_1 < n_2 , <\ldots n_k < \ldots$ in $\mathbb{N}$ such that there is some $f \in [0,1]^{\{0,1\}^\mathbb{N}}$ such that $f_{n_k} \rightarrow f$ as $k \rightarrow \infty$.
Because we are working in the product topology (a.k.a. the topology of pointwise convergence) this exactly means (or at least implies by continuity of projections) that
$$\forall \omega \in \{0,1\}^\mathbb{N}: f_{n_k}(\omega) \rightarrow f(\omega), \text{ as } k \rightarrow \infty$$
Now define a special sequence $\hat{\omega} \in \{0,1\}^\mathbb{N}$ as follows:
$\hat{\omega}_{n_{2k}} = 1$ for all $k$, and $\hat{\omega}_n = 0$ for all other $n$ not of the form $n_{2k}$.
For $\hat{\omega}$ we have that $f(\hat{\omega})$ equals the limit of $f_{n_{2k}}(\hat{\omega}) = \omega_{n_{2k}} \equiv 1$ for the subsequence $f_{n_{2k}}, k \rightarrow \infty$ so $f(\hat{\omega}) =1$ but also $f(\hat{\omega})  =\lim_k f_{n_{2k+1}}(\hat{\omega}) = \omega_{n_{2k+1}} = 0$, as a constant sequence of $0$'s. So the pointwise convergence fails for this coordinate $\hat{\omega}$, so there can be no convergent subsequence.
As an aside: we could have played the same trick using the reals as the index set and using decimal expansions (but then you'd have to be precise about ambiguous expansions (do you use 0.99999 or 1.0000) etc.) As a diagonal argument I find using the $0-1$-sequences as index set "cleaner"; we could also have used the power set $\mathscr{P}(\mathbb{N})$ as an indexing set and the "equivalent" sequence $f_n(A) = 1$ iff $n \in A$, which makes the analogy to Cantor's argument a bit more direct...)
It is quite a lot harder to show that this size of the index set (continuum, $\mathfrak{c}$) is the smallest for which this always happens : e.g. if the continuum hypothesis fails and $\aleph_1 < \mathfrak{c}$, it is consistent that $[0,1]^{\aleph_1}$ is sequentially compact, even though the index set is uncountable while $[0,1]^{\mathfrak{c}}$ will always be compact and not sequentially compact (the same argument remains valid).
Large products also give (IMHO) natural examples of the reverse phenomenon: sequentially compact spaces that are not compact:
Define the following subspace of $[0,1]^I$ (where $I$ is uncountable):
$$\Sigma [0,1]^I = \{f \in [0,1]^I: \sup(f) \text{ at most countable }\}$$
were $\sup(f) = \{i \in I: f(i) \neq 0\}$, so the set of functions that are $0$ almost everywhere (except on the countable support set $\sup(f)$.
This set is easily shown to be dense in $[0,1]^I$ (even finite support would do, using basic open sets), so cannot be compact (it would be closed in [0,1]^I, not dense..) but it is  sequentially compact: suppose $(f_n)$ is a sequence in $\Sigma[0,1]^I$, define $J = \bigcup_n \sup(f_n) \subset I$, which is countable as a countable union of countable sets. Note that by definition, for all $n$ and all $i \notin J$: $f_n(i) = 0$, so outside $J$ we have a constant $0$ sequence in all coordinates. Then observe that $[0,1]^J$ is homeomorphic to $[0,1]^\mathbb{N}$, the Hilbert cube, which is metrisable in the infinite product metric (remember the first remark of this post). $[0,1]^J$ being compact metrisable, is sequentially compact so there is a convergent subsequence $f_{n_k}\rightarrow f$ in $[0,1]^J$. So we have pointwise convergence to $f$ on $J$ and setting $f(i) = 0$ for all $i \notin J$, we have it for all coordinates.
So $\Sigma[0,1]^I$ is sequentially compact and not compact. So neither property implies the other in general. (they do for metric spaces as is well known).


Q:

calling another activity function inside an activity via handler doesn't work

I want to start a CountDownTimer from another activity. I use handlers to do that, but it doesn't work. Which part am I doing wrong?  This is my code:
activity1.java :
public class Activity1 extends Activity {
public static Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initHandler();
mHandler.sendEmptyMessage(1);

startActivity(new Intent(Activity1.this, Activity2.class));
}

private void initHandler(){
mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        switch (msg.arg1) {
        case 1:
            mCountDownTimer.start();
            break;
        }
    }
};
}

private CountDownTimer mCountDownTimer = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
    Toast.makeText(Activity1.this, "Count is: "+ millisUntilFinished/1000,    Toast.LENGTH_SHORT).show();
}

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

}
};
}

activity2.java :
public class Activity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Activity1.mHandler.sendEmptyMessage(1);

}
}

Why is this not working?

A:

In your initHandler() method, change your condition in switch case from switch (msg.arg1) to switch (msg.what)
According to Android Developer site sendEmptyMessage(int) Sends a Message containing only the what value.


Q:

Big query: result is hiding rows where a record is null

I have imported data from Firestore to BigQuery.
I have a field called "hole", which has a planned depth (planned depths can never be null), and an array of measured depths (this can be null). A measured depth has a value, date and person.
If I do a query where I just ask for the planned depths, all the holes are visible in the resulting table:
select name,  un_holes.Number as hole_number, un_holes.PlannedDepth.Value as planned_depth
from reporting.reporting_data_staging ,unnest (Holes) as un_holes
where mineName = 'Frasure Creek Mining'

This query gives me back all 100 records.

However, when I add the measured depths, I get only 8 rows back, which are the rows where the measured depth is not null:
select name,  un_holes.Number as hole_number, un_holes.PlannedDepth.Value as planned_depth,
         un_measured.Value as measured_depth
from reporting.reporting_data_staging ,
     unnest (Holes) as un_holes,
     unnest (un_holes.MeasuredDepths) as un_measured
where mineName = 'Frasure Creek Mining'

The result that would like to see the data from the second image, with a blank or null value against the rows were there is no measured data, instead of the rows being cut completely.
I am new to BigQuery and I have done SQL a long time ago. I've searched for similar questions, but I might have made the mistake of not phrasing my search correctly and so have may inadvertently missed out on similar questions, so apologies if I have done this.

A:

Use left joins to keep rows that have empty arrays:
select name,  un_holes.Number as hole_number, un_holes.PlannedDepth.Value as planned_depth,
         un_measured.Value as measured_depth
from reporting.reporting_data_staging left join
     unnest (Holes) as un_holes
     on 1=1 left join
     unnest (un_holes.MeasuredDepths) as un_measured
     on 1=1
where mineName = 'Frasure Creek Mining';

When using unnest() with left join, I think the on clauses are unnecessary.  I am not yet progressive enough to leave out on clauses for joins yet.


Q:

Bootstrap modal dialogs with a single text input field always dismiss on Enter key

Why does this simple modal dialog with one text field (and NO buttons) dismiss when the focus is on the field and Enter is pressed?
New Folder

Add Device Folder

    <form class="form-horizontal">

        Folder Name

          <input id="dlgAddDeviceFolder_name" type="text" placeholder="Folder Name" autocomplete="off">

    </form>

There is extensive discussion here that suggests it is a button issue (I have put type="button" on button and anchor tags.  I have converted button tags to anchors).  However, I tried all solutions proposed and then ended up just completely commenting out the buttons, and it still happens.
Note that if you simply duplicate the same text input and have two fields, the problem goes away (focusing on either text field will not cause dismissal on Enter)

A:

Thanks to @mccannf for pointing me in the right direction.  This seems to be a more general form submit issue than anything specific to Bootstrap.  Two solutions:
1. Set the form's onsubmit attribute to onsubmit="return false;"
(https://stackoverflow.com/a/1329168/569091)
I like this solution the best as it seems hard to predict (and is perhaps browser dependent) which form fields may or may not trigger a form submit on typing Enter.
So, in my example from the original Question:
<form class="form-horizontal" onsubmit="return false">

2. Set the onkeydown (or onkeyup?) attribute to return false when event.keyCode == 13
(https://stackoverflow.com/a/2037935/569091)
In this link, onkeyup worked, but I had to use onkeydown (browser dependent?)
So, in my example from the original Question:
function ignoreEnter(event)
{
  if (event.keyCode == 13) {
    return false;
  }
}

// and this in the HTML
<input id="dlgAddDeviceFolder_name" type="text" placeholder="Folder Name" onkeydown="return ignoreEnter(event);">

A:

Its just to clarify the answer before and to respond to the raykin comment.
1. Set the form's onsubmit attribute to onsubmit="return false;" (https://stackoverflow.com/a/1329168/569091)
This solution is helpful when you control the submit of the form by javascript as an example

      <button class="close" data-dismiss="modal" aria-hidden="true">×</button>

{% trans "Create" %}

       <form method="POST" class="form-horizontal" onsubmit="return false">
           <input id="id_name" maxlength="250" name="name" type="text">
       </form>

    <button id="save-button" class="btn">{% trans "Save" %}</button>
    <button class="btn" aria-hidden="true">{% trans "Cancel" %}</button>

As you can see to do a form submit is through the jquery call onclick of the button save id.
But if you want to add action to form tag, then you maybe have to use the second solution
2. Set the onkeydown (or onkeyup?) attribute to return false when event.keyCode == 13 (https://stackoverflow.com/a/2037935/569091)
In my opinion, I dont like this solution in case you want to build the form dinamically.

A:

Just a comment to Mara Jimenez post:
There is another way to use action tag, and not to play around with events. You can add dummy invisible input in form, and Enter key would not submit it. Here is sample:
<form role="form" method="post" action="submitform.php">
    <input type="text" id="name" name="name" >
    <input type="text" style="display: none;">
</form>


Q:

Problems starting MongoDB when installing MongoDB on Windows 7

I am following the tutorial: http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/
I am trying to start mongo db by running the mongod.exe file. I write the following in the command prompt: C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe
This path exist and contains the file. I have tried to start the command prompt as an administrator. When I write this I get the follwoing feedback (translated from Swedish): C: "Program is not an internal command, external command, a program or command file
Do you have any ideas what I have to do to run the exe file? Please let me know if you need more information.

A:

Use quotes when using the full path or cd to the directory that contains the exe and run it. The spaces in the path are causing the problem


Q:

Predicate для поиска с апострофом

Как задать предикат, чтобы поиск осуществлялся с апострофом?
Мой код:
let searchPredicate = NSPredicate(format: "name contains[cd] %@", searchText)
Например мне надо найти Daniel's, я пишу Daniels, и ничего не найдено. Находит только если написать Daniel.

A:

Возможно несколько грязно, но попробуйте так:
let searchAllText = searchText.characters.map({"*\($0)"}).joined()
let searchPredicate = NSPredicate(format: "name like[cd] '\(searchAllText)*'")

UPD Думал только текст.
Для начала нужно решить что делать с апострофом + можно сделать чтоб не экранировать(ну по сути вернуть что и было у Вас). Первый вариант - не обращать особо внимание:
let searchAllText = searchText.characters.map({"*\($0)"}).joined() + "*"
//либо вариант 2 - вообще исключить его
//let searchAllText = searchText.replacingOccurrences(of: "'", with: "").characters.map({"*\($0)"}).joined() + "*"
let searchPredicate = NSPredicate(format: "name like[cd] %@", searchAllText)

Ну и третий вариант - если пользователь поставил апостроф, то не искать между всеми буквами его:
var searchAllText: String
if searchText.contains("'") {
    searchAllText = "*\(searchText)*"
} else {
    searchAllText = "\(searchText.characters.map({"*\($0)"}).joined())*" //пусть уже в одном стиле формирование строки
}


Q:

How do you get all the descendents of a DOM element which have any class defined?

I'm fairly new to jQuery and javascript in general, and I'm looking to return only the DOM elements which have a class defined. For example:

hello world

bar

foo

I'm wondering if there exists a jQuery function or a clever search parameter I can pass to $(#myObject).find(...) which would return only .foo and .bar, since those are the only two DOM elements which have a class defined. To generalize, would it also be possible to search for the presence of any attribute?
It seems I can do this using a more complex string of function calls, such as
var toReturn = [];
var descendants = $('#myObject').find('*');
$.map(descendants, function (element, index) {
    if(element.getAttribute('class') != undefined){
      toReturn.push(element);
    }
});

But if there's something simpler, it would be helpful to know about it.

A:

Use $('#myObject [class]:not([class=""])').  It will select all descendants of #myObject that have a class defined, and it will exclude elements that have had a class removed.  (Thanks to @TravisJ for the not syntax!)
Snippet:

$('.byebye').removeClass('byebye');

$('#myObject [class]:not([class=""])').addClass('selected');
.selected {
  color: green;
}

hello world

bar

foo

    class removed

    no class here

  none here either


Q:

Find a random Local Drive and download files there

As the title says, I want to find a random local drive and download some files inside the drive.
Well, thats my actual line:
powershell.exe -Command "& {if($PSversionTable.PSVersion.Major -ge 3) {Invoke-WebRequest http://download1475.mediafire.com/dgmccvd5felg/cu6x9bzhx3hmz78/Teste.jpg -OutFile atf3@~~.exe}}"

As you can see, I already have a way to download the files, but I want these files to be downloaded inside this random drive, and I need some help with that.
It will happen in another computer, so I don't have how to know nothing about the local drives, so prepare this script for any situation please, and I need that script to run in one single batch file.

A:

You can pick a random local drive and change the working directory to its root folder like this:
$root = (Get-WmiObject Win32_Volume -Filter 'DriveType=3 AND NOT DriveLetter IS NULL' | Get-Random).DriveLetter + '\'
Set-Loction $root


Q:

If statement that checks if a user entered string contains user entered letters excluding any extra letters

I need to create a program in which a string and 5 letters are entered by the user and the program checks if the string can be created again from those 5 letters, but ignores any letters that the string cannot be created from.
For example, if I enter the word "hello" and then I enter the 5 letters "h", "e", "l", "o", and "p", I want the program to makes sure that those letters do make up the word "hello", but ignores any extra letters, which in this case is the "p". Another example, if I enter the word "apple" and then I enter the 5 letters "a", "p", "l", "o", and "f", I want the program to recognize that those letters do not create the word apple and to ignore the letters "o" and "f".
If the program does verify that the string can be created from those 5 letters, while ignoring any extras, then it will output "You win!", but if not it will output "You lose!". Here is the code I have so far:
public static void main(String[] args) {

    Scanner keyboard = new Scanner (System.in);
    System.out.print("Please enter a word: ");
    String in = keyboard.nextLine();
    System.out.print("Please enter the first letter: ");
    String letter1 = keyboard.next();
    System.out.print("Please enter the second letter: ");
    String letter2 = keyboard.next();
    System.out.print("Please enter the third letter: ");
    String letter3 = keyboard.next();
    System.out.print("Please enter the fourth letter: ");
    String letter4 = keyboard.next();
    System.out.print("Please enter the fifth letter: ");
    String letter5 = keyboard.next();

    if (in.contains(letter1 + letter2 + letter3 + letter4 + letter5)) {
        System.out.println("You win!");
    } else {
        System.out.println("You lose!");
    }

}

Here is the output I am getting when I run this:

I am new to Java so I do not know if there is some kind of code I could use to do this. If somebody does know, please lead me in the right direction.

A:

The easiest algorithm I can think of is: For each character inputted, remove all occurences from the string. At the end, check if string is empty. Or in code:
char[] cs = new char[] {'h', 'e', 'l', 'o', 'p'};
String s = "hello";
for (char c : cs) s = s.replace(c+"", "");
if (s.isEmpty()) System.out.println("You win!");

Note that this approach is not performing very well. For a given number of characters n and a string length m this performs as O(n*m). It also does a lot of costly String reallocations.


Q:

Enable access to location Windows 8 app (Geolocator)

I'm using Geolocator. So I have async method OnPositionChanged() and everything should be good. But I have problem with getting access to location. If I use Windows 8 Sample Geolocation App everything works ok. I have Message that app use location I give access and it works, but in my application this message not appears and status of Geolocator is Disabled. How can I give access to location to my app programmatically?

A:

Similarly to Windows Phone, using a location requires you as a developer, to explicitly declare that your application will require access to the location API. This is set in the application manifest. In a Solution explorer, look for Package.appmanifest item and double click on it to open – the manifest properties window will open.
Click on the Capabilities tab. Check Location capability (just under it).


Q:

Network database access - How do I connect to a remote database?

I am able to connect to a specific MS Access Database when it is on the same Windows computer as Mathematica via the command
<< DatabaseLink`;
conn = OpenSQLConnection[JDBC["odbc", "Databasename"]];

However, I cannot figure out how to connect to this database over a local area network -- disregarding trivial network problems (the computers can ping eachother), is this even possible?

A:

Empirically, it is not possible to directly connect Linux (and therefore also not MMA under Linux) to a MS Access data source in an acceptable amount of time.
An alternative solution is to migrate the .accdb -> MySQL DB, which then can be queried platform independently. How to connect to this DB is described in the MMA documentation (works out of the box). The migration step is, according to MySQL whitepapers, easily possible - I will update this post if this is the case. MS Access can still be used as a convenient frontend to the MySQL DB.


Q:

Can a pom.xml file have multiple build tags?

Can a pom.xml file have multiple build tags? Or is only one build tag allowable throughout the file?

A:

You can have multiple build profiles in a single pom.xml, each with different <build>
 configuration and you can choose which profile to build with

Related

Can I tailor a maven build based on platform?


Q:

Global list keeps changing despite copy

I'm having difficulty understanding why expqueue keeps changing to multiple iterations of state,
I've tried everything I have looked up from [:] to deep copy. Can someone explain whats wrong?
The code is for a 8 puzzle game, and if I could get a running list going of all the different
combinations I'm sure I could complete this myself, and yes, it is homework.
import copy
init = [[2,0,3], [1,5,6],[4,7,8]]
goal = [[1,2,3], [4,5,6],[7,8,0]]
expqueue = []
tempqueue = []
depth = 0

def myappend(lst1, lst2):
    new = list(lst1)
    new2 = list(lst2)
    new.append(new2)
    global expqueue
    expqueue = new

def makeState(state):
for x in range(0,3):
    for i in range(0,3):
        print state[x][i],
    print "\n"

def locate(state):
    for x in range(0,3):
        for y in range(0,3):
            if state[x][y] == 0:
                return [x, y]

def moveU(state):
    location = locate(state)
    x = location[0]
    y = location[1]
    s = x-1
    if x>0:
        swap = state[x][y]
        state[x][y] = state[s][y]
        state[s][y] = swap
        myappend(expqueue, state)

def moveL(state):
    location = locate(state)
    x = location[0]
    y = location[1]
    s = y-1
    if y>0:
        swap = state[x][y]
        state[x][y] = state[x][s]
        state[x][s] = swap
        myappend(expqueue, state)

def moveR(state):
    location = locate(state)
    x = location[0]
    y = location[1]
    s = y+1
    if y<2:
        swap = state[x][y]
        state[x][y] = state[x][s]
        state[x][s] = swap
        myappend(expqueue, state)

def moveD(state):
    location = locate(state)
    x = location[0]
    y = location[1]
    s = x+1
    if x<2:
        swap = state[x][y]
        state[x][y] = state[s][y]
        state[s][y] = swap
        myappend(expqueue, state)

def expand(lst):
    tempqueue = lst[:]
    while tempqueue != []:
        state = tempqueue[0]
        current = state[:]
        moveU(current)
        moveL(current)
        moveR(current)
        moveD(current)
        del tempqueue[0]
    return expqueue

def solve(queue, initial, solution, level):
    length = len(queue)
    for x in range(length):
        if queue[x] == solution:
            return "This works!"
    return solve(expand(queue), initial, solution, level+1)

print solve([init], init, goal, 0)

I've since added deepcopy over the initial slices, and I've noticed the ID's are coming back the same after the copy. Does anyone know why?
Apparently I don't have enough street cred to post a screen shot so here's a link to it:
Matching id's after copy

A:

You are altering the nested lists, but only copied the outer list; a list(original) or original[:] call only creates a shallow copy; the new list 'inherits' the references to the contents, and if those contents are mutable then you'll see the changes to those contents in both places.
Create copies of the nested lists:
new = [nested[:] for nested in lst1]

and
tempqueue = [nested[:] for nested in lst]

This creates a shallow copy of each nested list instead.
Or use the copy.deepcopy() function to recursively copy objects.

A:

tempqueue = lst[:] makes a shallow copy, not a deep copy. That means you get a new container list, but references to the exact same contents. Since the contents are themselves lists, you are getting references to mutable objects. If you mutate those lists in either lst or tempqueue, then the other is also affected.
If you want a deep copy of a list of lists, you could use
tempqueue = [[x for x in item] for item in lst]

or
tempqueue = [list(item) for item in lst]

or
tempqueue = [item[:] for item in lst]

or, for even more deeply nested structures, you could use
tempqueue = copy.deepcopy(lst)

The example here shows the difference between using a shallow versus a deep copy.


Q:

Show unconfirmed email addresses in the preferences tab

The email for getting notifications can be changed by clicking the "preferences" tab in your profile. After entering a new email address, the "Save email settings" button becomes clickable:

Clicking the button turns it grey:

So all looks well. But if you don't confirm the email by clicking on the link sent to your email inbox, the next time you go back to the preferences, you will see your old email address with no indication that it changed.
You can subscribe to the weekly newsletter from the "edit" tab of your profile. If you click the option and save, the next time you visit the edit page before confirming your email you get this message:

Once you confirm the email, the resend link disappears so you know the subscription is set up:

Ideally, the two systems would be unified so that all email subscriptions happen the same way. But short of that, it would be very helpful to indicate that an email address is unconfirmed for notification emails just like newsletters.

A:

We've been getting quite a few emails regarding this, of users being absolutely confused about why their settings are not updating. Unless they have notifications for new emails like I do, they're not going to know that there's some magical link in an email sitting inside their inbox. Nothing told them to look there. There's no instructions anywhere on that page that say they will have to confirm the new email address they enter.
It seems like there are a couple of simple things that could be done to achieve this:

Upon clicking the Save button, if they changed their email, display a popup message informing them that the changed email will need to be verified and that they should check their inbox.
When viewing the page while a confirmation email is still pending, include a message above the form that indicates they attempted to change their email recently and that the confirmation is still pending, preferably with a resend link like in the right sidebar (image in your question).

A:

This will be implemented in build 3933 in MSE/MSO, and 3039 on other sites.
The two systems are still not unified, so the pending-verification email addresses are not actually synced up between the two systems, but there is some sort of pending verification setting now.


Q:

Post on a page on facebook

How can I (programatically, duh!) post on my page on facebook? I'm talking about an actual Page in the sense of the Facebook API, e.g. like this.
I read my way through most of the Graph API, but I can't really come to grips of which endpoint to use in order to post something.
I already roughly know how to get my authentication, but when I want to access my page through the graph API, it just returns false.

A:

You need to get access_token for the page - read this on how to get the right access_token (just change the permissions to what you need) - Facebook: post image and description to wall and in page album via php
once you have the right token you post the same way as to any user's feed, e.g. https://graph.facebook.com/<page_id>/feed


Q:

Canceling a creature spell during combat

Ok, so I play Shaman of the Pack (I'm using an elf deck) whilst having a few elves (6 or so), and my opponent takes the damage. His creatures are tapped out, and I have a 5/4 elf with an artifact equipped that gives +1/+1 for each creature that shares a type with it, and I begin to declare attackers. At this time, he decides to counter Shaman of the Pack. Is this a legal move or is he in the wrong?

A:

If he has said that he takes the life loss from Shaman of the Pack then the spell has already resolved, entered the battlefield, the enter-the-battlefield-trigger has been put on the stack and resolved. It is then way too late to decide to counter the Shaman.
If he had not yet acknowledged the life loss from the Shaman verbally or by obvious gesture, then he still retains priority and you cannot decide to move to combat.
The important thing is that he acknowledged the loss of life.

A:

It is too late for your opponent to counter Shaman.
You mentioned that your opponent took the damage from Shaman's "enters the battlefield" triggered ability. Your opponent cannot take damage from an "enters the battlefield" trigger and then decide to back the game up to counter the creature that entered.


Q:

Re-create table with Entity Framework 5 and nuget

I am using Code First to create a table.
I created the class, the mapping file and issued the add-migration command in nuget and then the update-database command
I then changed the class and like an idiot deleted the table.
I deleted the migration class file
I issued a add-migration command
When I issue the update-database command I get the following error:

System.Data.SqlClient.SqlException (0x80131904): Cannot find the
  object "dbo.CorrectiveActionPlan" because it does not exist or you do
  not have permissions.    at
  System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
  Boolean breakConnection, Action1 wrapCloseInAction)    at
  System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
  exception, Boolean breakConnection, Action1 wrapCloseInAction)    at
  System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
  stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)    at
  System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
  SqlCommand cmdHandler, SqlDataReader dataStream,
  BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
  stateObj, Boolean& dataReady)    at
  System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String
  methodName, Boolean async, Int32 timeout)    at
  System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1
  completion, String methodName, Boolean sendToPipe, Int32 timeout,
  Boolean asyncWrite)    at
  System.Data.SqlClient.SqlCommand.ExecuteNonQuery()    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction
  transaction, MigrationStatement migrationStatement)    at
  System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction
  transaction, MigrationStatement migrationStatement)    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable1
  migrationStatements)    at
  System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable1
  migrationStatements)    at
  System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String
  migrationId, XDocument targetModel, IEnumerable1 operations, Boolean
  downgrading, Boolean auto)    at
  System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration
  migration, DbMigration lastMigration)    at
  System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration
  migration, DbMigration lastMigration)    at
  System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1
  pendingMigrations, String targetMigrationId, String lastMigrationId)
  at
  System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable1
  pendingMigrations, String targetMigrationId, String lastMigrationId)
  at System.Data.Entity.Migrations.DbMigrator.Update(String
  targetMigration)    at
  System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String
  targetMigration)    at
  System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
  at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
  ClientConnectionId:a6e92a35-cc9e-4867-97a5-0a274081d853 Cannot find
  the object "dbo.CorrectiveActionPlan" because it does not exist or you
  do not have permissions.

How do I force EF to recreate the table?

A:

I found my answer.
I deleted the row in [dbo].[__MigrationHistory] that corresponded to my Migration
I then deleted the new migration file
I re-ran add-migration
and then re-ran update-database -verbose


Q:

angular.js:xxxx Error: [$injector:unpr] Unknown provider: cookiesServiceProvider <- cookiesService

I am getting the following error from angular.js library. How can i debug the below console error?
angular.js:12477 Error: [$injector:unpr] Unknown provider: cookiesServiceProvider <- cookiesService <- CatalogViewController
http://errors.angularjs.org/1.4.7/$injector/unpr?p0=cookiesServiceProvider%20%3C-ookiesService%20%3C-%20CatalogViewController
    at http://testsite/Scripts/angular_bootstrap_UI/angular.js:68:12
    at http://testsite/Scripts/angular_bootstrap_UI/angular.js:4289:19
    at Object.getService [as get] (http://testsite/Scripts/angular_bootstrap_UI/angular.js:4437:39)
    at http://testsite/Scripts/angular_bootstrap_UI/angular.js:4294:45
    at getService (http://testsite/Scripts/angular_bootstrap_UI/angular.js:4437:39)
    at invoke (http://testsite/Scripts/angular_bootstrap_UI/angular.js:4469:13)
    at Object.instantiate (http://testsite/Scripts/angular_bootstrap_UI/angular.js:4486:27)
    at http://testsite/Scripts/angular_bootstrap_UI/angular.js:9151:28
    at http://testsite/Scripts/angular-ui-router.js:4018:28
    at invokeLinkFn (http://testsite/Scripts/angular_bootstrap_UI/angular.js:8789:9)

A:

You need to include the cookies part of angular
https://code.angularjs.org/1.4.7/angular-cookies.js
and inject it in your module
angular.module('myModule', ['ngCookies'])

make sure you don't get 404 for the cookies


Q:

regular expression problem (Pattern/Matcher)

I need to find specific word on a string using regular expression.
rules :
before that word, I must not have a letter, a number or an underscore.
this word must be not followed by a letter, a number or an underscore.
Example :
I'm looking for the word 'the' in :
'Hi, it\'s a random text containing some words, the .the thingthe THE, tthe Tthe test_the@thesite.com'
in this string It must be found 3 times : the and .the and THE
so I must get true as a return.
my code :
String str = 'Hi, it\'s a random text containing some words, the .the thingthe THE, tthe Tthe test_the@thesite.com';
String var = 'the';
String s = '(?<![\\w])'+var.toUpperCase()+'(?![\\w])';
Pattern MyPattern = Pattern.compile(s);
Matcher MyMatcher = MyPattern.matcher(str.toUpperCase());
System.debug('###matches : '+MyMatcher.matches());

Matches return always false.
I tried with this also :
 '(?<![a-zA-Z0-9_])'+var.toUpperCase()+'(?![a-zA-Z0-9_])';

A:

The matches method will only return true if the entire input string matches the result. You want to use find instead, which will match a substring. Take a look at the Matcher documentation for these methods:

find()
  Attempts to find the next subsequence of the input sequence that matches the pattern. This method returns true if a subsequence of the input sequence matches this Matcher object's pattern.
matches()
  Attempts to match the entire region against the pattern.

So if you want to know whether your substring is contained anywhere in the input string, use MyMatcher.find() instead.
A couple side notes:

If you want your expression to be case insensitive, set the i flag by starting your expression with (?i).
If you want to look for a whole word, wrap it in the word boundary character (\b), not backward and forward lookaheads for non-word characters.
With the above in mind, I would change the expression to: '(?i)\\b' + var + '\\b'


Q:

How to set custom data-attribute to option with Laravel Collective

I have a form, inside I have a select with some options and I'm using Laravel Collective Forms to build it, I have something like:
{!! Form::select('size', $data, $selecteds, ['multiple' => true]) !!}

All going well until here, but now I need to set a data-section attribute to each option, how can I make it?

A:

I had to do the same thing recently. After inspecting the FormBuilder class to write my own marco I found out that the select() method actually has an undocumented fifth parameter for option attributes:
Form::select('size', $data, $selecteds, ['multiple' => true], $optionAttributes)
The index must match the value of the option, e.g.:
$optionAttributes = [
    'S' => [
        'data-title' => 'Small',
        'data-surcharge' => '0',
    ],
    'M' => [
        'data-title' => 'Medium',
        'data-surcharge' => '5',
    ],
    'L' => [
        'data-title' => 'Large',
        'data-surcharge' => '10',
    ],
];

So I ended up writing a marco which generates this array based on a collection and then uses the default select() method. Something like that:
\Form::macro('locationSelect', function ($name, $value = null, $attributes = []) {
    // Get all locations from the DB
    $locations = \App\Location::all();

    // Make an id=>title Array for the <option>s
    $list = $locations->pluck('title', 'id')->toArray();

    // Generate all data-attributes per option
    $optionAttributes = [];
    foreach ($locations as $location) {
        $optionAttributes[$location->id] = [
            'data-icon' => $location->icon,
            'data-something' => $location->some_attribute,
        ];
    }

    // Use default select() method of the FormBuilder
    return $this->select($name, $list, $value, $attributes, $optionAttributes);
});

Very convenient.
{{ Form::locationSelect('location_id') }}


Q:

Is it secure to distribute a client / server application with same SSL Key/TrustStore?

I'm working on a client / server application. Client and server connect via NIO and the connection is secured by SSL. I based my architecture on this GitHub Project.
Right now KeyStore and TrustStore (for client and server) are stored as resources to my project and loaded when they are needed during the connection process.
Is this a secure solution?
If I was to publish the application that would mean every copy of client and server would be using the same KeyStore and TrustStore. This would make things very simple. But is it safe?
The alternative solution would be to have the end user manage their certificates themselves which seems overly complicated.
EDIT:
Clarification: Client and server are mutually authenticating. They each have their own private key.

A:

It's OK to use the same key for all clients, as long as you enforce ECDHE or DHE (perfect forward secrecy). In that case the key is only used to prove identity of the client, while a new, ephemeral key is used for communication. Otherwise clients are able to sniff and decrypt each others traffic.
And of course one key for all clients means if a client's key is compromised, you need to issue a new key and distribute to all the clients.


Q:

How to extract specific content from a column of a dataframe and make new column?

I want to make a new column containing the titles (for eg: Mr, Miss, Capt etc.) of the names given in the 'Name' column below.
train_df['Name'].head()

0                              Braund, Mr. Owen Harris
1    Cumings, Mrs. John Bradley (Florence Briggs Th...
2                               Heikkinen, Miss. Laina
3         Futrelle, Mrs. Jacques Heath (Lily May Peel)
4                             Allen, Mr. William Henry
Name: Name, dtype: object

Can you explain the above task also using 'pandas.Series.str.extract'? Thank you.

A:

You can use str.extract:
df['Titles'] = df['Name'].str.extract(r', (\w+\.)')

Returns:
                                           Name Titles
0                       Braund, Mr. Owen Harris    Mr.
1  Cumings, Mrs. John Bradley (Florence Briggs)   Mrs.
2                        Heikkinen, Miss. Laina  Miss.
3  Futrelle, Mrs. Jacques Heath (Lily May Peel)   Mrs.
4                      Allen, Mr. William Henry    Mr.

You can see the regex in action here.


Q:

Compare two TimeStrings in XPath 1.0?

How can I compare these Strings in XPath1.0:
08-jul-2014 05:00:00
08-jul-2014 06:00:00

For example:
08-jul-2014 05:00:00 > 08-jul-2014 06:00:00 should return false
08-jul-2014 05:00:00 < 08-jul-2014 06:00:00 should return true
I looked at Xpath built funcions and I can't find any funciton to convert String to UTC Seconds for example...
Thanks in advance!

A:

You can use the following hack. Remove delimiters using translate() and use substring() to make it into format yyyyMMddHHmmss and then compare this atrocity.
article[number(substring(translate(translate(translate(@pub-date,'-',''),':',''),' ','') ,5,4)+substring(translate(translate(translate(@pub-date,'-',''),':',''),' ',''),2,3)+substring(translate(translate(translate(@pub-date,'-',''),':',''),' ',''),0,2)+substring(translate(translate(translate(@pub-date,'-',''),':',''),' ',''),9,6)) > number(substring(translate(translate(translate(@pub-date2,'-',''),':',''),' ','') ,5,4)+substring(translate(translate(translate(@pub-date2,'-',''),':',''),' ',''),2,3)+substring(translate(translate(translate(@pub-date2,'-',''),':',''),' ',''),0,2)+substring(translate(translate(translate(@pub-date2,'-',''),':',''),' ',''),9,6))]

I just realised that since you have month as string you are pretty much stuffed.


Q:

Angular 2 Perform Login Authentication (i am getting into infinite loop.)

I am trying to create a website backend for which I need User Authentication in Angular 2. But I am unable to resolve some of issue, this is what I am doing.
This is my routing file.
const appRoutes: Routes = [
 {
   path: 'admin',
   component: AdminloginComponent,
   canActivate: [LoggedInGuard]
 },
 {
   path: '',
   component: HomepageComponent
 },
 {
   path: '**',
   component: OurservicesComponent
 },
];

This is my gaurd file: // after successfull login i am setting is_logged_in in local storage.
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class LoggedInGuard implements CanActivate {
 constructor(private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  if(localStorage.getItem("is_logged_in"))
  {
      this.router.navigate(['/admin/dashboard']);
      return true;
  }
  return false;
}

}
** My issue is that when the url is /admin canActivate comes into action and if I get local storage I am navigating to admin/dashboard.
But if user is logged out then in this case on /admin their should be loginform, but if I navigate to /admin if not logged in then it comes into canActivate and again their is nothing in local storage so it goes to admin and so on. So what is the correct way to solve this.
Thanks in advance.

A:

It unclear what exactly you try to accomplish, but redirect with router.navigate should go with return false;, not with return true;
Either
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if(localStorage.getItem("is_logged_in")) {
      return true;
    }
    this.router.navigate(['/admin/dashboard']);
    return false;
  }

or
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if(localStorage.getItem("is_logged_in")) {
      this.router.navigate(['/admin/dashboard']);
      return false;
    }
    return true;
  }


Q:

How to know if an admin removed a Telegram bot from group?

I encounter with a problem in programming of a Telegram bot via Python!
The problem is that if I add the bot to a group which is not super group I can successfully detect that the bot is added in that group via calling getUpdate method but if admin of that group decides to remove the bot I can't detect removing process because getUpdate doesn't consider removing process!
If the group will be a super group there won't be any problems at all!
Thanks in advance!

A:

You can try getChatMember with the bots ID as the user ID.


Q:

Symfony validation optional all constraint

How do I have an Optional constraint inside an All constraint.
Basically I want to validate that a key exists inside an array, and its value is an array which can include blanks, or any value.
If I omit the key in the Collection constraint I get the error:
This field was not expected

I know I can use the allowExtraFields, but I want to validate that the key exists.
I though I would be about to use:
$optional = new Constraints\Optional();
$all = new Constraints\All($optional);

But that results in:
Fatal error: Class
'Symfony\Component\Validator\Constraints\OptionalValidator'
not found in
~\symfony\validator\Symfony\Component\Validator\ConstraintValidatorFactory.php
on line 36

Here is the full code:
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints;
$input = [
    'frames' => [
        'header' => [
            'test-header-1',
            'test-header-2',
            '',
        ],
        'content' => [
            'test-content-1',
            'test-content-2',
            '',
        ],
    ],
];
$optional = new Constraints\Optional();
$constraint = new Constraints\Collection([
    'frames' => new Constraints\Collection([
        'header' => new Constraints\All($optional),
        'content' => new Constraints\All($optional),
    ]),
]);
$validator = Validation::createValidator();
$violations = $validator->validateValue($input, $constraint);
echo $violations;

I also tried:
$optional = new Constraints\Optional([
    new Constraints\Type('array'),
]);
$constraint = new Constraints\Collection([
    'frames' => new Constraints\Collection([
        'header' => $optional,
        'content' => $optional,
    ]),
]);

But then that does not validate that the key exists.

A:

Just validate that the header and content items are arrays:
$constraint = new Constraints\Collection([
    'frames' => new Constraints\Collection([
        'header' => new Constraints\Type('array'),
        'content' => new Constraints\Type('array'),
    ]),
]);


Q:

Select most recent rows based on a DateTime field within 5 mins of current time

In a SQL Server table, I have a DateTime field and every time I have a login failure for an external web service I write the current DateTime to the table.
I currently have code that parses through the returns and determines if there are > 2 failures within 5 mins. If so I have a flag to turn off calling of the web service. I am curious if there is a way I can just use sql to return the number of rows that are within 5 mins from the current time?

A:

This will return all records that are less than five minutes old:
SELECT [Columns]
FROM [YourTable]
WHERE [DateTimeField] >= dateadd(minute, -5, getdate())

You can get more information on DATEADD here  .


Q:

Check if PHP variables are hold unique values

I have 20 variables, each holding a number between 1 and 10000.
Is there a simple way of checking that all of the variables hold a unique value, and if not sending the user away.
for example,
if($var1,$var2,$var3...etc are not unique)
{
location wherever.php
exit;
}

The front end should prevent the user submitting the same value twice however I need to check it.
Thanks :)

A:

$data   = array( /* your numbers */);
$unique = array_unique($data);

if ( count($data) != count($unique) ) {
  // not unique
}

You can also compare that arrays instead of counting their elements:
if ( $data != $unique ) {
  // not unique
}

A:

Put the values in an array.
Pass the array to the php function
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

If the array returned by the function is smaller then the input then it found non unique keys.


Q:

foreach error: cannot operate on type because it does not contain a public definition for 'GetEnumerator'

I am getting an error related to foreach which states:

Foreach statement cannot operate on type ' ' because it does not contain a public definition for 'GetEnumerator'.

I am not getting what to do with this error. Please suggest the changes to be made to improve and correct the error in the code.
public partial class Form1 : Form
{
     store store = new store();
    public List<item> insert= new List<item>();//this is the list of second list items

    BindingSource itemslist = new BindingSource();
    BindingSource selectitem2 = new BindingSource();
    public Form1()
    {
        InitializeComponent();
        setupdata();
        itemslist.DataSource = store.items;
        item.DataSource = itemslist;//linked between the two
        // what to print inside
        item.DisplayMember = "Display";
        item.ValueMember = "Display";
        //put the data to the selected item list
        selectitem2.DataSource=insert;
        selected_item.DataSource = selectitem2;

        selected_item.DisplayMember = "Display";
        selected_item.ValueMember = "Display";

    }

    private void purchase_Click(object sender, EventArgs e)
    {
        foreach (item item in selected_item)
        {

        }
    }
}

A:

you cannot iterate through a control (ListBox).
It has no enumerator as the error message tells you. You need to iterate through the underlying data collection.
In your case it would be insert
so change the loop line into this:
foreach (item item in insert)

you can though of course iterate through the Items of the ListBox:
foreach (item item in selected_item.Items)

EDIT:
Also your naming pattern is frankly rather confusing. selected_item does not sound as if it would represent a collection of things but rather one entity.


Q:

How can I align a progress indicator to the right of a label and keep the label centred in a VStack in SwiftUI?

I want to display a label in the centre of a view with a progress indicator to the right of the label.  How can I do this in SwiftUI on macOS?
The code below aligns the HStack in the centre of the VStack but I want the text centered and the progress indicator aligned with the text's trailing edge.  I guess I could replace the HStack with a ZStack but it's still not clear how one aligns two controls to each other or how one prevents the container from be centered by its container.
import SwiftUI

struct AlignmentTestView: View {
    var body: some View {
        VStack(alignment: .center, spacing: 4) {
            HStack {
                Text("Some text")
                ActivityIndicator()
            }
        }.frame(width: 200, height: 200)
            .background(Color.pink)
    }
}

struct AlignmentTestView_Previews: PreviewProvider {
    static var previews: some View {
        AlignmentTestView()
    }
}

A:

Here is possible approach (tested replacing ActivityIndicator with just circle).
Used Xcode 11.4 / iOS 13.4 / macOS 10.15.4

var body: some View {
    VStack {
        HStack {
            Text("Some text")
                .alignmentGuide(.hAlignment) { $0.width / 2.0 }
            ActivityIndicator()
        }
    }
    .frame(width: 200, height: 200, alignment:
           Alignment(horizontal: .hAlignment, vertical: VerticalAlignment.center))
    .background(Color.pink)
}

extension HorizontalAlignment {
    private enum HAlignment : AlignmentID {
        static func defaultValue(in d: ViewDimensions) -> CGFloat {
            return d[HorizontalAlignment.center]
        }
    }

    static let hAlignment = HorizontalAlignment(HAlignment.self)
}


Q:

Get count of multiple column occurrences in SQL

Have a question about a query I am attempting to write, using SQL Server 2012. I have a table with 2 columns (Agent and UN) I am focusing on. I would like to find the number off occurrences that Agent and UN occur. For example, in the table below:
+----+-------+----+
| ID | Agent | UN |
+----+-------+----+
| 1  | 27    | 1  |
| 2  | 28    | 1  |
| 3  | 27    | 1  |
| 4  | 27    | 2  |
| 5  | 28    | 2  |
| 6  | 28    | 2  |
+----+-------+----+

An example would look similar to this:
+-------+--------+----+
| Count | Agent  | UN |
+-------+--------+----+
|     2 |     27 |  1 |
|     2 |     28 |  2 |
|     1 |     27 |  2 |
|     1 |     28 |  1 |
+-------+--------+----+

The ID does not matter, I just want to get where Agent and UN occur as pairs and their counts.
My attempt was this. I would have to do this for every agent and then combine them, but I'm thinking there is probably a quicker way to accomplish this?
select count(UN) as Count, Agent, UN
Where Agent = 27
group by UN
order by count(UN) desc

A:

Group by both agent and UN, and take out the condition from the where clause, to get the count for all groups.
select      count(*), agent, un
from        tbl
group by    agent, un
order by    1 desc


Q:

Why does a temporary variable suppress the "type ascription is experimental" error?

I am using the Serde JSON crate to deserialize a JSON file to a struct, and one of the properties is optional. When the property is missing a default value (from the command line) it is substituted. This leads me to modifying my code which raises the following error, and was difficult to figure out how to fix it.
My problem is that I'm getting the type ascription is experimental error unless I assign the value to a temporary variable, and I don't understand why. I'll show the code and obmit the struct for Config as I don't think that part matters.
Here is the code that works:
    pub fn new(file_name: &str, param_urls: &[String]) -> Result<Config, io::Error> {
        let mut config: Config = Config {
            queue: None
        };
        if Path::new(file_name).exists() {
            let json = read_to_string(file_name)?;
            let c: Config = serde_json::from_str(&json)?;
            config = c;
            // ^^^^^^^ must use temporary c variable
        }
        if config.queue.is_none() {
            config.queue = Some(param_urls.to_vec());
        }
        Ok(Config {
            queue: None
        })
    }

The above took me awhile to figure out, and I don't understand why it fixes the error, but here is the original source code that raises the error.
    pub fn new(file_name: &str, param_urls: &[String]) -> Result<Config, io::Error> {
        let mut config: Config = Config {
            queue: None
        };
        if Path::new(file_name).exists() {
            let json = read_to_string(file_name)?;
            config: Config = serde_json::from_str(&json)?;
            // ^^^^^^^^^^^ ERROR! type ascription is experimental error
        }
        if config.queue.is_none() {
            config.queue = Some(param_urls.to_vec());
        }
        Ok(Config {
            queue: None
        })
    }

As a new Rust programmer coming from other languages. I simply don't understand this error, and I've Googled it without really any clear explanation. From my perspective, coming from other languages I see no difference here and don't understand what the problem was that was fixed or why.

A:

To expand my comment into an answer, type ascription is when the type of a variable is explicitly notated using a colon. An example of this is in your code already: config: Config, meaning that config has type Config. Most of the time, Rust is able to deduce the type of a variable based on its value, so type ascription isn't needed. In fact, except for a few special instances, type ascription isn't even allowed in the language yet (see this issue).
The main place where type ascription is allowed right now is when declaring variables. This is when you say something like let x: u32 = 7; or let mut s: String = "abc".to_string();. Similarly, when defining a struct, you use type ascription to describe its fields:
struct Foo {
    bar: Vec<i32>,
    baz: String,
}

The other main place that type ascription can (or must) be used is in function and closure arguments. For example
fn add_one(x: u64) -> u64 {
    x + 1
}

or let f = |t: String| t + "123". With closures, the type of the variable can often be inferred based on how the closure is used, but sometimes it's helpful to the compiler or to readers to explicitly state the type of the arguments.
In your particular case, you're using type ascription for a reassignment operation, which doesn't fall into any of the categories where type ascription is allowed right now. config: Config = serde_json::from_str(&json)?; could probably be changed to config = serde_json::from_str(&json)?; without any problems, since the compiler already knows that config has type Config. Reassignment very rarely needs type ascription since it can't change the type of the variable.


Q:

Adding TestNG to and existing Selenium Script - My pass/fail Output not matching up with TestNGs

First timer here to Stackoverflow, and a beginner to Java/Scripting/Selenium/TestNG
I created a simple script to check page meta data which correctly prints pass or fail if expected page title, I modified some code from a tutorial I found. I Later tried to add the test of some TestNG frame work modding the code a bit more, but even though say the test can fail in my print output the TestNG output fails
Here is my code thus far
package live_MetaData;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Demo{
         private WebDriver driver;
         private StringBuffer verificationErrors = new StringBuffer();

         @BeforeClass(alwaysRun = true)
         public void setUp() throws Exception {
          System.setProperty("webdriver.gecko.driver", "C:\\Automation\\SeleniumFiles\\Browser Drivers\\geckodriver.exe");
          driver = new FirefoxDriver();
          driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        }

        @Test
        public void DemoTest() throws Exception {
        String baseUrl = "http://demo.guru99.com/test/newtours/";
        String expectedTitle = "Not Meta";
        String actualTitle = "";

        driver.get(baseUrl);

        actualTitle = driver.getTitle();

        if (actualTitle.contentEquals(expectedTitle)){
            System.out.println("Test Passed!");
        } else {
            System.out.println("Test Failed");}}

        //close Fire fox
        @AfterClass(alwaysRun = true)
        public void tearDown() throws Exception {
          driver.quit();
          String verificationErrorString = verificationErrors.toString();
          if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);

    }

}}

Which gives me this output text:
Test Failed

PASSED: DemoTest

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

Thanks for any help especially if it could be explained where Im going wrong and why it should be like in (hopefully) Solution, I went from not knowing anything on Tuesday to this.

A:

Your actualTitle is "Welcome: Mercury Tours" and expectedTitle = "Not Meta"
Your code :
if (actualTitle.contentEquals(expectedTitle)){
            System.out.println("Test Passed!");
        } else {
            System.out.println("Test Failed");}

Control of problem will go to else , since if condition didn't meet. Your Test case is pass but you are printing "Test Failed" in else.
===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================

This means that Test case pass count is 1.
Test case failure count is 0.
Test case skip count is 0.
My suggestion :  Use Assertions to verify this kind of conditions.
Use this code for assertions :
@Test
        public void DemoTest() throws Exception {
        String baseUrl = "http://demo.guru99.com/test/newtours/";
        String expectedTitle = "Not Meta";
        String actualTitle = "";
        driver.get(baseUrl);
        actualTitle = driver.getTitle();
        assertEquals(actualTitle , expectedTitle );

}


Q:

How do you optimize searching a large file in Python

I have a large file containing around 8 million lines of file names, and I am trying to search for file names that include a certain value. Finding one is fine, but the issue is that I am trying to search for around 50k unique values, and the time it takes to search is immense.
with open('UniqueValueList.txt') as g:
    uniqueValues = g.read().splitlines()

outF = open("Filenames_With_Unique_Values.txt", "w")
with open('Filenames_File.txt') as f:
    fileLine = f.readlines()
    for line in fileLine:
        for value in uniqueValues:
            if value in line:
                outF.write(line)
outF.close()

I am unable to load the filenames file into memory for it is much too large. Is there any other way to optimize this search?

A:

My two theories are to (1) memory map the file and use a multiline regular expression for each value search, and (2) farm the work out to multiple subprocesses. I combined the two and came up with the following. It may be possible to do the mmap in the parent and share, but I went the easy route and just did it in each subprocess assuming the operating system will figure out efficient sharing for you.
import multiprocessing as mp
import os
import mmap
import re

def _value_find_worker_init(filename):
    """Called when initializing mp.Pool to open an mmaped file in subprocesses.
    The file is `global mmap_file` so that the worker can find it.
    """
    global mmap_file
    filenames_fd = os.open(filename, os.O_RDONLY)
    mmap_file = mmap.mmap(filenames_fd, length=os.stat(filename).st_size,
        access=mmap.ACCESS_READ)

def _value_find_worker(value):
    """Return a list of matching lines in `global mmap_file`"""
    # multiline regex for findall
    regex = b"(?m)^.*?" + value + b".*?$"
    matched = re.compile(regex).findall(mmap_file)
    print(regex, matched)
    return matched

def find_unique():
    with open("UniqueValueList.txt", "rb") as g:
        uniqueValues = [line.strip() for line in g]
    with open('UniqueValueList.txt', "rb") as g:
        uniqueValues = [line.strip() for line in g]
    with mp.Pool(initializer=_value_find_worker_init,
            initargs=("Filenames_File.txt",)) as pool:
        matched_values = set()
        for matches in pool.imap_unordered(_value_find_worker, uniqueValues):
            matched_values.update(matches)
    with open("Filenames_With_Unique_Values.txt", "wb") as outfile:
        outfile.writelines(value + b"\n" for value in matched_values)

find_unique()


Q:

How to test redirect to created instance in Flask

Having following function in  views.py:
def ask_question():
        form = QuestionForm()
        if form.validate_on_submit():
            question = Question(title=form.title.data, text=form.text.data)
            db.session.add(question)
            db.session.commit()
            return redirect('/questions/%d/' % question.id)
        return render_template('ask_question.html', form=form)

How can I get an id of created model to put it in assertion?
def test_can_post_question(self):
    response = self.tester.get('/new-question')
    self.assert_200(response)
    form = self.get_context_variable('form')
    self.assertIsInstance(form, QuestionForm)
    response = self.tester.post('/new-question', data={'title': 'What about somestuff in Flask?',
                                                       'text': 'What is it?'})
    self.assertRedirects(response, '/questions/%d' % created_question.id)
                                                     #^ how can I get id of created model here?

I'm using Flask, Flask-SQLAlchemy, Flask-Testing

A:

Query the created question object. As a side effect, you can test that the question was created.
...
q = Question.query.filter_by(title='What about somestuff in Flask?').first()
self.assertRedirects(response, '/questions/%d/' % q.id)


Q:

Double authenitcation needed with mounting a Nas In Linux Mint

I use the command and am prompted twice:
sudo mount //192.168.0.12/volume_1 /mnt/stableNas/
[sudo] password for {myUserName}:
Password:

I use the same password
This works great, but I am wondering why I have to type the password twice.  I believe this is blocking my automount(now removed) that I have attempted in the past, but will save that for another question.
If I specify the -t option I use cifs and not smbfs.
This is from my auth.log:
Dec 30 15:11:07 pino sudo:  {myUserName} : TTY=pts/1 ; PWD=/home/{myUserName} ; USER=root ; COMMAND=/bin/mount //192.168.0.12/volume_1 /mnt/stableNas/
Dec 30 15:11:07 pino sudo: pam_unix(sudo:session): session opened for user root by {myUserName}(uid=0)
Dec 30 15:11:11 pino sudo: pam_unix(sudo:session): session closed for user root

Linux Mint Nadia with cinnamon
contents of fstab (although I don't think it is relevant, but I know it will be asked)
proc            /proc           proc    nodev,noexec,nosuid 0       0
UUID=fdd8cdb4-876a-4387-8aa0-0c9101d1b004     /ext4     errors=remount-ro 0 1
UUID=3fb319aa-7e96-49b5-a26f-27da6ce47187     /home     ext4 defaults     0 2
UUID=f756c855-5ed7-478d-9451-8b2b3ffd9ff8     /opt      ext4 defaults     0 2
UUID=83ac367a-7bf1-4495-bad7-1620ae5382d3     /srv      ext4 defaults     0 2
UUID=1cf91e67-6b32-4036-87cc-b296ab3f7984     /tmp      ext4 defaults     0 2
UUID=c2961ad5-2f1e-458c-b5ae-2eb397a8b548     /var      ext4 defaults     0 2
UUID=88ab57b9-291f-4250-8986-c5988d2070d4     none      swap sw           0 0
UUID=3c9654b4-fb32-4974-b4d4-ca525114b19d     /boot     ext4 defaults     0 2
UUID=308A-36A4                                /boot/efi vfat defaults     0

A:

So this one is pretty easy.  The first time it's asking for a password, you're authenticating against sudo.  Sudo does not pass this authentication onto the mount command (nor should it); if you execute the mount command from a root prompt (ie, 'sudo bash', enter password, then issue the mount command), you'll just need to type the password once (although you'll have already had to type it once to become root using sudo).  If your root account has a password, you could instead login to a terminal as root or su to root, and the mount command will still require a password, because this password is used by SMB/CIFS for authentication.


Q:

How to "float" an absolutely positioned element div out of its container

Here's the (simplified) scenario. I have a div which contains another div.  The outer div is of fixed size, has scrollbars and relative positioning. The inner div is larger than and is positioned relative to the outer div. I want the inner div to be fully visible, "floating" above the outer div.
I appreciate this sounds artificial as there is no point in constraining the size of the outer div in this way. It is. In the real application though, there is other content inside the outer div which does need to be controlled with scrollbars.
How can I do this, using css alone? Please note, the inner div must be positioned relative to the external one, so using position:fixed is not an option.
Markup:

Popup Text

Css:
#container{
  overflow: scroll;
  height:50px;
  width:50px;
  position:relative;
}
#popup {
  position:absolute;
  top:20px;
  border:1px solid #000;
  height:100px;
  width:100px;
}

Here's a Plunker

A:

You can add extra wrapper and set position: relative and overflow to different wrappers:
HTML

Popup Text

CSS
#base {
  height:50px;
  width:50px;
  position:relative;
}
#container{
  overflow: scroll;
  height:100%;
  width:100%;
}
#popup {
  position:absolute;
  top:20px;
  border:1px solid #000;
  height:100px;
  width:100px;
}

Fiddle: http://jsfiddle.net/UGftq/
The "secret" is that the overflow property

...affects the clipping of all of the element's content except any
  descendant elements (and their respective content and descendants)
  whose containing block is the viewport or an ancestor of the element.

The containing block for absolutely positioned elements is the nearest ascestor with non-static position. Therefore, when element with overflow is not positioned itself, it doesn't clip absolutely positioned descendants.


Q:

Cannot add a new Topology Manager Mapping

After following the steps in Error while updating Discovery Service Registrations I am faced with a new problem.
When I try to add a new mapping to an existing WebApplication like below
Add-TtmMapping -PublicationID tcm:0-18-1 -WebApplicationID Website1_RootWebApp -RelativeUrl /dev/en/ -CmEnvironmentId Tridioncm_WWCMCEO1000DIT

I get the error

Add-TtmMapping : Unable to save item of type 'MappingData' with id
  'Mapping6'. One or more errors occurred. An error occurred while
  communicating with CD Discovery Service
  'http://url:8082/discovery.svc'
  in CD Environment 'CdEnvironment1'. Error performing batch request 400
  BAD REQUEST The related used by item doesn't exist in database:
  Website1_RootWebApp

This part is strange, item doesn't exist in database: Website1_RootWebApp
Tracing this backwards, trying to find the error, I've explored the following
Is the WebApplication Id correct? Yes
Get-TtmWebApplication

ContextUrl           : /
WebsiteId            : Website1
EnvironmentPurpose   : Staging
CdEnvironment        :
ScopedRepositoryKeys : {}
Id                   : Website1_RootWebApp
ExtensionProperties  : {}

Does the WebApplication exist in CdEnvironment1? Yes
Get-TtmWebsite

BaseUrls             : {http://url}
CdEnvironmentId      : CdEnvironment1
EnvironmentPurpose   : Staging
CdEnvironment        :
ScopedRepositoryKeys : {}
Id                   : Website1
ExtensionProperties  : {}

So I am not sure why I am getting this error.
When I check on the Topology Manager side, I see similar answers
/ttm201501/CdEnvironments
{
 "@odata.context":"http://url:81/ttm201501/$metadata#CdEnvironments","value":[
    {
      "Id":"CdEnvironment1","ExtensionProperties":[

      ],"ScopedRepositoryKeys":[
],"EnvironmentPurpose":"Staging","DiscoveryEndpointUrl":"http://url:8082/discovery.svc","Credentials":{
        "@odata.type":"#Tridion.TopologyManager.Client.AnonymousServiceCredentials","AuthenticationType":"Anonymous"
      },"IsOffline":false
    }
  ]
}

/ttm201501/Websites
{
  "@odata.context":"http://url:81/ttm201501/$metadata#Websites","value":[
    {
      "Id":"Website1","ExtensionProperties":[

      ],"ScopedRepositoryKeys":[

      ],"BaseUrls":[
        "http://url"
      ],"CdEnvironmentId":"CdEnvironment1","EnvironmentPurpose":"Staging"
    }
  ]
}

/ttm201501/WebApplications
{
  "@odata.context":"http://url:81/ttm201501/$metadata#WebApplications","value":[
    {
      "Id":"Website1_RootWebApp","ExtensionProperties":[

      ],"ScopedRepositoryKeys":[

      ],"ContextUrl":"/","WebsiteId":"Website1","EnvironmentPurpose":"Staging"
    }
  ]
}

/ttm201501/Mappings
{
  "@odata.context":"http://url:81/ttm201501/$metadata#Mappings","value":[
    {
      "Id":"Mapping2","ExtensionProperties":[

      ],"CmEnvironmentId":"Tridioncm_WWCMCEO1000DIT","PublicationId":"tcm:0-9-1","EnvironmentPurpose":"Staging","WebApplicationId":"Website1_RootWebApp","RelativeUrl":"/ww/en","PrimaryMappedUrl":"http://url/ww/en","IsOffline":false
    },{
      "Id":"Mapping5","ExtensionProperties":[

      ],"CmEnvironmentId":"Tridioncm_WWCMCEO1000DIT","PublicationId":"tcm:0-16-1","EnvironmentPurpose":"Staging","WebApplicationId":"Website1_RootWebApp","RelativeUrl":"/ww/fr","PrimaryMappedUrl":"http://url/ww/fr","IsOffline":false
    }
  ]
}

I think that the problem could be the following
Before executing steps in Error while updating Discovery Service Registrations DefaultWeb (in my discovery database) was Website1_RootWebApp
If I sync with WebCapability commented out, there is no DefaultWeb
If I sync with WebCapability included, I have two DefaultWeb rows, each with a GUID. There is no sign of Website1_RootWebApp

A:

Sync-TtmCdEnvironment is the best way to fix it. make sure discovery.svc is accessible from your CMS


Q:

Cheapshark API: reading NSDictionary without a key

I have been playing around with the Cheapshark API and came up with this code:
- (IBAction)sendRequest:(UIButton *)sender {

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cheapshark.com/api/1.0/deals?storeID=6&desc=0&title=civilization%20V&pageSize=2"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
    [request setHTTPMethod:@"GET"];

    NSError *requestError;
    NSURLResponse *urlResponse = nil;

    NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
    NSDictionary *results = [NSJSONSerialization JSONObjectWithData:response1 options:NSJSONReadingMutableContainers error:nil];
}

Looking at the debugger I can see that the NSDictionary results has this value:
(lldb) po results
<__NSArrayM 0x17004aaa0>(
{
    dealID = "exhfdIoNgaoB4ieTIZi30ObELpggqQ9B9hpkSnN5rl0%3D";
    dealRating = "0.0";
    gameID = 106353;
    internalName = SIDMEIERSCIVILIZATIONVTHECOMPLETEEDITION;
    lastChange = 1412962351;
    metacriticLink = "/game/pc/sid-meiers-civilization-v-the-complete-edition";
    metacriticScore = 0;
    normalPrice = "49.99";
    releaseDate = 1392076800;
    salePrice = "49.99";
    savings = "0.000000";
    storeID = 6;
    thumb = "http://www.gamersgate.com/img/boximgs/small/DD-CIV5CE.jpg";
    title = "Sid Meier's Civilization V: The Complete Edition";
},
{
    dealID = "KvMAVxjVD4GOORbG2LPd%2FYy6ZVpyAyZPj%2FCiS0nwOhQ%3D";
    dealRating = "0.0";
    gameID = 61;
    internalName = SIDMEIERSCIVILIZATIONV;
    lastChange = 1412962393;
    metacriticLink = "/game/pc/sid-meiers-civilization-v";
    metacriticScore = 90;
    normalPrice = "29.99";
    releaseDate = 1285027200;
    salePrice = "29.99";
    savings = "0.000000";
    storeID = 6;
    thumb = "http://cdn.akamai.steamstatic.com/steam/apps/8930/capsule_sm_120.jpg?t=1414605253";
    title = "Sid Meier's Civilization V";
}
)

But how do I go about accessing any of the individual values? There doesn't seem to be a key for me to find values for in the dictionary. How do I access the individual elements?

A:

the results from response1 is an array, so the following code should help
NSArray *results = [NSJSONSerialization JSONObjectWithData:response1 options:NSJSONReadingMutableContainers error:nil];
    for(NSDictionary* dict in results){
        for(NSString* key in dict.allKeys){
            NSLog(@"keys :%@ ,value: %@",key,[dict objectForKey:key]);
        }
    }


Q:

If I don't want subdomains to send out email, do I need SPF records for them?

I have a main domain with (now) valid SPF record, but we also programmatically create lots and lots of subdomains for clients via cpanel PHPXML API. These subdomains are not intended to send any mail.
When we create them, they are getting an A record of my ip, and a TXT record of
"v=spf1 +a +mx +ip4:[MY IP] ?all". Those are all the DNS records they have
Recently we have had a lot of email spoofing and realized there was an invalid (duplicate SPF) for our main domain. We just fixed that, but are unsure if:
1) Can spammers still spoof email from subdomains without MX records, with above current listed SPF?
2) Is it better to have no SPF for subdomains than the one I have listed?
3) Is there a way to prevent subdomains from sending/spoofing email via my main domain's SPF?
Here is the main domain SPF that our host suggested we switch to:
"v=spf1 a mx ptr a:dedrelay.[webhost].com include:dedrelay.[webhost].com ~all"

A:

Subdomains are not affected by the main domain's SPF record.  If you have a bunch of subdomains that you know will never send mail, the best thing to do is to define an SPF record of -all for each of them.  That way, the internet can also know that you intend them never to send email.
Edit: if there is no SPF record in place for a subdomain, recipients who check SPF will see no SPF-related reason to block it.
Yes, SPF will do nothing to prevent someone accepting mail from a subdomain without an MX record.  They might choose not to, but as long as it resolves - and sometimes even if it doesn't - they might choose to.  That is not an SPF issue.
Your current SPF record will do nothing to prevent spoofing on your subdomains, because as I said, subdomains are not affected by the main domain's SPF record.
I'm sorry this will be a lot of work for you, but if you want to use SPF to advise recipients to reject emails from these subdomains, you will need to define SPF records for them.  That's how the protocol works.


Q:

Count the number of entries in the table

I have a table allData

id     name
1      meat
2      chicken
3      fish
4      chicken
5      fish
6      chicken

and table relevantData

id        name
1         meat
2         fish

I want to count the total number of occurrence per name in allData, but only for names which appear in relevantData. I.e.
The result I want to get :

id       name     count
1        meat     1
2        fish     2

I thought about the query:
Select count(*) from allData group by name

Not sure how I correlate with relevantData. Any thoughts?

A:

Change the point of view, you are interested in relevantData, that's the base of your query. You can use a correlated subquery, no need to use join or group-by:
SELECT rd.name,
       (SELECT COUNT(*) FROM allData ad WHERE rd.name = ad.name) AS Count
FROM relevantData rd

Demo


Q:

How to remove ListView hover effect when using an ItemTemplate

Could not find a solution that works for my scenario where I have a ListView with an ItemTemplate like this:
<Window x:Class="ListViewHover.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListView ItemsSource="{Binding Items}" SelectedIndex="0">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Id}"/>
                        <TextBlock Text="{Binding Text}"/>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

Code behind:
namespace ListViewHover
{
    using System.Collections.Generic;
    using System.Windows;

    public partial class MainWindow : Window
    {
        public MainWindow()
        {

            InitializeComponent();
            DataContext = this;
            Items = new List<Item> { new Item(1), new Item(2), new Item(3) };
        }

        public List<Item> Items { get; set; }
    }

    public class Item
    {
        public Item(int id)
        {
            Id = id;
        }

        public int Id { get; set; }
        public string Text { get => $"This is Item number {Id}"; }
    }
}

If you run this the list has the default hover-effect. I need this to go away so the only effect is the background changing when an item is selected.
I've tried to specify the ItemContainerStyle and also applying style triggers on the ListViewItems but I can't get it to work.

A:

Can you use ItemsControl?
        <ItemsControl ItemsSource="{Binding Items}" >
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="local:Item">
                    <StackPanel>
                        <TextBlock Text="{Binding Id}"/>
                        <TextBlock Text="{Binding Text}"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

If you want to write the ListView and rewrite the ItemContainerStyle that you can use this code.
<Window.Resources>
    <!-- set SelectedBackgroundColor to Transparent when you do not need the background in selected items -->
    <Color x:Key="SelectedBackgroundColor">#00FFFFFF</Color>
    <Color x:Key="SelectedUnfocusedColor">#FFB2A3A2</Color>

    <!-- set the MouseOverColor to Transparent when you do not need the effect in the unselected items -->
    <Color x:Key="MouseOverColor" >#00FFFFFF</Color>

    <Style x:Key="ListViewItemStyle"
           TargetType="ListViewItem">
        <Setter Property="SnapsToDevicePixels"
                Value="true" />
        <Setter Property="OverridesDefaultStyle"
                Value="true" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Border x:Name="Border"
                            Padding="2"
                            SnapsToDevicePixels="true"
                            Background="Transparent">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="MouseOver" >
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                                                      Storyboard.TargetProperty="(Panel.Background).
                (SolidColorBrush.Color)">
                                            <EasingColorKeyFrame KeyTime="0"
                                                                 Value="{StaticResource MouseOverColor}" />
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Disabled" />
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="SelectionStates">
                                <VisualState x:Name="Unselected" />
                                <VisualState x:Name="Selected">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                                                      Storyboard.TargetProperty="(Panel.Background).
                (SolidColorBrush.Color)">
                                            <EasingColorKeyFrame KeyTime="0"
                                                                 Value="{StaticResource SelectedBackgroundColor}" />
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="SelectedUnfocused">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                                                      Storyboard.TargetProperty="(Panel.Background).
                (SolidColorBrush.Color)">
                                            <EasingColorKeyFrame KeyTime="0"
                                                                 Value="{StaticResource SelectedUnfocusedColor}" />
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <ContentPresenter />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</Window.Resources>

        <ListView ItemsSource="{Binding Items}"
                  ItemContainerStyle="{StaticResource ListViewItemStyle}">
            <ListView.ItemTemplate>
                <DataTemplate DataType="local:Item">
                    <StackPanel>
                        <TextBlock Text="{Binding Id}" />
                        <TextBlock Text="{Binding Text}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

The core code is changing the SelectedBackgroundColor to Transparent when you do not need the background in the selected items and changing the MouseOverColor to Transparent when you do not need the effect in the unselected items.
See: https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/listview-styles-and-templates


Q:

Store and reuse distance between items

I am creating a table in which I have cells containing itemize environments. For a given row I have either zero or two cells containing this environment and working together. However the text for the items of the first cell is usually longer than the text for the items of the second cell.
I am looking for a way to implement this table with the bullet points of the items being respectively at the same height. A picture being better than a long description, here it is:

I would like the bullet point of Short 1 to be at the same level as the one from the first long item, and the same goes for Short 2 and its related item.
Here is the code used to produce this table:
\documentclass{article}

\usepackage{enumitem}
\usepackage{array}

\begin{document}

\begin{table}[H]
\begin{center}
\begin{tabular}{| m{0.3cm} | m{5.5cm} | m{4cm} | m{1.8cm} | m{1cm}|}
\hline
 1 &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item This is a first long long long item, spanning on two lines
\item And here comes a second one lon long item
\end{itemize} & Some text which can be either long or short, there is no general rule &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item Short 1
\item Short 2
\end{itemize} & Some short text\\ \hline
\end{tabular}
\end{center}
\end{table}

\end{document}

NOTE 1 I would like a solution as compact in height as possible
NOTE 2 I am using the m{<value>} column style because the longest cell for a different rows is not always the same.
NOTE 3 I am aware that the Table is ugly and the vertical lines should be removed to match more to a more readable and reader-friendly solution but this is a mandatory template... Too bad...
EDIT Trylks proposed to use a combination of \multirow in the non-list cell and to split the list cells in more cells. This does fix the problem of the vertical alignment of the items but it also creates misalignments for the other cells.
MWE for the Edit suggestion
\documentclass{article}

\usepackage{enumitem}
\usepackage{array}
\usepackage{multirow}

\begin{document}

\begin{table}[H]
\begin{center}
\begin{tabular}{| m{0.3cm} | m{5.5cm} | m{4cm} | m{1.8cm} | m{1cm}|}
\hline
\multirow{2}{*}{1} &
\begin{itemize}[leftmargin=0.3cm]
\item This is a first long long long item, spanning on two lines
\end{itemize}
& \multirow{2}{*}{Some text which can be either long or short, there is no general rule} &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item Short 1
\end{itemize}
& \multirow{2}{*}{Some short text}\\
& \begin{itemize}[leftmargin=0.3cm]
\item And here comes a second one lon long item
\end{itemize}
& &
\begin{itemize}[leftmargin=0.3cm]
\item Short 2
\end{itemize}
& \\ \hline
\end{tabular}
\end{center}
\end{table}

\end{document}

And the corresponding output:

EDIT 2 jfbu proposed a solution which seems to work (see his answer) for the above case but it is just a coincidence. If one item has a text longer than two lines, it crashes also. See the MWE and its output:
\documentclass{article}

\usepackage{enumitem}
\usepackage{array}

\begin{document}

\begin{table}[H]
\begin{center}
\begin{tabular}{| m{0.3cm} | m{5.5cm} | m{4cm} | m{1.8cm} | m{1cm}|}
\hline
 1 &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item \strut This is a first long long long item, spanning on two lines. This is a first long long long item, spanning on two lines. This is a first long long long item, spanning on two lines \strut
\item \strut And here comes a second one lon long item \strut
\end{itemize} & Some text which can be either long or short, there is no general rule &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item \strut Short 1 \hfill\break \strut
\item \strut Short 2 \hfill\break \strut
\end{itemize} & Some short text\\ \hline
\end{tabular}
\end{center}
\end{table}

\end{document}

A:

I still recommend \strut's.
\documentclass{article}

\usepackage{enumitem}
\usepackage{array}

\makeatletter
\def\LUDOVIC {}
\def\LUDOvic {\par\xdef\LUDOVIC{\LUDOVIC {\the\prevgraf}}}
\def\ludoVIC {\par\expandafter\ludovic@ \LUDOVIC\relax }
\def\ludovic@ #1#2\relax {\gdef\LUDOVIC {#2}%
   \vspace{\numexpr #1-\prevgraf\relax\baselineskip}}
\makeatother

\begin{document}

\begin{table}[H]
\begin{center}
\begin{tabular}{| m{0.3cm} | m{5.5cm} | m{4cm} | m{1.8cm} | m{1cm}|}
\hline
 1 &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item This is a first long long long item, spanning on many
  lines. This is a first long long long item, spanning on many
  lines. This is a first long long long item, spanning on many
  lines. This is a first long long long item, spanning on many
  lines. \LUDOvic
\item  And here comes a second one long long
  item. And here comes a second one long long
  item. And here comes a second one long long
  item. And here comes a second one long long
  item. And here comes a second one long long
  item. \LUDOvic
\item And here is a third one.  And here is a third one.  And here is a third
  one.  And here is a third one.  And here is a third one. \LUDOvic
\item And a fourth one. \LUDOvic
\end{itemize} & Some text which can be either long or short, there is no general rule &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item Short 1\ludoVIC
\item Short 2\ludoVIC
\item Short 3\ludoVIC
\item Short 4\ludoVIC
\end{itemize} & Some short text\\ \hline
\end{tabular}
\begin{tabular}{| m{0.3cm} | m{5.5cm} | m{4cm} | m{1.8cm} | m{1cm}|}
\hline
 1 &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item This is a first long long long item, spanning on many
  lines. This is a first long long long item, spanning on many
  lines. \LUDOvic
\item  And here comes a second one long long
  item. And here comes a second one long long
  item. And here comes a second one long long
  item. \LUDOvic
\end{itemize} & Some text which can be either long or short, there is no general rule &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item Short 1\ludoVIC
\item Short 2\ludoVIC
\end{itemize} & Some short text\\ \hline
\end{tabular}
\end{center}
\end{table}

\end{document}

Output:

First quickly drafted answer:
This seems to work.
\documentclass{article}

\usepackage{enumitem}
\usepackage{array}

\begin{document}

\begin{table}[H]
\begin{center}
\begin{tabular}{| m{0.3cm} | m{5.5cm} | m{4cm} | m{1.8cm} | m{1cm}|}
\hline
 1 &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item \strut This is a first long long long item, spanning on two lines\strut
\item \strut And here comes a second one lon long item\strut
\end{itemize} & Some text which can be either long or short, there is no general rule &
\begin{itemize}[leftmargin=0.3cm]\itemsep0pt
\item \strut Short 1\hfill\break \strut
\item \strut Short 2\hfill\break \strut
\end{itemize} & Some short text\\ \hline
\end{tabular}
\end{center}
\end{table}

\thispagestyle{empty}
\end{document}


Q:

PHP Authenticate HTTP Message

I have following Situation,
Server A sends some data (HTML form) to server B, B then does some DB queries and stuff (irrelevant) and sends "Confirmed" or "not confirmed" back to A (via fsock, to an address that is deliverd as an hidden field in the form ). But it is possible to fake this answer, so how can i ensure ( on A side ) that the answer is real?
I am looking for an safe aproach easier than GPG for example...
Thanks!

A:

Use a client certificate for HTTPS requests from Server A, and only allow access to Server B if the request comes from a valid certificate.
There are plenty of tutorials out there on the interwebs.


Q:

MySQL: Retrieve data from multiple tables

Please have a look at the below table structure.

Client table has the foreign key for Provider Table, which is not NULL. Portfolio table has the foreign key for the Client table, which is also not NULL.
I need to retrieve all the fields from the Portfolio table, Name of the Client and the Provider Name who is allocated to the Client which is referred by the Portfolio table..
How can I do this in SQL Code?

A:

Try following query with INNER JOIN.
SELECT Portfolio.*,Client.name as "Client Name",Provider.name as "Provider Name"
FROM Portfolio
INNER JOIN Client ON Portfolio.Client_id=Client.id
INNER JOIN Provider ON Client.Provider_id = Provider.id


Q:

Use VSCode explorer with remote server (using SSH)

I need to code / edit files in a remote server using SSH, and I would like to access it with VSCode.
I'm on Windows 10, using "Git Bash" as integrated terminal in VSCode, which means I can connect to the server using VSCode's terminal.
What I'm missing is a way to open files from the terminal to the editor, and even better - interacting with the files using the explorer.
How can this be done?

A:

Since the May, 2nd 2019 announcement of "Remote Development with VS Code", you now officially have:
Visual Studio Code Remote - SSH

The Remote - SSH extension lets you use any remote machine with a SSH server as your development environment.
  Since nearly every desktop and server operating system has a SSH server that can be configured, the extension can greatly simplify development and troubleshooting in a wide variety of situations.
You can:

Develop on the same operating system you deploy to or use larger, faster, or more specialized hardware than your local machine.
Quickly swap between different, remote development environments and safely make updates without worrying about impacting your local machine.
Access an existing development environment from multiple machines or locations.
Debug an application running somewhere else such as a customer site or in the cloud.

Q1 2020: VSCode 1.42 improves support for Windows servers, including automatic OS detection.


Q:

Postback not working on mouse click in Safari

So I have a dropdown context box, which I use to select which item I am going to be working with.
Now everything seems to be working on all browsers except Safari.  I have a type function that works fine in safari if you focus on the box and type the name in and hit enter.  However my issue is with the mouse click.  If I select an item from the dropdown and click it, the postback doesn't work until I hit enter on the keyboard.
Here is my .ascx.cs file
...
if (cboContext.Visible)
    {
        string postBackFunction = "function contextPostback() {\n"
        + "var newValue = document.getElementById(\"" + cboContext.ClientID + "\").value;\n"
        + "if (newValue != " + cboContext.SelectedValue + ") " + Page.ClientScript.GetPostBackEventReference(cboContext, "") + ";\n}";

        Page.ClientScript.RegisterClientScriptBlock(typeof(string), "contextPostback", postBackFunction, true);

        if (Request.UserAgent.ToLower().IndexOf("chrome") > -1)
        {
            cboContext.Attributes.Add("onkeypress", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
            cboContext.Attributes.Add("onclick", "contextPostback();");
        }
        else if (Request.UserAgent.ToLower().IndexOf("safari") > -1)
        {
            cboContext.Attributes.Add("onclick", "contextPostback();");
            cboContext.Attributes.Add("onkeypress", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
            cboContext.Attributes.Add("onkeydown", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
            cboContext.Attributes.Add("onkeyup", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
        }
        else
        {

            cboContext.Attributes.Add("onkeydown", "if (typeAhead(event,'" + cboContext.ClientID + "') == 1) contextPostback();");
            cboContext.Attributes.Add("onclick", "contextPostback();");
        }
    }

Here is the typeAhead() function
function typeAhead(e, nextFocus) {

//don't trap Ctrl+keys
if ((window.event && !window.event.ctrlKey) || (e && !e.ctrlKey)) {

    // timer for current event
    var now = new Date();

    ....
    if (inputBuffer.accumString == "" || now - inputBuffer.last < inputBuffer.delay) {
        //check for browsers
        var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
        var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
        // make shortcut event object reference
        var evt = e || window.event;
        // get reference to the select element
        var selectElem = evt.target || evt.srcElement;
        // get typed character ASCII value
        var charCode = evt.keyCode || evt.which;
        // get the actual character, converted to uppercase
        var newChar = "";
        // get reference to the actual form selection list
        // added cross browser fix to enable the context switcher to work properly
        if (is_chrome) {
            var selection = document.getElementById("ctl00_ContextSwitch1_cboContext").selectedIndex;
        }
        else {
            var selection = document.getElementById(nextFocus);
        }
....

Now I have a section in the typeAhead for the chrome browser, but everything I try for safari doesn't seem to allow me to use the mouse click to select an item.
Any help would be appreciated.

A:

simple fix.  safari recognizes onchange so once I added that, it worked fine.