text:
Q: Get the item doubleclick event of listview What do I need to do in order to reference the double click event for a listview control?

A:     private void positionsListView_DoubleClick(object sender, EventArgs e)
    {
        if (positionsListView.SelectedItems.Count == 1)
        {
            ListView.SelectedListViewItemCollection items = positionsListView.SelectedItems;

            ListViewItem lvItem = items[0];
            string what = lvItem.Text;

        }
    }

A: <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <EventSetter Event="MouseDoubleClick" Handler="listViewItem_MouseDoubleClick" />
    </Style>
</ListView.ItemContainerStyle>

The only difficulty then is if you are interested in the underlying object the listviewitem maps to e.g.
private void listViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    ListViewItem item = sender as ListViewItem;
    object obj = item.Content;
}

A: I don't yet have a large enough reputation score to add a comment where it would be most helpful, but this is in relation to those asking about a .Net 4.5 solution.
You can use the mouse X and Y co-ordinates and the ListView method GetItemAt to find the item which has been clicked on.
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    ListViewItem item = myListView.GetItemAt(e.X, e.Y)
    // Do something here
}

A: I needed that as well. I found that on msdn:
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.activation.aspx
I think this delegate is for that.

A: for me, I do double click of ListView in this code section .
    this.listView.Activation = ItemActivation.TwoClick;

    this.listView.ItemActivate += ListView1_ItemActivate;

ItemActivate specify how user activate with items
When user do double click, ListView1_ItemActivate will be trigger.
Property of ListView ItemActivate refers to access the collection of items selected.
    private void ListView1_ItemActivate(Object sender, EventArgs e)
    {

        foreach (ListViewItem item in listView.SelectedItems)
           //do something

    }

it works for me.

A: I'm using something like this to only trigger on ListViewItem double-click and not for example when you double-click on the header of the ListView.
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject obj = (DependencyObject)e.OriginalSource;

    while (obj != null && obj != myListView)
    {
        if (obj.GetType() == typeof(ListViewItem))
        {
            // Do something here
            MessageBox.Show("A ListViewItem was double clicked!");

            break;
        }
        obj = VisualTreeHelper.GetParent(obj);
    }
}

A: Use the ListView.HitTest method
    private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        var senderList  = (ListView) sender;
        var clickedItem = senderList.HitTest(e.Location).Item;
        if (clickedItem != null)
        {
            //do something
        }
    }

Or the old way
    private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        var senderList  = (ListView) sender;
        if (senderList.SelectedItems.Count == 1 && IsInBound(e.Location, senderList.SelectedItems[0].Bounds))
        {
            //Do something
        }
    }

    public  bool IsInBound(Point location, Rectangle bound)
    {
        return (bound.Y <= location.Y &&
                bound.Y + bound.Height >= location.Y &&
                bound.X <= location.X &&
                bound.X + bound.Width >= location.X);
    }

A: I found this on Microsoft Dev Center. It works correctly and ignores double-clicking in wrong places. As you see, the point is that an item gets selected before double-click event is triggered.
private void listView1_DoubleClick(object sender, EventArgs e)
{
    // user clicked an item of listview control
    if (listView1.SelectedItems.Count == 1)
    {
        //do what you need to do here
    }
}

http://social.msdn.microsoft.com/forums/en-US/winforms/thread/588b1053-8a8f-44ab-8b44-2e42062fb663

A: Here is how to get the selected object and object matching code for the double clicked listview item in a WPF listview:
/// <summary>
/// Get the object from the selected listview item.
/// </summary>
/// <param name="LV"></param>
/// <param name="originalSource"></param>
/// <returns></returns>
private object GetListViewItemObject(ListView LV, object originalSource)
{
    DependencyObject dep = (DependencyObject)originalSource;
    while ((dep != null) && !(dep.GetType() == typeof(ListViewItem)))
    {
        dep = VisualTreeHelper.GetParent(dep);
    }
    if (dep == null)
        return null;
    object obj = (Object)LV.ItemContainerGenerator.ItemFromContainer(dep);
    return obj;
}

private void lvFiles_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    object obj = GetListViewItemObject(lvFiles, e.OriginalSource);
    if (obj.GetType() == typeof(MyObject))
    {
        MyObject MyObject = (MyObject)obj;
        // Add the rest of your logic here.
    }
}

A: You can get the ListView first, and then get the Selected ListViewItem.
I have an example for ListBox, but ListView should be similar.
private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        ListBox box = sender as ListBox;
        if (box == null) {
            return;
        }
        MyInfo info = box.SelectedItem as MyInfo;
        if (info == null)
            return;
        /* your code here */
        }
        e.Handled = true;
    }

A: In the ListBox DoubleClick event get the selecteditem(s) member of the listbox, and there you are.
void ListBox1DoubleClick(object sender, EventArgs e)
    {
        MessageBox.Show(string.Format("SelectedItem:\n{0}",listBox1.SelectedItem.ToString()));
    }

A: Either use the MouseDoubleClick event, and also, all the MouseClick events have a click count in the eventargs variable 'e'. So if e.ClickCount == 2, then doubleclicked.

A: It's annoying, but the best way to do it is something like:
<DataTemplate Name="MyCoolDataTemplate">
    <Grid Loaded="HookLVIClicked" Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}">
        <!-- your code here -->
    </Grid>
</DataTemplate>

Then in the code:
public void HookLVIClicked(object sender, RoutedEventArgs e) {
    var fe = (FrameworkElement)sender;
    var lvi = (ListViewItem)fe.Tag;
    lvi.MouseDoubleClick += MyMouseDoubleClickHandler;
}

A: Was having a similar issue with a ListBox wanting to open a window (Different View) with the SelectedItem as the context (in my case, so I can edit it).
The three options I've found are: 1. Code Behind 2. Using Attached Behaviors 3. Using Blend's i:Interaction and EventToCommand using MVVM-Light.
I went with the 3rd option, and it looks something along these lines:
<ListBox x:Name="You_Need_This_Name"
ItemsSource="{Binding Your_Collection_Name_Here}"
SelectedItem="{Binding Your_Property_Name_Here, UpdateSourceTrigger=PropertyChanged}"
... rest of your needed stuff here ...
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
    <Command:EventToCommand Command="{Binding Your_Command_Name_Here}"
        CommandParameter="{Binding ElementName=You_Need_This_Name,Path=SelectedItem}"     />
    </i:EventTrigger>
</i:Interaction.Triggers>

That's about it ... when you double click on the item you want, your method on the ViewModel will be called with the SelectedItem as parameter, and you can do whatever you want there :)

A: The sender is of type ListView not ListViewItem.
    private void listViewTriggers_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        ListView triggerView = sender as ListView;
        if (triggerView != null)
        {
            btnEditTrigger_Click(null, null);
        }
    }

A: i see this subject is high on google, there is my simple and working sample :)
XAML:
    <ListView Name="MainTCList" HorizontalAlignment="Stretch" MinHeight="440" Height="Auto" Margin="10,10,5.115,4" VerticalAlignment="Stretch" MinWidth="500" Width="Auto" Grid.Column="0" MouseDoubleClick="MainTCList_MouseDoubleClick" IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="UserTID" DisplayMemberBinding="{Binding UserTID}" Width="80"/>
                <GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" Width="410" />
            </GridView>
        </ListView.View>
    </ListView>

C#
    private void MainTCList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
            TC item = (TC)MainTCList.Items.CurrentItem;
            Wyswietlacz.Content = item.UserTID;
    }

Wyswietlacz is a test Label to see item content :) I add here in this last line a method to Load Page with data from item.


text:
Q: Java Application + Logging I am bit confused so, thought to ask experts.
I have written small java application. I have function which reads properties files which contains the path of the directory where to write the log and exceptions. Lets say I get exception while reading the properties file since logger wouldn't have been initialized by that time, how can I know that there was an error or exception? If I have written e.printStackTrace() in catch block where it will be printed? I am running this application through windows scheduler.
Thanks for advice.
BR
SC

A: Use log4j configure it [here it will configure it self by using log4j.properties or .xml from the classpath ] , initialize it in app startup and use it app wide.

A: Forget about Log4j. That was useful when logging capabilites were not embbeded inside JRE itself. You can configure the logging properties by a means of a logging.properties file (which is provided at JVM start point). Inside the application you can log messages with different levels of severity with or without nested exceptions.
Here is a useful page with example of basic configuration and logging capabilites use.

A: If you want to know for sure that the exception was thrown, don't catch it :) The printStackTrace() writes to stderr. You could run your app though console to read it. If you want to log no matter what without any config or extra libs, you can use java-util.logging which is bundled with the jdk and writes to stdout by default

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make firebase push notification time reliable? I am making a chat application and using firebase messages to deliver the chats to the clients( i have my own server ),but the time to receive the notification varies a lot.Sometimes its instantaneous but sometimes it takes 20-30 minutes.
I searched a lot over the internet and found a lot of people have the issue.
Is there a way to fix this issue?


text:
Q: Deploy Spring Batch to AWS I am new to AWS. I have developed a batch processing application using Spring boot, batch and Quartz for scheduling. It pulls a file from remote FTP server and loads into DB. Can someone pls help, how can I deploy this to AWS?
Will this be on Elastic Beanstalk (EC2) instance with volume mounted to it for downloading the file from FTP and then processing?
Thanks,

A: You should probably look at the official Spring site, Spring Cloud AWS. It is a somewhat involved process, but powerful. If your job is a small one, you may wish to consider a AWS Lambda function instead.


text:
Q: Static and instance method with same name? I have created two methods name sum
one sum method is an instance method this method only takes int ...nums and another sum method is
static method it's takes int x and int ...nums.
My code
public class varArgs{
    int sum(int ...nums){
        int sum = 0;
        for (int num: nums){
            sum += num;
            }
        return sum;
        }
    static int sum(int x, int ...nums){
        int sum = x;
        for (int num: nums){
            sum += num;
            }
         return sum;
        }
    public static void main(String[] args) {
        varArgs obj = new varArgs();
        System.out.println("3 + 4 = "+ obj.sum(3,4));
        System.out.println("7 + 3 + 4 = "+ obj.sum(7, 8,9));
        System.out.println("10 +1+5+6+7= "+obj.sum(10,1,5,6,7));
        System.out.println(obj.sum());

        System.out.println(sum(7, 8, 9, 10));

    }
}

The error I am getting
/storage/emulated/0/varArgs.java:18: error: reference to sum is ambiguous
        System.out.println("3 + 4 = "+ obj.sum(3,4));
                                          ^
  both method sum(int...) in varArgs and method sum(int,int...) in varArgs match
/storage/emulated/0/varArgs.java:19: error: reference to sum is ambiguous
        System.out.println("7 + 3 + 4 = "+ obj.sum(7, 8,9));
                                              ^
  both method sum(int...) in varArgs and method sum(int,int...) in varArgs match
/storage/emulated/0/varArgs.java:20: error: reference to sum is ambiguous
        System.out.println("10 +1+5+6+7= "+obj.sum(10,1,5,6,7));
                                              ^
  both method sum(int...) in varArgs and method sum(int,int...) in varArgs match
/storage/emulated/0/varArgs.java:23: error: reference to sum is ambiguous
        System.out.println(sum(7, 8, 9, 10));
                           ^
  both method sum(int...) in varArgs and method sum(int,int...) in varArgs match
4 errors

How can I solve this Error

