text:
Q: iOS How can I dynamic change the PageControl color when change the page? I have 3 page - A ViewController, B ViewController and C ViewController.
And A PageViewController control there horizontal scroll.
PagesViewController.m
 - (void)viewDidLoad {
     [super viewDidLoad];
     self.aVC = [self.storyboard
       instantiateViewControllerWithIdentifier:@"AViewController"];
     self.bVC = [self.storyboard
            instantiateViewControllerWithIdentifier:@"BViewController"];
     self.cVC = [self.storyboard
            instantiateViewControllerWithIdentifier:@"CViewController"];

     self.delegate = self;
     self.dataSource = self;

     self.allViewControllers = @[self.aVC,self.bVC
                            ,self.cVC];

     [self setViewControllers:@[self.aVC]
               direction:UIPageViewControllerNavigationDirectionForward
                animated:NO completion:nil];

     _pageControl = [UIPageControl appearance];

 }

I want to change the _pageControl color when I scroll to A VC , B VC and C VC.
So I put the code in
 -(NSInteger)presentationIndexForPageViewController:
 (UIPageViewController *)pageViewController
 {

     NSLog(@"%@",pageViewController.viewControllers[0]);
     for( int i = 0 ; i< self.allViewControllers.count ; i++ )
     {
         if( pageViewController.viewControllers[0] == self.allViewControllers[i])
         {
             if( i ==0 )
             {
                 _pageControl.backgroundColor = [UIColor greenColor];
             }
             else if( i ==1)
             {
                 _pageControl.backgroundColor = [UIColor redColor];
             }
             else
             {
                 _pageControl.backgroundColor = [UIColor clearColor];
             }
             NSLog(@"return index:%d", i);
             return i;
         }
     }

     return 0;
 }

But the page control was not change the color.
I try to put below the code in the viewDidLoad, it will change color at all the view controller.
 _pageControl.backgroundColor = [UIColor redColor];

But now I want to change the pageControl color when I scroll to different UIViewController.
How can I do? or How can I refresh the pageControl color?
Because now the color always black.
I offer others delegate method about the PageViewController:
 -(UIViewController*) pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController

{
NSUInteger currentIndex = [self.allViewControllers indexOfObject:viewController];
if( currentIndex == 0 )
{
    return nil;
}
currentIndex--;

     return [self.allViewControllers objectAtIndex:currentIndex];
 }

 -(UIViewController *) pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
 {
     NSUInteger currentIndex = [self.allViewControllers indexOfObject:viewController];

     NSLog(@"after currentIndex:%ld",currentIndex);
     currentIndex++;

if( currentIndex == [self.allViewControllers count])
{
    return nil;
}

     return [self.allViewControllers objectAtIndex:currentIndex];
 }

 -(NSInteger)presentationCountForPageViewController:
 (UIPageViewController *)pageViewController
 {
     return self.allViewControllers.count;
 }

A: Here's an example, just with a pageControl in a UIViewController:
#import "ViewController.h"

@interface ViewController () {
    UIPageControl *pageControl;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor lightGrayColor];

    pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
    pageControl.numberOfPages = 6;
    [pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:pageControl];
}

- (void) changePage:(UIPageControl *)page {
    NSInteger currentPage = page.currentPage;
    switch (currentPage) {
        case 0:
            pageControl.backgroundColor = [UIColor redColor];
            break;
        case 1:
            pageControl.backgroundColor = [UIColor greenColor];
            break;
        case 2:
            pageControl.backgroundColor = [UIColor blueColor];
            break;

        default:
            break;
    }
}

@end

A: In your viewDidLoad: method,
instead of:
_pageControl = [UIPageControl appearance];

use:
NSArray *subviews = self.view.subviews;
_pageControl = nil;
for (int i=0; i<[subviews count]; i++) {
    if ([[subviews objectAtIndex:i] isKindOfClass:[UIPageControl class]]) {
        _pageControl = (UIPageControl *)[subviews objectAtIndex:i];
    }
}

=====
EDIT:
For your specific project, you're not getting the _pageControl (it's returning nil) because the Storyboard has not completed instantiating your view controller in the viewDidLoad.  I thought it would need to go in viewDidAppear:animated, but that didn't work either, so I cheated by delaying requesting it for 0.2 milliseconds.
In your viewDidLoad, put this:
[self performSelector:@selector(findPageControl) withObject:nil afterDelay:0.2f];

Then, add this method:
- (void) findPageControl {
    NSArray *subviews = self.view.subviews;
    _pageControl = nil;
    for (int i=0; i<[subviews count]; i++) {
        if ([[subviews objectAtIndex:i] isKindOfClass:[UIPageControl class]]) {
            _pageControl = (UIPageControl *)[subviews objectAtIndex:i];
        }
    }
    [self changePage:0];
}

In your viewControllerAfterViewController method, I added this right after the NSUInteger currentIndex = line:
[self changePage:currentIndex];

That seems to have made it work.  Now, you could add an animation in your changePage method to make the transition seem a little smoother.
Also, when debugging, this is what I did:
I added a breakpoint on the _pageControl = line, so I could check and see what was happening.  When I saw it was nil, that told me that it wasn't being set properly.  Look in the debug area, and you can see what I printed out ("po") to see what values existed -- and why there was no UIPageControl.  If you do the same after the changes I list above, you'll see that this is now found and set.


