text:
Q: Wait for an asyncrhonous event raised event in a unit test I am trying to unit test raising of the event SmtpClient.SendCompleted from a unit test, and I am running into an annoying problem with the test continuing to process before the event can actually fire, terminating the application without actually getting to the event.  So, imagine the following code:
[TestClass]
public class emailTest
{
    public bool sentEmail = false;

    [TestMethod]
    public void sendEmail()
    {
        SmtpClient smtp = new SmtpClient("smtpserver");
        smtp.SendCompleted += delegate(Object sender, System.ComponentModel.AsyncCompletedEventArgs e) { sentEmail = true; };
        MailMessage mm = new MailMessage("from@address.com", "to@address.com", "test subject", "test body");
        smtp.SendAsync(mm, "test");
        Assert.IsTrue(sentEmail);
    }
}

This test fails, however, if I manually insert a delay like so...
[TestClass]
public class emailTest
{
    public bool sentEmail = false;

    [TestMethod]
    public void sendEmail()
    {
        SmtpClient smtp = new SmtpClient("smtpserver");
        smtp.SendCompleted += delegate(Object sender, System.ComponentModel.AsyncCompletedEventArgs e) { sentEmail = true; };
        MailMessage mm = new MailMessage("from@address.com", "to@address.com", "test subject", "test body");
        smtp.SendAsync(mm, "test");
        System.Threading.Thread.Sleep(50000); // Manual Delay
        Assert.IsTrue(sentEmail);
    }
}

Then the test passes.
having the method await smtp.SendAsync by wrapping it as a task doesn't seem to actually work because I'm not actually waiting on SendAsync, I'm trying to wait for SendCompleted to finish executing before proceeding with the rest of the test, and I'm not quite sure how to do it.
For time reasons, it's very important that I wait only the minimum amount of time for SendCompleted to finish processing.
I did a whole lot of searching and just can't seem to find anything that addresses this specific issue.
quick edit: in all cases, the email successfully sends, it's only the test that fails.

A: Well, I must admit that the fact that SendCompleted is only fired after SendAsync returns sounds a bit odd... it does make unit testing harder.
But if you want to wait the minimum amount of time, you'll have to introduce a synchronization primitive. AutoResetEvent sounds like a good fit for this scenario.
// Arrange
var are = new AutoResetEvent(false);

var smtp = new SmtpClient("smtpserver");
smtp.SendCompleted += (s, e) => { are.Set(); };
var mm = new MailMessage("from@address.com", "to@address.com", "test subject", "test body");

// Act
smtp.SendAsync(mm, "test");

// Assert
var wasSignaled = are.WaitOne(timeout: TimeSpan.FromSeconds(1));
Assert.True(wasSignaled);


text:
Q: Find the lowest value and output username I have a members table which (could and should have been normalised) but it hold the following information:
**members**
member_id
firstName
lastName
score_1
score_2
score_3
score_4
score_5
score_6
score_7
score_8