A: Just remove the first non-static method and leave this one, you can add the initial number into the other numbers being added
public static int add(int ... nums) {
    int sum = 0;
    for (int num : nums) {
        sum += num;
    }
    return sum;
}

BTW make sure to make your class names start with an uppercase (VarArgs, not varArgs)

A: You have to remove your non-static method and try to using correct name conversion.
static int sum(int x, int ...nums){
    int sum = x;
    for (int num: nums){
        sum += num;
    }
    return sum;
}

public static void main(String[] args) {

[ClassName]  obj = new [ClassName]  ();
System.out.println("3 + 4 = "+ obj.sum(3,4));
 System.out.println("7 + 3 + 4 = "+ obj.sum(7, 8,9));

System.out.println("10 +1+5+6+7= "+obj.sum(10,1,5,6,7));
System.out.println(obj.sum());

// hope you using values inside the sum() method because you created
parameterized method.

 System.out.println(sum(7, 8, 9, 10));

}


text:
Q: Regularized Logistic Regression Cost Function Log(1-p) = inf I am trying to implement logistic regression cost function.
I tested my implementation and it works fine for different datasets.
But when I was trying to solve by new dataset, I realized that the second part of below equation (term2) always is inf. The problem is the value passed to the np.log() function is 0, so it gives me inf. Actually, the answer of sigmoid(hypothesis(x,theta)) = 1.
term1 = -y*(np.log(sigmoid(hypothesis(x,theta))))
term2 = ((1-y)*(np.log(1 - sigmoid(hypothesis(x,theta)))))
infunc1 = term1 - term2
infunc2 = (lambda_*np.sum(theta[1:]**2))/(2*m)
j = (np.sum(infunc1)/m)+infunc2

The first solution I think is to add a very small value to 0 to prevent from inf. But I do not know this is correct or not. (based on this question).
What should I when the answer of multiplying some features to weights is zero and pass this answer to log?
Thanks for any advice.
Happy coding

A: As friends told, you just need to add a very small value to log function:
epsilon = 1e-5
term1 = -y*(np.log(epsilon+sigmoid(hypothesis(x,theta))))
term2 = ((1-y)*(np.log(epsilon+1 - sigmoid(hypothesis(x,theta)))))
infunc1 = term1 - term2
infunc2 = (lambda_*np.sum(theta[1:]**2))/(2*m)
j = (np.sum(infunc1)/m)+infunc2


text:
Q: Access GCP Cloud SQL from AI notebook? Looking for relevant python code to be used in the GCP AI Platform notebook which will be able to query GCP Cloud SQL (specifically Postgresql.) Unfortunately, I haven't found any relevat resources/tutorials from GCP official or even unaffiliated resources.

A: I work on the Developer Relations team for Cloud SQL at Google. The quickest and simplest way to connect to a Cloud SQL instance from an AI Platform Notebook is to use our newly released Cloud SQL Python Connector. To install, run pip install cloud-sql-python-connector[pg8000]. This will also install the pg8000 driver which is used to connect to Postgres.
Then, you can use the following code to get a connection object which you can use to run queries:
conn = connector.connect(
    "project_name:region-name:instance-name",
    "pg8000",
    user="postgres",
    password="password",
    db="db_name"
)

An alternative, which is language-independent, is to download and run the Cloud SQL Auth Proxy in a separate terminal from your notebook.
For either of these solutions, make sure to enable the Cloud SQL Admin API first.


text:
Q: Why do I need LINQ if I use NHibernate-like ORMs? I was reading this SO question but still I am not clear about one specific thing.
If I use NHibernate, why do I need LINQ?
The question in my mind becomes more aggravated when I knew that NHibernate also included LINQ support.
LINQ to NHibernate?
WTF!

A: LINQ is a query language. It allows you to express queries in a way that is not tied in to your persistence layer.
You may be thinking about the LINQ 2 SQL ORM.
Using LINQ in naming the two is causes unfortunate confusions like yours.
nHibernate, EF, LINQ2XML are all LINQ providers - they all allow you to query a data source using the LINQ syntax.

A: First of all LINQ alone is not an ORM. It is a DSL to query the objects irrespective of the source it came from.
So it makes perfect sense that you can use LINQ with Nhibernate too
I believe you misunderstood the LINQ to SQL with plain LINQ.

