text:
Q: Removing a rectangle with color on mouse release I am developing a game and in some part of my game I want the rectangle to disappear on mouse release. I have placed 26 rectangles in an arrayList and remove the particular rectangle clicked as the mouse is released. So if I remove the fill methods, the rectangle disappears successfully but if the fill methods are there, it does not work anymore.
Here is my paint method:
   public void paintComponent(Graphics g)
   {
      super.paintComponent(g);

        Image img = Toolkit.getDefaultToolkit().getImage(Rectangles2.class.getResource("background.jpg"));
        g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);

        Graphics2D g2 = (Graphics2D) g;

        for (Rectangle s : rectanglesList) {
            g2.draw(s);
        }

        g2.setColor(bColor);
        g2.fill(box1);
        g2.fill(box2);
        g2.fill(box3);
        g2.fill(box4);
        g2.fill(box5);
        g2.fill(box6);
        g2.fill(box7);
        g2.fill(box8);
        g2.fill(box9);
        g2.fill(box10);
        g2.fill(box11);
        g2.fill(box12);
        g2.fill(box25);
        g2.setColor(wColor);
        g2.fill(box13);
        g2.fill(box14);
        g2.fill(box15);
        g2.fill(box16);
        g2.fill(box17);
        g2.fill(box18);
        g2.fill(box19);
        g2.fill(box20);
        g2.fill(box21);
        g2.fill(box22);
        g2.fill(box23);
        g2.fill(box24);
        g2.fill(box26);
    }

Here is how I did the removing of the rectangle (Just an excerpt):
        if (box1.getBounds().contains(x, y)) {
            pickedPanelNum = 0;
            rectanglesList.remove(box1);
            panelsPane.repaint();
        }

Here are the values of the bColor and wColor:
Color bColor = Color.BLACK;
Color wColor = Color.WHITE;

NOTE:
The pickedPanelNum is just for assigning an int value and has no connection to the problem.
I think it is because when I repaint, the fill methods are still there. However I have no idea for an alternate way of painting the rectangles.
I hope my problem is stated clearly. If you have ideas how I could solve this, please tell me. Thank you!
UPDATE:
Here is a shorter, runnable version of my program. (Background image isn't included though):
import java.awt.*;
import java.awt.Color.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.geom.Rectangle2D;

public class Rec extends JComponent
{
    public ArrayList<Rectangle> rectanglesList = new ArrayList<Rectangle>();
    public int arrx[] = new int[120];
    public int arry[] = new int[120];
    JFrame frame = new JFrame();
    public int xSize = 2000;
    public int ySize = 1000;
    public int x;
    public int y;
    public int pickedPanelNum = 0;
    public String pickedPanelDash = "";
    public String pickedPanelColor = "";
    Color bColor = Color.BLACK;
    Color wColor = Color.WHITE;
    boolean removedPanel = false;

    public void launchFrame()
    {
        Random rand = new Random();
        for(int x = 0;x<120;x++)
        {
            arrx[x] = rand.nextInt(640);
            arry[x] = rand.nextInt(590);
        }

        Rectangle box1 = new Rectangle(arrx[103],arry[59],80,90);
        Rectangle box2 = new Rectangle(arrx[105],arry[3],80,90);

        rectanglesList.add(box1);
        rectanglesList.add(box2);

        JPanel mainPanel = new JPanel();

        JPanel panelsPane = new JPanel()
        {
           public void paintComponent(Graphics g)
           {
              super.paintComponent(g);

                Image img = Toolkit.getDefaultToolkit().getImage(Rectangles2.class.getResource("background.jpg"));
                g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);

                Graphics2D g2 = (Graphics2D) g;

                for (Rectangle s : rectanglesList) {
                    g2.draw(s);
                }

                g2.setColor(bColor);
                g2.fill(box1);
                g2.setColor(wColor);
                g2.fill(box2);
            }
        };

        JPanel rightPane = new JPanel();

        panelsPane.addMouseListener (new MouseAdapter ()
        {
            public void mousePressed(MouseEvent event)
            {
                x = event.getX();
                y = event.getY();
            }

            public void mouseReleased(MouseEvent event)
            {
                if (box1.getBounds().contains(x, y)) {
                    pickedPanelNum = 0;
                    rectanglesList.remove(box1);
                    panelsPane.repaint();
                }
                if (box2.getBounds().contains(x, y)) {
                    pickedPanelNum = 1;
                    rectanglesList.remove(box2);
                    panelsPane.repaint();
                }
            }
        });

        panelsPane.addMouseMotionListener (new MouseAdapter ()
        {
            public void mouseDragged(MouseEvent event)
            {
                Rec obj = new Rec();
                int dx = event.getX() - x;
                int dy = event.getY() - y;

                if (box1.getBounds().contains(x, y)) {
                    box1.x += dx;
                    box1.y += dy;
                    panelsPane.repaint();
                }
                if (box2.getBounds().contains(x, y)) {
                    box2.x += dx;
                    box2.y += dy;
                    panelsPane.repaint();
                }

            x += dx;
            y += dy;

            }

            public void mouseReleased(MouseEvent event) {}
            public void mouseClicked(MouseEvent event) {}
            public void mouseEntered(MouseEvent event) {}
            public void mouseExited(MouseEvent event) {}
        });

        panelsPane.setPreferredSize(new Dimension (800, ySize-315));
        rightPane.setPreferredSize(new Dimension (530, ySize-315));
        mainPanel.setPreferredSize(new Dimension (xSize, ySize));
        frame.setPreferredSize(new Dimension (xSize, ySize));
        rightPane.setBackground(Color.gray);
        mainPanel.add(panelsPane);
        mainPanel.add(rightPane);
        frame.add(mainPanel);

        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);

    }

    public static void main(String args[])
    {
        Rec obj = new Rec();
        obj.launchFrame();
    }
}

A: Even if you remove box1 from the List, there is nothing stopping it from getting filled in your paintComponent method, the for-loop is only drawing the outline of the rectangles within the list, but you code implicitly fills them anyway.
So, first, get rid of all the box{n} variables. Next change the paintComponent method...
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    //Image img = Toolkit.getDefaultToolkit().getImage(Rectangles2.class.getResource("background.jpg"));
    //g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
    Graphics2D g2 = (Graphics2D) g;

    for (Rectangle s : rectanglesList) {
        g2.setColor(bColor);
        g2.fill(s);
        g2.setColor(wColor);
        g2.draw(s);
    }
}

So, this just uses the rectanglesList to first draw the rectangles and the fill them
Then, lets update the mouseReleased...
public void mouseReleased(MouseEvent event) {
    // Because the rectangles are painted in order, the later
    // rectangles are painted over the eailer ones, so, we reverse
    // the list so we can check for the higher positioned
    // rectangles
    List<Rectangle> copy = new ArrayList<>(rectanglesList);
    Collections.reverse(copy);
    for (Rectangle r : copy) {
        if (r.contains(event.getPoint())) {
            rectanglesList.remove(r);
            break;
        }
    }
    event.getComponent().repaint();
}

Okay, this is little more funky, but basically, we reverse the list of rectangles (because those rectangles that appear later in the list are painted over those that appear before them) and checks to see if the mouse was clicked within any one of them.  The moment we find a match, we break out of the loop and repaint the component which generated the event
And, because it's nice to see this stuff running, a complete example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Rec extends JComponent {

    public ArrayList<Rectangle> rectanglesList = new ArrayList<Rectangle>();
    public int arrx[] = new int[120];
    public int arry[] = new int[120];
    JFrame frame = new JFrame();
    public int xSize = 2000;
    public int ySize = 1000;
    public int x;
    public int y;
    public int pickedPanelNum = 0;
    public String pickedPanelDash = "";
    public String pickedPanelColor = "";
    Color bColor = Color.BLACK;
    Color wColor = Color.WHITE;
    boolean removedPanel = false;

    public void launchFrame() {
        Random rand = new Random();
        for (int x = 0; x < 10; x++) {
            arrx[x] = rand.nextInt(640);
            arry[x] = rand.nextInt(590);
            rectanglesList.add(new Rectangle(arrx[x], arry[x], 80, 90));
        }

        JPanel mainPanel = new JPanel();

        JPanel panelsPane = new JPanel() {
            public void paintComponent(Graphics g) {
                super.paintComponent(g);

//              Image img = Toolkit.getDefaultToolkit().getImage(Rectangles2.class.getResource("background.jpg"));
//              g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
                Graphics2D g2 = (Graphics2D) g;

                for (Rectangle s : rectanglesList) {
                    g2.setColor(bColor);
                    g2.fill(s);
                    g2.setColor(wColor);
                    g2.draw(s);
                }
            }
        };

        JPanel rightPane = new JPanel();

        panelsPane.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent event) {
                x = event.getX();
                y = event.getY();
            }

            public void mouseReleased(MouseEvent event) {
                // Because the rectangles are painted in order, the later
                // rectangles are painted over the eailer ones, so, we reverse
                // the list so we can check for the higher positioned
                // rectangles
                List<Rectangle> copy = new ArrayList<>(rectanglesList);
                Collections.reverse(copy);
                for (Rectangle r : copy) {
                    if (r.contains(event.getPoint())) {
                        rectanglesList.remove(r);
                        break;
                    }
                }
                event.getComponent().repaint();
            }
        });

        panelsPane.addMouseMotionListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent event) {
            }

            public void mouseReleased(MouseEvent event) {
            }

            public void mouseClicked(MouseEvent event) {
            }

            public void mouseEntered(MouseEvent event) {
            }

            public void mouseExited(MouseEvent event) {
            }
        });

        panelsPane.setPreferredSize(new Dimension(800, ySize - 315));
        rightPane.setPreferredSize(new Dimension(530, ySize - 315));
        mainPanel.setPreferredSize(new Dimension(xSize, ySize));
        frame.setPreferredSize(new Dimension(xSize, ySize));
        rightPane.setBackground(Color.gray);
        mainPanel.add(panelsPane);
        mainPanel.add(rightPane);
        frame.add(mainPanel);

        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);

    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                Rec obj = new Rec();
                obj.launchFrame();
            }
        });
    }
}


