text:
Q: Unable to bind cefsharp with selenium chromedriver Using below code i was able to bind cefglue client with Selenium Chrome Driver. But it doesn't works for cefsharp.
Imports OpenQA.Selenium.Chrome
Imports System.Threading
Imports OpenQA.Selenium
Imports OpenQA.Selenium.Support.Events
Imports OpenQA.Selenium.Support.Extensions
Imports OpenQA.Selenium.Support.PageObjects
Imports OpenQA.Selenium.Support.UI

Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Try

            Dim service = ChromeDriverService.CreateDefaultService("D:\chromedriver_win32")
            Dim chromeOptions As New OpenQA.Selenium.Chrome.ChromeOptions()

            chromeOptions.BinaryLocation() = "D:\cefsharp\net452\CefSharp.MinimalExample.WinForms.exe"

            chromeOptions.AddExcludedArgument("ignore-certifcate-errors")
            chromeOptions.AddArgument("test-type")
            chromeOptions.AddArgument("--allow-insecure-localhost")
            chromeOptions.AddArguments("start-maximized") ' open Browser In maximized mode
            chromeOptions.AddArguments("disable-infobars") ' disabling infobars
            chromeOptions.AddArguments("--disable-extensions") ' disabling extensions
            chromeOptions.AddArguments("--disable-gpu") ' applicable To windows os only
            chromeOptions.AddArguments("--disable-dev-shm-usage") ' overcome limited resource problems
            chromeOptions.AddArgument("--remote-debugging-port=20480")
            chromeOptions.AddArguments("--disable-dev-shm-usage")

            Dim driver As OpenQA.Selenium.Chrome.ChromeDriver = New OpenQA.Selenium.Chrome.ChromeDriver(service, chromeOptions, TimeSpan.FromSeconds(120))
            driver.Navigate().GoToUrl("https://chromedriver.chromium.org/downloads")
            Thread.Sleep(5000)

        Catch ex As Exception
            MsgBox(Err.Description)
        End Try
    End Sub
End Class

Also the standalone Cefsharp works fine, i am able to browse website etc, but when i pair it with selenium it crashes and chromedriver prints this  error.
---------------------------
chromedriver
---------------------------
unknown error: Chrome failed to start: crashed.
  (chrome not reachable)
  (The process started from chrome location CefSharp.MinimalExample.WinForms.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
---------------------------
OK
---------------------------

I have tried below options:

*

*tried with latest chrome driver and cef versions

*Ran code as admin

*Used x86 version of cefsharp exe

Below are the logs written while executing above code
chromedriver console log:
Starting ChromeDriver 107.0.5304.62 (1eec40d3a5764881c92085aaee66d25075c159aa-refs/branch-heads/5304@{#942}) on port 61991
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
[0214/160638.323:VERBOSE1:pref_proxy_config_tracker_impl.cc(187)] 342B4700: set chrome proxy config service to 34238700
[0214/160638.403:VERBOSE1:webrtc_internals.cc(120)] Could not get the download directory.
[0214/160638.407:VERBOSE1:media_stream_manager.cc(1100)] MSM::InitializeMaybeAsync([this=34260840])
[0214/160638.409:VERBOSE1:media_stream_manager.cc(1100)] MDM::MediaDevicesManager()
[0214/160638.409:VERBOSE1:media_stream_manager.cc(1100)] MSM::MediaStreamManager([this=34260840]))

DevTools listening on ws://127.0.0.1:20480/devtools/browser/d1d13b12-10ad-4cb6-ad07-b948e92d26d6
[0214/160638.481:VERBOSE1:component_installer.cc(285)] StartRegistration for Widevine Content Decryption Module
[0214/160638.482:VERBOSE1:first_party_sets_handler_impl.cc(279)] Empty path. Failed initializing First-Party Sets database.
[0214/160638.502:VERBOSE1:component_installer.cc(439)] FinishRegistration for Widevine Content Decryption Module
[0214/160638.509:VERBOSE1:component_updater_service.cc(131)] CrxUpdateService starting up. First update attempt will take place in 60 seconds. Next update attempt will take place in 18000 seconds.
[0214/160638.599:VERBOSE1:pref_proxy_config_tracker_impl.cc(187)] 342B6D80: set chrome proxy config service to 3423A800
[0214/160653.789:INFO:child_thread_impl.cc(918)] ChildThreadImpl::EnsureConnected()

Debug log:
[0214/160638.323:VERBOSE1:pref_proxy_config_tracker_impl.cc(187)] 342B4700: set chrome proxy config service to 34238700
[0214/160638.403:VERBOSE1:webrtc_internals.cc(120)] Could not get the download directory.
[0214/160638.407:VERBOSE1:media_stream_manager.cc(1100)] MSM::InitializeMaybeAsync([this=34260840])
[0214/160638.409:VERBOSE1:media_stream_manager.cc(1100)] MDM::MediaDevicesManager()
[0214/160638.409:VERBOSE1:media_stream_manager.cc(1100)] MSM::MediaStreamManager([this=34260840]))
[0214/160638.481:VERBOSE1:component_installer.cc(285)] StartRegistration for Widevine Content Decryption Module
[0214/160638.482:VERBOSE1:first_party_sets_handler_impl.cc(279)] Empty path. Failed initializing First-Party Sets database.
[0214/160638.502:VERBOSE1:component_installer.cc(439)] FinishRegistration for Widevine Content Decryption Module
[0214/160638.509:VERBOSE1:component_updater_service.cc(131)] CrxUpdateService starting up. First update attempt will take place in 60 seconds. Next update attempt will take place in 18000 seconds.
[0214/160638.599:VERBOSE1:pref_proxy_config_tracker_impl.cc(187)] 342B6D80: set chrome proxy config service to 3423A800
[0214/160653.789:INFO:child_thread_impl.cc(918)] ChildThreadImpl::EnsureConnected()

How can i bind cefsharp with selenium?


text:
Q: Angular2 listSearchPipe usage for arrays

  <input class="input" type="text" placeholder="{{ 'Search name' | translate }}" [(ngModel)]="searchText">

      <mat-icon class="iq-accordion-icon-left" svgIcon="cards-outline"></mat-icon>
      {{k.name}}

I have the above code which executes a search based on name. My Fruit objects also have tag field which is a list of string.
Now, what I want to do is creating a search functionality for tag-based search as well. For example, when a tag is selected lets say "red", I want to show the objects which contain the tag "red". How can I achieve this with using something similar to the above code. Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: is a closed subscheme of the projective line closed under the action of Gal(Qbar/Q) Let $S$ be a non-empty closed subscheme of $P^1_K$, where $K$ is a number field. Assume that the cardinality of $S$ is finite.
Is $S$ closed under the action of the absolute Galois group of the field of rational numbers ?
I would like to know this because a certain theorem I want to apply requires this condition.

A: If you mean to use the action of the absolute Galois group of $K$, then this is true for closed subschemes of $P^n_K$, pretty much by definition. A closed subscheme of $P^n_K={\rm Proj}K[x_0,...,x_n]$ is described by a homogeneous ideal $I$, and the closed subscheme is equal to $W={\rm Proj}K[x_0,...,x_n]/I$. (More precisely, $W$ embeds naturally into $P_K^n$.) Then ${\rm Gal}(\bar K/K)$ acts on $W$, since the ideal $I$ is Galois invariant. So for example, ${\rm Gal}(\bar K/K)$ clearly acts on the geometric points $W(\bar K)$ of $W$. (But maybe I'm missing some subtlety here.)
But if you really mean to look at the action of ${\rm Gal}(\bar{\mathbb{Q}}/\mathbb{Q})$, then it's certainly false. For example, take $K=\mathbb{Q}(i)$ and $S$ to be the subscheme consisting of the single point $[i,1]\in P^1_K$. (Formally, $S$ is associated to the ideal generated by the polynomial $x-iy$, which defines a closed subscheme of $P_K^1$.) The ${\rm Gal}(\bar{\mathbb{Q}}/\mathbb{Q})$ orbit of $S$ consists of two points.


text:
Q: WxPython, How to fill ListBox with class attributes I am building a wxpython project, I have a list of elements that are a class instances. Each of this elements has an attribute title. In a ListBox I want to display only the titles, and when the title selected, after we GetSelection from listbox, the instance should be returned and not just the title. Is this achievable ?
Note: Searching for the string is out of question because names(titles) may be recurring.
Thank you.

A: *

*Put your instances in a list

*Use GetSelection to retrieve the index of the item you selected from the listbox

*Get the corresponding instance from that index in the list


text:
Q: CSRF Cookie/Header mismatch - CouchDB I am trying to call a design doc I wrote in CouchDB however when I make the call I get the following error:
{"error":"forbidden","reason":"CSRF Cookie/Header mismatch"}

I am calling this design doc from an HTML form as a POST. Can anyone help me?
Thanks.

A: We've disabled this now. It's clearly not possible to pass the CSRF test for a form post with our current implementation. Please confirm you are able to post to Cloudant now, at your convenience.
B.


text:
Q: Changing Roles name in Sonata Admin Symfony 2 I am trying to change the default sonata admin Roles which are disabled like ROLE_ADMIN_CATEGORY_EDITOR, ROLE_ADMIN_BLOG_POST_STAFF ....
to friendly names for the final user like Category Admin or BlogPost Admin ...
I've created a method in the overridden User entity which retrieves the classic roles from getRealRoles() and transforms them.
The problem is that with the formMapper in the UserAdmin the new array doesn't seem to contain any value.


text:
Q: how to make two dependent ajax requests on one buttonclick I want insert two forms as two table rows in db using a button click event.I have used ajax request to insert in database and done for one form, while making another ajax request depending on first form it is not working
here is my java script using jquery.
var transportid = 2;
$.ajax({
    url : '/TransportJob/create',
    type : 'POST',
    data : $('form[action="/TransportJob/Create"]').serialize(),
    success : function sfn(data, textStatus, jqXHR) { // **success spelling mistake**
        transportid = parseInt(data);
        alert('inserted id :' + data);
        $('#TransportJobId').val((transportid));
        $.ajax({

            url : '/TransportJobAddress/create',
            type : 'POST',
            //beforeSend: function myintserver(xhr){
            //        $('#addAddress').html('
please wait ...
');
            //},
            data : $('form[action="/TransportJobAddress/Create"]').serialize(),
            success : function poste(data, textStatus, jqXHR) {
                $('#addAddress').html(data);
            },
            error : function err(jqXHR, textStatus, errorThrown) {
                alert('error at address :' + errorThrown);
            }

        });
    },
    error : function myfunction(jqXHR, textStatus, errorThrown) {
        alert("error at transport :" + jqXHR.textStatus);
    },
    complete : function completefunc() {
        alert('ajax completed all requests');
    }

});
return false;
});

A: The first ajax sucess spelling problem make correction success then it will work

A: In your first ajax call, changesucess to success ?

A: I have modify your code first ajax request success portion spelling mistake.
sucess : function sfn(data, textStatus, jqXHR) {

Change to
success : function sfn(data, textStatus, jqXHR) {

Second error at end of request is
Remove extra code
return false;
});

and Put return false; after closing complete method.
e.g.
    complete : function completefunc() {
        alert('ajax completed all requests');
    }
    return false;
});


text:
Q: using 'for' in shell script I am trying to create a script that will go through several steps on specific files in a directory.  Each step work file at a prompt.  It's when I use 'for' to work through the needed files that isn't working.
here is the script and starting text file.
#lab2dno.sh
#
#use cygwin
#cygwin
#work in %RAM%:\
cd '/cygdrive/e'
  # delete header lines