A: Well, you don't need Linq, you can always do without it, but you might want it.
Linq provides a way to express operations that behave on sets of data that can be queried and where we can then perform other operations based on the state of that data. It's deliberately written so as to be as agnostic as possible whether that data is in-memory collections, XML, database, etc. Ultimately it's always operating on some sort of in-memory object, with some means of converting between in-memory and the ultimate source, though some bindings go further than others in pushing some of the operations down to a different layer. E.g. calling .Count() can end up looking at a Count property, spinning through a collection and keeping a tally, sending a Count(*) query to a database or maybe something else.
ORMs provide a way to have in-memory objects and database rows reflect each other, with changes to one being reflected by changes to the other.
That fits nicely into the "some means of converting" bit above. Hence Linq2SQL, EF and Linq2NHibernate all fulfil both the ORM role and the Linq provider role.
Considering that Linq can work on collections you'd have to be pretty perverse to create an ORM that couldn't support Linq at all (you'd have to design your collections to not implement IEnumerable<T> and hence not work with foreach). More directly supporting it though means you can offer better support. At the very least it should make for more efficient queries. For example if an ORM gave us a means to get a Users object that reflected all rows in a users table, then we would always be able to do:
  int uID = (from u in Users where u.Username == "Alice" select u.ID).FirstOrDefault();

Without direct support for Linq by making Users implement IQueryable<User>, then this would become:
SELECT * FROM Users

Followed by:
while(dataReader.Read())
  yield return ConstructUser(dataReader);

Followed by:
foreach(var user in Users)
  if(user.Username == "Alice")
    return user.ID;
return 0;

Actually, it'd be just slightly worse than that. With direct support the SQL query produced would be:
SELECT TOP 1 id FROM Users WHERE username = 'Alice'

Then the C# becomes equivalent to
return dataReader.Read() ? dataReader.GetInt32(0) : 0;

It should be pretty clear how the greater built-in Linq support of a Linq provider should lead to better operation.
Linq is an in-language feature of C# and VB.NET and can also be used by any .NET language though not always with that same in-language syntax. As such, ever .NET developer should know it, and every C# and VB.NET developer should particularly know it (or they don't know C# or VB.NET) and that's the group NHibernate is designed to be used by, so they can depend on not needing to explain a whole bunch of operations by just implementing them the Linq way. Not supporting it in a .NET library that represents queryable data should be considered a lack of completeness at best; the whole point of an ORM is to make manipulating a database as close to non-DB related operations in the programming language in use, as possible. In .NET that means Linq supprt.

A: Common sense?
There is a difference between an ORM like NHibernate and compiler integrated way to express queries which is use full in many more scenarios.
Or: Usage of LINQ (not LINQ to SQL etc. - the langauge, which is what you talk about though I am not sure you meant what you said) means you dont have to deal with Nhibernate special query syntax.
Or: Anyone NOT using LINQ - regardless of NHibernate or not - de qualifies without good explanation.

A: You don't need it, but you might find it useful.  Bear in mind that Linq, as others have said, is not the same thing as Linq to SQL.  Where I work, we write our own SQL queries to retrieve data, but it's quite common for us to use Linq to manipulate that data in order to serve a specific need.  For instance, you might have a data access method that allows you to retrieve all dogs owned by Dave:
new DogOwnerDal().GetForOwner(id);

If you're only interested in Dave's daschunds for one specific need, and performance isn't that much of an issue, you can use Linq to filter the response for all of Dave's dogs down to the specific data that you need:
new DogOwnerDal().GetForOwner(id).Where(d => d.Breed == DogBreeds.Daschund);

If performance was crucial, you might want to write a specific data access method to retrieve dogs by owner and breed, but in many cases the effort expended to create the new data access method doesn't increase efficiency enough to be worth doing.
In your example, you might want to use NHibernate to retrieve a lump of data, and then use Linq to break that data into lots of individual subsets for some form of processing.  It might well be cheaper to get the data once and use Linq to split it up, instead of repeatedly interrogating the database for different mixtures of the same data.


text:
Q: "Too many indexes on table" error when creating relationships in Microsoft Access 2010 I have tblUsers which has a primary key of UserID.
UserID is used as a foreign key in many tables.  Within a table, it is used as a foreign key for multiple fields (e.g. ObserverID, RecorderID, CheckerID).
I have successfully added relationships (with in the the MS Access 'Relationship' view), where I have table aliases to do the multiple relationships per table:
*tblUser.UserID -> 1 to many -> tblResight.ObserverID
*tblUser_1.UserID -> 1 to many -> tblResight.CheckerID
After creating about 25 relationships with enforcement of referential integrity, when I try to add an additional one, I get the following error:
"The operation failed.  There are too many indexes on table 'tblUsers.' Delete some of the indexes on the table and try the operation again."
I ran the code I found here and it returned that I have 6 indexes on tblUsers.  I know there is a limit of 32 indexes per table.
Am I using the relationship GUI wrong?  Does access create an index for the enforcement of referential integrity any time I create a relationship (especially indexes that wouldn't turn up when I ran the script)?  I'm kind of baffled, any help would be appreciated.

A: Your table has hidden indexes which were created when you defined your relationships.  The names for hidden indexes start with the "~" character.  But the code you found ignores hidden indexes because of this expression:
If Left(tbl.Name, 4) <> "MSys" And Left(tbl.Name, 1) <> "~" Then

You could make that ListIndexes() function include hidden indexes by changing that line to this:
If Left(tbl.Name, 4) <> "MSys" Then

Also, you can verify the total number of indexes for your table with this statement in the Immediate Window:
? CurrentDb.TableDefs("tblUsers").Indexes.Count

A: Okay, after doing some more research, I think I got the answer to this question.  Apparently this is a very common ceiling with access.  I'll sum up this post I found below:
Each table can only have 32 'constraints'. Each index and enforcement of referential integrity (RI) counts towards this 32.  MS Access automatically creates a constraint when you select to enforce RI; you cannot disable this option.
All the code snipets and things I found through google, returned that I had six indexes on the table (and hence I was getting confused).  What I wasn't finding/didn't know was that my 25 relationships were counted against my 32, because I had RI enforced.
My solution to this was to drop RI on the 'lower priority' fields (it pains me to say that), and to 'enforce' it through the data entry forms.
Basically, this is one more reason I'm migrating out access and into PostgreSQL shortly.
If anyone has a better work around, I would love to here it. Thanks.

A: You can get a listing of all indexes, including hidden ones, with the following:
Sub TableListIndexes(sTableName As String, Optional bPrintFields As Boolean = False)

    'Print indexes on a table, and fields in each index.
    'Need to add a reference to Microsoft ADO Ext. [version] for DDL and Security (ADOX).

    Dim cat As New ADOX.Catalog
    Dim idxs As ADOX.Indexes
    Dim idx As ADOX.Index
    Dim col As ADOX.Column
    Dim i As Integer

    Set cat.ActiveConnection = CurrentProject.Connection
    Set idxs = cat.Tables(sTableName).Indexes
    For Each idx In idxs
        Debug.Print i, idx.Name
        If bPrintFields Then
            For Each col In idx.Columns
                Debug.Print , col
            Next
        End If
        i = i + 1
    Next

End Sub

Sub TestTableListIndexes()
    TableListIndexes "tblProject"
End Sub

Which gives
0            PrimaryKey
1            ProjectBusinessUnitID_6D55FF7827CC48648A15A8E576EF02EF
2            ProjectDivisionID_9CAC7B9D8136467B97F9BAA7217EAC38
etc

Note that if you have any multivalue fields in a table each will have a hidden index.

A: It is quite old, but the problem come back very often and this thread comes first in search machines (someone told me ;) )
A good possibility to overcome this problem is to work with a "helper-Table" to link to other Tables.
An example:
A table Article is linked to a lot of other tables for different reasons. Also she may need a lot of foreign keys for itself. Such table get very often out of possible indexes. I do also have three or four of them in my biggest projects.
To almost double the possible RI Joins/indexes you can work with a helper table which has a 1:1 RI Join to the table tblArticle with just the Unique-Identifier as a Field. I do name it the same not with shortletter fk in Front of it as I would do normally. Let's call it tblArticleLinker.
Every table that gets a foreign Key from tblArticle, for example an Order-Position, get its join from the tblArticleLinker.
--> You do not loose an index for all these links, just one to the Linkertable
The only thing you have to make sure, is that you always add the key to the linkertable when saving, otherwise it is not possible to use the Record.
Such a table is - from my experience - much easier to handle than the usual approach to split the fields in different tables. In Queries you do not especially need the helpertable (sometimes queries are faster if you do so), you could link directly to the table. It is just not done automatically as usual.
Tipp: Same approach can also be used to make sure, that only "released" Records can be used by the user. Or to just use as a Hard-Filter. This helps to overcome possible Software-Bugs which do not follow the logic they should.


text:
Q: What is the best way to share files between Xen VM's? Is there some built-in way to share files between Xen guests?  I don't currently need to share the actual images, just some data files.

A: Do you mean between Xen and the host or between different guests?
If guests, I don't think there is something provided but you should probably use NFS as it is the best supported file system that supports a decent number of permissions and attributes but assumes a trusted network.

A: You can also try glusterfs or lustre to share files between Xen guests.

A: I ran into this same issue and my solution was to add an extra virtual drive to each guest which pointed to a shared lvm or device.
So xvda3 was pointed at /dev/md0 in the guest configuration file. You could just as easily use /dev/vg0/lg0 for an logical volume.


text:
Q: Android navigation drawer with section I searched a lot in google but couldn't find something good. I want use navigation drawer like shown in the picture. Look carefully in item 4. when click on this item opens option. How could I do this?
Thank you.

A: SlidingMenu is an Open Source Android library that allows you to easily create applications with sliding menus like in the Google+.
Feel free to use it all you want in your Android apps provided that you cite this project and Demo HERE
Another tool you can use is Navigation Drawer


text:
Q: how can i see output of Console.Error.WriteLine? in vb.net i have some code that looks like this:
Imports System
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Public Class Form1

    Public Sub New1()
        Directory.SetCurrentDirectory("C:\Users\alexluvsdanielle\Desktop\") '"
        Console.WriteLine("Chapter 10 example 10: nested PdfPTables")
        Dim doc As Document = New Document(PageSize.A4, 50, 50, 50, 50)

        Try
            Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("Chap1010.pdf", FileMode.Create))
            doc.Open()
            Dim table As PdfPTable = New PdfPTable(4)
            Dim nested1 As PdfPTable = New PdfPTable(2)
            nested1.AddCell("1.1")
            nested1.AddCell("1.2")
            Dim nested2 As PdfPTable = New PdfPTable(1)
            nested2.AddCell("2.1")
            nested2.AddCell("2.2")
            Dim k As Integer = 0
            While k < 24
                If k = 1 Then
                    table.AddCell(nested1)
                Else
                    If k = 20 Then
                        table.AddCell(nested2)
                    Else
                        table.AddCell("cell " + k)
                    End If
                End If
                System.Threading.Interlocked.Increment(k)
            End While
            table.TotalWidth = 300
            table.WriteSelectedRows(0, -1, 100, 600, writer.DirectContent)
            doc.Close()

        Catch de As Exception
            Console.Error.WriteLine(de.Message)
            Console.Error.WriteLine(de.StackTrace)
        End Try
    End Sub

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

End Class

i would like to see what the console is writing. how do i do this?

A: An alternative is to use the System.Diagnostics.Trace class for these messages.  Then they will show up in your Visual Studio output window, and you can optionally attach other "listeners", like a ConsoleTraceListener (for the console, when it's available) or the TextWriterTraceListener (for log files).  You can even implement your own (like a DatabaseLogTraceListener or MessageBoxTraceListener — be careful with that last one, though).

A: I have piped the output of a WinForms application by starting it from the command line:
myapp.exe > debugfile.txt

I've done that before to redirect the output to a file that I can then read.

A: Why not use Debug.Print ? it will show up in the output window while developing and is much cleaner then a bunch of Message boxes everywhere...

A: There is no Console in a Winforms application.
You will need to use a MessageBox to display your message.
MessageBox.Show(de.Message)

A: I have my own solution:
I created a form with a multiline textbox docked to fill the window size. I created a function to append some text to the textbox. My function looks like this:
Friend Sub ConsoleBox(ByVal message As String)
    If frmConsole.Visible = False Then
        frmConsole.Show()
    End If
    frmConsole.txtConsole.AppendText(message & vbNewLine)
End Sub

Then, instead of using MsgBox("error message") i call my function this way:
ConsoleBox("My error message")

This has worked so far, and replaces all the annoying message boxes whose Accept buttons you must clik every time something goes wrong.
Hope this helps.


text:
Q: How to replace all dots in vi How to replace in vi? There are numerous explanations in Internet, but most of them doesn't contain information about which buttons to press.
If I enter
:s/[.]/[.] <ENTER>

then only one occurrence replaced. Pressing n does only search.
If I enter
:%s/[.]/[.] <ENTER>

it replaces dots in entire file, but in first positions only.
For example, it changes .123pagerank.com to [.]123pagerank.com, ignoring second dot.
How to accomplish?

A: Use the following code for replacing the "dots"
:%s/\./_/g <ENTER>

Here "_" is replaced word.
This works because Vim uses regex, and to represent a dot ., you need to use the backslash \ before the dot, to search in the file for the dot, because a dot without the backslash means any character, therefore the search will include every character, and it would substitute them with _.


text:
Q: unicode method doesn't work in Python3 def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
    csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
    for row in csv_reader:
        yield [unicode(cell, 'utf-8') for cell in row]

filename = '/Users/congminmin/Downloads/kg-temp.csv'
reader = unicode_csv_reader(open(filename))

out_filename = '/Users/congminmin/Downloads/kg-temp.out'
#writer = open(out_filename, "w", "utf-8")
for question, answer in reader:
  print(question+ " " + json.loads(answer)[0]['content'])
  #writer.write(question + " " + answer)

reader.close();

This code works in Python 2.7. But it gives an error message in Python 3.6:
Unresolved reference 'unicode'

How to adapt it to Python 3.6?

A: Simply ensure your data is str, not a bytestring, to begin with, and just use csv.reader without this decoding stuff.
data = utf8_data.decode('utf-8')
for row in csv.reader(data, dialect=csv.excel, ...):
    # ...

A: Python 3 has excellent unicode support already. Any time you open a file in text mode, you can use a specific encoding, or let it default over to UTF-8. There is no longer a difference between str and unicode in Python 3. The latter does not exist, and the former has full unicode support. This simplifies your job greatly since you don't need your setup method at all. You can just iterate over a normal csv.reader.
As an additional note, you should always open files in a with block, so things get cleaned up if there is any kind of exception. As a bonus, your file will get closed automatically when the block ends:
with open(filename) as f:  # The default mode is 'rt', with utf-8 encoding
    for question, answer in csv.reader(f):
        # Do your thing here. Both question and answer are normal strings

This will only work properly if you are sure that each row contains exactly 2 elements. You may be better off doing something more like
with open(filename) as f:  # The default mode is 'rt', with utf-8 encoding
    for row in csv.reader(f):
        if len(row) != 2:
            continue  # Or handle the anomaly by other means
        question, answer = row
        # Do your thing here as before


text:
Q: Scope settings - what does "list" type returns? i am trying to get the string selected from a list (defined in the settings.ini with name [listname]) using this code:
unity::scopes::VariantMap config = settings();
std::string selected_string = config["listname"].get_string();

However it says this:
ScopeBase::run(): unity::LogicException: Variant does not contain a string value:
boost::bad_get: failed value get using boost::get

What does the Variant variable contain? How can i retrieve the selected entry?

A: Ok i just figured it out, the Variant contains an integer, so one should use:
config["listname"].get_int();

And then do the rest in the code (according to values order in settings.ini)


text:
Q: Delete all items from listobox Hi i am try to delete all elements from a list box:
this is my simple listbox:
 <ListBox Margin="0,0,-12,0" ItemsSource="{Binding Items}" Name="listbox" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel  Orientation="Horizontal" Margin="0,0,0,17" >

                            <!--Replace rectangle with image-->
                            <Image Source="{Binding Img}" />
                            <StackPanel Width="311">
                                <TextBlock  Text="{Binding Pos}"
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
</ListBox>

But when i try to delete all elements of list box the error is:
A first chance exception of type 'System.InvalidOperationException' occurred in      System.Windows.dll
System.InvalidOperationException: Operation not supported on read-only collection.
   at System.Windows.Controls.ItemCollection.ClearImpl()
   at System.Windows.PresentationFrameworkCollection`1.Clear()
   at aaaaa.MainPage.Button_Click(Object sender, RoutedEventArgs e)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at     System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs,   Int32 argsTypeIndex, String eventName)

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            listbox.Items.Clear();
        }
        catch (Exception ss) {
            Debug.WriteLine(ss.ToString());
        }
    }

Thank!

A: You cannot clear Items collection if you specify it as Binding. You should clear bound collection instead. Don't forget that your source collection should implement INotifyCollectionChanged

A: You should do your binding using ObservableCollection
// this should be level member instance or something like that just to keep a reference to it.
ObservableCollection<YourClass> itemsSource = new ObservableCollection<YourClass>();
// ... Fill you items collection
listBox.ItemsSource = itemsSource;

// if you need to clear your list, just use this code
itemsSouce.Clear();


text:
Q: Make a one-way switch with a BJT or relay? I've been trying to figure out how to make a one-way switch with some analogue electronics.
i.e.: my first idea was to use a BJT. What I'm trying to find is a design that when the base current is applied the transistor is activated and current flows connector->emitter, but then you can remove the base current and the device stays on. ("one way switch"). I can't figure out how to get that to work.
Or should I be looking at a relay for this?
Thanks!

A: You can't create a latching circuit with only one transistor. You can make one with a thyristor and you can make a thyristor with a PNP and NPN transistor.

simulate this circuit – Schematic created using CircuitLab
Figure 1. (a) A latching circuit using a thyristor. (b) The same circuit made of transistors.
On the second circuit when ON2 is pressed Q2 receives some base current via R4 and this turns on Q2. Q1 now turns on as base current is drawn through the emitter and out through the base into Q2. Q1 then maintains Q2's base current and so the circuit latches.

A: A latching circuit using an ordinary relay is very simple.
You basically wire the relay coil so it is initially energized by a momentary start switch.
Then you wire one of the relay contacts in parallel with the start switch, so they also energize the coil, even with the start switch open.  This way once the coil is energized, it stays energized - latches.
Then to unlatch, you'll need a momentary stop switch to kill the power from the contacts to the coil.
There are of course variants but that's the gist of it.


text:
Q: How to get the video's duration or number of frames in ffmpeg filter I'm writing a filter in ffmpeg and I have to get the duration or number of frames in filter_frame function. But the parameters of "filter_frame" function only consist of AVFilterLink and AVFrame:
static int filter_frame(AVFilterLink* link, AVFrame* in) {
    AVFilterContext* avctx = link->dst;
    ExtractContext* privCtx = (ExtractContext*)avctx->priv;
    AVFilterLink* outlink = avctx->outputs[0];
    //here I want to get the duration of total number of frames:
}

I can't find attributes which is related to duration of frame numbers in either class. I have googles but all answers are about getting duration or frame numbers using ffmpeg.exe, which don't meet my requirements because I have to get them in self-written filter in FFMPEG. Thanks for your help!


text:
Q: Efficiently subtracting many columns I need to perform the following example functions efficiently on a large data set:
df$A1-df$B1
df$A2-df$B2
df$A3-df$B3

Here are the sample data:
> df
  A1 A2 A3 B1 B2 B3
1  3  4  3  1  0  1
2  5  6  6  0  0  1
3  4  5  4  2  2  0
4  4  7  3  1  0  1

Is there a way I can tell R to subtract any column containing B from any column containing A, as long as their numbers are the same?
Thanks!

A: We can subset the columns 'A' and 'B' separately with grep and subtract them
df[grep("A", names(df))] - df[grep("B", names(df))]

or if the positions are known
df[1:3] - df[4:6]

In cases where the columns are not in order, then we order it first
df <- df[gtools::mixedsort(names(df))]

before doing the subtraction


text:
Q: Support for http:// in embedded video URL I have embedded youtube video using URL format
https://www.youtube.com/embed/<video id>?autoplay=1&showinfo=0
in my iOS app using UIWebView. It was working well, but currently its broken and displays a blank screen.
The error is:
Error Domain=WebKitErrorDomain Code=102 "Frame load interrupted"
UserInfo=0x14dbb230 {NSErrorFailingURLKey=https://www.youtube.com/embed/jsTg-rO8JrM?autoplay=1&showinfo=0,
NSErrorFailingURLStringKey=https://www.youtube.com/embed/jsTg-rO8JrM?autoplay=1&showinfo=0,
NSLocalizedDescription=Frame load interrupted}

If I change the URL to use https:// it works fine. So, looks like youtube support for http:// ceased or is limited.
Is there a fix for this issue without me having to submit a new version of the iOS app with the protocol change?


text:
Q: CatalogSearch Rewrite Rule Magento I am trying to use Apache HTTPD to change the rewrite URL for any request to be re-written as catalogsearch/result/?q=
If I put these lines in .htaccess:
RewriteCond %{THE_REQUEST} \ /+catalogsearch/result/\?q=([^&\ ]+)
RewriteRule ^ /q/%1? [L,NE,R=301]
RewriteRule ^q/(.*)$ /catalogsearch/result/?q=$1 [L,NE,QSA]

it always results in a 404 error... (although the url is correctly rewritten).
Can you help me please to solve?


text:
Q: $a_1 + a_2 + a_3 + a_4 + a_5=0$ and $\displaystyle\max_{1\le iLet $a_1,a_2,a_3,a_4,a_5$ be real numbers such that $a_1 + a_2 + a_3 + a_4 + a_5=0$ and $\displaystyle\max_{1\le i<j\le 5} |a_i - a_j|\le1$. Prove that $a_1^2 + a_2^2 + a_3^2 + a_4^2 + a_5^2 \le 10$.
I am not able to understand what $\displaystyle\max_{1\le i<j\le 5} |a_i - a_j|\le1$ means or how to extract useful information from this expression, maybe because I am not mathematically mature enough. How should I approach this problem?

A: The condition gives $$\sum_{1\leq i<j\leq5}(a_i-a_j)^2\leq10$$ or
$$4\sum_{i=1}^5a_i^2-2\sum_{1\leq i<j\leq5}a_ia_j\leq10$$ or
$$5\sum_{i=1}^5a_i^2-\left(\sum_{i=1}^5a_i\right)^2\leq10,$$ which gives
$$\sum_{i=1}^5a_i^2\leq2<10.$$
Because since $(a-b)^2=a^2-2ab+b^2,$ we obtain $$\sum_{1\leq i<j\leq5}(a_i-a_j)^2=(a_1-a_2)^2+(a_1-a_3)^2+(a_1-a_4)^2+(a_1-a_5)^2+$$
$$+(a_2-a_3)^2+(a_2-a_4)^2+(a_2-a_5)^2+(a_3-a_4)^2+(a_3-a_5)^2+(a_4-a_5)^2=$$
$$=4(a_1^2+a_2^2+a_3^2+a_4^2+a_5^2)-$$
$$-2(a_1a_2+a_1a_3+a_1a_4+a_1a_5+a_2a_3+a_2a_4+a_2a_5+a_3a_4+a_3a_5+a_4a_5)=$$
$$=5(a_1^2+a_2^2+a_3^2+a_4^2+a_5^2)-(a_1^2+a_2^2+a_3^2+a_4^2+a_5^2+$$
$$+2(a_1a_2+a_1a_3+a_1a_4+a_1a_5+a_2a_3+a_2a_4+a_2a_5+a_3a_4+a_3a_5+a_4a_5))=$$
$$=5(a_1^2+a_2^2+a_3^2+a_4^2+a_5^2)-(a_1+a_2+a_3+a_4+a_5)^2=5(a_1^2+a_2^2+a_3^2+a_4^2+a_5^2).$$

A: Because of symmetry we can assume that $x:=a_1\leq a_2\leq a_3\leq a_3\leq a_5$.
So $a_i-a_1 \leq 1 \implies a_i\leq x+1$ for each $i=2,3,4,5$.
Since $$5x\leq \underbrace{a_1+a_2+...a_5}_{=0}\leq 5x+4$$ we get $-{4\over 5}\leq x\leq 0$
Since $x\in[-{4\over 5},0]$ we have $a_2,a_3,a_4,a_5\leq 1$ so
Now we have $$a_1^2+...+a_5^2\leq 4+{16\over 25}<10$$

A: The following is a proof for a bound of 1.2: $$$$
Without loss of generality, let $$a_1\le a_2 \le ... \le a_5$$
let $$(i,j)= |a_i - a_j|$$
Now we have $$\sum_{i=1}^{5}{(i,i+1)} = \sum_{i=1}^{4}{(i,i+1)} + (5,1) = 2 \times (1,5) < 2 $$ where i is taken mod 5.
Also, $$\sum_{i=1}^{5}{(i,i+2)} = (1,3)+(2,4)+(3,5)+(1,4)+(2,5) \le 4(1,5) \le 4 $$ (this is clear from drawing the 5 numbers on a number line and drawing segments.
So now we have
$$\sum_{1\le i < j \le 5} (i,j) \le 6$$
Note that $$0\le(i,j)\le 1 \implies (i,j)^2 \le (i,j),$$
so $$\sum_{1\le i < j \le 5} (i,j)^2 \le 6 \implies 4\sum_{i=1}^{5}{a_i}^2-2\sum_{1\le i < j \le 5}{a_i a_j} \le 6$$
By squaring the first condition,
$$\sum_{i=1}^{5}{a_i}^2 = -2\sum_{1\le i < j \le 5}{a_i a_j}$$
So substituting this, we find that $$5\sum_{i=1}^{5}{a_i}^2\le 6$$
which gives the desired bound of 1.2. $$$$Careful analysis of the solution shows that $${0.4, 0.4, 0.4, -0.6, -0.6}$$ and $${0.2, 0.2, 0.2, 0.2, -0.8}$$ as well as negation of each term and permutations are the only equality cases.

A: What the question means is that absolute value of the difference between any two of those five numbers is less than or equal to $1$.
Since the sum of those five numbers is equal to zero, this should necessarily mean that all five numbers are in the interval $(-1, 1)$.
Hence the value of the sum of their square can never be more than $5$, which solves the problem.
Note - I believe that you may have mis-typed the question since the bound is too weak!

A:
$\max_{1\le i<j\le 5} |a_i - a_j|\le1$

means
$|a_x - a_y|\leq\max_{1\le i<j\le 5}|a_i - a_j|\le1$
for any $x,y$ (by definition of the max function)
See if you can solve it from there
Hint:

 Since one of the $a_i$s is not positive, and one is not negative (otherwise they can't sum to $0$), what is the largest any $a_i$ can be? What about the smallest value?

(Edit  I think $a_1^2 + a_2^2 + a_3^2 + a_4^2 + a_5^2 \le 1.2$ is true as well - is that what you meant?)
I have a proof of the $\le1.2$ if you want it
Consider $$\sum_{i<j}(a_i-a_j)^2=\sum_{i<j}(a_i-a_j)^2+(\sum a_i)^2=5\sum
a_i^2$$
Now assume $a_1\leq a_2\leq\ldots\leq a_5$. Note that $(c-a)^2\geq(c-b)^2+(b-a)^2$ if $c\geq b\geq a$ (think about this geometrically if that helps). Applying this to the LHS gives us
$$\begin{align}
6\geq
&(a_5-a_4)^2+(a_4-a_3)^2+(a_3-a_2)^2+(a_2-a_1)^2+\\
&(a_5-a_4)^2+(a_4-a_2)^2+(a_2-a_1)^2+\\
&(a_5-a_4)^2+(a_4-a_1)^2+\\
&(a_5-a_3)^2+(a_3-a_1)^2+\\
&(a_5-a_2)^2+(a_2-a_1)^2+\\
&(a_5-a_1)^2\geq\\
&\sum_{i<j}(a_i-a_j)^2
\end{align}$$
since each line is at most $1$. Therefore $6\geq5\sum
a_i^2$ as required (also this is attainable, e.g $(0.4,0.4,0.4,-0.6,-0.6)$)


text:
Q: To-Do list which could read the task on time I'm looking for the application for OS X (Maverick), which could merge two tasks for me.
One is the TO-DO list just like "Reminders".
The second one is more tricky - I wish "Reminders" to read task on loud as soon as the task will be close to specific time frame.
I use similar functionality in the OSX's clock, which tells me each 15 minutes what time is it.
Do you have any suggestions?


text:
Q: Typescript in react JS I am using react-select-async-paginate:
async function loadOptions(search, loadedOptions, { page }) {
  const response = await fetch(`/awesome-api-url/?search=${search}&page=${page}`);
  const responseJSON = await response.json();

  return {
    options: responseJSON.results,
    hasMore: responseJSON.has_more,
    additional: {
      page: page + 1,
    },
  };
}

<AsyncPaginate
  value={value}
  loadOptions={loadOptions}
  onChange={setValue}
  additional={{
    page: 1,
  }}
/>

How to apply the typescript for this code: (search, loadedOptions, { page }) taking into account that these  are the types?
demo: https://codesandbox.io/s/react-select-async-paginate-forked-qiizl?file=/src/SelectAsyncPaginate.tsx

A: As you can see loadOptions type is LoadOptions<OptionType, Additional>.
That's how you should type your loadOptions function
const loadOptions: LoadOptions<any, {page: number}> = ...

You should replace any with the actual option's type (you can figure it from the API response)
https://codesandbox.io/s/react-select-async-paginate-forked-00k7m?file=/src/SelectAsyncPaginate.tsx


text:
Q: Onclick SyntaxError: identifier starts immediately after numeric literal I have an onclick function:
onclick='deleteRow(".$bon['Werkbonnummer'].");updateVak(".$bon['Stellingvak'].");)'`

Implemented in:

echo "<button class='delete' onclick='deleteRow(".$bon['Werkbonnummer'].");updateVak(".$bon['Stellingvak'].");)'>Klaar</button>
";`

When I push the button, FireBug gives me this error:
SyntaxError: identifier starts immediately after numeric literal
deleteRow(71);updateVak(4D);)`

`-----------------------^

Can somebody point out what I did wrong?

A: 4D is not a valid number. If you want it to be handled as a string, you must surround it with quotes ("4D"). If you want it to be handled as an hex number, use 0x4D.


text:
Q: Construct a function $f\in C^{\infty}_{0}(\mathbb{R}^2)$ The question request that :
Let $A=[-1,1]\times[-1,1]$, B be a open ball centered at the origin with radius 2. Construct a function $f\in C^{\infty}_{0}(\mathbb{R}^2)$ such that $f(x)=1$ for $x\in A$, $f(x)=0$ for $x\in B^{c}$, and $0<f<1$ on $B\setminus A$.
I attempted to mimic what I learned in constructing a bump function by considering $f(x)=e^{-x^2}$. But then I ran into a trouble that the required function is not radial symmetry. Can anyone give some hints for solving this question? By the way, is there a general method for constructing a smooth function of compact support for arbitrary spaces?

A: Let $A_\epsilon = [-1-\epsilon, 1+\epsilon] \times [-1-\epsilon, 1+\epsilon]$ and let $\psi_\epsilon \in C_c^\infty(\mathbb R)$ such that $\psi_\epsilon(x) = 0$ for $|x|>\epsilon$ and $\int \psi_\epsilon = 1$.
Now just take $\epsilon$ small enough for $A_{2\epsilon} \subset B$ and let $f = \chi_{A_\epsilon} * (\psi_\epsilon \otimes \psi_\epsilon)$.

A: Take $A_1$, $A_2$ two disjoint closed sets. Assume that we found $\phi_1$,$\phi_2$ smooth on $\mathbb{R}^2$ , $\phi_i\ge 0$, $\phi_i^{-1}(0)=A_i$, $i=1,2$. Then we can take
$$f=\frac{\phi_2}{\phi_1+\phi_2}$$
To construct $\phi_1$, $\phi_2$ for our sets, use
$$\chi(t)=\begin{cases} \exp({-\frac{1}{t}} )&\text{ for } t>0 \\
                        0 &\text{ for } t\le0 \end{cases} $$
Then $$\phi_1(x_1,x_2)= 1 - (1-\chi(1-x_1^2))(1-\chi(1-x_2^2))=\\
= \chi(1-x_1^2)+\chi(1-x_2^2)-\chi(1-x_1^2)\chi(1-x_2^2)\\
\phi_2(x)= \chi(4-\|x\|^2)$$
So
$$f(x_1,x_2)= \frac{\chi(4-\|x\|^2)}{\chi(1-x_1^2)+\chi(1-x_2^2)-\chi(1-x_1^2)\chi(1-x_2^2)+\chi(4-\|x\|^2)}$$

A: Let $g\in C^\infty(\mathbb R)$ satisfy $g=1$ on $[-1,1]$ and $0<g<1$ everywhere else. Note that $g(x)g(y)=1$ on $ [-1,1]^2$ and $0<g(x)g(y)<1$ everwhere else.
Writing $z=(x,y),$ choose $h\in C^\infty(\mathbb R^2)$ that satisfies $h(z)=1$ for $0\le |z| \le \sqrt 2,$ $h(z)=0$ for $|z| \ge 2,$ and $0<h(z)<1$ in between. Note that $h=1$ on on $ [-1,1]^2.$
The function $f(x,y)= g(x)g(y)h(z)$ then does the job.


text:
Q: Stacked bar chart using pandas DataFrame and vbar in Bokeh plot I am looking for bokeh version (using vbar) of the following plot in matplotlib:
import pandas as pd
%matplotlib inline

data = [
    ['201720', 'cat1', 20],
    ['201720', 'cat2', 30],
    ['201720', 'cat3', 40],
    ['201721', 'cat1', 20],
    ['201721', 'cat2', 0],
    ['201721', 'cat3', 40],
    ['201722', 'cat1', 50],
    ['201722', 'cat2', 60],
    ['201722', 'cat3', 10],
]

df = pd.DataFrame(data, columns=['week', 'category', 'count'])

pt = df.pivot('week', 'category', 'count')

pt.plot(kind='bar', stacked=True)

I tried googling but I could not find a simple solution.

A: I think the following code is the best I can do as of now:
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource
from bokeh.models.ranges import FactorRange
import pandas as pd

data = [
    ['201720', 'cat1', 20],
    ['201720', 'cat2', 30],
    ['201720', 'cat3', 40],
    ['201721', 'cat1', 20],
    ['201721', 'cat2', 0],
    ['201721', 'cat3', 40],
    ['201722', 'cat1', 50],
    ['201722', 'cat2', 60],
    ['201722', 'cat3', 10],
]

df = pd.DataFrame(data, columns=['week', 'category', 'count'])

pt = df.pivot('week', 'category', 'count')

pt = pt.cumsum(axis=1)

output_file("lines.html", title='Dashboard')

p = figure(title="count",
           x_axis_label='week', y_axis_label='category',
           x_range = FactorRange(factors=list(pt.index)),
           plot_height=300, plot_width=500)

p.vbar(x=pt.index, bottom=0, top=pt.cat1, width=0.2, color='red', legend='cat1')
p.vbar(x=pt.index, bottom=pt.cat1, top=pt.cat2, width=0.2, color='blue', legend='cat2')
p.vbar(x=pt.index, bottom=pt.cat2, top=pt.cat3, width=0.2, color='green', legend='cat3')

show(p)

The resulting plot looks like:

Including vbar(), Bokeh plotting methods do not seem to support 'vectorized input' or maybe I am missing something. Is this really the simplest way?


text:
Q: How to create a React Link to make API call through click handler quick question. Does anyone know how to construct a call to a click/event handler for the react-router <Link> component. If I have this API data return in searchData and mapping over the values how do you call an event Handler and pass {key} and {v} to the click handler?
<Link to={`${key}/${v}`}>
{v}
</Link>))