text:
Q: Javascript: Passing a function as argument which will be executed at onclick event I would like to creat a confirm box based on the idea that when the button is clicked, a div is appended
to the body, and its OK button executes a function given as argument. I managed to do it if the function name is not a variable, but in this case I would need as many confirm boxes as many types of functions I have.
Here's the html button:
<button onclick=" executeAfterConfirmed( myFunc );">SHOW</button>
Here's the confirm box function:
function execAfterConfirmed( functionToExecute , arg ){
    $("body").prepend("
CONFIRM ?
<button class='myConfirmButton'   id='yesButton' onclick='$(\"div#createdConfirmDiv\").remove();" + functionToExecute + "("+arg+")'>YES</button><button class='myConfirmButton' onclick='$(\"div#createdConfirmDiv\").remove()'>NO</button>
");

}
However, I got Unexpected token (

A: I hope I did understand your problem, as you are trying to describe. Here is a solution:
function confirmBox(button, message, func) {
    button.addEventListener('click', function(){
       var re = confirm(message);

       if (re) func();
    })
}

confirmBox( document.getElementById('button'),
            "You clicked because you liked me.",
            function(){
                // do stuff
            });

A: Just add the handler programmatically...

function myFunc() {
  alert("myFunc!");
}

function executeAfterConfirmed(functionToExecute, arg) {
  var $show = $("#show-button").hide();

  $("body").prepend("
Test dialog
<button>OK</button>
");

  $("#createdConfirmDiv button").one("click", function(e){
    functionToExecute(arg);
    $("#createdConfirmDiv").remove();
    $show.show();
  });

}

<button id="show-button" onclick="executeAfterConfirmed(myFunc);">SHOW</button>

A: CSS
.createdConfirmDiv{display(none;}

HTML

CONFIRM?

<button class='myConfirmButton'   id='yesButton' onclick=("remove(1)");>YES
</button>
<button class='myConfirmButton' onclick=("remove(2)";)>NO
</button>

SCRIPT
myFunc function(f,a){
document.getElementById('createdConfirmDiv').sytle.display='block');

}

remove function(r){
document.getElementById('createdConfirmDiv').sytle.display='none');
if (r==0){

}
if (r==1){

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: User controls communicating via Commands - how? I'm working on my first project in WPF/XAML, and there's a lot I've not figured out.
My problem is simple - I need a window that has a bunch of fields at the top, with which the user will enter his selection criteria, a retrieve button, and a data grid.  When the user clicks on the button, a query is run, and the results are used to populate the grid.
Now the simple and obvious and wrong way to implement this is to have a single module containing a single window, and have everything contained within it - entry fields, data grid, the works.  That kind of mangling of responsibilities makes for an unmaintainable mess.
So what I have is a window that is responsible for little more than layout, that contains two user controls - a criteria control that contains the entry fields and the retrieve button, and a data display control that contains the data grid.
The question is how to get the two talking to each other.
Years back, I would have added a function pointer to the criteria control.  The window would have set it to point to a function in the display control, and when the button was clicked, it would have called into the display control, passing the selection criteria.
More recently, I would have added an event to the criteria control.  I would have had the window set a handler in the display control to listen to the event, and when the button was clicked, it would have raised the event.
Both of these mechanisms would work, in WPF. But neither is very XAMLish.  It looks to me like WPF has provided the ICommand interface specifically to accommodate these kinds of connection issues, but I've not yet really figured out how they are intended to work.  And none of the examples I've seen seem to fit my simple scenario.
Can anyone give me some advice on how to fit ICommand to this problem?  Or direct me to a decent explanation online?
Thanks!

A: MVVM is the prevalent pattern used with WPF and Silverlight development. You should have a read up on it.
Essentially, you would have a view model that exposes a command to perform the search. That same view model would also expose properties for each of your criteria fields. The view(s) would then bind to the various properties on the view model:
<TextBox Text="{Binding NameCriteria}"/>

...

<Button Command="{Binding SearchCommand}".../>

...

<DataGrid ItemsSource="{Binding Results}"/>

Where your view model would look something like:
public class MyViewModel : ViewModel
{
    private readonly ICommand searchCommand;
    private string nameCriteria;

    public MyViewModel()
    {
        this.searchCommand = new DelegateCommand(this.OnSearch, this.CanSearch);
    }

    public ICommand SearchCommand
    {
        get { return this.searchCommand; }
    }

    public string NameCriteria
    {
        get { return this.nameCriteria; }
        set
        {
            if (this.nameCriteria != value)
            {
                this.nameCriteria = value;
                this.OnPropertyChanged(() => this.NameCriteria);
            }
        }
    }

    private void OnSearch()
    {
        // search logic, do in background with BackgroundWorker or TPL, then set Results property when done (omitted for brevity)
    }

    private bool CanSearch()
    {
        // whatever pre-conditions to searching you want here
        return !string.IsEmpty(this.NameCriteria);
    }
}


text:
Q: TSQL how to remove all characters or text after the last tab space I have some data that look like this:
Maple Leaf City

This is all in a single column called City.
I want to remove the word City so that the output looks like this:
Maple Leaf

My code below removes the everything after the first space instead of the last.
How do I take this: Maple Leaf City and turn it into Maple Leaf?
This is what I have got:
SELECT LEFT(City, CHARINDEX(' ', City) - 1)
FROM MyTable
WHERE CHARINDEX(' ', City) > 1

My code gives me this: Maple

A: declare @str varchar(255)
set @str = 'Maple Leaf City'
select LEFT(@str, LEN(@str) - CHARINDEX(' ', REVERSE(@str)))


text:
Q: Java: How to extract the largest name from multiple folders kept at a path into a variable where folder names are all numeric? There is a directory which has many folders. The folder names are all numeric. How to extract the folder name which has the greatest value into an integer variable in java?
For example: Lets say directory .../home/user has following folders:
.../home/user/19620918
.../home/user/19620919
.../home/user/19620920
How to get x = 19620920, where x is lets say the integer variable, using the simplest and most efficient code?

A: Using a Files.list(), you can use the following approach:
public static OptionalInt getMaxNumericFilename(Path path) {
    try (Stream<Path> files = Files.list(path)) {
        return files
            .filter(Files::isDirectory)
            .map(Path::getFileName)
            .map(Path::toString)
            .mapToInt(Integer::parseInt)
            .max();
    } catch (IOException e) {
        return OptionalInt.empty();
    }
}

Example usage:
Path path = Path.of(".../home/user");

OptionalInt max = getMaxNumericFilename(path);
System.out.println(max.getAsInt());

If the OptionalInt is empty, there are no present directories. If you want to add additional resiliency, you can filter if the filename is an int before parsing with Integer::parseInt which can throw an exception.
This solution will work for filename numbers up to Integer.MAX_VALUE (2.147.483.647). Consider using long or BigDecimal if required.


text:
Q: How do we know which term to attach a phase factor to in a state equation? I need to find the state of a particle in a one-dimesional harmonic oscillator where a measurement of the energy yields the values $\hbar\omega\over 2$ or $3\omega\hbar\over 2$, each with a probability of one-half at time t. I would have thought that the state would be $\big|\psi(0)\big>= {1\over \sqrt2}\big|0\big>+{1\over \sqrt2}\big|1\big>$. However the right equation is $\big|\psi(0)\big>= {1\over \sqrt2}\big|0\big>+{1\over \sqrt2}e^{-i\phi}\big|1\big>$. I know that the $e^{-i\phi}$ is a relative phase factor, but I can't figure out where it came from.
Where did the phase factor come from and when do phase factors need to be applied to the terms in state equations?

A: Your answer is correct, but there are other states that would give probability 50% and 50% if you add a phase shift to any of the states. However, any phase shift could be rewritten by a relative phase shift factor, as in the last expression in your question.


text:
Q: Android studio debugger stops at random location I put the breakpoint at the updateChauffeurs method, it sets it at the loadLicenties method and it breaks at the loadLicenties method (see watches).
Project Clean, project rebuild, computer and android tablet reboot didn't help.
What did help was to replace the Nexus 7 (2012) tablet with a Samsung TabPro 8.4 tablet -> here the breakpoints are hitted correctly.
Any tips? Running android studio 2 beta 7 with gradle 2.10 and instant run enabled.

A: Wukash comment was right: simply uninstalling the apk and reinstalling did the trick. I don't understand though, installing a new apk using adb didn't do the trick.

A: Android Studio 2 Beta is not stable yet. I think you should return latest stable Android 1.5 version in order to get rid of strange errors.


text:
Q: MalformedCookieException: Invalid 'expires' attribute We are using header manager in our JMeter script and getting the following exception in one of the request responses. I tried with all the available options in the header manager but no luck.
Response from Server where it threw exception was- Set-Cookie: X-Region=B; expires=1581079580; path=/
I looked on multiple sites but no resolution. Could you please suggest a resolution for this exception-
org.apache.http.cookie.MalformedCookieException: Invalid 'expires' attribute: 1581079580
    at org.apache.http.impl.cookie.LaxExpiresHandler.parse(LaxExpiresHandler.java:161) ~[httpclient-4.5.6.jar:4.5.6]
    at org.apache.http.impl.cookie.RFC6265CookieSpec.parse(RFC6265CookieSpec.java:181) ~[httpclient-4.5.6.jar:4.5.6]
    at org.apache.jmeter.protocol.http.control.HC4CookieHandler.addCookieFromHeader(HC4CookieHandler.java:125) [ApacheJMeter_http.jar:5.0 r1840934]

A: What do you want to fix from JMeter side?
As per RFC 6265 the format of the Expires attribute is following:
cookie-date     = *delimiter date-token-list *delimiter
   date-token-list = date-token *( 1*delimiter date-token )
   date-token      = 1*non-delimiter

   delimiter       = %x09 / %x20-2F / %x3B-40 / %x5B-60 / %x7B-7E
   non-delimiter   = %x00-08 / %x0A-1F / DIGIT / ":" / ALPHA / %x7F-FF
   non-digit       = %x00-2F / %x3A-FF

   day-of-month    = 1*2DIGIT ( non-digit *OCTET )
   month           = ( "jan" / "feb" / "mar" / "apr" /
                       "may" / "jun" / "jul" / "aug" /
                       "sep" / "oct" / "nov" / "dec" ) *OCTET
   year            = 2*4DIGIT ( non-digit *OCTET )
   time            = hms-time ( non-digit *OCTET )
   hms-time        = time-field ":" time-field ":" time-field
   time-field      = 1*2DIGIT

My expectation is that the server should return something like:
Expires=Fri, 07 Feb 2020 12:46:00 GMT

So you need to raise a bug against your application instead of looking for the workaround.
If you're absolutely sure that your application works as expected (which is not the case in my opinion) you won't be able to automatically handle the cookies using HTTP Cookie Manager, you will have to extract them from previous response Set-Cookie header using i.e. Regular Expression Extractor and add Cookie header with the extracted values using HTTP Header Manager

A: It looks like your 'expires' attribute is not compliant with https://www.rfc-editor.org/rfc/rfc6265 There is epoch time 1581079580 But there should be time in format specified by https://www.rfc-editor.org/rfc/rfc2616#section-3.3.1 E.g.: Wed, 09 Jun 2021 10:18:14 GMT Do you have a cookie policy set to standard or standard-strict (RFC6265)?

A: Sometimes the HTTP Authorization Manager does this error occures. If you have, try with toggled off this.


text:
Q: how to get contacts type in android? I want to retrieve both contacts name and their type in my layout.I am providing my activities and layout file.I am getting an invalid column type exception.any help would be greatly appreciable.thanks in advance.
TestActivity.class:
        package application.test;
        import android.app.ListActivity;

        import android.os.Bundle;
        import android.provider.ContactsContract;
        import android.provider.ContactsContract.CommonDataKinds.Phone;
        import android.provider.ContactsContract.Data;
        import android.view.LayoutInflater;
        import android.view.ViewGroup.LayoutParams;
        import android.widget.LinearLayout;
        import android.widget.ListView;
        import android.widget.RelativeLayout;
        import android.content.ContentResolver;
        import android.database.Cursor;
        import android.database.SQLException;

        public class TestActivity extends ListActivity
        {
            String name[];
            String phoneType[];

            ListView lview;
           ListViewAdapter lviewAdapter;
           @Override
            protected void onCreate(Bundle savedInstanceState)
            {

                super.onCreate(savedInstanceState);
                 LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
                LinearLayout mainLayout=new LinearLayout(this);
                mainLayout.setOrientation(LinearLayout.VERTICAL);
                LayoutInflater layoutInflater = getLayoutInflater();
                mainLayout.addView(layoutInflater.inflate(R.layout.main,null));
                mainLayout.addView(layoutInflater.inflate(R.layout.extra,null));

                this.addContentView(mainLayout, params);

              lview = (ListView) findViewById(android.R.id.list);
             getContacts();
          lviewAdapter=new ListViewAdapter(this, name, phoneType);
              lview.setAdapter(lviewAdapter);

             }//onCreate

           public void getContacts(){
               int i=0;
               ContentResolver cr = getContentResolver();

                         String[] projection = new String[] { Data._ID,
                      ContactsContract.Contacts.DISPLAY_NAME, Phone.TYPE};

              Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI,
                      projection, null, null, null);

               if (cur != null && cur.moveToFirst()) {

               try {

                    int indexID =  cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
                    int indexName = cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
                    int indexPhoneType = cur.getColumnIndexOrThrow(Phone.TYPE);

                 while (cur.moveToNext()) {

                    i++;
                     String id = cur.getString(indexID);
                     name[i] = cur.getString(indexName);
                     phoneType[i] =  cur.getString(indexPhoneType);
                 }

               } catch (SQLException sqle) {

              sqle.printStackTrace();
               } finally {
                if (!cur.isClosed()) {
                    cur.close();
                }
            }
           }
         }

        }

ListViewAdapter.class
        package application.test;
        import android.app.Activity;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.BaseAdapter;
        import android.widget.TextView;

        public class ListViewAdapter extends BaseAdapter  {

            Activity context;
            String name[];
            String phoneType[];

            public ListViewAdapter(Activity context,String[] name,String[] phoneType){
                super();
                this.context=context;
                   this.name=name;
                this.phoneType=phoneType;
            }

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return name.length;
            }

            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return 0;
            }
        public class viewHolder {
            TextView top;
            TextView bottom;
        }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                // TODO Auto-generated method stub

                viewHolder holder;
                if(convertView==null){

                    LayoutInflater inflator=context.getLayoutInflater();
                convertView=inflator.inflate(R.layout.row,null);

                 holder=new viewHolder();
                holder.top=(TextView)convertView.findViewById(R.id.toptext);
                holder.bottom=(TextView)convertView.findViewById(R.id.bottomtext);
                convertView.setTag(holder);
                }else{
                    holder=(viewHolder)convertView.getTag();
                }

                holder.top.setText(name[position]);
                holder.bottom.setText(phoneType[position]);

                return convertView;
            }

 }

row.xml:
          <?xml version="1.0" encoding="utf-8"?>
         <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="?android:attr/listPreferredItemHeight"
            android:padding="6dip">

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="0dip"
                android:layout_weight="1"
                android:layout_height="fill_parent">
                <TextView
                    android:id="@+id/toptext"
                    android:layout_width="fill_parent"
                    android:layout_height="0dip"
                    android:layout_weight="1"
                    android:gravity="center_vertical"
                />
                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="0dip"
                    android:layout_weight="1"
                    android:id="@+id/bottomtext"
                    android:singleLine="true"
                    android:ellipsize="marquee"
                />
            </LinearLayout>
        </LinearLayout>

