text:
Q: Capture output of a command, process it and ONLY then output to terminal I would like to capture the stdout (as sent to a terminal), and perform some processing after it is output on the terminal (for the user).
I want to know how to grab the output, process and make changes accordingly.
(If possible) I want this to happen for every command I type on the terminal.

Edit: After a dialogue in a temporary chat forum it was clear that

*

*we should

*

*both look for which commands are issued

*and what output there is from the commands and

*do something, if a particular command or output is detected.

A: Well, maybe it is not a good idea to grab the output, process and display the output of every command you type on the terminal.
But you can do it for some particular command via tee
your-command | tee saved-output | processing-tool

When you have seen the result from the processing-tool, you can look at the saved-output for example with cat (if short output) or less (if long output).
Example:
$ LANG=C sudo lshw | tee saved-output | grep -i -A2 disk
        *-disk
             description: ATA Disk
             product: KINGSTON SKC300S
             physical id: 0.0.0
--
        *-disk
             description: ATA Disk
             product: WDC WD4002FYYZ-0
             vendor: Western Digital
$ less saved-output

After a dialogue in a temporary chat forum , I suggest to

*

*try vialog or viafifo according to the following links

*maybe modify one of them to do what is expected in this case,

*

*both look for which commands are issued

*and what output there is from the commands and

*do something, if a particular command or output is detected.

*Send a notification or alert when bash asks for input from user

*This link to AskUbuntu
It works directly to use vialog like the following example.
vialog 2>&1 | tee saved-output | grep 'docker container ls' && echo 'it was mentioned'

In the real case, I think you would like to start something more advanced than echo 'it was mentioned', but this is only a demo example. And things can be more efficient, if you build the specific checks into vialog and disable the alerts, that are probably not necessary in your case.
Screenshot during the dialogue:

Screenshot after the dialogue:

This way you can easily check if a command that is called is not found:
$ LANGUAGE=C vialog 2>&1 | tee saved-output | grep -i 'Command.*not found' && echo 'it was mentioned'
Command 'docker' not found, but can be installed with:
it was mentioned
$ cat saved-output
----- start vialog at 2019-01-12 18:57:33 ----------------------------
$ docker container ls

Command 'docker' not found, but can be installed with:

sudo apt install docker.io

$ exit
exit
------- end vialog at 2019-01-12 18:58:01 --- used 28 seconds


text:
Q: problem with setters and getters Hi I'm Trying to work with setters and getters in python for one class and I want to use the setter with other instruction, so when setting the property value, the setter do more than only assign the value to the property. Maybe I'm confused on how the setter and getter work. Here is an example:
class test:
      self.x = None

      @property
      def var(self):
           return self.x

      @var.setter
      def var(self, value):
           print("Assigning Value")
           self.x = value

 v = test()
 v.var = "hello"

So what I'm trying to do in this example is to print "Assigning Value" when x value is assigned, but so far Isn't working.
My question is. Do I'm doing something wrong?,Do I miss something?, or that's not the way setters and getters work?
Thanks

A: Change
class test:

To:
class test(object):

In Python 2.x you can only use the descriptors if inheriting from object. (Its a backwards compatibility thing). Fortunately, this has been resolved in Python 3.x

A: At this point, there is no self:
class test:
      self.x = None
#     ^^^^^ BAD

change it to either set in the initializer:
class test:
     def __init__(self):
         self.x = None

or use a class attribute normally.
class test:
      x = None

If you aren't sure which, go with the first; it'll confuse you less to use that pattern until you are more confident about the difference.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does my header moves down when I set it fixed? In my header I put the title of the page and my navbar, but as soon as I set it position:fixed; the margin on the top increased. Here is the link to Codepen:

@import "https://fonts.googleapis.com/css?family=Permanent+Marker|Work+Sans|Oswald|Baloo+Bhaijaan|Roboto" ;

  #header{
    background-color:#191919;
    height:3rem;
    width:100%;
    position:fixed;
}

#header-img{
  font-family: 'Permanent Marker', cursive;
  color:white;
  margin-left:1.5rem;
  float:left;
  font-size:25px;
}
ul{
  list-style:none;
  display:flex;
  flow-direction:row;
  justify-content:space-around;
}

#nav-bar{
  background-color:#191919;
  float:left;
  width:100%;
}

#form{
  margin-top:45rem;
  margin-left:25%;
  margin-right:25%;
}

img{
  width:70%;
  height:70%;
}

a {
  text-decoration:none;
  font-family: 'Work Sans', cursive;
  color:white;
  font-size:12px;
}

#email{
  width:100%;
  box-shadow:3px 3px 5px grey;
}

#submit{
  font-family:'Roboto', cursive;
  font-size:14px;
  font-weight:bold;
  color:#686868;
  box-shadow:3px 3px 5px grey;
  padding: 5px 5px;
}

.catalog{
  margin-left:10%;
  margin-right:10%;
  margin-top:5rem;
  width:90%;
  float:left;
}

#password{
  width:100%;
  box-shadow:3px 3px 5px grey;
}

#video{
  margin-top:5rem;
  margin-left:25%;
  margin-right:25%;
  width:50%;
}

#courses{
  display:flex;
  flow-direction:row;
  flex-wrap:wrap;
}

#description{
  font-family: 'Oswald', cursive;
  font-size: 20px;
  text-align:center;
  font-size:16px;
}

li{
  padding: .25rem .5rem;
}

a:hover{
 color:#4ba0c8;
}

.nav-link{

}

.course-label{
  font-family: 'Baloo Bhaijaan', cursive;
  font-size:18px;
}

.images{
    margin: 5% 5%;
    padding: 3% 3%;
    width: 10vw;
    height:10vw;
    color:#d2d2d2;
  }

.images:hover{
  background-color:#99d3ff;
  color:#99d3ff;
}

@media (min-width:555px){
  #nav-bar{
    float:right;
    width:20rem;
    margin-right:1rem;
  }

  #form{
    margin-top:5rem;
  }
}
@media (min-width:360px){
  a{
    font-size:16px;
  }
  #description{
    font-size:20px;
  }
  #header-img{
    font-size:30px;
  }
  #header{
    height:4.5rem;
  }
}

Codexpert

Community

Catalog

Pricing

<form id="form">

Get started for free

  <input type="input" id="email" placeholder="Enter your email">

  <input type="password" id="password" placeholder="Enter your password">

  <input type="submit" value="Submit" id="submit">
</form>

Courses

Python

Java

JavaScript

Html

Ruby on Rails

C++

A: You are facing a margin collapsing issue. After making the header fixed, you removed it from the flow and your form become the first in-flow element thus its top margin will collpase with the top margin of the body1. This mean that the body will have a big top margin and your fixed element will be positioned considering the body since you didn't set any top value2.
To avoid this you simply need to disable margin-collapsing (which I recommend in order to avoid other issues) or set top value to move the element where you want.

@import "https://fonts.googleapis.com/css?family=Permanent+Marker|Work+Sans|Oswald|Baloo+Bhaijaan|Roboto" ;

body {
 padding-top:1px; /*disable margin-collpasing*/
}

  #header{
    background-color:#191919;
    height:3rem;
    width:100%;
    position:fixed;
}

#header-img{
  font-family: 'Permanent Marker', cursive;
  color:white;
  margin-left:1.5rem;
  float:left;
  font-size:25px;
}
ul{
  list-style:none;
  display:flex;
  flow-direction:row;
  justify-content:space-around;
}

#nav-bar{
  background-color:#191919;
  float:left;
  width:100%;
}

#form{
  margin-top:45rem;
  margin-left:25%;
  margin-right:25%;
}

img{
  width:70%;
  height:70%;
}

a {
  text-decoration:none;
  font-family: 'Work Sans', cursive;
  color:white;
  font-size:12px;
}

#email{
  width:100%;
  box-shadow:3px 3px 5px grey;
}

#submit{
  font-family:'Roboto', cursive;
  font-size:14px;
  font-weight:bold;
  color:#686868;
  box-shadow:3px 3px 5px grey;
  padding: 5px 5px;
}

.catalog{
  margin-left:10%;
  margin-right:10%;
  margin-top:5rem;
  width:90%;
  float:left;
}

#password{
  width:100%;
  box-shadow:3px 3px 5px grey;
}

#video{
  margin-top:5rem;
  margin-left:25%;
  margin-right:25%;
  width:50%;
}

#courses{
  display:flex;
  flow-direction:row;
  flex-wrap:wrap;
}

#description{
  font-family: 'Oswald', cursive;
  font-size: 20px;
  text-align:center;
  font-size:16px;
}

li{
  padding: .25rem .5rem;
}

a:hover{
 color:#4ba0c8;
}

.nav-link{

}

.course-label{
  font-family: 'Baloo Bhaijaan', cursive;
  font-size:18px;
}

.images{
    margin: 5% 5%;
    padding: 3% 3%;
    width: 10vw;
    height:10vw;
    color:#d2d2d2;
  }

.images:hover{
  background-color:#99d3ff;
  color:#99d3ff;
}

@media (min-width:555px){
  #nav-bar{
    float:right;
    width:20rem;
    margin-right:1rem;
  }

  #form{
    margin-top:5rem;
  }
}
@media (min-width:360px){
  a{
    font-size:16px;
  }
  #description{
    font-size:20px;
  }
  #header-img{
    font-size:30px;
  }
  #header{
    height:4.5rem;
  }
}

Codexpert

Community

Catalog

Pricing

<form id="form">

Get started for free

  <input type="input" id="email" placeholder="Enter your email">

  <input type="password" id="password" placeholder="Enter your password">

  <input type="submit" value="Submit" id="submit">
</form>

Courses

Python

Java

JavaScript

Html

Ruby on Rails

C++

1Two margins are adjoining if and only if:
..

*

*both belong to vertically-adjacent box edges, i.e. form one of the following pairs:

*

*top margin of a box and top margin of its first in-flow childref
...

2: Why aren't my absolutely/fixed-positioned elements located where I expect?


text:
Q: Let $f(x)=\int_0^1|t-x|t~dt$ for all real $x$. Sketch the graph of $f(x)$, what is the minimum value of $f(x)$ Let $f(x)=\int_0^1|t-x|t~dt$ for all real $x$. Sketch the graph of $f(x)$, what is the minimum value of $f(x)$
I could not in any way understand how to approach this problem. I think I will be able to plot the graph if I know how the function looks like, so one can wish to avoid that part.
To find the minimum value I thought of differentiating the function. But, there is $x$ on one side and $t$ along with $x$ on the other side. I got really confuse how should I do that. Please help.

A: Hint

*

*If $x\in [0,1]$ then
$$f(x)=\int_0^x(x-t)tdt+\int_x^1(t-x)tdt$$

*If $x\ge1$ then
$$f(x)=\int_0^1(x-t)tdt$$

*If $x\le0$ then
$$f(x)=\int_0^1(t-x)tdt$$

so calculate these integrals and you find that $f$ is a polynomial on every interval.