text:
Q: how to extend a plain java class android? I am having problems properly setting up a complex listview: I am trying to create a two-level listview with a swipe tab layout, but my second level does not react to any actions taking place (e.g. clicking on an item in the list).
Perhaps I need to extend a plain java file class but I am unsure how to do this.  Suggestions?
File MainActivity.Java
  package com.learn2crack.tab;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity implements AnItemClickListener, HeadlinesFragment.OnHeadlineSelectedListener {
    ViewPager Tab;
    TabPagerAdapter TabAdapter;
    ActionBar actionBar;

    public void clickHappens(int position){
        //whatever you need to do in response to a click knowing what position in the
        //data set correlated to the row that was clicked.
         // The user selected the headline of an article from the HeadlinesFragment

        // Capture the article fragment from the activity layout
        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);

        } else {
            // If the frag is not available, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);
            android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TabAdapter = new TabPagerAdapter(getSupportFragmentManager());

        Tab = (ViewPager)findViewById(R.id.pager);
        Tab.setOnPageChangeListener(
                new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {

                        actionBar = getActionBar();
                        actionBar.setSelectedNavigationItem(position);                    }
                });
        Tab.setAdapter(TabAdapter);

        actionBar = getActionBar();
        //Enable Tabs on Action Bar
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        ActionBar.TabListener tabListener = new ActionBar.TabListener(){

            @Override
            public void onTabReselected(android.app.ActionBar.Tab tab,
                    FragmentTransaction ft) {
                // TODO Auto-generated method stub

            }

            @Override
             public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {

                Tab.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(android.app.ActionBar.Tab tab,
                    FragmentTransaction ft) {
                // TODO Auto-generated method stub

            }};
            //Add New Tab
            actionBar.addTab(actionBar.newTab().setText("Software Search").setTabListener(tabListener));
            actionBar.addTab(actionBar.newTab().setText("Maps").setTabListener(tabListener));
            actionBar.addTab(actionBar.newTab().setText("Scanner").setTabListener(tabListener));

    }

@Override
public void onArticleSelected(int position) {
    // TODO Auto-generated method stub

}

}

File SoftWareSearchActivity.java
package com.learn2crack.tab;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

interface OnHeadlineSelectedListener {
    /** Called by HeadlinesFragment when a list item is selected */
    public void onArticleSelected(int position);
}

public class SoftWareSearchActivity extends FragmentActivity
        implements HeadlinesFragment.OnHeadlineSelectedListener {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first fragment
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create an instance of ExampleFragment
            HeadlinesFragment firstFragment = new HeadlinesFragment();

            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
    }

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment

        // Capture the article fragment from the activity layout
        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);

        } else {
            // If the frag is not available, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }
}

File HeadlinesFragment.java
package com.learn2crack.tab;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // The container Activity must implement this interface so the frag can deliver messages
    public interface OnHeadlineSelectedListener {
        /** Called by HeadlinesFragment when a list item is selected */
        public void onArticleSelected(int position);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // We need to use a different list item layout for devices older than Honeycomb
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

        // Create an array adapter for the list view, using the Ipsum headlines array
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
    }

    @Override
    public void onStart() {
        super.onStart();

        // When in two-pane layout, set the listview to highlight the selected list item
        // (We do this during onStart because at the point the listview is available.)
        if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        mCallback.onArticleSelected(position);

        // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);
    }
}

File ArticleFragment.java
package com.learn2crack.tab;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class ArticleFragment extends Fragment {
    final static String ARG_POSITION = "position";
    int mCurrentPosition = -1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        // If activity recreated (such as from screen rotate), restore
        // the previous article selection set by onSaveInstanceState().
        // This is primarily necessary when in the two-pane layout.
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
        }

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.article_view, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();

        // During startup, check if there are arguments passed to the fragment.
        // onStart is a good place to do this because the layout has already been
        // applied to the fragment at this point so we can safely call the method
        // below that sets the article text.
        Bundle args = getArguments();
        if (args != null) {
            // Set article based on argument passed in
            updateArticleView(args.getInt(ARG_POSITION));
        } else if (mCurrentPosition != -1) {
            // Set article based on saved instance state defined during onCreateView
            updateArticleView(mCurrentPosition);
        }
    }

    public void updateArticleView(int position) {
        TextView article = (TextView) getActivity().findViewById(R.id.article);
        article.setText(Ipsum.Articles[position]);
        mCurrentPosition = position;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // Save the current article selection in case we need to recreate the fragment
        outState.putInt(ARG_POSITION, mCurrentPosition);
    }
}

File AnItemClickListener.java
package com.learn2crack.tab;

public interface AnItemClickListener {

    void clickHappens(int i);

}

A: short answer: you don't, classes are classes b/c you said 'class' at the beginning of the class; they are outer classes if they are outer and match the file name
if you want to communicate between a fragment and the activity that is holding it, first write an interface; u can get away with not writing one, but it's good form and helps organize your code:
package com.yourcompany.appname.interfaces;

public interface AnItemClickListener
{
void clickHappens(int i);
}

note the lack of a method body, also note that since I'm calling this an interface, I don't need to specify that these are abstract, but they are. You can add more methods, and any class that implements this must have a clickHappens method or itself be abstract, containing classes that do.
Then you edit the top of your mainActivity to say: 'public class MainActivity extends FragmentActivity implements AnItemClickListener, HeadlinesFragment.OnHeadlineSelectedListener {', meaning it has methods that provide the body for all the abstract methods in both the AnItemClickListener and the HeadlinesFragment.OnHeadlineSelectedListener interfaces.
At this point you IDE should be throwing an error and telling you that you need to implement an abstract function, so put the following method in this class:
public void clickHappens(int position){
    //whatever you need to do in response to a click knowing what position in the
    //data set correlated to the row that was clicked.
}

isn't that neat-o?
now, you can call this function in one of two ways that come immediatly to mind: if we know the fragment is only ever going to be running as a part of this activity( not being reused, which defeats one of the purposes for Fragments ) then in our fragment we can say
MainActivity.this.clickHappens(pos); //where pos is the position

but this isn't using the interface.
more robustly, since we pass this to the Fragment during onAttach, we make sure a callback can be cast correctly in onAttach like so:
class aFragment extends ListFragment{
Activity callback;

@Override
onAttach{
    try {
            callback = (AnItemClickListener) activity; //look familiar?
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() +
                                     " must implement AnItemClickListener");
        }
    }
}

so when you override onListItemClick, just say
callback.clickHappens( position );

and you've sent the clicked position to the activity that passed 'this' to the Fragment.
tell me if any part of that isn't clear =]
a more "normal" use of interfaces is when you do something like
Map map = new Hashmap<String, String>;

and then
map.get(s);

in that case, though map is a Map, you aren't calling .get() of Map--Map is only the base class--you are calling the method .get of HashMap.
gl hf

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disable mouse cursor inactivity hide The default behavior when using an external mouse with Android is to hide the cursor/mouse pointer after ~15 seconds.
How can I disable this functionality, so the cursor is shown at all times?
I'm building from AOSP source.

A: Figured it out.
The file to look in is:
frameworks/base/services/input/PointerController.cpp

The file on AndroidXRef
The inactivity timeout is defined on line 39 (Android 4.2.2):
static const nsecs_t INACTIVITY_TIMEOUT_DELAY_TIME_NORMAL = 15 * 1000 * 1000000LL; // 15 seconds

The method used for fading the cursor:
void PointerController::fade(Transition transition) {
    AutoMutex _l(mLock);

    // Remove the inactivity timeout, since we are fading now.
    removeInactivityTimeoutLocked();

    // Start fading.
    if (transition == TRANSITION_IMMEDIATE) {
        mLocked.pointerFadeDirection = 0;
        mLocked.pointerAlpha = 0.0f;
        updatePointerLocked();
    } else {
        mLocked.pointerFadeDirection = -1;
        startAnimationLocked();
    }
}

Commented out everything in the method except:
removeInactivityTimeoutLocked();

Since there's no point in having the inactivity timeout running in the background, when it isn't used.


text:
Q: Underscores in my session id I'm trying to preserve a session across an AJAX request.  Simply calling session_start() is not picking up the existing session, and instead is creating a new session id.  My solution was to pass the session id to the PHP through the AJAX call, but this resulted in the following error:

Warning: session_start() [function.session-start]: The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in ...

I believe this is because the current session id contains underscore characters, but that session id is being fetched by a call to session_id(), so how can it contain bad characters?
Simple example of what I mean:
JavaScript on page (using jQuery)
var sessID = "<?php echo session_id(); ?>";  //sessID contains underscore characters
$.get('/path/to/script.php',{sid:sessID}, function(data) {
    //do something
});

script.php
<?php
session_id($_GET['sid']);
session_start();
echo $_SESSION['some_key'];
?>