main.xml:
          <?xml version="1.0" encoding="utf-8"?>

            <RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
            android:layout_width="fill_parent" android:id="@+id/relativeLayout1"
             android:layout_height="fill_parent">
                <TextView android:id="@+id/textView1"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_height="wrap_content" android:layout_width="wrap_content"
            android:text="All Contacts" android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"></TextView>
                <TextView android:id="@+id/textView2"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_height="wrap_content" android:layout_width="wrap_content"
            android:text="Search  " android:layout_alignBaseline="@+id/editText1"
            android:layout_alignBottom="@+id/editText1"
            android:layout_alignParentLeft="true"></TextView>
                <EditText android:layout_height="wrap_content" android:layout_width="180dp" android:id="@+id/editText1" android:layout_below="@+id/textView1" android:layout_toRightOf="@+id/textView2" android:layout_marginTop="18dp">
                    <requestFocus></requestFocus>
                </EditText>
                <Button android:layout_height="wrap_content"
            android:text="Search" android:layout_width="wrap_content" android:id="@+id/button_searchContact"
            android:layout_alignBottom="@+id/editText1" android:layout_toRightOf="@+id/editText1"></Button>
                <ListView android:id="@android:id/list"
            android:layout_height="wrap_content" android:layout_width="fill_parent"
            android:layout_marginBottom="70dp"
            android:layout_alignParentLeft="true" android:layout_below="@+id/editText1"></ListView>
            </RelativeLayout>

extra.xml:
        <?xml version="1.0" encoding="utf-8"?>

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical" android:layout_width="fill_parent"
            android:layout_height="fill_parent" android:id="@+id/commonButtons"
            android:gravity="bottom">
            <ImageButton android:background="@drawable/favorite" android:layout_width="65dp" android:id="@+id/button_favorites" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_marginBottom="20dp"></ImageButton>
            <ImageButton android:background="@drawable/recents" android:layout_width="65dp" android:id="@+id/button_recent" android:layout_height="50dp" android:layout_alignTop="@+id/button_favorites" android:layout_toLeftOf="@+id/button_contacts"></ImageButton>
            <ImageButton android:background="@drawable/contacts" android:layout_width="65dp" android:id="@+id/button_contacts" android:layout_height="50dp" android:layout_alignTop="@+id/button_recent" android:layout_centerHorizontal="true"></ImageButton>
            <ImageButton android:background="@drawable/keypad" android:layout_width="65dp" android:id="@+id/button_keypad" android:layout_height="50dp" android:layout_alignTop="@+id/button_contacts" android:layout_toLeftOf="@+id/button_about"></ImageButton>
            <ImageButton android:background="@drawable/about" android:layout_width="65dp" android:id="@+id/button_about" android:layout_height="50dp" android:layout_alignTop="@+id/button_keypad" android:layout_alignParentRight="true"></ImageButton>
            <TextView android:layout_width="wrap_content" android:text="Favorites"
            android:id="@+id/textView1" android:layout_height="wrap_content"
            android:layout_below="@+id/button_recent" android:layout_toLeftOf="@+id/button_recent"></TextView>

        <TextView android:layout_width="wrap_content" android:text="Contacts"
            android:id="@+id/textView3" android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/textView2"
            android:layout_alignBottom="@+id/textView2" android:layout_toLeftOf="@+id/button_keypad" android:layout_alignLeft="@+id/button_contacts"></TextView>
        <TextView android:layout_width="wrap_content" android:text="  Recents" android:id="@+id/textView2" android:layout_height="wrap_content" android:layout_below="@+id/button_recent" android:layout_toRightOf="@+id/button_favorites" android:layout_alignRight="@+id/button_recent"></TextView>
        <TextView android:layout_width="wrap_content" android:text="  Keypad"
            android:id="@+id/textView4" android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" android:layout_toRightOf="@+id/button_contacts"
            android:layout_toLeftOf="@+id/button_about"></TextView>
        <TextView android:layout_width="wrap_content" android:text="   About"
            android:id="@+id/textView5" android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" android:layout_alignLeft="@+id/button_about"
            android:layout_alignParentRight="true"></TextView>
        </RelativeLayout>

AndroidManifest.xml:
        <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
              package="application.test"
              android:versionCode="1"
              android:versionName="1.0">
            <uses-sdk android:minSdkVersion="8"/>
             <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>

            <application android:icon="@drawable/icon" android:label="@string/app_name">
                <activity android:name=".TestActivity"
                          android:label="@string/app_name">
                    <intent-filter>
                        <action android:name="android.intent.action.MAIN" />
                        <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
                </activity>

            </application>
        </manifest>

A: Here's my Activity class I tested the code with. The layout is not important, as the contact info is printed on the standard output (look in DDMS).
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts.Data;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public final class ContactManager extends Activity {

public static final String TAG = "ContactManager";
@Override
public void onCreate(Bundle savedInstanceState)
{
    Log.v(TAG, "Activity State: onCreate()");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contact_manager);

    testGetContacts();
}

private void testGetContacts() {

        ContentResolver cr = getContentResolver();

        String[] projection = new String[] { Data._ID,
                ContactsContract.Contacts.DISPLAY_NAME, Phone.TYPE};

        Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI,
                projection, null, null, null);

        if (cur != null && cur.moveToFirst()) {

        try {

            int indexID =  cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
            int indexName = cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
            int indexPhoneType = cur.getColumnIndexOrThrow(Phone.TYPE);

          while (cur.moveToNext()) {
              String id = cur.getString(indexID);
              String name = cur.getString(indexName);
              String phoneType =  cur.getString(indexPhoneType);

              System.out.println(id + "\n");
              System.out.println(name + "\n");
              System.out.println(phoneType + "\n");
          }

        } catch (SQLException sqle) {
           //handle exception here - like missing column name!
        } finally { //close your cursor if it's not needed!
         if (!cur.isClosed()) {
             cur.close();
         }
     }
    }

}

}

A: Suggestions for better code:
0) Add projection to your code => getting all columns is inefficient
    String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,ContactsContract.PhoneLookup.TYPE};

And than add the projection to your query:
Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI,
                        projection, null, null, null);

1) In your loop, your getting column index on every iteration. That's not necessary move the cur.getColumnIndex out of the loop.
2) When working with cursor, you may supplement the for-loop with while-condition loop. Here's a suggestion of impl. of your method getContacts():
  // A list of providers imports used!
 import android.provider.ContactsContract;
 import android.provider.ContactsContract.CommonDataKinds.Phone;
 import android.provider.ContactsContract.Contacts.Data;

 public void getContacts(){
         ContentResolver cr = getContentResolver();

                   String[] projection = new String[] { Data._ID,
                ContactsContract.Contacts.DISPLAY_NAME, Phone.TYPE};

        Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI,
                projection, null, null, null);
         // don't use this ContentProvider
        // Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                    //    projection, null, null, null);

         if (cur != null && cur.moveToFirst()) {

         try {

              int indexID =  cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
              int indexName = cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
              int indexPhoneType = cur.getColumnIndexOrThrow(Phone.TYPE);

           while (cur.moveToNext()) {
            //do your logic here;
              String id = cur.getString(indexID);
              String name = cur.getString(indexName);
              String phoneType =  cur.getString(indexPhoneType);
           }

         } catch (SQLException sqle) {
            //handle exception here - like missing column name!
         } finally { //close your cursor if it's not needed!
          if (!cur.isClosed()) {
              cur.close();
          }
      }
     }
   }

EDIT:
Use this imports:
 import android.provider.ContactsContract;
 import android.provider.ContactsContract.CommonDataKinds.Phone;
 import android.provider.ContactsContract.Contacts.Data;

Use this projection
   String[] projection = new String[] { ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,ContactsContract.PhoneLookup.TYPE};

Use this Query:
   Crsor cur = cr.query(ContactsContract.Data.CONTENT_URI,
                projection, null, null, null);

Use this column names:
              int indexID =  cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
              int indexName = cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
              int indexPhoneType = cur.getColumnIndexOrThrow(Phone.TYPE);


text:
Q: Ubuntu Software Center is not allowing me to download software when I try to install something I recently have gotten myself an Acer C720 Chromebook. This is the device I am currently using. On this device I have XFCE4 installed. I installed Ubuntu software center so that I may in turn get software. I did so using the apt-get install command. It runs fine, It's just that when I select a software I would like to install nothing happens. Even after repeatedly clicking, nothing happens. I am only allowed to get certain software from the apt-get install command in the terminal, and sometimes some of that software isn't installed correctly. I would really like a solution to this problem.

A: Don't blame Ubuntu!  I too have an acer chromebook.  It is stored elsewhere or I'd rattle off my model number to you.
Like you I did the sideways Ubuntu installation through terminal so that I can have Ubuntu and Chrome essentially running concurrently, accessible via some key combination, something like ctrl-alt 1 or 2 or something.  It works remarkably well but I've proven it to have certain limitations.
For one thing I discovered that even though I was sort of able to install WINE, it would not actually run.  I suspect that if Chrubuntu were installed in place of chrome, it would work but sharing the chrome kernel, it would not.  Trust me, I tried very very hard.
Realizing as I do that the type of Ubuntu we have installed is sharing a non Ubuntu kernel essentially owned by a manufacturer which appears to be in competition with microsoft, and to a lesser degree, other linux derived operating systems, it is not remotely surprising that Google chose to curtail our freedoms a bit.


text:
Q: How kernel disable the softirq in the local processor when softirq handler runs Recently I study the Linux-Kernel-Development by Robert Love.
There is a paragraph describes mechanism of softirq.
The softirq handlers run with interrupts enabled and cannot sleep.
While a handler runs, softirqs on the current processor are disabled.
Another processor, however, can execute other softirqs.
I don't understand the meaning of "softirqs on the current processor are disabled."
Does this mean that when running __do_softirq, even if some of the bit in the softirq_pending is raising again, the __do_softirq function cannot be interrupted? If yes then what statements in the __do_softirq do this kind of protection?
When tracing the code in __do_softirq, I found that there are a pair of __local_bh_disable and __local_bh_enable functions.
Do they disable the local softirq?
Thanks.

A: Yes, __local_bh_disable and __local_bh_enable disable and enable processing of softirqs on the current CPU.  Softirqs are also known as "bottom halves", which is what the "bh" in those names represents.


text:
Q: SharePoint framework https://dev.office.com/sharepoint/docs/spfx/sharepoint-framework-overview
In this new Client Web Part model there would be no IFrames. It will be all cient side thing.
My question is, where would the server code reside which is needed to support this new client side web part. for e.g some server side custom json/xml is queried.
Will that code reside in provider hosted App for SharePoint ??

A: SPFX webparts will not have any server side code and it is all written in Javascript/typescript with Calls made to SharePoint using REST API or using JSOM. But if you need to write some server side code for e.g.: query something from external database or for some other scenario, then you need to create an ODATA Rest WebAPI for it and consume it in your SPFX webpart .


text:
Q: UnityVS (Visual Studio Tools for Unity 1.9) + Visual Studio Ultimate 2013 Compatibility Issue? I have installed the recently released Visual Studio Tools for Unity 1.9 on my computer with a copy of Visual Studio Ultimate 2013 and am encountering a problem which I can't seem to fix. After creating a new Unity project, importing the VSTU package, and creating a script and opening it, I see a message within the VS 2013 Solution Explorer stating that:
"This project is incompatible with this version of Visual Studio"
However, I have read on the UnityVS site and nothing indicates that it is incompatible with VS 2013. Are there any possible solutions to this problem? Thanks.

