text:
Q: Error null exception in "for" construct xamarin android. Where is incorrect? This method returns the number of types of Views that will be created by getView method.

public class CustomAdapter : BaseAdapter{

  private  const int TYPE_ITEM = 0;
  private const int TYPE_SEPARATOR = 1;

  private List<string> mData;
  private TreeSet sectionHeader;

  private LayoutInflater mInflater;

  public CustomAdapter(Context context, List<string> Data) {
   mInflater = (LayoutInflater) context
    .GetSystemService(Context.LayoutInflaterService);
   this.mData=Data;
  }

  public void addItem(string item) {
   mData.Add(item);
   NotifyDataSetChanged();
  }

  public void addSectionHeaderItem(string item) {
   mData.Add(item);
   //sectionHeader.Add(mData.Count - 1);
   NotifyDataSetChanged();
  }

  public int getItemViewType(int position) {
   return sectionHeader.Contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
  }

  public int getViewTypeCount {
   get{ return 2; }
  }

  public override int Count {
   get {return mData.Count;}
  }

  public override Java.Lang.Object GetItem(int position) {
   return mData[position];
  }

  public override long GetItemId(int position) {
   return position;
  }

  public override View GetView(int position, View convertView, ViewGroup parent) {
   ViewHolder holder = null;
   int rowType = getItemViewType(position);

   if (convertView == null) {
    holder = new ViewHolder();
    switch (rowType) {
    case TYPE_ITEM:
     convertView = mInflater.Inflate(Resource.Layout.textViewItemsSeparator, parent);
     holder.textView = (TextView) convertView.FindViewById(Resource.Id.textviewHeaderItems);
     break;
    case TYPE_SEPARATOR:
     convertView = mInflater.Inflate(Resource.Layout.textViewHeaderItems, parent);
     holder.textView = (TextView) convertView.FindViewById(Resource.Id.textviewItemsSeparator);
     break;
    }
    convertView.Tag=holder;
   } else {
    holder = (ViewHolder)convertView.Tag as ViewHolder;
   }
   holder.textView.Text=mData[position];

   return convertView;
  }

  public  class ViewHolder:Java.Lang.Object {
   public TextView textView;
  }

 }