So I'm currently thinking to parse the session id on the first page, and replace any bad characters within it before trying to use it, but I'm not sure if this is the right thing to do or if I need to look elsewhere for a solution.

A: $.get('/path/to/script.php',{sid:<?php echo session_id(); ?>}, function(data) {
    //do something
});

should be
$.get('/path/to/script.php',{sid:"<?php echo session_id(); ?>"}, function(data) {
    //do something
});

A: So it turns out that underscores were not part of my problem at all.  The issue was caused by Drupal's session handling, and so it was necessary to call Drupal's bootstrap rather than session_start in the AJAX call target.
//use Drupal bootstrap instead of session_start() to access session data set by Drupal
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);
$base_url = 'http://'.$_SERVER['HTTP_HOST'];
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

Credit for solution: http://www.csdesignco.com/content/using-drupal-data-functions-and-session-variables-external-php-script


text:
Q: ASP.NET Core 2.1 Localization Options SupportedCultures always contains only English I want to setup localization in my ASP.NET Core 2.1. I build the RequestLocalizationOptions object with 6 supported cultures and configure the services, but when retrieving these options (the localizationOptions object in the code sample below), the SupportedCultures and SupportedUICultures collections only contain one culture.
public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<RequestLocalizationOptions>(opts => BuildLocalizationOptions());
        services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });

        services.AddMvc()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.SubFolder)
            .AddJsonOptions(opts => opts.SerializerSettings.ContractResolver = new DefaultContractResolver());
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();

        var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(localizationOptions.Value);

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

    private RequestLocalizationOptions BuildLocalizationOptions()
    {
        IList<CultureInfo> supportedCultures = new List<CultureInfo>
        {
            new CultureInfo("en-US"),
            new CultureInfo("en"),
            new CultureInfo("fr-FR"),
            new CultureInfo("fr"),
            new CultureInfo("ro-RO"),
            new CultureInfo("ro")
        };

        var options = new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US", "en-US"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        };

        return options;
    }

Any help would be appreciated, maybe I'm missing something.
UPDATE: Sorry, forgot to include the BuildLocalizationOptions() method.

A: I think you want to do something like:
RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions
{
    SupportedCultures = new List<CultureInfo> { new CultureInfo("en-GB") },
    SupportedUICultures = new List<CultureInfo> { new CultureInfo("en-GB") },
    DefaultRequestCulture = new RequestCulture("en-GB")
};
app.UseRequestLocalization(localizationOptions);


text:
Q: Excel data rearranging into another sheet I'd need to make excel copy/refer and restructure data from sheet 1 into sheet sheet 2.
Sheet1 has the following structure:

week..........1.........1..................2...........2................3..........3 etc.
  id...........text  A....text B.........text A......text B
  30010......200......400..............10...........20
  30011.......50.......150...............5............15

Now I'd need to make rearrange this data for sheet2 into this:

week...........1...............2...............3.....etc
   id
   30010
   Text A........200...........10..............
   Text B........400...........20..............
   30011
   Text A........50..............5.............
   Text B........150............15.............

Hopefully this illustrates the issue I haven't been able to tackle or to describe in words properly.
There are about a hundred lines (id's) that would need this sort of treatment.. thank you in advance for any help!

A: You can use pivot table for this after you copy and paste your data with 'transpose'. Here are the steps:

*

*copy your data

*Paste as 'transpose'. You should now have headers of columns as
week, id, '30010' and '30011'.

*Insert > Pivot table into new sheet with data source as your newly
pasted table.

*Drag 'week' into column labels

*Drag '30010' and '30011' into Values label (bottom right hand
corner). You should notice there is a summation of values for both
30010 and 30011 appearing in row label.

*Drag 'id' into row label.

*p.s. You can off the subtotals and grand totals. Highlight the pivot
table and copy paste into excel as text, change the labels
accordingly (eg. Row label -> Week ; 'Sum of 30010' -> '30010') as
what your table requires.

*insert a row below 'Week' and input 'ID'.
Hope that helps.

A: Tableau makes a plugin for Excel which can reshape data into a columnar format. It would put your data into four columns: ID, Week, (Text A/B), and the values in the table. I don't think it would get you exactly what you're looking for, but you could pivot Tableau's output until you have what you want.
http://kb.tableau.com/articles/knowledgebase/addin-reshaping-data-excel


text:
Q: Rounding error in c integration program im making a program that finds the integral of a function for different values of a power n, and constant a. my program seems to be working correctly but im getting a small rounding error in my results and i cant figure out why. i know i have an error as a friend of mine is also making the same program and his results are slightly different to mine, and his a definitely the right ones as doing the integration on a calculator gives values much closer to his. below are my results and his for a=2 and n=1.
His result: 0.189070
my result: 0.189053
ive tried going through and casting just about everything i can think of but still cant work out where im getting my error from, any help in pointing out where im being an idiot would be greatly appreciated! :p
My Program:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#define debug 0
#define N (double)10000

double Integrand(double x, int a, int n);
double Integral(double *x, double dx, int a, int n);

int main (int argc, char* argv[])
{
    int j,a,n=0,count=0,size=(int)N;
    double dx=1/N, x[size];

    sscanf(argv[1], "%d", &a);
    for(j=0;j<N;j++) {
        x[j]=(double)(j)*dx;
    }
    for(n=1;n<=10;n++) {
        printf("n is %d integral is %lf\n",n,Integral(x,dx,a,n));
    }
    return(EXIT_SUCCESS);
}

double Integral(double *x, double dx, int a, int n)
{
    int i;
    double result=0;

    for(i=0;i<N;i++) {
       result +=(double)((Integrand((double)x[i],a,n))*dx);
    }
    return(result);
}

double Integrand(double x, int a, int n)
{
   double result;
   result=(double)(((pow(x,(double)n))/(x+(double)a)));
   return(result);
}

A: It's not a rounding error, you just don't pick the best choice for integration points. Change the initialisation to
x[j]=(j+0.5)*dx;

so that you take the midpoint of each integration strip to calculate the value of the integrand. If you always take the left or right endpoint, you will get a systematically too large error for monotonic functions.
If you approximate the integral of a sufficiently smooth function f by a Riemann sum,
 b           n
 ∫ f(x) dx ≈ ∑ f(y_k)*(b-a)/n
 a          k=1

the choice of y_k in the interval [x_(k-1), x_k] = [a+(k-1)*(b-a)/n, a+k*(b-a)/n] influences the error and the speed of convergence. Writing
f(x) = f(y_k) + f'(y_k)*(x-y_k) + 1/2*f''(y_k)*(x-y_k)² + O((x-y_k)³)

in that interval, you find that
x_k                                   x_k                            x_k
 ∫ f(x) dx = f(y_k)*(b-a)/n + f'(y_k)* ∫ (x-y_k) dx + 1/2*f''(y_k) * ∫ (x-y_k)² dx + O(1/n^4)
x_(k-1)                               x_(k-1)                       x_(k-1)

           = f(y_k)*(b-a)/n + 1/2*f'(y_k)*(b-a)/n*((x_k-y_k)-(y_k-x_(k-1))) + O(1/n³)

and the first and largest error term with respect to the approximation f(y_k)*(b-a)/n vanishes for
y_k = (x_k + x_(k-1))/2

giving you an overall O(1/n³) error for that strip, and a total O(1/n²) error for the entire Riemann sum.
If you choose y_k = x_(k-1) (or y_k = x_k), the first error term becomes
±1/2*f'(y_k)*[(b-a)/n]²

leading to an O(1/n) total error.

A: At a Linux terminal prompt, type:
man fegetenv


text:
Q: Connecting to external unix domain socket from NDK JNI I'm building a POC Android app that needs to communicate with an ELF binary over a Unix domain socket server that the binary binds to and listens on. The app is meant for rooted phones and executes the binary as a superuser upon launch. I need to connect with the binary from my client residing in native code, which I'm presently failing to do.
I'm using a self-ported, stripped down version of libsocket to implement the domain socket functionality for both the binary and the Android app (through JNI). The binary communicates perfectly with a command line client, however, it fails to connect with the client that I've implemented in JNI code. I've made sure that the binary is running from /data/data/<my_package_name>/files and that the server socket has public access (777).
While researching the above problem, I stumbled across the fact that NDK requires LocalSockets to be in the Linux abstract namespace. My server (arm binary) binds to an absolute path (/data/data/<my_package_name>/files/serversocket) as libsocket does not support the abstract namespace for unix domain sockets (due to the usage of strlen() and strncopy() which do not support strings beginning with \0).
The following is the code for create_socket from libsocket that's failing with a negative fd.
int create_socket(const char* path, int flags) {
    if (path == NULL) {
        return -1;
    }
    if (strlen(path) > sizeof(((struct sockaddr_un*) 0)->sun_path) - 1) {
        return -1;
    }

    int fd = socket(AF_LOCAL, SOCK_STREAM | flags, 0);
    if (fd < 0) {
        return -1;
    }

    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(addr));

    addr.sun_family = AF_LOCAL;
    strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);

   // the connect call below fails, errno is set to 13 (EACCESS)

    if (connect(fd, (struct sockaddr*) &addr, sizeof(addr.sun_family) + strlen(addr.sun_path))) {
        close(fd);
        return -1;
    }
    return fd;
}

EDIT :
In the above code, the call to connect() fails, with errno being set to 13 (EACCESS). This seems to be an insufficient privileges problem.
I'm wondering if there's any way for me to connect my client to an absolute path from within NDK. It works just fine when I package the client in an ELF executable that runs as superuser, am I missing something obvious here?