A: This is an old question now, but I ran into the same problem recently with a brand new install of Unity 4.6.1, VS Professional 2013 and VSTU 2013.
A re-install of VSTU fixed the problem.


text:
Q: Regex looping through a foreach to find a certain pattern I'm using openXML and I'm trying to loop through an excel file to see if anything matches with a specific pattern. My Regex pattern is as fallows @"(?<!\w)#\w+". This should return anything that starts with a "#". There are a number of defined names that begin with "#" such as <definedName name="_KEY" hidden="1" localSheetId="3">#REF!</definedName> in my excel workbook xml. However my count is returning zero when I try and find the defined name.
My code is as fallows
First I browse for the file and select the file. I've made sure that this works perfectly.
I then try and do a count and loop through each match and it's here where I have my issue. I assume I'm messing up my foreach loop and I really need some guidance.
    var spreadsheet = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(filePath, false);
    var workbook = spreadsheet.WorkbookPart;
    var names = workbook.Workbook.DefinedNames;

    //result.InactiveNamedRangeCount = names.Where(n => n.InnerText.Contains(pattern)).Count();

    foreach (Match match in Regex.Matches(names.ToString(), @"(?<!\w)#\w+"))
    {
            result.InactiveNamedRangeCount = names.Where(n => n.InnerText.Contains(match.ToString())).Count();

    }

A: Check what is returned by names.ToString(), you shouldn't run regex on it.
To get the number of DefinedNames matching your pattern, you can use:
names.Count(n => Regex.IsMatch(n.InnerText, @"(?<!\w)#\w+"));


text:
Q: Can't redirect users to log in page when attempting to access a members only page I feel like I'm beating a dead horse by asking this question, but I'm just not understanding redirects... If a user attempts to access a members only web page without logging in, how do I redirect that user to the log in page? In my searching, I've seen several references to modifying my web.config file, however, nothing has stood out to me as being the key to getting this working... When I try to access a members only page when I'm not authenticated, I get a 404 error. When I am authenticated, the page loads just fine... What am I missing?
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
  </appSettings>
  <connectionStrings>
    <add name="LOTOConnectionString" connectionString="Data Source=WIWRMS-SQLD2\SQLD2;Initial Catalog=LOTO;User ID=LOTO_ADMIN;Password=lotoadmin"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <authentication mode="Forms">
      <forms name=".ASPXFORMSAUTH" loginUrl="~/Account/Login" defaultUrl="~/" />
    </authentication>
    <membership defaultProvider="SqlProvider" >
      <providers>
        <clear />
        <add
          name="SqlProvider"
          type="System.Web.Security.SqlMembershipProvider"
          connectionStringName="LOTOConnectionString"
          applicationName="/"
          enablePasswordRetrieval="false"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="true"
          requiresUniqueEmail="true"
          passwordFormat="Hashed"/>
      </providers>
    </membership>
    <pages enableEventValidation="false" />
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
</configuration>

A: Turns out I was on the right track. All I needed to do was modify the authentication module from:
<authentication mode="Forms">
  <forms name=".ASPXFORMSAUTH" loginUrl="~/Account/Login" defaultUrl="~/" />
</authentication>

to:
<authentication mode="Forms">
  <forms name=".ASPXFORMSAUTH" loginUrl="~/Account/Login.aspx" defaultUrl="~/" />
</authentication>

The simple mistakes get me every time.


text:
Q: How to reference pointer array to several const array I have three set of array with different data
const UINT16 array1[4] = {1,2,3,4};

const UINT16 array2[4] = {3,2,2,4};

const UINT16 array3[4] = {8,7,2,4};   //This is not PIN code, :-)

...

void example(void)
{

    UINT16 * pp;

    UINT16 data;

    pp = array1;

    data = pp[0];

    pp = array2;

    data = pp[3];

    pp = array3;

    data = pp[2];

    //and rest of code, this is snipped version of my larger code

}

in dspIC33, I get "warning: assignment discards qualifiers from pointer target type"
Based on impression from google search, I might do this way....
void example(void)
{

    const UINT16 * pp;

    pp = array1;

    pp = array2;

    pp = array3;

    //and rest of code, this is snipped version of my larger code

}

then would that make pp variable that store address data a fixed value? (ie in ROM memory)?
What the right way?, I perfer to keep data in const memory if possible?

A: You are wrong in your analysis, pp is not const but the value pointed by pp is const (that is *pp is const).
const UINT16 * pp; // means pp is a pointer to a const UINT16 value

If you want pp to be const as the address pointed is const you have to write:
UINT16 * const pp; // means pp is a const pointer to a UINT16 value

If you want to have both constness of pointer and pointed value, you have to write:
const UINT16 * const pp; // means pp is a const pointer to a const UINT16 value.


text:
Q: How to call a wizard in write function Odoo 14 In write function of  'stock.move' model , I want t return a wizard if some conditions, but that not work.
Here is my code:
 def write(self, vals):

        # Handle the write on the initial demand by updating the reserved quantity and logging
        # messages according to the state of the stock.move records.
        receipt_moves_to_reassign = self.env['stock.move']
        if 'product_uom_qty' in vals:
            for move in self.filtered(lambda m: m.state not in ('done', 'draft') and m.picking_id):
                if float_compare(vals['product_uom_qty'], move.product_uom_qty,
                                 precision_rounding=move.product_uom.rounding):
                    self.env['stock.move.line']._log_message(move.picking_id, move, 'stock.track_move_template', vals)
            if self.env.context.get('do_not_unreserve') is None:
                move_to_unreserve = self.filtered(
                    lambda m: m.state not in ['draft', 'done', 'cancel'] and float_compare(m.reserved_availability,
                                                                                vals.get('product_uom_qty'),
                                                                                precision_rounding=m.product_uom.rounding) == 1
                )
                move_to_unreserve._do_unreserve()
                (self - move_to_unreserve).filtered(lambda m: m.state == 'assigned').write(
                    {'state': 'partially_available'})
                # When editing the initial demand, directly run again action assign on receipt moves.
                receipt_moves_to_reassign |= move_to_unreserve.filtered(lambda m: m.location_id.usage == 'supplier')
                receipt_moves_to_reassign |= (self - move_to_unreserve).filtered(
                    lambda m: m.location_id.usage == 'supplier' and m.state in ('partially_available', 'assigned'))
        if 'date_deadline' in vals:
            self._set_date_deadline(vals.get('date_deadline'))
        res = super(StockMove, self).write(vals)
        if 'move_line_nosuggest_ids' in vals:
            done_qty = vals['move_line_nosuggest_ids'][0][2]['qty_done']
            for rec in self:
                if rec.product_uom_qty < done_qty:
                    return self.env["ir.actions.actions"]._for_xml_id("my_module.action_test")

        if receipt_moves_to_reassign:
            receipt_moves_to_reassign._action_assign()
        return res

What's wrong please ?
Any help?
Thanks.

A: You can not open wizard or any action from write. if you see write function's return type it's a Boolean
Thumb rule: you can not return action until browser request/call for it
The workaround you could try is, raise ValidationError or UserError with a message.


text:
Q: Is everything in Westworld made of the "white stuff"? In the opening titles of the Westworld TV series, we see various things being constructed using some sort of white "thread".

This is mostly people (hosts) and animals, but it also looks like a piano is being built this way.

Click images to embiggen.
Does this mean that all the buildings, clothes, weapons and everything else is made of this material? If so, why? Surely it would have been a lot less trouble to put a real piano in the saloon, or to build a house using real wood, for instance?

A: No.
We know for a fact that the oldest/first generations of hosts are constructed of metal and feature a much more robotic interior than the later, "white stuff" fabricated, hosts.

As for buildings, there is no evidence to support the idea that the buildings are made from the "white stuff", and there is actually evidence of the opposite; as seen through flashbacks, many of the buildings that stand have been around since the initial opening of the park (specifically in Sweetwater), long before the 'white stuff' technology was utilized.


text:
Q: How update table column using row number Hi I have a table #Configuration and if exist any record  where Schedule =N'Test' and Sequence >=2000000 and Kind <> 632  then I want update Sequence on this and other records in schedule test where Kind <>632. Sequence should start from 10 and next schould be +10 but i want the same order which is now
 So I have to update record with [ConfigurationId] = 8 and set Sequence new seqeunce  for all records in schedule test where Kind <> 632
I know that i have to use rownumber() but i don't know how.
if object_id(N'tempdb..#Configuration') is not null
drop table #Configuration;

create table #Configuration
(
    [ConfigurationId] int
    ,Kind int
    ,Schedule nvarchar(100)
    ,[Sequence] int
);

insert into #Configuration
Values ( 1,15,N'I',10)
,( 300,16,N'I',20)
,( 248,817,N'Test',3000)
 ,( 675,817,N'Test',20)
 ,( 432,632,N'Test',2000000)
 ,( 889,632,N'Test',2000010)
 ,( 1,632,N'Test',2000020)
 ,( 8,999,N'Test',2000030)
  ,( 44453,632,N'Test',2000040)

  select * from #Configuration

A: You can't use ROW_NUMBER in update statement directly, so you need to wrap a SELECT statement in a derived table or common table expression. To preserve the existing order, specify ORDER BY [Sequence] in the OVER clause. Also, filter out the rows, which values you want to be preserved (i.e. add WHERE Kind <> 632 and Schedule = 'Test'). Since you want sequence with gaps (10, 20, 30 instead of 1, 2, 3), simply multiply the generated row number by 10. And after that, use this SELECT statement to update your temp table, like this:
;with cte as (
    select c.ConfigurationId, ROW_NUMBER() OVER(ORDER BY [Sequence]) * 10 as NewSequence
    from #Configuration c
    where c.Kind <> 632 and c.Schedule = 'Test'
)
update #Configuration set
    [Sequence] = cte.NewSequence
from cte
where #Configuration.ConfigurationId = cte.ConfigurationId

select * from #Configuration