A: When defined without a specific component prop, the <Link> component in React Router defaults as a common anchor: . You can pass any prop to this component by defining the props on the <Link> component. You can pass the key and v variables in the function you define on the onClick prop.
For example:
<Link to={`${key}/${v}`} onClick={e => onClickHandler(e, key, v)}>

{v}

</Link>

Here is a link to the <Link> component definition to see how it works:
https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/Link.js


text:
Q: Why has object been created without importing class? I came across some java code where the following statement was present.
com.myproject.bar.Foo foo = new com.myproject.bar.Foo();

The class com.myproject.bar.Foo has not been imported into the class but an object of Foo is created in the class where this statement is written.
Why has such an implementation been done? Are there any advantages of using such an implementation over doing an import of the class Foo?

A: It's instantiation with the fully-qualified name of the class.
com.myproject.bar.Foo foo = new com.myproject.bar.Foo();

This doesn't require to add an import statement, because you've already told the compiler which is the package of the class you want to instantiate.
Sometimes this is used when there are several classes with one and the same simple name.
If you'd like to do this:
Foo foo = new Foo();

then you will have to import the class:
import com.myproject.bar.Foo;

A: An import statement just makes the type available by its short name without specifying the package. That's all it does. It's not like the class can't be used without an import.
Usually it's clearer to use an import instead, but sometimes that's not possible - you may want to use two classes both called Foo from different packages with the same class, for example. (This is most common when you've got two representations of the same entity - an API representation and a storage representation, for example.)
Without knowing what the real code looks like, we can't tell whether that was the case here, or whether an import would have been fine. If it can work, an import is usually more readable.

A: If you address the class with fully qualified name such as com.myproject.bar.Foo,  you need to specify it every time when you try to access that class.
But in case of import, you dont need to.
That's one of the advantages.

A: There is no special advantages.
But useful in case if two classes have same class name and belongs to different packages then you need to specify the fully qualified package name to differentiate both while using them in a Class.
Consider 2 classes
com.myproject.bar.Foo
com.myproject.bar.innerbar.Foo

Now in some other class you are going to instatiate like
Foo foo = new Foo();

Which Foo to import now?
To avoid that ambiguity, we need to specify the full package name.

A: com.myproject.bar.Foo is absolute class name.
Foo is just the Class name(relative) and it can be in any package, so to specify the package, import statements are used.
In cases where you have more than one class with same name, you have to use the absolute class name in your code to distinguish between the duplicate names. Example com.Foo and org.Foo then you use Foo for com.Foo and org.Foo for org.Foo.


text:
Q: Visual Studio 2013 Unit Test error: Could not load Microsoft.VisualStudio.TestPlatform.ObjectModel.dll For some reason the unit tests from a test project in VS 2013 (w/Update 3) doesn't show up.
Could not load file or assembly
'file:///C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 12.0\
COMMON7\IDE\COMMONEXTENSIONS\MICROSOFT\TESTWINDOW\
Microsoft.VisualStudio.TestPlatform.ObjectModel.dll'
or one of its dependencies. Unspecified error (Exception
from HRESULT: 0x80004005 (E_FAIL))```

When checking the folder, the file is there.
My Chutzpah tests in another project in the same solution shows up. Couldn't find much info on this error when searching. Anyone had similar issues or know how to resolve this?

A: In my case  , I have noticed in the Test Project's app.config file, that more than one assemblyIdentity where enclosed as part of  tag, which should not be.
Improper configuration
<dependentAssembly>
<assemblyIdentity name="WindowsAzureTelemetryEvents" publicKeyToken="31BF3856AD364E35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.4.0.0" newVersion="2.4.0.0" />
<assemblyIdentity name="WindowsAzureEventSource" publicKeyToken="31BF3856AD364E35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.4.0.0" newVersion="2.4.0.0" />
</dependentAssembly>

Proper Configuration
<dependentAssembly>
<assemblyIdentity name="WindowsAzureTelemetryEvents" publicKeyToken="31BF3856AD364E35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.4.0.0" newVersion="2.4.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WindowsAzureEventSource" publicKeyToken="31BF3856AD364E35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.4.0.0" newVersion="2.4.0.0" />
</dependentAssembly>

A: After hours of trial and error, I noticed there was a app.config file in the test project for some reason. Removing this worked :)

A: Related answer:  I was trying to be clever and use the XML directive thingey to comment out large sections of app.config that included other comments.  Don't use <?... ?> directives in app.config.


text:
Q: Gist: How are images uploaded to a gist? Here is the image file:
https://gist.github.com/mbostock/5503544#file-thumbnail-png
I tried to drag-and-drop the image file in the edit mode of a gist.  That didn't seem to work in Chrome and FireFox.
Update: After back and forth emails with GitHub, this feature (drag-and-drop binary files, including images) isn't supported.

A: I was looking for answer for the same question, here is what I just found:

*

*You can clone your gist as a git repository and add your picture, then push to origin. See loading-thumbnail-into-gist-for.

*There is a script written to do this: hecticjeff/gist-img.
I have not tried the above solutions yet, but pretty sure they should work. I did try using defunkt/gist to update my gist with a png but ended up displaying a binary file in my gist.

A: Clone gist with SSH:
$ git clone git@gist.github.com:<hash>.git mygist

HTTP clone worked fine, but ran into HTTP authentication problems at git push.

A: *

*Create a gist or reuse one of your gists.

*Clone your gist:
git clone https://gist.github.com/<hash>.git

*Add your image to your gist's repository:
git add my-image.jpg

*Commit the image:
git commit -m "adding my image to my gist"

*Update gist by pushing you modifications:
git push origin master

A: I was looking for an answer to this same question too, in my case in order to be able to upload PDF files. I had trouble with gist-img (mentioned in another answer to this question). I searched some more and discovered gistup, which worked perfectly, the first time I tried it. It uses node and npm, so it should work on most major operating systems.

A: How to put images in your Gist url:

*

*upload your image to a place like imgur.com for free, then get the hot-link.

*Add a file and give it a markdown extension .md and use markdown image syntax:

![alt text here](https://URL)

*?????

*Profit

A: With a little creativity you can achieve this faster than cloning. To drag/drop:

*

*Create the Gist

*Drag an image into the comment field below. This will auto-upload your image file to https://user-images.githubusercontent.com and insert  markdown code in the comment field to display the image.

*Copy this markdown code to your gist

Note: It is not required that you submit the comment.
Live example

A: uploading the image somewhere and using the HTML <img> tag works for me

A:
(2013) Update: After back and forth emails with GitHub, this feature (drag-and-drop binary files, including images) isn't supported.

Update Sept. 2021

File attachment support in Markdown for gists
You can now add images and videos to Markdown files in gists by pasting them into the Markdown body or selecting them from the dialog at the bottom of the Markdown file.
For information on supported file types, see the documentation.

As announced by tweet

If you checkout https://gist.github.com, you can now easily include images and videos in your markdown files.
Paste the image in or browse your file system to attach. Let us know what you think.

A: This above answer is correct but added a bit more detail...

*

*Create the Gist AND SAVE IT

*Since it is saved a comment field will show at the bottom.

*Drag an image into the comment field below. This will auto-upload your image file to https://user-images.githubusercontent.com and insert markdown code in the comment field to display the image.

*You can check that this code works by toggling to the preview tab at the top of the comment.

*Copy this code and EDIT your gist and paste the code

A: If you upload an image, try these steps:

*

*Convert your image into DataURI. For example here on duri.me

*Then this string insert to GIST as a text file

If you want to convert back, there are several options. For example, this:
Converting data URI to image data


text:
Q: Reading HTML page using Libreoffice Basic I'm new to LibreOffice Basic. I'm trying to write a macro in LibreOffice Calc that will read the name of a noble House of Westeros from a cell (e.g. Stark), and output the Words of that House by looking it up on the relevant page on A Wiki of Ice and Fire. It should work like this:

Here is the pseudocode:
Read HouseName from column A
Open HtmlFile at "http://www.awoiaf.westeros.org/index.php/House_" & HouseName
Iterate through HtmlFile to find line which begins "<table class="infobox infobox-body"" // Finds the info box for the page.
Read Each Row in the table until Row begins Words
Read the contents of the next  tag, and return this as a string.

My problem is with the second line, I don't know how to read a HTML file. How should I do this in LibreOffice Basic?

A: There are two mainly issues with this.
1. Performance
Your UDF will need get the HTTP resource in every cell, in which it is stored.
2. HTML
Unfortunately there is no HTML parser in OpenOffice or LibreOffice. There is only a XML parser. Thats why we cannot parse HTML directly with the UDF.
This will work, but slow and not very universal:
Public Function FETCHHOUSE(sHouse as String) as String

   sURL = "http://awoiaf.westeros.org/index.php/House_" & sHouse

   oSimpleFileAccess = createUNOService ("com.sun.star.ucb.SimpleFileAccess")
   oInpDataStream = createUNOService ("com.sun.star.io.TextInputStream")
   on error goto falseHouseName
   oInpDataStream.setInputStream(oSimpleFileAccess.openFileRead(sUrl))
   on error goto 0
   dim delimiters() as long
   sContent = oInpDataStream.readString(delimiters(), false)

   lStartPos = instr(1, sContent, "<table class=" & chr(34) & "infobox infobox-body" )
   if lStartPos = 0 then
     FETCHHOUSE = "no infobox on page"
     exit function
   end if
   lEndPos = instr(lStartPos, sContent, "
")
   sTable = mid(sContent, lStartPos, lEndPos-lStartPos + 8)

   lStartPos = instr(1, sTable, "Words" )
   if lStartPos = 0 then
     FETCHHOUSE = "no Words on page"
     exit function
   end if
   lEndPos = instr(lStartPos, sTable, "
")
   sRow = mid(sTable, lStartPos, lEndPos-lStartPos + 5)

   oTextSearch = CreateUnoService("com.sun.star.util.TextSearch")
   oOptions = CreateUnoStruct("com.sun.star.util.SearchOptions")
   oOptions.algorithmType = com.sun.star.util.SearchAlgorithms.REGEXP
   oOptions.searchString = "<td[^<]*>"
   oTextSearch.setOptions(oOptions)
   oFound = oTextSearch.searchForward(sRow, 0, Len(sRow))
   If  oFound.subRegExpressions = 0 then
     FETCHHOUSE = "Words header but no Words content on page"
     exit function
   end if
   lStartPos = oFound.endOffset(0) + 1
   lEndPos = instr(lStartPos, sRow, "	")
   sWords = mid(sRow, lStartPos, lEndPos-lStartPos)

   FETCHHOUSE = sWords
   exit function

   falseHouseName:
   FETCHHOUSE = "House name does not exist"

End Function

The better way would be, if you could get the needed informations from a Web API that would offered from the Wiki. You know the people behind the Wiki? If so, then you could place this there as a suggestion.
Greetings
Axel


text:
Q: Is there a way to crack a 129 character length hash? I was given a 129 character length hash ( probably whirlwind or SHA-512) to decrypt. I have tried cracking it using the whirlpooldeep and hashcat tools (without wordlists, i.e dictionary attack) but with no success. I'm sorry for the ambiguous question but this is all the information I have about my current task. Any suggestion would be gladly appreciated

A: I assume this task is feasible because whoever gave you the hash has prepared it on purpose in a way so you have a chance to crack it. If this is not the case, you have no chance at current computer performance and will not within the next few decades.
So, assuming it is feasible, e.g. because the hash is of some short data like less than 10 bytes:
You are probably making a mistake in how you compare the hashes. The hash should not be of length 129. It should be of length 128. That you see a file with 129 bytes is probably because there is a line feed (\n) at the end of the file.
Moreover, you should, for performance, not compare the hashes in hexadecimal format (length 128), but instead in binary format (length 64).

A: A rainbow table seems to be the perfect tool for your scenario.
There is a software called RainbowCrack to do this sort of reversing a hash. There should be rainbow tables available for SHA-512, which should be, roughly estimated, about 1TB in size (for finding original data of length up to 9 bytes).
Using this kind of hash reversal is likely to take you a day or two to get into the matter and understand it, and if it's feasible, after downloading the 1TB, you are likely to get the result in less than a day.
Before you start all this, I would ask the source of your hash how long the data is that you are searching for. This could easily end up being a kid's joke, e.g. that your source hashed 512bit of random data, in which case you would have absolutely no chance and you would waste your time.


text:
Q: PagedList MVC to get data from db based on pagesize i added PagedList in my project, i have a search view, which basically calls a function to get values from database, my Pagedlist is working fine, but i am not sure if this gets whole data from database or only based on pageSize. For example i have total 30 records, and i added pagesize as 10, so view will show 10 records at a time and 3 pages. Now this PagedList get all 30 values, or only get 10 first time, then if user click on page 2 it gets next 10 records.
Because lets say i have thousand records, so i dont want system to load all of them, i just want to load it according to pagesize , and when user click on second page it gets next records, hope my point is clear, below is my code:
View:
@model PagedList.IPagedList<BackendIntegration.Models.VendorAllTransactions>
@using PagedList.Mvc;
@if (Model != null)
{

                @Html.DisplayName("Date")

                @Html.DisplayName("Type")

                @Html.DisplayName("Amount")

                @Html.DisplayName("User Name")

                @Html.DisplayName("Vendor Name")

                @Html.DisplayName("POS ID")

        @foreach (var trans in Model)
        {

                    @Html.DisplayFor(model => trans.Date)

                    @Html.DisplayFor(model => trans.TypeDesc)

                    @Html.DisplayFor(model => trans.Amount)

                    @Html.DisplayFor(model => trans.UserName)

                    @Html.DisplayFor(model => trans.VendorName)

                    @Html.DisplayFor(model => trans.POS_ID)

        }

        Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
        of @Model.PageCount

        @Html.PagedListPager(Model, page => Url.Action("VendorAllTransactions", new { page }))

}

Controller:
public ActionResult VendorAllTransactions(VendorAllTransactionView vw, int? page)
        {
            int pageSize = 10;
            int pageIndex = 1;
            pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;

            IPagedList<VendorAllTransactions> model = null;

            try
            {
                model = sales.VendorAllTransactions(vw).ToPagedList(pageIndex, pageSize);
            }
            catch (Exception exp)
            {
                ModelState.AddModelError("", exp.Message);
            }
            return View(model);
        }

sales.VendorAllTransactions(vw) this call a fucntion with query, which will return records. But this clearly returning all the records. Is Pagedlist get only required number of rows(pagesize) or it gets everything.???
Please advise.
Thanks


text:
Q: Changing Case of a String I'm new to C and am trying to write a simple function that can take in a string (or array of characters) and convert its case based on the following rules:

*

*The first character should be uppercase.

*The remaining characters should be lowercase.

I've written code, but I'm running into segmentation fault errors, and I'm baffled as to what's going wrong. Here's what I've written:
void myFunction(char name[]) {

  printf("Before: %s", name);

  name[0] = toupper(name[0]); // This line seems to cause problems.

  // Convert the other letters to lowercase if they aren't already.
  for(int i = 1; name[i] != '\0'; i++) {
    if(islower(name[i])) {
      name[i] = tolower(name[i]);
    } else {
      name[i] = name[i];
    }
  }
  name[i] = '\0';

  printf("After: %s", name);
}

void my_caller(*name1) {
  printf("Name before changing case: %s\n", name1);
  myFunction(name1);
  printf("Name after changing case: %s\n", name1);
}

// In another .c file.
int main() {
  char name1[] = "adam";
  my_caller(&name1);
}

In myFunction, if I comment out the lines except for
name[0] = toupper(name[0]);

I still get the segmentation fault. So that would suggest that this line is (one of) the culprits, but I don't understand why. I want to convert the letter to uppercase and put it back into the string.

A: To start with, having a function definition like
 void my_caller(name1)

is problematic, as missing type (used to be, now obsolete rule) default to int. You want this to be a char *. not int.
You need to change it to
  void my_caller(char * name1) {....

Moreover, you need to call the function as my_caller(name1);, passing an array is the same as passing a pointer to the first element of the array.
Also, you don't pass the address of the array (check the types if you're in confusion) while calling the function.
That said, inside myFunction(), the scope of i is limited to the for loop only, but you want to use that beyond the scope (to null-terminate), so you got to declare i in the function block scope.
Moral of the story: Turn up the compiler warning / error settings, and pay close attention to the messages emitted by the compiler. They are there for a reason.

Note: After making these changes, code works as expected.


text:
Q: Concatenate return type for a crosstab() query from another query I can't post my original query here, it's too complex. So I am explaining my problem with a sample query:
Working pivot query:
Select pivot.* from public.crosstab($$ select 'na' as na, 1 as analysis,100 as value
 union all select 'ba' as na, 2 as analysis,100 as value $$,
 $$ VALUES ('1'), ('2')$$
) as pivot (na text, "1" integer,"2" integer)

But I would like to use it like this:
Select pivot.* from public.crosstab($$ select 'na' as na, 1 as analysis,100 as value
 union all select 'ba' as na, 2 as analysis,100 as value $$,
 $$ VALUES ('1'), ('2')$$
) as pivot select '(na text,"1" integer,"2" integer)'
I want to add the return type from a query (bold emphasis). How to do that?

A: Clear test case
First I formated and clarified your example:
SELECT * FROM public.crosstab(
   $$VALUES ('na', 1, 100)   -- VALUES expression does the same, shorter
          , ('ba', 2, 300)$$ -- no column names needed (ignored anyway)
  ,$$VALUES ('1'), ('2')$$
   ) AS pivot (na text, co11 int, col2 int)  -- sane column names

Input table:
col1  key  val
---------------
na    1    100
ba    2    300

Output table
na    co11    col2
--------------------
na    100     <NULL>
ba    <NULL>  300

You can pick output column names freely, no need to stick to unwieldy names like "1", "2". Only the data types have to match.
Dynamic return type
You cannot provide the column definition list from a query. We have had many similar requests here on SO. They all clash with the nature of SQL, which does not accept a return type "after the fact". Must be declared with the query, at least at the time of executing it.
You would have to build the crosstab() query with the output of the SELECT query you want to add in your 2nd example. Two round trips to the server.
But we can read a well know type from the system catalogs - that's what SELECT * FROM tbl does after all. I have tried hard and implemented what I found in this related answer:

*

*Dynamic alternative to pivot with CASE and GROUP BY
My function crosstab_n() is probably your best shot. Read the linked answer!
It's a wrapper around crosstab() that takes the query string (just like crosstab()) and an additional polymorphic parameter that provides the return type. We still cannot pass the return type on the fly. The only acceptable way for SQL is to read it from the system catalog. So we install a composite type "on the fly" by way of creating a temporary table:
CREATE TEMP TABLE my_pivot (na text, col1 int, col2 int);

SELECT * FROM crosstab_n(
    $$VALUES ('na', 1, 100), ('ba', 2, 100)$$
    ,NULL::my_pivot
    );

Result as above. Voilà!
If you want the temp table to last for the transaction only, add ON COMMIT DROP to it. Both statements must be executed in one transaction then.  Details:

*

*Select from a table variable


text:
Q: Why layer.get_weights() is returning list of length 1 and 4? I am trying to get the weights and biases of all convolutional layers of resnet50 model for one of my assignments. I learned that we can use the function layer.get_weights() to get the weight and bias. This will return a list of which contains two elements weight of the layer stored at layer.get_weights()[0] and the bias is stored at layer.get_weights()[1]. Here is the code which I used.
import tensorflow as to
import source
from source import models
from source.utils.image import read_image_bgr, preprocess_image, resize_image
from source.utils.visualization import draw_box, draw_caption
from source.utils.colors import label_color
from source.models import retinanet
import warnings
warnings.filterwarnings("ignore")
from tensorflow import ConfigProto

import numpy as np
import os
import argparse
import keras
from keras.layers import Input,Conv2D,MaxPooling2D,UpSampling2D, Activation, Dropout
from keras.models import Model

ap = argparse.ArgumentParser()
ap.add_argument("-weight", "--weight_file", type=str,default="trained_model.h5",help="Path to the weights file")
ap.add_argument("-backbone", "--backbone", type=str, default="resnet50",help="Backbone model name")
args = vars(ap.parse_args())

#fetching a tensorflow session
def get_session():
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    return tf.Session(config=config)

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.keras.backend.set_session(tf.Session(config=config))
keras.backend.tensorflow_backend.set_session(get_session())

model = str(args.get("weight_file", False))
backbone = str(args.get("backbone", False))
model = models.load_model(str(model), backbone_name=str(backbone))

#model is the resnet50 model
for layer in model.layers:
    print('layer name', layer.name)
    we = layer.get_weights()
    print('len(we)',len(we))

But in my case, I am getting length 1 for some of the cases and length 4 for other cases which is different from what it is expected. I am really confused at this point. If anybody has any idea and suggestions will be really helpful.
Thanks in advance.

A: The get_weights() function returns both trainable and not trainable parameters of a layer. The BatchNormalization layer has 4 parameters, which explains the 4 length outputs (since Resnet blocks have batchnorm). As far as I am aware, ResNet models do not use the bias term in the convolutional layers because of the batchnorm, which would explain the length 1 outputs.


text:
Q: How to URL-encode ParsedUrlQuery? I'm migrating from vanilla React to NextJS. Before the change, I got my URL query params (the part after the ? in the URL) through react-router's useSearchParams hook, which returns URLSearchParams.
NextJS's router, however, returns the query params in the form of ParsedUrlQuery.
I want to forward these ParsedUrlQuery parameters to my (Express) backend server, again in the form of URL query params (the same form they are shown in the website's URL) but I can't figure out how to URL-encode them.
Here is my old code. I need to replace URLSearchParams for ParsedUrlQuery. Or alternatively, transform the ParsedUrlQuery into URLSearchParams  How can I do that?
export async function searchResources(searchParams: URLSearchParams): Promise<SearchResourcesResponse> {
    const response = await fetchWithTimeout(
        process.env.NEXT_PUBLIC_TUTHUB_SERVER_URL + '/resources?' + searchParams
    )
    const resources = await response.json();
    return resources;
};

A: EDIT
Simplest method: use the the encode/stringify method included in the querystring lib
import { encode } from 'querystring'

// From useRouter:
// const { query } = useRouter()

// From GetServerSidePropContext
// const { query } = ctx

const urlQueryString = encode(query)
const searchParams = new URLSearchParams(urlQueryString )

OLD ANSWER
Or you can use these helper methods to transform the query params from one type to another in a very simple way.
export function parsedUrlQueryToURLSearchParams(
  query: ParsedUrlQuery
): URLSearchParams {
  const searchParams = new URLSearchParams()
  for (const [key, value] of Object.entries(query)) {
    if (!value) continue
    if (Array.isArray(value)) {
      value.forEach((element) => {
        searchParams.append(key, element)
      })
    } else {
      searchParams.append(key, value)
    }
  }
  return searchParams
}

export function urlSearchParamsToParsedUrlQuery(
  searchParams: URLSearchParams
): ParsedUrlQuery {
  const query: ParsedUrlQuery = {}
  for (var [key, value] of searchParams.entries()) {
    query[key] = value
  }
  return query
}

If you want, you can also create another helper method to transform the query object from next/router to an encoded string
export function parsedUrlQueryToURLString(query: ParsedUrlQuery): string {
  const params = []
  for (const [key, value] of Object.entries(query)) {
    if (!value) continue
    if (Array.isArray(value)) {
      value.forEach((element) => {
        params.push(`${key}=${encodeURIComponent(element)}`)
      })
    } else {
      params.push(`${key}=${encodeURIComponent(value)}`)
    }
  }
  return params.join('&')
}


text:
Q: How to read media files(audio files , not text files ) in a jar file ?     Media.jar
    |--gmor.wav
    +--some.txt

the code below can not work to get the inputstream , and throws
java.lang.NullPointerException .
     input   = JarFileRead.class.getClassLoader().getResourceAsStream("some.txt");  can work.
[code]
import java.io.*;
public class JarFileRead
{
public static InputStream input = null;
public JarFileRead()
   {
       try
       {
           input = JarFileRead.class.getClassLoader().getResourceAsStream("gmor.wav");

           while(input.read()!=-1)
           {

               System.out.print(input.read());
           }
           input.close();
       }
       catch(Exception e)
       {
           e.printStackTrace();
       }
   }
public static void main(String [] args)
{
   new JarFileRead();
}

}
[/code]

A: The getResourceAsStream method returns null if it can't find the resource that you asked for.  Your code doesn't check for the null, and that is the cause of your NPEs.
So the solution is:

*

*Check that the file actually exists in the JAR, in the location that it is supposed to exist.

*Change the pathname to be correct for the way that you are using that method.

Note: if you were trying to name the file relative to JarFileRead, then you need to do this:
JarFileRead.class.getResourceAsStream("gmor.wav");

The way you are currently doing it should resolve relative paths relative to the root of the namespace; i.e. it is equivalent to asking for "/gmor.wav".  But it that is what you mean, it is simpler and clearer to write:
JarFileRead.class.getResourceAsStream("/gmor.wav");


text:
Q: convert json to xml using a plugin in JS I found a plugin to convert JSON to XML however its not working on IE, just wondering if anyone had this issue on IE.
I'm using this https://github.com/abdmob/x2js.
I'm trying to convert my JSON to XML on success of AJAX call, however on IE it's giving me an error X2JS is undefined but the jsfiddle example on the github seems to be working fine as well as on other browser like Chrome.
$.get(apiUrlPath)
    .then(function (data) {
        var x2js = new X2JS();
        var json2XMLResult = x2js.json2xml_str(data);
        console.log(data, json2XMLResult)
    })

Does anyone know why its not working on IE?


text:
Q: Finding the work to lift a rocket
The force of gravity on a mass $m$ is $F=-GMm/x^2$. With $G=6\cdot10^{-17}$ and Earth mass $M=6\cdot10^{24}$ and rocket mass $m=1000$, compute the work to lift the rocket from $x=6400$ to $x=6500$. (The units are kgs and kms and Newtons, giving work in Newton-kms).

The force required to lift the rocket is $F=\frac{GMm}{x^2}=\frac{36\cdot10^{10}}{x^2}$. The work is $\int_{6400}^{6500}\frac{36\cdot10^{10}}{x^2}\;dx=\left.-\frac{36\cdot10^{10}}x\right|_{6400}^{6500}=36\cdot10^{10}\left(\frac1{6400}-\frac1{6500}\right)=\frac9{104}\cdot10^7\approx865384.6154$.
However, the answer key says that it is 864,000 Nkm. Why is there a difference of 1384.6154?

A: Just a guess, but
$$\int_{6400}^{6500}\frac{1}{x^2}\,dx \approx 2.4038\times10^{-6}.$$
If you round that off to $2.40 \times 10^{-6}$ and then multiply by
$3.6 \times 10^{11},$ you get $8.64 \times 10^5.$
I would question how you're supposed to decide to round to three significant digits when two of the inputs to the problem are stated with only one significant digit.
But given those very rough approximations in the input,
a discrepancy of less than $0.2\%$ such as you found between your answer and the answer key is not significant.


text:
Q: parse .mxl file with Clojure I would like to parse an .mxl file (MusicXML) with clojure
So far i've seen a lot of tools to work with .xml files but I can't find a way to work with .mxl, maybe i should convert mxl to xml first but i don't know how to do that neither.

A: From the Wikipedia page on MusicXML:

The textual representation listed above is verbose; MusicXML v2.0 addresses this by adding a   compressed zip format with a .mxl suffix that can make files roughly one-twentieth the size of the uncompressed version.[16]

I'm guessing that your .mxl file is an XML file which has been compressed, and this is why you're getting parse errors. As far I can gather, the compression algorithm is a zip algorithm, so you should be able to use java's zip functionality to get at it.
EDIT
I just had a go at this with a sample .mxl file I found online. The .mxl file, once unzipped contained the xml file within it. I was then able to use following (inspired by this answer) to get the raw XML...
 (defn extract-mxl [path]
   (let [[_ filename] (re-matches #"(.*)\.mxl$" (.getName (java.io.File. path)))
         zipfile (java.util.zip.ZipFile. path)
         zipentry (.getEntry zipfile (str filename ".xml"))
         in (.getInputStream zipfile zipentry)]
     (slurp in)))

A: MusicXML's zip structure for .mxl files is similar to that of the EPUB format. See http://www.musicxml.com/tutorial/compressed-mxl-files/zip-archive-structure/ in the MusicXML tutorial for more information about where to find the XML score data within the MXL archive.

A: if someone stumbles upon this, and can't figure out how to unzip the compressed mxl file:
on mac, I just renamed it to .zip and it worked out fine!


text:
Q: Openweather api call failure in react.js I want to fetch weather data via open weather api. I noticed in console that the data is not downloading even though the connection to the api was also made correctly. By entering the API address in the browser, the data will be displayed. After clicking the get weather button, no data is downloaded. I came across a problematic snippet in my code. What causes the problem in this code?
 e.preventDefault();

    const city = e.target.elements.city.value;
    const country = e.target.elements.country.value;

This piece of code above causes problems when fetching data through the API. If I delete it the data via API downloads without any problems and I get the current weather in London.
Entire App.js
import React from "react";

import './App.css';

import 'weather-icons/css/weather-icons.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Weather from "./components/weather.component";
import Form from "./components/form.component";

const API_KEY = "79b5009058dfaeaae8ed70533cb72a0d";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      city: undefined,
      country: undefined,
      icon: undefined,
      main: undefined,
      celsius: undefined,
      temp_max: undefined,
      temp_min: undefined,
      description: '"',
      error: false
    };

    this.weatherIcon = {
      Thunderstorm: "wi-thunderstorm",
      Drizzle: "wi-sleet",
      Rain: "wi-storm-showers",
      Snow: "wi-snow",
      Atmosphere: "wi-fog",
      Clear: "wi-day-sunny",
      Clouds: "wi-day-fog"
    };
  }

  calCelsius(temp) {
    let cell = Math.floor(temp - 273.15);
    return cell;
  }

  get_WeatherIcon(icons, rangeId){
    switch(true){
      case rangeId >= 200 && rangeId <= 232:
        this.setState({icon: this.weatherIcon.Thunderstorm})
        break;
      case rangeId >= 300 && rangeId <= 321:
        this.setState({icon: this.weatherIcon.Drizzle})
        break;
      case rangeId >= 500 && rangeId <= 531:
        this.setState({icon: this.weatherIcon.Rain})
        break;
      case rangeId >= 600 && rangeId <= 622:
        this.setState({icon: this.weatherIcon.Snow})
        break;
      case rangeId >= 701 && rangeId <= 781:
        this.setState({icon: this.weatherIcon.Snow})
        break;
      case rangeId === 800:
        this.setState({icon: this.weatherIcon.Clear})
        break;
      case rangeId >= 801 && rangeId <= 804:
        this.setState({icon: this.weatherIcon.Clouds})
        break;
      default:
        this.setState({icon: this.weatherIcon.Clouds})
    }
  }

  getWeather = async(e)=>{

    e.preventDefault();

    const city = e.target.elements.city.value;
    const country = e.target.elements.country.value;

    if(city && country) {
      const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`);

      const response = await api_call.json();

      console.log(response);

    this.setState({
      city: response.name,
      country: response.country,
      celsius: this.calCelsius(response.main.temp),
      temp_max: this.calCelsius(response.main.temp_max),
      temp_min: this.calCelsius(response.main.temp_min),
      description: response.weather[0].description,
    });
      this.get_WeatherIcon(this.weatherIcon, response.weather[0].id);
    } else {
      this.setState({error: true});
    }
  };

  render() {
    return (

      <Form loadweather={this.getWeather} error={this.state.error}/>
      <Weather
        city={this.state.city}
        country={this.state.country}
        temp_celsius={this.state.celsius}
        temp_max={this.state.temp_max}
        temp_min={this.state.temp_min}
        description={this.state.description}
        weatherIcon={this.state.icon}
      />

    )
  }
}