A: If $x\ge 1$, then $|t-x|=x-t$ and $f(x) = \int_0^1t(x-t)dt = x/2-1/3$.
If $x\le 0$, then $|t-x|=t-x$ and $f(x)=\int_0^1t(t-x)dt = 1/3-x/2$.
If $x\in (0,1)$, then we split the integral in two: $$f(x)=\int_0^1t|t-x|dt =\int_0^xt|t-x|dt+\int_x^1t|t-x|dt  $$
$$=\int_0^xt(x-t)dt+\int_x^1t(t-x)dt = x^3/2-x^3/3+(1-x^3)/3-x(1-x^2)/2$$$$=1/3-x/2+x^3/3. $$
Can you find the minimum value?


text:
Q: How does jwt.io read encrypted jwt although it's not possible to get the key? (HS256) I am very surprised to see that jwt.io can decode my jwt token that was generated via HS256 algorithm. Compared to RS256, HS256 carries only one key that is shared on both parties. I have never allowed one partiy to know what this key is (only serverside knows that) but, to be honest, one can find the key by doing crazy iteration until output comes out.
So now I am at the stage that single secret is not as secured as public/private key method. At the same time, jwt.io decodes my token successfully.
Anyone has any ideas about the limitation of HS256 algorithm and how jwt.io knows my jwt?
Best!


text:
Q: Inter-Operablity of ML Models between python and C# Is there any way to use python ML model in ml .net for prediction. Is it inter-operable?
I know there are some other ways using Process to fire python script but here I am looking for inter-operablity of Python ML models.
I have tried with Process class of c#. but I am looking for something more generic.


text:
Q: Accessing Sencha javascript files in Phonegap on Android I was able to run the Sencha Touch Application with Phonegap on Android Emulator 3.1.
But when it comes to an Android Tablet (Samsung Galaxy, 3.1), it was not able to load up the application. It comes up with an error in accessing *.js files generated by the sencha for Store, Model, View & Controller.
The Error is:
Failed loading 'app/store/xyz.js', please verify that the file exists
 Uncaught Error: [Ext.Loader] Failed loading 'app/store/xyz.js', please verify that the file exists at file:///android_asset/www/sencha-touch-all-debug.js:8010

I am using Sencha Touch 2.0.0 and PhoneGap 1.7.0.

A: Webview on Android v3.x and above is unable to load local files with parameters, see issue #17535 for details but in short, this won't work:
test

The vicious consequence of this problem is that Sencha Touch 2 and particulary the Ext.Loader and Ext.Ajax classes are unable to load javascript dependencies due to the extra 'timestamp' parameter that is added to each javascript file (see disableCachingParam).
To workaround this, you need to disable the 'disableCaching' option:
Ext.Loader.setConfig({ enabled: true, disableCaching: false });
Ext.Ajax.setDisableCaching(false);

See also bug #TOUCH-1463


text:
Q: Google Maps v2 SupportMapFragment inside a Fragment into an Activity with NavigationDrawer I'm working to an app that uses a map with the user's current location. I've designed the UI following the standards of Android platform (reference: Android Developers/Design), so I'm trying to insert a GoogleMap into a Fragment within an Activity that contains a Navigation Drawer and four Fragments.
The problem is that in the web I found only solutions that matches for the case I use an Activity (e.g. a fragment inside Activity XML layout), but it isn't what I desire!
I want to insert only a map (with current location) in a Fragment, possibly using SupportMapFragment (I want in fact that my application works on Gingerbread+).
I've tried to insert only a map follow a tutorial in the web (I don't remember the link, sorry), but it was impossible to customize it.
For a major comprehension, I attach some piece of code:
MainActivity.java (that contains a NavDrawer and 4 Fragments)
public class MainActivity extends AbstractNavDrawerActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new MapFragment()).commit();
        }
    }
    ...
}

MapFragment.java (Fragment in which I want to insert a working map with position)
public class MapFragment extends Fragment {
    // Argument representing the section number for this fragment.
    private static final String ARG_SECTION_NUMBER = "section_number";

    public static MapFragment newInstance(int sectionNumber) {
        MapFragment fragment = new MapFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public MapFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        return view;
    }

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

fragment_map.xml (Map layout)
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mapView" />

I ensure that GoogleMaps works correctly, the example tutorial that use an Activity with a Map works well. I've read some solution here, for example here, but it doesn't works in my case!
Anyone can help me?
Thank you very much indeed guys! :)

A: In your MapFragment use the following code
 GoogleMap map=((MapFragment)getActivity().getFragmentManager().findFragmentById(R.id.map)).getMap();

 if(map!=null){
     map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
     map.addMarker(new MarkerOptions()
     .position(new LatLng(latitude, longitude)) // latitude and longitude info is given here
     .title(TITLE)); // title for the marker
 }

In your layout file create a fragment for displaying the map
<fragment
     android:id="@+id/map"
     android:name="com.google.android.gms.maps.MapFragment"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
/>


text:
Q: Facebook's modified DAU & MAU public app metrics On January 2013, Facebook had changed the way the publicly reported DAU and MAU figures are interpreted. Instead of reporting exact MAU & DAU figures per app, Facebook started categorizing each app into a MAU & DAU tiers, thus reported MAU & DAU numbers are rounded into tiers (or levels). Facebook has also introduced a new approach to metrics: ranks - that indicates how well an application is performing against all other apps. (https://developers.facebook.com/blog/post/2013/01/09/platform-updates--operation-developer-love/ and see also http://www.appdata.com/understanding_facebook_ranks)
My question is this:
Indeed when I check Farmville2's usage metrics by visiting https://graph.facebook.com/321574327904696 I do see the new approach. i.e: DAU and MAU reported figures are rounded up into tiers. No exact figures as before January. See below, MAU is reported in the 10 million tier, DAU reported as above 1 million, i.e: 1m tier.
results:
{
   "id": "321574327904696",
   "name": "FarmVille 2",
   "description": "Grow and harvest beautiful crops, raise adorable animals, and craft delicious treats on your very own lifelike 3D farm.",
   "category": "Games",
   "subcategory": "Simulation",
   "link": "https://www.facebook.com/apps/application.php?id=321574327904696",
   "namespace": "farmville-two",
   "icon_url": "http://photos-d.ak.fbcdn.net/photos-ak-snc7/v85005/104/321574327904696/app_2_321574327904696_1179950008.gif",
   "logo_url": "http://photos-h.ak.fbcdn.net/photos-ak-snc7/v85005/104/321574327904696/app_1_321574327904696_637315223.gif",
   "company": "Zynga Inc.",
   "daily_active_users": "1000000",
   "weekly_active_users": "5000000",
   "monthly_active_users": "10000000",
   "daily_active_users_rank": 4,
   "monthly_active_users_rank": 1
}

However if I use Facebook Graph API explorer and issue FQL query like the one below about Farmville2's usage, I still see its exact MAU & DAU figures, not the approximate MAU & DAU tier level to which the app belongs to.
i.e:
SELECT metric, value
FROM insights WHERE object_id='321574327904696' AND metric='application_active_users' AND period=period('month') AND end_time=end_time_date('2013-01-20')

results in showing a MAU of 41,848,270. If I query about DAU, I will get 8,264,964.
{
  "data": [
    {
      "metric": "application_active_users",
      "value": 41848270
    }
  ]
}

My question is this:
which DAU & MAU figures should I take into consideration? Are the exact figures reported by querying the Insights table still there for just a short period of time as a result of wanting to be backward compatible and are soon to be removed? Should I assume I cannot get exact DAU and MAU numbers any longer?

A: You should probably assume you won't be able to get exact DAU and MAU numbers soon.  The numbers you get from the Graph API are the correct results, and the FQL query sounds like it hasn't been migrated to the new app metrics yet.
I would recommend that you only use the Graph API metrics into consideration as the exact figures returned by FQL might be changed in the near future.  I recommend creating a bug report on our bug tool and updating your answer here on SO with the link to the bug report so that others can track the status of this issue.  Also, reference this SO thread in the bug report so we can take a look at this.


text:
Q: getting "Error in xj[i] : only 0's may be mixed with negative subscripts" when performing polynomial regression in for loop I am trying to use a for-loop to determine the optimal polynomial degrees to use for each variable in my regression, and will then use k-fold cross-validation. I am getting an error  "Error in xj[i] : only 0's may be mixed with negative subscripts". I know this code may not be very "r-ish" as im new to the language so any other tips would be helpful as well.
b1 = rep(0,27)
b2 = rep(0,27)
b3 = rep(0,27)
cv.error = rep(0,27)
index = 1
for (i in c(2,3,4)) {
  for (j in c(2,3,4)) {
    for (k in c(2,3,4)) {
       fit = lm(user_Score ~
               poly(user_count, i),
               poly(year_of_Release, j),
               poly(global_Sales, k), data = video_games)
        b1[index] = i
        b2[index] = j
        b3[index] = k
        cv.error[index] = cv.glm(video_games, fit, K=10)$delta[1]
        index = index + 1
    }
  }
}

I'm expecting to end up with vectors where I store each combination as well as the MSE so that I can then see which combination was optimal.


text:
Q: Getting elements on page to reset to default size after font increase/decrease How do I get the elements on my page to reset back to default after font increase/decrease
I've tried the following but with little success (font increase/decrease works):
jsfiddle
Here is my code:
$(".resetFont").click(function () {
});

$(".increaseFont").click(function () {
    var fontSize = getFontSize();
    var newFontSize = fontSize + 1;
    setFontSize(newFontSize);
    return false;
});

$(".decreaseFont").click(function () {
    var fontSize = getFontSize();
    var newFontSize = fontSize - 1;
    setFontSize(newFontSize);
    return false;
});

function getFontSize() {
    var currentSize = $("html").css("font-size");
    var currentSizeNumber = parseFloat(currentSize, 12);
    if (currentSizeNumber > 24) {
        currentSizeNumber = 24;
    }
    if (currentSizeNumber < 10) {
        currentSizeNumber = 10;
    }
    return currentSizeNumber;
}

function setFontSize(size) {
    $("html").css("font-size", size);
    $(".actualSize").html(size);
}

A: var defaultFontSize = $('html').css('font-size');

$(".resetFont").click(function () {
    $('html').css('font-size', defaultFontSize);
});

Updated DEMO

A: var defaultFontSize = $('html').css('font-size');
$(".resetFont").click(function () {

$("html").css("font-size", defaultFontSize);
    $(".actualSize").html(defaultFontSize );

});

A: Just set what you want the original font size to be:
 $(".resetFont").click(function () {
      $("html").css("font-size", '24px');
 });