text:
Q: fitting a gam with constraints on parameters to deal with separation in parametric terms I am trying to fit a gam using mgcv which has a mix of smooth and parametric terms.  The model is for some count data on fish catches.  I am modelling variation in location and time, but also differences among individual operators.  I am interested in the differences in operators specifically, and so am treating them as a fixed effect in my model.  While there are solutions for my problem outlined below in a glm context, I need to work with a gam as I have a 2 dimensional surface that is a key feature of the model.
My challenge is that some levels of the fixed effect for vessels always have responses of 0, leading them to have coefficient estimates that move to negative infinity, due to the log link. This leads to convergence failures.
I am looking for ways to solve this issue.  One obvious solution is to move to a Bayesian approach, and use weakly informative priors on the fixed effects terms.  I have implemented this in brms, using the same structure.  This works, but the complexity of the models means that the fitting time is much longer and I have a number of data sets to analyze.
I have found a few related questions:
Dealing with quasi-complete separation in General Additive Model?
How to deal with perfect separation in logistic regression?
but the first which dealt with gams wasn't resolved, and the second didn't appear to have any viable solutions that I haven't tried.
I would like to find a way to address this using gams in mgcv.  It seems like there should be two possibilities, using penalties of some sort on the fixed effect term or imposing a constraint on the fixed effect term.  After a lot of reading, I have not been able to find a good example of a penalty approach, and I am struggling to operationalize the pcls example from the mgcv help.
The help for pcls in mgcv is https://rdrr.io/cran/mgcv/man/pcls.html and the first example is the closest to what we are trying to do.
I have included an example dataset to illustrate the problem, any suggestions are greatly appreciated.
#set up data
Lat <- runif(100,1,20)
Lon <- runif(100,1,20)
Year <- runif(100,1,10)
Vessel <- rep((1:5)/10,each = 20)
Lambda <- exp(0.1*Lat - 0.01*Lat^2 + 0.1*Lon + 0.01*Lon^2 + 0.05*Year + Vessel)
Vessel <- as.factor(Vessel)
Catch <- apply(matrix(Lambda),1,rpois,n=1)
dt <- data.frame(Lat,Lon,Year,Vessel,Catch)

#now fit gam
M <- gam(Catch ~ s(Lat,Lon) + s(Year) + Vessel, family = tw, data = dt)

#create separation, all observations zero for one vessel
dt$Catch[dt$Vessel == levels(dt$Vessel)[2]] <- 0

#now fit gam again with separation
M <- gam(Catch ~ s(Lat,Lon) + s(Year) + Vessel, family = tw, data = dt)

A: I think you'd be better off putting a ridge penalty on the Vessel parametric term using the paraPen argument to gam() rather than trying to squish the whole model in pcls().
library("mgcv")
#set up data
set.seed(1) # repeatable
Lat <- runif(100,1,20)
Lon <- runif(100,1,20)
Year <- runif(100,1,10)
Vessel <- rep((1:5)/10,each = 20)
Lambda <- exp(0.1*Lat - 0.01*Lat^2 + 0.1*Lon + 0.01*Lon^2 + 0.05*Year + Vessel)
Vessel <- as.factor(Vessel)
Catch <- apply(matrix(Lambda),1,rpois,n=1)
dt <- data.frame(Lat,Lon,Year,Vessel,Catch)

# create separation, all observations zero for one vessel
dt$Catch[dt$Vessel == levels(dt$Vessel)[2]] <- 0

# now fit gam with separation problem
m1 <- gam(Catch ~ s(Lat,Lon) + s(Year) + Vessel, family = tw, data = dt)

With the paraPen argument we can set whatever penalty you want on the individual parametric terms. A ridge penalty is an identity penalty matrix, so we can do
pp <- list(Vessel = list(rank = 4, diag(4)))
m2 <- gam(Catch ~ s(Lat,Lon) + s(Year) + Vessel, family = tw, data = dt,
          paraPen = pp, method = "REML")

We need a rank 4 penalty because the Vessel term will become 4 columns in the model matrix with the default contrasts
> contrasts(dt$Vessel)
    0.2 0.3 0.4 0.5
0.1   0   0   0   0
0.2   1   0   0   0
0.3   0   1   0   0
0.4   0   0   1   0
0.5   0   0   0   1

so we need an identity matrix that is 4x4.
Now the coefficient is reasonable and the Wald-like test indicates the importance of this term (though note Simon's warning in ?summary.gam about the default p values for paraPen terms, so we might use freq = TRUE in the summary call):
summary(m2, freq = TRUE)

> summary(m2, freq = TRUE)

Family: Tweedie(p=1.01)
Link function: log

Formula:
Catch ~ s(Lat, Lon) + s(Year) + Vessel

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  2.61557    0.06388  40.947  < 2e-16 ***
Vessel0.2   -7.88552    1.41870  -5.558 3.66e-07 ***
Vessel0.3    0.16667    0.05882   2.833  0.00586 **
Vessel0.4    0.26836    0.05867   4.574 1.77e-05 ***
Vessel0.5    0.36089    0.06286   5.741 1.72e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
              edf Ref.df      F p-value
s(Lat,Lon) 15.385 19.139 259.80  <2e-16 ***
s(Year)     1.712  2.125  24.76  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =  0.996   Deviance explained = 99.4%
-REML = 242.41  Scale est. = 0.99247   n = 100

However this is just a common-or-garden random intercept so we can do this much more easily using the random effect basis
m3 <- gam(Catch ~ s(Lat,Lon) + s(Year) + s(Vessel, bs = "re"),
          family = tw, data = dt, method = "REML")
summary(m3)

> summary(m3)

Family: Tweedie(p=1.01)
Link function: log

Formula:
Catch ~ s(Lat, Lon) + s(Year) + s(Vessel, bs = "re")

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)    1.192      1.870   0.637    0.526

Approximate significance of smooth terms:
              edf Ref.df      F p-value
s(Lat,Lon) 15.383 19.138 259.81  <2e-16 ***
s(Year)     1.716  2.131  24.73  <2e-16 ***
s(Vessel)   3.890  4.000  16.58  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =  0.996   Deviance explained = 99.4%
-REML = 242.86  Scale est. = 0.99247   n = 100

We can extract the random effects relatively easily:
library("gratia")
smooth_coefs(m3, "s(Vessel)")

> smooth_coefs(m3, "s(Vessel)")
s(Vessel).1 s(Vessel).2 s(Vessel).3 s(Vessel).4 s(Vessel).5
   1.424014   -6.489148    1.589729    1.691450    1.783955

remembering those are about the overall model constant term (the (Intercept) bit). And they match (approximately) the estimates from the paraPen model:
> sc <- smooth_coefs(m3, "s(Vessel)")
> sc[1] - sc[-1]
s(Vessel).2 s(Vessel).3 s(Vessel).4 s(Vessel).5
  7.9131616  -0.1657155  -0.2674363  -0.3599419

A: The suggestion from Simon works a treat.  Just for completeness I thought I would also provide the answer for how to make the constrained approach to the problem work.
Lat <- runif(100,1,20)
Lon <- runif(100,1,20)
Year <- runif(100,1,10)
Vessel <- rep((1:5)/10,each = 20)
Lambda <- exp(0.1*Lat - 0.01*Lat^2 + 0.1*Lon + 0.01*Lon^2 + 0.05*Year + Vessel)
Vessel <- as.factor(Vessel)
Catch <- apply(matrix(Lambda),1,rpois,n=1)
dt <- data.frame(Lat,Lon,Year,Vessel,Catch)

#create separation, all observations zero for one vessel
dt$Catch[dt$Vessel == levels(dt$Vessel)[2]] <- 0

#now fit gam again with separation
M <- gam(Catch ~ s(Lat,Lon) + s(Year) + Vessel, family = tw, data = dt)

Now we want to impose constraints on the parametric terms for the vessel effect
#get length of fixed effects coefficients and all coefficients
coefs <- coef(M)
NG <- nlevels(dt$Vessel) - 1
NC <- length(coefs)

Set up a model but don't fit it, so we can build the necessary inputs
mf <- Catch ~ s(Lat,Lon) + s(Year) + Vessel
mgam <- gam(mf, family=poisson, data=dt, fit=FALSE)

inequality constraints: all vessel coefficients must be > 0.  We want zeros in all positions not occupied by terms we want to constrain.
mgam$Ain <- cbind(matrix(0, NG, 1),
                  diag(NG),
                  matrix(0, NG, NC - (1 + NG)))
 #this should match the no columns in design matrix wide, and the number of constrained parameters in rows
mgam$bin <- rep(-100, NG)
mgam$sp <- M$sp
mgam$p <- coefs
mgam$p[2:(NG+1)] <- 1 # make initial parameters values satisfy constraints
mgam$C <- matrix(0, 0, 0)

#fit with pcls and save the output
p <- pcls(mgam)


text:
Q: What is the best way to use python code from Scala (or Java)?
Possible Duplicate:
Java Python Integration

There is some code written in Python and I need to use it from Scala. The code uses some native C. Is it possible to use this from Scala or Java without having to rewrite much?
I intend to use the code as a black-box without understanding, so I prefer not to look into it but rather to somehow generate a jar that I can import in my code.

A: Why not try Jython?You directly compile python code to Java classes or call Python code from Java through interface.


text:
Q: Can't build appcompat on Android Studio Every time I start a new project on Android Studio I have this problem. It's starting to piss me off.
Here is my build.gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion '21.0.1'

    defaultConfig {
        applicationId "com.estudiotrilha.inevent"
        minSdkVersion 9
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:support-v4:21.0.3'
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.facebook.android:facebook-android-sdk:3.21.1'
    compile 'com.google.android.gms:play-services:6.5.87'
    compile 'com.j256.ormlite:ormlite-android:4.45'
}

As expected, since I'm using appcompatv21, I need to build it using build tools 21+.
When I build, I get more than 400 errors, all looking like these:
/Users/mauricio/AndroidstudioProjects/InEvent/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/values/values.xml
Error:(609, 21) No resource found that matches the given name: attr 'windowFixedHeightMajor'.
Error:(596, 21) No resource found that matches the given name: attr 'windowFixedHeightMinor'.
Error:(590, 21) No resource found that matches the given name: attr 'windowFixedWidthMajor'.