A: To anyone who might be following this, it is necessary to set appropriate permissions on the socket pseudo file manually every time it is launched as root, else connect() fails with errno being set to EACCESS. I'm yet to find a better solution to this.


text:
Q: Extract time from ISO8601 string I have an ISO8601 string
2013-05-11 05:54:07.589698

Is there anyway to extract just the time from this without string manipulation?

A: There are many answers for similar questions, just posting this answer incase you haven't found it yet
NSString *inputString = @"2013-05-11 05:54:07.589698";

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS"];

NSDate *date = [dateFormatter dateFromString:inputString];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *timeString = [dateFormatter stringFromDate:date];

NSLog(@"%@",timeString);


text:
Q: Database modeling, user, moderator, admin I have a 3 type of users (users, moderator, admin).
And specific data for all 3 (users have name, admins have phonenumbers...)
My solution for roles, is two have one table "Users"(id, name...), one table "Roles" (id roles, name...) and one xref table usersXrefRoles (join table)(IDusers, IdRoles)
but that is NOT solution for the part "all 3 table have different fields", in other words do I must have 3 separate tables (users, moderator, admin) , or some kind of inheritance ?
What is the best practice for this kind od problem ?

A: sub classing.   You should have three tables, but they should be Users (with userId, name, and other fields common to all users) Every users should be in this table, including the moderator and admins. Then have two other tables with the same PK value for the users who are moderators, and the users who are admins, with the data fields specific to those roles.

A: If you have just three types of roles, you could have something as simple as single user table with a role column, that would hold an enum value (or role_id column that would hold a reference to a role table - if there is any need for that).
If you would have different fields for each user type, you could use other tables and do table subclassing but it would be nice to tell what kind of fields. Maybe there is a better way to do what you want.
Also, read about RBAC and ACLs as alternatives to static roles. Many popular frameworks come with built-in support or extensions for such solution.


text:
Q: Create another instance of GNOME shell extension for development purposes I have the Clipboard Indicator GNOME shell extension installed. How can I create another instance of the extension (for development purposes)?
I created a fork of the original project and cloned the files to
/home/rahi/.local/share/gnome-shell/extensions.
I renamed my working directory to clipboard-indicator@rahi.ca, as the original extension is named clipboard-indicator@tudmotu.com.
I restarted the GNOME shell using Alt + F2 and then r. When I try to enable my cloned extension using the Tweak tool, I do not see a second Clipboard Indicator toggle.
I'm running Ubuntu 16.04 with GNOME shell 3.18.5.

A: Open the metadata.json file located at
/home/rahi/.local/share/gnome-shell/extensions/clipboard-indicator@rahi.ca/
 and put "clipboard-indicator@rahi.ca" for the "uuid" entry so that it looks like
"uuid": "clipboard-indicator@rahi.ca",

(i.e. it should match the directory containing the metadata.json file).
You may also want to change the value for the "name" parameter.
Then save the file and restart GNOME shell (or re-login).
Then you should find another instance of the extension in Tweaks > Extensions (I renamed it "Clipboard Indicator for development"):

To learn more about uuid see this.


text:
Q: How to get request header value from http request in spring mvc using custom annotaion? How to get request header value from http request in spring mvc based on custom annotation condition on Field level Element type without using any handlerMapping object?

A: I don't really get what you're asking, Spring MVC already offers an annotation to map request headers, see the doc
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
        @RequestHeader("Keep-Alive") long keepAlive) {
    //...
}


text:
Q: Add session to fake httpContext in C# MVC project How can i add the session to a fakeContext ?
This function have we build for partial request where the content must be returned as a string.
Only we don't have sessions now in the partial request.
And i can't add them like fakeContext.Session = HttpContext.Current.Session
Someone a suggestion ?
    ///<summary>
    /// Invoke the partial request and return the result as a string.
    ///</summary>
    ///<param name="context">The controller context to use.</param>
    ///<returns>A string containing the result of the partial request.</returns>
    public String InvokeAsString(ControllerContext context)
    {
        var stringBuilder = new StringBuilder();
        //create memory writer used for httpresponse.
        var memoryWriter = new StringWriter(stringBuilder);
        //create a fake response
        var fakeResponse = new HttpResponse(memoryWriter);
        //create a fake context.
        var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
        var oldPrincipal = context.HttpContext.User;
        fakeContext.User = oldPrincipal;

        //create a fake controllercontext to use for the default invoke action.
        var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), context.RouteData, context.Controller);

        var oldContext = HttpContext.Current;
        HttpContext.Current = fakeContext;

        ManagedWebSessionContext.Bind(
            HttpContext.Current,
            SessionManager.SessionFactory.OpenSession(new Interceptor()));

        //perform the default invoke action.
        Invoke(fakeControllerContext);
        HttpContext.Current = oldContext;

        //Flush memory and return output
        memoryWriter.Flush();
        var content = stringBuilder.ToString();

        return content;
    }

A: Found the solution
fakeContext.Items.Add("AspSession", HttpContext.Current.Session);
On this way you can change the session even as fakeContext.Session is readOnly


text:
Q: How to determine if field value is an object? If this has already been asked before I apologize. I couldn't find it.
I need to loop through a list of fields in an object. I'm using:
for (var property in preferences_data.person){
    $("div.item form[name=" + property + "]").addClass('active');
}

Which worked great until the preferences_data.person object got an object as the value for one of the fields. I hoping to find a way to check if the property is an object itself and not use those, or a better way altogether.

A: if (typeof preferences_data.person[property] === "object")

A: You can use typeof for this and check if it's an object.
for (var property in preferences_data.person){
   if (typeof property !== 'object') {
      $("div.item form[name=" + property + "]").addClass('active');
   } else {
      //do something else
   }
}

A: Instead of checking for an object, which can be an object literal, array, and null will produce, you could check that the value is a string/number, for example:
for (var property in preferences_data.person) {
    var cur = preferences_data.person[property];
    if (typeof cur === "string" || typeof cur === "number") {
        $("div.item form[name=" + property + "]").addClass('active');
    }
}

Of course, if you want to still check for objects, you can filter out arrays and null by using:
var theType = Object.prototype.toString.call(obj);

theType will then be "[object Object]", "[object Array]", or "[object Null]" (among possible others). So you could use those, and/or !== null for checking against null.
Also note that characters in the value may break the attribute selector - you should always quote the value inside the selector. So change the selector to this:
$('div.item form[name="' + property + '"]')

A: how about:
(typeof property == "object")

for (var property in preferences_data.person){
     if(typeof(property) != "object")    {
          $("div.item form[name=" + property + "]").addClass('active');
     }
}

A: Try using typeof preferences_data.person[property] === 'object'

A: You can use the typeof operator to check the property is a string:
 for (var property in preferences_data.person){
    if (typeof property === "string") {
        $("div.item form[name=" + property + "]").addClass('active');
    }
 }


text:
Q: Dropzone Multiple File Select not Work Android Browser I am using file upload method using Dropzone.
The computer also works fine. It works fine in the Android Chrome app. However, Default android browser, Instagram browser etc. In some cases, the user can select multiple files, but the selected files do not cause a reaction in the browser.
Example Test : https://www.retroahsapposter.com/urun/kisisellestirilebilir-urun8489-829


text:
Q: Error using Delete Controller in MVC 5 I have three tables:
QUESTIONS (PK: QuestionID)
REPLIES (PK:ReplyID)
VOTES (PK:UserID, ReplyID)

Relationship between QUESTIONS and Table REPLIES is one-to-many. Similarly, I have one-to-many relationship between REPLIES and VOTES.
I have generated CRUD functionality controller for Question model by using MVC-Scaffolding which is working fine. But I have a problem with Delete controller which works only when there is NO reply inside question.
While debugging, I have noticed that (bool)SaveChangesError becomes true.
I have written "Delete" controller for "Replies" which works even if a reply contains "Votes".
public ActionResult DeleteReply(int? id, int returnId)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    var query = db.Replies.Where(t => t.ReplyID == id).Delete();
    return RedirectToAction("Details", new { id = returnId });
}

Does any one know what could be the issue? Any help would be appreciated.


text:
Q: PostgreSQL on Windows 10. Locale is broken I have installed PostgreSQL version 11 on Windows 10 PC two times. First time it was from official installer for Windows, second time it was a set of packages for cygwin.
The problem is, I can't get any database locale settings to work correctly. In any of the two above cases, the Postgres cluster was initialized with initdb command.
With cygwin install, the command has -E UTF8, --locale=uk_UA.utf8 and same for collation and ctypes. cygwin seemed to recognize the command, the cluster was created. Then I've created database with appropriate settings and some tables in it.
The output of simple query were plain wrong for my locale. It was $ sign instead of грн for monetary, . insteed of , for fraction and so on. The official installer gave the same results, with locale set up and displayed correctly.
Same initdb and create database are giving me correct results with linux OS.
initdb
initdb —pgdata=... \
          —locale=uk_UA.utf8
          —lc-collate=...
          —lc-type=...
          —lc-monetary=...
          —lc-numeric=...
          —lc-time=...
          —encoding=UTF-8

Here, basically I've repeated the uk_UA.utf8 locale.
Also tried with "uk-x-icu" locale, as windows version compiled with icu library as it seems.
The queries
create database db
 template         = template0
 encoding         = 'UTF8'
 lc_collate       = 'uk_UA.utf8'
 ...              = 'uk_UA.utf8'
 lc_ctype         = 'uk_UA.utf8'
 connection_limit = -1
 is_template      = false
;