export default App;

form.component.jsx
import React from "react";
import "./form.style.css";

const Form = props => {
    return(

{props.error ? error() : null}

        <form action="">

                    <input
                        type="text"
                        className="form-control"
                        name="city"
                        autoComplete="off"
                        placeholder="City"
                    />

                    <input
                        type="text"
                        className="form-control"
                        name="country"
                        autoComplete="off"
                        placeholder="Country"
                    />

                    <button onSubmit={props.loadweather} className="btn btn-warning">Get Weather</button>

        </form>

    );
}

function error() {
    return(

        Please Enter City and Country

    )
}
export default Form;

weather.component.jsx
import React from 'react';

const Weather = (props) => {
    return(

{props.city}

               <i className={`wi ${props.weatherIcon} display-1`} />

            {props.temp_celcius ? (

): null}

{props.temp_celsius}°

             {minmaxTemp(props.temp_min, props.temp_max)}

{props.description}

    );
};

function minmaxTemp(min,max) {
    if(min && max) {
        return(

                {min}°
                {max}°

        );
    }
}

export default Weather;

A: The problem seems to be in form.component.jsx
Try using
<input className="btn btn-warning" type="submit" value="Get Weather" />

instead of
<button onSubmit={props.loadweather} className="btn btn-warning">Get Weather</button>