tail +4 preg.txt > file1.txt
  # split into herdcode.tx1 from %RAM% (e) in bash-3.2
awk -F "," '{close(f);f=$1}{ print > f".tx1" }' file1.txt
  #file list (no ext)
ls -1 *.tx1 | sed 's/\(.*\)\..*/\1/' > hc.ls1
  # delete extra fields (and rename works @ prompt))
  # cut -d "," -f 2,3,6 41300090.tx1 > 41300090.tx2
  # this one does not work
for i in hc.ls1; do cut -d "," -f 2,3,6 $i > $i.tx2;done
  # reorder fields and rename (works at propmt)
  # awk -F, '{ print $2,$3,$1}' *.tx2 > *.tx3
  # this one does not work
for i in *.ls1; do awk -F, '{ print $2,$3,$1}' $i > $i.DNO;done

...preg.txt...
MNDHIA Export

Name,Test Date,ID,Tag,Final Calculation,Symbols (Final Calculation),1,Parachek
41300090,1/25/2013,1636,56439256,-0.008,OPEN,1,Parachek
41300090,1/25/2013,1238,67046268,-0.017,OPEN,1,Parachek
41732189,1/29/2013,304,55567637,-0.006,OPEN,1,Parachek
41732189,1/29/2013,415,55646609,-0.007,OPEN,1,Parachek

A: for i in hc.ls1; do cut -d "," -f 2,3,6 $i > $i.tx2;done

This won't work. Use set -x at the top of your script, it will turn on debug mode and echo every command.
What you're doing in the line above is set the value of i to hc.ls1. What you actually want is to set it to each value listed inside hc.ls1:
for i in $( cat hc.ls1 ) ; do cut -d "," -f 2,3,6 $i > $i.tx2;done


text:
Q: Can i add two new columns to all my tables through a MYSQL query In my database i have like 200 tables which starts from pre_table_XX( example : pre_table_1, pre_table_2, pre_table_3, pre_table_4 etc  ). currently i need to add two new coloumns two all these tables by using a mysql query at once. below is an example of one of my tables
example table
trackID MyID    Rid     panelID timestamp           useragent_browser   useragent_OS
1       17      123     25      2014-04-29 10:02:01 Default Browser     unknown NULL
2       17      123     25      2014-04-30 05:11:01 Default Browser     unknown NULL
3       17      123     25      2014-05-15 06:44:02 Default Browser     unknown NULL
4       17      59595   25      2014-10-06 07:50:30 Default Browser     unknown 0

I need to add two new columns to each of these tables known as, device_name and browser
i tried it like this for no avail
SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = 'abc_db' AND table_name LIKE 'pre_table_%'

ALTER TABLE `abc_db`.`stats`

ADD COLUMN `device_name` VARCHAR(45) NULL AFTER `useragent_os`,

ADD COLUMN `browser` VARCHAR(45) NULL AFTER `device_name`;

can anybody help on this. putting a mysql loop kind of thing would do i guess!!!


text:
Q: Single-spaced comments in changes package with double-spaced document I'm using the changes package for comments. Is it possible to get the comments to be single-spaced, even if the document itself is double-spaced?
MWE:
\documentclass{article}
\usepackage{changes}
\usepackage{lipsum}

\linespread{2}

\begin{document}

\lipsum[1-1][1-3]\comment{I would like this comment to be single-spaced.} \lipsum[1-1][4-6]

\end{document}

Output:

A: Quite likely you want all of your margin notes to be single spaced.
\documentclass{article}
\usepackage{changes,etoolbox}

\usepackage{lipsum}

\makeatletter
\preto\@marginparreset{\linespread{1}}
\makeatother

\linespread{2}

\begin{document}

\lipsum[1-1][1-3]\comment{I would like this comment to be single-spaced.}
\lipsum[1-1][4-6]

\end{document}

Explanation: \@marginparreset is the hook that the LaTeX kernel provides for doing initializations before starting to typeset a margin paragraph (internally used by the changes package).

A: Using this answer I tried
\documentclass{article}
\usepackage{changes}
\usepackage{lipsum}
\linespread{2}

\begin{document}
\lipsum[1-1][1-3]\renewcommand*{\baselinestretch}{1}\comment{\selectfont
I would like this comment to be single-spaced.}
\lipsum[1-1][4-6]

\end{document}