What I am trying to do is add up all of those scores and find which one is overall the lowest total and THEN output the members firstName
I was kindly helped yesterday in getting the lowest value overall but I am struggling to find a way to change the end score to a output a string of the members name.
$lowScoreResult = $conn->query("SELECT team_members.team_id, team_members.member_id, members.member_id, members.firstName, members.lastName, SUM(members.score_1) `score_1`, SUM(members.score_2) `score_2`, SUM(members.score_3) `score_3`, SUM(members.score_4) `score_4`, SUM(members.score_5) `score_5`, SUM(members.score_6) `score_6`, SUM(members.score_7) `score_7`, SUM(members.score_8) `score_8`
    FROM team_members
    JOIN members
    ON team_members.member_id = members.member_id
    WHERE members.dashboard_id = $dashboard_id AND team_members.team_id = $teamSelect");

while($row=mysqli_fetch_array($lowScoreResult, MYSQLI_ASSOC)) {
    $low1[] = $row['score_1'];
    $low2[] = $row['score_2'];
    $low3[] = $row['score_3'];
    $low4[] = $row['score_4'];
    $low5[] = $row['score_5'];
    $low6[] = $row['score_6'];
    $low7[] = $row['score_7'];
    $low8[] = $row['score_8'];
}

$low_score_1 = min($low1);
$low_score_2 = min($low2);
$low_score_3 = min($low3);
$low_score_4 = min($low4);
$low_score_5 = min($low5);
$low_score_6 = min($low6);
$low_score_7 = min($low7);
$low_score_8 = min($low8);

// lowest of the entire set
$t = array($low_score_1,$low_score_2,$low_score_3,$low_score_4,$low_score_5,$low_score_6,$low_score_7,$low_score_8);

so the current output form that would be a numeric value which is an over score from a particular column, i,e score_1, score_2 etc as these columns are scores for departments so score_1 is for department 1 score_2 for department 2 etc... I need a way to say like overall value that is shown is from department 1 if it from there...

A: I havent tried it on my console but it should give you some idea about caluculatinf the lowest score with fields name details in query itself
    select team_members.team_id, team_members.member_id, members.member_id, members.firstName, members.lastName,
    min(score_1),min(score_2),min(score_3),min(score_4),min(score_5),min(score_6),min(score_7),min(score_8)
    from ( select team_members.team_id, team_members.member_id, members.member_id, members.firstName, members.lastName,
            SUM(members.score_1) `score_1`, SUM(members.score_2) `score_2`, SUM(members.score_3) `score_3`, SUM(members.score_4) `score_4`, SUM(members.score_5) `score_5`, SUM(members.score_6) `score_6`, SUM(members.score_7) `score_7`, SUM(members.score_8) `score_8`from
            team_members
            JOIN members
            ON team_members.member_id = members.member_id
            WHERE members.dashboard_id = $dashboard_id AND team_members.team_id = $teamSelect
     ) as t;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Alignment Issue in Android How do I solve these icon, divider and listview alignment issue. It comes perfect for some screens but for other screens, it eases out. Below is the code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:padding="8dp">

    <LinearLayout
        android:id="@+id/Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="8dip">

        <TextView
            android:id="@+id/list_item_entry_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="marquee"
            android:textColor="#666666"
            android:fadingEdge="horizontal"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceLarge"
             />

        <TextView
            android:id="@+id/list_item_entry_summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#666666"
            android:layout_alignLeft="@id/list_item_entry_title"
            android:layout_below="@id/list_item_entry_title"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceSmall"
            />
    </LinearLayout>

    <ImageView
            android:id="@+id/divider"
            android:layout_width="2dip"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="70dip"
            android:layout_centerInParent="true"
            android:gravity="center_horizontal|center_vertical"
            android:paddingBottom="15dip"
            android:paddingTop="15dip"
            android:background="#e7ebee"
            />

    <ImageView
        android:id="@+id/list_item_entry_drawable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:paddingRight="10dip"
        android:src="@drawable/icon" />

</RelativeLayout>

A: Add android:layout_toLeftOf="@+id/divider" to the LinearLayout with the id of Text
<LinearLayout
    android:id="@+id/Text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@+id/divider"
    android:orientation="vertical"
    android:paddingLeft="8dip" >

A: Copy and Paste Following Code:
It will work for any Screen

<LinearLayout
    android:id="@+id/Text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_toLeftOf="@+id/divider"
    android:orientation="vertical"
    android:paddingLeft="8dip" >

    <TextView
        android:id="@+id/list_item_entry_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:singleLine="true"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#666666" />

    <TextView
        android:id="@+id/list_item_entry_summary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/list_item_entry_title"
        android:layout_below="@id/list_item_entry_title"
        android:singleLine="true"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="#666666" />
</LinearLayout>

<ImageView
    android:id="@+id/list_item_entry_drawable"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:paddingRight="10dip"
    android:src="@drawable/icon" />

<ImageView
    android:id="@+id/divider"
    android:layout_width="2dip"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/list_item_entry_drawable"
    android:layout_toLeftOf="@+id/list_item_entry_drawable"
    android:background="#e7ebee"
    android:layout_marginRight="3dp"
    android:layout_marginLeft="3dp"
    android:gravity="center_horizontal|center_vertical"
    android:paddingBottom="15dip"
    android:paddingTop="15dip" />


text:
Q: ASP .NET MVC application user in database I want create database using entity framework (code first). And I want change Application User ID type (string->int). How I can do it?
Second question: How I can delete some default columns in table User (example Phone number).

A: To change the primary key of the user entity, you should follow this turorial: http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity
To remove unecesarry data from user class, you can create your own IdentityUser implementation. Basically you shoud imlement Interface IUser with your own class.
See the hierarhy here: https://msdn.microsoft.com/en-us/library/dn613256(v=vs.108).aspx, and here: https://msdn.microsoft.com/en-us/library/dn613291(v=vs.108).aspx


text:
Q: EncryptByPassphrase in PHP query I'm here for your help.
I'm using framework Zend with SQL Server 2008. I want to know if it's possible to use EncryptByPassPhrase in query with php like this.
$db->query('INSERT INTO TABLE_861_FLUX_RH_DOSSIER_ENCOURS
                (POSITION_EMPLOI_POSTE_RCE)
        VALUES(EncryptByPassPhrase(N'.$pass.', N'.$this->_getParam ( 'position_emploi_poste',null ).', NULL))');

I have an error :

Message: [Microsoft][SQL Server Native Client 10.0][SQL Server]Nom de colonne non valide : 'NDRH'. It's in french. In English : Column name is not valid.

PS: NDRH is my password I gave to encrypt the column.
Thanks for your help.

A: It seems to be single quote problem, try below code,

    $param = $this->_getParam ('position_emploi_poste', null);
    $db->query('INSERT INTO TABLE_861_FLUX_RH_DOSSIER_ENCOURS
            (POSITION_EMPLOI_POSTE_RCE)
    VALUES(EncryptByPassPhrase(N'.$pass.', N'.$param.', NULL))');


text:
Q: How to open a text box when I click on the button? I have created a button which when clicked should open a text box or even a dialogue box. Once the user inputs the data it should save  and display the data there on the screen without reloading it.

A: Dont know about exact question but code something similar to you requirement.
<button type="button" id="btn1" >Button</button>

    $('#btn1').click(function(){
 $('#txtBox').show();
});
$("#txtBox").focusout(function(){
    $('#output').html($("#txtBox").val());
});

Fiddle

A: $('#btn1').click(function(){
 $('#txtBox').show();
});
$("#txtBox").focusout(function(){
$('#output').text($("#txtBox").val());
 $('#txtBox').hide();   //Use this line if you want to hide the textbox after showing the value
});

<button type="button" id="btn1" >Button</button>
<input type="text" id="txtBox">

If you want to clear the textbox value every time then you can use the below code
$('#btn1').click(function(){
 $('#txtBox').show();
});
$("#txtBox").focusout(function(){
$('#output').text($("#txtBox").val());
 $('#txtBox').hide();   //Use this line if you want to hide the textbox after showing the value
$('#txtBox').val("");
});


text:
Q: It seems that Thread.start() doesn't call the run method private void showLocation(final Location location){
    new Thread(new Runnable(){
        HttpURLConnection connection;
        @Override
        public void run() {
            try{
                Toast.makeText(MainActivity.this, "here", Toast.LENGTH_SHORT).show();
                StringBuilder url=new StringBuilder();
                url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng=");
                url.append(location.getLatitude());
                url.append(",");
                url.append(location.getLongitude());
                url.append("&sensor=false");
                URL Url=new URL(url.toString());
                connection=(HttpURLConnection)Url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);
                InputStream in=connection.getInputStream();
                BufferedReader reader=new BufferedReader(new InputStreamReader(in));
                StringBuilder response=new StringBuilder();
                String line;
                while((line=reader.readLine())!=null){
                    response.append(line);
                }
                JSONObject jsonObject=new JSONObject(response.toString());
                JSONArray resultArray=jsonObject.getJSONArray("results");
                if(resultArray.length()>0){
                    JSONObject subObject=resultArray.getJSONObject(0);
                    String address=subObject.getString("formatted_address");
                    Toast.makeText(MainActivity.this, address, Toast.LENGTH_SHORT).show();
                    Message message=new Message();
                    message.what=SHOW_LOCATION;
                    message.obj=address;
                    handler.sendMessage(message);
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                if(connection!=null){
                    connection.disconnect();
                    connection=null;
                }
            }
        }
    }).start();

}

I use this method to show detail information about position via using Goole map Api.
But it seems that the run() is never called due to the App's activity.
I have searched the problem but didn't fix it.
I'm new to andoird and I can't find the bug. Need help.

A: Check your log. My guess is that there is an error because you are trying to create a Toast from a thread. For the Toast command, and all other calls that affects the ui, you should wrap it in runOnUiThread().

A: You can not update UI from a non UI thread.You need to remove your Toast call.
try this..
private void showLocation(final Location location){
    new Thread(new Runnable(){
        HttpURLConnection connection;
        @Override
        public void run() {
            try{
                StringBuilder url=new StringBuilder();
                url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng=");
                url.append(location.getLatitude());
                url.append(",");
                url.append(location.getLongitude());
                url.append("&sensor=false");
                URL Url=new URL(url.toString());
                connection=(HttpURLConnection)Url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);
                InputStream in=connection.getInputStream();
                BufferedReader reader=new BufferedReader(new InputStreamReader(in));
                StringBuilder response=new StringBuilder();
                String line;
                while((line=reader.readLine())!=null){
                    response.append(line);
                }
                JSONObject jsonObject=new JSONObject(response.toString());
                JSONArray resultArray=jsonObject.getJSONArray("results");
                if(resultArray.length()>0){
                    JSONObject subObject=resultArray.getJSONObject(0);
                    String address=subObject.getString("formatted_address");
                    Log.e("address",address);
//                    Toast.makeText(MainActivity.this, address, Toast.LENGTH_SHORT).show();
                    Message message=new Message();
                    message.what=SHOW_LOCATION;
                    message.obj=address;
                    handler.sendMessage(message);
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                if(connection!=null){
                    connection.disconnect();
                    connection=null;
                }
            }
        }
    }).start();

}

and see the logs.. notice the tag "address".


text:
Q: Unity AdBannerView The Unity ADBannerView example code is:
private ADBannerView banner = null;
void Start()
{
    banner = new ADBannerView(ADBannerView.Type.Banner, ADBannerView.Layout.Top);
    ADBannerView.onBannerWasClicked += OnBannerClicked;
    ADBannerView.onBannerWasLoaded  += OnBannerLoaded;
}
void OnBannerClicked()
{
    Debug.Log("Clicked!\n");
}
void OnBannerLoaded()
{
    Debug.Log("Loaded!\n");
    banner.visible = true;
}

My question is does the ad banner automatically go away after a set length or do I have to manually do something to get it only to display for a short amount of time, because that seems a little risky trying to interfere with an ad.

A: It's a simple wrapper around the ADBannerView class in iAd.framework, so it will behave just like that.
iAd's ADBannerView will stay visible as long as you set it to be (and as long as there is ad inventory).

A: I think AD Banner display can be hidden.
Simply use:
banner.Hide();

wherever you want.
Or you can use IEnumerator to delay the time of showing this.


text:
Q: When/how should a new user flag their own question as not useful? I recently posted a question at https://dba.stackexchange.com/questions/107255/postgresql-hot-standby-changing-password-out-from-under-me. As you can see in the latest edit, I still don't know the cause of my error or what I did to fix it. Based on one of the comments on the question, the situation I thought I had should be impossible.
I don't see any way to salvage a clear and answerable question out of the situation. Is a vote to delete correct? A vote to close? Since I don't have the reputation to vote to close, how do I get the attention of someone who can?

A: Unless your question has multiple answers or a single up-voted answer you can just delete it. So if it is truly irredeemable, then just click on that "delete" link.
I know it's says "vote to delete", but your vote is binding and the question will be deleted immediately.


text:
Q: CsvHelper: An element with the same key '' already exists in the ExpandoObject With code similar to, I receive the exception:

An element with the same key '' already exists in the ExpandoObject

using (var reader = new StreamReader("SampleData.csv"))
using (var csv = new CsvReader(reader))
{
    var records = csv.GetRecords<dynamic>();
}

A: This is simply due to CsvHelper is using the column headers by default as the name of the dynamic object's properties:
It is important to ensure csvReaderConfig.HasHeaderRecord = false; is set or to use another technique such as mapping to a class.
var csvReaderConfig = new Configuration();

csvReaderConfig.HasHeaderRecord = false;

using (var reader = new StreamReader("SampleData.csv"))
using (var csv = new CsvReader(reader, csvReaderConfig))
{
    var records = csv.GetRecords<dynamic>();
}


text:
Q: How to copy MyDocuments files into newly created folder? Ok, so I have a perfectly running script... minus the fact that it does not truly copy the files/folders from my MyDocuments into my new folder. I have rack my brain over and over through this and have tried a few different commands to see if it would work. It copies over the Documents folder with Mymusic folder inside but not the folder and file I have selectively placed in there. Below is the script I currently have setup...
Option Explicit

Dim objWShell, userName, objFso, Wshshell, strDocuments, strLocation

Set objFso = WScript.CreateObject("Scripting.FileSystemObject")

Set objWShell = WScript.CreateObject("WScript.Shell")

Set WshShell = Wscript.CreateObject("WScript.Shell")

userName = objWShell.expandEnvironmentStrings("%userName%")

If Not objFso.FolderExists("C:\" + "Backups\") Then
  objFso.CreateFolder ("C:\" + "Backups\")
End If

If Not objFso.FolderExists("C:\Backups\" + userName +"\") Then
  objFso.CreateFolder ("C:\Backups\" + userName + "\")
End If

strDocuments = ("C:\Users\" + userName +"\Documents")

strLocation = ("C:\Backups\" + userName + "\")

If objFso.FolderExists (strDocuments) Then
  objFso.CopyFolder strDocuments, strLocation, True
End If

A: I believe the answer to my problem is adding a "\" at the end of the referenced folders as well as the CopyFolder command. As I am away from my scripting computer at this time can anyone confirm my findings?
Option Explicit

Dim objWShell, userName, objFso, Wshshell, strDocuments, strLocation

Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Set objWShell = WScript.CreateObject("WScript.Shell")
Set WshShell = Wscript.CreateObject("WScript.Shell")

userName = objWShell.expandEnvironmentStrings("%userName%")

If Not objFso.FolderExists("C:\" + "Backups" + "\") Then
  objFso.CreateFolder ("C:\" + "Backups" + "\")
End If

If Not objFso.FolderExists("C:\Backups\" + userName +"\") Then
  objFso.CreateFolder ("C:\Backups\" + userName + "\")
End If

strDocuments = ("C:\Users\" + userName + "\" + "Documents"+ "\")
strLocation = ("C:\Backups\" + userName + "\")

If objFso.FolderExists (strDocuments) Then
  objFso.CopyFolder strDocuments, strLocation, True
End If


text:
Q: How can I define a custom loss function with three inputs in tensorflow? I want make a model consists of two modules, a cluster-level prediction module and a global-level prediction module. All city regions are partitioned into several clusters, and the cluster-level prediction module employs independent recurrent neural networks for the demand prediction of each cluster. The global-level prediction module uses a single recurrent neural network to simultaneously predict the taxi demand of all regions.
My mixed loss function is designed to train model, consisting of three parts:
Loss = WMSE(Dc, D) + WMSE(Dg, D) + WMSE(Dc, Dg)

WMSE = weighted mean square error
Dc: Dc is the predicted taxi demand by cluster-level prediction module.
Dg: Dg is the predicted value from the global-level prediction module.
D: D is regarded as the final prediction.

How can I define a custom loss function with three inputs in tensorflow?


text:
Q: Spring MVC and annotated controllers issue: I'm having a strange issue with annotated controllers and Spring MVC. I was trying to use Annotated controllers for the sample MVC application that Spring ships with its documentation. I used 2.5 version.
When I specify @RequestMapping at type level, I get "HTTP ERROR: 500
No adapter for handler [Controller class name]: Does your handler implement a supported interface like Controller?
If I include it in the method level, it works fine with out an issue. Adding or removing the default handle adapters to context files made no difference:

Finally, I resorted to having @RequestMapping at controller level, as well as one at the Method level, and it worked. Anyone know what could be the issue?
Here is the sample code:
This did not work:
@Controller
@RequestMapping("/*")
public class InventoryController {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private ProductManager productManager;

    public ModelAndView inventoryHandler() {
        String now = (new java.util.Date()).toString();
        logger.info("returning hello view with " + now);
        Map<String, Object> myModel = new HashMap<String, Object>();
        myModel.put("now", now);
        myModel.put("products", this.productManager.getProducts());
        return new ModelAndView("hello", "model", myModel);
    }
}

This worked:
@Controller

public class InventoryController {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private ProductManager productManager;

    @RequestMapping("/hello.htm")
    public ModelAndView inventoryHandler() {
        String now = (new java.util.Date()).toString();
        logger.info("returning hello view with " + now);
        Map<String, Object> myModel = new HashMap<String, Object>();
        myModel.put("now", now);
        myModel.put("products", this.productManager.getProducts());
        return new ModelAndView("hello", "model", myModel);
    }
}

This also worked:
@Controller
@RequestMapping("/*")
public class InventoryController {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private ProductManager productManager;

    @RequestMapping( method = RequestMethod.GET, value = "/hello.htm" )
    public ModelAndView inventoryHandler() {
        String now = (new java.util.Date()).toString();
        logger.info("returning hello view with " + now);
        Map<String, Object> myModel = new HashMap<String, Object>();
        myModel.put("now", now);
        myModel.put("products", this.productManager.getProducts());
        return new ModelAndView("hello", "model", myModel);
    }
}

Any ideas, what's happening here? I did a lot of search and no solution. I also tried with 2.5.6, and the issue was similar.

A: You need to put @RequestMapping on the method because putting it on the class isn't enough information - Spring needs to know which method to call to handle the request.
If your class only has one method, then understandably you might think that it would pick that, but it doesn't.
Consider that one of the benefits of annotated controllers is that you can have as many @RequestMapping-annotated methods in your class as you want.

A: You don't need to use @RequestMapping on the class. It is just a convenience. You do need the method level @RequestMapping annotations.
Given this:
@Controller
public class InventoryController {
...
@RequestMapping("/inventory/create/{id}")
public void create(...){}

@RequestMapping("/inventory/delete/{id}")
public void delete(...){}
...

You can factor out the inventory part of the URI.
@Controller
@RequestMapping("/inventory")
public class InventoryController {
...
@RequestMapping("create/{id}")
public void create(...){}

@RequestMapping("delete/{id}")
public void delete(...){}
...

A: This is beacuse the first configuration doesn't tell wich method of the class invoke.


text:
Q: SQL left join exclude non matching records I'm working on this query (running on MySQL 5.6):
SELECT
    veicoli_contratti.targa AS targa,
    veicoli_contratti.canone_noleggio AS canone,
    anag_convenzionati.nome AS convenzionato,
    SUM(noleggio_veicoli.fatt_prezzo_totale_noleggio) AS noleggi_incasso,
    noleggio_veicoli.modalita_noleggio,
    COUNT(DISTINCT noleggio_veicoli.id) AS noleggi
FROM
    veicoli_contratti
        LEFT JOIN
    noleggio_veicoli ON veicoli_contratti.id = noleggio_veicoli.id_veicolo
        INNER JOIN
    anag_convenzionati ON veicoli_contratti.id_convenzionato = anag_convenzionati.id
WHERE
        (veicoli_contratti.data_cancellazione IS NULL)
        AND (veicoli_contratti.targa <> '')
        AND (noleggio_veicoli.data_cancellazione IS NULL)
        AND (anag_convenzionati.data_cancellazione IS NULL)
        AND (YEAR(noleggio_veicoli.rientro_data) = 2020)
        AND (MONTH(noleggio_veicoli.rientro_data) = 10)
        AND ((noleggio_veicoli.stato_noleggio = 'C')
              OR (noleggio_veicoli.stato_noleggio = 'F')
            )
        AND ((noleggio_veicoli.modalita_noleggio = 'S')
             OR (noleggio_veicoli.modalita_noleggio = 'OPO')
             OR (noleggio_veicoli.modalita_noleggio = 'M')
            )
        AND (veicoli_contratti.stato = 'OPERATIVA')
GROUP BY anag_convenzionati.id , veicoli_contratti.id , noleggio_veicoli.modalita_noleggio
ORDER BY convenzionato , noleggi DESC , canone DESC , noleggi_incasso DESC ;

I thought LEFT JOIN clause will produce a record even if there's not a matching record in table noleggio_veicoli but this doesn't happen.
The result include just records where a match is found between veicoli_contratti and noleggio_veicoli.
I tried also adding OR noleggio_veicoli.id IS NULL in WHERE clause but it's not the solution.
How can I fix this?
I created an SQL fiddle to try this here

A: Your understand is correct.  However, the where clause is "undoing" the LEFT JOIN.  Why?
You have conditions such as this:
   AND ((noleggio_veicoli.stato_noleggio = 'C') OR (noleggio_veicoli.stato_noleggio = 'F'))

Well, NULL fails those conditions so non-matches are filtered out.  This condition (along with other conditions) should be included in the ON clause.  For this one, it looks like:
   AND noleggio_veicoli.stato_noleggio IN ('C', 'F')


text:
Q: How to make custom scrollbar in tkinter python I wanted to create a custom scrollbar without arrows in tkinter,  Python 3.7, Windows 7.
Below is some example:

A: tkinter has standard module tkinter.ttk with widgets which can use themes and maybe one of themes has scrollbars like this.
tkinter can also use external modules which can add themes - like ttkthemes

Minimal working example
It displays buttons with all themes and with scrollbar (on the right) and you can see how scrollbar looks in other themes.
Screenshots from Linux Mint 21. I don't know if Windows has the same themes.
import tkinter as tk
import tkinter.ttk as ttk
from ttkthemes import ThemedStyle

def changer_theme(name):
    print('theme:', name)
    #root.set_theme(name)        # with ThemedTk
    style.theme_use(name)   # with Tk and ThemedStyle

# --- main ---

root = tk.Tk()

style = ThemedStyle()   # with Tk and ThemedStyle

frame = ttk.Frame(root)
frame.pack(side='left')

for item in sorted(style.get_themes()): # with Tk and ThemedStyle
    b = ttk.Button(frame, text=item, command=lambda name=item: changer_theme(name))
    b.pack(fill='x')

scroll = ttk.Scrollbar(root)
scroll.pack(side='right', fill='y')

root.mainloop()

Old question with code using classes:
How to change whole app's theme when used within Class, Tkinter, ttkThemes, ThemedTk Python
Documentation for tcl/tk: List of ttk Themes. It shows other widgets.

Adapta:

Breeze:

Scidblue / Scidgreen / etc.

Yaru:


text:
Q: Plugging in values for limits I know limits exist when we compute the limit from the right hand side and limit from the left hand side & they both equal but how can we find the limit by using only the limit laws? Is that possible?
Thank you.

A: Computation of a limit ${\displaystyle \lim_{x\to a}}f(x)$ is entirely dependent on the function $f(x)$ and its properties. There is no catch-all method for quickly determining a limit. You must have some kind of understanding of how $f$ behaves on its domain. You come to this understanding from your knowledge of algebra, the real numbers, and functions on the real numbers. The limit laws follow from the properties of real numbers, but they're not of any use in actually computing the limit, aside from potentially simplifying the problem (e.g. factoring out constants, etc.).


text:
Q: How to define React component with conditional props interface? i need to define "Field" component that renders textarea or input depends on prop multiline
I trying to do this like that:
import React from 'react';

type Props<T extends boolean = boolean> = { multiline: T } & T extends true
    ? React.HTMLProps<HTMLTextAreaElement>
    : React.HTMLProps<HTMLInputElement>

export const Field: React.FC<Props> = ({ multiline, ...props }) => { // error here
    const Element = multiline ? 'textarea' : 'input';

    return <Element {...props} onInput={e => {}} />; // error here
}

// usage

const result = (
    <Field onChange={e => console.log(e.target.value)} /> // error here
);

But typescript provide several errors like:
1 Property 'multiline' does not exist on type 'HTMLProps<HTMLInputElement> & { children?: ReactNode; }'.(2339)

2 [large error, more in playground]

3 Property 'value' does not exist on type 'EventTarget'.(2339)

Playground here
How can i define such component?

A: I believe you should be using an intersection of the 2 types, so it can be either/or. So for Props type use the '&' operator to cover both input types, then in the onChange event use it again for each input type event (since it can be either). Something like this:
import React from 'react';

type Props<T extends boolean = boolean> = { multiline?: T } &
    React.HTMLProps<HTMLTextAreaElement> &
    React.HTMLProps<HTMLInputElement>;

export const Field: React.FC<Props> = ({ multiline, ...props }) => {
    const Element = multiline ? 'textarea' : 'input';

    return <Element {...props} />;
}

// usage

const result = (
    <Field onChange={(e: React.ChangeEvent<HTMLInputElement> & React.ChangeEvent<HTMLTextAreaElement>) => (
        console.log(e.target.value)
    )} />
);

A: Problem: No T in Field
You have defined a generic type Props that depends on T but your component is not generic.  It always takes Props<boolean> which resolves to the HTMLInputElement props because boolean extends true is false.  The reason {multiline: boolean} is getting lost is because you need parentheses around the rest of your type.
React.HTMLProps
When using your React.HTMLProps typings I didn't get errors when assigning mismatched properties like type="number" to a textarea or rows={5} to an input.  The more restrictive types are JSX.IntrinsicElements['textarea'] and JSX.IntrinsicElements['input'] (which resolve to a type like React.DetailedHTMLProps<React.TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement>).  If you want strict enforcement then use these!  This also makes the e value in the onChange callback get the correct type based on the element.
Implementation
When using a generic component with restrictive types, we now get an error in the implementation on return <Element {...props} />;  I thought that breaking it into two (return multiline ? <textarea {...props} /> : <input {...props}/>;) would help but we still get errors.  Conditionals are rough.  You can use as assertions to fix things.  I'm generally ok with making assertions in the implementation of a function when the usage of it stays strictly typed.  So you can do this:
type Props<T extends boolean = boolean> = { multiline: T } & (T extends true
    ? JSX.IntrinsicElements['textarea']
    : JSX.IntrinsicElements['input'])

export const Field = <T extends boolean>({ multiline, ...props }: Props<T>) => {
    const Element = multiline ? 'textarea' : 'input';

    return <Element {...props as any} />;
}

Playground #1
Union Type
We can avoid having to make assertions by typing Props as a union of two situations.  This allows us to check which type in the union we have by looking at props.multiline.  This gets messy though because you cannot desctructure until after you have discriminated the union, but we don't want to pass multiline through to the DOM.
This code passes all type checks, but it needs additional work to prevent passing multiline through to the DOM.
type Props = (
    { multiline: true } & JSX.IntrinsicElements['textarea'] |
    { multiline: false } & JSX.IntrinsicElements['input']
);

export const Field = ({ ...props }: Props) => {
    return props.multiline ? <textarea {...props} /> : <input {...props}/>
}

Playground #2
Usage
Either way the usage is very strongly typed!  Our onChange callback gets the correct type like React.ChangeEvent<HTMLTextAreaElement> and we get error if passing textarea props when multiline={false} or vice-versa.
<Field
    onChange={e => console.log(e.target.value)} // e: React.ChangeEvent<HTMLTextAreaElement>
    multiline={true}
    rows={5} // ok
    type="number" // error
/>
<Field
    onChange={e => console.log(e.target.value)} // e: React.ChangeEvent<HTMLInputElement>
    multiline={false}
    type="number" // ok
    rows={5} // error
/>


text:
Q: File transfer from dos 6 system On my new job we have an old dos machine running dos 6.22.
This machine is necessary for data acquisition for scientific experiments. So it needs to continue to work as it is.
Since data transfer is a real pain I got the task to find a solution to transfer files from the dos machine to a Linux server, preferably automatic.
I'm an engineer and not a computer scientist, I know a few things but I've never had anything to do with dos.
I know that a few years ago the file transfer was done by scpdos, this eventually stopped working. With scpdos you can connect and it even asks for the remote password, but then "unsupported remote protocol" is shown.
Well, I have no idea and wanted to ask you for help.
Optimally I can run a script in the mail lunix server, that copies all files in a specific directory on the dos machine and deletes them afterwards. This every x min.
I've got a raspberry pi, wo may be the pi could act as coping device like: get data from dos, send to server, delete data on dos... Repeat
Hopefully you can help. Thanks.

A: DOS 6.22 was not designed to be used in a networked environment. Since those days, people have written all sorts of creative tools to make DOS speak on a network. The best way to copy files between Linux and DOS is going to be NFS, SSH or FTP.
NFS
There is a NFS client for DOS called XFS:
http://omolini.steptail.com/mirror/winsite/winsite-mar96-3/info/pc/win3/winsock/xfs191.zip/index.html
The way this works is that you would set up an NFS export on the Linux side and then mount that NFS share with the XFS client in DOS as described here:
http://freedos.sourceforge.net/wiki/index.php/NFS
Then you could script actions on the DOS side to push files to the NFS server in Linux land.
FTP
If you need to work the other way around then you need an FTP server for DOS like this:
https://www.brutman.com/mTCP/mTCP_FTPSrv.html
Then you could make the FTP home directory point to the location of the files you need. That way you could script the collection of the files from the FTP server using the FTP client on the Linux side.
SSH\SCP
You could use SSH\SCP as well but I only see a client for DOS:
http://sshdos.sourceforge.net/
This means you would have to make the batch script connect, and upload the results to the Linux SSH server.


text:
Q: Problems with Submenu after resizing Jquery for responsive site (jsfiddle provided) I have a problem with a submenu that I have created using both Jquery and CSS.
I have created the following fiddle in order to show you what's wrong with this: https://jsfiddle.net/kurt111078/c5xhLrho/8/

*

*1st step: After the page is loaded, the submenu behaves correctly: when passing the mouse over the menu with submenu, the submenu is shown. Once you move the mouse out, the submenu disappears. Until here everything looks like correct.

*2nd step: When I resize the page to see how this behaves in smaller screens, also in this case everything works fine.
The problem arises when I resize again the screen to a larger one.
I was expecting the menu to behave like in step 1 but even if the screen is larger, the submenu is now shown only if I click on the menu with submenu, which is an incorrect behavior because with larger screens the the submenu needs to be shown when I pass the mouse over the parent menu.
Could you please help me understand what's wrong with my code?
Really strange since I have already added a resize handler:
        $(window).resize(resizeMenu);
     resizeMenu();
    setupMenuButton();
    setupSubMenu();
});

Thanks a lot

A: Problem
Following two instructions are referencing the same element and clashing the display css with each other.
CSS
.mynavbar li:hover > ul { display: block;}

JavaScript
function setupSubMenu() { $(".mysubmenu").toggle(); }

Solution
So basically in your scenario if you want mouse hover effect on larger screen and click feature on smaller screens, you can achieve in this way:
function resizeMenu() {
    if ($(this).width() >= 500) {
        //.....
        //.....
        $(".munuwithsubmenu").hover(
           function(){ $(".mysubmenu").css({'display': 'block'}) },
           function(){ $(".mysubmenu").css({'display': 'none'}) }
         );
    }
    else if ($(this).width() < 500) {
        //.....
        //.....
       $(".munuwithsubmenu").off( "mouseenter mouseleave" );
    }
}

The trick is bind/unbind the mouseenter-mouseleave events.


text:
Q: What tools to use as api for building a generic performance profiler for .net applications? I know a similar question has already been asked here What features should a C#/.NET profiler have? but this thread is not only about the wishlist but also about how to go about implementing that wishlist.
So let me ask you this just once more. I am in the process of building a generic performance profiler. I know I can take in a dll as input and take the usual Stopwatch approach to profile the response times of methods in that dll. But this is very basic stuff. I am willing to use third party api(or do some code on my own too) to extract whatever useful information I can lay my hands on from that dll. I want to know everything that makes it slow. I want to know about it's memory leaks. Anything at all that would help me find bottlenecks of the application. I'd want similar approach to find expensive db operations. But all this, under one application.
So what approach do you suggest? Which tools can I bring under my umbrella so that I can use them in my project?
I want to make a 'single' application that will take generic inputs like dlls, can also take input as source code tree(solution, projects, .cs files) and emit out results in the form of response times, identifying bottlenecks, memory leaks, etc.

A:
Anything at all that would help me find bottlenecks of the
  application.

Be careful of the universal profiling assumption that measurements unerringly lead to where the bottlenecks are, because some of them can be found that way, but only some.
Then the remaining bottlenecks sit there consuming time needlessly, but the developer is oblivious to them because profiler measurements did not isolate them.
A simple example could be some sort of dictionary lookup that appears to be optimal, except that the words being looked up are highly non-random. If certain words are looked up much more frequently, that represents an opportunity for optimization, but to detect that you need to know something about the data. Measuring profilers don't look at the program's data.
A more extreme example is any sort of interpreter, whose data is the "instruction set" for another language. The bottlenecks could easily be in that other language, but since it is data the measuring profiler would not see them.
What does see problems of this sort are not measurements but a small number of samples of the program's state, where the developer can fully examine and characterize the content of each sample (call stack and data). This leads to a much better understanding of how and why the program is spending its time than putting measurements on methods or browsing a call graph.


text:
Q: Make pragma with string from array at compile time #pragma code_seg(push, ".text$EBC000")

code_seg prama changes function order in .text section. I want to have a general macro like CHANGE_FUNCTION_ORDER that uses __COUNTER__ macro to everytime get different string that will be used for code_seg pragma.
const char *array = {".text$EBC002", ".text$EBC000", ".text$EBC003"};
#define CHANGE_FUNCTION_ORDER __pragma(code_seg(push, ????)) // how do I tell compiler to use string at __ COUNTER__ index from array

The idea is from http://lallouslab.net/2018/03/26/shuffling-function-addresses-in-c-c-with-msvc/

A: Here is a solution using Boost.Preprocessor:
#include <boost/preprocessor/tuple/elem.hpp>

#define CODE_SEGMENTS (".text$EBC002", ".text$EBC000", ".text$EBC003")
#define CHANGE_FUNCTION_ORDER __pragma(code_seg(push, BOOST_PP_TUPLE_ELEM(__COUNTER__, CODE_SEGMENTS))

See it live on Coliru


text:
Q: apex:actionSupport 'action' was not fired, when using onchange attribute in apex:selectList Actionsupport action method is not fired when I use onchagen attribute in apex:selectlist. If I remove the onchange attribute from the selectlist then actionsupport is working as expected.
<apex:selectList value="{!selectedRectype}" size="1" onchange="reloadPage(this);">
     <apex:selectOptions value="{!RecType}"/>
     <apex:actionSupport action="{!loadElements}" event="onchange" status="oppRecType"/>
</apex:selectList>

Why this behaviour is happening..?

A: You can't use both onchange an an actionSupport for onchange at the same time. This is true for all events; you can use either the attribute or actionSupport, but not both on the same element.
Depending on your specific case, it seems appropriate that you'd probably want to call reloadPage after the actionSupport finishes:
<apex:actionSupport action="{!loadElements}"
                    event="onchange"
                    status="oppRecType"
                    oncomplete="reloadPage(this)"/>

However, this may not behave correctly for this, so you'll want to try it out.
The alternative is to use an apex:actionFunction from your reloadPage script:
<apex:actionFunction name="loadTheElements"
    action="{!loadElements}" reRender="someTarget"
    status="oppRecType" />

function reloadPage(el) {
  loadTheElements();
  // Rest of code here
}

A: Since you are using actionSupport with event="onchange" thats which is wrapped inside apex:selectList thats why do not use onchange of apex:selectList.
Rather use other event to reload the page.
Would say, that better to rerender attribute of the actionSupport for page or section of the page rendering.
<apex:selectList value="{!selectedRectype}" size="1">
     <apex:selectOptions value="{!RecType}"/>
     <apex:actionSupport action="{!loadElements}" event="onchange" status="oppRecType" reRender="form1"/>
</apex:selectList>


text: Q: How to pass record from gridview control to pdf viewer Devexpress I am trying to create Devexpress Winform Outlook inspired app 2019 Demo Products page. The product page on the Devexpress winform Demo contains gridview controls with rows of images and other texts. When l click on any row it shows pdf that appears on the pdf viewer. I want to know how to create this pdf that contains data from the database. thanks in advance for any assistance provided


text:
Q: WPF/C# Cancelling BackgroundWorker call outside DoWork I have a BackgroundWorker DoWork function as follows
    private void WorkerGetFeedData(object sender, DoWorkEventArgs args)
    {
            _feed.FetchUserData(_userNameCollection);
    }

The FetchUserData is a function in another class(whose object is _feed) in another project in the same solution. The data fetch process takes considerable time and I'd like for the user to be able to cancel the process if necessary. How do I convey a cancel operation from the user to a function call elsewhere and just stop it?

A: You can use BackgroundWorker.CancelAsync method. Here's more info with example: MSDN
To be more exact to your problem, pass the worker to FetchUserData. It is the sender parameter. Then in the FetchUserData function you can check if the flag BackgroundWorker.CancellationPending is set and finish your method.
void FetchUserData(IEnumerable<Users> userNameCollection, BackgroundWorker worker)
{
    // ...

    if(worker.CancellationPending)
    {
        // Finish method..
    }
}

And the WorkerGetFeedData method:
private void WorkerGetFeedData(object sender, DoWorkEventArgs args)
{
        var worker = sender as BackgroundWorker;
        if(worker != null)
            _feed.FetchUserData(_userNameCollection, worker);
}

A: Send a message (event) to the worker thread that changes a boolean, indicating that the worker thread should end/cancel itself.
Edit: I was a bit quick reading your question, missing the important part. While trying to make up I found this interesting article which might help:
http://ondotnet.com/pub/a/dotnet/2003/02/18/threadabort.html
It does work when simulating a long running process with Thread.Sleep(), being at work I dont have time right now to write code to test it on a proper application/long running task.
class Program
{
    static void Main(string[] args)
    {
        Thread thread = new Thread(new ThreadStart(Foo));
        thread.Start();
        Console.ReadKey();
        thread.Abort(); // cause ThreadAbortException to be thrown
        Console.ReadKey();
    }

    static void Foo()
    {
        try
        {
            while( true )
            {
                Console.WriteLine("Long running process...");
                Thread.Sleep(100000);
            }
        }
        catch( ThreadAbortException ex )
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            Console.WriteLine("Thread Closing ...");
        }
    }
}

The problem with this approach is - it uses Thread.Abort() - which interrupts the thread no matter what it is doing. This can lead to left open handles, memory leaks, etc. So while it may help it would most likely be very unwise to use.
Ian Griffiths supposes that another way to (force) cancel a thread would be to run it in its own, seperate process: http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation which you can kill whenever without affecting your process's internal state.


text:
Q: Definition for swift annotated apis I was reading this link https://developer.apple.com/library/ios/documentation/swift/conceptual/buildingcocoaapps/WorkingWithCocoaDataTypes.html and in the section regarding Memory Managed Objects, they talk about annotated APIs. However, I can't find a definition for annotated APIs. Anyone know what that means?

A: Essentially, Apple is having to go through all their APIs and annotate each function with information about the allocation of memory for parameters and return values. Once that's done, annotated functions can be used from within Swift more easily, since the compiler knows what it has to do to safely bridge types back and forth from Swift code to annotated C code.
Here's an example of similar annotated and unannotated functions. First, the C versions:
// Creates an immutable copy of a string.
CFStringRef CFStringCreateCopy ( CFAllocatorRef alloc, CFStringRef theString );

// Encodes an OSType into a string suitable for use as a tag argument.
CFStringRef UTCreateStringForOSType ( OSType inOSType );

Both of these functions return a CFStringRef - a reference to a CFString. A C CFString can be bridged to a Swift CFString instance, but this is only safe if the method has been annotated. Here are the Swift versions:
// annotated: returns a memory-managed Swift `CFString`
func CFStringCreateCopy(alloc: CFAllocator!, theString: CFString!) -> CFString!

// unannotated: returns an *unmanaged* `CFString`
func UTCreateStringForOSType(inOSType: OSType) -> Unmanaged<CFString>!

If you're calling the second one, you'll need to call .takeRetainedValue() or .takeUnretainedValue() on the result to get a memory-managed CFString instance - to know which one, you'll have to read the documentation or know the conventions to understand whether the result you get back is retained or unretained. With annotated functions, Apple has already done this work for you.
There are a couple threads in the forums on the subject, since Apple is also indicating whether or not return values should be optional with its annotations, but they're keeping things pretty close at this point.


text:
Q: How to run the Android application in background forever after installing in android phone? I am working on android application in which there is two text boxes one take IP Address and another textbox take port number and button start service.
this app connected to web server. during installation the App on Android phone when user click start service Button the application connected to webserver and whole application goes in Background...run forever


text:
Q: Error with OpenCV 2.4.x with Visual C++ 12 I'm developing a image processing using Visual C++ 2013 Update 4 with OpenCV 2.4.x library in Windows 7 x64 SP1.
For the project, I use two configuration, one for x86, another for x64.
On x86 config, it works fine. However, on x64, it always generate an exception at line:
Mat dst = imdecode(buff, CV_LOAD_IMAGE_UNCHANGED);

For the first time calling this line, the output window prints:
Unhandled exception at 0xDDDDDDDDDDDDDDDD in AppClient.exe: Microsoft C++ exception: cv::Exception at memory location 0xCCCCCCCCCCCCCCCC

The next times calling it, the output is:
First-chance exception at 0xDDDDDDDDDDDDDDDD in AppClient.exe: Microsoft C++ exception: cv::Exception at memory location 0xCCCCCCCCCCCCCCCC.

I try this in original project:
imencode(".jpg", src, buff, vector<int>{CV_IMWRITE_JPEG_QUALITY, 100});
imdecode(buff, CV_LOAD_IMAGE_UNCHANGED);

and debug. The buff vector is ok after imencode but it give the exception as described above.
I also try to copy these line to a sample project, also the property sheet of original project and use the same input. It's working perfectly for both x86 and x64.
I've tried for OpenCV 2.4.10, 2.4.11, debug and release lib. The problem is the same!
Any help!
Thanks!


text:
Q: ContourPlot ClippingStyle? In Plot3D, Mathematica by default imposes a scheme for clipping the plot if it exceeds the PlotRange. You can change the default with the option ClippingStyle.
Why is there no similar option in ContourPlot3D? Or is there a way? I'd like both of these plots to look identical.
Plot3D[x^-x + y^-y, {x, 0, 3}, {y, 0, 3}, BoxRatios -> {1, 1, 1},
 PlotRange -> {0, 2.5}]

ContourPlot3D[x^-x + y^-y == z, {x, 0, 3}, {y, 0, 3}, {z, 0, 2.5}]

A: Plot3D samples 2D domain and calculates values of provided expression for those points. If those calculated values exceed PlotRange then we have a clipping. Since domain is 2D, the PlotRange takes part in generating primitives.
ContourPlot3D samples 3D domain and (more or less) calculates values of x^-x + y^-y - z trying to find positions where those values change sign, contours. It has no idea about parts of the contour which are outside the initial domain because it was not sampled at all. Initial domain is already 3D so PlotRange does not affect primitives generation, only rendering. It could but It does not have to.
One could argue, what if ContourPlot3D's PlotRange is narrower than provided domain. The answer is, the plot was not clipped, you just don't see everything, as per request.
Take a look at this example, a contour needed for full domain was calculated even with smaller PlotRange. We can change the range later to confirm:
n = 2;

Show[
   ContourPlot3D[x^-x + y^-y == z, {x, 0, 3}, {y, 0, 3}, {z, 0, 2.5}
     , PlotRange -> {{0, 1}, {0, 1}, {0, 1}}
   ]
 , PlotRange -> Dynamic[n {{0, 1}, {0, 1}, {0, 1}}]
]

Slider[Dynamic[n], {1, 5}]

Related
Modular surface of tri-focal Cassini curve ContourPlot3D missing feet


text:
Q: Is there a way to run this logistic regression with separation? I want to run a logistic regression with a binary outcome (correct vs incorrect) and three predictors: condition (2 levels: A and B), and time (2 levels: before and after), and their interaction. I've run into a problem, however, in that the model gives meaningless parameter estimates with huge SEs. I'm pretty sure the reason is that for one level of the condition predictor the outcome is always correct. Alternatively, it could be that there is some missing data (see below) but my understanding is that this shouldn't be a problem for logistic regression.
The counts are:

*

*Cond A T1: 28 of 28 correct

*Cond B T1: 23 of 26 correct

*Cond A T2: 30 of 30 correct

*Cond B T2: 24 of 30 correct

Is there a way I can run this analysis? The reason being that if I just use chi-square to compare the counts then it looks as though at T2 there is a significant difference between Cond A and Cond B, but this doesn't account for the fact that Cond B was already doing worse at T1. I'd also like to test for a main effect of condition.
EDIT: I realize I didn't model the within-subj variance, which I can do with this code by adding it as a random effect in a mixed model:
glmer(df$outcome ~ df$condition*df$time + (1|d$ID),       family=binomial(logit))

However I get an error message that the "model is nearly unidentifiable: large eignenvalue ratio". Additionally, the estimates are identical whether I use this model or the one where I didn't model within-subject error as a random effect, which made me wonder if I was doing something wrong. There was, however, some variance associated with this term so maybe it's fine (aside from the error message)?

A: As answered above, you seem to be handling within-subject correlation by assumption it's zero.
But to the original question there is no reason to abandon the model or the parameter estimates in the case of complete separation.  The estimations of $\beta$ are still valid.  As stated above they will result in probability estimates of 0 or 1.  Standard errors are not valid.  So you have the Hauck-Donner effect.  You can still get completely valid hypothesis tests using likelihood ratio $\chi^2$ tests, ignoring the standard errors.

A: Logistic regression seems wrong as it would assume independence between the observations at time t1 and t2 (I assume these are the same subjects). Either t1 could be a factor in the model for t2 (or vice versa) or you would want a generalised linear mixed model (GLMM) or could use GEEs. Also,  you probably cannot ignore the missing data of people with a response at t2 that do not have a response at t1 except under some extremely strong assumptions (MCAR). A GLMM would implicitly impute the missing data under a specific MAR assumption, which at least allows the response at one time to influence the missingness at the other time.
Regarding the separation, one thing that would help is a Bayesian approach with at least weakly-informative priors.

A: The other answers are helpful from a general perspective, but there is an additional consideration for this data set: it's too small.
Note that you do not really have 114 informative data points from the perspective of logistic regression. The effective data size in logistic regression is the smaller number of the 2 outcome classes. That's only 9 in this data set (the "incorrect" cases). Based on the rule of thumb of 10-20 of the least-frequent case per predictor variable evaluated, that's barely enough to support analysis of the main A versus B effect. Treating the 30 individuals as a random effect in a mixed model adds at least 1 more predictor to the model (if only differences among intercepts are of interest) and adds 2 predictors if you also care about differences in slope (as you seem to, given your initial attempt to look at the treatment/time interaction). So you really need about 3 times as much data to accomplish what you want.

A: Yet another approach would be to use Firth's bias-corrected logistic model. It is outlined in

@ARTICLE{firth93,
  author = {Firth, D},
  year = 1993,
  title = {Bias reduction of maximum likelihood estimates},
  journal = {Biometrika},
  volume = 80,
  pages = {27--38},
  keywords = {glm}
}

and is available in R and Stata at least.
I am not sure that the sample size you have is a issue at this point, you would not design a study to have this size knowing the prevalence of your outcome but now you have the data you have to do the best you can with it.

A: Your diagnosis is correct. Since you are using a model with two main effects, one interaction, and (I presume) one intercept, you have as many parameters as conditions. Your model will fit itself exactly to the empirical results under each condition: it will predict a probability of 28 / 28 = 1 for Cond A T1, et cetera. For a logistic regression to predict a probability of 1 or 0, some combination of the coefficients must go to the logit of 1 or 0, which is $\pm \infty$.
It doesn't seem profitable to analyze these data on a logit scale. I'd suggest you look instead at the the risk difference between the groups. You can test first for a difference between condition A and condition B using a simple z-test like this. You can also test different times within condition B with same method.
One warning: the normal approximation may not work great given your low counts.
In my opinion, there is not too much point in looking for a main effect of time. On a risk-difference scale, the model with intercept, condition main effect, and a condition B : T2 indicator can explain as much of the observed variation as anyone possibly could with those covariates.


text:
Q: Fermion field in $U(1)$ gauge theory I'm studying Nakahara's Geometry, topology and physics chapter 10.
In section 10.4 on page 391, the book writes:

In physics, we often need to differentiate sections of a vector bundle which is associated with a certain principle bundle. For example, a charged scalar field in QED is regarded as a section of a complex line bundle associated with a $U(1)$ bundle $P(M,U(1))$. Differentiating sections covariantly is very important in constructing gauge-invariant actions.

My questions: what about fermions like electrons? Are they sections of a certain bundle? And how would we define covariant derivative $D_\mu=\partial_\mu+ieA_\mu(x)$ mathematically for fermions then?


text:
Q: how to append if found, and replace if not found at all? (xml find.each loop) I'm trying to search a string value in an xml file, and then append to a div if the string value is found. If not found at all, then I need to display an error text in the same div that the search term was not found.
This is basically supposed to be a search page which loads the searched items into div content.
Currently my content is loading fine. The searched term if found loads all the corresponding divs from the xml, but I've been unable to display an error if the search term was not found.
My XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <item>
        <animal_id>1_1</animal_id>
        <animal_title>Sparrow</animal_title>
        <animal_generic>Birds 1</animal_generic>
        <animal_category>Birds</animal_category>
        <animal_code>a1</animal_code>
        <animal_img>http://i.imgur.com/R0754lr.png</animal_img>
        <animal_url>1_1_Animals1.html</animal_url>
    </item>
    <item>
        <animal_id>1_2</animal_id>
        <animal_title>Crow</animal_title>
        <animal_generic>Birds 2</animal_generic>
        <animal_category>Birds</animal_category>
        <animal_code>b2</animal_code>
        <animal_img>http://i.imgur.com/R0754lr.png</animal_img>
        <animal_url>1_2_Animals2.html</animal_url>
    </item>
    <item>
        <animal_id>1_3</animal_id>
        <animal_title>Parrot</animal_title>
        <animal_generic>Birds 3</animal_generic>
        <animal_category>Birds</animal_category>
        <animal_code>c3</animal_code>
        <animal_img>http://i.imgur.com/R0754lr.png</animal_img>
        <animal_url>1_3_Animals3.html</animal_url>
    </item>
</items>

HTML

Javascript
var s_string = 'bird';

$.ajax({
    url: 'https://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml', // name of file you want to parse
    dataType: "xml",

    success: function parse(xmlResponse){

    $(xmlResponse).find("item").each(function() {
        var pr_id = $(this).find("animal_id").text();
        var p_title = $(this).find("animal_title").text();
        var p_category = $(this).find("animal_category").text();
        var p_code = $(this).find("animal_code").text();
        var p_img = $(this).find("animal_img").text();
        var p_url = $(this).find("animal_url").text();
        var p_gen_name = $(this).find("animal_generic").text();

        var p_xml_string = p_title + p_gen_name, results_string = '', error;
        if(s_string)
        var s_string2 = s_string.replace("%20"," ");
        //console.log(p_xml_string + s_string2);

        if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){
            //console.log("FOUND : " + p_title);

            results_string = '

' + p_title + '

';
                found_string = true;  //// KEEP VALUES = TRUE OR FALSE IN AN ARRAY...GLOBAL ARRAY, AND THEN SEARCH THAT ARRAY FOR TRUE. IF ALL FALSE, SHOW ERROR.
            }

        if(found_string){
        $('.list-h').append(results_string);
            $('

').text("found");
        }
        }); //xmlResponse .each function end.

        },  error: function(){console.log('Error: Animals info xml could not be loaded.');}

        });

// START OF NOT FOUND SEARCH SCRIPT
    $(window).load(function(){
    var error_found = $('#error_div').text(); console.log(error_found);
        setTimeout(function(){
        if(error_found != 'found'){
        var results_string = 'Your Search Query "' + $.url().param('q').replace("%20"," ") + '" was not found! Maybe you entered an invalid search query.';
        $('.list-h').append(results_string); }
        }, 0);
    });
// END OF NOT FOUND SEARCH SCRIPT

And here's the js fiddle with complete XML url: http://jsfiddle.net/mohitk117/B89Ms/
Please could someone help me out regarding this? Thanks!

A: I'm a bit uncertain of how everything fits together because the javascript code is not self-explanatory. But, can you start by addressing this issue here...?
    if(s_string)
    var s_string2 = s_string.replace("%20"," ");
    //console.log(p_xml_string + s_string2);

    if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){

s_string2 variable is out of scope when you use it in this expression...
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){

What were you trying to do there? The expression above will always evaluate to false because s_string2 is undefined. In other words, whatever processing you are doing inside that if block will never be reached
Again, this variable is instantiated and disposed at the very same time...
 if(s_string)
     var s_string2 = s_string.replace("%20"," "); //<--- This variable's lifecycle ends here

and, this expression will always be false until you address the variable issue above...
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1)

A: Some changes may sort out your problem
Add a div in your html

Change below code
if (s_string) var s_string2 = s_string.replace("%20", " ");
//console.log(p_xml_string + s_string2);
if (p_xml_string.toLowerCase().indexOf(s_string2) > -1) {

to
var s_string2='';
if (s_string) s_string2 = s_string.replace("%20", " ");
if (s_string2 && p_xml_string.toLowerCase().indexOf(s_string2) > -1) {

Change found_string code like,
if (found_string) {
   $('.list-h').append(results_string);
   $('#error_div').text("found");
}

Optionally add css for error_div
#error_div {
    color:red;
}

Live Demo
Updated success code
    var found_string = false; // define found_string globally
    $(xmlResponse).find("item").each(function () {
        var pr_id = $(this).find("animal_id").text();
        var p_title = $(this).find("animal_title").text();
        var p_category = $(this).find("animal_category").text();
        var p_code = $(this).find("animal_code").text();
        var p_img = $(this).find("animal_img").text();
        var p_url = $(this).find("animal_url").text();
        var p_gen_name = $(this).find("animal_generic").text();

        var p_xml_string = p_title + p_gen_name,
            results_string = '',
            error;
        var s_string2 = '';

        if (s_string) s_string2 = s_string.replace("%20", " ");
        if (s_string2 && p_xml_string.toLowerCase().indexOf(s_string2) > -1) {
            //console.log("FOUND : " + p_title);
            results_string = '

' + p_title + '

';
            found_string = true; //// KEEP VALUES = TRUE OR FALSE IN AN ARRAY...GLOBAL ARRAY, AND THEN SEARCH THAT ARRAY FOR TRUE. IF ALL FALSE, SHOW ERROR.
        }
        if (found_string) { // if found then append in list
            $('.list-h').append(results_string);
        }

    }); //xmlResponse .each function end.
    if (found_string) { // if found then empty error div
        $('#error_div').text("");
    } else { // else show error text or not found
        $('#error_div').text("not found");
    }

Updated Found Demo and Not Found Demo


text:
Q: Maven Skipping one of the repositories from my pom.xml I'm working with a Java Maven - project
in my parent pom, I have defined
3 repositories
<repositories>
    <repository>
        <id>company-central</id>
        <name>company</name>
        <url>https://artifactory.company.com/artifactory/company/</url>
    </repository>
    <repository>
        <id>releases</id>
        <name>nexus</name>
        <url>https://nexus-proxy.dev.company.io/nexus/content/repositories/releases/</url>
    </repository>
    <repository>
        <id>thirdparty</id>
        <name>nexus</name>
        <url>https://nexus-proxy.dev.company.io/nexus/content/repositories/thirdparty/</url>
    </repository>
</repositories>

but when i run maven its skipp the company-central repository and wont try to download from there
[INFO] Building core 0.0.1-SNAPSHOT                                      [7/49]
[INFO] --------------------------------[ jar ]---------------------------------
Downloading from releases: https://nexus-proxy.dev.company.io/nexus/content/repositories/releases/org/....
Downloading from thirdparty: https://nexus-proxy.dev.company.io/nexus/content/repositories/thirdparty/org/....
Downloading from releases: https://nexus-proxy.dev.company.io/nexus/content/repositories/releases/com/....
Downloading from thirdparty: https://nexus-proxy.dev.company.io/nexus/content/repositories/thirdparty/com/....

And finally it fails on "missing jars" which exists on company-central
[ERROR] Failed to execute goal on project core: Could not resolve dependencies for project com.company:core:jar:0.0.1-SNAPSHOT: Failed to collect dependencies at org.apache.commons......

My setting.xml
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      https://maven.apache.org/xsd/settings-1.0.0.xsd">
  <servers>
    <server>
      <id>company-central</id>
      <username>1234</username>
      <password>1234</password>
    </server>

  <server>
    <id>nexus</id>
    <username>/1234</username>
    <password>1234</password>
  </server>

  <server>
    <id>central</id>
    <username>/1234</username>
    <password>1234</password>
  </server>

  <server>
    <id>core</id>
    <username>/1234</username>
    <password>1234</password>
  </server>

  </servers>

the profile part in my setting XML
  <profiles>
      <profile>
        <id>AAAAA</id>
        <repositories>
          <repository>
            <id>central</id>
            <url>https://example.com/nexus/content/groups/public</url>
          </repository>
        </repositories>
        <pluginRepositories>
          <pluginRepository>
            <id>central</id>
            <url>https://example.com/nexus/content/groups/public</url>
          </pluginRepository>
        </pluginRepositories>
      </profile>
    </profiles>
    <activeProfiles>
      <activeProfile>AAAAA</activeProfile>
    </activeProfiles>

</settings>


text:
Q: Determinar el numero mas cercano, dentro del array, al numero dado Buenas tengo este problema: a partir de un array y un numero determinar que numero del array es el mas cercano al numero. No me sale
 public static int masCercano(int[] numeros, int num)
 {
    int cercano = 0;
    for (int i = 0; i < numeros.length; i++)
    {
        if (numeros[i] ==  num)
        {
            return numeros[i];
        }
        else
            if (numeros[i] > num || numeros[i] < num)
            {
                cercano = numeros[i];
                if (cercano > numeros[i])
                {
                    cercano = numeros[i];
                }
                else
                    cercano = numeros[i];
            }
    }
    return cercano;
 }

A: El problema es que estás pasando por todos los números preguntando si es menor o mayor al número que necesitamos comparar, es decir simplemente cercano lo hará igual al último número que evaluó y fue menor o mayor al número a comparar, pero en ningún momento se está buscando el menor más cercano o el mayor más cercano.
Usando una variable llamada diferencia vamos guardando la que hasta el momento sea la menor diferencia entre los números del arreglo y el número a comparar y así mismo vamos guardando cuál es este número de menor diferencia, sea mayor o menor

    public static int masCercano(int[] numeros, int num) {
        int cercano = 0;
        int diferencia = Integer.MAX_VALUE; //inicializado valor máximo de variable de tipo int
        for (int i = 0; i < numeros.length; i++) {
            if (numeros[i] == num) {
                return numeros[i];
            } else {
                if(Math.abs(numeros[i]-num)<diferencia){
                    cercano=numeros[i];
                    diferencia = Math.abs(numeros[i]-num);
                }
            }
        }
        return cercano;
    }

A: Este bloque de código, te permite determinar el número más cercano si no se encuentra una coincidencia exacta, que según entiendo es lo que necesitas.
public static int masCercano(int[] numeros, int numero) {

    int menor = 0;
    int mayor = 0;
    int cercano = 0;

    for (int i = 0; i < numeros.length ; i++) {

        if (numeros[i] == numero) {
            return numeros[i];
        } else if (numeros[i] < numero) {
            menor = numeros[i];
        } else if (numeros[i] > numero) {
            mayor = numeros[i];
        }
    }

    if ((mayor - numero) < (numero - menor)) {
        cercano = mayor;
    } else {
        cercano = menor;
    }

    return cercano;

}

A: Se me ocurre, que podrías guardar el indice del valor mas cercano eh ir haciendo restas. Luego el mas cercano al 0 es el que esta mas cerca.
public static int masCercano(int[] numeros, int num) {
  int menorDistanciaActual = Math.abs(num - numeros[0]); // Aca guardas la resta
  int posicionNumeroMasCercano = 0; // Si viene un array con un elemento, es el [0]

  // Empezas en 1, porque ya sabes que el 0 es el mas cercano hasta ahora.
  for (int i = 1; i < numeros.length; i++) {
    int distanciaEntreNumeros = Math.abs(num - numeros[i]);

    if (distanciaEntreNumeros < menorDistanciaActual) {
      menorDistanciaActual = distanciaEntreNumeros;
      posicionNumeroMasCercano = i;
    }
  }

  return numeros[posicionNumeroMasCercano];
}

Nota:

*

*Uso Math.abs() porque queres saber la distancia mínima, y para eso se utiliza el modulo. Si diera un resultado negativo por ejemplo quedando  -100 la distancia seria mayor a la de 5. En cambio con Math.abs(-100) = 100

*Si te viene un array con solo un elemento, te retornará ese elemento.

Espero que te sirva. Saludos!


text:
Q: How do I test collision between two rectangles, one with multiple instances of its class? This is more of a question of logic than code, I do believe.
I have two rectangles (of class "RedBlock"), referenced by "Main.blocks[]" and another rectangle (of class "MainCharacter"), whose class this code comes from. The rectangle of class "MainCharacter" should stop moving when it collides with either of the rectangles in the "Block" array (named "blocks"). Since it is in a "for" loop, any "if" statement inside the block must be true for both instances of "Block" for it to keep the "MainCharacter' from moving. Also, since the code is run twice, the "movementSpeed" seems to be doubled, caused by the "setX()" method being called twice.
My problem, therefore, is that I cannot test collision between one of the two blocks, but only between both blocks at the same time, and that I cannot accurately control the speed of the "MainCharacter" (as it is relative to the number of blocks). Can you tell me what I am doing wrong? If you have a superior form of collision detection at hand, feel free to include that in your answer.
    for (int i = 0; i <= Main.blocks.length - 1; i++) {
        if (Main.blocks[i] != null) {
            if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
                if (Math.abs(getRight() - Main.blocks[i].getLeft()) < movementSpeed
                        && getBottom() <= Main.blocks[i].getTop()
                        && getTop() >= Main.blocks[i].getBottom()) {
                    setX(getX() + Math.abs(getRight() - Main.blocks[i].getLeft()));
                } else {
                    setX(getX() + movementSpeed);
                }
            } else if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
                if (Math.abs(getLeft() - Main.blocks[i].getRight()) < movementSpeed
                        && getBottom() <= Main.blocks[i].getTop()
                        && getTop() >= Main.blocks[i].getBottom()) {
                    setX(getX() - Math.abs(getLeft() - Main.blocks[i].getRight()));
                } else {
                    setX(getX() - movementSpeed);
                }
            } if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
                if (Math.abs(getBottom() - Main.blocks[i].getTop()) < movementSpeed
                        && getLeft() <= Main.blocks[i].getRight()
                        && getRight() >= Main.blocks[i].getLeft()) {
                    setY(getY() - Math.abs(getBottom() - Main.blocks[i].getTop()));
                } else {
                    setY(getY() - movementSpeed);
                }
            } else if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
                if (Math.abs(getTop() - Main.blocks[i].getBottom()) < movementSpeed
                        && getLeft() <= Main.blocks[i].getRight()
                        && getRight() >= Main.blocks[i].getLeft()) {
                    setY(getY() + Math.abs(getTop() - Main.blocks[i].getBottom()));
                } else {
                    setY(getY() + movementSpeed);
                }
            }
        } else return;
    }

A: Why are you calling the event in the keyboard event? why not just check block[i].leftrighttop and down from the block[i+1] and then move it back the distance it traveled inwards eg.
for(int i = 0; i < Main.blocks.length - 2/*Because we will be checking i +1*/; i ++){
if((Main.blocks[i].left > Main.blocks[i+1].left)&&(Main.blocks[i].left < Main.blocks[i+1].left)){}
}

that would check the x pos of the blocks... now you can just tell it to move to the nearest point and do the same for the rest :) hopes it helps! i always did it in delphi7.


text:
Q: Matlab GUI ODE solver 'Value' must be a double scalar I am trying to make an 2nd order ODE solver but it's not working (Error using matlab.ui.control.internal.model.AbstractNumericComponent/set.Value (line 111)
'Value' must be a double scalar.) when I run it on the normal matlab (not the app designer), I get the right answer.
    m1 = app.m.Value;
    c1 = app.c.Value;
    k1 = app.k.Value;

    syms y(x)
Dy = diff(y);

ode = m1*diff(y,x,2) == app.u.Value - c1*Dy - k1*y;
cond1 = y(0) == 1;
cond2 = Dy(0) == 0;
conds = [cond1 cond2];
ySol(x) = dsolve(ode,conds);
ySol = simplify(ySol);
app.EditField.Value = ySol;


text:
Q: Как регулировать отступы между секциями диаграммы doughnut в Chart.js
    const ctx = document.getElementById('myChart');
    new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 50, 3, 5, 50, 3],
      borderWidth: 0,
      backgroundColor: ['red', 'blue', 'yellow','green', 'purple', 'orange'],
      borderColor: ['aqua'],
    }]
  },
  options: {
    maintainAspectRatio: true,
    borderJoinStyle: 'miter',
    //spacing: 20,
    rotation: 0,
    borderAlign: 'inner',
    borderRadius: 0,
    circumference: 360

  }
});

Мне нужно сделать отступы между секциями диаграммы и чтобы отступы были одинаковыми,  я делал отступы с помощью spacing , но тогда отступы получаются не равными, как это можно сделать?


text:
Q: WSO2 AM 1.10.0 validate query parameters To prevent Log injection, I need to validate the query parameters (country, pesticide and crop) in WSO2 AM. the API looks like below,
http://172.17.100.149/api/mrldatabase/v1/reports?country=AUS&pesticide=ABew30000&crop=22020347

Really appreciate if someone can show me a way of validation.

A: You can write a custom mediation sequence for this. See docs.
You can read query params like this. See this for more details.
<sequence xmlns="http://ws.apache.org/ns/synapse" name="admin--Temp:v1.0.0--In">
      <log level="custom">
          <property name="SubPath" expression="$ctx:REST_SUB_REQUEST_PATH"/>
      </log>
 </sequence>


text:
Q: Difference between HBase and Hadoop/HDFS This is kind of naive question but I am new to NoSQL paradigm and don't know much about it. So if somebody can help me clearly understand difference between the HBase and Hadoop or if give some pointers which might help me understand the difference.
Till now, I did some research and acc. to my understanding Hadoop provides framework to work with raw chunk of data(files) in HDFS and HBase is database engine above Hadoop, which basically works with structured data instead of raw data chunk. Hbase provides a logical layer over HDFS just as SQL does. Is it correct?

A: Hadoop uses distributed file system i.e  HDFS for storing bigdata.But there are certain Limitations of HDFS and Inorder to overcome these limitations, NoSQL databases such as HBase,Cassandra and Mongodb came into existence.
Hadoop can perform only batch processing, and data will be accessed only in a sequential manner. That means one has to search the entire dataset even for the simplest of jobs.A huge dataset when processed results in another huge data set, which should also be processed sequentially. At this point, a new solution is needed to access any point of data in a single unit of time (random access).
Like all other FileSystems, HDFS  provides us storage, but in a fault tolerant manner with high throughput and lower risk of data loss(because of the replication).But, being a File System , HDFS lacks random read and write access. This is where HBase comes into picture. It's a distributed, scalable, big data store, modelled after Google's BigTable. Cassandra is somewhat similar to hbase.

A: Both HBase and HDFS in one picture

Note:
Check the HDFS demons(Highlighted in green) like DataNode(collocated Region Servers) and NameNode in the cluster with have both HBase and Hadoop HDFS

HDFS is a distributed file system that is well suited for the storage of large files. which does not provide fast individual record lookups in files.
HBase, on the other hand, is built on top of HDFS and provides fast record lookups (and updates) for large tables. This can sometimes be a point of conceptual confusion. HBase internally puts your data in indexed "StoreFiles" that exist on HDFS for high-speed lookups.

How does this look like?

Well, At the infrastructure level, each salve machine in the cluster have following demons

*

*Region Server - HBase

*Data Node - HDFS

How is it fast with lookups?

HBase achieves fast lookups on HDFS(sometimes other distributed file systems also) as underlying storage, using the following data model

*

*Table

*

*An HBase table consists of multiple rows.

*Row

*

*A row in HBase consists of a row key and one or more columns with values associated with them. Rows are sorted alphabetically by the row key as they are stored. For this reason, the design of the row key is very important. The goal is to store data in such a way that related rows are near each other. A common row key pattern is a website domain. If your row keys are domains, you should probably store them in reverse (org.apache.www, org.apache.mail, org.apache.jira). This way, all of the Apache domains are near each other in the table, rather than being spread out based on the first letter of the subdomain.

*Column

*

*A column in HBase consists of a column family and a column qualifier, which are delimited by a : (colon) character.

*Column Family

*

*Column families physically colocate a set of columns and their values, often for performance reasons. Each column family has a set of storage properties, such as whether its values should be cached in memory, how its data is compressed or its row keys are encoded, and others. Each row in a table has the same column families, though a given row might not store anything in a given column family.

*Column Qualifier

*

*A column qualifier is added to a column family to provide the index for a given piece of data. Given a column family content, a column qualifier might be content:html and another might be content:pdf. Though column families are fixed at table creation, column qualifiers are mutable and may differ greatly between rows.

*Cell

*

*A cell is a combination of the row, column family, and column qualifier, and contains a value and a timestamp, which represents the value's version.

*Timestamp

*

*A timestamp is written alongside each value and is the identifier for a given version of a value. By default, the timestamp represents the time on the RegionServer when the data was written, but you can specify a different timestamp value when you put data into the cell.

Client read request flow:

What is the meta table in the above picture?

After all the information, HBase read flow is for lookup touches these entities

*

*First, the scanner looks for the Row cells in the Block cache - the read-cache. Recently Read Key Values are cached here, and Least Recently Used are evicted when memory is needed.

*Next, the scanner looks in the MemStore, the write cache in memory containing the most recent writes.

*If the scanner does not find all of the row cells in the MemStore and Block Cache, then HBase will use the Block Cache indexes and bloom filters to load HFiles into memory, which may contain the target row cells.

sources and more information:

*

*HBase data model

*HBase architecute

A: Hadoop is basically 3 things, a FS (Hadoop Distributed File System), a computation framework (MapReduce) and a management bridge (Yet Another Resource Negotiator). HDFS allows you store huge amounts of data in a distributed (provides faster read/write access) and redundant (provides better availability) manner. And MapReduce allows you to process this huge data in a distributed and parallel manner. But MapReduce is not limited to just HDFS. Being a FS, HDFS lacks the random read/write capability. It is good for sequential data access. And this is where HBase comes into picture. It is a NoSQL database that runs on top your Hadoop cluster and provides you random real-time read/write access to your data.
You can store both structured and unstructured data in Hadoop, and HBase as well. Both of them provide you multiple mechanisms to access the data, like the shell and other APIs.
And, HBase stores data as key/value pairs in a columnar fashion while HDFS stores data as flat files. Some of the salient features of both the systems are :
Hadoop

*

*Optimized for streaming access of large files.

*Follows write-once read-many ideology.

*Doesn't support random read/write.

HBase

*

*Stores key/value pairs in columnar fashion (columns are clubbed together as column families).

*Provides low latency access to small amounts of data from within a large data set.

*Provides flexible data model.

Hadoop is most suited for offline batch-processing kinda stuff while HBase is used when you have real-time needs.
An analogous comparison would be between MySQL and Ext4.

A: Apache Hadoop project includes four key modules

*

*Hadoop Common: The common utilities that support the other Hadoop modules.

*Hadoop Distributed File System (HDFS™): A distributed file system that provides high-throughput access to application data.

*Hadoop YARN: A framework for job scheduling and cluster resource management.

*Hadoop MapReduce: A YARN-based system for parallel processing of large data sets.

HBase is A scalable, distributed database that supports structured data storage for large tables. Just as Bigtable leverages the distributed data storage provided by the Google File System, Apache HBase provides Bigtable-like capabilities on top of Hadoop and HDFS.
When to use HBase:

*

*If your application has a variable schema where each row is slightly different

*If you find that your data is stored in collections, that is all keyed on the same value

*If you need random, real time read/write access to your Big Data.

*If you need key based access to data when storing or retrieving.

*If you have huge amount of data with existing Hadoop cluster

But HBase has some limitations

*

*It can't be used for classic transactional applications or even relational analytics.

*It is also not a complete substitute for HDFS when doing large batch MapReduce.

*It doesn't talk SQL, have an optimizer, support cross record transactions or joins.

*It can't be used with complicated access patterns (such as joins)

Summary:

Consider HBase when you're loading data by key, searching data by key (or range), serving data by key, querying data by key or when storing data by row that doesn't conform well to a schema.

Have a look at Do's and Don't of HBase from cloudera blog.

A: Reference: http://www.quora.com/What-is-the-difference-between-HBASE-and-HDFS-in-Hadoop
Hadoop is a general name for several subsystems:
 1) HDFS. A distributed file system that distributes data across a cluster of machines taking care of redundancy etc
 2) Map Reduce. A job management system on top of HDFS - to manage map-reduce (and other types) jobs processing the data stored on HDFS.