A: $('.resetFont').click(function(){
    setFontSize('auto');
}

Really no one got this?


text:
Q: getActionCommand not working in code (watching tutorial series) I'm watching a youtube tutorial series by mybringback. (38th video in the series). At the very bottom of the code, I have e.getactioncommand.  When I click on the radio button, I want it to say something in the text field.  For instance when I hit radio button 1, it should say "you selected radio button 1" in the text field.  I followed the tutorial exactly, but I can't figure out what's wrong.
I have the driver class as well.  that i didn't post here.
Here;s the video https://www.youtube.com/watch?v=pjS_IiNp008&list=SPDAA5DE54FB5215EC
      package ActionCommandnActionListeners;

      import java.awt.BorderLayout;
      import java.awt.GridBagConstraints;
        import java.awt.GridBagLayout;
        import java.awt.Insets;
        import java.awt.Label;
        import java.awt.event.ActionEvent;
         import java.awt.event.ActionListener;

           import javax.swing.ButtonGroup;
       import javax.swing.JButton;
       import javax.swing.JCheckBox;
       import javax.swing.JFrame;
       import javax.swing.JLabel;
        import javax.swing.JOptionPane;
      import javax.swing.JPanel;
      import javax.swing.JRadioButton;
      import javax.swing.JTextArea;
      import javax.swing.JTextField;

    public class FirstWindow extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;

String s;
JCheckBox cb, cb2;
JTextField textField;
JLabel label;
JRadioButton b1, b2, b3, b4;
ButtonGroup group;
JTextArea tb;

public FirstWindow() {
    super("Your Computer is very special");

    setSize(600, 400);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    JPanel p = new JPanel();
    JPanel p2 = new JPanel();
    JPanel p3 = new JPanel(new GridBagLayout());
    JPanel p4 = new JPanel();

    b1 = new JRadioButton("Choice 1");
    b1.setActionCommand("you selected num1");
    b1.addActionListener(this);

    b2 = new JRadioButton("Choice 2");
    b2.setActionCommand("you selected num2");
    b2.addActionListener(this);

    b3 = new JRadioButton("Choice 3");
    b3.setActionCommand("you selected num3");
    b3.addActionListener(this);

    b4 = new JRadioButton("Choice 4");
    b4.setActionCommand("you selected num4");
    b4.addActionListener(this);

    group = new ButtonGroup();
    group.add(b1);
    group.add(b2);
    group.add(b3);
    group.add(b4);

    p4.add(b1);
    p4.add(b2);
    p4.add(b3);
    p4.add(b4);

    JButton b = new JButton("Button 1");
    JButton c = new JButton("Button 2");

    p.add(b);
    p.add(c);

    cb = new JCheckBox("Do you LOVE bacon?");
    cb2 = new JCheckBox("Do you LOVE cheese?");

    p2.add(cb);
    p2.add(cb2);

    label = new JLabel("This is a label");
    JTextArea tb = new JTextArea("This is a text area");
    textField = new JTextField("text field");

    c.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            String s2 = textField.getText();
            label.setText(s2);
        }
    });

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets(15, 15, 15, 15);

    gbc.gridx = 0;
    gbc.gridy = 0;
    p3.add(label, gbc);
    gbc.gridx = 0;
    gbc.gridy = 1;
    p3.add(tb, gbc);
    gbc.gridx = 0;
    gbc.gridy = 2;
    p3.add(textField, gbc);

    add(p, BorderLayout.SOUTH);
    add(p2, BorderLayout.NORTH);
    add(p3, BorderLayout.CENTER);
    add(p4, BorderLayout.WEST);

    b.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            s = "Good job kid, you harvested your corn! \n";

            if (cb.isSelected()) {
                s += " And of course you love bacon! \n";
            }
            if (cb2.isSelected()) {
                s += " Most naturally you love cheese! \n";
            }
            JOptionPane.showMessageDialog(null, s);
        }
    });

}

@Override
public void actionPerformed(ActionEvent e) {
    tb.setText(e.getActionCommand());

}

}

A: JTextArea tb = new JTextArea("This is a text area");

You are shadowing your variables. You defined the "tb" variable as an instance variable and a local variable. You don't want the local variable because your actionPerformed() method can't reference local variables.
So the code should be:
//JTextArea tb = new JTextArea("This is a text area");
tb = new JTextArea("This is a text area");

I'm watching a youtube tutorial series by mybringback

I've never quite figured out why people use youtube for tutorials.
I would start with the Swing tutorial. This way not only can you read the tutorial at your pace but you can actually download the code and compile and test and change the code. So you start with working code and then you customize it to do what you want.


text:
Q: Python Flask server on elastic beanstalk cant save files I am trying to upload and save a file to my EC2 instance so that I can do some file manipulation.
My upload looks like this:
UPLOAD_FOLDER = os.getcwd() + '/uploads'
application = Flask(__name__)
CORS(application)
application.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@application.route("/test-upload", methods=["POST"])
def test_upload():
    file = request.files['file']
    filename = secure_filename(file.filename)
    file.save(os.path.join(application.config['UPLOAD_FOLDER'], filename))
    # return redirect(url_for('download_file', name=filename))
    return str(os.path.join(application.config['UPLOAD_FOLDER'], filename))

If I remove the file.save() line, then the function won't return errors. And as you can see I'm returning the path, so that will return the correct path. But, I get a 500 bad request from the server when I try and save the file.
I'm not sure what I'm missing here.
I can locally try this using postman, and this works fine. The file saves to the right location. I do have file size for EC2 enabled to be 100MB, but I am testing with a 50 Byte file so size can't be the issue. I know the file is being uploaded to the EC2 web server for sure.


text:
Q: PDF - Split Single Words into Individual Lines - Python 3 I am trying to extract words from a PDF into individual lines, but can only do this with Text files as demonstrated below.
Moreover, the rule is that I cannot convert PDF files to TXT then perform this operation. It must be done on PDF files.
with open('filename.txt','r') as f:
    for line in f:
        for word in line.split():
           print(word)

If filename.txt has just "Hello World!", then this function returns:
Hello
World!

I need to do the same with searchable PDF files as well. Any help would be appreciated.

A: For the PDF, you should use pdf.miner or PyPDF2.
Here is a good article you can use to extract the text, and then you can use Anilkumar's method to extract line by line.
https://medium.com/@rqaiserr/how-to-convert-pdfs-into-searchable-key-words-with-python-85aab86c544f

A: Check out PyMuPDF. There's loads of stuff you can do, including get line by line text from a PDF using page.getText()

A: You can use pdfreader to extract texts (plain and containing PDF operators) from PDF document
Here is a sample code extracting all the above from all document pages.
from pdfreader import SimplePDFViewer, PageDoesNotExist

fd = open(you_pdf_file_name, "rb")
viewer = SimplePDFViewer(fd)

plain_text = ""
pdf_markdown = ""
try:
    while True:
        viewer.render()
        pdf_markdown += viewer.canvas.text_content
        plain_text += "".join(viewer.canvas.strings)
        viewer.next()
except PageDoesNotExist:
    pass

Just want to outline, that text in PDFs usually do not come as "words", they look like commands to a conforming PDF viewer where and how to put a glyph. Which means a single word may be displayed by several commands. Read more on that in PDF 1.7 docs sec.9 - Text

A: when I saw filename.txt I got confused.
Since you are working with PDF below link might be helpful. See it helps
How to use PDFminer.six with python 3?