Here is my styles.xml file. Maybe it helps to solve the problem.
<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:inevent="http://schemas.android.com/apk/lib/com.estudiotrilha.view"
    xmlns:tools="http://schemas.android.com/tools">

    <style name="Floating" parent="@style/Theme.AppCompat.Light">
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

    <style name="Transparent" parent="@android:style/Theme.NoTitleBar">
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

    <style name="NoActionBar" parent="@android:style/Theme.NoTitleBar">
        <item name="android:windowNoTitle">true</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

    <style name="Header">
        <item name="android:textColor">#0c5890</item>
        <item name="android:textSize">14sp</item>
    </style>

    <style name="Header2">
        <item name="android:textColor">#0c5890</item>
        <item name="android:textSize">16sp</item>
    </style>

    <!-- DARK ACTIONBAR -->
    <style name="DarkActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@color/backgroundDark</item>
        <item name="background">@color/backgroundDark</item>

        <item name="subtitleTextStyle">@style/TextColorDarkActionBar</item>
    </style>

    <style name="SpinnerTextAppearenceDarkActionBar" parent="@style/Widget.AppCompat.DropDownItem.Spinner">
        <item name="android:textAppearance">@style/TextColorSpinnerDarkActionBar</item>
    </style>

    <style name="TextColorSpinnerDarkActionBar" parent="@style/Widget.AppCompat.Base.DropDownItem.Spinner">
        <item name="android:textColor">@color/textLight</item>
        <item name="android:textSize">16sp</item>
    </style>

    <style name="TextColorDarkActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="android:textColor">@color/textLight</item>
    </style>
    <!-- END -->

    <!-- PURPLE ACTIONBAR -->
    <style name="PurpleActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@color/backgroundPurple</item>
        <item name="background">@color/backgroundPurple</item>

        <item name="subtitleTextStyle">@style/TextColorDarkActionBar</item>
    </style>
    <!-- END -->

    <!-- WHITE ACTIONBAR -->
    <style name="WhiteActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid">
        <item name="android:background">@color/background</item>
        <item name="background">@color/background</item>

        <item name="subtitleTextStyle">@style/TextColorWhiteActionBar</item>
    </style>

    <style name="TextColorWhiteActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid">
        <item name="android:textColor">@color/text</item>
    </style>
    <!-- END -->

    <style name="InEventTheme" parent="@style/Theme.AppCompat.Light">
        <item name="actionBarStyle">@style/WhiteActionBar</item>

        <item name="actionMenuTextColor">@color/text</item>

        <item name="setAcceptIcon">@drawable/ic_action_accept</item>
        <item name="setAddIcon">@drawable/ic_action_new</item>
        <item name="setCancelIcon">@drawable/ic_action_cancel</item>
        <item name="setEditIcon">@drawable/ic_action_edit</item>
        <item name="setFeedbackIcon">@drawable/ic_action_half_important</item>
        <item name="setMessageIcon">@drawable/ic_action_new_email</item>
        <item name="setNewEventIcon">@drawable/ic_action_new_event</item>
        <item name="setPresenceIcon">@drawable/ic_action_cc_bcc</item>
        <item name="setQuestionIcon">@drawable/ic_action_help</item>
        <item name="setRefreshIcon">@drawable/ic_action_refresh</item>
        <item name="setRemoveIcon">@drawable/ic_action_discard</item>
        <item name="setShareIcon">@drawable/ic_action_share</item>
    </style>

    <style name="WlPilatesTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="actionBarStyle">@style/DarkActionBar</item>

        <item name="actionMenuTextColor">@color/textLight</item>
        <item name="spinnerDropDownItemStyle">@style/SpinnerTextAppearenceDarkActionBar</item>
        <item name="android:spinnerDropDownItemStyle">@style/SpinnerTextAppearenceDarkActionBar</item>

        <item name="setAcceptIcon">@drawable/ic_action_accept_light</item>
        <item name="setAddIcon">@drawable/ic_action_new_light</item>
        <item name="setCancelIcon">@drawable/ic_action_cancel_light</item>
        <item name="setEditIcon">@drawable/ic_action_edit_light</item>
        <item name="setFeedbackIcon">@drawable/ic_action_half_important_light</item>
        <item name="setMessageIcon">@drawable/ic_action_new_email_light</item>
        <item name="setNewEventIcon">@drawable/ic_action_new_event_light</item>
        <item name="setPresenceIcon">@drawable/ic_action_cc_bcc_light</item>
        <item name="setQuestionIcon">@drawable/ic_action_help_light</item>
        <item name="setRefreshIcon">@drawable/ic_action_refresh_light</item>
        <item name="setRemoveIcon">@drawable/ic_action_discard_light</item>
        <item name="setShareIcon">@drawable/ic_action_share_light</item>
    </style>

    <style name="StartupABCTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle" tools:ignore="NewApi">@style/PurpleActionBar</item>
        <item name="actionBarStyle">@style/PurpleActionBar</item>

        <item name="actionMenuTextColor">@color/textLight</item>
        <item name="spinnerDropDownItemStyle">@style/SpinnerTextAppearenceDarkActionBar</item>
        <item name="android:spinnerDropDownItemStyle">@style/SpinnerTextAppearenceDarkActionBar</item>

        <item name="setAcceptIcon">@drawable/ic_action_accept_light</item>
        <item name="setAddIcon">@drawable/ic_action_new_light</item>
        <item name="setCancelIcon">@drawable/ic_action_cancel_light</item>
        <item name="setEditIcon">@drawable/ic_action_edit_light</item>
        <item name="setFeedbackIcon">@drawable/ic_action_half_important_light</item>
        <item name="setMessageIcon">@drawable/ic_action_new_email_light</item>
        <item name="setNewEventIcon">@drawable/ic_action_new_event_light</item>
        <item name="setPresenceIcon">@drawable/ic_action_cc_bcc_light</item>
        <item name="setQuestionIcon">@drawable/ic_action_help_light</item>
        <item name="setRefreshIcon">@drawable/ic_action_refresh_light</item>
        <item name="setRemoveIcon">@drawable/ic_action_discard_light</item>
        <item name="setShareIcon">@drawable/ic_action_share_light</item>
    </style>

</resources>

I don't know what to do anymore, I'm following every instruction, and it still fails to build. PS: when I use appcompatv20 it also throws a lot of errors.
Why is so harsh to use appcompat with Android Studio? This is the only library that I always waste time trying to build it.


text:
Q: Prisma .findUnique() error: Unknown arg `email` in where.email for type userWhereUniqueInput. Did you mean `id` I'm new to Prisma so bear with me. I have a (Postgres) DB on Supabase and I have the following model:
model user {
  created_at DateTime? @default(now()) @db.Timestamptz(6)
  email      String    @unique
  id         BigInt    @id @default(autoincrement())
}

As you can see, email is set to unique. However, when I try to query it with .findUnique() like so:
const data = await prisma.user.findUnique({
    where: {
        email: user.email
    }
})

I get the following error:

Error:
Invalid `prisma.user.findUnique()` invocation:

{
  where: {
    email: 'johndoe@gmail.com'
    ~~~~~
  }
}

Unknown arg `email` in where.email for type userWhereUniqueInput. Did you mean `id`? Available args:
type userWhereUniqueInput {
  id?: BigInt
}

The table is currently empty, so I am expecting to get back an empty array. But instead, I get this error. If I run the query as .findMany() I get the empty array and no error.
What am I missing here?

A: As confirmed in the comments,
prisma generate

was missing.
The command is necessary after each schema change to make prisma aware of it.


text:
Q: Restricting IP address not working in phpmyadmin In the default configuration of phpmyadmin with ISPconfig-3 on Ubuntu.
Strange thing happens, "Order Deny,Allow" & "Deny from All" works for sub-directories (blocks all requests) but not for the root of them.
/usr/share/phpmyadmin (Not working)
/usr/share/phpmyadmin/setup (working)
/usr/share/phpmyadmin/libraries (working)
/usr/share/phpmyadmin/setup/lib (working)
Can you explain this behavior? Do i miss something?
Of course I'm not going to block it at all but when it fails to bock all IPs except mine I tried to test blocking all but it fails!
Note: Ubuntu version 12.04.5 LTS
Here is the /etc/apache2/conf.d/phpmyadmin.conf
# phpMyAdmin default Apache configuration

Alias /phpmyadmin /usr/share/phpmyadmin

<Directory /usr/share/phpmyadmin>
        Options FollowSymLinks
        DirectoryIndex index.php

        ......
        Order Deny,Allow
        Deny from All

</Directory>

# Authorize for setup
<Directory /usr/share/phpmyadmin/setup>
    Order Deny,Allow
    Deny from All

    .......
</Directory>

# Disallow web access to directories that don't need it
<Directory /usr/share/phpmyadmin/libraries>
    Order Deny,Allow
    Deny from All
</Directory>
<Directory /usr/share/phpmyadmin/setup/lib>
    Order Deny,Allow
    Deny from All
</Directory>

A: I figured it out there is a configuration duplication. The main configuration file of PhpMyAdmin package (/etc/apache2/conf.d/phpmyadmin.conf) configure the directory "/usr/share/phpmyadmin", and ISPConfig re-configured it again in "/etc/apache2/sites-available/ispconfig.conf"! Honestly I didn't expect this duplication but I choose to disable the one in "/etc/apache2/sites-available/ispconfig.conf" and restriction now works.
ISPConfig is great but I think developers should consider this small issue and alike.


text:
Q: How to resolve problem about future cannot be sent between threads safely without tokio-mutex and channel? I know this question has been asked by many people, and in the past, either tokio::sync::Mutex was recommended to replace std::sync::Mutex, or it was made to be called in the same task via Channel.
What I want to know is if there is any other way to do this? In the case of my current TcpStream send.
#[tokio::test]
async fn test_send_arc_mutex_tcps() {
    async fn one(tcps: Arc<std::sync::Mutex<TcpStream>>, src: String) {
        tcps.lock().unwrap().write(src.as_bytes()).await.unwrap();
        //--------------------                      ^^^^^^ await occurs here, with `tcps.lock().unwrap()` maybe used later
        // |
        // has type `std::sync::MutexGuard<'_, tokio::net::TcpStream>` which is not `Send`
    }

    async fn two(tcps: Arc<std::sync::Mutex<TcpStream>>, src: String) {
        let w = {
            let mut tcps = tcps.lock().unwrap();
            tcps.write(src.as_bytes()) // `tcps` does not live long enough
                                       // borrowed value does not live long enough
        };
        let _ = w.await;
    }

    let tcps = TcpStream::connect("192.168.1.10:8080").await.unwrap();
    let tcps = Arc::new(std::sync::Mutex::new(tcps));
    let datum = [
        "hello".to_string(),
        "rustl".to_string(),
        "tokio".to_string(),
    ];
    for data in datum.iter() {
        let tcps1 = tcps.clone();
        let tcps2 = tcps.clone();
        let data1 = data.clone();
        let data2 = data.clone();
        tokio::spawn(async move {
            // error: future cannot be sent between threads safely
            one(tcps1, data1).await;
            two(tcps2, data2).await;
        });
    }
}


text:
Q: C# forbid duplicate Enum values Is there a way to forbid duplicate Enum values in C# or VB.NET, so that the compiler can not run?
Somthing like that:
[NoDuplicateEnumValues]
enum Importance
{
    None      = 0,
    Trivial   = 2,
    Regular   = 3,
    Important = 3,   //<-- compiler error
    Critical  = 4
};

A: No, there is no ways to do it.