Basically it means its an offline system - you store data on HDFS and you can process it by running jobs.
HBase on the other hand in a column based database.
It uses HDFS as storage - which takes care of backup\redundency\etc but its an "online store" - meaning you can query it for specific row\rows etc and get an immediate value.

A: HDFS is a Java based distributed file system that allows you to store large data across multiple nodes in a Hadoop cluster. Whereas HBase is a NoSQL database (similar as NTFS and MySQL).
As Both HDFS and HBase stores all kind of data such as structured, semi-structured and unstructured in a distributed environment.
Differences between HDFS & HBase

*

*HBase provides low latency access to small amounts of data within large data sets
while HDFS provides high latency operations.

*HBase supports random read and writes while HDFS supports WORM (Write once Read Many
or Multiple times).

*HDFS is basically or primarily accessed through MapReduce jobs while HBase is accessed
through shell commands, Java API, REST, Avro or Thrift API.

HDFS stores large data sets in a distributed environment and leverages batch
processing on that data.
While HBase stores data in a column oriented manner where each column is stored together so that, reading becomes faster leveraging real time processing.


text:
Q: Julia: Using the Underscore as a Digit Separator in BigFloat and BigInt According to the Julia 1.0.0 docs:

The underscore _ can be used as digit separator:

julia> 10_000, 0.000_000_005, 0xdead_beef, 0b1011_0010
(10000, 5.0e-9, 0xdeadbeef, 0xb2)