text:
Q: Is there a way to make particles face towards a players x and z coordinates but take another players y? I used a command that makes particles that face a certain player, but I am not sure how to make it on one y coordinate. This is the command I was using: execute as @a[nbt={SelectedItem:{id:"minecraft:music_disc_11"}}] at @s if entity @a[distance=0.1..] facing entity player1 eyes positioned ~ ~1 ~ positioned ^ ^ ^3 run particle minecraft:dust 1.0 1.0 1.0 1.0 ~ ~ ~ 0 0 0 0 1. I am trying to figure out how to make it face the x and z of one player, player1 (I didn't want to post a real username), but then take the y of the player the particles are close to, so it doesnt point downward if the player is below me. Is there a way to do that or is that not possible?

A: I don't think it's possible directly, but you can use a dummy entity, like an invisible marker armour stand. Summon it at one player and then use a command like this one:
/execute as [dummy_entity] run data modify entity @s Pos[1] set from entity [other_player] Pos[1]

The copies the y coordinate from the NBT of the player to the NBT of the entity, therefore teleporting it to that player's height. You can then use the coordinates of that entity for your other commands and afterwards kill the dummy entity again.


text: Q: Ffmpeg downloading slow? Mine download speed is slow when I use ffmpeg to download a video. When I use other programs that use ffmpeg I am getting no problem but downloading on termux I am getting slow speed.


text:
Q: Tabular Model in Azure Portal Won't Open in Visual Studios I have a Tabular model in Azure Analysis Services that I created by importing a .pbix. It loaded the model perfectly, but when I try to open the model in Visual Studio nothing happens. When I click on Open in Excel it creates a .odc file and when I click on Open in Power BI it creates a .pbix file. You can see below the options:
Screenshot:

I would like to open it in Visual Studios. Has anyone else ran into this problem or does anyone else have a solution?
Any help would be appreciated.
Thanks!

A: Well, it looks like the Open in Visual Studio button is now working. The next day, it now downloads a .zip file that contains a .SMPROJ file and a .BIM file. Not sure why it wasn't working yesterday, maybe the model needs some time after it is created to be able to be loaded into Visual Studios. If anybody knows why, then post, to help anyone else in the future.
Thanks


text:
Q: create clearly distinguishable line plot of pairs of variables I have the following dataframe:
library(dplyr)
library(tidyr)
library(ggplot2)

foobar <- structure(list(month = structure(c(1477872000, 1480464000, 1483142400,
1485820800, 1488240000, 1490918400, 1493510400, 1496188800, 1498780800,
1501459200, 1504137600, 1506729600, 1509408000, 1.512e+09, 1514678400,
1517356800, 1519776000, 1522454400, 1525046400, 1527724800, 1530316800
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), r = c(283L,
298L, 277L, 231L, 276L, 323L, 242L, 255L, 208L, 289L, 284L, 263L,
280L, 278L, 269L, 288L, 255L, 324L, 339L, 355L, 300L), r_unanswered = c(133L,
139L, 106L, 85L, 132L, 141L, 89L, 110L, 80L, 142L, 174L, 159L,
146L, 162L, 153L, 161L, 142L, 174L, 211L, 208L, 194L), regression = c(260L,
278L, 249L, 242L, 301L, 349L, 249L, 309L, 256L, 280L, 326L, 276L,
299L, 322L, 235L, 281L, 256L, 293L, 356L, 307L, 279L), regression_unanswered = c(102L,
119L, 92L, 107L, 119L, 126L, 108L, 132L, 89L, 141L, 199L, 148L,
161L, 160L, 125L, 159L, 137L, 139L, 208L, 177L, 162L), machine_learning = c(208L,
190L, 176L, 208L, 221L, 265L, 204L, 215L, 251L, 283L, 314L, 257L,
250L, 290L, 240L, 290L, 275L, 295L, 292L, 316L, 324L), machine_learning_unanswered = c(64L,
67L, 62L, 86L, 78L, 76L, 67L, 67L, 90L, 128L, 155L, 106L, 125L,
132L, 125L, 143L, 132L, 159L, 159L, 158L, 191L)), row.names = c(NA,
-21L), class = c("tbl_df", "tbl", "data.frame"))
> glimpse(foobar)
Observations: 21
Variables: 7
$ month                       <dttm> 2016-10-31, 2016-11-30, 2016-12-31, 2...
$ r                           <int> 283, 298, 277, 231, 276, 323, 242, 255...
$ r_unanswered                <int> 133, 139, 106, 85, 132, 141, 89, 110, ...
$ regression                  <int> 260, 278, 249, 242, 301, 349, 249, 309...
$ regression_unanswered       <int> 102, 119, 92, 107, 119, 126, 108, 132,...
$ machine_learning            <int> 208, 190, 176, 208, 221, 265, 204, 215...
$ machine_learning_unanswered <int> 64, 67, 62, 86, 78, 76, 67, 67, 90, 12...

I want to group all the non-month variables in pair (e.g, r and r_unanswered) and plot all of them at the same time versus the month column. I want to achieve three goals:

*

*the pairs must be easily distinguishable, i.e, it must be easy to discern the two lines corresponding to the pair r and r_unanswered, from the two lines corresponding to regression and regression_unanswered;

*inside each pair, it must be easy to discern by eye the unanswered variable from the other one.

*the approach must scale to more pairs. In this simple example I have 3 pairs: in my real case I may have 10 or more.

I was thinking to achieve this by using the same color for each pair, and inside each pair, by plotting the unanswered variable as a dashed line, but I'm open to other suggestions, if you think they could be more visually appealing. Anyway, my problem is that I cannot even implement this simple idea. I tried
tall_unanswered <- foobar %>% select(ends_with("unanswered"), month) %>%
  gather(key = tag, value = count, -month)
tall_total <- foobar %>% select(-ends_with("unanswered")) %>%
  gather(key = tag, value = count, -month)
p <- ggplot(tall_total, aes(x = month, y = count, color = tag)) +
  geom_line() +
  geom_line(data = tall_unanswered, linetype = "dashed")

But it doesn't work: the colors are not the same for each pair, and so I dont' manage to achieve goal 1 (each pair must be easily distinguishable from the others).

A: I would do this by gathering all the columns into a long format and then creating variables based on those column names for mapping to color and linetype.  You can do this latter task with tidyr::separate().
I found your particular case a little more difficult since some of the tag names contained underscores other than those directly before "unanswered".  So I first replaced "_unanswered" with ".unanswered" so I could separate "tag" on a period instead of an underscore.  This makes two new columns, one for color (based on the tag name) and one for linetype (based on answered vs unanswered). The answered questions don't have info to say they are answered, so I add it with an ifelse() statement.
Here's the data manipulation:
foolong = foobar %>%
    gather(tag, count, -month) %>%
    mutate(tag = sub("_unanswered", ".unanswered", tag)) %>%
    separate(tag, into = c("name", "answered"), sep = "\\.",
             remove = FALSE, fill = "right") %>%
    mutate(answered = ifelse(!is.na(answered), "unanswered", "answered"))

And then the plot can be made by mapping colors and linetypes to the new variables.
ggplot(foolong, aes(x = month, y = count,
                    color = name) +
    geom_line( aes(linetype = answered))

You can remove or change legends as needed to suit your purpose.
More sophisticated way to split via separate()
As @Henrik pointed out, you can use a look-ahead via regex to split on only the underscores preceded by the word "unanswered".  This avoids my work-around sub() and saves a step.
That part of the code would look like:
foobar %>%
     gather(tag, count, -month) %>%
     separate(tag, into = c("name", "answered"), sep = "_(?=[unanswered])",
              remove = FALSE, fill = "right")


text:
Q: Referencing indirect dependencies in nuget Looks like this is trivial question but somehow I can't figure it out.
Let's suppose very easy case: App A references Library B which in turn references Library C.
Now, when I try to run App A and it invokes Library B in code I get runtime exception that referenced Library C could not be loaded. This is obvius, can be fixed by either a) referencing library C in App A so that it is added in Bin folder or preferrably b)adding it to GAC.
I would like to ask - is there any way to automatically resolve such dependencies?


text:
Q: How do you make a transparent border (with CSS) that goes over a background image?
I want to make a border around my div that is transparent. I want the background image to show through the transparent border. In my picture, you can see that my code makes a transparent border, but the white shows through instead of the background image. No matter what size I make the border, it basically increases the white space to fit the border.
The following is my code that includes the border of .mainbody and the background image. I'm thinking that maybe, something my code is interfering with the border transparency over the background image.
.mainbody {
    max-width: 1500px;
    height: auto;
    background: white;
    margin-top: -27px;
    border: 10px dashed rgba(236, 200, 236, .5);
    }

body {
    background: url("https://scenesfromphiladelphia.files.wordpress.com/2010/02/026.jpg");
    background-size: cover;
    background-position: center;
    text-align: left;
    text-indent: 50px;
    color: 000000;
    font-family: Bree Serif;
    max-width: 800px;
    margin: auto;
}

A: Maybe it helps you
* {
    box-sizing: border-box;
}
.mainbody {
    position: relative;
    max-width: 1500px;
    height: auto;
    padding: 10px;
}
.other {
    border: 10px dashed rgba(236, 200, 236, .5);
    position: absolute;
    background: transparent;
    opacity: .5;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
}

body {
    background: url("https://scenesfromphiladelphia.files.wordpress.com/2010/02/026.jpg");
    background-size: cover;
    background-position: center;
    text-align: left;
    text-indent: 50px;
    color: 000000;
    font-family: Bree Serif;
    max-width: 800px;
    margin: auto;
}

And the HTML:

Hello


text:
Q: UITableView inside a UITableViewCell? What's the best design? I've not found a answer to this question anywhere, but this seems like a typical problem: I am dynamically (from a xml file) creating a view to display "Questions" I take from the XML file. I am having problems to display multiple choice questions. I am trying following approach:
Question 1
MultipleChoiceQuestion 2
--First Option
--Second Option
--Third Option
Question 3
Question 4
MultipleChoiceQuestion 5
--First Option
--Second Option
and so on...

So, my Idea is: I have a first UITableView and row for each "normal" question , and a second UITableView for each "Multiple Choice" question that should be loaded into a row from the first UITableView as I showed before.
Is this a good approach or you guys have a better design pattern for this issue?
Thanks a lot!

A: There is a tutorial for creating custom UITableViewCells with UITableView inside it at:
http://iosstuff.wordpress.com/2011/06/29/adding-a-uitableview-inside-a-uitableviewcell/
iOS SDK is flexible and you can add any UIView subclass element to tableview cells. Have a look at 'Pulse', its a news reader app that won Apple Design Award. This app has horizontally scrollable images and its developers explained that how they used UITableViews to create that. So don't be afraid to implement new ideas no matter how wild they might appear.
Good Luck!

A: No, no! Please, no! Do not place big UI Elements like table views in a tableviewcell (and surely do not make them scrollable =P).
What about making the user be able to select a question (one question per row) and then show up a picker view with answers, on the place where to keyboard would normally be?
Just like a list of HTML select tags in Mobile Safari.

Or you can use a grouped table view with one group per question, including the chosable answers.


text:
Q: Programatically blocking a url to rate limit, unblocking or expiring the block My requirements are to be able to rate limit or temporarily hard block any requests to our server for a particular URL if the client sends more than x requests per hour.
There are about 250K urls that could potentially be blocked.
Clients have unique urls that they make a http post too, so something like:
customer1.example.com/post/location/36A107F4-DD68-47F2-A093-753F7A427CF6/
Where customer1 is the customer name, and 36A107F4-DD68-47F2-A093-753F7A427CF6 is their unique location guid.
I want my application to be able to make some sort of an API call to block a given url, and then either use an API call to unblock or have the block expire after x minutes.
Is this possible with any open source service like haproxy or nginx?

A: Here are a few ideas...these aren't specific to nginx or HAProxy, but possibly you could use the same ideas.
This article discusses how they are using Varnish to implement per-URL rate limiting for an application.  The application communicates with Varnish using a custom HTTP header, rather than an API call, but the idea is similar.
Using Apache, you could do something similar using a programmatic RewriteMap...look up requests in a database, and for those that are currently rate-limited, rewrite them to an error page, otherwise pass them through unmodified.  Turning rate-limiting on/off for a particular URL would be simple one-row changes in the database.


text:
Q: Getting Python to Confirm If/Elif/Else before proceeding I've written a simple python script to take command line arguments and write them to a file for deployment to a router using Ansible. But before my script creates that output file, I want to force the user to confirm the request with a Y/N (Yes or No) entry.
How can I modify this script to request that after each if/elif statement?
#!/usr/bin/python

import argparse
import sys

parser = argparse.ArgumentParser()
parser.add_argument("-s", "--set", help="set", action="store_true")
parser.add_argument("-d", "--delete", help="delete", action="store_true")
parser.add_argument("-i", "--ipaddr", help="Target IP")
args = parser.parse_args()
if args.set:
        print "Deploying: set routing-options static route %s" % (args.ipaddr)
        filename = open("/var/tmp/output.txt",'w')
        sys.stdout = filename
        print "set routing-options static route %s" % (args.ipaddr)
elif args.delete:
        print "Deploying: delete routing-options static route %s" % (args.ipaddr)
        filename = open("/var/tmp/output.txt",'w')
        sys.stdout = filename
        print "delete routing-options static route %s" % (args.ipaddr)
else:
        exit(1)

A: Just write a ask_confirm function and call it wherever needed:
def ask_confirm(msg="Are you sure?"):
    answer = ""
    while answer not in ("yes", "no"):
        answer = input(msg + " [yes/no]")
    return (True if answer == "yes" else False)

The default value of msg lets you call ask_confirm with a generic message.
It returns a boolean value so it is easier to handle.
The inputs could be customized in a fancier way if needed.
Here is a fancier version:
def ask_confirm(msg="Are you sure?", yes=None, no=None):
    if yes is None:
        yes = ["yes"]
    if no is None:
        no = ["no"]
    if isinstance(yes, str):
        yes = [yes]
    if isinstance(no, str):
        no = [no]

    answer = ""
    while answer not in yes and answer not in no:
        answer = input(msg + " [{}/{}]".format(yes[0], no[0]))
    return (True if answer in yes else False)

Then you can ask for confirmation at the beginning of each block:
if args.set:
    if not ask_confirm("Do you really want to set?"):
        sys.exit()
    # else (not needed)
    # proceed

elif args.delete:
    if not ask_confirm("Are you sure you want to delete?"):
        sys.exit()
    # else (not needed)
    # proceed

else:
    sys.exit(1)


text:
Q: New Rails 4 project requiers mysql gem installed I am creating a new rails project without any -d option, but when I open it in browser it crashes with:

Specified 'mysql' for database adapter, but the gem is not loaded. Add gem 'mysql' to your Gemfile.

There is no mention of mysql adapter anywhere any the project (it's a new one) and the adapter in database.yml is sqlite3. I also tried -d sqlite3, no luck. Some lines of the trace are:
vendor/bundle/gems/activerecord-4.0.1/lib/active_record/connection_adapters/connection_specification.rb:58:in `rescue in resolve_hash_connection'
vendor/bundle/gems/activerecord-4.0.1/lib/active_record/connection_adapters/connection_specification.rb:55:in `resolve_hash_connection'
vendor/bundle/gems/activerecord-4.0.1/lib/active_record/connection_adapters/connection_specification.rb:46:in `resolve_string_connection'
vendor/bundle/gems/activerecord-4.0.1/lib/active_record/connection_adapters/connection_specification.rb:32:in `spec'
.
.
.
/usr/local/var/rbenv/versions/2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
/usr/local/var/rbenv/versions/2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
/usr/local/var/rbenv/versions/2.0.0-p247/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'


text:
Q: Can I use ng-click with ng-if to hide and show two different sections simultaneously I'm working on an app in angularjs and trying to do something directly in the DOM. While I know this is not the greatest practice, it would be pretty practical in this case since I'm specifically trying to circumvent the controller.   I tried to hook a button into ng-click with two functions true and false, then using ng-if to show and hide a section.  Two functions because there are two sections.  I'd like to get it to where if one button is clicked one section shows while the other hides and vice versa. It sort of works, but it will never get hide the first section. Also, in certain attempts, I got it sort of working but it would not default to any one element on load.  Any ideas? My code looks something like:
<button class="add col-xs-6 col-sm-6 col-md-3 col-lg-3 add-btn" ng-model="showThis=true" ng-click="showMe=false; showThis=true">Add</button>
<button class="edit col-xs-6 col-sm-6 col-md-3 col-lg-3 edit-btn" ng-click="showMe=true; showThis=false">Edit</button>

    {A Section of Code}

    {Another Section of Code}

A: I would set a single variable, and then use it to toggle between the two divs:
<button class="add col-xs-6 col-sm-6 col-md-3 col-lg-3 add-btn" ng-model="showMe=true" ng-click="showMe=false">Add</button>
<button class="edit col-xs-6 col-sm-6 col-md-3 col-lg-3 edit-btn" ng-click="showMe=true">Edit</button>

    {A Section of Code}

    {Another Section of Code}

If showMe is true, the top block will display, and the ! or NOT operator will hide the second block (!true == false).


text:
Q: About code optimization in Flash AS3 i'm curious about something. Let say we have 30 object in the code, and every object should be animated trough enter frame event. Which will be faster(in terms of memory execution) : to have just one event listener in the main object (for example) and to call object methods, or, to have separate event listener for every object?
Thanks :) .
UPDATE: Well, actually, i need to monitor each object to find out when that object is on current frame, e.g. on end of animation, and than remove it from display list. What is the best way to that?

A: For 30 objects, this doesn't really matter. Actually, in general it matters only little, since the bottleneck will always be rendering.
But to answer your question: Listeners are slow. For one notification to happen, an Event object needs to be created (allocation is generally quite expensive), and an untyped call of an anonymous function or a method closure needs to be done (which is signifficantly slower than calling a method on a strictly typed value).

A: You should try to use tweens instead of animating via ENTER FRAME event.
Animating on ENTER FRAME will cause tremendous lag, especially if you have lots of objects.
Checkout TweenLite: http://www.greensock.com/tweenlite/

A: Definitely to have just one event listener. The less listeners, the faster.

A: As a rule of thumb, one listener is better, and will induce a more predictible behaviour.
That being said, it depends pretty heavily on what you're trying to do. You might not have to animate every object on every enter frame event, thus gaining performance further.


text:
Q: Concat each element of list with each element of second list I have two lists ['_ru', '_uk', '_en'], ['1','2','3']
How I can get
['1_ru', '1_uk', '1_en', '2_ru', '2_uk', '2_en', '3_ru', '3_uk', '3_en']

in one line?

A: You can use itertools.product to get the cartesian product of two lists and join them, like this
>>> l2, l1 = ['_ru', '_uk', '_en'], ['1','2','3']
>>> from itertools import product
>>> ["".join(items) for items in product(l1, l2)]
['1_ru', '1_uk', '1_en', '2_ru', '2_uk', '2_en', '3_ru', '3_uk', '3_en']

Or in one line, with list comprehension
>>> ["{}{}".format(i1, i2) for i1 in l1 for i2 in l2]
['1_ru', '1_uk', '1_en', '2_ru', '2_uk', '2_en', '3_ru', '3_uk', '3_en']

This is basically the same as iterating the second list for each item in the first list and accumulating the result, like this
>>> result = []
>>> for i1 in l1:
...     for i2 in l2:
...         result.append("{}{}".format(i1, i2))
>>> result
['1_ru', '1_uk', '1_en', '2_ru', '2_uk', '2_en', '3_ru', '3_uk', '3_en']


text:
Q: How to get list of application which are maintain history data? I am Developing an Application, in that i have to show a list which applications are showing the history or maintain the previous data  like Browsers and whatsapp, wechat... . is there any intent action or use full  method in android API.
thank you for helping.

A:
is there any intent action or use full method in android API

No. App developers do not have to tell other app developers whether their app is "showing the history" or can "maintain the previous data".

i have to show a list which applications are showing the history or maintain the previous data

Since almost all apps "maintain the previous data" (e.g., game high scores, blood pressure readings, to-do items), simply list all applications.


text:
Q: Groupby and extract groups containing only value with a pattern I have a dataframe such as :
COL1 COL2
G1 AHA_(+)jjd
G1 6EGEGUG
G1 897E97eh
G1 77E97E
G2 8JHEJE_(-)
G2 8JHEJE_(+)
G3 TTTD
G3 YYYDD
G4 DTTDHD
G4 DYD
G5 tTDHD(+)
G6 DGDGGD

and I would like to add the Gnumber into a list for those that contain only COL2 value containing the pattern ().
her I should get
expected output :
print(list)

[G2,G5]

thanks for your help

A: Use  Series.str.contains with negate masks by ~ and test matched values by Series.isin:
#filter values with ()
m1 = df['COL2'].str.contains(('\(.*\)'))
#filter COL1 values with no ()
m2 = df.COL1.isin(df.loc[~m1, 'COL1'])

#filter values only with ()
out = df.loc[~m2, 'COL1'].unique()
print (out)
['G2' 'G5']

Or use GroupBy.all for test if all Trues per groups and then filter index values:
s = df['COL2'].str.contains(('\(.*\)')).groupby(df['COL1']).all()

out = s.index[s]
print (out)
Index(['G2','G5'], dtype='object', name='COL1')


text:
Q: Ruby on rails mailer + Mailgun marked as spam I have a ActionMailer with following settings(according to this guide):
require 'digest/sha2'
class WinnerMailer < ActionMailer::Base
  include Resque::Mailer
  default "Message-ID"=>"<#{Digest::SHA2.hexdigest(Time.now.to_i.to_s)}@my-domain.com>"
  default from: "mail@my-domain.com"

My email has:
From: mail@my-domain.com
To: xxx@gmail.com
Message-Id: <50117ee0355959752a01b1737c8568f30ea72db2f35ec68cfa7808cea18dbb69@my-domain.com>

My production.rb has following settings:
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.perform_deliveries = :true #try to force sending in development
  config.action_mailer.raise_delivery_errors = :false
  config.action_mailer.smtp_settings = {
      :authentication => :plain,
      :address => "smtp.mailgun.org",
      :port => 587,
      :domain => "my-domain.com",
      :user_name => "postmaster@my-domain.com",
      :password => "qqqqq"
  }

For some reasons all my letters go to spam folder. What am I doing wrong?

A: There are tons of different reasons, why your mail might be marked as spam. Just a few examples:

*

*based on the wording (blacklisted words, too short),

*the domain is on a blacklist,

*the IP is on a blacklist,

*the receiver once marked your mail as spam

*you sent too many emails in a short period of time

*you recently change domain or IP

*IP does not match domain name

*number of recipients

*...

Some spam filters add a description to the mail header why the mail was marked as spam and how the mail scored in different spam checks. You might want to take a lock the header to get more information.
Furthermore, you might need some help from the company that manages your mail server, to find out if your domain or IP is on a list of hosts known for spam. People who manage mail servers usually have access to such lists and monitor list entries for the customers and may take actions against wrong listings.


text:
Q: What is the complete list of keys in ClipboardActionTransformations.xml to configure Remote Desktop There is very little documentation on ClipboardActionTransformations.xml which can be edited to map keys in Remote Desktop.
For example, if I want to map the (host Mac) command key to be the (client Windows) ctrl, I would use the following:
<?xml version="1.0" encoding="utf-8" ?>
<!-- transformation for clipboard actions (cut copy paste) -->
<!-- layout specific -->
<layouts>
    <layout name="default">
        <transformations>
            <transform>
                <from command="1" key="A" />
                <to control="1" key="A" />
            </transform>
        </transformations>
    </layout>
</layouts>

repeating transform for each key.
This file should be copied into the Remote Desktop app after it is updated.
sudo cp ~/ClipboardActionTransformations.xml /Applications/Microsoft\ Remote\ Desktop.app/Contents/Resources/Keyboard

What are all the other keys?

A: Viewing the contents of /Applications/Microsoft\ Remote\ Desktop.app/Contents/MacOS/Microsoft\ Remote\ Desktop I have found:

*

*Num1, Num2, etc.

*F1, F2, etc.

*LeftBrace, RightBrace (or Bracket?)

*Return, Tab, Delete, Escape

*Comma, SemiColon, Period

*Slash, BackSlash

*Space

*Equal, Minus

*LeftCommand, RightCommand

*LeftShift, RightShift

*LeftControl, RightControl

*LeftOption, RightOption

*CapsLock

*Apps

*ForwardDelete, Delete, Insert,

*PageUp, PageDown, Home, End

*UpArrow, RightArrow, DownArrow, LeftArrow
and

*

*Keypad1, Keypad2, etc.

*KeypadDecimal

*KeypadMultiple, KeypadDivide, KeypadPlus, KeypadMinus

*KeypadEnd

*KeypadEnter

*KeypadCl???

Modifiers are:

*

*control

*command

*option

*shift
Note:

*

*most of the symbols are truncated, so I'm guessing at them (I couldn't guess one keypad symbol)