create table c_types (
 id           serial,
 c_date       date,
 c_text       text,
 c_time       time,
 c_timestamp  timestamp,
 c_money      money,
 c_float      float
);

insert into c_types(c_date,c_text,c_time,c_timestamp,c_money,c_float) values
('2019-09-01', 'text0', '00:00:01', timestamp '2019-09-01 20:00:00', 1000.0001, 1000.0001),
('2019-09-01', 'text1', '00:00:02', timestamp '2019-09-01 21:00:00', 2000.0001, 2000.0001)
;

select * from c_types;

Correct output(Linux)
# id |   c_date   | c_text |  c_time  |     c_timestamp     |    c_money    |  c_float
#----+------------+--------+----------+---------------------+---------------+-----------
#  1 | 2019-09-01 | text0  | 00:00:01 | 2019-09-01 20:00:00 |  1 000,00грн. | 1000.0001
#  2 | 2019-09-01 | text1  | 00:00:02 | 2019-09-01 21:00:00 |  2 000,00грн. | 2000.0001

This post shows that lc_numeric does not do influence separator in numerics as is
https://stackoverflow.com/a/41759744/8339821
Influenced functions are to_number, to_char etc
https://stackoverflow.com/a/8935028/8339821
The question is, how can I set up Postgres for my locale?


text:
Q: Swift CHARTS library how to change the legend colour to reflect Bar chart colour I am using CHARTS library in swift. https://github.com/danielgindi/Charts and tutorial from the link https://www.appcoda.com/ios-charts-api-tutorial/ on how to customise to suit your needs.
I am trying to change the Bar chart colour using the commands below as listed in the tutorial. While the bar chart colour changes correctly but the 'legend' colour listed below the bar chart is not updated. Can some suggest how to change the legend colour to reflect the bar chart.
2 different commands suggested in the tutorial, first one to change all the bars to one single colour and second to change to multiple colours. Both works fine for changing bar chart colour but NOT the legend.
chartDataSet.colors = [UIColor(red: 230/255, green: 126/255, blue: 34/255, alpha: 1)]
chartDataSet.colors = ChartColorTemplates.colorful()

A: The documentation says you should refer to the android documentation.
https://github.com/PhilJay/MPAndroidChart/wiki/Legend
That one says:

you can retreive the Legend object from the chart using the
  getLegend() method

Then you will have access to methods that modify the way legends look.

Styling / modifying the legend
setTextColor(int color): Sets the color of the legend labels.
  setTextSize(float size): Sets the text-size of the legend labels in
  dp. setTypeface(Typeface tf): Sets a custom Typeface for the legend
  labels.

A: For swift 5 + general color change
BarChartView.legend.textColor = UIColor.white

if you want to give some special format , you can refer to
Formatting Custom Legend Entries in Chart's PieChartView?


text:
Q: Removing a macro with doxygen I have the following function:
void MYMACROTOEXPORTFUNCTION function1()

how do I instruct doxygen to remove the "MYMACROTOEXPORTFUNCTION" part from the documentation and prevent it from being shown? I already used "@cond ... @endcond" without success

A: You can do as follows (sample based on doxywizard)


text:
Q: arrays comparison
Possible Duplicate:
How to count duplicates in Ruby Arrays
Ruby: Compare 2 arrays for matches, and count the number of match instances

I am starting to using ruby language. Suppose I have two arrays:
a=["A", "B", "C", "D"]
b=["C", "A", "X", "Y", "F"]

I would like to count the number of duplicated elements of the two arrays. To achieve this, the idea I came up with is like following:
nr_of_duplicates = (a- (a - b)).size

Is there a better way to achieve this?

A: There is already a method defined in Array class for this called '&':
ary & other_ary → new_ary

Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.

   [ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]


text:
Q: Android Studio failed to build App Engine module I tried to generate app engine backend for android app module in Android Studio. First I had encountered the Maven nonexistence problem, which was solved later on. Then another problem appeared.

Below is the error log generated:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.5.1:compile (default-compile) on project AndroidBackend-AppEngine: Compilation failure
[ERROR] error: error reading C:\Users\arifsamin.m2\repository\com\google\appengine\orm\datanucleus-appengine\2.1.2\datanucleus-appengine-2.1.2.jar; error in opening zip file

Do I have to download a new repo due to this? If I have to how to do so? Android Studio is very alien to me.

A: Make sure you have fresh install of Android Studio 0.2.+. Upgrade from pre 0.2 doesn't work as google included extra maven repo to serve support libraries.
Edit:
path in the log is correct, just stackoverflow plays silly and hides \ before .


text:
Q: How can I make this branchless? (Avoiding log(0)) I have to calculate the function f(x)= x log2(x) branchlessly, defined at 0 as f(0)=0.
The problem is that c#'s Math.Log2(x) returns negative infinity for x=0 and 0*NegativeInfinity=NaN.
Can I write this branchlessly?
List<int> list = GetList();
int size = 0;
for (int i = 0; i < list.Count; i++)
{
    if (list[i] != 0)
        size += list[i] * Math.Log2(list[i]);
}

A subproblem of this might be doing the branchless version of:
int x = 0;
int y;

if (x == 0)
    y = 2; // This can be any integer as long as it's positive
else
    y = x;

I'm new to the concept of branchless code so I couldn't adapt any of the famous branchless code techniques to this problem.


text:
Q: Number of patients At a doctor's clinic patients arrive at an average rate of 10 per hour. The consultancy time per patient is exponentially distributed with an average of 6 minutes per patient. The doctor does not admit any patient if at any time 10 patients are waiting. Then at the steady state of this M/M/1/R queue the expected number of patients waiting is ?
I tried exponential distribution. But I do not know how it works.
Please help.

A: Look at Section 2.4 here  The inter-arrival time equals the service time, so we have $\rho=1.$  The system is therefore equally likely to have any number of patients from $0$ to $11$.  Notice that when there are $0$ or $1$ patients, there is no one in the waiting room.  So if $p_k$ is the steady-state probability that there are $k$ patients in the waiting room, we have $$p_k=\cases{\frac16,&$k=0$\\{1\over12},&$1\leq k\leq10$\\0,&$k>10$}$$


text:
Q: Choosing the best method to test how random are P/RNGs [1]
I'm testing some P/RNGs algorithms, so in order to see how normally distributed are the values obtained by these Random Number Generators (resp. Pseudo-), which method suits best? Is drawing the Normal Distribution Curve would be sufficient? Or doing a Chi-squared test is preferable?
By normally distributed, I mean purely random values (or pseudo-random since I am using pseudo-random number generators).
[2]
Please correct my statements if I am mistaken:

*

*In a Chi-squared test, by accepting the null hypothesis, we conclude that there is no correlation between the generated values and therefore they are "purely" random (resp. pseudo-random)

*If the obtained normal distribution curve is a Bell-shaped curve, can we reach the same previous conclusion?

A: I would start with running NIST test suite on your RNG. If you're using a vendor product then chances are that it has already been tested for randomness.
NIST suite has a lot of different tests, there's no need to invent your own unless the application is very unusual.


text:
Q: pandas - groupby and select variable amount of random values according to column Starting from this simple dataframe df:
df = pd.DataFrame({'c':[1,1,2,2,2,2,3,3,3], 'n':[1,2,3,4,5,6,7,8,9], 'N':[1,1,2,2,2,2,2,2,2]})

I'm trying to select N random value from n for each c. So far I managed to groupby and get one single element / group with:
sample = df.groupby('c').apply(lambda x :x.iloc[np.random.randint(0, len(x))])

that returns:
   N  c  n
c
1  1  1  2
2  2  2  4
3  2  3  8

My expected output would be something like:
   N  c  n
c
1  1  1  2
2  2  2  4
2  2  2  3
3  2  3  8
3  2  3  7

so getting 1 sample from c=1 and 2 samples for c=2 and c=3, according to the N column.

A: Pandas objects now have a .sample method to return a random number of rows:
>>> df.groupby('c').apply(lambda g: g.n.sample(g.N.iloc[0]))
c
1  1    2
2  5    6
   2    3
3  6    7
   7    8
Name: n, dtype: int64


text:
Q: Custom toolbox imported without elements I created a profile in order to create a custom toolbox.
I export the profile as XML file, and import it to a new project:
 The new toolbox is added as expected, but without any elements in it.
Resources panel: the profile has no hierarchy.

The Profile diagram:

Any ideas?

A: The ToolboxPage «metaclass» should be the target of extensions from one or more «stereotype» classes, each of which represents one "page" (= expandable section) of the toolbox. Within each such class, the elements and/or connectors should be represented as attributes.
In your example, it looks like you're drawing extensions not from proper toolbox page classes but from the elements you want in the toolbox. This won't work.
If you're unclear about the proper representation, use the profile helpers.
EDIT: The "Profile Helpers" webinar video on the following page is recommended.