However, in the Julia 1.0.0 REPL I get this:
julia> VERSION
v"1.0.0"

# Underscore does not work work on right side of decimal in BigFloat.
julia> big"3.141_592"
ERROR: ArgumentError: invalid number format 3.141_592 for BigInt or BigFloat

 # Underscore does not work on left side of decimal in BigFloat.
julia> big"123_456.7898"
ERROR: ArgumentError: invalid number format 123_456.7898 for BigInt or BigFloat

# Underscore works for BigInt in example below:
julia> big"123_456_789"
123456789
julia> typeof(ans)
BigInt

Apparently, the underscore can be used in BigInt, but not BigFloat.
Is this by design or has underscore use for BigFloat simply not been implemented yet?

A: This issue is now posted and discussed on the Julia GitHub Issues site here.


text:
Q: How to interpolate {{xi,yi},... ,{xn,yn}} with minimum bending energy? Thin Plate Splines are explained here, and a Mathematica implementation of that for real samples { { x1, y2, z1 }, { x2, y2, z2 },  ...  , { xn, yn, zn } }  is given here.  As I understand it, the algorithm gives the function $f(x, y)$ that interpolates through the samples { { xi, yi, zi }, ... } and  minimizes the bending energy $\int _{-\infty }^{\infty }\int _{-\infty }^{\infty }(D[f[x,y],\{x,1\}]^2+D[f[x,y],\{x,2\}]^2)dx$ $dy$. Now suppose I have the following:
data = {{1.0, 4.2}, {2.0, 9.3}, {4.0, 7.1}, {5.0, 4.3}, {8.0,
5.7}, {9.0, 10.2}, {10.0, 10.6}, {12.0, 7.2}};