ListView lst;
  string[] items = new string[] { "Alternative Rock","Classical",...........};

  List<string> listItems;

  private CustomAdapter mAdapter;
  public override void OnCreate (Bundle savedInstanceState)
  {
   base.OnCreate (savedInstanceState);

   // Create your fragment here
  }

  public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
   // Use this to return your custom view for this Fragment
   // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

   listItems = new List<string> (items);

   return inflater.Inflate (Resource.Layout.GenerFragment, container, false);
  }

  public override void OnActivityCreated(Bundle savedInstanceState)
  {
   base.OnActivityCreated(savedInstanceState);

   lst = View.FindViewById<ListView> (Resource.Id.lstGenres);

   //lst.Adapter = new ArrayAdapter<string>(Activity, Resource.Layout.textViewHeaderItems,Resource.Id.textviewHeaderItems, items);
   //lst = View.FindViewById<ListView> (Resource.Id.lst_genre);

   //lst.SetAdapter(new ArrayAdapter<String>(this.Activity, Resource.Layout.GenerFragment, items));
   //mAdapter=new CustomAdapter();
   for (int i = 0; i < listItems.Count(); i++) {
    mAdapter.addItem (listItems[i]);
    if (i == 0) {
     mAdapter.addSectionHeaderItem ("Music");
    } else if(i==13) {
     mAdapter.addSectionHeaderItem ("Audio");
    }
   }
   lst.Adapter = new CustomAdapter (Activity, listItems);

I spent much time for looking for errors but I have no idea why It was null. although It got a data from list
mAdapter.addItem (listItems[i]); -> null exception when I debug on device. Where is incorrect?

A: in OnActivityCreated you are referencing listItems
for (int i = 0; i < listItems.Count(); i++) {

however, listItems is null.  You initialize it in OnCreateView, which has not been executed yet.  You need to be sure that listItems is initialized before you attempt to reference it.
Additionally, you are attempting to add items to mAdapter, but it's never been initialized (as far as I can see)
you declare it here, but it will be NULL until you initalize it
private CustomAdapter mAdapter;

here is the initialization, which is commented out
//mAdapter=new CustomAdapter();

when you attempt to reference it here, it is still null, and will throw a Null Reference Exception
mAdapter.addItem (listItems[i]);


text: Q: Projective objects of chain category I am tempted to think that the projective objects in the chain category $\text{Ch}(\mathcal C)$ for $\mathcal C$ abelian are exactly the complexes $P_\bullet$ for which each $P_i$ is projective. Is this true? If not, what is a counterexample?

redpajama_set_name: RedPajamaStackExchange


text:
Q: T-SQL Convert/Concatenate/Transpose Rows to Columns Have tried numerous SQL fiddles but got nowhere fast. I have the following in a table
Col1 | Col2 | Col3
-------------------
 A   | B    | C
 D   | E    | F
 G   | H    | I

I need the output to be
 A   | D    | G
 B   | E    | H
 C   | F    | I

Please can someone help. I understand a PIVOT might be the best bet?
Thanks

A: Start by unpivotting it, then push it back the other way.
with --Build up as we go
--Start with original data
t (Col1, Col2, Col3)
as
(          select 'A','B','C'
 union all select 'D','E','F'
 union all select 'G','H','I')
,
--Put rownums in there - they'll help
numbered as (
select row_number() over (order by Col1) as rownum, *
from t)
,
--Now unpivot the data, using cross apply.
unpivotted as (
select r.rownum, c.colnum, c.val
from numbered r
cross apply (values (1, Col1), (2, Col2), (3, Col3)) as c (colnum, val)
)
--Now pivot it back again, grouping by colnum
select max(case when rownum = 1 then val end),
       max(case when rownum = 2 then val end),
       max(case when rownum = 3 then val end)
from unpivotted
group by colnum;


text:
Q: How to receive RTP Packets which are Streaming from RTP URL in iOS Device? (e.g. rtp://@225.0.0.0) I am trying to stream RTP Packets (which is streaming an audio) from RTP URL e.g. rtp://@225.0.0.0
after so much research on the same i have somewhat streamed the URL in my device and playing it with https://github.com/maknapp/vlckitSwiftSample.
This is only playing the Streamed Data but does not have any function to store the data.
From research and other sources i dint find much content and simple information that should be helpful to stream the Packet over RTP and store it in iOS Device.
I have tried with following link.

*

*https://github.com/kewlbear/FFmpeg-iOS-build-script

*https://github.com/chrisballinger/FFmpeg-iOS
These two are not even compiling due to POD Issues other projects or guide just giving me reference on RTSP Stream instead of RTP Stream.
If anyone can give us a guidance or any idea that how we can implement such things then it will be appreciated.

A: First foremost, you need to understand how this works.
The sender i.e. the creator of RTP stream is probably doing the following:

*

*Uses a source for the data: In case of audio, this could be the microphone or audio samples or a file

*Encodes the audio using a audio codec such as AAC or Opus.

*Uses RTP packetizer to create RTP packets from encoded audio frames

*Uses a transport layer such as UDP to send these packets

Protocols such as RTSP provides the necessary signaling information to provide better stream information. Usually RTP itself isn't enough as things such as congestion control, feedback, dynamic bit rate are handled with the help of RTCP.
Anyway, in order to store the incoming stream, you need to do the following:

*

*Use a RTP depacketizer to get the encoded audio frames out of it. You can write your own or use a third party implementation. In fact ffmpeg is a big framework which has all necessary code for most of the codecs and protocols. However for your case, find a simple RTP depacketizer. There could be headers corresponding to a particular codec to make sure you refer to a correct RFC.

*Once you have access to encoded frames, you can write the same in a media container such as m4a or ogg depending upon the audio codec used in the stream.
In order to play the stream, you need to do the following:

*

*Use a RTP depacketizer to get the encoded audio frames out of it. You can write your own or use a third party implementation. In fact ffmpeg is a big framework which has all necessary code for most of the codecs and protocols. However for your case, find a simple RTP depacketizer.

*Once you have access to encoded frames, use a audio decoder (available as a library) to decode the frames or check if your platform supports that codec directly for playback

*Once you have access to decoded frames, in iOS, you can use AVFoundation to play the same.
If you are looking at an easy way to do it, may be use a third party implementation such as http://audiokit.io/


text:
Q: Why is Drop not dropping the specified variable on the second iteration? I having an issue with SparkR at the moment using the Drop function. I have function which is designed to replace a date column in a Spark dataframe (df1) with a modified date column from another Spark dataframe (df2). It does this by joining the two frames together on an ID variable and date matching the premodified date in the second dataframe and then drops the specified date column from the joined dataframe. It then goes on to drop the now duplicated ID variable from the second dataframe, preserving the first one. It will do this for the first iteration (replacing Date1 in the example), but when I try and do this for the subsequent columns (Date2, Date3 etc.) it does not drop the ID column when requested. This results in an error later one, when it complains that reference to ID is ambiguous. According the SparkR documentation on Drop "This is a no-op if schema doesn't contain column name(s)." If this means what I think it does, it won't do anything if the column name doesn't exist in the schema. However, I've checked and prior to the drop command, both ID variables exist in the schema.
As a dummy example of what I'm trying to do (where datename is one of Date1, Date2, Date3..):
df1 <- ID Date1 Date2 Date3 Date4 Date5
df2 < -ID DateOrig DateMod

df3<-drop(join(df1, df2, df1[["id"]] == df2[["id"]] & df1[[datename]] == df2[["date"]], "left_outer"),df1[[datename]])

df3<-drop(df1, df2[[1]]) #This command works once, but not again..

#The rest of the function...

Sorry I can't be more detailed in my example, I'm very new to SparkR so I don't know how to make example datasets or anything.


text:
Q: Repeated URL post parameters issue Hi can anyone help why URL string parameters post again and again?
HTTP://127.0.0.1/ab/1936.html?cart=yes?cart=yes

i m using this parameter to open mini cart when we added product into cart in magneto 1.9
Please help me how to protect this?
i am using this code-

<?php
if ($_GET['cart']=='yes') {
    echo "<script type='text/javascript'>
          jQuery('.minicart_open').show();
    </script>";
}
?>

cartController.php
protected function _goBack()
{
    $returnUrl = $this->getRequest()->getParam('return_url');
   // print_r($returnUrl);exit;
    if ($returnUrl) {

        if (!$this->_isUrlInternal($returnUrl)) {
            throw new Mage_Exception('External urls redirect to "' . $returnUrl . '" denied!');
        }

        $this->_getSession()->getMessages(true);
        $this->getResponse()->setRedirect($returnUrl);
    } elseif (!Mage::getStoreConfig('checkout/cart/redirect_to_cart')
        && !$this->getRequest()->getParam('in_cart')
        && $backUrl = $this->_getRefererUrl()
    ) {
        $this->getResponse()->setRedirect($backUrl.'?cart=yes');
    } else {
        if (
            (strtolower($this->getRequest()->getActionName()) == 'add')
            && !$this->getRequest()->getParam('in_cart')
        ) {
            $this->_getSession()->setContinueShoppingUrl($this->_getRefererUrl());
        }
        $this->_redirect('checkout/cart');
    }
    return $this;
}

A: i got the answer

Just replace below line

$this->getResponse()->setRedirect($backUrl.'?cart=yes');

To
$url = $backUrl;
        // Search substring
            if (strpos($url, $key) == false) {
                 $this->getResponse()->setRedirect($backUrl.'?cart=yes');
            }
            else {
                 $this->getResponse()->setRedirect($backUrl);
            }
            //exit;

its working for me...Hope its helpful for you...


text:
Q: Exception org.apache.catalina.core.ApplicationContext.log Servlet.init() for servlet [] threw exception java.lang.IllegalArgumentException While moving from Java 8 to Java 11 I am getting the following exception
   Exception org.apache.catalina.core.ApplicationContext.log Servlet.init() for servlet [health-    servlet] threw exception java.lang.IllegalArgumentException

A: To fix the error i upgraded the version in pom
 -        <jersey.version>2.23.2</jersey.version>
 +        <jersey.version>2.30.1</jersey.version>

I had this in my web.xml
<servlet>
    <servlet-name>health-servlet</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.xyz.platform.registry.service.ServiceRegistryApplication</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>


text:
Q: Arranging DIV using bootstrap 4 without using extra DIV Arranging DIV is easy using bootstarp grid system, but some time its not achievable for me,

I think it's not very complex and achieve without using extra DIV or code but my junk brain is not capable of achieve this grid deisgn,
Thanks

A: Try this layout:-

A: This site may help you to create what you want.


text:
Q: Perl: Replace string with/without "+" sign I am trying to replace parts of string. Currently I am using a simple method as follows:
my $text = $ARGV[0];
my $in_d = $ARGV[1];
my $out_d = "Sample_text";

$text =~ s/$in_d/$out_d/;

The above code does not seem to work if there is a '+' sign involved.
For e.g. for the code:
my $text = "I+here starving here";
my $input_d = "I\+here";
my $out_d = "I";
$text =~ s/$input_d/$out_d/;
print $text."\n";

Output:
I+here starving here

How do I make sure that the text gets replaced regardless of characters involved? Thanks for your help in advance.

A: Use \Q, \E sequence to escape block of characters.
\Qfoo+\E

So, it would be
$text =~ s/\Q$input_d\E/$out_d/;

DEMO


text:
Q: Unable to find an error i know it's a minor and maybe a fool question but i'm stuck for about an hour at an error which i cant see. This is my code:
const ModalRoot = ({ modalType, modalProps, locale }) => {
  if (!modalType) {
    return ;
  }

  return (
    <IntlProvider
      locale={locale}
      key={locale}
      messages={messagesFor(locale)}
    >

        {renderAppropriateModal(modalType, modalProps)}

    </IntlProvider>
  );
};

The console shows an error in the if saying unexpected token. Why is this happening??

A: This can be your error...
check this samples.
Wrong place to declare.
import React from 'react';

class YOURCLASS extends React.Component {
   constructor(props) {
     super(props);

   }

   //do not place this ModalRoot here
   const ModalRoot = ({ modalType, modalProps, locale }) => {
      //contents
   }

   render(){
     return(

{yourContent}

     );
   }
}

Right place to declare
import React from 'react';

//Place it here outside the class YOURCLASS
const ModalRoot = ({ modalType, modalProps, locale }) => {
      //contents
}

class YOURCLASS extends React.Component {
   constructor(props) {
     super(props);

   }

   render(){
     return(

{yourContent}

     );
   }
}

if you still intends to do it inside class... better use function instead...
import React from 'react';

class YOURCLASS extends React.Component {
   constructor(props) {
     super(props);

   }

   //function type ModalRoot
   ModalRoot(modalType, modalProps, locale){
      //contents
      return <IntlProvider />;
   }

   render(){
     const {modalType, modalProps, locale} = this.props;
     let yourContent = this.ModalRoot(modalType, modalProps, locale);
     return(

{yourContent}

     );
   }
}

hope it helps...


text:
Q: I am getting an error about "is of '.class' expected." and I don't understand why. The error that i am getting is of '.class' expected. All i want to do is to get the values of the array from the user.
Kindly help me out.
int[] array = new int [10];
Scanner input=new Scanner (System.in);

// The error comes from the next line.
int array = input.nextInt[];

System.out.println("1. Find Mean");
System.out.println("2. Change Number");
System.out.println("1. Print All");
System.out.println("1. Exit");

A: You already have a variable named array.
int[] array = new int [10]; // <-- right there.
int count = 0; // <-- add this.
Scanner input=new Scanner (System.in);
array[count++] = input.nextInt(); // <-- parens for a method call,
      // square brackets for the array, and add one to the count.

A: Use parentheses () for a method call with no parameters, not brackets [].
int array = input.nextInt();


text:
Q: Why dofactory declare _true_ and _false_ variables dofactory have javascript patterns and practices framework. And here ( 4th example in Idioms and Hacks ) they provide and example of a guru programmer code. Its all clear for me, except for one thing: why do they declare true and false variables? I mean this code:
var _true_ = true; var _false_ = false;
The only idea I have is they want to reduce the lookup time as done for undefined, which makes sure undefined was not overriden and reduce the lookup time. But it seems true and false doesnt give anything to performance.


text:
Q: How to get the current user's (who is logged in) user_id in social engine? php in my socialengine directory. How should I get user's user_id who is logged in? can you give me an exact example?

A: If you're doing this within a controller which extends either Core_Controller_Action_Standard or Engine_Content_Widget_Abstract you can use the following;
Engine_Api::_()->user()->getViewer()->getIdentity();

A: $viewer = Engine_Api::_()->user()->getViewer()->getIdentity();

A: Create an instance of User_Model_User, let's say user and call it's method, e.g. $user.getIdentity()
As simple as your question.


text:
Q: Get IP or MAC addresses of Windows Multipoint Server 2012 stations? Is it possible to programmatically retrieve the IP or MAC address of a station assigned to a Windows MultiPoint Server 2012 host, using PowerShell or any other .NET or Windows API?
Background: I'm developing a application to help set up USB-over-Ethernet zero clients in a WMS 2012 setup, bridging the PowerShell "WmsCmdlets" module (Microsoft.WindowsServerSolutions.MultipointServer.PowerShell.Commands.Library.WmsStation) and a third-party vendor API for configuring zero client IP address, etc. So far, I do not know any means of matching up the "stations" of the WmsCmdlets with the zero client objects in the vendor's API.
Finding out the IP or MAC associated with a WMS station would do nicely, since I have this on the zero client API side. However, I haven't found any information I could use in the PowerShell WmsCmdlets module, such as Get-WmsStation which returns the following:
Id                         : 1
Name                       : <my station name>
IsAutoLogOn                : False
IsSplit                    : False
CollabId                   : 0
RemoteConnectionServerName :
VirtualMachineName         :
VirtualMachineId           :
AutoLogOnUserName          :
AutoLogOnPassword          :
DeviceTypes                : {DT_Mouse, DT_Keyboard, DT_Audio, DT_MassStorage...}
DeviceCounts               : {2, 2, 0, 0...}
ComputerName               : <my WMS host server name>
SessionId                  : 4294967295
SessionHostServer          : <my WMS host server name>

A: Not sure how to find the IPs of other clients, but we found a major bug when you turn on the feature for each station to get a virtual IP. The second someone logs in, our DNS changes the host computer name to use that new IP, even though its IP hasn't changed. This then makes it so that RDP and remote Dashboard no longer works with the host name (the original IP of the host still works).
We had to create a special service that looks for this every few seconds and fixes our DNS server. Kind of a pain that we had to do this, but beware. Microsoft says they're going to add a patch to fix IP issues, but I'm not sure if it'll fix this particular issue.

A: Take a look in the registry under
HKLM\software\microsoft\windows multipoint server\stations
You have what looks live a list of station Ids with the corresponding MAC address of the client as part of the stationhub path


text:
Q: From a list of lists of integer, choose a minimal length list of integers that intersects each sublist I have this list of lists of integers between 1 and 255.
data = Uncompress@"1:[encoded data, 17440 characters]"

Is there any efficient method to obtain one (not all) minimal length list L such that:
Union[Intersection[#, L] =!= {} & /@ data] === True

It's known that there exist one, because the sublists are non-empty.
Example
data = {{1,2}, {2, 3}, {3, 4}};

Note that the intersection of data is empty. For this set, one possibility is:
L = {2, 4};

Check:
Union[Intersection[#, L]=!={}& /@ data]

{True}

A: Here is another implementation of @FalafelPita's algorithm:
greedy[sets_] := Module[{s = First @ Commonest @ Flatten @ sets},
    Sow[s];
    greedy[Cases[sets, x_ /; FreeQ[x,s]]]
]
greedy[{}] := Null

minset[sets_] := Reap[greedy[sets]][[-1,1]]

For your data set:
res = minset[data]

{36, 17, 8, 10, 35, 44}

Check:
Min[Length[Intersection[res, #]]& /@ data]

1

I don't think this algorithm is guaranteed to find a minimal set, but I can only think of a brute force method to check, and in this case I expect that such a method would take more than 400 hours. I did modify the greedy function to randomize the commonest element it picks, but over a run of 10^4 trials, the minimal set always contained 6 elements. So, perhaps 6 is the length of the minimal set?

A: Here's one approach for finding such a set. It begins by counting the number of sets in which each element appears. Then, (one of) the most frequently appearing element(s) is Sown, and all sets that contained that element are removed from the list of remaining sets. This process continues until all sets have been removed, and then the list of Sown elements is returned.
findSmallSet[data_] := Module[
  {nSets, remainingSets, remainingElements, common},

  nSets = Length[data];
  remainingSets = DeleteDuplicates[data];
  Reap[
    While[nSets > 0,
      remainingElements = Flatten[remainingSets];
      common = Commonest[remainingElements];
      If[ListQ[common], common = First[common]];
      Sow[common];
      remainingSets =
       DeleteCases[remainingSets, _?(MemberQ[#, common] &)];
      nSets = Length[remainingSets];
      ];
    ][[2, 1]]
  ]

Older Solution
The first solution I posted was a bit less efficient because it discarded frequencies to create a list of unique elements, but then calculated frequencies later.
freqCounts[elementsList_, sets_] :=
  Function[element, Count[sets, _?(MemberQ[#, element] &)]] /@
   elementsList;

findSmallSet[data_] := Module[
  {nSets, remainingSets, remainingElements, frequentElement,
   freqElemPos},

  nSets = Length[data];
  remainingSets = DeleteDuplicates[data];
  remainingElements = DeleteDuplicates[Flatten[data]];
  Reap[
    While[nSets > 0,
      freqElemPos =
       Position[#, Max[#]] &[
        freqCounts[remainingElements, remainingSets]];
      If[ListQ[freqElemPos], freqElemPos = First[freqElemPos]];
      Sow[frequentElement = Extract[remainingElements, freqElemPos]];
      remainingSets =
       DeleteCases[remainingSets, _?(MemberQ[#, frequentElement] &)];
      remainingElements = DeleteDuplicates[Flatten[remainingSets]];
      nSets = Length[remainingSets];
      ];
    ][[2, 1]]
  ]

A: LinearProgramming
By enumerating your lists and associating each element of Union @@ data with set of indices of lists that contain this element, you can translate this problem to a "minimum set cover problem". You're looking for minimal number of sets of indices such that their union gives set of all indices. "Minimal set cover problems" can be formulated as "integer linear programs" that in Mathematica can be solved by LinearProgramming function.
In this case we are looking for vector $x$ of $k = 255$ zeros or ones such that $x_i$ is $1$ when $i$ is in our result set and $0$ if it isn't. So we want to minimize $\sum_{i=1}^k x_i$, in other words c.x with $c$ being vector of ones. So c = ConstantArray[1, k] should be used as first argument of LinearProgramming.
Our first constrain is that for each list from data, number of its elements present in result should be at least $1$ which can be written as m.x >= b with $b$ being vector of ones b = ConstantArray[1, n], $n$ being number of lists n = Length@data, and $m$ being $n \times k$ matrix such that each row corresponds to list from data and has $1$ at positions associated with elements present in list and $0$ at positions associated with elements not present in list. This m should be used as second -, and b as third argument of LinearProgramming.
Second constrain is that for each $i$: $x_i \in \{0, 1\}$. Which can be communicated to Mathematica by using ConstantArray[{0, 1}, k] as fourth argument of LinearProgramming and restricting domain (fifth argument) to Integers.
Putting it together we get:
n = Length@data;
k = 255;
m = ConstantArray[0, {n, k}];
MapIndexed[(m[[First@#2, #1]] = 1) &, data];
(x = LinearProgramming[ConstantArray[1, k], m, ConstantArray[1, n], ConstantArray[{0, 1}, k], Integers]) // MaxMemoryUsed // AbsoluteTiming
res = Flatten@Position[x, 1, {1}, Heads -> False]
(* LinearProgramming::lpip: Warning: integer linear programming will use a machine-precision approximation of the inputs. *)
(* {464.846, 1107448} *)
(* {9, 15, 48, 58, 122} *)

In less than 8 minutes we get result set containing 5 elements: {9, 15, 48, 58, 122}.
Let's check that this is a correct answer:
And @@ (IntersectingQ[res, #] & /@ data)
(* True *)

Random Searches
You could try to search for minimal sets using algorithm similar to one used in other answers but with some randomization added.
We start by defining fast compiled function rejecting sets containing chosen element:
selectNonContaining = Compile[{{searchMatrix, _Integer, 2}, {remaining, _Integer, 1}, {chosen, _Integer}},
  With[{result = Internal`Bag@Most@{0}},
    Do[
      If[Compile`GetElement[searchMatrix, i, chosen] === 0,
        Internal`StuffBag[result, i]
      ],
      {i, remaining}
    ];
    Internal`BagPart[result, All]
  ],
  RuntimeOptions -> "Speed", CompilationTarget -> "C"
];

Final minset function accepting arbitrary function choiceFunc selecting element from all elements of remaining sets.
minset // ClearAll
minset[choiceFunc_, data_, searchMatrix_, indices_] :=
  Module[{remaining = indices, result = {}, chosen},
    While[remaining =!= {},
      chosen = choiceFunc[Join @@ data[[remaining]]];
      result = {result, chosen};
      remaining = selectNonContaining[searchMatrix, remaining, chosen]
    ];
    Flatten@result
  ]

Prepare auxiliary data useful for fast searching:
packedData = Developer`ToPackedArray /@ data;
n = Length@data;
searchMatrix = ConstantArray[0, {n, Max@packedData}];
MapIndexed[(searchMatrix[[First@#2, #1]] = 1) &, data];
indices = Range@n;

With First@*Commonest choice function we recreate greedy algorithm from other answers:
minset[First@*Commonest, packedData, searchMatrix, indices] // RepeatedTiming
(* {0.00035, {36, 17, 8, 10, 35, 44}} *)

As noted in Carl Woll`s answer, instead of first commonest element we can choose random commonest element:
(results = Table[minset[RandomChoice@*Commonest, packedData, searchMatrix, indices], 10^4]) // MaxMemoryUsed // AbsoluteTiming
KeySort@Counts[Length /@ results]
(* {3.51511, 1176080} *)
(* <|6 -> 10000|> *)

But we get only 6-element sets, so it seems that it's highly unlikely for greedy algorithm to find smaller set on this data.
Instead of commonest element we could simply pick random remaining element:
(results = Table[minset[RandomChoice, packedData, searchMatrix, indices], 10^4]) // MaxMemoryUsed // AbsoluteTiming
KeySort@Counts[Length /@ results]
Select[results, Length@# === 5 &]
Function[res, And @@ (IntersectingQ[res, #] & /@ data)] /@ %
(* {1.42398, 1410688} *)
(* <|5 -> 2, 6 -> 43, 7 -> 554, 8 -> 2419, 9 -> 3608, 10 -> 2385, 11 -> 768, 12 -> 189, 13 -> 27, 14 -> 4, 15 -> 1|> *)
(* {{123, 110, 14, 79, 124}, {44, 109, 115, 24, 116}} *)
(* {True, True} *)

In less than one and half second I've found two 5-element sets.
I got best result by balancing greed and randomness, by randomly choosing between random element and random commonest element in each step:
(results = Table[minset[RandomChoice[{RandomChoice@*Commonest, RandomChoice}]@# &, packedData, searchMatrix, indices], 10^4]) // MaxMemoryUsed // AbsoluteTiming
KeySort@Counts[Length /@ results]
Select[results, Length@# === 5 &]
Function[res, And @@ (IntersectingQ[res, #] & /@ data)] /@ %
(* {2.89473, 1263376} *)
(* <|5 -> 36, 6 -> 2852, 7 -> 4073, 8 -> 2359, 9 -> 590, 10 -> 83, 11 -> 7|> *)
(* {{43, 90, 13, 85, 62}, {11, 87, 97, 91, 122}, {92, 76, 126, 101, 2}, {18, 116, 19, 29, 49},
    {47, 84, 49, 58, 48}, {48, 21, 23, 22, 12}, {103, 19, 28, 116, 82}, {101, 37, 105, 66, 46},
    {114, 111, 61, 120, 87}, {103, 40, 113, 93, 122}, {43, 20, 23, 33, 28}, {82, 92, 99, 98, 63},
    {72, 68, 6, 47, 81}, {75, 69, 29, 97, 101}, {42, 37, 40, 84, 72}, {48, 36, 40, 75, 51},
    {124, 37, 105, 59, 126}, {116, 27, 101, 28, 19}, {45, 53, 55, 18, 38}, {6, 12, 15, 106, 81},
    {29, 78, 13, 27, 115}, {95, 31, 11, 15, 96}, {103, 61, 68, 65, 43}, {22, 94, 12, 91, 20},
    {59, 115, 124, 79, 77}, {31, 121, 101, 29, 112}, {78, 109, 59, 57, 68}, {100, 115, 45, 51, 97},
    {78, 105, 97, 103, 28}, {88, 103, 102, 92, 14}, {76, 78, 95, 72, 11}, {117, 51, 118, 91, 102},
    {123, 7, 16, 93, 17}, {7, 5, 14, 114, 45}, {112, 71, 76, 16, 28}, {36, 96, 40, 19, 1}} *)
(* {True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True,
    True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True} *)

This method found 36 5-element sets in less than three seconds.
Automating Random Search
We can automate random searching function, making it repeat search until it reaches certain specified length of result, or runs out of given time.
minsetRepeated // ClearAll
minsetRepeated // Options = {
  "ChoiceFunction" -> (RandomChoice[{RandomChoice@*Commonest, RandomChoice}]@#&),
  "LengthGoal" -> 1, TimeConstraint -> 1
};
minsetRepeated[data_, OptionsPattern[]] := Module[
  {packedData, n, k, result, lengthGoal, choiceFunc, indices, searchMatrix},
  packedData = DeleteDuplicates[Developer`ToPackedArray /@ data];
  k = Max@packedData;
  result = Range@k;
  TimeConstrained[
    {lengthGoal, choiceFunc} = OptionValue@{"LengthGoal", "ChoiceFunction"};
    n = Length@data;
    indices = Range@n;
    searchMatrix = ConstantArray[0, {n, k}];
    MapIndexed[(searchMatrix[[First@#2, #1]] = 1)&, data];
    While[Length@result > lengthGoal,
      Module[{remaining = indices, bag = Internal`Bag@{}, chosen},
        While[Internal`BagLength@bag < Length@result && remaining =!= {},
          chosen = choiceFunc[Join @@ packedData[[remaining]]];
          Internal`StuffBag[bag, chosen];
          remaining = selectNonContaining[searchMatrix, remaining, chosen]
        ];
        If[Internal`BagLength@bag < Length@result, result = Internal`BagPart[bag, All]]
      ]
    ],
    OptionValue@TimeConstraint
  ];
  Sort@result
]

Default TimeConstraint is one second, so it'll give best result it could find in one second:
SeedRandom@0
minsetRepeated@data
(* {24, 44, 53, 116, 117} *)

Which, as we can see, is enough to find 5-element set.
We can also set specific "LengthGoal", so that function will stop immediately after finding set with given Length:
SeedRandom@0
minsetRepeated[data, "LengthGoal" -> 5] // AbsoluteTiming
(* {0.005669, {24, 44, 53, 116, 117}} *)

Finding first 5-element set took less than six milliseconds.
While it's possible for this random search to find minimal set very fast, it can't guarantee that it actually is set with minimal length.


text:
Q: Execute Task.Run() in ASP.NET ActionResult without waiting for result Below is the function where I am trying to execute a function in the background and then carry on without waiting for a result from it.
When debugging the task itself is executed but the actual function within it does not. The rest of the code then carries on like normal.
What could be the issue as there is no error produced after that to indicate otherwise?
This is on a page load.
public ActionResult ExceptionReport(int? id)
{
    var ExceptionList = db.Invoices.Where(m => m.ExceptionFlag == true && m.GlobalInvoiceID == id);

    if (ExceptionList.Count() == 0)
    {

        globalInvoice.Status = "Exception Verification";
        db.Entry(globalInvoice).State = EntityState.Modified;
        db.SaveChanges();

        Task.Run(() => ExceptionFinalTests(globalInvoice)); //Function To run in the background

        TempData["warning"] = "Verifying all exceptions fixed. A notification will be sent when the verifications are complete.";
        return RedirectToAction("Index", "GlobalInvoices");
    }

    return View(ExceptionList);
}

   private void ExceptionFinalTests(GlobalInvoice globalInvoice)
    {
        RunTests(globalInvoice, true);

        decimal TotalPaymentAmount = db.Invoices.Where(m => m.GlobalInvoiceID == globalInvoice.Id).Sum(m => m.Invoice_Amount) ?? 0;
        }

        GlobalInvoicesController globalInvoicesController = new GlobalInvoicesController();

        var ApproverList = globalInvoicesController.GetUserEmailsInRole(globalInvoice, "Reviewer");

        globalInvoicesController.Dispose();

        var exceptionExistCompulsoryTest = db.Invoices.Where(m => m.ExceptionFlag == true && m.GlobalInvoiceID == globalInvoice.Id);

        if (exceptionExistCompulsoryTest.Count() > 0)
        {
            try
            {
                string baseUrl = ConfigurationManager.AppSettings["site"];

                EmailExtension emailExtension = new EmailExtension();

                foreach (var approver in ApproverList)
                {
                    string approvalLink = baseUrl + "/Invoices/ExceptionReport/" + globalInvoice.Id;

                    StringBuilder mailbody = new StringBuilder();
                    mailbody.AppendFormat("Hi
");
                    mailbody.AppendFormat("There are " + exceptionExistCompulsoryTest.Count() + " exceptions for invoice #" + globalInvoice.Id + "that need attention before proceeding. - Click Here

");

                    mailbody.AppendFormat("Exception Count: {0}
", exceptionExistCompulsoryTest.Count());
                    mailbody.AppendFormat("Invoice Amount: {0}
", TotalPaymentAmount.ToString("C"));
                    mailbody.AppendFormat("Reviewed By: {0}
", "");
                    mailbody.AppendFormat("Approved By: {0}
", "");

                    EmailVM emailVM = new EmailVM()
                    {
                        Subject = "Invoice - #" + globalInvoice.Id,
                        EmailAddress = approver,
                        Message = mailbody.ToString()
                    };

                    emailExtension.SendEmail(emailVM);
                }
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog(ex.Message);
                LogWriter.WriteLog(ex.StackTrace);
            }
        }
    }

    private void RunTests(GlobalInvoice globalInvoice, bool retestFlag = false)
    {

        List<Invoice> invoices;
        var vendorTests = globalInvoice.Vendor.VendorTests;
        string[] testsToRun = vendorTests.Split(',');

        if (retestFlag == true)
        {
            if (globalInvoice.Vendor.VendorHasHierarchy == true)
            {
                testsToRun = new string[] { "Account Number", "Hierarchy" };
            }
            else
            {
                testsToRun = new string[] { "Account Number" };
            }
        }

            using (var context = new MyContext())
            {
                invoices = context.Invoices.Where(m => m.GlobalInvoiceID == globalInvoiceToTestID).ToList();
            }

        foreach (var test in testsToRun)
        {
            if (test == "Account Number")
            {
                LogWriter.WriteLog("Starting Account Number Check : Invoice Batch ID - " + globalInvoice.Id);
                AccountNumberCheck(invoices, globalInvoice.VendorID);
                LogWriter.WriteLog("Account Number Check Complete : Invoice Batch ID - " + globalInvoice.Id);
            }
            if (test == "Hierarchy")
            {
                LogWriter.WriteLog("Starting Hierarchy Check : Invoice Batch ID - " + globalInvoice.Id);
                BillingHierarchyCheck(invoices);
                LogWriter.WriteLog("Hierarchy Check Complete : Invoice Batch ID - " + globalInvoice.Id);
            }
        }
    }


text:
Q: What is the correct way to structure a module directory so that the Sphinx extension autodoc can access all files found using sphinx-apidoc? I'm trying to make documentation using Sphinx for a module which I've recently started creating. How do I organise my code so that both autodoc and python can read it properly?
I have the following file structure in which inference.py imports a Class from create_data.py:
[meg_analysis]
  |
  |-[docs]
  |    |
  |    |-{files created by apidoc}
  |
  |-create_data.py
  |-inference.py

sphinx-apidoc creates a file called meg_analysis.rst which contains ReST directives including:
.. automodule:: meg_analysis.inference
   :members:
   :undoc-members:
   :show-inheritance:

When I run make html, I get this message:
WARNING: autodoc: failed to import module 'inference' from module 'meg_analysis'; the following exception was raised:
No module named 'create_data'

I can fix this error by changing the import statement from from create_data import SimulatedData to from meg_analysis.create_data import SimulatedData.
The issue is then that now when I run python inference.py I get ModuleNotFoundError: No module named 'meg_analysis' and PyCharm starts underlining all of its uses in red.
Is there a way that I can get autodoc to successfully document all of my files without having to include a module-level import every time I want to use something from another part of the module? Am I structuring my code wrongly in some fundamental way?

A: Adding both the project directory and the directory above fixed the issue.
In the conf.py file created by sphinx-quickstart, add the lines
import sys
sys.path.insert(0, '/Users/{USER_NAME}/PycharmProjects/')
sys.path.insert(0, '/Users/{USER_NAME}/PycharmProjects/meg_analysis/')

Not sure if this is the best solution, but it seems to work.


text:
Q: How Coalesce function deals with datatype I am new to COALESCE function in REDSHIFT. I ran below four queries in mysql and Redshift.
1st and 2nd query executed as expected in both mysql and redshift. But for 3rd and 4th query I am getting two different results in mysql and Redshift. How does this behave?

*

*select COALESCE(null,null,1) -> 1

*select COALESCE(null,null,'John') -> 1

*select COALESCE(null,null,1,'John') -> (Redshift : error , mysql:1)

*select COALESCE(null,null,'John',1)    -> (Redshift: error, mysql:John)
Also this query should give error in mysql but it has succeeded
Any help is appreciated

A: Amazon Redshift Database Developer Guide claims:

An NVL expression is identical to a COALESCE expression. NVL and
  COALESCE are synonyms.
Syntax
NVL | COALESCE ( expression, expression, ... )

An NVL or COALESCE expression returns the value of the first expression
  in the list that is not null. If all expressions are null, the result
  is null. When a non-null value is found, the remaining expressions in
  the list are not evaluated.
This type of expression is useful when you want to return a backup
  value for something when the preferred value is missing or null. For
  example, a query might return one of three phone numbers (cell, home,
  or work, in that order), whichever is found first in the table (not
  null).

If you obtain the error this may mean that the returned value datatype do not match the datatype of recordset field or any another structure which must accept the returned value.
PS. Will you show error messages?

A: Though it is not written in the documentation, but coalesce works on the compatible data types. Integer and varchar cannot be compared.
The error becomes more evident when you provide column name instead of hard-code values. Try executing this:
select coalesce(integer_column, varchar_column) from a_table;

You would get an error saying something like this:

coalesce types integer and varchar cannot be matched.


text:
Q: How to grab all attachments [video, images] from a post and display in a UL in template I wrote some code that displays all attachment images in a UL to sidescroll on a custom post type.  client now wants video returned too. Right now, I'm using a regex to parse all the images from the post but it's not grabbing video. Also, I hate depending on regex as it is impossible to also grab url etc with present implementation.
Is there a way to grab all attachments associated with a post (not including the custom-field-thumbnail), and then populate the attachments in a  element on the page?

A: This would call all your attachment types - just add extra statements for other mime types (png, gif etc.)
    <?php
$thumb_ID = get_post_thumbnail_id( $post->ID );
$attachments = get_posts(array(
        'post_parent' => $post->ID,
        'post_type' => 'attachment',
        'numberposts' => -1,
        'orderby'        => 'title',
        'order'           => 'ASC',
        'exclude' => $thumb_ID,
    ));

if ( $attachments ) {
foreach( $attachments as $attachment ) {
    $attachment_mime = wp_check_filetype(wp_get_attachment_url($attachment->ID) );
            $title = apply_filters( 'the_title' , $attachment->post_title );
            if ( $attachment_mime['type'] == 'image/jpeg') {echo '
ID ) . '" alt="'.$title.'"  />
'; }
            elseif( $attachment_mime['type'] == 'video/mp4'){echo '
<video class="video-js vjs-default-skin" controls data-setup="{}"><source src="'.wp_get_attachment_url( $attachment->ID ).'" type="video/mp4" /></video>
';}
}
}?>


text:
Q: Combining functions to produce a desired integer output I'm not sure if this question belongs on stackoverflow or math, but I'll give stackoverflow a shot.
I'm attempting to create an algorithm / function that will allow me to solve a puzzle, but I am simply unable to. The puzzle is as stated.

*

*Let a unit be a function that accepts a integer i between 0 and 15.

*A unit can add or subtract any number in the range 0 - 15 to/from i.

*Additionally, instead of adding or subtracting a number to/from i, a unit can also contain a number from 0-15 and subtract i from that.

*A unit can only perform 2 operations on a number, and the operation producing the largest value will be the output of the unit.

*Values only go from 0 - 15, so 9 - 15 = 0 and 13 + 5 = 15.

*We may combine units together to produce a more complex result.
The first unit may only accept numbers ranging from 0 - 9.

*In my examples I will string together 3 units.

This is a problem that is unrelated to coding, but it seems that I need a program to figure out possible solutions. I've attempted to create a brute force algorithm to find solutions, but I've been unable to do so, as I'm not that great with coding.
For example, a problem could be:
For values 1 and 4, let the output be 0. For all others, e.g. 0, 2, 3, 5, 6, 7, 8, 9, the output must be greater than 0.
A solution here might be:
def unit1(input):
    return max(5 - input, input)

def unit2(input):
    max(14 - input, input)

def unit3(input):
    max(10 - input, input - 10)

print(unit3(unit2(unit1(4))))

Another example might be:
For values 4, 5, 6 and 8 the output must be 3 or greater. For all others, e.g. 0, 1, 2, 3, 7, 9, the output must be less than 3.
A solution here might be:
def unit1(input):
    return max(4 - input, input - 4)

def unit2(input):
    max(2, input)

def unit3(input):
    max(1 - input, input - 6)

print(unit3(unit2(unit1(5))))

Given an example as the two stated above, is there a general algorithm / formula I can use to find my desired output?
Additionally, is it possible to solve the problems above using only 2 units?
Please do let me know if I need to elaborate on something, and know that your help is extremely appreciated!

A: There seems to be basically two kinds of things you have to do:  map inputs that should be handled the same way to contiguous ranges, and then move contiguous ranges to the right place.
max(A-x,x-B) is the only kind of unit that can map non-contiguous ranges together.  It has limitations:  It always maps 2 inputs onto one output, and you've gotta be careful never to map two inputs that have to be handled differently onto the same output.
In terms of what gets mapped together, you only need one parameter, since max(x,A-x) handles all cases.  You can try all 16 possibilities to see if any of them help.   Sometimes you may need to do a saturating add before the max to collapse inputs at the top or bottom of the range.
In your first example, you need to map 0 and 4 together.
In max(x,A-x), we need 4 = A-1.
Solving that we get A=5, so we start with
max(x, 5-x)

That maps 4 and 1 to 4, and everything else to other values.
Now we need to combine the ranges above and below 4.  Everything less than 4 has to map to something higher than 4.  We solve 5 = A-3 to get A = 8:
max(x, 8-x)

Now the ranges of things that need to be handled the same way are contiguous, so we just need to move them to the right place.  We have values >=4 and we need 4->0.  We could add a subtraction unit, but it's shorter just to shift the previous max by subtracting 4 from both cases.  We're left with a final solution
max(x, 5-x)
max(x-4, 4-x)

You haven't really defined all the possible questions you might be asked, but it looks like they can all be solved by this two step combine-and-shift process.  Sometimes there will be no solution because you can't combine ranges in any valid way with max.

A: I think your missing piece you need to proceed is a higher-order function. That's a function that returns another function. Something like:
def createUnit(sub, add):
    def unit(input):
        return max(sub - input, input + add)
    return unit

You can use it like:
unit1 = createUnit(5, 0)
unit2 = createUnit(14, 0)
unit3 = createUnit(10, -10)

Your first example can be solved with two units, but your second example can't.
I think the key to solving this efficiently is to work backwards from the output to the input, but I haven't spent enough time on it to figure out precisely how to do so.


text:
Q: Restore the UI-state after recreating the fragment How can I restore the UI status of my Fragment-A after I have replaced it with Fragment-B and then call Fragment-A again?

A: You could use SharedViewModel between these two fragments and store the state there.
Share data between fragments with SharedViewModel


text:
Q: Get "ALL" value in selectinput to plot with multi-filters (shiny) I would like to get a reactive plot with multiple filters and an initial minimal plot with the number of ALL diagnostics by month.
The aim requires 4 filters AND a scale of period (display data by week,month ..).
I tried but not it's not working on the step to sum data (ALL).
If you have a suggestion I am open .
Thank you  :)
library(shiny)
library(ggplot2)
library(dplyr)

#data
data.hosp <- data.frame(stringsAsFactors=FALSE,
                    id= c(1,2,3,4,5),
                  Annee = c(2018, 2018, 2018, 2018, 2018),
                  Mois = c("2018-01","2018-01","2018-02","2018-03","2018-03"),
                  Semaine = c("2018-001","2018-003","2018-008","2018-011","2018-013"),
                  uf= c("A3352","Z6687", "A3352", "A3352", "Z6687"),
                  um= c(3350,6687, 3352, 3350, 6687),
                  ghm= c("AAAAA","DFFDF","DDFDA","AZEEA","DDFDA"),
                  diag= c("A","A","C","Z","R"),
                  nb=c(1,3,1,1,10))

  ui <- fluidPage(
          titlePanel("Plot with filters"),

        fluidRow(
          column(2,
                 selectInput(inputId = "sel_uf",
                             label = "UF",
                             choices = as.character(unique(data.hosp$uf)),
                             multiple=TRUE,
                             width = validateCssUnit(200))),
           column(2,
                 selectInput(inputId = "sel_um",
                             label = "UM",
                             choices = as.character(unique(data.hosp$um)),
                             multiple=TRUE,
                             width = validateCssUnit(200))),
          column(3,
                 selectInput(inputId = "sel_ghm",
                             label = "GHM",
                             choices =as.character(unique(data.hosp$ghm)),
                             multiple=TRUE,
                             width = validateCssUnit(200))),
          column(3,
                 selectInput(inputId = "sel_diag",
                             label = "Diagnostic",
                             choices =c('Tous', as.character(unique(data.hosp$diag))),
                             multiple=TRUE,
                             width = validateCssUnit(250))),
          column(4,  selectInput("periodec",
                      label="Affichage par :",
                      choices = c("Semaine"= "Semaine",
                                "Mois"   = "Mois",
                                "Année"  = "Annee"),
                    selected   = "Mois" ) ),

          plotOutput("graph1", height=300 )
))

server <- function(input, output) {

  #Period filter (display by :)
  periode <- reactive({
    ifelse(input$periodec=="Semaine", "Semaine",
    ifelse(input$periodec=="Mois", "Mois",
    ifelse(input$periodec=="Année", "Annee")))     })

  # Data filters
  df_dat <- reactive({
    df_dat  <- data.hosp

  #code to get "ALL" in selectsizeInput
    if ('Tous' %in% input$sel_diag) { sel_diag <- unique(data.hosp$diag)
    } else {
      data.hosp <- data.hosp %>% filter(nb == input$sel_diag)
      nb <- unique(data.hosp$nb) }

    if (!is.null(input$sel_um)) {
      df_dat  <- df_dat  %>% filter(um == input$sel_um)   %>% group_by_(periode()) %>% summarise(sum_active = sum(nb))}
    if (!is.null(input$sel_uf)) {
      df_dat  <- df_dat  %>% filter(uf == input$sel_uf)   %>% group_by_(periode()) %>% summarise(sum_active = sum(nb))}
    if (!is.null(input$sel_ghm)) {
      df_dat  <- df_dat  %>% filter(ghm == input$sel_ghm)   %>% group_by_(periode()) %>% summarise(sum_active = sum(nb)) }
    if (!is.null(input$sel_diag)) {
      df_dat  <- df_dat  %>% filter(diag == input$sel_diag)   %>% group_by_(periode()) %>% summarise(sum_active = sum(nb)) }
    return(df_dat)
  })

  # Ensures that our filter works properly
  observe(print(str(df_dat())))
  # graph
  output$graph1 <- renderPlot({
    req(df_dat())
    ggplot(df_dat(), aes_string(x =periode(), y = "sum_active",  group = factor(periode() ))) +
             geom_bar(aes_string(periode(), "sum_active"), stat = "identity", fill="steelblue")
  })
}
shinyApp(ui,server)

A: Maybe this is what you are looking for. In my opinion the main issue is that your approach was overly complicated. (;

*

*My approach sets all filters first. If NULL (and/or 'Tous') the "selection" is set to all categories of a variable, otherwise only the chosen ones are included.

*Doing so you only need one pipe to filter and summarise the data

*There is no need for the observe statement which I dropped

*I fixed the req in the renderPlot to check wether the filtered data contains any rows. Otherwise ggplot will raise an error.
server <- function(input, output) {

  #Period filter (display by :)
  # While a nested ifelse works in the present case a better choice is using `if
  periode <- reactive({
    if (input$periodec == "Semaine") {
      "Semaine"
    } else if (input$periodec == "Mois") {
      "Mois"
    } else {
      "Annee"
    }
  })

  df_dat <- reactive({
    # First: Setup the filters. If NULL: all categories else: chosen ctaegories
    # In case of diag additionally check for "Tous"
    sel_diag <- if (is.null(input$sel_diag) | 'Tous' %in% input$sel_diag) unique(data.hosp$diag) else input$sel_diag
    sel_um <- if (is.null(input$sel_um)) unique(data.hosp$um) else input$sel_um
    sel_uf <- if (is.null(input$sel_uf)) unique(data.hosp$uf) else input$sel_uf
    sel_ghm <- if (is.null(input$sel_ghm)) unique(data.hosp$ghm) else input$sel_ghm

    # Filter the data and summarise
    data.hosp %>%
      filter(diag %in% sel_diag, um %in% sel_um, uf %in% sel_uf, ghm %in% sel_ghm) %>%
      group_by_(periode()) %>%
      summarise(sum_active = sum(nb), .groups = "drop")
  })

  # graph
  output$graph1 <- renderPlot({
    # Plot only if any data
    req(nrow(df_dat()) > 0)
    ggplot(df_dat(), aes_string(x = periode(), y = "sum_active",  group = factor(periode() ))) +
      geom_bar(aes_string(periode(), "sum_active"), stat = "identity", fill="steelblue")
  })
}


text:
Q: i5 540M or i7 720QM for laptop running VMs and software development tools? I'm a software developer that would primarily be running Windows 7 as the primary operating system.  On a typical day, I might, at any given moment, be running Visual Studio, Expression Web, SQL Server developer (and Management Console), IIS, Photoshop, a dozen browser tabs in 2-3 different browsers, Skype video chat, streaming music, and a couple of VMs (WinXP and Ubuntu) for testing/experimentation.
Obviously, RAM is a concern, which is why I plan to use 8 GB so I can devote enough to the VMs to be usable.  I'm also tempted to use an ExpressCard SSD for storing the VM disks to ease disk contention.  And I know that that is asking a lot from a laptop, and I should just use a desktop, but I need to be able to take my work with me between several locations.
It seems that at a reasonable price point, it comes down to the i5 540M versus the i7 720QM. I'm leaning toward the i7 since it would allow me to dedicate a whole hyperthreaded core to each VM, and still have two cores left for the primary OS.
I've heard that the i5 has better battery life, but I'm curious for my scenario if there would be a meaningful difference.  I don't usually work without a plug, but I do occasionally ride the train or fly and it would be nice to have at least 3 hours of juice for unusual circumstances.
And, finally, for this usage scenario, would a dedicated video option be preferred over the i5's integrated video?  It sounds like Visual Studio 2010 (and Windows 7) can take advantage of the video card.

A: if you go for i7 you would have no option but to get dedicated video card as i7 doesn't seem to have intel graphics.
i would anyway suggest you to get dedicated graphics as graphic card cannot be upgraded later(like ram or hard drive).
IMO get the i7 but be careful some laptops out there powered by i7 are facing heating issues.
so be smart while selecting a model....

A: The other two people have said contracdicting information about upgrading graphics - it is possible to upgrade, but I cannot give a certain answer - it depends if the laptop supports MXM or a similar card - however, I cannot advise upgrading. Typically, if it is not available as an option when you first buy the laptop, I wouldn't upgrade as it can (not always) lead to problems such as heat.
As for power, the Core I5 540m uses 35W and the Core I7 720QM uses 45W, however these are the maximum values, when idle - Windows 7 (hopefully you will be using it!) will take advantage of certain advanced features such as core parking and they should use an almost identical amount of power, meaning that the core I7 will only need the additional power when you are doing complex / big tasks.
As for what to recommend, if they are similar prices and you are anything like me, I need a laptop for portability and to take to clients, but EVERYWHERE I go has a plug! Even most long distance trains have a plug, but even without it, with power saving modes and low back light, I can still get a good 2 hours. Based on this, I would go with the I7!


text:
Q: NSubstitute ForPartsOf calling concrete implementation event when substituted I have the following class:
public class MyClass : IMyClass
{
    public string MyFunc(string name)
    {
        if (string.IsNullOrWhiteSpace(name))
        {
            throw new Exception("Blank Name");
        }

        return name;
    }

    public double MyFuncWrapper(string name)
    {
        var value = MyFunc(name);

        return value;
    }

In trying to test it, I was under the impression that NSubstitute's ForPartsOf effectively subclassed my class and replaced the flagged methods; so I did this:
[Fact]
public void TestMyFuncWrapper()
{
    // Arrange
    var myClass = Substitute.ForPartsOf<MyClass>();
    myClass.MyFunc(Arg.Any<string>()).Returns("Test");

    // Act
    var result = myClass.MyFuncWrapper("");

    // Assert
    Assert.Equal("Test", result);
}

However, I get the exception raised from, what I understood to be, my substituted method.  Oddly, it appears that the following line:
myClass.MyFunc(Arg.Any<string>()).Returns("Test");

Is actually calling the concrete function immediately.  Looking here, it appeared that a construct like this may solve the problem (although it does use the phrase "playing it safe" which sounds quite vague):
myClass.When(a => a.MyFunc(Arg.Any<string>())).DoNotCallBase();

However, calling this actually invokes MyFunc immediately in the same way.  Clearly I'd misunderstood the ForPartsOf method; my question is: can I do what I'm attempting using NSubstitute, or do I need to resort to manually subclassing MyClass?

A: This is by design for NSubstitute (and for most mocking frameworks).
The docs state:

For starters, NSubstitute can only work with virtual members of the
  class, so any non-virtual code in the class will actually execute!

Thus, you need to add virtual to the function declarations you plan to mock.
Or (as per the docs):

If possible, stick to substituting interfaces.


text:
Q: Is there any way to implement numbered pagination instead of PREV | NEXT using JSOM without using search I'm wondering if there any way to implement Numbered pagination while retrieving items from a list like
"PREV 1,2,3..NEXT" instead of just having "prev | next". I followed this code example MSDN and the "paginationinfo" needs the item ID of the last item while moving to next page. So looks like there is no way to get numbered pagination. Even OOTB list-view web-parts using the same approach, we don't have 1,2,3.. there. I know that we can get it done using search API, but wondering if there is another way to do this by querying list directly. If not, I want to know the reason behind why SharePoint does not support this type of pagination.
Thanks


text:
Q: SWTBot: Press "F5" on project in package explorer I'm currently trying to press the F5 keybinding using SWTBot tests to refresh a project in the package explorer. So far, I have been unsuccessful.
When I attempt to press the F5 keybinding in a way such as this:
SWTBotView packageExplorer = getPackageExplorer();
SWTBotTree tree = packageExplorer.bot().tree();
SWTBotTreeItem treeItem = tree.getTreeItem("newProject");
treeItem.select();
treeItem.pressShortcut(0, SWT.F5, (char) 0);

I receive the following stack trace:
java.lang.ExceptionInInitializerError
at org.eclipse.swtbot.swt.finder.keyboard.Keyboard.pressShortcut(Keyboard.java:138)
at org.eclipse.swtbot.swt.finder.widgets.AbstractSWTBot.pressShortcut(AbstractSWTBot.java:862)
at org.eclipse.project.ui.wizard.project.RefreshUiTest.performDefaultEclipseRefresh(RefreshUiTest.java:43)
at org.eclipse.project.ui.wizard.project.RefreshUiTest.defaultEclipseBehaviourIsNotHindered(RefreshUiTest.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner.run(SWTBotJunit4ClassRunner.java:54)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.pde.internal.junit.runtime.RemotePluginTestRunner.main(RemotePluginTestRunner.java:62)
at org.eclipse.pde.internal.junit.runtime.PlatformUITestHarness$1.run(PlatformUITestHarness.java:47)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:3717)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3366)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1113)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:997)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:140)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:611)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:567)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
at org.eclipse.pde.internal.junit.runtime.NonUIThreadTestApplication.runApp(NonUIThreadTestApplication.java:54)
at org.eclipse.pde.internal.junit.runtime.UITestApplication.runApp(UITestApplication.java:47)
at org.eclipse.pde.internal.junit.runtime.NonUIThreadTestApplication.start(NonUIThreadTestApplication.java:48)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:354)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:181)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:636)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:591)
at org.eclipse.equinox.launcher.Main.run(Main.java:1450)
at org.eclipse.equinox.launcher.Main.main(Main.java:1426)
Caused by: java.lang.IllegalArgumentException: EN_CA.keyboard not found, see http://wiki.eclipse.org/SWTBot/Keyboard_Layouts for more information.
at org.eclipse.swtbot.swt.finder.keyboard.KeyboardLayout.getKeyboardLayout(KeyboardLayout.java:89)
at org.eclipse.swtbot.swt.finder.keyboard.KeyboardLayout.getDefaultKeyboardLayout(KeyboardLayout.java:75)
at org.eclipse.swtbot.swt.finder.keyboard.Keystrokes.<clinit>(Keystrokes.java:110)
... 61 more

I've also tried using:
Keyboard key = KeyboardFactory.getSWTKeyboard();
key.pressShortcut(Keystrokes.F5);

but it has failed with a nearly identical stacktrace.
How can I simulate pressing the F5 key on a project in the package explorer using SWTBot tests?

A: The root cause indicates that EN_CA.keyboard not found. SWTBot does not come with a predefined EN_CA keyboard layout.
If it fits your needs you can use the EN_US keyboard layout like this
SWTBotPreferences.KEYBOARD_LAYOUT = "EN_US";

Or define your own keyboard layout as desribed here: https://wiki.eclipse.org/SWTBot/Keyboard_Layouts


text:
Q: How to delay UI feedback when AppBarButton is touched in WP 8.1 I need to add delay (2000ms) to AppBarButton touch event before any kind of user feedback is shown by the UI. The highlight colour should appear after the delay, not before it. How this can be done in WP 8.1?

A: You will have to change the styles. I don't think you can delay the touchdown of a standard button, therefore you may have to use a RepeatButton.
<RepeatButton Style="{StaticResource RepeatButtonStyle1}" Delay="2000" Interval="100000" />

Then you can customize the style, and more specifically the Pressed VisualState storyboard:
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
    <DiscreteObjectKeyFrame KeyTime="2000" Value="{ThemeResource ButtonPressedForegroundThemeBrush}"/>
</ObjectAnimationUsingKeyFrames>

If you need it to be an AppBarButton, you may just change its style to delay the keyframe, however you would have to handle the 2s timer using the DispatcherTimer and be sure the button is still on pressed state, but you also have to reset the timer if the Release event is raised.


text:
Q: Basic web app saying "hello, world." I am watching one tutorial to get a basic web app saying "hello, world"
But for some reason I don't understand, I am getting this
"The localhost page isn't working
localhost is currently unable to handle this request."
This is what I did.
1. I installed Google App Engine SDK for python.
2. I created two files like this:
main.py
import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello, World!')

app = webapp2.WSGIApplication([
    ('/', MainPage),
], debug=True)

app.yaml
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: helloworld.app

I didnt write these. These were given in google app engine website.
and I tried two different methods to run it.

*

*Using terminal
in the folder where the two files are:

I used this command: dev_appserver.py .
and this is what I get:
INFO     2016-04-02 04:28:02,071 sdk_update_checker.py:229] Checking for updates to the SDK.
INFO     2016-04-02 04:28:02,949 sdk_update_checker.py:257] The SDK is up to date.
INFO     2016-04-02 04:28:02,982 api_server.py:205] Starting API server at: http://localhost:50345
INFO     2016-04-02 04:28:02,988 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
INFO     2016-04-02 04:28:02,989 admin_server.py:116] Starting admin server at: http://localhost:8000

and when I enter "http://localhost:8000" on chrome, I get this error msg:
"The localhost page isn't working
localhost is currently unable to handle this request."
and this is the error msg I get on terminal
ERROR    2016-04-02 04:43:47,109 wsgi.py:263]
Traceback (most recent call last):
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
ImportError: No module named helloworld
INFO     2016-04-02 04:43:47,114 module.py:787] default: "GET / HTTP/1.1" 500 -
ERROR    2016-04-02 04:43:47,602 wsgi.py:263]
Traceback (most recent call last):
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
ImportError: No module named helloworld
INFO     2016-04-02 04:43:47,606 module.py:787] default: "GET / HTTP/1.1" 500 -

*Using google app engine launcher
I created a new application and this gave me all the files I needed.
So I just ran it.
It shows me a port number, and when I tried that on chrome,
"http://localhost:8000"
I get the same error as the first msg.

What is it that I am doing wrong?
Thank you.

A: The issue you have is that you've  named your module main.py, but told the GAE server to look for a module named helloworld. That module doesn't exist, so the site can't be loaded.
Either rename your main.py file to helloworld.py, or change app.yaml to point to main.app instead of helloworld.app.

A: webapp2 doesnt have a good introduction. if you're new to web frameworks i would adivse you to start through this one.
https://github.com/iogf/untwisted
It is an event-driven library that has a set of plugins implemented and one of the is a micro web framework whose design is similar to flask but much faster.


text:
Q: PowerShell command lets for TFS2013 I am using TFS 2013. I have installed Power tools 2013 update 2 on my local machine.
I have tried to use this Add-PSSnapin : The Windows PowerShell snap-in 'microsoft.teamfoundation.powershell. on both the 32 and the 64 bit version of power shell and  I get the following error.
Add-PSSnapin : The Windows PowerShell snap-in 'microsoft.teamfoundation.powershell' is not installed on this machine.

I have tried to look and read through a few forums but in vain.
What am I missing?

A: I had to uninstall Power tools 2013 and re install to get the options that explained PowerTools cmdlets can be installed only if I installed Windows6.1-KB2506143-x64.msu.
Before that I had tried Repair multiple times but had not helped.


text:
Q: Check if Certificate Signature is MD5 OpenSSL I need to check if a X509 certificate's signature algorithm is MD5 or SHA. To do this I know I can extract the NID corresponding to the signature algorithm:
int sig_nid = OBJ_obj2nid(cert->sig_alg->algorithm);

Now the problem is that I can't seem to find an easy way to compare this against MD5 or SHA as I do believe multiple NIDs can be returned for a signature. Is there an easy way to compare this NID or a place where I could find all MD5 and SHA NIDs so that I could do a long comparison myself?

A: I think this is what you're after: http://www.alvestrand.no/objectid/1.2.840.113549.1.1.html It lists the hash/encryption available for X509 certificates. You can generate the nids you're comparing against using OBJ_txt2nid().
The so you want to compare the algorithm nid to OBJ_txt2nid("1.2.840.113549.1.1.4") - or in practice NID_md5WithRSAEncryption (defined in openssl/objects.h)
Edit:
Just to add some more info: The X509v3 RFC refers to other RFCs which define "acceptable" algorithms. These are RFC3279, RFC4055, and RFC4491. They all include OIDs which can be used. Only the first one seems to define schemes with MD5 hashing.


text:
Q: How to fetch remote file using Client Interface in java I have a file located remotely at url : www.something.com/abc.txt.
I want to fetch this remote file(abc.txt) and store it in InputStream or String object using 'Client' Interface.

A: This is very simple:
HttpClient client = new HttpClient();
String url = "http://www.example.com/README.txt";
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
byte[] responseBody = method.getResponseBody();
String fileContents = new String(responseBody);

Here is also a nice tutorial that can help you out
Hope that helps

A: You can do it this way:
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtil {

    public static void main(String... args) {

        CloseableHttpClient httpClient = HttpClients.custom().build();
        CloseableHttpResponse response = null;

        try {

            HttpGet httpGet = new HttpGet("http://txt2html.sourceforge.net/sample.txt");
            httpGet.setHeader("Content-Type", "text/plain");
            response = httpClient.execute(httpGet);

            String strValue = EntityUtils.toString(response.getEntity());
            System.out.println(strValue);

        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            IOUtils.closeQuietly(response);
            IOUtils.closeQuietly(httpClient);
        }

    }
}

Here are the dependencies.
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.2</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.3.1</version>
</dependency>
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>


text:
Q: How to retrieve a newly generated image in JSP using expression I have a class the creates a QR code and saves it in an folder in the project.
I have a servlet that calls this QR code creator class, inserts the file path of the qr code to a database, and stores the ResultSet of the qr codes into the request.
After successfully creating the qr codes and inserting the file paths into the database, the JSP queries these using expression and outputs them using a while loop, to output all the rows in the ResultSet.
However, I get an error 404 on the images. After inspecting the element in Chrome, the img src points to the already created qr code correctly. What am I missing here?
I can give additional information if need be.
Tomcat 7.0.23
Eclipse Juno
Java SE 7

A: SOLVED: I just need to refresh the folder containing the qr codes. After refreshing they are all displaying properly.


text:
Q: Parse Database not cleared on logout Android As the question says, I'm having a problem when logging out from parse. If I login to another account, the old data is still in the DB.
My question is, do I need to clear it manually ? I mean, calling ParseObject.unpinAll() ?
FYI, the app doesn't have the user annonymous enabled. (I think it's disabled by default, right ?)
What approach should I take?
Thanks

A: Well it turns out to be the solution I commented on the question, I call ParseObject.unpinAll() and it's good to go.
Thanks


text:
Q: Select Result from MySQL Database and Assign it to a Variable I am connecting to a MySQL database through a Python environment. I'm using pypyodbc as the connector. Everything works fine, I can Select and Insert results, etc.
The issue comes in when I attempt to actually assign results fetched from the database to a variable: It literally only works sometimes, and rarely.
Here's some code:
SQLCommand = ("SELECT TRIM(' ' FROM ColumnName) FROM MyDB.dbo.MyTable WHERE ColumnName='%s'" % (my_variable)
cursor.execute(SQLCommand)
print("Here is the result from the database ",  cursor.fetchone())

another_variable =  cursor.fetchone()
print("Here is the value from the database assigned to a variable: ", another_variable)

As you can see I attempt to assign the fetched result to a variable at:
another_variable =  cursor.fetchone()

The word I'm fetching will be in the database plain as day. Cursor.fetchone will fetch the result and print it every time. But it will only assign it to a variable sometimes. Rarely.
I'm baffled, is there some known issue doing this? Am I somehow missing anything? I need it to assign the result to the cursor everytime, not rarely.

A: First, you should be assigning an alias to your call to TRIM inside the query, e.g.
SELECT TRIM(' ' FROM ColumnName) AS val FROM MyAI_DB.dbo.MyDatabase ...

Then, to access a column/alias, you need to reference the row object returned by fetchone():
sql = "SELECT TRIM(' ' FROM ColumnName) AS val FROM MyAI_DB.dbo.MyDatabase " +
    "WHERE ColumnName = '%s'" % (my_variable)
cursor.execute(sql)
row = cursor.fetchone()
print print "%s" % (row["val"])


text:
Q: Show matplotlib plots in Ubuntu (Windows subsystem for Linux) - Python 3 I have followed the answer in the question linked below to the letter, and it works beautifully in Python 2, but I need this to work with Python 3 also. I can't seem to get matplotlib to play nicely in Python 3.
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)

And here is the output I get:
OMP: Error #100: Fatal system error detected.
OMP: System error #22: Invalid argument
[1]    5245 abort (core dumped)  python

Show matplotlib plots in Ubuntu (Windows subsystem for Linux)


text:
Q: How can I store and use an array of different types derived from a common base type? The title may need a bit of explanation, so here's what i'm trying to do:

*

*Common base type for UI elements, e.g. BasePanel

*More specialised elements can be defined, derived from BasePanel. For example, buttons and textboxes.

*A list of elements will be stored (of type BasePanel, so that specialised ones can be stored)

*This list will be looped through each frame and drawn (ignoring optimisation at the moment)

Example usage:
class UIButton : BasePanel
{
    public override void Draw(blah)
    {
        // Specialised drawing code
    }
}

foreach (BasePanel Element in StoredElements)
{
    Element.Draw(blah);
}

The problem with this is that it won't run the specialised code; it will just run the BasePanel code.
How can I improve this so that it will run the specialised code instead? Could I store the type of the element on the BasePanel, and then cast to it at runtime?
I've tried storing the BasePanel in a Container class which stores the original type, but I can't access the method - for example:
foreach(ElementContainer Container in StoredElements)
{
    Type t = Container.OriginalType;
    object el = Container.Element;

    Convert.ChangeType(el, t); //Can't use the returned object!

    t Element = (t)Convert.ChangeType(el, t); //This would be perfect, but it doesn't work.
}

Thanks for any help. This has made my brain explode.

A: It works 100% for me with the following code:
class BasePanel
{
    public virtual void Draw(string blah)
    {
        Console.WriteLine("Base: " + blah);
    }
}

class UIButton : BasePanel
{
    public override void Draw(string blah)
    {
        Console.WriteLine("UIButton: " + blah);
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<BasePanel> list = new List<BasePanel>();

        list.Add(new BasePanel());
        list.Add(new UIButton());
        list.Add(new BasePanel());
        list.Add(new UIButton());
        list.Add(new UIButton());

        foreach (var b in list)
        {
            b.Draw("just a string");
        }
    }
}

What is wrong with yours comes from your drawing code/logic.

A: it looks like your example should work, but you could try extracting the Draw method (and any others you need for polymorphism) into an Inerface, then implementing the interface in each of the classes you want in the list.

A: As DarkSquirrel stated, you can declare the parent class's functions as virtual. This should allow your code to run the specialized code

A: What specialized type are you trying to execute
if you have
class Bar {
  public virtual void Draw() {
    DO STUFF!
  }
}

class Foo : Bar {
  override public virtual Draw() {
    DO MORE STUFF!
  }
}

then somewhere in your code
Bar[] data = new Bar[] { new Foo(), new Bar()};
foreach (Bar elem in data) {
  elem.Draw();
}

The first elem will execute the overriden code in Foo for the first elem and the code in Bar for the second. Even if you cast an item down the code executed in the methods will still be the code in original object (and elem.GetType() will return Foo for a Foo type.


text:
Q: Add new row editable in ng-grid Angular I want to add a new row to my ng-grid that is the only enable to be edited. I can add a new row pushing a new object into the datasource of the grid.
I know that I can use cellEdit in the columnDefinitions object but I need that only the last row could be editable all the columns so if I press a button this last row is saved.
Any help or suggestions would be appreciated.


text:
Q: XCOPY Behavior copying between remote servers I am trying to determine the bandwidth usage of XCOPY when copying files between two remote servers.
I am on an XP workstation running a batch file (over a WLAN) which uses XCOPY to copy files from \\server1 to \\server2.
When this copy is run how much file data is actually going through the workstation?  Is the workstation actually reading and copying all of files between servers or is the actually copying of the files being handled at the network layer between the servers themselves?
Does Robocopy work the same way?

A: Data is transferred through your computer, by reading chunks from the source and writing them to destination. Remote-remote copy is a relatively rare operation and not worth the implementation complexity.

*

*Reachability: if client can reach both servers, it doesn't mean server A can reach server B directly.

*Compatibility: In Windows, UNC paths can point to SMB, WebDAV, old NetWare, and possibily other protocols. If both server connections use different protocols or variants, a direct connection can be complicated if not impossible.

*Security: Extending a file transfer protocol to add commands to establish connections to third-party servers can introduce security holes. See the FXP extension to FTP, and why no one uses it.

*Authentication: Server A does not have your credentials for server B. In typical SMB, the password is never transmitted in plain text, and what is transmitted cannot be sent further (delegation is only possible with Kerberos, which needs Active Directory or equivalent). And that's assuming both servers accept the same set of credentials... And having server A ask you for server B's password would be a Bad Thing.

Both XCOPY and Robocopy work the same way, since neither of them knows the difference between local and remote paths. File accesses from UNC paths are handled entirely by the Windows kernel itself.


text:
Q: If I reset all my skills, do I lose the bonuses from critical success in missions? Basically... I never really understood skills/I thought if I played long enough, I could max them all out.
I am annoyed at how I spent quite a few of my skill points and I have also had critical success in quite a few duty officer missions that have awarded skill points, some of which have are in skills I already maxed out - so are pretty useless.
I was just wondering, if I get a respec/reskill/reset token and use it, do all of the skills that I have won stats in also reset to 0, or do I keep critical success skill buffs?
(Side question - if I loose them (or even if I don't), is there a complete list of every possible win from missions so that I know not to spend skill points in them, as give enough time, I should fill them from missions?)

A: Well, looks like I got this wrong - I assumed it was a permanent skill point, but, it looks like you only get temporary buffs from critical missions - so, my problem isn't really an issue at all.
I will respec and just be more careful where I spend points.