text:
Q: Is the functor $\operatorname{Aut}(X): \operatorname{Mon} \longrightarrow \operatorname{Grp}^f$ representable ? Let $X$ be a finite set. It defines a functor from the category of (finitely generated) commutative monoids to the category of groups as follows :
$$\operatorname{Aut}(X):M\mapsto \operatorname{Aut}_M(M\times X) $$
where $\operatorname{Aut}_M$ denotes the group of $M$-equivariant automorphisms of a set on which $M$ acts (clearly, $M$ acts on $M\times X$ by multiplication on the $M$ factor). Is this functor representable ?
Motivation
This is an attempt to better understand (finite) sets as (finite) vector spaces over "the field with one element" $\mathbb F_1$, since in the case of a field $k$, we have the corresponding functor for a given vector space $E$ from finitely generated commutative $k$-algebra to groups:
$$\operatorname{GL}(E):R\mapsto \operatorname{Aut}_R(R\otimes_k E)$$
which is represented by the algebra $$k[m_{11},\dots,m_{nn},t]/(t\cdot\operatorname{det}(M)-1)$$
where $\operatorname{det}(M)$ is the usual matrix determinant, which is a polynomial expression in the $m_{ij}$'s.
What I've tried so far
For $M$ a commutative f.g. monoid, there is a natural isomorphism $$\operatorname{Aut}_M(M\times X) \simeq \operatorname{Hom}(X,M^\times)\times \operatorname{Aut}(X)$$
where $M^\times$ is the group of invertible elements of $M$. This comes from the fact that if $\varphi$ is an $M$-automorphism of $M\times X$, then it is defined by its images on the pairs $(1,x)$ where $1$ is the neutral element of $M$, by $M$-equivariance, so there is a map $\mu:X \to M$ and a map $\sigma\in\operatorname{End}(X)$ such that $$\varphi(m,x)=(m\cdot\mu(x),\sigma(x)).$$
The fact that $\varphi$ is an isomorphism implies that $\mu$ has values in $M^\times$ and that $\sigma\in\operatorname{Aut}(X)$.
I know that $M\mapsto\operatorname{Hom}(X,M^\times)$ is representable (by the free abelian group generated by $X$). I am however stuck on how to deal with the $\operatorname{Aut}(X)$.

A: The functor you describe is not representable. In the first place, a representable functor lands in $\mathbf{Set}$, not $\mathbf{Grp}$. But a more fundamental problem is that (in general) it does not preserve the terminal object: $\mathrm{Aut} (X) (1) \cong \mathrm{Aut} (X)$, and $\mathrm{Aut} (X) \cong 1$ if and only if $X \cong 1$.
Personally, I do not believe that the category of $\mathbb{F}_1$-modules is literally $\mathbf{Set}$ (or for that matter $\mathbf{Set}_*$). There are other structures that have the "correct" automorphism groups: for instance, for any set $X$, the power set $\mathscr{P} (X)$ is a join semilattice, and its automorphism group is canonically isomorphic to $\mathrm{Aut} (X)$, because $\mathscr{P} (X)$ is complete and atomic.


text:
Q: how to fetch multiselect option values with dynamic id? I have few multiselect dropdowns in my page.So I need to get the values of that multiselect selected options with id.Here the id for the particular element will be generated dynamically.
I will loop through an array then
var value = $('#' + arrayObj[i]+'option:selected').val();

I am unable to the fetch the selected option value.Instead its showing undefined

A: Here's how you could achive this. Hope it helps.

const selectList = [
  {id: 'list1', options: ['a', 'b', 'c']}
];
selectList.map(select => {
  let list = '<select id="' + select.id + '" multiple></select>';
  $('#lists-container').append(list);
  select.options.map(option => {
    $('#' + select.id).append('<option>' + option + '</option>');
  });

  $('#' + select.id).on('change', evt => {
     let result = '';
     $(evt.target).children('option:selected' ).each(function() {
      result += $( this ).text();
    });
    $("#results").text(result);
  });
});


text:
Q: iOS MDM client app sending token to app server I need some information about sending the token from iOS to the server. I know that when developing an app, NSURL can be used to specify remote server location. But, in the case of MDM in iOS, the MDM client is an in-built service. So, how do I send the device token to the MDM server? Can coding be done on built-in MDM client? How did the iOS MDM client knows to which server the token is to be sent?

A: This information is contained in the MDM profile. There will be a MDM Server URL and Checkin URL, which is where the device sends the tokens to.


text:
Q: Terminate Application on exit in Windows CE 6.0 I'm running Windows CE 6.0 on an ARM processor device using .NET CF 2.0 SP2 with an application written in C#.
I'm experiencing a problem where my application continues to run after it has closed. The application opens a connection with something connected to the device and doesn't release it until properly closed. Because of this, I cannot reopen and use the application while it continues to run and I can't run other applications which wish to use the attached device either.
I have tried to run Application.Exit() and all of my threads have the IsBackground property set to true but this doesn't work. After closing the application I can use a task manager and see that the process continues to run.
I'd normally use Environment.Exit() but this is not available in CF, unfortunately.
Is there any of methods I can try and use or causes that would be making this happen?
Thanks.

A: You could try something like this:
Process thisProcess = Process.GetCurrentProcess();
thisProcess.Kill();

And see what happens. It's obviously not ideal to closing a application, but it might work as a last resort, especially if you're handling the saving and discarding of data manually prior to that anyway.

A: For anyone still struggling with this:
I found the problem was that with Windows CE / WEHH / .NET Compact, applications don't exit on pressing the X button on a form, they are only minimized (meaning the closing event doesn't get called).
As per one of the answers on this page, the close button can be changed to actually exit the application by setting the form property 'MinimizeBox' to false.
this.MinimizeBox = false;

This will change the X button to an OK button, and will exit the application completely.

A: May be this can Help. Set Thread's Background Property to false before calling Application.exit();
private void BtnExit_Click(object sender, EventArgs e)
{
  Thread1.IsBackground = false;
  Thread2.IsBackground = false;

  Application.exit();
}


text:
Q: Hosting a WCF Service outside a WebRole and WorkerRole in x86 based C# console application on Windows Azure Cloud We want to build an azure application which uses a unmanaged win32 DLL, developed in VC++(We can not compile this dll for 64-bit) for some background processing. The very first question is - Is this possible? We have tried many approaches, but none has worked. Below is the approach we are trying currently. Please help us solve the problem or suggest a better technique.
According to our knowledge we cannot use this DLL directly inside a WebRole or WorkerRole.
For this purpose we want to build a WCF service hosted inside a x86 based C# console application which can use this Win32 DLL. We will launch this application on cloud and host our WCF service.
With this approach we developed a Cloud project in visual studio 2010 and Windows Azure SDK 1.2, which is working perfectly on local emulator. But it is not running on cloud.
To date we are able to launch this application and WCF service on cloud, but the problem
is while consuming the service it is giving following errors.
The remote server returned an error: (404) Not Found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (404) Not Found.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[WebException: The remote server returned an error: (404) Not Found.]
   System.Net.HttpWebRequest.GetResponse() +7769892
   System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +156

[EndpointNotFoundException: There was no endpoint listening at http://10.62.43.187:20000/CalculatorService/Http that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.]
   System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +4767763
   System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +1725
   emuser_WCFContract.ICalcService.Add(Int32 num1, Int32 num2) +0
   emuser_WebRole._Default.btnAdd_Click(Object sender, EventArgs e) in C:\projects\emuserWCF_HTTP\emuser_WebRole\Default.aspx.cs:39
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3691

We are using BasicHTTPBinding. Following are the details of our service contract, service class, and host application.
Service Contract:
[ServiceContract]
    public interface ICalcService
    {
        [OperationContract]
        int Add(int num1, int num2);
        [OperationContract]
        int Sub(int num1, int num2);
    }

Service Implementation Class:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
                     ConcurrencyMode = ConcurrencyMode.Multiple,
                     IncludeExceptionDetailInFaults = true,
                     AddressFilterMode = AddressFilterMode.Any)]
    public class CalcService : ICalcService
    {
        public int Add(int num1, int num2)
        {
            return num1 + num2;
        }
         public int Sub(int num1, int num2)
        {
            return num1 - num2;
        }
    }

Code snippet from WebRole.
We are using "HttpIn" endpoint of WebRole and its port to bind a service. In following code snippet, we are launching that Console application from onStart() method of WebRole(WebRole.cs)
 ProcessStartInfo psi = new ProcessStartInfo(path);
    RoleInstanceEndpoint externalEndPoint =   RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["HttpIn"];
psi.Arguments = externalEndPoint.IPEndpoint.ToString();
                              Global.ExternalIp = externalEndPoint.IPEndpoint.ToString();
                              Process dllHost = Process.Start(psi);

We know that this console application starts well on cloud, and starts hosting the WCF service.
Following is the Code snippet of console application which is hosting the WCF service.
string ep = args[0];
        string baseAddress = "http://" + ep + "/CalculatorService";
        ServiceHost serviceHost = new ServiceHost(typeof(CalcService), new Uri(baseAddress));
        Console.WriteLine("WCFHost_x86 Is Started - v1.3");
        Console.WriteLine("Endpoint Received : " + ep);
        try
        {
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(smb);
            BasicHttpBinding httpBinding = new BasicHttpBinding(BasicHttpSecurityMode.None);

            serviceHost.AddServiceEndpoint(typeof(ICalcService), httpBinding, "http://" + ep + "/CalculatorService/Http");
            Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding();
            Uri mexAddress = new Uri("http://" + ep + "/CalculatorService/Mex");
            serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, mexAddress);
            mexAddress = new Uri("http://" + ep + "/CalculatorService/Http/Mex");
            serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, mexAddress);
            serviceHost.Open();
            Console.WriteLine("Service Started At Endpoint : " + baseAddress);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error In Starting WCF Host : " + ex.Message);
        }
        Console.WriteLine("Press <Enter> To Exit");
        Console.ReadLine();