How would I find the function $f(x)$ that interpolates the {xi,yi} data samples, and minimizes the bending energy $\int _{-\infty }^{\infty }  (f''[x])^2 dx.$ ?
****** Edit ******
The Mathematica implementation I refer to above is the answer by J.M.
I give an improvement on that implementation below:
ThinPlateInterpolation::usage = "ThinPlateInterpolation[{{x1,y1,z1},{x2,y2,z2}..}] returns a CompiledFunction that gives a smooth interpolation between the points provided. The function returned is a function of two real numbers.";

ThinPlateInterpolation[points_?(And[Last[Dimensions@#] === 3, 3 <= First[Dimensions@#],MatrixQ[#, Element[#, Reals] &]] &)]:=
Module[{xs, ys, zs, xys, len, func, m, b, xx,yy},
{xs, ys, zs} = N@Transpose[points];
xys = Transpose[{xs, ys}];
len = Length[xs];
func = Compile[{{x0, _Real}, {y0, _Real},{xsys, _Real,2},{n, _Integer}},
Join[
 With[{abs = Norm[#]},
   If[abs == 0.0, 0.0, abs^2* Log[abs]]] & /@ (Table[{x0, y0},n] - xsys),
 {1.0, x0, y0}]
];
m = func[#1, #2, xys, len] & @@@ xys;
m = m~Join~{ConstantArray[1.0, len]
~Join~{0., 0., 0.},
xs~Join~{0., 0., 0.}, ys~Join~{0., 0., 0.}};
b=zs~Join~{0., 0., 0.};
Compile @@ {{{xx, _Real}, {yy, _Real}},
  Quiet[func[xx, yy, xys,len].
  LinearSolve[m, b], {LinearSolve::luc,CompiledFunction::cfsa}]}
 ]

A: In the very simple case you have given, the expression for the required thin plate spline is very easily derived, and the elaborate machinery in my other answer is not necessary. Using formulae 28, 29, and 31 in Eberly's note, we have the following:
pts = {{1., 4.2}, {2., 9.3}, {4., 7.1}, {5., 4.3}, {8., 5.7}, {9., 10.2},
       {10., 10.6}, {12., 7.2}};

{xa, ya} = Transpose[pts];
lsf = LinearSolve[DistanceMatrix[xa, xa]^3/12];
nmat = PadLeft[{xa}, {2, Automatic}, 1];

bc = LinearSolve[nmat.lsf[Transpose[nmat]], nmat.lsf[ya]];
ac = lsf[ya - Transpose[nmat].bc];

tps[x_] = bc.{1, x} + ac.Abs[x - pts[[All, 1]]]^3/12;

Plot[tps[x], {x, 1, 12},
     Epilog -> {Directive[AbsolutePointSize[6], ColorData[97, 4]], Point[pts]}]


text:
Q: How to find the posterior predictive distribution of a hierarchical model where the dependent variable is group indexed? I have data on $i = 1, \ldots, N$ units which belong in $s = 1, \ldots, M$ groups. The data is indexed by these two indices. I have an independent binary data $X$ corresponding to dependent binary data $Y$. The hierarchical model is given by:
$$
X_{is} \sim Bern(\theta_{s, y})\\
Y_{is} \sim Bern(\pi_s)\\
\theta_{s,y} \sim Beta(a_y,b_y)\\
\pi_s \sim Unif(0,1)\\
a_y \sim Gamma(0.5,0.5)\\
b_y \sim Gamma(0.5,0.5)\\
$$
I am wondering how I can obtain posterior predictive draws of $Y$ and $X$ after running MCMCs. For example, suppose I wanted to draw $Y$. I would first take a set of draws from the chain on $\pi_s$, then plug this into $Bern(\pi_s)$ to get a single draw of $Y$. However, each draw of $\pi$ from the chain consists of $s$ values. Which of these $s$ values do I plug into the Bernoulli?
Do I look at my observed data and randomly select a unit, and record their group membership indicator $s$, and select the value of a chain draw $\pi_s$ off that?


text:
Q: Autocompleting combobox in ASP.NET MVC? I'm trying to convert an app that I had previously written in ASP.NET Web Forms to MVC and am stuck on the problem of implementing an autocompleting combobox. Previously, I had used Telerik's RadComboBox, but I'm not sure how to make this work in MVC or if it even can be made to work. Here's the markup code I was using:
<telerik:RadComboBox ID="Brand" runat="server" Width="250px" EmptyMessage="Choose a brand" EnableLoadOnDemand="true" OnItemsRequested="Brand_OnItemsRequested" />

And the code-behind:
protected void Brand_OnItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
  foreach (BrandCode b in _repository.GetBrandCode(e.Text).OrderBy(b => b.BrandName).Take(10))
  {
    Brand.Items.Add(new Telerik.Web.UI.RadComboBoxItem(b.BrandName, b.BrandCode1));
  }

  Brand.DataBind();
}

Any ideas appreciated.

A: We do this at work by simply populating a drop down list (or combobox, whichever tickles your fancy), and then using jquery's autocomplete by doing something like $('#myddl').autocomplete();