Also, use
<form onSubmit={props.loadweather}>

Refer to this just in case:
https://reactjs.org/docs/forms.html
Happy coding!


text:
Q: Way of recalculating keys after using array_unique in PHP I remove dupliactes from array (list #1) with array_uniqe but how to recalculate kyes of it's output (list #2) to [0-x] (list #3):
list #1:
 array (size=24)
          0 => string '2013-09-18' (length=10)
          1 => string '2013-09-18' (length=10)
          2 => string '2013-09-18' (length=10)
          3 => string '2013-09-18' (length=10)
          4 => string '2013-09-19' (length=10)
          5 => string '2013-09-19' (length=10)
          6 => string '2013-09-19' (length=10)
          7 => string '2013-09-19' (length=10)
          8 => string '2013-09-19' (length=10)
          9 => string '2013-09-19' (length=10)
          10 => string '2013-09-19' (length=10)
          11 => string '2013-09-20' (length=10)
          12 => string '2013-09-20' (length=10)
          13 => string '2013-09-20' (length=10)
          14 => string '2013-09-20' (length=10)
          15 => string '2013-09-21' (length=10)
          16 => string '2013-09-21' (length=10)
          17 => string '2013-09-21' (length=10)
          18 => string '2013-09-21' (length=10)
          19 => string '2013-09-21' (length=10)
          20 => string '2013-09-21' (length=10)
          21 => string '2013-09-22' (length=10)
          22 => string '2013-09-22' (length=10)
          23 => string '2013-09-22' (length=10)

List #2:
array (size=5)
  0 => string '2013-09-18' (length=10)
  4 => string '2013-09-19' (length=10)
  11 => string '2013-09-20' (length=10)
  15 => string '2013-09-21' (length=10)
  21 => string '2013-09-22' (length=10)

List #3:
array (size=5)
  0 => string '2013-09-18' (length=10)
  1 => string '2013-09-19' (length=10)
  2 => string '2013-09-20' (length=10)
  3 => string '2013-09-21' (length=10)
  4 => string '2013-09-22' (length=10)

A: $list3 = array_values($list2);


text:
Q: how to make particular column of datagrid a combobox when AutoGenerateColumns="True" I am new to MVVM . I am using wpf with MVVM in my project . So I am testing things right now before diving into an app I need to write.
My page (EmpDetailsWindow.xaml) is like this
<Grid>
    <DataGrid Name="dgEmployee" Grid.Row="0" AutoGenerateColumns="True" ItemsSource="{Binding EmployeeDataTable}" CanUserAddRows="True" CanUserDeleteRows="True" IsReadOnly="False"  />
    <Button x:Name="btnSubmit" Content="Submit" Command="{Binding SubmitCommand}" CommandParameter="sample param" HorizontalAlignment="Left" Margin="212,215,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>

and my model (EmpDetailsWindowViewModel) is as below
public class EmpDetailsWindowViewModel : INotifyPropertyChanged
    {
        public ICommand SubmitCommand { get; set; }
        public EmpDetailsWindowViewModel()
        {
            EmployeeDataTable = DataTableCreator.EmployeeDataTable();
            GenderDataTable = DataTableCreator.GenderDataTable();
            SubmitCommand = new SubmitCommand();
        }

        DataTable _employeeDataTable;
        public DataTable EmployeeDataTable
        {
            get { return _employeeDataTable;}
            set
            {
                _employeeDataTable = value;
                RaisePropertyChanged("EmployeeDataTable");
            }
        }

        DataTable _genderDataTable;
        public DataTable GenderDataTable
        {
            get { return _genderDataTable; }
            set
            {
                _genderDataTable = value;
                RaisePropertyChanged("GenderDataTable");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

datagrid is successfully bound to the datatable . Now I have a column "Gender" in datagrid. This should be a combobox and the item source of the cobobox is got from GenderDataTable of the view model . How can I achieve this ?

A: You can do it like this
<DataGrid AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"/>

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyName == "Gender")
    {
        var cb = new DataGridComboBoxColumn();
        cb.ItemsSource = (DataContext as MyVM).GenderDataTable;
        cb.SelectedValueBinding = new Binding("Gender");
        e.Column = cb;
    }
}

A: There doesn't seem to quite be a complete answer here so I'll post what I found from this question and from experimentation. I'm sure this breaks many rules but it's simple and it works
public partial class MainWindow : Window
    {
        // define a dictionary (key vaue pair). This is your drop down code/value
        public static Dictionary<string, string>
              dCopyType = new Dictionary<string, string>() {
                 { "I", "Incr." },
                 { "F", "Full" }
              };

// If you autogenerate columns, you can use this event
// To selectively override each column
// You need to define this event on the grid in the event tab in order for it to be called
private void Entity_AutoGeneratingColumn(object sender,
                                         DataGridAutoGeneratingColumnEventArgs e)
        {

            // The name of the database column
            if (e.PropertyName == "CopyType")
            {
                // heavily based on code above
                var cb = new DataGridComboBoxColumn();
                cb.ItemsSource = dCopyType;  // The dictionary defined above
                cb.SelectedValuePath = "Key";
                cb.DisplayMemberPath = "Value";
                cb.Header = "Copy Type";
                cb.SelectedValueBinding = new Binding("CopyType");
                e.Column = cb;
            }

        }
  } // end public partial class MainWindow