Following is code snippet of WCF Client that we creating on Deafault.aspx.cs page.
private static bool initilized = false;
    private static ICalcService CalculatorClient;
    protected void Page_Load(object sender, EventArgs e)
    {
        lblService.Text = "http://" + Global.ExternalIp + "/CalculatorService/Http";
        lblExtIp.Text = Global.ExternalIp;
        if (!initilized)
        {
            BasicHttpBinding httpBinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            EndpointAddress endPoint = new EndpointAddress("http://" + Global.ExternalIp + "/CalculatorService/Http");
            ChannelFactory<ICalcService> factory = new ChannelFactory<ICalcService>(httpBinding, endPoint);
            CalculatorClient = factory.CreateChannel();
            initilized = true;
        }
    }
     protected void btnAdd_Click(object sender, EventArgs e)
    {
        int num1 = Int32.Parse(txtNum1.Text);
        int num2 = Int32.Parse(txtNum2.Text);
        int result = CalculatorClient.Add(num1, num2);
        txtResult.Text = result.ToString();
    }

Please help us solve the problem or suggest a better technique. Thanks In Advance

A: A few shots in the dark - could it be that you require running under elevated privileges?


text:
Q: How do I deal with different keyspace definitions between environments? i have a code-related question for cassandra.
in dev/qa, we have a 1-node cassandra cluster
in stage/prod environments, we have multiple-nodes in a cluster.
same cluster NAME, same keyspace name, but different replication factors needed.
how does everybody manage their code-base? an example below is when i need to deploy my scripts to dev/qa, we chose a simplestrategy repl factor.
when we need to go to the stage/prod deploy.. we need to now use a NetworkTopologyStrategy with a repl factor = 3.
right now, i'm forced to deploy different scripts, or comment out one line for the other in my scripts:
two versions:

*

*create_keyspace_tables.dev.cql

*create_keyspace_tables.stg.cql