text:
Q: When I debug a C program with gdb, and key in 'p system', what exactly do I get? Before I go deep into my questions, I need to confess that I am still fairly inexperienced to this subject, and am confused over quite a number of concepts, so please bear with me if my manner of asking those questions seems unorganized.
I recently learnt that as standard C library would be loaded into every C program we compiled (is this because we have #include  at the beginning of the source file?[quesiton1]), we would have its functions loaded into the memory. So, I would know that the system() function had already been loaded and stored somewhere in the memory, and then I was made know that I could find the exact address of where the system() function was stored by debugging a random C program with gdb, and issuing the command 'p system', which would print out the address of the function. I understand that 'p' is used to print variable in gdb, and 'system' in this case probably indicates the address of the system() function, so it seems to make sense to do so, but then I think to myself, wait a second, it does not appear that I have used the system() function anywhere in my code, why would the inventor of gdb include such a variable for me to print out the address of some function that I don't even use? and does this imply that the address of every function in stand C library can be found out in the same fashion? and they all have a corresponding variable name in gdb? [question2]
One more question unrelated to stuff I talked above is whether functions like system(), execve() and many others are specific to Linux OS, or they are also used in Windows OS? [question3]
Hope that you guys can help me out. Thanks in advance!

A: The standard C library is linked with every program because it's necessary for it to be there to be able to run your program. There's a lot of things happening in your program before your main function gets called and after it returns, the standard library takes care of this. It also provides you with most of the standard functions you can call. You can compile things without a standard library, but that's an advanced topic. This is pretty much unrelated to #include.
Gdb can see system with p because it prints more than just variables. It prints anything that is in scope. system just happens to be a symbol that's visible to you in that scope. You could print any symbol that's visible to you, including all the globally visible variables and functions in libc and your program. Symbols in this context means "names of various things that need to be findable by programs and other libraries", this includes all functions, variables, section boundaries and many other things that the compiler/linker/runtime/debugger need to find to do its job.
Usually the standard library gets linked dynamically, which means that every program has the exact same copy of the library. In that case all symbols in it will be visible to your program because there's no reason to exclude them. If you link your program statically only the necessary parts of libc will be included and you would probably not see the system symbol unless you actually use that function.


text:
Q: Get Previous Data Row in Oracle I have a Oracle table where data can be ordered on the basis of date. Now I have a request to get data to specific condition and previous row to that data. for example :
if I have

Date
Dept
Employee

18-Aug
2
John

19-Aug
1
Meredith

20-Aug
9
Steve

21-Aug
0
Bella

so i give condition Dept = '0' , it should retrun below 2 rows :

Date
Dept
Employee

08/20
9
Steve

08/21
0
Bella

A: This would give you all with dept 0 and it predecessors, but would not have duplicates

SELECT
"Date", "Dept", "Employee" FROM tab1 WHERE "Dept" = 0
UNION
SELECT "Date", "Dept", "Employee" FROM tab1
WHERE "Date"  IN (SELECT "DAT"
FROM
(SELECT "Date","Dept",
 LAG("Date") OVER (ORDER BY
 "Date") dat FROM  tab1 ) t1
 WHERE "Dept" = 0
)

Date  | Dept | Employee
:---- | ---: | :-------
08/20 |    9 | Steve
08/21 |    0 | Bella

db<>fiddle here

A: You may use a subquery to get the date of the required department and select the first two rows where date column is less than or equal to that department date. Try the following (Supposing that the date is unique among departments)
Select D.Date_, D.Dept, D.Employee
From tbl_name D
Where D.Date_ <= (Select Date_ From tbl_name Where Dept = 0)
Order By Date_ DESC
FETCH NEXT 2 ROWS ONLY;

See a demo from db<>fiddle.
If the date is not unique, you may choose an extra column to order by, i.e. employee column. In this case you may try the following:
With CTE As
(
  Select Date_, Dept, Employee,
         ROW_NUMBER() Over (Order By Date_ DESC, Employee) rn
  From tbl_name
)
Select Date_, Dept, Employee
From CTE
Where rn >= (Select rn From CTE Where Dept = 0)
FETCH NEXT 2 ROWS ONLY;

The second query is valid for both cases, see a demo.


text:
Q: Google API Batch Request with Node I noticed Google removed batch requests from their Node client recently:
https://github.com/google/google-api-nodejs-client/blob/0db674b7d3a04cf65e223f876cf7b3f427025cd4/MIGRATING.md
How might I write a batch request with Node? I'm trying to get the content of emails in Gmail given a set of message IDs.
Here's how Google says I should do it, but I've never made this type of request before:
https://developers.google.com/gmail/api/guides/batch

A: I've created a module as a stop gap! https://github.com/wapisasa/batchelor
I hope this got to you in time :)


text:
Q: Python Threaded Server Only Serving Once Trying to create a threaded http server. When I connect to this server through the webbrowser though I can only pull up one single thing before the server stops. Is there any particular reason this would be happening?
import socket
from threading import Thread
class http():
    def __call__():
        return 0
    def site(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind(("localhost", 5124))
            s.listen(2)
        except socket.error, (value,message):
            if s:
                s.close()
                return 2
        c, addr = s.accept()
        s = c.recv(1024)
        print s
        c.send("test")
        c.close()
        return s

serve = http()

def happy():
    while True:
        serve.site()

if __name__ == '__main__':
    Thread(target = happy()).start()

A: try target=happy, without parentheses.

A: The problem comes when the connection is closed and you try to reconnect before the socket leave the TIME_WAIT state. Try using the socket.SO_REUSEADDR socket option or use a random port every time.
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 1234))
s.listen(2)
print 'listening on port %s' % s.getsockname()[1]
while True:
    c, addr = s.accept()
    buf = c.recv(1024)
    c.send(buf)
    c.close()


text:
Q: Executing a Thread in Asynctask and its complications I was wondering is it ok to execute a Thread inside the doInBackground method of Asynctask. Should I avoid using this kind of structure on my codes? And if yes, why should I avoid it? Would this cause any ineffectiveness in my apps?

A: In principle, there's no problem with starting a thread in the doInBackground() of an AsyncTask, but sometimes you see this done not because it's the right thing to do, but because of a misunderstanding about how AsyncTask works.
The point is that doInBackground() will automatically get executed on a background (non-GUI) thread, without you needing to create a thread for it yourself. That, in fact, is the whole point of an AsyncTask. So if you have a simple, linear task that you want executed in the background, you do it with an AsyncTask, and you don't need to do any manual thread creation.
Where you might want to start a new thread in an AsyncTask is if you want your background task to use multiple threads to complete. Suppose that you were writing an app to check the online status of various servers, and display something about their status on the screen. You'd use an AsyncTask to do the network access in the background; but if you did it in a naive way, you'd end up with the servers being pinged one by one, which would be rather slow (especially if one was down, and you needed to wait for a timeout). The better option would be to make sure that each server was dealt with on its own background thread. You'd then have a few options, each of which would be defensible:

*

*Have a separate AsyncTask for each server.

*Create a thread for each server inside the doInBackground() of your single AsyncTask, and then make sure that doInBackground() doesn't complete until all the individual threads have completed (use Thread.join()).

*Use a ThreadPool / some kind of ExecutorService / a fork/join structure inside your single AsyncTask, to manage the threads for you.

I would say that with modern libraries there is rarely a need for manual thread creation. Library functions will manage all of this for you, and take some of the tedium out of it, and make it less error-prone. The third option above is functionally equivalent to the second, but just uses more of the high-level machinery that you've been given, rather than going DIY with your thread creation.
I'm not saying that threads should never be created manually, but whenever you're tempted to create one, it's well worth asking whether there's a high-level option that will do it for you more easily and more safely.

A:
is it ok to execute a Thread inside the doInBackground method of
  Asynctask.

yes it is but it really depends on your application and your usage. for example in a multithread server-client app you must create for each incoming clients one thread and also you must listen on another thread. so creating thread inside another is ok. and you can use asynctask for listening to your clients.

Should I avoid using this kind of structure on my codes? And if yes,
  why should I avoid it?

If you design it carefully you do not need to avoid, for example make sure that on rotation you do not create another asynctask because for example if your user rotates 5 times you create 5 asynctasks and in each of them you create a thread that means you will get 10 threads, soon you will get memory leak.

Would this cause any ineffectiveness in my apps? Can you explain
  these questions please.

I answered it above, I think better idea is using Thread Pool to minimize number of creating your threads or wraping your asynctask in a UI less fragment so you are sure you have one asynctask regardless of whats going to happen.

A: In any higher programming language, there is concept of multi-tasking. Basically the user needs to run some portion of code without user interaction. A thread is generally developed for that. But in Android, multi-tasking can be done by any of the three methods Thread and AsyncTask.
Thread
A thread is a concurrent unit of execution. It has its own call stack. There are two methods to implement threads in applications.
One is providing a new class that extends Thread and overriding its run() method.
The other is providing a new Thread instance with a Runnable object during its creation.
A thread can be executed by calling its "start" method. You can set the "Priority" of a thread by calling its "setPriority(int)" method.
A thread can be used if you have no affect in the UI part. For example, you are calling some web service or download some data, and after download, you are displaying it to your screen. Then you need to use a Handler with a Thread and this will make your application complicated to handle all the responses from Threads.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each thread has each message queue. (Like a To do List), and the thread will take each message and process it until the message queue is empty. So, when the Handler communicates, it just gives a message to the caller thread and it will wait to process.
If you use Java threads then you need to handle the following requirements in your own code:

*

*Synchronization with the main thread if you post back results to the user interface

*No default for canceling the thread

*No default thread pooling

*No default for handling configuration changes in Android

AsyncTask
AsyncTask enables proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
AsyncTask will go through the following 4 stages:
1. onPreExecute()
Invoked on the UI thread before the task is executed
2. doInbackground(Params..)
Invoked on the background thread immediately after onPreExecute() finishes executing.
3. onProgressUpdate(Progress..)
Invoked on the UI thread after a call to publishProgress(Progress...).
4. onPostExecute(Result)
Invoked on the UI thread after the background computation finishes.
And there are lot of good resources over internet which may help you:
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html http://www.mergeconflict.net/2012/05/java-threads-vs-android-asynctask-which.html

A: I would say there is no problem in doing that if you need something to run concurrently beside the AsyncTask.
One issue could be one of readability (using 2 different ways for concurrency), but I really can't see the harm in that - especially if one of the tasks needs to show it's result in the UI and the other one doesn't.


text:
Q: Is there any analytic method for solving $\ddot{\phi} + 2\cot{\theta}{\dot\theta}{\dot\phi} =0$ Hi i am trying to solve the following two equations:
$$\ddot{\phi} + 2\cot{\theta}{\dot\theta}{\dot\phi} =0$$
$$\ddot{\theta}-\sin\theta\cos\theta{\dot{\phi}}^2=0$$
where $\dot{\theta}=\frac{d\theta}{dt}$ and $\dot{\phi}=\frac{d\phi}{dt}$ and $\ddot{\theta}=\frac{d^2\theta}{dt^2}$ and $\ddot{\phi}=\frac{d^2\phi}{dt^2}$. I am trying to solve this analytically and looked up the standard techniques but couldn't find how solve these. Basically i want $\phi$ in terms of $\theta$ that  is $\phi(\theta)$. Is there any way to do this?