which seems to work. If you decide this is the way to go, then obviously one may make it more automatic and safer by patching this into \comment. You could just look up its definition from changes.sty and redefine it as follows:
\documentclass{article}
\usepackage{changes}
\usepackage{lipsum}
\linespread{2}
\makeatletter
\renewcommand*{\comment}[2][\@empty]{%
\edef\oldbaselinestretch{\baselinestretch}%
\typeout{\oldbaselinestretch}%
\renewcommand*{\baselinestretch}{1}%
\setkeys{Changes@comment}{#1}%
\Changes@output%
{comment}%
{\Changes@comment@id}%
{}%
{}%
{\selectfont #2}%
{\changescommentname}%
{\selectfont #2}%
\renewcommand*{\baselinestretch}{\oldbaselinestretch}%
}
\makeatother
\begin{document}
\lipsum[1-1][1-3]\comment{I would like this comment to be single-spaced.}
\lipsum[1-1][4-6]

\selectfont
\lipsum[1-1]

\end{document}


text:
Q: Select From Select Laravel How can i query this in laravel
SELECT * from (SELECT member_services.* FROM `member_services`
WHERE payment_date BETWEEN '2020-04-22' and '2021-04-22') `as member_services WHERE start_date BETWEEN '2020-04-16' and '2020-05-25';`

?
Thank you sir. Appreciate it.

A: Use below code
$result = DB::select("YOUR MYSQL SELECT QUERY HERE");


text:
Q: Stop .click() from firing is there a way to stop .click() from firing when a condition has been met? My code looks like :
$(document).ready(function() {

// stocheaza ordinea corecta a imaginilor
var correctOrder = $("#puzzle > img").map(function() {
  return $(this).attr("src");
}).get();

// amesteca imaginile
var x = $("#puzzle > img").remove().toArray();
for (var i = x.length - 1; i >= 1; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var bi = x[i];
    var bj = x[j];
    x[i] = bj;
    x[j] = bi;
    }
$("#puzzle").append(x);

// event onclick pe 2 piese sa'si schimbe pozitia
$("img.element").click(function(){
    if (clickCount == 0)
    {
        imgSrc = $(this).attr("src");
        lastImgId = $(this).attr("id");
        clickCount++;
    }
    else {
        $("#"+lastImgId).attr("src",$(this).attr("src"));
        $(this).attr("src",imgSrc);
        clickCount = 0;

// returneaza ordinea imaginilor curente
        var currentOrder = $("#puzzle > img").map(function() {
          return $(this).attr("src");
        }).get();

// compara ordinea imaginilor curente cu cea corecta
        if (currentOrder.compare(correctOrder))
        updateBubble(2);
    }
});
});

I need to stop $("img.element").click(function(){ } when this condition if (currentOrder.compare(correctOrder)) has been met. At the moment this .click() function allow me to click on 2 images and change their positions but updateBubble(2); is the final feedback and i must cannot change images when this feedback is given. Thx

A: Try this:
 $("img.element").click(function(){
 if(currentOrder.compare(correctOrder))//return and do not execute click event code if condition
  return;

 //rest click event code here
 });

A: the general way to stop the click from firing is to use preventDefault, like this:
("img.element").click(function(event){
    if(condition) {
        event.preventDefault();
    }
}

A: $(this).unbind('click');

might do what you're looking for....

A: Try
if(condition){
return false;
}

That will stop the other part of the function from firing!

A: Try this:
 $("img.element").click(function(){
 if(currentOrder.compare(correctOrder) ){
   return false; // return and prevent further listener.
 }

if (clickCount == 0)
    {
        imgSrc = $(this).attr("src");
        lastImgId = $(this).attr("id");
        clickCount++;
    }
    else {
        $("#"+lastImgId).attr("src",$(this).attr("src"));
        $(this).attr("src",imgSrc);
        clickCount = 0;

// returneaza ordinea imaginilor curente
        var currentOrder = $("#puzzle > img").map(function() {
          return $(this).attr("src");
        }).get();

// compara ordinea imaginilor curente cu cea corecta
        if (currentOrder.compare(correctOrder))
        updateBubble(2);
    }

 });

A: I think you should change little bit like this with use of .on() to bind the event and .off() to unbind the event:
$("img.element").on('click', function(){ // use with .on() handler

and here to unbind the event:
if (currentOrder.compare(correctOrder))
    updateBubble(2);
    $(this).off('click'); // use .off() to unbind the click event


text:
Q: Converting an RDD to a Spark DataFrame I am trying to create a data frame from an rdd in spark2.
When I try to convert the rdd to a data frame I get an error stating the following
error reading Scala signature of org.apache.spark.sql.package: assertion failed: unsafe symbol Unstable (child of package InterfaceStability) in runtime reflection universe

Here is my code
import org.apache.spark.sql.{ SparkSession}
object TestLoad extends App{

  val spark: SparkSession = SparkSession.builder.master("local[*]").getOrCreate
  val sc = spark.sparkContext
  val rdd = sc.parallelize(
    Seq(("1", "someval"), ("2", "someval"))
  )

  val df = spark.createDataFrame(rdd)
  df.show()
}

A: There is no problem about your RDD to DFF code. It seems like a problem about your computer's library configuration.
For this type exercising you can use databricks community notebook.
This will provide you to focus on the Spark's capabilities not the library issues.


text:
Q: Can I re-direct an existing (entire) gnome-session's display to a remote work station? So instead of using VNC for example
- I could actually run a command on my home-fedora terminal
and have my work-fedora existing gnome-session appear at home?

A: I think you use, Vino.

Vino is the GNOME desktop sharing server.

This (vino) is default package in most of the distribution along with gnome.

A: The Tiger's x0vncserver could help share the existing X server regardless of the desktop in use:
NAME
       x0vncserver - TigerVNC Server for X displays

SYNOPSIS
       x0vncserver [options]
       x0vncserver -version

DESCRIPTION
       x0vncserver  is a TigerVNC Server which makes any X display
       remotely accessible via VNC, TigerVNC or compatible viewers.
       Unlike Xvnc(1), it does not create a virtual display.
       Instead, it just shares an existing X server (typically,
       that one connected to the physical screen).

A: If you would like a secure channel, then you can use ssh.  You would need to enable X11 forwarding on both the client and server (/etc/ssh/ssh_config and /etc/ssh/sshd_config, X11Forwarding, TrustedX11Forwarding).


text:
Q: Why isn't my socket.on() autoscroll function working? I'm trying to set up this auto-scroll function:
const autoscroll = () => {
// New message element
const $newMessage = $messages.lastElementChild

// Height of the new message
const newMessageStyles = getComputedStyle($newMessage)
const newMessageMargin = parseInt(newMessageStyles.marginBottom)
const newMessageHeight = $newMessage.offsetHeight + newMessageMargin

// Visible height
const visibleHeight = $messages.offsetHeight

// Height of messages container
const containerHeight = $messages.scrollHeight

// How far have I scrolled?
const scrollOffset = $messages.scrollTop + visibleHeight

if (containerHeight - newMessageHeight <= scrollOffset) {
    $messages.scrollTop = $messages.scrollHeight}
}

This is the socket.on() function. It works just fine up until the autoscroll():
socket.on('message', (message) => {
console.log(message)
let stamp = localized.format(Date.now());
const html = Mustache.render(messageTemplate, {
    username: message.username,
    message: message.text,
    createdAt: stamp
})
$messages.insertAdjacentHTML('beforeend', html)
autoscroll()
})

When I inspect the site on my browser, there are no errors. The function runs, but the page position doesn't change. Should it be autoscroll('message') inside of the socket function? I can't figure out what the problem is.. here is the HTML.

I've got socket.io, jQuery, mustache, moment, etc. all linked to the main HTML and everything works fine up until it's time to change the scroll position.


text:
Q: Do you get Human form back for helping as a White Phantom? Back in Dark Souls, being a white phantom that helped to kill a boss gave you a significant amount of reward.  Not only did you get the souls of the monsters you helped to kill, you got half the souls of the boss you killed, a sun token if you had a person from that covenant, and you got humanity for your troubles.  At least I'm pretty sure that those were the benefits.
Now, in Dark Souls 2, it seems you still get tokens (either sunlight or fidelity), but you don't always get your humanity back.  There were a number of times I remember finishing a boss with a group of people and I would go from hollow to human.  There were other times that I stayed hollow.
From what research I did on the internet, it sounds like FromSoftware didn't intend you to get humanity back from helping to kill a boss, or even beating a boss in your own game session.  So, that leaves Human Effigies the only way of going back to human.  And with them being a very limited commodity, I question if there will be enough for one play-through in the game.
So, is this really the case?

A: Update
Since Patch 1.03 the bug of randomly getting human form back after multiplayer sessions has been fixed. According to the patch notes, you now get some humanity back for helping others as a white phantom, meaning your health penalty will decrease. When all your health is back, you will regain your human form (I have just tested this). This means you are no longer dependent on human effigies to get your humanity back in online mode.
Patch note excerpt:

Players now receive a small portion of Humanity after successfully assisting in a Multiplayer session instead of regaining full Humanity.

Before Patch 1.03:
Before Patch 1.03, you got revived by playing co-op at random. It does not matter whether you defeat the boss or die, sometimes you will return to your world revived, although you placed your summon sign hollowed.
There are several rumours on the internet, that it gets less likely to revive the more often you fight the boss, or that the amount of human effigies you have has an influence on your chances to revive, but they are wrong.
I once got revived although the summoner died in a boss fight, and once it took six times killing a boss and then only one time killing the same boss to revive, although the circumstances had not changed.
This random procedure indicates, that you are not actually meant to revive. In From Software's twitter post, that has been partially translated at reddit, it has been confirmed, that phantoms reviving is a bug and not actually supposed to happen:

Somebody asked the official Japanese FromSoftware twitter if it was a bug that sometimes you didn't revive to human after helping somebody else play coop.
The answer? "Actually you're not supposed to revive to human, we'll investigate why that happens".

Human effigies are limited in Dark Souls 2, as long as you don't use Bonfire Ascetics, which practically turn areas into New Game + difficulty, but as long as you use them rarely and with care, you shouldn't run out of them. You can find a lot of them as treasure and they also drop from (limited) enemies. For more information on that, see How do I farm Human Effigies?.
Should you find yourself running out of effigies anyway, you can either try to find the Ring of Life Protection, which makes you practically immortal as it can be repaired, or you could try to get summoned and ask other players through private messages to give you an effigy.

A: To add to Dominic's answer, according to fextralife wiki there's another method to become human without using human effigies:

In the Shrine of Amana, there is an altar you can pray to and you can
  become human. After you defeat the boss, proceed to the right and
  follow this path. Take another right and you'll come to a staircase
  leading to a door. It only becomes unlocked if you're hollow. Follow
  this path and you will come across the alter. To become human, a few
  things are required. You must have talked to the Milfanito (the woman
  before boss) so she disappears. You must also not have killed any of
  the other singing women in the Shrine of Amana. Also, you must not
  have a high Sin level and have no Human Effigies in your inventory or
  your item box.

A: You can also join the SunBros which grants you full Humanity if you successfully aid another player in a boss fight.


text:
Q: NHibernate LINQ and Many to Many Mapping I have this clases mapped on NHibernate 3.2 with FluentNHibernate 1.3:
public class ClassA
{
    public virtual Int32 Id{ get; }
    ....
    public ICollection<ClassB> ClassesB { get; }
    public ICollection<ClassC> ClassesC { get; }
}

public class ClassB
{
    public virtual Int32 Id{ get; }
    ....
    public ICollection<ClassA> ClassesA { get; }
    public ICollection<ClassC> ClassesC { get; }
}

public class ClassC
{
    public virtual Int32 Id{ get; }
    ....
    public ICollection<ClassA> ClassesA { get; }
    public ICollection<ClassB> ClassesB { get; }
}

All the mappings works correctly and as spected. But I need to make queries with LINQ that returns, for example, all the ClassC instances in a given ClassB or ClassA instances, and viceversa. I need to do this without loading any ClassB or ClassA instances before getting the list of ClassC, just make the query with the ID of the instance.
I know that I can load, for example, a ClassB instance and then get the ClassesC collection, but with my application desing I must do this without doing that, I'll use this for things like paging on a Grid, and other operations diferent from the paging.
On pure SQL I can do that with a simple join query, but I dont know how to do that with LINQ. And I dont want the option of HQL or ICriteria, it must be done with LINQ (Extensions preferable) because the application uses plugins that must not have awareness of the NHibernate presence. The plugin receives a IQueryable instance to make the queries (this allow us to easely port the core application to other data base schema, like NoSQL or something else without even recompilation of the plugins or other parts of the aplication).
Thanks for your help in advance.

A: By default HasMany in FluentNHibernate will load collections lazy. You could configure this using fluent syntax.
Example of lazy loading:
class ClassAMap : ClassMap<ClassA>
{
    public ClassAMap()
    {
    // ...
    // lazy loading using select
    HasMany(x => x.ClassesB)
        .LazyLoad()
        .Fetch.Select()
    // ...
}

or greedy loading using join:
class ClassAMap : ClassMap<ClassA>
{
    public ClassAMap()
    {
    // ...
    // greedy loading using join
    HasMany(x => x.ClassesB)
        .Fetch.Join()
    // ...
}

or conventions
Table.Is(x => x.EntityType.Name + "Table")
    DefaultLazy.Always()

Anyway this configuration topic is quite complex and depends on how exactly you configure your mapping. I advice you to take a look at hHibernate SQL logs using log4net  to see SQL command are generated by ORM.


text:
Q: Method similar to tts.getEngines().size() in API 8 I have a code to check the TTS engine availability in the device. As the statement tts.getEngines().size() < 1 will be executed only from the API 14. I need to know if there is any way(methods) to check the same functionality even from the API 8.
Thanks in Advance
Code:
private void checkTTSAvailability() {
    tts = new TextToSpeech(this, this);
    ttsPresent=true;
    **if (tts.getEngines().size() < 1) {**
        PackageManager pm = getPackageManager();
        Intent installIntent = new Intent();
        installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
        ResolveInfo resolveInfo = pm.resolveActivity(installIntent, PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfo == null) {
            Log.i("DragDrop", "No voice support on your phone");
            Dialog d = new Dialog(this);
            d.setTitle("Alert  ");
            TextView tv = new TextView(this);
            tv.setText("No voice support on your phone");
            d.setContentView(tv);
            d.show();
            ttsPresent=false;
            // Not able to find the activity which should be started for
            // this intent
        } else {
            Dialog d = new Dialog(this);
            d.setTitle("Alert  ");
            TextView tv = new TextView(this);
            tv.setText("Installing");
            d.setContentView(tv);
            d.show();
            Log.i("DragDrop", "Installing");
            startActivity(installIntent);
        }
    }
}

A: AFAIK, there is no way to list TTS engines or otherwise know they are installed, below API 14. Maybe you could review a list of all installed packages and recognize known TTS engine names there, but it's far from ideal.
The correct way of doing this would be to implement TextToSpeech.OnInitListener() callback in your activity, to know when the default system TTS engine was initialized, and if the initialization was a success or failure. Then, from within this callback on SUCCESS return, first set the language you need on the TTS object, then send an Intent to TTS to check for installed data (ACTION_CHECK_TTS_DATA) for that language, and again when the activity result comes, call ACTION_INSTALL_TTS_DATA if needed.
For a code example, see my other post, link below. It compares async operations in Android Java and C# for Android (with Xamarin for Android), but the Java code sample given there has the correctly functioning OnInitListener() callback.
How to implement Android callbacks in C# using async/await with Xamarin or Dot42?
Greg


text:
Q: How to remove the method's input parameter class < T >, each call will be convenient import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.samples.ar.entity.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo<T> {
    private T t;

    public <T> List<T> getOnet(List<Map<String, Object>> list, Class<T> tClass) {
        //Null pointer exception in this way
        //But this way is convenient, how to realize
        //return (List<T>) JSONArray.parseArray(JSON.toJSONString(list), t.getClass());
        return JSONArray.parseArray(JSON.toJSONString(list), tClass);
    }

    public static void main(String[] args) {
        User user = new User();
        Class<? extends User> aClass = user.getClass();
        List<Map<String, Object>> list = new ArrayList<>();
        for (long i = 0; i < 10; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", i);
            list.add(map);
        }
        List<User> users = new Demo<User>().getOnet(list, User.class);
        System.out.println(users);
    }
}

Environment:Java 8,IntelliJ IDEA
If there is no class <T> input parameter of the method, each call will be convenient. Similar to the implementation of MyBatis plus.
I was worried that the picture would not be displayed, so I wrote this method out
com.baomidou.mybatisplus.core.mapper.BaseMapper

T selectById(Serializable id);

Mybatis-plus BaseMapper

A:
If there is no class < T > input parameter of the method, each call will be convenient

The generics couldn't be used then. Remember you want to serialize JSON into an object, so you need to pass a type of the object through Class<T> tClass. However, the whole thing can be simplified:

*

*Remove the generic type from Demo<T> resulting in Demo.

*Remove the unused type private T t;.

*Define the method getOnet with an explicit generic type:
public <T> List<T> getOnet(List<Map<String, Object>> list, Class<T> tClass) {
    return JSONArray.parseArray(JSON.toJSONString(list), tClass);
}

The usage of this method becomes straightforward as long as the generic type becomes inferred.
List<User> users = new Main().getOnet(list, User.class);


text:
Q: Converting polar coordinate expression to cartesian coordinates An intermediate step in my analysis requires me to work in polar coordinates, but I would like to convert the results back into cartesian coordinates. The conversion is very simple but tedious for complex expressions. I expected to use substitutions, but it isn't panning out for me
polarf[{r_, phi_}] := r^6 Sin[phi]^2 Cos[phi]^2
cartesianf[{k1_, k2_}] :=
 polarf[{r, phi}] /. r^2 Sin[phi]^2 -> k2^2 /.
   r^2 Cos[phi]^2 -> k1^2 /. r^2 -> k1^2 + k2^2
cartesianf[{k1, k2}]

gives me back my original expression:
r^6 Cos[phi]^2 Sin[phi]^2

I'm pretty sure there is a way to get Mathematica to spit out
(k1^2 + k2^2) k1^2 k2^2

or something similar. But how? My searches of Google, Mathematica documentation, and this site have not turned up an answer.

A: You obviously misunderstand replacement rules. Replacement rules work on the structure level, and don't care about the mathematical meaning (they do take into accounts attributes like Orderless, however). In your case, you are saying with your first replacement rule that whereever your result contains the structure (more exactly, the pattern) r^2 Sin[phi]^2 (that is, Times[Power[r, 2], Power[Sin[phi], 2]]), you want that replaced with the expression k2^2. However the result of your function does not contain this structure. It contains r^6 Sin[phi]^2 which doesn't match your pattern because 6 is not 2. For the same reason, your second replacement rule doesn't do anything, either.
What does work is
polarf[{r, phi}] /. { Cos[phi] -> k1/r, Sin[phi] -> k2/r } /.
                    { r -> Sqrt[k1^2 + k2^2] }

This works because the expression generated by polarf, r^6 Cos[phi]^2 Sin[phi]^2, does contain Cos[phi] and Sin[phi], which in the first step get replaced by k1/r and k2/r. Thus you get r^6 (k1/r)^2 (k2/r)^2 which gets further evaluated to r^2 k1^2 k2^2. Now the last replacement rule kicks in, replacing r by Sqrt[k1^2 + k2^2]. Thus you get Sqrt[k1^2 + k2^2]^2 k1^2 k2^2 which evaluates to (k1^2 + k2^2) k1^2 k2^2, which is the expression you want.


text:
Q: What if Paul Atreides failed the Gom Jabbar? I've wondered about the possibility that Mohiam's test was only the threat of death, that she would not have actually killed Paul for failing. However, Jessica's reaction to his success "My son lives!" heavily implies that the test was in fact lethal.
What would Jessica and Mohiam have done with the body of a dead ducal heir on their hands? Maybe 'Weekend at Leto's'? lol

A: I think it's very obvious he would be dead. I don't see any reason for the Bene Gesserit to spare his life if he failed he was after all expendable they wanted a daughter he was never part of their plan.


text:
Q: Facebook Javascript API - Post status update I'm trying to find a complete description of how to post a user status update to Facebook using the Javascript API.
I've looked at other questions and answers on stackoverflow and none of them provide useful answers (most of them just tell you to go look at Facebook's documentation... which is lacking for javascript)
The code I have logs the user in successfully, but i can't seem to request the permissions properly.
The Facebook response error looks like this:
(#200) The user hasn't authorized the application to perform this action
I've been trying to request the permissions AFTER they log in, so that permissions will be requested from them if they visit the web page and are already logged in. Unfortunately adding the following line doesn't work:
FB.Connect.showPermissionDialog('publish_stream');
Any help would be appreciated, but please don't just forward me to Facebook documentation on permissions or Javascript, I've gone through the docs on both, and just can't figure it out.
So far I have:
//Initialize facebook
     window.fbAsyncInit = function() {
      FB.init({
        appId      : '243153685858721',
        status     : true, // check login status
        cookie     : true, // enable cookies to allow the server to access the session
        xfbml      : true  // parse XFBML
      });

      // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
      // for any authentication related change, such as login, logout or session refresh. This means that
      // whenever someone who was previously logged out tries to log in again, the correct case below
      // will be handled.
      FB.Event.subscribe('auth.authResponseChange', function(response)
      {
        // Here we specify what we do with the response anytime this event occurs.
        if (response.status === 'connected') {
          // The response object is returned with a status field that lets the app know the current
          // login status of the person. In this case, we're handling the situation where they
          // have logged in to the app.
            FB.Connect.showPermissionDialog('publish_stream');
            FB.api('/me/feed', 'post', { message: body }, function(response2)
            {
                console.log(response);

                if (!response || response.error) {
                console.log("error");
                console.log(response2);
                console.log(response.error);
                alert("You haven't given our app permissions to post to your wall, please logout of Facebook, then back");
                } else {
                alert('Post ID: ' + response.id);
              }
            });
        } else if (response.status === 'not_authorized') {
          // In this case, the person is logged into Facebook, but not into the app, so we call
          // FB.login() to prompt them to do so.
          // In real-life usage, you wouldn't want to immediately prompt someone to login
          // like this, for two reasons:
          // (1) JavaScript created popup windows are blocked by most browsers unless they
          // result from direct interaction from people using the app (such as a mouse click)
          // (2) it is a bad experience to be continually prompted to login upon page load.
          FB.login();
        } else {
          // In this case, the person is not logged into Facebook, so we call the login()
          // function to prompt them to do so. Note that at this stage there is no indication
          // of whether they are logged into the app. If they aren't then they'll see the Login
          // dialog right after they log in to Facebook.
          // The same caveats as above apply to the FB.login() call here.
          FB.login();
        }
        });
      };


text:
Q: Problem to combine 2 queries to get single set of results I have written two queries for SQL Server, one to provide "Revenue Total" and one to provide "Carrier Total".  I have confirmed that both work properly.  Now, I'm trying to pull all of this data into on set of results with the following query.
select
    a.ctripnumber, 'Revenue Total', 'Carrier Total'
from
    (
        (select r.ctripnumber, sum(Revenue_Subtotal) as 'Revenue Total'
         from
             (select
                  r.ctripnumber, r.cmethod, sum(r.curevenue) as Revenue_Subtotal
              from
                  revenuedtl r
              where
                  r.cmethod in (select distinct r.cmethod from revenuedtl r)
                  --and r.ctripnumber = '324198'
              group by
                  r.ctripnumber, r.cmethod) r
         group by
             r.ctripnumber),
        (select p.ctripnumber, sum(Carrier_Subtotal) as 'Carrier Total'
         from
             (select
                  p.ctripnumber, p.cmethod, sum(p.curevenue) as Carrier_Subtotal
              from
                  payrolldtl p
              where
                  p.cmethod in (select distinct p.cmethod from payrolldtl p)
                  --and p.ctripnumber = '324198'
              group by
                  p.ctripnumber, p.cmethod) p
         group by p.ctripnumber)) a
where
    p.ctripnumber = r.ctripnumber
group by
    a.ctripnumber

However, I'm getting these errors:

Msg 102, Level 15, State 1, Line 11
  Incorrect syntax near ','.
Msg 102, Level 15, State 1, Line 20
  Incorrect syntax near ')'.

The ',' seems that it should be correct, as I am trying to get results from three columns.  I checked the ')' and don't see any orphaned ones.
I've tried the following using inner join, but I get some different errors
select
    r.ctripnumber, 'Revenue Total', 'Carrier Total'
    (select r.ctripnumber, sum(Revenue_Subtotal) as 'Revenue Total'
     from
         (select r.ctripnumber,r.cmethod,sum(r.curevenue) as Revenue_Subtotal
          from revenuedtl r
          where r.cmethod in (select distinct r.cmethod from revenuedtl r)
          group by r.ctripnumber, r.cmethod) r
     group by r.ctripnumber)
inner join
    (select p.ctripnumber,sum(Carrier_Subtotal) as 'Carrier Total'
     from
         (select p.ctripnumber,p.cmethod,sum(p.curevenue) as Carrier_Subtotal
          from payrolldtl p
          where p.cmethod in (select distinct p.cmethod from payrolldtl p)
          group by p.ctripnumber, p.cmethod) p
     group by p.ctripnumber) on r.ctripnumber = p.ctripnumber

The errors that I get this time are:

Msg 156, Level 15, State 1, Line 9
  Incorrect syntax near the keyword 'inner'
Msg 156, Level 15, State1, Line 17
  Incorrect syntax near the keyword 'on'
Clarification

There are two queries that are working well, one that pulls trip numbers and revenue, and another that pulls trip numbers and carrier cost.

Query 1

select r.ctripnumber, sum(Revenue_Subtotal) as 'Revenue Total'
         from
             (select r.ctripnumber, r.cmethod, sum(r.curevenue) as Revenue_Subtotal
              from revenuedtl r
              where r.cmethod in
                  (select distinct r.cmethod from revenuedtl r)
              group by r.ctripnumber,r.cmethod) r
         group by r.ctripnumber

Partial results are:

ctripnumber Revenue Total
160837  682.00
232813  1151.75
163973  335.00
249132  3024.00

Query 2

select p.ctripnumber, sum(Carrier_Subtotal) as 'Carrier Total'
         from
             (select p.ctripnumber, p.cmethod, sum(p.curevenue) as Carrier_Subtotal
              from payrolldtl p
              where p.cmethod in
                  (select distinct p.cmethod from payrolldtl p)
         group by p.ctripnumber, p.cmethod) p
    group by p.ctripnumber

Partial Results are:

ctripnumber Carrier Total
206266  48.00
111099  225.00
107283  206.25
6558    250.00

Now that I have these queries, I want to combine the results, so I
  wrote the following:

select
    a.ctripnumber, 'Revenue Total', 'Carrier Total'
from
    (
        (select r.ctripnumber, sum(Revenue_Subtotal) as 'Revenue Total'
         from
             (select r.ctripnumber, r.cmethod, sum(r.curevenue) as Revenue_Subtotal
              from revenuedtl r
              where r.cmethod in
                  (select distinct r.cmethod from revenuedtl r)
              group by r.ctripnumber,r.cmethod) r
         group by r.ctripnumber),
        (select p.ctripnumber, sum(Carrier_Subtotal) as 'Carrier Total'
         from
             (select p.ctripnumber, p.cmethod, sum(p.curevenue) as Carrier_Subtotal
              from payrolldtl p
              where p.cmethod in
                  (select distinct p.cmethod from payrolldtl p)
         group by p.ctripnumber, p.cmethod) p
    group by p.ctripnumber)
) a
where p.ctripnumber = r.ctripnumber
group by a.ctripnumber

I am getting the following errors:
Msg 102, Level 15, State 1, Line 12 Incorrect syntax near ','.
Msg 102, Level 15, State 1, Line 21 Incorrect syntax near ')'.

A: I wouldn't recommend using spaces inside column names, but does this work for you?
select
    tRev.ctripnumber, "Revenue Total", "Carrier Total"
FROM
(select r.ctripnumber, sum(Revenue_Subtotal) as "Revenue Total"
 from
     (select r.ctripnumber,r.cmethod,sum(r.curevenue) as Revenue_Subtotal
      from revenuedtl r
      where r.cmethod in (select distinct r.cmethod from revenuedtl r)
      group by r.ctripnumber, r.cmethod) r
 group by r.ctripnumber) tRev
inner join
(select p.ctripnumber,sum(Carrier_Subtotal) as "Carrier Total"
 from
     (select p.ctripnumber,p.cmethod,sum(p.curevenue) as Carrier_Subtotal
      from payrolldtl p
      where p.cmethod in (select distinct p.cmethod from payrolldtl p)
      group by p.ctripnumber, p.cmethod) p
 group by p.ctripnumber) tCar on tRev.ctripnumber = tCar.ctripnumber


text:
Q: Suggestion regarding Cost reduction on Using Dynamodb I'm newbie to dynamodb, I have just 10 items and 1 global secondary Index with Read/write capacity units 5(minimum) which cost around $6/2days which is unacceptable for me because I have used only  0.01% of my actual needs I have gone through some documentation in aws dynamodb price reduction non helped me, because AWS recommend to avoid sudden spike read using query or scan, which is impossible to get more than one item with Partition key alone.
Tables as follows
Add_Employee
Add_Stocks
Add_vendor
All above table have read/write capacity units 1 and each have one global secondary index read/write capacity units 1. All tables are config within specified region Asia Pacific (Mumbai)
Here is my billing for reference
$0.00 per hour for 25 units of read capacity for a month (free tier)18,600 ReadCapacityUnit-Hrs $0.00
$0.00 per hour for 25 units of write capacity for a month (free tier)18,600 WriteCapacityUnit-Hrs $0.00
$0.000148 per hour for units of read capacity beyond the free tier 6,723 ReadCapacityUnit-Hrs $1.00
$0.00074 per hour for units of write capacity beyond the free tier 6,723 WriteCapacityUnit-Hrs $4.98
Thanks in advance

A: You're not just paying for actual throughput, you're paying for provisioned throughput.
Looking at The Dynamo cost page, this means you are paying $0.0065 per throughput-hour each table exists per month, minus the free-tier hours.
Based on your table names, I'm guessing you are not following the best practice of using 1 de-normalized table table for everything.  You may be better off using an RDS instance, which will not charge by the table, but by the hour (it's an EC2 instance behind the scenes).
Cost Breakdown
The default is 5 provisioned read/write units, and there are 720 hours in a 30-day month
$0.0065 * 5 * 720 = $24.37 a month per table
The free tier generally allows one table for free a month.
Per AWS docs you must have at least 1 provisioned unit.
How to Save

*

*Make sure you're following the best practice of using 1 de-normalized table

*For any dev work, make sure both read and write provisions are set to 1 ($0.0065 * 1 * 720 = $4.68 a month per table)

*If you know you're going to be away for a while, remove the stack from AWS.  You're only charged while the table(s) exists.
By limiting read/write units you should be able to bring the cost down to ~$5.00 a table per dev.
DO NOT TURN ON AUTO-SCALING
A commenter suggested auto-scaling.  Per docs, you'll be charged for at least 5 units, which is what you are paying now.
This AWS forum link is about the same thing.


text:
Q: Reference all pages where specific label occurs It seems like a simple question, but I cannot find the solution. In the body of the book the same name, say John Smith is mentioned a number of times. I would like to label this name with \label{Smith} across entire book, so I can write in the prefatory note to the book something like "In this autobiography, the name of Dr. Smith is mentioned on pages xyz \pageref{Smith}" (something similar to what \makeindex generates). Obviously, when I try to use same label more than once, I get an error. Is there a specific package to create a list of pages that I am looking for? I would appreciate if someone can stir me in the right direction.
\documentclass[a4paper,12pt]{extreport}
\usepackage{fontspec}
\usepackage{polyglossia}
\setdefaultlanguage{english}
\setmainfont{CMU Serif}
\begin{document}
The word to the reader:
"In this autobiography, the name of Dr. Smith is mentioned on pages xyz `\pageref{Smith}`"
\newpage
Bla... John Smith\label{Smith}
\newpage
Bla... John\label{Smith}
\newpage
Ba...Dr. J. Smith\label{Smith}
\end{document}


text:
Q: customize a spinner to drop down a textview and reduce the size of two other spinners with the same customized dropdown So What My application does is query a Database, I finally have the query all worked out and I got it to display to a Textview. The problem is I want the user to be able to see the result of 3 separate but similar queries, all in the same Activity, in Textviews.
I have almost no knowledge of how to customize layout items in android and I really wanted to Have a layout with nothing but 3 spinners and whenever you click on one (or when you arrive at the Activity) to have one dropdown of a Spinner (Which has a textview) that takes up most of the screen but leaves enough room for the two other spinners to be clearly viewed and clicked but not displaying their textviews.
Then when one of the other Spinners are clicked, It would reduce the size of the spinner that was open (with textview) to just the spinner and open the dropdown (with textview) of the spinner that was just clicked.
I don't even know if this is possible and if it is where would I start?


text:
Q: Accept Macbook Touchbar typing suggestions with keyboard I mostly type using my external keyboard while my Macbook Pro is sitting on my desk, away from my hands. Sometimes I'd like to accept the Touchbar typing suggestions, but it's more work to get my fingers to the Touchbar and back than it is to finish typing the word, no matter how long or contrived.
Is there a way to accept suggestions with a keyboard shortcut? I didn't find such an option within MacOS preferences, I'm hoping I just missed it.

A: From Apple documentation:

Touch Bar typing suggestions
If your Mac has a Touch Bar, enable this option to display typing
suggestions in the Touch Bar as you type.
While typing, you can display a list of suggested words onscreen by
pressing F5 (you may need to also press the Fn key, depending on your
Mac model).


text:
Q: Python: Import Class: how to disable automatic initialization? I created the mySimpleFile.py file with class "MySimple"
class MySimple (object):
    def __init__(self, name):
        self.name = name
        print("from Class",self.name)

print ("I do not want this automatically!!!")

Now I want to import this class to my another file.
import mySimpleFile

print("bla bla bla")

So I get this:
I do not want this automatically!!!
bla bla bla

So how can I disable this initialization?
Thank you!

A: Put it in an if __name__ block so that it's only executed if it's the "main" script file, and not if it's imported:
if __name__ == '__main__':
    print ("I do not want this automatically!!!")

A: Use the following idiom:
if __name__ == '__main__':
    print ("I do not want this automatically!!!")

This feature is specifically there to run a portion of code when the file is run directly, not when it's imported.

A: add
if __name__ "__main__":
    print("I don't want this")

So when you'll import this file, the print won't be execute because it's not the main file


text:
Q: Microsoft OLE DB Provider for Visual FoxPro: Invalid path or file name I'm able to connect to my VFP database when running my classic ASP site locally w/ Visual Studio and IIS Express but when I deploy to a server on IIS it get:

Microsoft OLE DB Provider for Visual FoxPro: Invalid path or file name

From a comment on this post, I see the problem is probably related to permissions but I've got the application pool running under a domain account that has access to the UNC where the DB resides.

A: I changed my authentication on anonymous access from IUSR to the Application pool identity and it started working.
IIS Manager -> Website -> Authentication -> Anonymous Authentication -> Edit

After changing that, the database access must be using the service account now.  I guess there's a difference between ASP.NET and Classic ASP?

References how I arrived at this answer
I found this post which talked about anonymous access which got me thinking more about "classic asp run under service account".  That Google search lead to me to this SO post:

Classic ASP runs impersonating the user who is authenticated to the server in the HTTP session.


text:
Q: Busca recursiva de arquivos em diretórios Tenho uma função que busca arquivo passado por parâmetro em diretórios usando linguagem C no Linux, estou conseguindo entrar nos subdiretórios e fazer a busca, porem ao terminar os arquivos no subdiretório não consigo voltar ao diretório anterior e continuar a busca.
   int buscaArquivo(char *arquivo, char *diretorio){
   dir = opendir(diretorio);
   if(dir==NULL){
       printf("\n não foi possivel abrir o diretorio %s", diretorio);
       return -1;
   }
   finito = 0;
   do{
       entry = readdir(dir);
       if(entry == NULL){
          printf("\nfim do diretorio");
          closedir(dir);
          finito = 1;

       }else{
           char entrada[PATH_MAX];
           snprintf(entrada,sizeof(entrada),"%s/%s",
                  diretorio, entry->d_name);
           if(entry->d_type == 4){
           //    printf("\n%s",entry->d_name);

           }

           if(strcmp(entry->d_name,arquivo)== 0) //compara nome do arquivo
             printf("\n%s/%s\n", diretorio,arquivo); // achou

           if( (strcmp(".",entry->d_name)) && (strcmp("..",entry->d_name)) && (entry->d_type == 4) ){
               printf("\nentrou no dir %s",entry->d_name);
               buscaArquivo(arquivo,entrada);
           }
       }

   }while(finito == 0);
   return 0;
}

A: O comando return da função buscaArquivo já faz isso...e aparentemente seu código está correto. Só reformatei para ficar mais ao meu gosto, mas está funcionando.
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

int buscaArquivo(char *arquivo, char *diretorio)
{
   char entrada[PATH_MAX];
   struct dirent* entry;

   printf("abrindo diretorio %s\n", diretorio);
   DIR* dir = opendir(diretorio);

   if (dir == NULL)
   {
      printf("não foi possivel abrir o diretorio %s\n", diretorio);
      return -1;
   }

   for (;;)
   {
       entry = readdir(dir);
       if (entry == NULL)
       {
          printf("fim do diretorio %s\n", diretorio);
          closedir(dir);
          break;
       }

       snprintf(entrada,sizeof(entrada),"%s/%s", diretorio, entry->d_name);
       if (entry->d_type == 4)
       {
          printf("(diretorio %s)\n",entry->d_name);
       }

       if (strcmp(entry->d_name,arquivo) == 0)
          printf("encontrou arquico: %s/%s\n", diretorio,arquivo);

       if ((strcmp(".",entry->d_name)) && (strcmp("..",entry->d_name))
          && (entry->d_type == 4))
       {
           printf("entrou no dir %s\n",entry->d_name);
           buscaArquivo(arquivo,entrada);
       }
   }

   return 0;
}

int main()
{

buscaArquivo("aaa", "bbb");

}

A: Como foi dito que era em linux, não resisto a lembrar que o C nos permite tirar partido do sistema operativo (=fazer um pouco de batota ☺). Usando popen:
#include <stdio.h>
#include <string.h>

int buscaArquivo(char *arquivo, char *diretorio){
   char com[200],entrada[200];
   sprintf(com,"find '%s' | grep '/%s$'", diretorio, arquivo);
   FILE* f = popen(com,"r");
   while(fgets(entrada,200,f)){
      printf("--> %s",entrada);
   }
   pclose(f);
}

int main(int argc, char* argv[]){
  if(argc == 3) buscaArquivo(argv[1],argv[2]);
}


text:
Q: SQLite data disappears after being updated I've created an empty table in a sqlite database, DB, via a database adapter.
Since I have a lot of data (10,000+ rows) to be inserted and I don't want to do it in the activities so I pull the sqlite database out of data/data/package-name/databases and inserted the rows via sqlite browser software. I then reinserted/push the updated DB it back into the eclipse DDMS and all was fine at first.
The DB has an inflated size of 800kb from the original 22kb.
But after running the emulator again, I noticed that the DB shrunk back to 22kb and upon pulling it out and inspecting it, the rows I inserted is no longer there.
Strange enough, the DB journal file in the same folder is now inflated to 800kb, but I can not open that file (sqlite browser says the file is either corrupt or encrypted but not a valid Sqlite file). Can someone explain what happened?

A: Did you commit changes after updating database? Also check if database is not dropped when Eclipse uninstall old version of the application before new one is deployed on target.


text:
Q: Rails with Postgres data is returned out of order I've just transitioned my app from MySQL to Postgres. Previously, a request for .all returned all the rows in id order. On Postgres the rows are returned out of order. Likewise,
Person.first

used to return the record with id 1, now it sometimes returns another record.
If I add an order clause like this:
Person.order("id").first

The query succeeds and returns the first row. Is this expected behaviour?

A: this post answers your question:

I don't think ordering by ID is guaranteed by default, since I believe it's up to the database how a non-ordered query gets returned. You can make it be ordered so by defining a default scope at the top of your model like so:
default_scope order('id ASC')

Then calling Model.all will be equivalent to calling Model.order('id ASC').


text:
Q: Call function in query in Entity framework 3.5 I am trying to run following query in entity framework 3.5
var test = from e in customers where IsValid(e) select e;
Here IsValid function takes current customer and validate against some conditions and returns false or true. But when I am trying to run the query it is giving error "LINQ Method cannot be translated into a store expression." Can any body tell me any other approach?
One approach I can think of is to write all validation conditions here, but that will make the code difficult to read.
Thanks
Ashwani

A: As the error text implies, the EF Linq provider can not translate the IsValid method into SQL.
If you want the query to execcute in the DB, then you would have to write your validation conditions in the linq statement.
Or if you simply want to fetch all customers and then check if they are valid you could do:
var test = from e in customers.ToList() //execute the query directly w/o conditions
           where IsValid(e)
           select(e);


text:
Q: How to create a MasterDetailPage using MvvmCross? I'm trying to develop a Xamarin.Forms app using MvvmCross and I'd like to use a Hamburguer Menu (MasterDetailPage), but I don't know how to do it. I tried different ways, searched for tutorials and samples, but I don't had success. Can anyone help me?

A: As you can see here MvvmCross Playground, you should create first a RootViewModel, MenuViewModel, and FirstViewModel for example. Then create and a RootPage, MenuPage and FirstPage on your UI folder.
Your RootViewModel should look like this:
public class RootViewModel : BaseViewModel
{
    private readonly IMvxNavigationService _navigationService;
    public RootViewModel(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;
    }

    public override void ViewAppearing()
    {
        base.ViewAppearing();

        MvxNotifyTask.Create(async ()=> await this.InitializeViewModels();
    }

    private async Task InitializeViewModels()
    {
        await _navigationService.Navigate<MenuViewModel>();
        await _navigationService.Navigate<FirstViewModel>();
    }
}

edit: I move the navigation to an async task to avoid using async void.
The xaml RootPage must implement MvxMasterDetailPage:
<?xml version="1.0" encoding="UTF-8"?>
<views:MvxMasterDetailPage x:TypeArguments="viewModels:RootViewModel"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:views="clr-namespace:MvvmCross.Forms.Views;assembly=MvvmCross.Forms"
    xmlns:mvx="clr-namespace:MvvmCross.Forms.Bindings;assembly=MvvmCross.Forms"
    xmlns:viewModels="clr-namespace:yournamespace.Core.ViewModels"
    x:Class="yournamespace.UI.Views.RootPage"
    Icon="hamburger.png">
</views:MvxMasterDetailPage>

and c# code behind use the presenter like this:
[MvxMasterDetailPagePresentation(MasterDetailPosition.Root, WrapInNavigationPage = false)]
public partial class RootPage : MvxMasterDetailPage<RootViewModel>
{
    public RootPage()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
    }
}

MenuPage must be normal MvxContentPage and c# code behind implement on menu page the presenter:
[MvxMasterDetailPagePresentation(MasterDetailPosition.Master)]

And FirstPage are MvxContentPage too and all the detail pages must be:
[MvxMasterDetailPagePresentation(MasterDetailPosition.Detail, NoHistory = true)]

Add the no history to all pages in master detail to prevent navigation back bug.
edit: i forgot, there's a bug that make menu doesn't close after navigate, probably they'll fix on version 6 of MvvmCross, to fix it now you must paste this in your navigation task before execute the navigation:
if(Application.Current.MainPage is MasterDetailPage masterDetailPage)
{
    masterDetailPage.IsPresented = false;
}
else if(Application.Current.MainPage is NavigationPage navigationPage && navigationPage.CurrentPage is MasterDetailPage nestedMasterDetail)
{
    nestedMasterDetail.IsPresented = false;
}


text:
Q: How to parse this json array? I have a php file that output json array:
[{"id":407,"parentId":406,"level":null,"name":"Зал VIII"},{"id":408,"parentId":406,"level":null,"name":"Зал IV"},]

Trying this function:
var levels = '';
function parse() {
    $.get('url_to_json_file', function(data){
        $.each(data, function(key, value){
            levels += (value.id +' - '+ value.name);
        });
    });
return levels;
}

But result always undefined - undefined.

A: jQuery has a $.parseJSON() function.
Try:
$.parseJSON('[{"id":407,"parentId":406,"level":null,"name":"Зал VIII"},{"id":408,"parentId":406,"level":null,"name":"Зал IV"}]');
//Returns [Object,Object];


text:
Q: List VMs - Google Compute Engine Node.js Client Library I get a list of all VMs when I exclude the keyFilename from Compute object's constructor.
const Compute = require('@google-cloud/compute');
const compute = new Compute();
const vms = await compute.getVMs(); // populated with right results

But as soon as I specify the keyFilename in Compute object's constructor, none of my VMs show up in result although they share the same Google Cloud Project ID as specified in the keyFilename.
const Compute = require('@google-cloud/compute');
const compute = new Compute({
    keyFilename: 'gcp.json'
});
const vms = await compute.getVMs(); // empty array

Please help!

A: Maybe it is a good idea to use an absolute path for the keyFilename and add the parameter
projectId: 'your-project-id'

to the constructor.
Besides that, your code looks pretty much vanilla so I see no problems, should work, according documentation.


text:
Q: Loading controller await problem with Ionic In my ngOnInit page I call a function to present a Loading and then call my service to load data.
The problem is that the service call ends before the loading starts.
How is it possibile with await?
loading: any;
...
ngOnInit() {
    this.presentLoading();
    this.myService.get().subscribe((item)=>{
      console.log('dismiss');
      this.loading.dismiss();
    }, ()=>{
      this.loading.dismiss();
    })
  }

  async presentLoading() {
    this.loading = await this.loadingController.create({
      message: 'Loading...',
      duration: 20000
    });
    console.log('presentLoading')
    await this.loading.present();
  }

In console i can see:
dismiss
ERROR TypeError: Cannot read property 'dismiss' of undefined....
presentLoading

I'm using Ionic4.

A: In your case (based on the code) you have presentLoading function that returns a promise (async), so even though inside of it you are using await statements - inside the ngOnInit hook nothing instructs execution to await for the presentLoading.
You could do:
  async ngOnInit() {
    await this.presentLoading();
    this.myService.get().subscribe((item)=>{
      console.log('dismiss');
      this.loading.dismiss();
    }, ()=>{
      this.loading.dismiss();
    })
  }

Also since you are using Onservables it may makes sense to call dismiss inside "completed" function:
  async ngOnInit() {
    await this.presentLoading();
    this.myService.get().subscribe((item)=>{
      console.log('dismiss');
    }, (error)=>{
      console.log(error);
    }, (completed)=>{
      this.loading.dismiss();
    }
  })

A note - making ngOnInit an async method does not "hurt", but its best to know a bit more waht implications it has: async/await in Angular `ngOnInit`


text:
Q: How to select a row that has a column with the minimum value from a subset of rows? I have a table of events' outcome probabilities from different bookmakers, odds(id, event_id, bookmaker_id, market_id, value), from where I want to select the lowest odd for all markets.
I came up with
SELECT * FROM odds WHERE value IN (SELECT MIN(value) FROM odds GROUP BY market_id)

But that's wrong because the IN filter may compare values that does not belong to the current row.

A: Use a correlated subquery:
SELECT o.*
FROM odds o
WHERE o.value = (SELECT MIN(o2.value) FROM odds o2 WHERE o2.market_id = o.market_id);


text:
Q: Images not showing in device for Web view in iphone I am working on one application. I stuck with one problem. I have HTML page and some images are in Resource Directory. Whenever i run the application on Simulator it works perfectly fine. But when i run the application on the device the image are not displaying but text is displaying only and instead of image Question mark is showing.
Code:
      NSString *path = [[NSBundle mainBundle]  pathForResource:@"test1" ofType:@"html"];
    NSFileHandle *readHandle = [NSFileHandle   fileHandleForReadingAtPath:path];
NSString *htmlString = [[NSString alloc] initWithData: [readHandlereadDataToEndOfFile]encoding:NSUTF8StringEncoding];
 NSURL *baseurl = [NSURL fileURLWithPath:path];
[self.webView loadHTMLString:htmlString baseURL:baseurl];

HTML Code:

A: Change your HTML code to (file:// tells that it's local resource):

Then use it in this way:
NSString *pathToLocalImage = [[NSBundle mainBundle] pathForResource:@"mainGrid" ofType:@"jpg"];
NSString *content = [NSString stringWaithFormat:htmlString, pathToLocalImage];
[self.webView content baseURL:nil];


text:
Q: Second Quantization: The Identity Operator does not Commute? Let me take the simplest possible example. Consider the fermonic Fock-space $\Lambda^*(\mathbb{C}^n)$ built out of a finite-dimensional, oriented single-particle Hilbert space $\mathbb{C}^n$ with orientation
$$[\psi_1,\cdots, \psi_n].$$
The identity operator on this Fock-space may be written as
$$1= \sum_{j=1}^n c_j^\dagger c_j,$$
where $c_j,c_j^\dagger$ create and annihilate $\psi_j$ respectively. Therefore, $1$ should commute with every other operator. However, it doesn't. Take $c_i$, for example:
$$[1,c_i]=\sum_{j=1}^n[c_i,c_j^\dagger c_j]=\sum_{j=1}^n(c_ic_j^\dagger c_j-c_j^\dagger c_jc_i)$$
$$~~~~~~~~~=\sum_{j=1}^n(\delta_{ij}c_j-c_j^\dagger c_ic_j-c_j^\dagger c_jc_i)=\sum_{j=1}^n\delta_{ij}c_j=c_i.$$
Does anyone else find this confusing?

A: The identity operator is not $\sum_j c^\dagger_j c_j = \sum_j |1_j\rangle\langle1_j|$ but rather $$\prod_j \big(|0_j\rangle\langle0_j| + |1_j\rangle\langle1_j| \big) = \prod_j\left(c^\dagger_j c_j + c_jc_j^\dagger\right) = \prod_j \left\{c_j^\dagger,c_j\right\}.$$Fortunately $\left\{c_j^\dagger,c_j\right\}=1$ for fermionic CAPs.


text:
Q: Youtube Javascript API Play/Pause/Stop not working I'm having some trouble with the Youtube API. Currently I'm simply trying to have a "play" button next to a video. I'm running the code on a local webserver (not on my hard drive) and I've searched multiple topics on the internet to no avail. Here's a demo I saw on another stackoverflow topic, which should theoretically work (and it's the code I'm trying to use currently): http://jsfiddle.net/L8qMe/1/
However, in Firefox 15 and IE on Windows 7, the play button does not work for me in the demo, so I no longer think this is a code problem. Is it a security setting maybe? Is there a way around it? Please help!
Update: neither the demo nor my webserver (running the demo's code) works in google chrome either.

A: You need to add event listeners:
function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("myytplayer");
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
    ytplayer.addEventListener("onError", "onPlayerError");
}

Check JSFiddle


text:
Q: F3 button not working in Minecraft My F3 button doesn't work in Minecraft and no I don't want to brighten me screen but the F3 button is used for opening the coordinates and a lot of other things but for some reason I press the button to do but it brightens the screen instead.

A: Usually I just hold function down while pressing F3 you can try this and if it doesn't work you can just try changing your controls.


text:
Q: Ruby modify hash in "each" block. Pass-by-value subtlety ? According to this question, ruby is strictly pass-by-value. I came across a case though, which consists of modifying a hash like so:
h = {"one" => ["un", "ein"], "two"=> ["deux", "zwei"]}
h.each { |k,v| v << "overriden"}

resulting in:
{"one"=>["un", "ein", "overriden"], "two"=>["deux", "zwei", "overriden"]}

However, the following behaves differently:
h = {"one" => "un", "two"=> "deux"}
h.each { |k,v| v = "overriden"}

resulting in:
{"one"=>"un", "two"=>"deux"}

How could I have predicted this?

A: If you read the next paragraph in the answer you linked, it says this:

Ruby doesn't have any concept of a pure, non-reference value, so you certainly can't pass one to a method. Variables are always references to objects. In order to get an object that won't change out from under you, you need to dup or clone the object you're passed, thus giving an object that nobody else has a reference to.

The << operator modifies an array in place. You have a reference to the array, the hash has a reference to that array, and when the array changes, they both point at the same array.
When you use = you are assigning a value to a variable. In a way, you are telling the variable to refer to something else, instead of doing something to the thing the variable references.


text:
Q: Create a matrix using values from a tuple with numpy I'm trying to create a matrix with values based on x,y values I have stored in a tuple. I use a loop to iterate over the tuple and perform a simple calculation on the data:
import numpy as np

# Trying to fit quadratic equation to the measured dots

N = 6
num_of_params = 3

# x values
x = (1,4,3,5,2,6)

# y values
y = (3.96, 24.96,14.15,39.8,7.07,59.4)

# X is a matrix N * 3 with the x values to the power of {0,1,2}
X = np.zeros((N,3))
Y = np.zeros((N,1))

print X,"\n\n",Y

for i in range(len(x)):
    for p in range(num_of_params):
        X[i][p] = x[i]**(num_of_params - p - 1)
    Y[i] = y[i]

print "\n\n"
print X,"\n\n",Y

Is this can be achieved in an easier way? I'm looking for some way to init the matrix like X = np.zeros((N,3), read_values_from = x)
Is it possible? Is there another simple way?
Python 2.7

A: Extend array version of x to 2D with a singleton dim (dim with length=1) along the second one using np.newaxis/None. This lets us leverage NumPy broadcasting to get the 2D output in a vectorized manner. Similar philosophy for y.
Hence, the implementation would be -
X = np.asarray(x)[:,None]**(num_of_params - np.arange(num_of_params)  - 1)
Y = np.asarray(y)[:,None]

Or use the built-in outer method for np.power to get X that takes care of the array conversion under the hoods -
X = np.power.outer(x, num_of_params - np.arange(num_of_params)  - 1)

Alternatively, for Y, use np.expand_dims -
Y = np.expand_dims(y,1)


text:
Q: Django-CMS, how to resolve a named apphook URL from a management command? I've got a management command which sends email. In this email, I'd like to include a URL to a signup form, which is an apphook module in the CMS.
How can I resolve the URL to that path?
From the management command, I only see the plain URLconf, without the changes made by Django-CMS.

A: Solved my problem. It turns out that the pages may not appear in the URLconf (or urlpatterns), but the reverse() will work nevertheless.
The pagename does have to be fixed with the language code. For example:
reverse('nl:my-profile')

And the cms.appresolvers module will do it's work to find the page.


text:
Q: How to change ng-model? There is Angular JS:
$scope.changeSelect = function (item){
    if(item == 0){
      // Здесь изменить ng-model элемента
    }
}

HTML:
<select ng-model="city" ng-change="changeSelect(city)">
<select ng-model="country" ng-change="changeSelect(country)">

I need reset ng-model for each ng-change if condition is true
What I want
When I call function ng-change="changeSelect()" I need check value on zero, if true, change this ng-model value to null. Updated question

A: Try this
Html :
<select ng-model="city" ng-change="changeSelect(this.city)">
<select ng-model="country" ng-change="changeSelect(this.country)">

JS Cde
$scope.changeSelect = function (item){
    if (item == 0) {
         item=null;
    }
}

Update :
Another way is manually thinking Way :p
 <select ng-model="city" ng-change="changeSelect(this.city,'city')">
    <select ng-model="country" ng-change="changeSelect(this.country,'country')">

.........
$scope.changeSelect = function (item, selectedContex) {
            if (item == 0) {
                if (selectedContex == "city") {
                    $scope.city = null;
                    return false;
                }
                else if (selectedContex = 'country') {
                    $scope.country = null;
                    return false;
                }
            }
        }

A: HTML:
<select  ng-model="(changeSelect(city) ? null: city)">

Script:
$scope.changeSelect = function (item){
    if(item == 0){
      return true;
    }
    else {
      return false;
    }
}

A: You can use the angular-reset-on directive I've wrote. With this directive you can specify a condition to reset each field.
For example:
<select ng-model="city" ng-reset-on="city == 0">
<select ng-model="country" ng-reset-on="country == 0">

It's as simple as that. :)


text:
Q: Replace a line with another line using IF - Batch file I am trying to replace a line in load.xml using the lines read from FileList.txt.
Contents of load.xml
<mainheader>
        <InFilePath>D:\Data\All_Inputfiles\oldfile.txt</InFilePath>
</mainheader>

FileList.txt
 newfile1.txt
 newfile2.txt

Expecting the output with each iteration as
   <mainheader>
            <InFilePath>D:\Data\All_Inputfiles\newfile1.txt</InFilePath>
    </mainheader>

and with the next iteration replace newfile1.txt with newfile2.txt. I am able to get original string with the final string but last part of the code is throwing syntax error, i.e. from
for /f "delims=" %%a in (!INTEXTFILE!) do call :Change "%%a"  .
Could please help me?
Thanks in advance.
    @echo off
SETLOCAL EnableDelayedExpansion
Set AllInputFile= D:\data\FileList.txt
SET INTEXTFILE=C:\c:\load.xml
set OUTTEXTFILE=D:\data\tmp_out.txt
SET BackupPath=D:\data\backupload.xml
Set TempFile=D:\data\tmp.txt
SET DbgFile=D:\data\debuginfo.txt
 Del !TempFile!
 Del !DbgFile!
 Copy !INTEXTFILE! !BackupPath!
:replace
   findstr /g "InFilePath" !INTEXTFILE!>!TempFile!
   :: set string="        <InFilePath>D:\Data\All_Inputfiles\oldfile.txt</InFilePath>"
   set /p string=< !TempFile!
   SET PREVFILE_NM=!string:~75,-13!
  set FinalreplaceLine=!string!
  set TARG_FILE=%~1
  REM ECHO  "Before Replace FinalreplaceLine "!FinalreplaceLine!>>!DbgFile!
   set FinalreplaceLine=!FinalreplaceLine:%PREVFILE_NM%=%TARG_FILE%!
   ECHO  "string "!string!>>!DbgFile!
  ECHO  "FinalreplaceLine "!FinalreplaceLine!>>!DbgFile!

  ::string has source string and FinalreplaceLine has target string to replace
  for /f "delims=" %%a in (!INTEXTFILE!) do call :Change "%%a"
  exit /b

  :Change
  set Text=%~1
   if "%Text%"=="%string%" (
    (echo !FinalreplaceLine!)>> !OUTTEXTFILE!
     ) else (
     (echo !Text!)>> !OUTTEXTFILE!
       )
    exit /b

A: Does this work for you?:
@echo off
for /f "usebackq delims=" %%a in ("FileList.txt") do (
   call :change "%%a"
   type "load.xml"
   pause
)
echo done
pause
goto :EOF
:change
(
echo ^<mainheader^>
echo        ^<InFilePath^>D:\Data\All_Inputfiles\%~1^</InFilePath^>
echo ^</mainheader^>
) > "load.xml"


text:
Q: Get element from selected listview row I have a ListView in Xamarin.Forms that uses data binding. I am using an ItemSelected event which gets the current index. I would like to get the price attribute of the selected ListView row. Using Tracepoint, I see the value in e => SelectedItem => Price.

How can I save this into a variable? I have tried:
double val = e.SelectedItem.Price;

However, this does not work.

'object' does not contain a definition for 'Price' and no accessible extension method 'Price' accepting a first argument of type 'object' could be found.

I would like to store the price of the selected ListView row into a variable. Thank you.

A: Since you had used data binding , you should handle all the logic in your ViewModel .
<ListView ItemsSource="{Binding xxx}" SelectedItem="{Binding SelectItem,Mode=TwoWay}" >
...

in ViewModel
public class YourViewModel :INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private YourModel selectItem;
    public YourModel SelectItem
    {
        get
        {
            return selectItem;
        }

        set
        {
            if (selectItem!= value)
            {
                selectItem= value;
                NotifyPropertyChanged();

               double val = selectItem.Price;
               // do some thing you want here
            }
        }
    }

    //...
}

In your case , Price is the property of the model ,not the property of SelectedItem .Or you can improve your code like following. But as I said ,use MVVM is better .
var SelectItem = e.SelectedItem as YourModel;
double val = SelectItem .Price;


text:
Q: Windows explorer only shows size of first disk in NAS My Zyxel NSA325v2 NAS has two 6TB disks. Free space on disk1 is 4,91 TB, on disk2 4,48 TB.
In windows explorer both disks are displayed to have 4,48 TB free, so it is showing the free space of disk2 for both the disks. Disk 2 was mounted before disk 1 so I think it actually is showing the size of the first disk that was loaded. I dont know if this a problem of the NAS (the GUI of the NAS is showing the right free space) or windows explorer.
My NSA325v2 is still using smbv1 and will not be upgraded to smbv2 or later. Could that be the problem?


text:
Q: Ordering on $\lambda$-tabloids Let $\lambda$ be a partition of $n$ ($n=\lambda_1+\lambda_2+\cdots + \lambda_k$ and $\lambda_1\ge \lambda_2\ge\cdots$).
There is an ordering on the collection of all the $\lambda$-tabloids:
Let $\{t_1\}$ and $\{t_2\}$ be two $\lambda$-tabloids. We sat $\{t_1\}<\{t_2\}$ if there is an $i$ such that

*

*$i$ is in higher row of $\{t_1\}$ than $\{t_2\}$

*for all $j>i$, the entry $j$ lies in same row of $\{t_1\}$ and $\{t_2\}$.

Q.0 Is there any other equivalent version of this ordering? (I didn't get what we want to say through this ordering?)
Q.1 For what purpose this ordering of tabloids is important in the representations of symmetric groups?
Q.2 Since $\lambda$-tabloids are canonically in bijection with subgroups of $S_n$ of the form $S_{\lambda_1}\times S_{\lambda_2}\times \cdots \times S_{\lambda_k}$, so on the {\it subgroup level}, what the above ordering corresponds? What the about ordering says in terms of subgroups?


text:
Q: Explaining why process obeys Central Limit Theorem I'm trying to explain why some complex process obeys Central Limit Theorem.
The process is a chip compiler that runs complex place & route algorithms. The input is an integer seed. It initializes the algorithms in a random way. The output is a real number, which determines quality of results; the higher the number - the better. Exact implementation of place & route algorithms is not known. But their goal is to reach quality of results be positive.
I run 100 compiles with different seeds. When I plot a histogram of the results, it looks like a normal distribution. I tried different designs, tool versions, etc., and always get nicely shaped normal distribution, but with different mean and variance.
I strongly suspect that Central Limit Theorem plays a role here. But why?
Why would a complex place&route algorithm obey CLT, if it has nothing to do with any random distribution. Or maybe the interpretation of the results has nothing to do with the CLT.
Below is a process block diagram and example of the results.

A: One important point that many seem to be confused about is the application of the Central Limit Theorem (CLT). The CLT applies to the arithmetic mean of a distribution—not the distribution itself. Given an increasing number of samples, the average of those samples tends to be normally distributed with the "mean mean" equal to the overall mean and the variance of that mean estimator proportional to the variance and the number of samples. The actual distribution itself is not going to be normal. If anything, the distribution of the samples (NOT their average) will flesh out the shape of the distribution and you will have a greater chance of seeing an extreme value the more samples are generated.
My hunch is that your routing score is probably an average of some values, and, as such, is the mean of some distribution. If so, as the mean of a distribution, under many conditions its own distribution will tend to the normal after enough samples are generated.

A: Although I don't know anything about circuit design, I'm confused as everyone else why you would expect results to cluster around the average. The CLT has to do not with the shape (as many have correctly pointed out) but the probability of each a data point landing into a random a subset. If the underlying process had a bi-modal distribution, most of the samples would have skinnier peaks.
If your random seeds determine the efficiency of their placement and there is some sort of upper and lower bound on performance then your numbers simply reflect the distribution of such locations.


text:
Q: How to properly bundle an already compiled executable in Android app using CMake? If I want to add a custom executable to an Android app using CMake to compile it, I can use the following:
add_executable(hello_world.so hello_world.cpp)

This will bundle the compiled executable in the /lib/{ANDROID_ABI} folder of the APK.
Despite this being an executable, it NEEDS to be named .so, otherwise it won't be packed. There's probably a way to work around this, but this is not my issue at the moment, as the file is properly packed and executes properly with this setup.
However, I'm failing to bundle the executable in the case that I do not want CMake to compile it for me because I already have it. I tried the following:
add_executable(hello_world.so IMPORTED)

set_target_properties(
        hello_world.so
        PROPERTIES IMPORTED_LOCATION
        ${CMAKE_CURRENT_SOURCE_DIR}/libs/${ANDROID_ABI}/hello_world.so)

However, in this case, it won't be packed in the APK. The variables and paths are correct. In fact I can use a similar set_target_properties (with same variables and path) to successfully include in the final APK a library added with add_library(lib.so SHARED IMPORTED).
What am I doing wrong?


text:
Q: how to clear cache of response header if the content(image) changed in asp.net In my project i have cached using response headers ,
mentioned as below:
  sMemooryStream.WriteTo(context.Response.OutputStream);

   context.Response.Cache.SetExpires(DateTime.Now.AddHours(24));
   context.Response.Cache.SetCacheability(HttpCacheability.Public);
   context.Response.Cache.SetValidUntilExpires(false);

Now the image has been chached sucessfully. But when i change some cached file  content the browser  is loading  the cached version of the file but expected is to get the latest file and not from the browser cahce how do i do it any help would b appriciated

A: You don't.
Once it's cached, it's cached.

And that's exactly why I don't like caching.
What you can do is add a parameter to the url, like
http://www.whatever.com/images/myfile.jpg?no_cache=lastWriteTimeUTC


text:
Q: bandgaps for 2D square lattice with potential of the form V=V(x) + V(y) - what are the general properties? Let us consider Bloch wave function solutions for a particle confined to a 2D square lattice with a potential of the form
$V=V(x) + V(y)$
(that is, one that can be factorized).
In this case we can factorize the Hamiltonian to
$\hat{H} = \hat{H}_x + \hat{H}_y$
and the band spectrum structure (the energy dispersion for states) can be presented as
$E( \vec{q}) = E_x(q_x) + E_y(q_y)$.
One-dimensional dispersion spectrum has gaps between the bands for quasimomentum values of $q_{x} = n \frac{\pi}{a}$,  here $n$ is integer. It means that the energy gaps between the bands are situated at the quasimomentum border values of $q_{x,y} = n \frac{\pi}{a}$.
Am I correct?
Is it a specific case of some general principle regarding the positions of band gaps I need to know about? What can be said about the band gap positions generally?

A: Yes, you are correct, and you don't need to assume factorizability--- the situation for a general square-lattice periodic potential is just the same, the bangaps occur at the edge of the k-space domain defined by lattice periodicity.
The reason is all symmetry: the translation group is broken to lattice translations. This means momentum is not conserved, but violations can only come by adding multiples of the k-space reciprocal lattice. At high electronic energies (assuming a smooth V), you don't notice the potential and the bandgaps go to zero, but where V is important, there are bandgaps only when either the x and y momentum are an integer multiple of ($2\pi$ times) the reciprocal lattice size.
Momentum conservation
On the lattice, a momentum state $|k\rangle$ can mix off the potential with momentum states $|k'\rangle$ only when $|k'\rangle$ has the same eigenvalue for the operators $T_x$ and $T_y$, where
$$T_x= e^{iaP_x}$$
$$T_y = e^{iaP_y}$$
Since $T_x$ and $T_y$ commute with the full Hamiltonian. This means that a momentum state only mixes with other states which acquire the same phase for x and y translations by a, and this justifies Bloch's form for the eigenstates--- they are periodic in x and y up to a phase.
The mixing in general will split the energy of the states, which gives rise to the bands. The bandgaps occur at the exact point where the phase acquired when you translate one of x,y by a becomes equal to (an integer multiple of) $2\pi$.
To see why, it is easiest to start with a tight-binding model. Consider a potential which is a deep square well with very high walls, but periodic in x and y. The bound states are only mixed by tunneling, so that the bands are very narrow, their energy is nearly the same as the bound state energy, and these states are mixed with a phase which varies in a linear way from well to well.
If you give a periodic boundary condition on x which says that $\psi(x+a,y)=e^{i\phi}\psi(x)$ where $\phi$ is close to $2\pi$, but slightly less, then $\psi$ in each well is very close to an energy eigenstate, say the ground state, but with a little twist in the tunneling region. The moment this phase $\phi$ equals $2\pi$, however, there is the requirement that the result must be orthogonal to $0$ phase shift, and this condition was absent just before.
It is impossible to satisfy this condition when $\phi=2\pi$ by using a state which is close to the ground state. You must use the first excited state to continue past this value of k. This gives rise to the gap discontinuity.
The discontinuity appears immediately when you add a periodic potential. It always occurs at the first point where you move from the solution being the lowest energy state with the given lattice phase condition to the next lowest energy state with this phase condition. This happens exactly at the boundary of the k-space of the lattice.
Separable potentials
In this case, there is a zero-counting theorem for arranging the eigenstates. The n-th eigenstate has n zeros. In the Bloch case, the parameter "n" is the number of $2\pi$ twists of the phase as you scan from left to right. The first band has no twists, the second band has 1 twist, etc.
The additivity of the energy means that the 2-d bands are sums of the bands of each motion separately. I don't know what more there is to say.
General theorem
it should be possible to prove that the energy as a function of k is continuous except at the boundary of the lattice k-space region It is obvious physically, but I didn't give a proof.

A: $q_{x} = n \frac{\pi}{a}$ is only correct solution here for a free electron model afaik, but depending of the actual form of your potential and the direction you view the crystal, you can and will get different positions of the gap or not at all one. Also bands can overlap if they get energetically wide enough.
But I'm no expert in this, as calculation of electronic band structures is a highly complex topic with lots of different electron models and approximation methods.
From my phenomenological knowledge you distinguish into halfmetals, semiconductors, isolators, metals. Metals like Cu or Al dont have at all energy gaps when you view their band structure scheme. So i highly doubt there are general properties of positions one could derive. The term "bandgap" mostly relates to materials showing a continuous gap like in Germanium independent of directional view.
This isnt really deeply coverd in most exp. orientated standard solid states books IMO, but search for some theoretical physics solid state scripts on the net if you are deeply intersted. Enough available IMO. Maybe there are some general properties derived by lattice symmetries and potential forms.


text:
Q: Smart local copy of a remote directory Currently I have a bunch of local copies of dev/production websites. Each copy contains the "files" directory, which contains files uploaded by site users. Currently I use rsync to synchronize the directories contents from remote servers (via ssh).
There are some annoyances:

*

*I have to run rsync manually each time when I want fresh files (this could be automated of course, but as I have a lot of website copies, it's not a good idea).

*The rsync execution takes some time.

*Disc space on my laptop is running out.

I think all of this could be solved if there is some kind of a software that can work like a proxy:

*

*When I list files, it requests the file list from the remote server and caches the results for some (configurable) time.

*When I first time request file contents, it retrieves the remote file and saves it locally.

*When I update a file, it only gets updated locally.

*When I save a new file in the "files" directory, it not goes to the remote server.

Of course, the logic of such software should be much more complex, but I hope, my idea is clear: don't waste disk space, download files on demand, no remote changes.
Is there any software that works like that?

A: Map a network drive with NFS or sshfs. Make local copies if you really need a file.

A: I did not mention it in the question, but I needed this for work with Drupal. And now I have found a Drupal-only solution, the Stage File Proxy module.
It does exactly what I need: downloads files from a remote server only when they are requested.


text:
Q: VB.Net Read txt file from current directory How can I get the application current directory and read the file from here?
So the application is in the same folder as the Logger.txt but when I start the app its try to read from the root folder of the application. Logger.txt is in the Logging/MainObject/Logger.txt
I have tryed to add the CurrentDirectory thing, but its gives me error,so I added bad.
 Dim sr As New StreamReader("Logger.txt")
 Dim line As String
 line = sr.ReadToEnd()

A: First of all I think you're confused about the difference between "Current directory" and "application directory". The current directory is piece of information maintained by the process to track what directory you're currently working in, so when you refer to a file without specifying a full path, it knows where to look for that file. The application directory is where the application's EXE file resides on the file system. Since reading from the current directory is a simple matter of referring to the file without providing a full path, I assume what you're trying to do is read a file from the application's directory (where the EXE file resides). Here's code to do that:
Dim ApplicationDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Dim LogfilePath = System.IO.Path.Combine(ApplicationDir, "Logger.txt")
Using sr As New System.IO.StreamReader(LogfilePath)
    sr.ReadToEnd()
End Using

A: Use Application.StartupPath
Dim sr As New StreamReader(Application.StartupPath & "\Logger.txt")
Dim line As String
line = sr.ReadToEnd()


text:
Q: python pandas df merge on part of multiindex I am using Python 3 with pandas.
I have two data frames, with multi-index, one's index is made of columns a,b and the other's is made of column a,b,c for the sake of this post lets call the data frames ab and abc accordingly.
I would like to use a left merge with pandas like so
abc.merge(ab, how="left") and use the index to create the merge. off course I need only a,b in the index because c is not in ab, how can I create this merge without dropping levels and without reset_index?
A simple and effective solution that will use the multi index is preferred.
Thanks

A: You can get same results using join since it is more index-focused. This is an MVE that I used to teach in an introduction to pd.MultiIndex:
first_index = [('A', 'a'), ('A', 'b'), ('B', 'a'), ('B', 'b')]
second_index = [('A', 'a', 'c'), ('A', 'b', 'c'), ('B', 'a', 'c'), ('B', 'b', 'c')]
data = [1, 2, 3, 4]

ab = pd.DataFrame(data=data, index=pd.MultiIndex.from_tuples(first_index,
                                                             names=['A', 'B']),
                  columns=['col_1'])
abc = pd.DataFrame(data=data, index=pd.MultiIndex.from_tuples(second_index,
                                                              names=['A', 'B', 'C']),
                   columns=['col_2'])

ab
A   B   col_1
A   a   1
A   b   2
B   a   3
B   b   4

abc
A   B   C   col_2
A   a   c   1
A   b   c   2
B   a   c   3
B   b   c   4

So till now, this is just simple MultiIndex with names, but with using join on those names:
abc.join(ab, on=['A', 'B'], how='left')
A   B   C   col_2   col_1
A   a   c   1   1
A   b   c   2   2
B   a   c   3   3
B   b   c   4   4

You get the left join without an reset_index.