sample script contents in which i have to deal with 2 diff replication factors:
    -- dev/qa
    -- CREATE KEYSPACE IF NOT EXISTS mykeyspace WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
    -- stage/prod
    -- CREATE KEYSPACE IF NOT EXISTS mykeyspace WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
    USE mykeyspace;
    CREATE TABLE my_table (
        storeNumber text,
        businessDate timestamp,


text:
Q: Why not make ε arbitrarily small in the (ε, δ)-definition of limit The $(ε, δ)$-definition of limit:For every real $ε > 0$, there exists a real $δ > 0$ such that for all real $x$, $0 < | x − a | < δ$ implies $| f(x) − L | < ε$.
From my point of view, I think ,in fact we want to make $f(x)$ can be made arbitrarily close to $L$ here, so it would be better to change "every real $ε > 0$" in the definition to "arbitrarily small real $ε > 0$", what do you think about my opinion here ?

A: That is exactly what we mean by "for every". We can take $\epsilon$ as small or large as we like. There is no need to change the statement, because it already hold for arbitrarily small $\epsilon$, since it holds for every $\epsilon \ge 0$. In math we want to be as general as possible, which here means saying that the statement must hold for every $\epsilon > 0$.


text:
Q: Why when I do write.csv I don't get the exact same dataframe output as it shows in the global environment In the dataframe I have something that looks like. Im satisfied with this look
ID1|PRO1|PRO2|PRO3|PROALL|PROALLINFO
  1   Y     Y    Y      Y   Y/Y/Y
  2                         No PRO1/No PRO2/ No PRO3
  3   Y     Y           Y   Y/Y/No PRO3/

In order to get that df i started off with
ID1|PRO1|PRO2|PRO3|
  1    Y    Y    Y
  2    N    N    N
  3    Y    Y    N

What I did was create a list
 PROALL LIST <- c("PRO1","PRO2","PRO3")

Then i created a script trying to say whenever one of those values is "Y" then assign "Y" for the new script which worked. Then i made another column based on the results of the cell to add as text in a second column.
df2<- df1 %>%
 mutate(PROALL=ifelse(is.na(.[PROALL LIST], "N",Y")) %>%
 mutate(PROALLINFO(ifelse(.$PRO1 == "Y", paste0(ifelse(!is.na(.$PRO1),.$PRO1,"No PRO1"),"/"
 ifelse(!is.na(.$PRO2),.$PRO2,"No PRO2"),"/",ifelse(!is.na(.$PRO3),.$PRO3,"No PRO3"))

As i did this script the outcome was the same as the dataframe outcome i have in global environment. The problem is when i do
write.csv(df2,"SAMPLE.csv",row.names=FALSE, na="")

I get a excel file with these set of columns. All I want it to do is to put out a file that resembles my dataframe in r.
ID1|PRO1|PRO2|PRO3|PROALL.PRO1|PROALL.PRO2|PROALL.PRO3|PROALLINFO.PRO1|PROALLINFO.PRO2|PROALLINFO.PRO3

A: Apart from typos, missing brackets and quotes in the code another issue with the code is ifelse(is.na(.[PROALL LIST], "N",Y") returns a matrix and then further code is ran on the matrix. So the final output (df2) consists of a dataframe which has a matrix in it. Although it "looks" correct but looking at str(df2) would give you the real understanding of the data.
Here is one way to solve this. Note that I have kept the approach general so if the number of columns in PROALL_LIST increase the code need not to be changed and it will work for any number of columns.
library(dplyr)

PROALL_LIST <- c("PRO1","PRO2","PRO3")

df2 <- df1 %>%
  mutate(PROALL=ifelse(rowSums(.[PROALL_LIST] == 'Y') > 0, 'Y', 'N')) %>%
  rowwise() %>%
  mutate(PROALLINFO = {
    x <- c_across(PROALL_LIST)
    paste0(ifelse(x == 'N', paste('No', PROALL_LIST), x), collapse = '/')
  }) %>%
  ungroup

df2

# A tibble: 3 x 6
#    ID1 PRO1  PRO2  PRO3  PROALL PROALLINFO
#  <int> <chr> <chr> <chr> <chr>  <chr>
#1     1 Y     Y     Y     Y      Y/Y/Y
#2     2 N     N     N     N      No PRO1/No PRO2/No PRO3
#3     3 Y     Y     N     Y      Y/Y/No PRO3

str(df2)
#tibble [3 × 6] (S3: tbl_df/tbl/data.frame)
# $ ID1       : int [1:3] 1 2 3
# $ PRO1      : chr [1:3] "Y" "N" "Y"
# $ PRO2      : chr [1:3] "Y" "N" "Y"
# $ PRO3      : chr [1:3] "Y" "N" "N"
# $ PROALL    : chr [1:3] "Y" "N" "Y"
# $ PROALLINFO: chr [1:3] "Y/Y/Y" "No PRO1/No PRO2/No PRO3" "Y/Y/No PRO3"

write.csv(df2,"SAMPLE.csv",row.names=FALSE, na="")


text:
Q: MySQL get relations users by one query from two tables Im trying to get list of "friends" from my tables. I have a two tables, one where I store users list, and second one where I store relations with this users. I add on sqlfiddle example schemas. I need to fetch all "friends" for specified user id:
CREATE TABLE tbl_users
    (`id` int, `name` varchar(7), `description` varchar(55));

INSERT INTO tbl_users
    (`id`, `name`, `description`)
VALUES
    (1, 'John', '111'),
    (2, 'Derrik', '222'),
    (3, 'Nikolas', '333'),
    (4, 'Hellen', '444'),
    (5, 'Jack', '555');

CREATE TABLE tbl_relations
    (`id` int, `user_id` int, `following_id` int);

INSERT INTO tbl_relations
    (`id`, `user_id`, `following_id`)
VALUES
    (1, '1', '2'),
    (2, '1', '3'),
    (3, '1', '4'),
    (4, '2', '1'),
    (5, '4', '1');

Yes, I can do two queries and then compare it, but I thing this should work with one.
Result expected: if specified user id = 1, result should be get 2,4 user
Thx.

A: If the table

*

*users

*relations

The two tables must have columns that have the same value. If the columns is user_id so
SELECT * from users,relations WHERE users.user_id = relations.user_id;
I hope this answer can help you :)

A: try this:
SELECT tbl_users.*

FROM tbl_users

INNER JOIN tbl_relations ON tbl_relations.user_id = tbl_users.id

More about join

A: "Result expected: if specified user id = 1, result should be get 2,4 user"
SELECT x.following_id reciprocations
  FROM tbl_relations x
  JOIN tbl_relations y
    ON y.user_id = x.following_id
   AND y.following_id = x.user_id
 WHERE x.user_id = 1;

A: This should return 2,3 for user id 1
SELECT id FROM tbl_relations
WHERE user_id = 1 AND id != user_id;

To get the friends instead of their ids use
SELECT * from tbl_users WHERE id IN (SELECT id FROM tbl_relations
WHERE user_id = 1 AND id != user_id);


text:
Q: How to make a shortcut of day display e.g Thursday 14/07/2022 => Thu 14/07/2022 in Django html template I have booking start date as follow

{{ booking.start_time|date:"j/F/Y" }}
 on Django html template which it displays the date as  14/July/2022 on the DOM, how I can make it display like this Thu 14/07/2022

A: You can do it like that:
from django.shortcuts import render
import datetime
currentdate = datetime.date.today()
print(currentdate)
print(currentdate.strftime("%a %d/%m/%y"))

In django html template i think it would be like that. I choose "d" for the day because it will be displayed with leading zeros.

{{ booking.start_time|date:"D d/m/Y" }}

A: According to the documentation:

{{ booking.start_time|date:"D j/m/Y" }}


text:
Q: How would you find the eccentricity of this conic section? $4x^2 - 5y^2 - 16x - 50y + 71 = 0$
Thank you!

A: Rewriting this in standard form we get
\begin{align*}
4x^2-5y^2-16x-50y+71 &= 4x^2-16x-5y^2-50y+71\\
&=4(x^2-4x)-5(y^2+10y)+71 \\
&= 4(x^2-4x+4)-16-5(y^2+10y+25)+125+71\\
&=4(x-2)^2-5(y+5)^2+180=0\\
&=4(x-2)^2-5(y+5)^2 = -180\\
&=5(y+5)^2-4(x-2)^2=180
\end{align*}
Dividing both sides by $180$ we get $$\frac{(y+6)^2}{36}-\frac{(x-2)^2}{45} = 1$$
This is a hyperbola with $a=6, b=3\sqrt5$ so $c = \sqrt{36+45} = 9$. The eccentricity is given by $\dfrac{c}{a}$. So it is $\dfrac96 = \dfrac32$.


text:
Q: Hosting Multiple Service Contracts in IIS How to host multiple service contracts in IIS. example , I have 3 different service contracts in my project and implements in three different class's. First I host a service contract in IIS with SVC file, now i want o host the another service in the same service. is it possible?
or
How to expose multiple service contracts in a single service (svc file) , is it possible?Please give me some inputs for this solution.

A: Yes. Your .svc file refers to the service class. This class can implement multiple service contracts, simply by listing them. Abbreviated example:
[ServiceContract]
public interface ICalculator // ...

[ServiceContract]
public interface IHelloWorld // ...

public MyMultiContractService : ICalculator, IHelloWorld // ...

<%@ServiceHost language=c# Debug="true" Service="MyMultiContractService"%>

A: If you are not aware already here is a nice screencast series on WCF.
http://msdn.microsoft.com/en-us/netframework/wcf-screencasts.aspx


text:
Q: Mysql in Python Query 2 or Parameters I am trying to send two parameters in my sql search using python. When I run the query in sql workbench it gives me the right result. Like the following:
Command used:
Select Name, Rating
From Restaurant
Where Location = "جوہر ٹاؤن" AND RestaurantID IN (SELECT RestaurantID
                                                  FROM Cuisine
                                                  WHERE Name = "چائنيز")
ORDER BY Rating DESC LIMIT 3;

What im trying to do is send a value that user enters using the variable location and cousin.
This is the query I am getting an error on.
query = "Select Name From Restaurant Where Location = '%s' AND RestaurantID IN (SELECT RestaurantID FROM Cuisine WHERE Name = '%s' ) ORDER BY Rating DESC LIMIT 3;" % (location,cuisine)

I have also tried the following:
query = "Select Name From Restaurant Where Location = {} AND RestaurantID IN (SELECT RestaurantID FROM Cuisine WHERE Name = {} ) ORDER BY Rating DESC LIMIT 3;". format(location, cuisine)

For both cases that I have tried my query returns empty. Any ideas?


text:
Q: Self Initializing Cellular Automata What is the largest cellular automata one can generate given the conditions:
-n x m rectangular grid
-Basic Conway Rules
-Grid is not continuous (meaning edge behavior is not wrapped)
-perfectly/near perfectly reproduces its initialization pattern (therefore recursive).


text:
Q: Is there some place on the internet where I can run my Java program? A program I am working on takes forever to complete (~3days, everytime).
Is there some place on the internet where I can leave the code, some robot might run it for me and I can come back and collect the results? Some online judge that offers this capability?
[I am not talking abt optimisations here.]

A: You may need to go to something like this:

Amazon Elastic Compute Cloud (Amazon
  EC2) is a web service that provides
  resizable compute capacity in the
  cloud. It is designed to make
  web-scale computing easier for
  developers.

http://aws.amazon.com/ec2/

A: If you really cannot run it on your own machines, you can run in on Amazon EC2 cloud.  You would need to maintain a virtual machine, but Amazon provides some preconfigured settings.
The pricing starts with $0.085/hour (~$6 for three days).  The actual price is determined by the duration of use and your CPU needs.  Higher CPU capability is more expensive.


text:
Q: Postman Retry logic goes in infinite loop I am using postman for testing my API.
One of the API which takes some time to process the data I have added a retry logic to try  3 times to check if the end points work fine.
The initial value of retryCount is 3 which is set in the few test before this test where retry is executed.
Below is the code:
let retryCount = pm.environment.get('retryCount');
let responseData = pm.response.json();
console.log(responseData.data.events.length);
console.log(retryCount);
if(responseData.data.events.length == 0 && retryCount > 0)
{
    retryCount = retryCount - 1;
    console.log(retryCount);
    pm.environment.set('retryCount',retryCount);
    postman.setNextRequest("GetEvents");
}
else
{
    pm.environment.set('data-response',responseData.data);
}

After 3 retries it should stop. however, it goes in the infinite loop. The problem is occurring because the variable is always 3 when the next call happens it should reduce by 1 and eventually become 0.
what could be the reason that above code goes in infinite state.

A: You might be reseting the value some where in collection scripts or some where elese in your collection. Create a new variable and try, use below method :
pm.variables.get("retryCounter")===undefined ? pm.variables.set('retryCounter',3):null

let responseData = pm.response.json();
console.log(responseData.data.events.length);

retryCount = pm.variables.get("retryCounter");
console.log(retryCount);
if(responseData.data.events.length === 0 && retryCount > 0)
{
    retryCount = retryCount - 1;
    console.log(retryCount);
    pm.variables.set('retryCounter',retryCount)
    //this gives this request name , you don't have to hardcode
    postman.setNextRequest(pm.info.requestName);
}
else
{
    pm.environment.set('data-response',responseData.data);
}

Try this code , here we are using pm.variables.set  which creates local variables. As the life time of local variable is the entire collection run and after that it will be destroyed, so for every new collection run the value will be undefined.
we are setting the value to 3 if its undefined . and then sends the request till the value becomes less than 1.


text:
Q: How to enforce a commit message policy when doing squash merge via GitHub Web UI? We do have a commit hook to enforce messages that follow config-conventional:
package.json
"husky": {
    "hooks": {
        "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
        "pre-commit": "yarn format:check",
        "pre-push": "yarn run test"
    }
},
"commitlint": {
    "extends": [
        "@commitlint/config-conventional"
    ],
    "rules": {
        "scope-case": [
        0,
        "always",
        "pascal-case"
        ]
    }
},

However, if me merge a PR with the squash strategy (via github web ui) then it is possible that a commit message is being sneaked in as the policy is not being enforced here:
feat: [TICKET-209] add completion tests
Added build instructions to README.md <-- Added via squash
feat: [TICKET-208] improve tests

This part of the GitHub history is the result of the 2nd line being added through a squash and therefore not being checked/rejected.
Is there a solution to reject invalid commit messages which are added via squash on github web ui?

A: If your priority is making sure no commits enter the main branch without the right format, then "Merge queue + Github Action to check commit msg" might solve this problem: https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-a-merge-queue (note this feature is in public beta)


text:
Q: How can I install Pytorch version 1.1 on Windows x64? I need to install an older version of Pytorch, version 1.1, on my Windows 10 x64 machine.
The instructions here tell me to download the wheel and install it. However, pip refuses to install this wheel, claiming it is not supported on my platform. I suppose that is because, judging by the the name of the wheel (torch-1.1.0-cp37-cp37m-win_amd64.whl) it is meant for AMD, and I'm on an Intel i7. I found no better matching wheel on the Pytorch site.
What is the easiest way to install Pytorch 1.1 on my machine?

A: You can use conda
conda install pytorch=1.1.0

I've checked the exisiting versions with conda search -f pytorch and 1.1.0 (and many others too) is available.

A: The current error is most likely because you are running Python 32 Bit, or a different CPython version. The following answer is solving the CPython version error. I couldn't find any 32bit python versions of pytorch.

Before using this solution, make sure you are using 64-bit Python, not OS! You can check this using the following code in command prompt:
>python
>import platform
>platform.architecture()

If it says '64bit', this solution should work. If not, download a 64-bit version of python. Unfortunately, I don't know any other alternative.

There are multiple different Pytorch versions for 1.1.0 if you want to use a GPU or want to be CPU only.
For Cuda 10.0: https://download.pytorch.org/whl/cu100/torch_stable.html
For Cuda 9.0: https://download.pytorch.org/whl/cu90/torch_stable.html
For CPU only: https://download.pytorch.org/whl/cpu/torch_stable.html

Then use ctrl+f to search for:
torch-1.1.0-cp{CPython version}-cp{CPython version}m-win_AMD64.whl

Replace {Cpython version} with your python version, for example 37 for 3.7.
Then download that file. Install using:
pip install <path to wheel file>


text:
Q: String Handeling Problem while Printing max/min code point of character I was trying to print the max & min code point value of character in each word of String.
char max=' ', min='z';
int word=1;
for(int i=0;i<s.length;i++) {
  for(int j=0;j<s[i].length;j++) {
    if(s[i].charAt(j)<min)
      min=s[i].charAt(j);

    if(s[i].charAt(j)>max)
      max=s[i].charAt(j);
  }
  System.out.println("CHARACTER WITH MAX & MIN CODE POINT VALUE  IN WORD "+word +"IS: "+ max + min);
  word++;
}
}

It's having the following error in the 5th line:

variable.length can't provide actual value.

What is the root cause for that error message?

A: The line 4th code should be: for(int j=0;j<s[i].length();j++) {

*

*.length is the attribute for Array.

*[].length attribute can get the number of objects in Array.

*.length() is the function for String.

*String.length() function can get the number of characters in String.