A: $$\frac{d^2\phi}{dt^2} + 2\cot(\theta)\frac{d\theta}{dt}\frac{d\phi}{dt} =0$$
This separable ODE is directly integrable.
$$\ln(\frac{d\phi}{dt})+2\ln(\sin(\theta))=\text{constant}$$
$$\sin^2(\theta)\frac{d\phi}{dt}=c_1\quad\implies\quad \frac{d\phi}{dt}=\frac{c_1}{\sin^2(\theta)}$$
Second equation :
$$\frac{d^2\theta}{dt^2}-\sin(\theta)\cos(\theta)\left(\frac{d\phi}{dt}\right)^2=0$$
$$\frac{d^2\theta}{dt^2}-\sin(\theta)\cos(\theta)\left(\frac{c_1}{\sin^2(\theta)}\right)^2=0$$
$$2\frac{d\theta}{dt}\frac{d^2\theta}{dt^2}-2(c_1)^2\frac{\cos(\theta)}{\sin^3(\theta)}\frac{d\theta}{dt}=0$$
$$\left(\frac{d\theta}{dt}\right)^2+(c_1)^2\frac{1}{\sin^2(\theta)}=(c_2)^2$$
$$\frac{d\theta}{dt}=\pm\sqrt{(c_2)^2-(c_1)^2\frac{1}{\sin^2(\theta)}}$$
$$t=\int \frac{\sin(\theta)}{\pm\sqrt{(c_2)^2\sin^2(\theta)-(c_1)^2 }}d\theta$$
$$t=\pm \sin^{-1}\left(\frac{c_2}{(c_1)^2+(c_2)^2}\cos(\theta) \right)+c_3$$
$$\frac{c_2}{(c_1)^2+(c_2)^2}\cos(\theta)=\pm\sin(t-c_3)$$
$$\theta(t)=\cos^{-1}\left(\pm\frac{(c_1)^2+(c_2)^2}{c_2}\sin(t-c_3) \right)$$

A: I think your system can be reduced to a Bernoulli Differential Equation: $y'(x)+p(x)\,y(x) = q(x) \, [y(x)]^n$.
$$$$
Rewrite $\dot{\phi}=\phi'(t)$ and $\ddot{\phi}=\phi''(t)$ by applying the chain rule for $\phi(\theta(t))$ and define $u(\theta)=\phi'(\theta)$ to get
$$u'(\theta) + 2 \cot(\theta) \, u(\theta) + \sin(\theta) \cos(\theta) \, [u(\theta)]^3 = 0 $$
$$$$
I will double-check this partial solution and write it down here step-by-step later.
$$$$
EDIT:
Considering the chain $\phi - \theta - t$, it's possible to write:
$$\frac{d\phi}{dt} = \frac{d\phi}{d\theta} \frac{d\theta}{dt}$$
$$\frac{d}{dt} \left[\frac{d\phi}{d\theta}\right] = \frac{d^2\phi}{dtd\theta}  = \frac{d^2\phi}{d\theta^2} \frac{d\theta}{dt}$$
$$\frac{d^2\phi}{dt^2} = \frac{d}{dt} \left[\frac{d\phi}{d\theta} \frac{d\theta}{dt}\right] = \frac{d^2\phi}{dtd\theta} \, \frac{d\theta}{dt} + \frac{d\phi}{d\theta} \, \frac{d^2\theta}{dt^2} = \frac{d^2\phi}{d\theta^2} \left[\frac{d\theta}{dt}\right]^2 + \frac{d\phi}{d\theta} \, \frac{d^2\theta}{dt^2}$$
Returning those results to your original system:
$$\ddot{\phi} + 2\cot{\theta}{\dot\theta}{\dot\phi} =0$$
$$\ddot{\theta}-\sin\theta\cos\theta{\dot{\phi}}^2=0$$
$$$$
$$\frac{d^2\phi}{d\theta^2} \left[\frac{d\theta}{dt}\right]^2 + \frac{d\phi}{d\theta} \, \frac{d^2\theta}{dt^2} + 2\cot{\theta} \, \frac{d\theta}{dt} \, \left[\frac{d\phi}{d\theta} \frac{d\theta}{dt}\right] =0$$
$$\frac{d^2\theta}{dt^2}- \sin\theta \cos\theta \, \left[\frac{d\phi}{d\theta} \frac{d\theta}{dt}\right] ^2=0$$
$$$$
$$\frac{d^2\phi}{d\theta^2} \left[\frac{d\theta}{dt}\right]^2 + \frac{d\phi}{d\theta} \, \frac{d^2\theta}{dt^2} + 2\cot{\theta} \, \frac{d\theta}{dt} \, \left[\frac{d\phi}{d\theta} \frac{d\theta}{dt}\right] =0$$
$$\frac{d^2\theta}{dt^2} = \sin\theta \cos\theta \, \left[\frac{d\phi}{d\theta}\right]^2 \left[\frac{d\theta}{dt}\right]^2$$
$$$$
$$\frac{d^2\phi}{d\theta^2} \left[\frac{d\theta}{dt}\right]^2 + \frac{d\phi}{d\theta} \, \sin\theta \cos\theta \, \left[\frac{d\phi}{d\theta}\right]^2 \left[\frac{d\theta}{dt}\right]^2 + 2\cot{\theta} \, \frac{d\phi}{d\theta} \, \left[\frac{d\theta}{dt}\right]^2 =0$$
$$$$
So you have a trivial equation, $[\theta'(t)]^2=0$, and
$$\frac{d^2\phi}{d\theta^2} + \sin\theta \cos\theta \, \left[\frac{d\phi}{d\theta}\right]^3 + 2\cot{\theta} \, \frac{d\phi}{d\theta} =0$$
$$$$
Define $u(\theta)=\phi'(\theta)$ to get a Bernoulli Differential Equation,
$$u'(\theta) + 2 \cot(\theta) \, u(\theta) + \sin(\theta) \cos(\theta) \, [u(\theta)]^3 = 0 \text{,}$$
which presumably has analytical solutions.

A: First, we must get rid of the middle man, $t$. In other words, we will make the following observations:
$$\dfrac{d\phi}{dt}=\dot\theta\dfrac{d\phi}{d\theta}$$ and
$$\dfrac{d^2\phi}{dt^2}=\dfrac{d}{dt}\dot\theta\dfrac{d\phi}{d\theta}=\ddot\theta\phi_{\theta}+\dot\theta^2\phi_{\theta\theta}.$$
Notice now how we have $\ddot\theta$ as $\dot\phi^2\sin\theta\cos\theta$. So the first equation becomes $$\dot\theta^2\sin\theta\cos\theta\cdot\phi^3_{\theta}+\dot\theta^2\phi_{\theta\theta}+2\cot\theta\dot\theta^2\phi_{\theta}=0$$ or $$\sin\theta\cos\theta\cdot\phi^3_{\theta}+\phi_{\theta\theta}+2\cot\theta\phi_{\theta}=0$$ This is the equation for $\phi(\theta)$. If you were not too picky about the parameter $t$, this could have been solved by [other answers on this post].
Now, notice that dividing through by $\phi_\theta$, we have
$$\sin\theta\cos\theta\cdot\phi^2_{\theta}+\dfrac{\phi_{\theta\theta}}{\phi_{\theta}}+2\cot\theta=0$$ Because we have a that second term as being $$\dfrac{d}{d\theta}\log(\phi_{\theta})$$ substitute $\phi=\int e^{\beta}\mathrm{d}\theta$. Thus,
$$\cos\theta\sin\theta e^{2\beta}+\beta_{\theta}+2\cot\theta=0$$ We're almost done. Divide through by $e^{2\beta}$, and subtract the beta-like terms to obtain
$$M+Le^{-2\beta}=\dfrac{d}{d\theta}e^{-2\beta}$$ where $M=2\sin\theta\cos\theta$ and $L=4\cot\theta$. This evidently takes the form
$$y'+ay=b$$ which has the general solution $$y=e^{-\int a}(k+\int b e^{\int a})$$ for some constant $k$, and so
$$e^{-2\beta}=e^{4\int \cot\theta\mathrm{d}\theta}\left[2\int \sin\theta\cos\theta \cdot e^{-4\int\cot\theta \mathrm{d}\theta}\mathrm{d\theta}+k\right]$$ which we know that
$$\phi =\int e^{\beta}\mathrm{d\theta}=\int \dfrac{e^{-2\int \cot\theta\mathrm{d}\theta}}{\sqrt{2\int \sin\theta\cos\theta \cdot e^{-4\int\cot\theta \mathrm{d}\theta}\mathrm{d\theta}+C_0}}\mathrm{d\theta}.$$
Edit A more complete solution would be where one notes that $e^{\int \cot \theta}=|\sin \theta|$ I'm ignoring constants because they're a pain, other than the one obtained by the linear solution. Then, $$\phi =\int \dfrac{1}{\sin^2\theta\sqrt{2\int \dfrac{\cos\theta}{\sin ^3\theta}\mathrm{d\theta}+C_0}}\mathrm{d\theta}$$ And since
$$\int \dfrac{1}{\sin^3\theta}d\sin \theta=-\dfrac{1}{2\sin^2\theta}$$ we have simply that
$$\phi = \int \dfrac{1}{\sqrt{C_0\sin^4\theta-\sin^2\theta}}d\theta=\arctan\left(\sqrt{C_0\sin^2\theta-1}\right)-\dfrac{\arctan\left(\dfrac{\sqrt{C_0\sin^2\theta-1}}{\sqrt{1-C_0}}\right)}{\sqrt{1-C_0}}$$
Please comment if I made any errors.

A: Here is my attempt. Divide the first equation by $\dot\phi$, then we get
$$ \frac{d\ln\dot\phi}{dt}+2\frac{d\ln(\sin\theta)}{dt}=0.$$
We then obtain the integral of motion
$$\ln\dot\phi+2\ln\sin\theta=C.$$
Hence, we find $\dot\phi\sin^2\theta=e^C=B$.
Plugging this in the second equation, we find
$$ \ddot\theta-B^2\frac{\cos\theta}{\sin^3\theta}\dot\theta=0.$$
Multiplying this by $\dot\theta$, we find
$$\frac12\frac{d\dot\theta^2}{dt}+\frac b2\frac{d\sin^{-2}\theta}{dt}=0,$$
where $b=B^2$.
Then we get another integral of motion, a Hamiltonian $H$.
$$\frac{\dot\theta^2}2+\frac b{2\sin^2\theta}=H.$$
I believe this is right, but I don't have time to check it carefully now.
I hope this helps.