*I could not find the symbol for ' or `

*I haven't tested them all, so some may be incorrect

*I haven't had much luck mapping the Windows key, in particular, when I press command, but don't press another key, the Start menu pops up which is annoying

*I haven't managed to get the Windows clipboard to show when pressing controlV, but it does show when pressing commandshiftV which is good enough


text:
Q: How to pass output as command line argument in bash? I have this two step bash command:
L=`wc -l testfile | cut -d' ' -f1`
myprogram testfile $L testfile.out

Long story short, myprogram needs the line count as an input.
I want to combine this into one line.
This does not work because using redirect | to - passes stdout stream as a file, not a string.
wc -l testfile | cut -d' ' -f1 | myprogram testfile - testfile.out

Is there a way to combine this into one line?

A: Use process substitution:
myprogram testfile $(wc -l < testfile) testfile.out
                   ^^^^^^^^^^^^^^^^^^^

This way, wc -l < testfile is evaluated together with the call of the program and you have both commands combined.
Note wc -l < file returns you just the number, so you don't have to do cut or any other thing to clean the output.


text:
Q: how to access string sent from wearable tizen app to android app A bit of background: I am using Samsung Gear 2, Samsung s4 ,Eclipse and Tizen IDE for Wearable.
I have an app on both devices that communicates using Accessory SDK. On the same app, I also have codes that read the heartrate. I pass the heartrate from the wear app using SASocket.sendData on the code below. I access the string on the android app using onRecieve method which is also on shown below.
Now, I want to save the heartrate in Mysql. How can I access the String and save it to Mysql?
 try {
        SASocket.setDataReceiveListener(onreceive);
        SASocket.sendData(CHANNELID,heartrate.toString());

    } catch(err) {
        console.log("exception [" + err.name + "] msg[" + err.message + "]");
    }

  @Override
    public void onReceive(int channelId, byte[] data) {
        Log.d(TAG, "onReceive");

        Time time = new Time();

        time.set(System.currentTimeMillis());

        String timeStr = " " + String.valueOf(time.minute) + ":"
                + String.valueOf(time.second);

        String strToUpdateUI = new String(data);
        System.out.println("strToUpdateUI : " + strToUpdateUI);
        heartrate =strToUpdateUI;
        final String message = strToUpdateUI.concat(timeStr);

        final HelloAccessoryProviderConnection uHandler = mConnectionsMap.get(Integer
                .parseInt(String.valueOf(mConnectionId)));
        if(uHandler == null){
            Log.e(TAG,"Error, can not get HelloAccessoryProviderConnection handler");
            return;
        }
        new Thread(new Runnable() {
            public void run() {
                try {
                    uHandler.send(HELLOACCESSORY_CHANNEL_ID, message.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

A: First of all, it's great that you have come this far in your Gear App development i.e. getting your provider and consume side apps to communicate. Most of the hard work is already done. I assume that you successfully have your heart rate data in your heartrate variable
heartrate =strToUpdateUI;
What you can do next is create a method that "saves" your data.

*

*Create a MySQL database and get its details. You can download wamp and install it on your local machine

*Create a database and a table to hold your heart rate data

*Your Android code might not be able to directly save data to a MySQL database, so you will need to write a web application (a simple mysqlhandler) written in any dynamic web app dev language of your choice which does this.

*From your Android code, you make a web request and post your heart rate data to your MySQL web handler which inserts the data into MySQL.
There is a tutorial on how to build a PHP-based MySQL handler here and save data from Android.


text:
Q: How to get value from input with Blur() inside of change event in vue I have a form that is using a change event to handle a method. One of the inputs is causing an error though because it is reading the value before the user is finished adding value. Is there a way to make inputvalue1's value have a blur function attached, so the value isn't read after each letter is typed? I can't make the whole thing a on Blur because then the date picker won't trigger the method.
    <form
      :items=item
      :key="formItem.id"
      @change="handleChange"
    >

const handleChange = () => {
 const inputValue1 = form.value[inputOne].toUpperCase()
 const inputDate = form.value[inputTwo]
if(inputValue1 === 'Something'){
  inputDate = '12/12'21'
}


text:
Q: Is there any way for sync MySql function from kafka MySql source connector to kafka Oracle sink connector I'm using kafka connector for CDC from MySQL to Oracle database.
It's my server specification.
- MySQL : 8.0
  - OS: centos 7.8(64-bit)
- Oracle : 18c xe
  - OS: Oracle Linux 7.6(64-bit)
- Source Connector : debezium-connector-mysql-1.9.5
- Sink Connector : confluentinc-kafka-connect-jdbc-10.5.0

I have trying to sync different database MySQL and Oracle.
I have succeeded in create table, insert in MySQL and sync to oracle.
However, when function is created, topic is created by reading bin log, but it is not sink to Oracle.
When the confluent sink connector sinks data, it appears to be running SQL by referring to a table-based topic.
But when a function is generated, a separate topic other than the topic of the bin log is not generated, so the sink does not seem to be normal.
Is there any way to transfer the function of the database using CDC?


text:
Q: Glob matching file or directory I'm using node-glob, https://github.com/isaacs/node-glob.
My structure is:
img/
 -/nested
     image1.png
     image2.jpg
 -/emtpy
 image1.png
 image2.jpg

I'm trying to get all the images + empty directories
Using

'**/*+(.jpg|.png)'

Results in:
[
    "img/nested/image1.png",
    "img/nested/image2.jpg",
    "img/image1.png",
    "img/image2.png"
]

Using

'**/*/'

Works as expected:
[
    "img/",
    "img/empty/",
    "img/nested/"
]

Trying to combine both results doesn't work at all

'**/*+(.jpg|.png|/)'

Empty array
 []

I would like to have 2 results combined in something like:
[
    "img/",
    "img/empty/",
    "img/nested/"
    "img/nested/image1.png",
    "img/nested/image2.jpg",
    "img/image1.png",
    "img/image2.png",
]

A: The final solution of our common experimenting session in comments: '**/*{/,+(.jpg|.png)}'


text:
Q: How to get the path where pip installs `data_files`? Running pip install seems to create the directory structure + files specified in data_files in /usr/local
However, if I run:
import sys
sys.prefix

I get the string /usr.
Is there any way to figure out where pip installed the data_files for a specific package in a distribution/OS agnostic way ?
Note: I am installing a package from a github repostiroy instead of pypi so maybe this results in the different behavior ?

A: I believe you should work with sysconfig.
First try:
path/to/pythonX.Y -m sysconfig

And then try its get_path function:
import sysconfig

data_path_str = sysconfig.get_path('data')
print("data_path_str", data_path_str)


text:
Q: Show FB Login, only if not logged in before for the current site Question is similar to
A proper approach to FB auth
However i only want client side code.
Conditions
1. User may not be logged into FB. In this case user "has to" login to FB and effectively my App.
   Show FB Login button.
2. User is already logged into FB. Not logged into my App.
   Show FB Login button.
3. User is logged into Fb and my app.
   Show App. No FB login button
Problem : if user is already logged into FB, FB.login results in error.
I need community help. I know its a simple logical problem, however I am circling around the solution for hours now.
My code

    Login with Facebook


text:
Q: Is it possible to assign events to individual data points on a stacked bar chart? I have a stacked bar chart on my userform that I am generating dynamically based of data that is currently in an array. There are approximately 500 data points in total, around 20 series.
What I currently have is each datapoint on this chart owns its own tooltip. That is, when a user hovers over a data point, a tooltip pops up, telling the user where the data is coming from. What I would like is to assign an event handler to each datapoint, so that on MouseOver, I can change the color of that individual datapoint.
I believe one way would be to capture the mouse position over the chart, and then with a little math, figure out which data point is being hovered. However, if possible, I would like a simpler solution. Are there any event handlers that can do this? If so, how would I go about assigning them? I did a little searching and it appears that I can only apply an event handler to the chart area itself, which doesn't really serve my purpose.
Any advice would be gladly appreciated

A: With the System.Windows.Forms.DataVisualization.Charting component this is only possible by registering the MouseMove event and calculating the hovered point as you suggested in your question.
The DataPoint class itself does not offer any events, see the documentation


text:
Q: No value provided for placeholder expressions Despite setting flyway.placeholderReplacement=false I keep seeing error about no value provided for placeholder expression in sql by Flyway

ERROR: Unexpected error
      org.flywaydb.core.api.FlywayException: No value provided for placeholder expressions:  & conditions.  Check your configuration!
        at org.flywaydb.core.internal.database.oracle.pro.SQLPlusPlaceholderReplacer.replacePlaceholders(SQLPlusPlaceholderReplacer.java:132)
        at org.flywaydb.core.internal.util.line.PlaceholderReplacingLine.getLine(PlaceholderReplacingLine.java:36)
        at org.flywaydb.core.internal.database.ExecutableSqlScript.extractStatements(ExecutableSqlScript.java:156)
        at org.flywaydb.core.internal.database.ExecutableSqlScript.(ExecutableSqlScript.java:133)
        at org.flywaydb.core.internal.database.oracle.OracleSqlScript.(OracleSqlScript.java:61)
        at org.flywaydb.core.internal.database.oracle.OracleDatabase.doCreateSqlScript(OracleDatabase.java:126)
        at org.flywaydb.core.internal.database.Database.createSqlScript(Database.java:163)
        at org.flywaydb.core.internal.resolver.sql.SqlMigrationExecutor.getSqlScript(SqlMigrationExecutor.java:96)
        at org.flywaydb.core.internal.resolver.sql.SqlMigrationExecutor.executeInTransaction(SqlMigrationExecutor.java:109)
        at org.flywaydb.core.internal.command.DbMigrate.isExecuteGroupInTransaction(DbMigrate.java:312)
        at org.flywaydb.core.internal.command.DbMigrate.applyMigrations(DbMigrate.java:275)
        at org.flywaydb.core.internal.command.DbMigrate.migrateGroup(DbMigrate.java:244)
        at org.flywaydb.core.internal.command.DbMigrate.access$100(DbMigrate.java:53)
        at org.flywaydb.core.internal.command.DbMigrate$2.call(DbMigrate.java:163)
        at org.flywaydb.core.internal.command.DbMigrate$2.call(DbMigrate.java:160)
        at org.flywaydb.core.internal.database.Connection$1.call(Connection.java:145)
        at org.flywaydb.core.internal.util.jdbc.TransactionTemplate.execute(TransactionTemplate.java:74)
        at org.flywaydb.core.internal.database.Connection.lock(Connection.java:141)
        at org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory.lock(JdbcTableSchemaHistory.java:150)
        at org.flywaydb.core.internal.command.DbMigrate.migrateAll(DbMigrate.java:160)
        at org.flywaydb.core.internal.command.DbMigrate.migrate(DbMigrate.java:138)
        at org.flywaydb.core.Flyway$1.execute(Flyway.java:947)
        at org.flywaydb.core.Flyway$1.execute(Flyway.java:910)
        at org.flywaydb.core.Flyway.execute(Flyway.java:1238)
        at org.flywaydb.core.Flyway.migrate(Flyway.java:910)
        at org.flywaydb.commandline.Main.executeOperation(Main.java:161)
        at org.flywaydb.commandline.Main.main(Main.java:108)
      Build step 'Execute shell' marked build as failure
      Finished: FAILURE

A: Using spring boot, in application.yml.
Add the below placeholderReplacement: false
 flyway:
    baseline-on-migrate: false
    sql-migration-prefix: V
    table: migration
    placeholderReplacement: false

This was happening, because i had in my .SQL migration file, HTML code with ${name}.
So it was trying to replace that! and i want it to be as is, to be inserted in the database.
Summary: in my case i want it always disabled, as i have no use of it
References: Possible Usages In Different Configuration

A: flyway.placeholderReplacement=false is only for Flyway placeholders, not SQL*Plus placeholders.
To disable SQL*Plus-specific placeholders, you must include SET DEFINE OFF in your script.

A: I think, best way to resolve this error - it's override default prefix and suffix
flyway.placeholderPrefix=$${
flyway.placeholderSuffix=}

because disabling this functionality may be unacceptably for some reasons: using flyway variables, for instance.

A: If your use case is similar to mine (you cannot disable placeholders and you cannot change the prefix), an alternative way is to break the placeholder value. Let's says you SQL is:
UPDATE table SET value = '${variable}';

You can avoid FlyWay picking up the placeholder by using something like:
UPDATE table SET value = '$' + '{variable}';

A: you can encode the whole string with UTF-8, then decode it when you need to use it


text:
Q: Spark distribute tasks over several executors I d'like to run a SQL query in parallel and be able to control the level of parallelism to 8 queries. Right now, I am doing this piece of code.
The idea is to create 8 partition and allow executors to run them in parallel.
  (1 to 8).toSeq.toDF.repartition(8) // 8 partitions
  .rdd.mapPartitions(
  x => {
  val conn = createConnection()
    x.foreach{
      s => { // expect the below query be run concurently
      execute(s"SELECT * FROM myTable WHERE col = ${s.get(0)}")
      }
    }
  conn.close()
  x
  }).take(1)

The problem is the 8 queries are run one by one.
How should I proceed to get queries run 8 by 8 ?

A: When you do
val df = (1 to 8).toSeq.toDF.repartition(8)

This will not create 8 partitions with 1 record each. If you inspect this dataframe (see e.g. https://stackoverflow.com/a/46032600/1138523), then you get :
+----------------+-----------------+
|partition_number|number_of_records|
+----------------+-----------------+
|               0|                0|
|               1|                0|
|               2|                0|
|               3|                0|
|               4|                0|
|               5|                0|
|               6|                4|
|               7|                4|
+----------------+-----------------+

So you will have only 2 partitions which are non empty, therefore you will have at max 2-fold parallelism (I've asked about this here : How does Round Robin partitioning in Spark work?)
To make equal-sized partitions, you better use
spark.sparkContext.parallelize((0 to 7), numSlices = 8)

instead of
(1 to 8).toSeq.toDF.repartition(8).rdd

The first option gives you 1 record per partition, the second one not as it uses round robin partitioning
As a side note, when you do x.foreach, then x will be consumed (Iterators are only traversable once) so if you return x you will always get an empty iterator.
So your final code can look like this :
 spark.sparkContext.parallelize((0 to 7), numSlices = 8)
.mapPartitions(
  x => {
  val xL = x.toList  // convert to List
  assert(xL.size==1) // make sure partition has only 1 record

  val conn = createConnection()
    xL.foreach{
      s => { // expect the below query be run concurently
      execute(s"SELECT * FROM myTable WHERE col = ${s}")
      }
    }
  conn.close()
  xL.toIterator
  })
 .collect // trigger all queries

Instead of using mapPartitions (which is lazy), you could also use foreachPartition, which is non-lazy
As you have only 1 record per partition, iterating the partitions isn't really beneficial, you could also just use a plain foreach:
 spark.sparkContext.parallelize((0 to 7), numSlices = 8)
.foreach( s=> {
  val conn = createConnection()
  execute(s"SELECT * FROM myTable WHERE col = ${s}")
  conn.close()
})


text:
Q: hide and show table row in loop Table edit button in loop is hiding and showing the first row of table with each edit button click. I need to hide and show each row in loop with its own edit button.
  <?php
        $counter = 0;
        foreach($db->getRecordSet($sqlRecord) as $row){ $counter += 1;
            ?>

                 <?php echo($counter); ?>

                 <?php echo($row['item_code']); ?>
                 <?php echo($row['item_name']); ?>
                 <?php echo($row['description']); ?>
                 <?php echo($row['quantity']); ?>
                 <?php echo($row['p_cost']); ?>

                 <input type="button" name="edit" id="edit" value="edit" onClick="hideRow()" />

                <input type="text" class="form-control" name="item_code" id="item_code" value="<?php echo($row['item_code']); ?>" required="required" />

                <?php
            }
        ?>

    <?php } ?>

 -------------------------
function hideRow(){
    if(
        document.getElementById('editContent').style.display=='none') {
        document.getElementById('editContent').style.display='';
        document.getElementById('rowDetails').style.display='none';
    } else {
        document.getElementById('editContent').style.display='none';
        document.getElementById('rowDetails').style.display='';
    }

A: try to use jquery bro.
change this line of code:
<input type="button" name="edit" id="edit" value="edit" onClick="hideRow()" />

to :
<input type="button" name="edit" class="hide_button" />

then change :
function hideRow(){
 if(
    document.getElementById('editContent').style.display=='none') {
    document.getElementById('editContent').style.display='';
    document.getElementById('rowDetails').style.display='none';
 } else {
    document.getElementById('editContent').style.display='none';
    document.getElementById('rowDetails').style.display='';
 }

To:
 $( document ).ready(function() {
    $(".hide_button").click(function(){
         $(this).parents('tr').hide();
    });
 });


text:
Q: How to handle exception in vertx consumer? I have code:
SqlTemplate
    .forQuery(client, "SELECT * FROM user WHERE id=#{id}")
    .execute(parameters)
    .onSuccess(users -> {
      users.forEach(row -> {
        // exception here
        System.out.println(row.get(UUID.class, "id1") + " " + row.getString("title"));
      });
    })

What is the best way to handle exceptions in consumers?
For now if exception raises it will be swallowed...

A: Assuming you want to fail the flow when an exception is thrown, it is better to use compose to iterate through the users and handle .onSuccess() and .onFailure() separately.
You can use CompositeFuture to achieve this. You can have a Future list and add succeededFuture / failedFuture (in case of exception) to the list in the forEach loop.
SqlTemplate
    .forQuery(client, "SELECT * FROM user WHERE id=#{id}")
    .execute(parameters)
    .compose(users -> {
      List<Future> usersFuture = new ArrayList<>();
      users.forEach(row -> {
        try {
          // exception here
          System.out.println(row.get(UUID.class, "id1") + " " + row.getString("title"));
          usersFuture.add(Future.succeededFuture());
        } catch (Exception e) {
          usersFuture.add(Future.failedFuture(e));
        }
      });
      return CompositeFuture.all(usersFuture).mapEmpty();
    })
    .onSuccess(res -> {
        // end the flow with success
    })
    .onFailure(e -> {
        // Add error message and fail the flow
    });

Also in general I'm curious about the exceptions that can be thrown here. As it is the data that you have written to your db after validations, you should be aware of the possible error scenarios and handle them accordingly without failing the flow.


text:
Q: UEFI, Windows 8 - installing SSD, removing HDD I have a perfectly good laptop for work, HP ProBook 455 G1, the only problem is it's really a garbage HDD_! So I decided to buy an SSD. But, the problem is that this machine has to be fully functional every day.
My question is: can I just buy an SSD, put it in in place of the original HDD, install Windows 8.1 on it (I have a DVD, and yes, the notebook still has a DVD drive :) ) and if something unexpected happens, just pop in the old drive and at least have it running for the time being?
Thank you.

A: Yes, This will work fine, Obviously any files you create on the SSD will not be copied over when you put the HDD back in so an idea to get around this is to use cloud storage like Dropbox or Google Drive.


text:
Q: How to sort tuples in a column of a dataframe I have a dataframe that consists of a column of tuples as shown:
pid         aid
0000000F    (0BDEAC61, 288E046F)
00000017    (7795AF0D, 4A259AFA, 7DA84B6E)
00000019    (8123B8CF, 3A25A1FE)
00000025    (28045D98, 8043B6E5, 81195E5D)
0000003A    (7D566708, 7F5583AE)

I want to sort the values in each of the tuples so the result would be as follows:
pid         aid
0000000F    (0BDEAC61, 288E046F)
00000017    (4A259AFA, 7795AF0D, 7DA84B6E)
00000019    (3A25A1FE, 8123B8CF)
00000025    (28045D98, 8043B6E5, 81195E5D)
0000003A    (7D566708, 7F5583AE)

I know that I can loop through them one at a time and sort as follows:
z = list(eval(df.aid.iloc[0]))
z.sort()

But that would take a long time as it's a huge dataframe (over 4 million). Is there a faster method.
I also tried:
df.aid = df.aid.apply(lambda x: list(eval(x)).sort())

but I got "None"
Any help would be appreciated.

A: I think simpliest is use list comprehension if no NaNs values:
#import ast
#one possible way for convert string to tuples
#df['aid'] = df['aid'].apply(ast.literal_eval)

print (df['aid'].head().apply(type))
0    <class 'tuple'>
1    <class 'tuple'>
2    <class 'tuple'>
3    <class 'tuple'>
4    <class 'tuple'>
Name: aid, dtype: object

df['aid'] = [tuple(sorted(x)) for x in df['aid']]
print (df)
        pid                             aid
0  0000000F            (0BDEAC61, 288E046F)
1  00000017  (4A259AFA, 7795AF0D, 7DA84B6E)
2  00000019            (3A25A1FE, 8123B8CF)
3  00000025  (28045D98, 8043B6E5, 81195E5D)
4  0000003A            (7D566708, 7F5583AE)

Or:
df['aid'] = df['aid'].apply(sorted)
print (df)
        pid                             aid
0  0000000F            [0BDEAC61, 288E046F]
1  00000017  [4A259AFA, 7795AF0D, 7DA84B6E]
2  00000019            [3A25A1FE, 8123B8CF]
3  00000025  [28045D98, 8043B6E5, 81195E5D]
4  0000003A            [7D566708, 7F5583AE]


text:
Q: How can I listen for a mouse event in Python on Mac? I need to listen for global mouse events(not bound to an app) on my Mac in an app written in Python.
I'm using PyObjC, but I can't figure out how to do it. Plain ObjC examples or other Python techniques also appreciated.
My code so far:
from Quartz import *
def MyFunction(proxy, type, event):
    print event

CGEventTapCreate(kCGHIDEventTap, kCGTailAppendEventTap, kCGEventTapOptionListenOnly, kCGEventLeftMouseDown, MyFunction)

== Segmentation fault
I know I need to add it to an event source later on, but I need to get this working first.
[update]
Using PyObjC form Macports solved the segfault, so now I wrote this:
from Quartz import *

def MyFunction(p, t, e, c):
    print e

tap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionListenOnly, kCGEventLeftMouseDown, MyFunction, None)

runLoopSource = CFMachPortCreateRunLoopSource(None, tap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
CGEventTapEnable(tap, True);

CFRunLoopRun();

But this just runs forever and does not respond to mouse events, what is wrong?

A: The fourth parameter of CGEventTapCreate is CGEventMask eventsOfInterest, and you gave it kCGEventLeftMouseDown which is an enum of type _CGEventType. Instead of the integer constant, you need to flip the appropriate bit in the bitmask. You can do this using CGEventMaskBit
So instead of this:
tap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap,
    kCGEventTapOptionListenOnly, kCGEventLeftMouseDown, MyFunction, None)

We can do this:
tap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap,
    kCGEventTapOptionListenOnly, CGEventMaskBit(kCGEventLeftMouseDown),
    MyFunction, None)

or equivalently:
tap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap,
    kCGEventTapOptionListenOnly, (1 << kCGEventLeftMouseDown),
    MyFunction, None)

A: The documentation for CGEventTapCreate (http://developer.apple.com/mac/library/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html#//apple_ref/c/func/CGEventTapCreate) says that you need to be root to use kCGHIDEventTap. Are you running your script as root? (sudo is one way to do this)
If you are, you should also check whether tap is None; that will help narrow down the problem. There are several error conditions listed in the documentation that can cause CGEventTapCreate to return NULL, which should be reflected as None in Python.

A: First, CGEventTapCreate and CGEventTapCreateForPSN leak some memory when they
are called. This is needed to avoid memory management problems. It is therefore
advisable not to call these functions, are at least call them a small number
of times.
Now, a mouse event works something like this:
evt = CGEventCreateMouseEvent(None, kCGEventLeftMouseDown, (80, 90), kCGMouseButtonLeft)
self.failUnlessIsInstance(evt, CGEventRef)


text:
Q: Iterator for loop logic I have a problem that I can't think through.
I have a list of phone numbers, which are represented as: A user has the app
I also have a treemap of all contacts in my phone
I want to compare all users that have the app to my treemap of contacts, so that if the user has the app - i can add them as a friend, but if they don't then I can send out a text invite. Here's what i have, but it's not working:
Iterator<Entry<String, String>> it = contacts.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
                for(int i = 0; i < users.size(); i++) {
                    String userNumber = Helper.formatNumber(users.get(i).getString("phone"));
                    if(pairs.getValue().equals(userNumber)) { //they have the app
                        contact_data.add(new Contact(pairs.getKey().toString(), pairs.getValue().toString(), true));
                    } else { //they don't have the app
                        contact_data.add(new Contact(pairs.getKey().toString(), pairs.getValue().toString(), false));
                    }
                }
                it.remove(); // avoids a ConcurrentModificationException
            }

A: Every time you check to see if a user matches the contact you are currently looking at, you add that user. It seems like you only want to add one user per contact.
One approach would be to add a boolean "found" before your for loop and initialize it to false. Once you find a user who has the app, set this boolean to true. Put the else branch labelled "//they don't have the app" after the for loop and only run it if(!found). This will ensure that you only add one contact data per contact.


text:
Q: XSS PHP Log Filter? I have a log function on my admin panel that checks user input for being correct and, if not correct, writes it to a log file. This log file is written to the admin when logged in.
I was testing my site for vulnerabilities, and I managed to fully exploit my server using an XSS hole. I tried to filter logged input by checking the input through this function:
function isXSS($in){
    return preg_match("[<>(%[0-9a-fA-F]{2}+)]", $in) == 1;
}

but that would either paranoidly mark everything as a loathed XSS worm, or ignore common XSS injections. I think that the problem is the + quantifier, but I have heard that other PHP regexes allow this.

A: What's wrong with good old htmlspecialchars? I see why you might want to track potentially malicious users, but if you're investing your energy in simply blocking the security holes instead, then there's really no need.

A: You're trying to enumerate badness, which is a battle you'll never win.  Instead, you should be only allowing through markup that you know is good, via a library like htmlpurifier
Also, I'm not sure about the {2}+ syntax, but I believe this is closer to what you want:
"[<>(%[0-9a-fA-F]{2,})]"


text:
Q: Backup seLinux system running strict I have a cron job that is backing up a SELinux system running in strict mode. The problem is that SELinux wants to deny access to to the backup script since it wants access to every single file on the filesystem (and all the contexts on those files). I'm running in permissive mode right now so the script works, but I would like to turn permissive mode off.
kernel: [1491196.754521] type=1400 audit(1325232096.275:12572): avc:  denied  { read open } for  pid=24642 comm="xfsdump" name="init.d" dev=dm-1 ino=268794309 scontext=root:sysadm_r:cronjob_t tcontext=system_u:object_r:initrc_state_t tclass=dir

Running the script as unconfined_t doesn't work as it seems unconfined_t is not allowed when running the strict policy.
The backup is being performed by taking an LVM snapshot of root, mounting that snapshot, and then doing an xfsdump. It also backs up the /boot partition (ext2) into a tarball.
What is the proper way to perform such a backup?
Is there a way to mount the filesystem where the file contexts can be backed up, but will not be enforced? But also for academic purposes, if I want to back up a system where such a mount isn't possible (already mounted and not possible to remount), how would that be accomplished?

A: You need to be more specific and tell us what distro/policy you are running, some allow for "unconfined" processes which would satisfy your needs (man runcon), others do not - in which case you would have to either label your backup script with an SELinux type that allows read access to all files OR create a new application policy for it (hard).
Edit: I assume you've already read SELinux FAQ entry on backup: use star

A: There is a backup policy module that can be used which provides a backup_t and allows system backups. Its part of tresys refpolicy, http://oss.tresys.com/projects/clip/browser/trunk/refpolicy/src/selinux-policy-clip/policy/modules/admin/backup.te
After installing, just set the file context of the backup script to backup_exec_t and it'll be able to access the whole system.


text:
Q: RandomForestClassifier Explainer Dashboard output in databricks notebook is not rendered I am trying to render RandomForestClassifier model dashboard using ExplainerDashboard package, but it is not rendering the dashboard in notebook.
Here is the code
model = RandomForestClassifier(n_estimators=50, max_depth=10).fit(X_train, y_train)
explainer = ClassifierExplainer(model, X_test, y_test)
ExplainerDashboard(explainer).run()

I was getting below output
=========================================================================

Detected RandomForestClassifier model: Changing class type to RandomForestClassifierExplainer...

Note: model_output=='probability', so assuming that raw shap output of RandomForestClassifier is in probability space...

Generating self.shap_explainer = shap.TreeExplainer(model)
Building ExplainerDashboard..

Detected notebook environment, consider setting mode='external', mode='inline' or mode='jupyterlab' to keep the notebook interactive while the dashboard is running...

Warning: calculating shap interaction values can be slow! Pass shap_interaction=False to remove interactions tab.

Generating layout...

Calculating shap values...

Calculating prediction probabilities...

Calculating metrics...

Calculating confusion matrices...

Calculating classification_dfs...

Calculating roc auc curves...

Calculating pr auc curves...

Calculating liftcurve_dfs...

Calculating shap interaction values... (this may take a while)

Reminder: TreeShap computational complexity is O(TLD^2), where T is the number of trees, L is the maximum number of leaves in any tree and D the maximal depth of any tree. So reducing these will speed up the calculation.

Calculating dependencies...

Calculating permutation importances (if slow, try setting n_jobs parameter)...

Calculating pred_percentiles...

Calculating predictions...

Calculating ShadowDecTree for each individual decision tree...

Reminder: you can store the explainer (including calculated dependencies) with explainer.dump('explainer.joblib') and reload with e.g. ClassifierExplainer.from_file('explainer.joblib')

Registering callbacks...

Starting ExplainerDashboard on http://19.221.249.249:8055

Dash is running on http://0.0.0.0:8055/

 * Serving Flask app 'explainerdashboard.dashboards' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://19.221.249.249:8055/

=========================================================================

But dashboard is not rendered in notebook. I tried with InlineExplainer also, it was returning <IPython.lib.display.IFrame at 0x7f4eea3e1c70>
Can you please suggest any idea to render dashboard in databricks notebook

A: To render the dashboard in your notebook, you should use the InlineExplainer.
With that, you can plot model performance or shape values for instance as explained in the documentation.
You can use the following code as a reference:
from sklearn.ensemble import RandomForestClassifier
from explainerdashboard.datasets import titanic_survive
from explainerdashboard import ClassifierExplainer, ExplainerDashboard
from explainerdashboard import InlineExplainer

X_train, y_train, X_test, y_test = titanic_survive()

model = RandomForestClassifier(n_estimators=50, max_depth=10).fit(X_train, y_train)
explainer = ClassifierExplainer(model, X_test, y_test)

InlineExplainer(explainer).shap.overview()

Output:

A: Please do the following steps you will be able to get the ExplainerDashboard view:
Step 1) Set the Environment variables in Databricks Cluster
For example :
DASH_REQUEST_PATHNAME_PREFIX=/driver-proxy/o/40xxxxxxxx/1004xxxxx/8888
Workspace ID : 40xxxxxxx
Cluster-ID: 1004xxxxxxxx
Port number: 8888
Step 2) Install the explainerdashboard library
%pip install explainerdashboard
Step 3) Sample code to validate the "dash"
from sklearn.ensemble import RandomForestClassifier
from explainerdashboard import ClassifierExplainer, ExplainerDashboard
from explainerdashboard.datasets import titanic_survive, feature_descriptions
X_train, y_train, X_test, y_test = titanic_survive()
model = RandomForestClassifier(n_estimators=50, max_depth=10).fit(X_train, y_train)
explainer = ClassifierExplainer(model, X_test, y_test,
cats=['Deck', 'Embarked'],
descriptions=feature_descriptions,
labels=['Not survived', 'Survived'])
ExplainerDashboard(explainer, mode = 'dash',
importances=False,
model_summary=False,
contributions=True,
whatif=False,
shap_dependence=False,
shap_interaction=False,
decision_trees=False).run(8888)
Step 4) Dashboard URL
https://xxxxxxxx.databricks.com/driver-proxy/o/<workspaceID/clusterID/8888


text:
Q: Creating copy of featureclass using ArcObjects does not set measures? I am making an exact (empty) copy of an existing featureclass using the following code:
public static string createFCCopy(IFeatureClass pFromFC, IFeatureWorkspace pToFWS, string sNewFCName)
{
    IFeatureClass pNewFC;
    UID pUID;

    pUID = new UIDClass();
    pUID.Value = UID_FEATURECLASS; // UID_FEATURECLASS is a constant set to "esriGeodatabase.Feature"

    sShpFld = pFromFC.ShapeFieldName;
    pNewFC = pToFWS.CreateFeatureClass(sNewFC, pFromFC.Fields, pUID, null, pFromFC.FeatureType, sShpFld, "");
}

The problem is that the resulting copy does not have Measures and Z set like the original.
Is there a way of specifying the fields set that preserves the HasM and HasZ values in the Geometry Def?

A: Curious about this problem I wrote the following code in VBA and it transferred over the ZM properties without any problems.
Public Sub CreateFC()
     Dim pMxDoc As IMxDocument
     Set pMxDoc = ThisDocument
     Dim pFL As IFeatureLayer
     Dim pL As ILayer
     Dim pFC As IFeatureClass
     Set pL = pMxDoc.FocusMap.Layer(0)
     Set pFL = pL
     Set pFC = pFL.FeatureClass
     Dim pUID As UID
     Set pUID = New UID
     pUID.Value = "esriGeodatabase.Feature"
     Dim pFWs As IFeatureWorkspace
     Dim pWS As IWorkspace
     Dim pWSF As IWorkspaceFactory
     Set pWSF = New FileGDBWorkspaceFactory
     Set pWS = pWSF.OpenFromFile("c:\scratch\fGDB_Scratch.gdb", 0)
     Set pFWs = pWS
     Dim pNewFC As IFeatureClass
     Set pNewFC = pFWs.CreateFeatureClass("fcTest", pFC.Fields, pUID, Nothing, pFC.FeatureType, pFC.ShapeFieldName, "")
End Sub

Looking at your code it's possible to provide a different shape field name to the one that is in the FeatureClass you are copying from, may be you have introduced some sort of conflict and it is dropping ZM property?
Failing this you could call the Geo-processing tool Create FeatureClass using the IGeoProcessor?