text:
Q: In Smalltalk, how to select both strings and integers from an array Using Pharo, I have a collection e.g.
array := #('up' '4' 'b').

and I'd like to use select: to create a collection that only includes the numbers, provided they're smaller than 20, and a specific string - in this case, 'up' and '4'
I tried:
array select: [:each | (each='up') | (each asInteger < 50)].

This leads to a MessageNotUnderstood because receiver of "<" is nil.
I figured I'd have to create a local variable x:= each asInteger, but just couldn't work it out.

A: Using select: you can only access one element of the array at a time. From your code I see you want to access two elements of the array at the same time. You could use in this case pairsDo:. For example the code below puts in an array all numbers that are preceded by the string 'up'.
numbers := OrderedCollection new.
#('up' '5' 'b') pairsDo: [ :first :second |
    ((first = 'up') and: [ second asInteger notNil ])
        ifTrue: [ numbers add: second asInteger ] ]

You could then use select: to only get those numbers less than 20:
numbers select: [:each| each < 20].

A: You're getting a MessageNotUnderstood because your code is trying to test whether 'b' asInteger (which is nil, because b isn't an integer) is < 20 (or < 50; you have different numbers in your text and your code). So all you need to do is test whether each array item is a number before you treat it as such.
This should work in a Pharo workspace:
| array |
array := #('up' '4' 'b' '22').
^array select: [ :each | each = 'up'
    or: [ each isAllDigits and: [ each asInteger < 20 ] ] ]

Inspecting the result of this gives #('up' '4') as expected.
Note that I'm checking whether each string is "made up of all digits", and only doing the comparison if that is the case. Also note that I'm using or: and and:, which only evaluate the block argument if required, while | and & evaluate both sides regardless.
You could also create a local variable, as you said you tried, but it would look a little clunkier (and I wouldn't call the variable x... unless it's an x-coordinate):
| array |
array := #('up' '4' 'b' '22').
^array select: [ :each |
    each = 'up' or: [
        | integerOrNil |
        integerOrNil := each asInteger.
        integerOrNil notNil and: [ integerOrNil < 20 ] ] ]

A: You get the error because second statement of comparison is being executed always: the message | in pharo (and any smalltalk) does not work as the homonym C operator, instead it is executed always, regardless the result of the first part of the statement (same happens with &, btw).
For having similar results you seem to pretend (execute the or clause just if first clause is true), we use the messages or: and and:
You can do:
array select: [ :each |
    each = 'up'
    or: [ each = '4'
    or: [ each isAllDigits and: [ each asInteger < 20 ] ] ] ]

Notice the nesting for calling the #or: statements and the fact I first check if the number can be converted to a number. If I do not do it like that, I will get nil when I try to convert a string to a number, because parsing (conversion) of a string into a number failed (and then the select will fail).
Another possible way to do it is:
array select: [ :each |
    each = 'up'
    or: [ each = '4'
    or: [ each asInteger notNil and: [ each asInteger < 20 ] ] ] ]

But I recommend the first one (using the fail of the parser a a way to determine if a string contains a number can be easily be considered an exploit :)
Finally, If you have to select more than one or two "constant" string, you can do something like:
constants := #('up' '4').
array select: [ :each |
    (constants includes: each)
    or: [ each asInteger notNil and: [ each asInteger < 20 ] ] ]

which is probably a more clean implementation.


text:
Q: RLMException: Object type does not match RLMArray type I have a simple object:
class MyObject : Object {
    dynamic var dummyField: String!;
}

and another object which inherits from MyObject:
class MyOtherObject : MyObject {
    dynamic var anotherDummyField: String!;
}

Now I do the following. I have a Realm List of MyObject and I create an instance of MyOtherObject and try to save it inside the list:
class Operator {
    internal var myObjects: List<MyObject>!;

    internal var myObject: MyObject!;

    func operate() {
        self.myObject = MyOtherObject();
        self.myObject.dummyField = "dummy field";
        self.myObject.anotherDummyField = "another dummy field";

        self.myObjects = List<MyObject>();
        self.myObjects.append(myObject); // crash!
    }
}

It crashes with the error:
Terminating app due to uncaught exception 'RLMException', reason: 'Object type 'MyOtherObject' does not match RLMArray type 'MyObject'.'

Since MyOtherObject is a subclass of MyObject I cannot understand why the app is crashing at this point with this error message.

A: Realm Lists are not covarient. You can only store objects of exactly the declared type in them.

A: self.myObjects = List<MyObject>();

This is not a proper value
self.myObjects = List<Needs actual object here not class>();

redpajama_set_name: RedPajamaStackExchange


text:
Q: latex table align decimal, stars, column width I am trying to align my columns on the decimal points. I'd like the column widths to be equal. I believe a possible answer is here, but I am really struggling to implement. Any thoughts?
Note: I need to have the asterisks in the same column. In other words, I cannot rely on -0.470&***. I should be able to wrap asterisks in other code, however (e.g., -0.470^{***}) if essential.
\documenttype{report}
\begin{document}

\begin{table}[ht]
\centering
\begin{tabular}{rllllll}
  \hline
 & 1 & 2 & 3 & 4 & 5 & 6 \\
  \hline
  1 &  &  &  &  &  &   \\
  2 &  0.47*** &  &  &  &  &   \\
  3 &  0.28* &  0.24* &  &  &  &   \\
  4 &  0.14 & -0.03 & -0.08 &  &  &    \\
  5 & -0.28* & -0.22 & -0.11 & -0.38*** &  &    \\
  6 &  0.14 & -0.02 &  0.02 &  0.23* & -0.02 &    \\
   \hline
\end{tabular}
\end{table}
\end{document}

The closest I've come is:
\documentclass{report}
\usepackage{siunitx}
\usepackage{booktabs}
\newcolumntype{L}{@{}l@{}} % a left column with no intercolumn space on either side
\newcommand{\mc}[1]{\multicolumn{1}{c}{#1}} % shorthand macro for column headings

\begin{document}

\begin{table}[ht]
\centering
%\begin{tabular}{rllllll}
\begin{tabular}{LS@{}S@{}S@{}S@{}S@{}S@{}}
  \hline
 \mc{} &  \mc{1} &  \mc{2} &  \mc{3} &  \mc{4} &  \mc{5} &  \mc{6} \\
  \hline
  1 &  &  &  &  &  &   \\
  2 &  0.47*** &  &  &  &  &   \\
  3 &  0.28* &  0.24* &  &  &  &   \\
  4 &  0.14 & -0.03 & -0.08 &  &  &    \\
  5 & -0.28* & -0.22 & -0.11 & -0.38*** &  &    \\
  6 &  0.14 & -0.02 &  0.02 &  0.23* & -0.02 &    \\
   \hline
\end{tabular}
\end{table}
\end{document}

But notice (a) the space between -0.28 and * and (b) varying column widths.

A: You can play with the following:
\documentclass{report}
\usepackage{siunitx}
\usepackage{booktabs}

\begin{document}

\begin{table}[ht]
\centering
\begin{tabular}{@{}l
                S[table-format = -1.2,table-space-text-post = {*}]
                S[table-format = -1.2,table-space-text-post = {*}]
                S[table-format = -1.2,table-space-text-post = {*}]
                S[table-format = -1.2,table-space-text-post = {*}]
                S[table-format = -1.2,table-space-text-post = {*}]
                S[table-format = -1.2,table-space-text-post = {*}]}
  \hline
           & {1}     & {2}   & {3}   & {4}      & {5}   & {6} \\
  \hline
  1       &         &       &       &          &       &     \\
  2       & 0.47*** &       &       &          &       &     \\
  3       & 0.28*   & 0.24* &       &          &       &     \\
  4       & 0.14    & -0.03 & -0.08 &          &       &     \\
  5       & -0.28*  & -0.22 & -0.11 & -0.38*** &       &     \\
  6       & 0.14    & -0.02 & 0.02  & 0.23*    & -0.02 &     \\
   \hline
\end{tabular}
\end{table}
\end{document}


text:
Q: How To Get Status Update Posted By Page - Facebook Graph API
I am creating a desktop application in which I needs to grab post_id of only status updates posted by page itself (no photos, videos and other stories/types.) I'm using type parameter to do this task easily.
https://graph.facebook.com/{username or ID of page}/posts?fields=object_id,type&limit=250&access_token={my access token}

The giving URL returning the list of posts with it's types and post ID
My Page Updated a Status
{
 "type": "status",
 "id": "493341197400693_627621933972618",
 "created_time": "2014-04-05T18:31:58+0000"
},

It's working fine but problem is some post in the list with the type=status are not a status update it's a story i.e "My Page commented on a photo"
My Page commented on a Photo
{
  "type": "status",
  "id": "493341197400693_626576670743811",
  "created_time": "2014-04-03T11:27:22+0000"
},

How to confirm that either it is a status update or a Story if the type of both response will be "Status".
I just want to ignore My Page commented on a photo or My Page Likes a Photo etc, Any Suggestion?
Sorry for my bad English.

A: you can look for the 'message' field. A status should have a 'message' field associated with it, whereas a story like 'My Page Likes a Photo' should not have a 'message'. Here is some sample php code.
if (array_key_exists("message", $post))
    //is a status

Modify you graph call to include message, like so.
https://graph.facebook.com/{username or ID of page}/posts?fields=object_id,type,message&limit=250&access_token={my access token}

A: Have a look at the stream FQL table. You can use the field type to filter the posts to a finer level than it's possible with the Graph API:
https://developers.facebook.com/docs/reference/fql/stream/#columns
Excerpt from the docs:
The type of this story. Possible values are:
11 - Group created
12 - Event created
46 - Status update
56 - Post on wall from another user
66 - Note created
80 - Link posted
128 -Video posted
247 - Photos posted
237 - App story
257 - Comment created
272 - App story
285 - Checkin to a place
308 - Post in Group


text:
Q: Avoid binding locale variable with implicit lambda capture? Im interested in the following (psudocode):
void set_it_up {
  A a{};

  //OK to use a...

  execute_it_later([&]{return a;});//When gets executed later, a has been destroyed...

  //here a also OK
}

Now Im well aware that this is usually fine to do something like this - if the lambda is used before the object gets destroyed.
But, is it possible to avoid capturing a somehow (making the code malformed) ? (lets just say I want to avoid 'accidents' to happend in the future by mistakenly capturing a temporary that gets de-allocated early).
Can I somehow openly show that A is a temporary that it shouldn't get a reference binding to ?
I can modify A as much as I want.


text:
Q: What was this novel about God's librarian apprentices? This is a novel I read a couple years ago (so at least that old), but I'm fairly sure it came out after 2010.
It centers around a bunch of people who are apprentices of someone who is not called God but might as well be God. The apprentices live in a library; the library is protected by zombies and dogs. Each apprentice studies a different topic and is not allowed to learn about other apprentices' topics; some of the topics include math, violence, animals, healing, and the afterlife. The apprentices dress oddly because they grew up in the library and don't understand fashion.
An initial plot point involves God going missing. Later the Sun goes out and is then replaced with a black sun. The main/POV characters are the apprentice who focuses on human languages, a burglar, and a US government agent of some sort (military? FBI?). One of the chapters is titled "Half a Fuckton of Lying-Ass Lies".

A: This is The Library at Mount Char by Scott Hawkins.

Carolyn had lived with eleven "siblings" under the care of a
millennia-old and godlike man known to them as Father (also known as
Ablakha or Adam Black), prone to acts of sadistic cruelty. All have
strange powers, learned from books held in Father's library. Carolyn
employs Steve Hodgson, a goodhearted former minor league housebreaker
to break into a house for her. Unknown to him, she wanted to conceal
evidence of a murder committed by her. Hodgson dies, betrayed by
Carolyn.

Chapter 6 is titled

"About Half a Fuckton of Lying-Ass Lies"


text:
Q: How to check another instance of application is running using the same resource I want to find another instance of application is running for the same resource already. My application supports multiple instances. I would like to restrict one instance per resource.
Application executable name is COMTest.exe
Assembly Title is COMPortTest . Task Manager shows the assembly title.
Application title can be COMPort1, COMPort2...COMPortX . Task Manager also shows the application title.
Let say if an instance is running for COM1 port and user launches another instance and select the same COM1 port, i should post error message.
i would like to check the application title of the running application. How can i do this.
Thanks

A: This is one of those cases, where the most reliable way could be to try and just handle the exceptions.
The COM ports being in use already is entirely exogenous to your application. And even if you could communicate this between instances of your program, what if some other program is using those ports?
You can not avoid it. You can not sensibly test for it. It is not fatal. It is clearly exogenous. So whatever Exceptions are thrown should be handled by your COM access code. You will propably use some form of loop or function call, and this handling can be done inside that loop or function.
One alternative could be to have the actually testing be done by a daemon. You can start it via TaskSheduler, you get a GUI for each user and the parties just communicate via any IPC approach you like. Of course you would still have to deal with somebody else's program using those ports, so you wouldn't really gain anything.


text:
Q: float multiple elements right and bottom once it's multiple elements a simple
position:absolute;
bottom:0;

won't help since it will overlay the multiple elements
Here is a fiddle of my atempt : http://jsfiddle.net/7uYUP/
(it's the .interaction elements that I want to float right and bottom, right now they only float right)
I was hoping not having to resort to JS..

A: The problem is the height different between your green and yellow boxes (10pt vs 40pt). You can adjust for that with margin-top:
.interaction{
   height:40pt;
   width:100pt;
   background-color:yellow;
   float:right;
   border: 1pt solid blue;
   margin-top:-32pt;
}

http://jsfiddle.net/7uYUP/2/

A:

 body{
      background-color:red;
    }

    #container{
     position:absolute;
      height:10pt;
      width:100%;
      background-color:green;
     bottom:0;
    }

    #container > div {
      position:relative;
      height:100%;
    }

    .interaction{
    height:40pt;
    width:100pt;
    background-color:yellow;
    float:right;
    border: 1pt solid blue;
    }

    .interaction.leftalign {
      float:left;
    }


text:
Q: Why am I unable to export my xcode instruments data as a CSV? The option is greyed out Currently I'm trying to record the average, high and low framerate of my iOS application by running it through Xcode. I:

*

*Load the project in Xcode.

*go to Product -> Build For -> Profiling and build it to my device (iPad 2)

*Long-click the play button and select Profile

*Select the Core Animation instrument when prompted.

*Press the Record button, launching the app.

*Perform a 5 minute test. Framerate is displayed in the tool.

*Press the Stop button to stop the application.

*Click "Instrument" from the xcode menu to attemp to expore.
At this point the option is greyed out with no explanation. Can anyone shed some light on this?

A: Some instruments do not support exporting to CSV. The Export Track menu item being disabled is a sign the Core Animation instrument cannot export its data to CSV. Disabling user interface elements and menu items is Apple's way of saying you can't do something in Instruments.
If you want to know why the Core Animation instrument cannot export its data to CSV, I have no answer for you. Your best option is to ask on Apple's developer forums. There's a Performance Tools board in the Xcode section. If you're lucky, an Apple engineer may explain why.
You may already know this, but you can save your trace from the File menu. You won't be able to read the data in a text editor, but you can at least examine the trace data in Instruments at a later time.


text:
Q: Haskell Format String Output "(x, y)," So I am trying to output a list of Points "(X,Y) \n" but I cant get it working.
Both values X and Y are Floats. I tried the module text-format but I cant make it work with Char and Float and the same time.
Anyone has an idea on how to make this work?
BEst regards
UPDATED:
format_pts_string cs = [
    format ("(" % a % ", " % b % ")")
    | c <- cs]

*

*This code is NOT working, Error -> Print Of Error

A: From the code of your question, I guess you want to convert a list of Double pair to a list of String, as said in comment, you may not need use Data.Text.Format package, since the basic function show can convert it to String properly as:
format_pts_string::[(Double, Double)]->[String]
format_pts_string cs = map (\c-> (show c) ++ "\n") cs

or use list comprehension:
format_pts_string::[(Double, Double)]->[String]
format_pts_string cs =  [show c ++ "\n" | c <- cs]

Furthermore, if need to control output format, you can use ++ to concatenate the String, here is an example:
format_pts_string::[(Double, Double)]->[String]
format_pts_string cs = map formatPair cs
    where formatPair (a, b) = "(" ++ (show a) ++ ", " ++ (show b) ++ ")" ++ "\n"

if you still love to use module text-format, you may need to enable OverloadedStrings language extension to convert String to Format type for call format function as:
{-# Language OverloadedStrings #-}
import Data.Text.Lazy (unpack)
import Data.Text.Format (format)

format_pts_string::[(Double, Double)]->[String]
format_pts_string cs = [unpack $ format "({}, {})\n" (c::(Double, Double))| c <- cs]

or don't use OverloadedStrings language extension, use formString in Data.String instead, but it is verbose as:
...
import Data.String (fromString)
...
[unpack $ format (fromString "({}, {})\n") (c::(Double, Double))| c <- cs]

A: Is this what you have in mind?
main = let ps = [
                  (1.0,1.0),
                  (2.0,2.0),
                  (3.0,3.0),
                  (4.0,4.0),
                  (5.0,5.0),
                  (6.0,6.0)
                ]
        in mapM print ps

output :
(1.0,1.0)
(2.0,2.0)
(3.0,3.0)
(4.0,4.0)
(5.0,5.0)
(6.0,6.0)


text:
Q: What should i do with the upgrade? I have dual booted Ubuntu 12.10 and windows 8. Recently, i have upgraded to 13.04 beta but i found there were some problems so i upgraded to beta 2. i lost all the programs i had. I tryed to install google chrome but failed so now i am stuck with chromiun instead. there are many irratating bugs that really get on my nerves and some of the features have been gotten a rid of.
What sould i do wait till ubuntu 13.04 official release comes out or just downgrade back into ubuntu 12.10. I have already made a bootable usb to prepare myself to go back into ubuntu 12.10 but should i do it. is it really worth the time and patience.

A: The next Ubuntu release will be on the 25th, so you will have to wait a couple days. It sounds like your installation is broken anyway, so consider installing 12.10 again and the upgrading to 13.04 once it is out. If you can live without Ubuntu for a couple days, then just wait.
I would not fix the Beta install.

A: Downgrading is what i would do loosing all your apps etc suck lol. there is a nifty little test drive ubuntu iso. if you are like me you want to see results for yourself or stay current test it there first, still learning that myself. i can change the OS everyday just to see what is new. P.S Ubuntu one is my best friend format delete whatever your data is safe.  Btw i believe WIN7/Win8 are like rivals to ubuntu. best results are dependent on What OS was installed first and Second


text:
Q: MessageBird WhatsApp: Can't move from sandbox mode We have developed an application to send notification through WhatsApp using MessageBird integration.
In Facebook - WhatsApp Management painel our account is in "Sandbox mode" which means that we can only send up to 10 messages/day to only 2 numbers. Detail: our company is already verified and the account status is approved.
Is there anything we are missing? Any help?

A: There are two prerequisites for your phone number to be promoted from the "sandbox mode":

*

*Your business needs to be verified on Facebook (as shown in this video)

*Your WhatsApp Business Account needs to be approved. You can easily check this by navigating to this page and finding the account under "Accounts > WhatsApp accounts". After finding the relevant account in that list, select "Settings". Your account status should show up as "verified".

In case you need help verifying your business and/or approving your WhatsApp Business Account, please reach out to MessageBird support. If both of these are in order and your phone number is still in sandboxed mode, this is also something they should be able to help you with.


text:
Q: Advice on creating a "popular now" widget that displays daily, or even hourly, popular posts I've made a widget for my theme that displays the most popular posts on the website, based on a few tutorials.
Currently, this function is run everytime a user views an article:
function wpb_set_post_views($postID) {
$count_key = 'wpb_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
    $count = 0;
    delete_post_meta($postID, $count_key);
    add_post_meta($postID, $count_key, '0');
}else{
    $count++;
    update_post_meta($postID, $count_key, $count);
}
}

And the widget loops out the posts via this loop:
$popularpost = new WP_Query( array('post_type', array( 'post', 'features', 'reviews', 'podcasts'), 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
                while ( $popularpost->have_posts() ) : $popularpost->the_post();

Although this works perfectly for showing the most popular posts of all time, I'm curious as to whether it would be possible to show the most popular posts at the moment, perhaps hourly or daily.
Would this be possible using the methods I'm using at the moment? If not, could anyone suggest alternative ways of solving this issue?
Thanks in advance.


text:
Q: S02E16 "A Matter of Time" How did Daniel suddenly come back? So everything was fine until the end. SG-10 plus Daniel got stuck on a planet where gravity was so heavy that time was really slow. As such they were moving so slow that the gate would close before they could enter it. Then... at the end, at main base, they explode a charge to put a spike of energy on the Stargate to make the wormhole bounce the other end to another Stargate.
Suddenly, O'neill wakes up and Daniel is there? It makes no sense, Daniel should be stuck on P3W-451. I understand that he's a main character, but it sucks they had to bend the laws of physics.

A: Daniel isn't with SG-10, he's with SG-6 on another planet.

O'NEILL : Daniel's with [SG-]6, isn't he?
CARTER: Yeah, he's on a dig on P3X-808.
SIMMONS: Computer can't identify the signal. It's not a GDO transmission

Obviously in reality the line was a throwaway to explain his total absence from the episode, aside from a pre-taped cameo at the end of the show.


text:
Q: C# with SQL database schema question Is it acceptable to dynamically generate the total of the contents of a field using up to 10k records instead of storing the total in a table?
I have some reasons to prefer on-demand generation of a total, but how bad is the performance price on an average home PC?  (There would be some joins -ORM managed- involved in figuring the total.)
Let me know if I'm leaving out any info important to deciding the answer.

EDIT: This is a stand-alone program on a user's PC.

A: Usually it is totally acceptable and even recommended to recalculate values. If you start storing calculated values, you'll face some overhead ensuring that they are always up to date, usually using triggers.
That said, if your specific calculation query turns out to take a lot of time, you might need to go that route, but only do that if you actually hit a performance problem, not upfront.

A: If you have appropriate indexing in place, it won't be too bad to do on demand calculations. The reason that I mention indexing is that you haven't specified whether the total is on all the values in a column, or on a subset - if it's a subset, then the fields that make up the filter may need to be indexed, so as to avoid table scans.

A: Using a Sql query you can quickly and inexpensively get the total number of records using the max function.
It is better to generate the total then keep it as a record, the same way as you would keep a persons birth date and determine their age then keep their age.

A: How offten and by what number of users u must get this total value, how offten data on which total depends are updated.
Maybe only thing you need is to make this big query once a day (or once at all) and save it somewhere in db and then update it when data, on which your total consist, are changed

A: You "could" calculate the total with SQL (I am assuming you do not want total number of records ... the price total or whatever it is). SQL is quite good at mathematics when it gets told to do so :) No storing of total.
But, as it is all run on the client machine, I think my preference would be to total using C#. Then the business rules for calculating the total are out of the DB/SQL. By that I mean if you had a complex calculation for total that reuired adding say 5% to orders below £50 and the "business" changed it to add 10% to orders below £50 it is done in your "business logic" code rather than in your storage medium (in this case SQL).
Kindness,
Dan

A: I think that it should not take long, probably less than a second, to generate a sum from 8000-10000 records.  Even on a single PC the query plan for this query should be dominated by a single table scan, which will generate mostly sequential I/O.
Proper indexing should make any joins reasonably efficient unless the schema is deeply flawed and unless you have (say) large blob fields in the table the total data volume for the rows should not be very large at all.  If you still have performance issues going through an O/R mapper, consider re-casting the functionality as a report where you can control the SQL.


text:
Q: Wifi not working- Dual boot Ubuntu 14.04 and Windows 10 Wifi was working properly on both Windows 10 and Ubuntu 14.04 until recently the wifi icon disappeared from Ubuntu. I've tried everything mentioned in other threads but I couldn't solve it.
prajval10@prajval:~$ lspci -knn | grep Net -A2 && rfkill list
08:00.0 Network controller [0280]: Broadcom Limited BCM43142 802.11b/g/n [14e4:4365] (rev 01)
    Subsystem: Hewlett-Packard Company Device [103c:2230]
09:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL810xE PCI Express Fast Ethernet controller [10ec:8136] (rev 08)
0: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no

I tried this as well:
sudo apt-get install bcmwl-kernel-source

I enabled the driver in Settings as well.
Additional drivers
modinfo wl | grep vermagic
vermagic:       4.4.0-116-generic SMP mod_unload modversions
sudo modprobe -fv wl
insmod /lib/modules/4.4.0-116-generic/updates/dkms/wl.ko
modprobe: ERROR: could not insert 'wl': Exec format error

A: Wifi works with kernel: 4.4.0-112-generic but not with 4.4.0-116-generic. This seems to be a known issue, so I'll stick to using 4.4.0-112-generic for now


text:
Q: Java regex , jsoup How to extract these messages by regex or jsoup ? 19040172b-1、 SQL Server Develop 、zheng 、3-5,7-14 、D-101 ,

  19040172b-1

SQL Server Develop

  zheng

  3-5,7-14

  D-101

I have tried the following ways but failed.
1. Pattern pattern = Pattern.compile(">(.*?)
");

2. Elements msg = doc.select(":matchesOwn([>.*?
])");

A: 1) First, it's never a good idea to parse HTMl with a regex. You can read more about that here.
2)You can just take all text between tags.
Document doc = Jsoup.parse(file, charsetName);
String text= doc.text();
System.out.println(text);

A: String html = "
  19040172b-1
SQL Server Develop
  zheng
  3-5,7-14
  D-101

 ";
html = html.replaceAll("
", "#~#");
Document doc = Jsoup.parse(html.toString());
String newHtml = doc.text();
String[] ary = newHtml.split("#~#");

This will do the job, yet there may be other clean ways to replace the br tag.


text:
Q: Cocos2d-x - CCDirector::sharedDirector()->getWinSize() returns totally wrong value on Win32 I came into a trouble with cocos2d-x, which I may not be able to solve alone, therefore I'm asking for your help. I wanted to create my own CCScene with CCLayer -as part of my cocos2d-x learning. Everything is working fine, except the size of the scene. CCDirector::sharedDirector()->getWinSize() report totally messed up resolution, like 0 x 108134400... and I don't know what I'm doing wrong.
Here is my class
.h
#pragma once
#include "cocos2d.h"

class zfGameScene : public cocos2d::CCLayer
{
public:
    static cocos2d::CCScene* scene();
    virtual bool init();
    CREATE_FUNC(zfGameScene);
};

Aaaaand
.cpp
#include "zfGameScene.h"
#include "cocos2d.h"

using namespace cocos2d;

CCScene* zfGameScene::scene(){
CCScene * scene = NULL;
    do
    {
     scene = CCScene::create();
        CC_BREAK_IF(! scene);

        zfGameScene *layer = zfGameScene::create();
        CC_BREAK_IF(! layer);

        scene->addChild(layer);
    } while (0);

    return scene;
}

bool zfGameScene::init(){
    bool returnValue = false;
    while(!returnValue){
        CC_BREAK_IF(!CCLayer::init());

        // This one is for loading the scene :P
        CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    CCLog("[zfGameScene] Initialising with %d x %d...", winSize.width, winSize.height);

        CCSprite *background = CCSprite::spriteWithFile("background.png", CCRect(0, 0, 2048, 1536));
        this->setScale(1);
        this->setPosition(ccp(0, 0));
        this->addChild(background);

        returnValue = true;
    }

    return returnValue;

}
Thanks in advance for your help.

A: Width and height are float. Just change your code like this:
CCLog("[zfGameScene] Initialising with %f x %f...", winSize.width, winSize.height);


text:
Q: how to keep playing audio with discord.py bot Hey im making music bot everything is working fine when i enter !join in discord chat the bot join voice channel and start playing local .wav file
the thing is i want it to keep playing next audio file randomly without stop
im trying while loop but not working.
@client.command(pass_context=True)
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        voice = await channel.connect()
        while True:
            mymusic = random.choice(['voice.wav', 'voice1.wav', 'voice2.wav', 'voice3.wav'])
            source = FFmpegPCMAudio(mymusic)
            player = voice.play(source)

    else:
        await ctx.send("You are not in a voice channel")


text:
Q: Double trigger for jquery action How can I get "count" to be incremented by one either if the button "next" is pressed, or if the right keyboard arrow is pressed?
I've tried like this:
$("#NextBtn").click(function()
$(document).keydown(function (e)

 {
  count = count + 1
  console.log(count);

});

But obviously I'm missing how to give this action a double trigger, don't know how to do it... Any ideas?
Thank you!!

A: try this
$("#NextBtn").click(increment);
$(document).keydown(increment);

function increment(){
  count = count + 1
  console.log(count);
}

A: Something like the following:
var count = 0;

$("#NextBtn").click(increment);
$(document).keydown(function(e){
    if (e.keyCode == 39) {
       increment();
    }
});

function increment(){
   count = count + 1;
   console.log(count);
}

Because everybody wants to know the keycodes:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Added jsFiddle: http://jsfiddle.net/tFkpm/


text:
Q: How to extract jvm parameters from binary heap dump I am analyzing several heap dumps and am interested in a way that I can get the jvm parameters from the heap dump. Using eclipse memory analyzer I can easy get the System Properties and class path but was wondering if there was a way to get other parameters such as -Xms -Xmx ect.

A: OpenJDK / Oracle JDK does not save JVM arguments in a heap dump.


text:
Q: How to trigger action on mount, but after redux storage load I use redux-storage for persisting the redux state tree across refreshes, etc.
redux-storage-engine-localstorage as the storage engine.
My problem has to do with the order of
1) the action which loads this persisted state, and
2) some other action I set off in a componentDidMount lifecycle function.
Because the storage load happens after some action I trigger, the action I trigger might as well not have happened, since the old state overwrites it.

Printing out the action type at the top of my reducer, on page load I see:
action.type @@redux/INIT
action.type HIDE_MODAL
action.type REDUX_STORAGE_LOAD
action.type REDUX_STORAGE_SAVE
action.type FETCH_USER_FAILURE
action.type REDUX_STORAGE_SAVE

The HIDE_MODAL action is triggered in one of my components' componentDidMount method.
The storage load happens before mounting my root node (right after creating my redux store):
import mainReducer from './reducers';
const reducer = storage.reducer(mainReducer);
const storageEngine = createEngine(some key);
const storageMiddleware = storage.createMiddleware(storageEngine);
const middleware = applyMiddleware(
  storageMiddleware,
);
const storageLoad = storage.createLoader(storageEngine);

const store = createStore(
  reducer,
  middleware,
);
storageLoad(store);

render(
  <Provider store={store}>
    ...
  </Provider>,
  document.getElementById('root')
);

Why does the REDUX_STORAGE_LOAD not happen before everything else, and is there a way to make sure it occurs before everything else?

A: I added a new state field reduxStorageLoaded, initially false, and added a case to my reducer:
import { LOAD } from 'redux-storage';

...

const mainReducer = (state = initialState(), action) => {
  switch (action.type) {
    ...
    case LOAD:
      return {
        ...state,
        reduxStorageLoaded: true,
      };
    ...

and wrapped my whole app in a conditional based on this new state variable reduxStorageLoaded so it only mounted once it becomes true, which is when redux-storage has fully loaded and dispatched the LOAD action.


text:
Q: How copy resources files with sbt docker plugin I'm running an application using docker which crashes because my application cannot access to a file located in the folder src/main/resources. Here my file project/plugins.sbt :
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.1.4")

my build.sbt file :
organization      := """foo"""

name              := """bar"""

version           := "1.0"

scalaVersion := "2.11.7"

libraryDependencies ++= Seq(
  "org.apache.kafka" % "kafka_2.10" % "0.10.0.0",
  "org.scalatest" % "scalatest_2.11" % "3.0.0-M16-SNAP1",
  "org.scalaz" %% "scalaz-core" % "7.2.5",
  "com.typesafe.akka" %% "akka-actor" % "2.4.11",
  "com.typesafe.play" % "play-json_2.11" % "2.4.8",
  "com.typesafe.scala-logging" %% "scala-logging" % "3.1.0",
  "com.typesafe" % "config" % "1.3.0",
  "com.amazonaws" % "aws-java-sdk" % "1.11.8",
  "ch.qos.logback" % "logback-classic" % "1.1.7",
  "com.typesafe.akka" % "akka-testkit_2.11" % "2.4.12"
)

// the default value in sbt is set to true
parallelExecution in Test := false

resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/conigtent/repositories/snapshots"

dependencyOverrides ++= Set(
  "com.fasterxml.jackson.core" % "jackson-databind" % "2.4.4"
)

resolvers ++= Seq(
  "Sonatype Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots/",
  "Sonatype Releases" at "https://oss.sonatype.org/content/repositories/releases/"
)

// http://www.scala-sbt.org/sbt-native-packager/formats/docker.html
enablePlugins(DockerPlugin, JavaAppPackaging)
// enablePlugins(JavaAppPackaging)
packageName in Docker := "foo/bar"

Here the main file :
object FGS_MainApp extends LazyLogging {

  val actorSystemName = "SYS"
  println("Create actor sys " + actorSystemName)
  val system = ActorSystem(actorSystemName)

  private val t = new Thread {
    override def run() = {
      if (system != null) {
        Database.closeConnection
        system.terminate
        logger.info("ACTOR SYSTEM SHUTDOWN")
      }
    }
  }

  Runtime.getRuntime.addShutdownHook(t)

  def main(args : Array[String]) = {
    // TODO : this needs to be remove quickly
    val saslPath = getClass.getResource("/sasl.conf").getPath
    println("saslPath = " + saslPath)
    System.setProperty("java.security.auth.login.config", saslPath)
  }
}

Then when I'm running the command : sbt docker:publishLocal && docker run -it foo/bar:1.0, I got this error :
Caused by: java.lang.SecurityException: java.io.IOException: Configuration Error:
    No such file or directory

The printed path is :
file:/opt/docker/lib/foo.bar-1.0.jar!/sasl.conf

What did I miss with the configuration in build.sbt ?
Update
Caused by: org.apache.kafka.common.KafkaException: java.lang.SecurityException: java.io.IOException: Configuration Error:
    No such file or directory
    at org.apache.kafka.common.network.SaslChannelBuilder.configure(SaslChannelBuilder.java:86)
    at org.apache.kafka.common.network.ChannelBuilders.create(ChannelBuilders.java:70)
    at org.apache.kafka.clients.ClientUtils.createChannelBuilder(ClientUtils.java:83)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:623)
    ... 18 more
Caused by: java.lang.SecurityException: java.io.IOException: Configuration Error:
    No such file or directory
    at sun.security.provider.ConfigFile$Spi.<init>(ConfigFile.java:137)
    at sun.security.provider.ConfigFile.<init>(ConfigFile.java:102)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at javax.security.auth.login.Configuration$2.run(Configuration.java:255)
    at javax.security.auth.login.Configuration$2.run(Configuration.java:247)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.login.Configuration.getConfiguration(Configuration.java:246)
    at org.apache.kafka.common.security.authenticator.AbstractLogin.login(AbstractLogin.java:61)
    at org.apache.kafka.common.security.authenticator.LoginManager.<init>(LoginManager.java:46)
    at org.apache.kafka.common.security.authenticator.LoginManager.acquireLoginManager(LoginManager.java:68)
    at org.apache.kafka.common.network.SaslChannelBuilder.configure(SaslChannelBuilder.java:78)
    ... 21 more
Caused by: java.io.IOException: Configuration Error:
    No such file or directory
    at sun.security.provider.ConfigFile$Spi.init(ConfigFile.java:335)
    at sun.security.provider.ConfigFile$Spi.init(ConfigFile.java:271)
    at sun.security.provider.ConfigFile$Spi.<init>(ConfigFile.java:135)
    ... 35 more

And it shows the line :
private val kafkaConsumer = new KafkaConsumer[String, Array[Byte]](kafkaProps) where kafkaProps is type of java.util.Properties. So it cannot find the file in resources folder.

A: The problem you're encountering is with how src/main/resources is treated. It's a special folder whose contents will be included in the jar file built by sbt. It's never actually copied as a file into your universal package. That's why the file path that's printed out includes the jar name and a ! - that means the file is inside the zipped jar. It's clear that the kafka library doesn't handle this.
To solve this, you should put the file in a different location, like src/main/conf (optional, but strictly-speaking more correct), then map it into your universal package:
mappings.in(Universal) +=
  ((sourceDirectory.value / "main" / "conf" / "sasl.conf"), "conf/sasl.conf"))

This will now be available as the file conf/sasl.conf within your universal package.


text:
Q: EasyAdminBundle count and statistique I want to add to the administration page of EasyAdminBundle (/ admin), the number of registered users for example, or the number of registered restaurants (for example). (statistics from my business layer) or even add statistics of the number of registrants, number of registrations of the day, total number of registrants, see even the number of visitors, ...
I'm starting with EasyAdminBundle and I don't know if it's possible or how to do it, ...
thanking you!

A: This is a simple example when you want to make a custom login with the EasyAdmin login template:
https://symfony.com/doc/current/bundles/EasyAdminBundle/dashboards.html#login-form-template
If you want to make a custom dashboard with EasyAdmin, follow this:
https://symfony.com/doc/current/bundles/EasyAdminBundle/dashboards.html#content-page-template
They don't provide full example in the documentation but regarding the way a custom login form is implemented with EasyAdmin , It should not be hard!


text:
Q: Can I loop over keys and values of an object in OPA to validate if they adhere to a certain format (CamelCase) We are using conftest to validate if our terraform changeset applies to certain rules & compliances. One thing we want to validate is wether our AWS resources are tagged according to the AWS tagging convention, which specifies certain tags to use (e.g. Owner, ApplicationRole, Project) and specifies that all tags and values are in CamelCase.
in terraform the changeset is portrayed in the following (simplified) json output:
{
   "resource_changes":{
      "provider_name":"aws",
      "change":{
         "before":{

         },
         "after":{
            "tags":{
               "ApplicationRole":"SomeValue",
               "Owner":"SomeValue",
               "Project":"SomeValue"
            }
         }
      }
   }
}

What I am now trying to do is to validate the following:

*

*Check wether tags are set.

*Validate if the keys and values are all camelcase.

*Check that the keys include the set (ApplicationRole, Owner, Project) in the minimum.

However, I am having trouble defining that in Rego (I am quite new to OPA).
Is there a way to "loop" over the keys and values of an object, and validate if they are formatted correctly?
in pseudo code:
for key, value in tags {
  re_match(`([A-Z][a-z0-9]+)+`, key)
  re_match(`([A-Z][a-z0-9]+)+`, value)
}

I have tried the following:
tags_camel_case(tags) {
    some key
    val := tags[key]
    re_match(`^([A-Z][a-z0-9]+)+`, key) # why is key not evaluated?
    re_match(`^([A-Z][a-z0-9]+)+`, val)
}

However, when evaluating against the following test json:
{
  "AppRole": "SomeValue",
  "appRole": "SomeValue"
}

the rule returns true, even though I am checking both key and value vs the regex

A: The tags_camel_case(tags) function returns true for the input with two keys because (by default) variables in Rego are existentially quantified. This means rule bodies are satisfied if for some set of variable bindings, the statements in the rule body are true. In the example above, the rule body would be satisfied by {key=AppRole, val=SomeValue}.
To express for all you can use a simple trick. First write a rule to check if any of the tags ARE NOT camel case. Second write the rule to check if the first rule is not satisfied.
For example:
# checks if all tags are camel case
tags_camel_case(tags) {
  not any_tags_not_camel_case(tags)
}

# checks if any tags are NOT camel case
any_tags_not_camel_case(tags) {
    some key
    val := tags[key]
    not is_camel_case(key, val)
}

# checks if a and b are both camel case
is_camel_case(a, b) {
  re_match(`^([A-Z][a-z0-9]+)+`, a)
  re_match(`^([A-Z][a-z0-9]+)+`, b)
}

For more info on expression 'for all' in Rego see https://www.openpolicyagent.org/docs/latest/how-do-i-write-policies/#universal-quantification-for-all


text:
Q: Validation Rule with multiple picklist fields I need to create a validation rule that fires where when either "Complete" or "Closed" is chosen from a picklist, another picklist becomes a required field. I have tried multiple options, but have not had luck yet. So far this is what I have tried:
AND (
   ISPICKVAL(Status__c, "Complete" || ISPICKVAL (Status__c, "Closed"),
   NOT(ISCHANGED(Root_Cause__c))
)

Both Root_Cause__c and Status__c are picklists.
I am currently getting a FIELD_CUSTOM_VALIDATION_EXCEPTION error on the page. Anyone have any ideas?

A: Start with your root criterion, namely this other field being null. The approach may vary based on field type, but that might look like:
ISBLANK(Root_Cause__c)

EDIT Now that you have explicated this field to be a picklist, you can change this check to:
ISPICKVAL(Root_Cause__c, "")

Now layer on top of that your check on the value of Status. You can do it the way you have, but please try to always use functions instead of && and ||, as that will be more consistent with the rest of your formula. So it would be better to do:
OR(ISPICKVAL(...), ISPICKVAL(...))

Better yet, though, is to use a CASE function so that you only reference the field once (field references are expensive):
1 = CASE(Status__c, "Complete", 1, "Closed", 1, 0)

Now the field you actually want to check if it changed should also be this status field. Putting it all together:
AND(
    ISPICKVAL(Root_Cause__c, ""),
    ISCHANGED(Status__c),
    1 = CASE(
        Status__c,
        "Complete", 1,
        "Closed", 1,
        0
    )
)

A: Your page is a visualforce page? if so, you need to use 'try catch' like below code.
Account acc = new Account();
acc.Name = 'ABC';
try {
    insert acc;
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getDmlMessage(i)));
}


text:
Q: Draw an arrow between nodes in forest I want to create an arrow between two nodes like the red one in below example.

I've seen the following in documentation, but tbh I don't understand how to use it and I need to use it in more than one tree.

A: It works precisely as described in the documentation...
\documentclass[tikz,border=3.14mm]{standalone}
\usepackage[edges]{forest}
\begin{document}
\tikzset{state/.style={draw,circle}}
\forestset{d/.style={dotted,edge=dotted},
r/.style={red,edge=red}}
\begin{forest}
for tree={state,edge={-},grow=south,l sep=6mm,s sep=10mm},
[22,d
 [13,d
  [30,red,edge=dotted
   [15,r]
   [85,r]{\draw[<->,red] () to[bend right=45] node[midway,above
   right,font=\small]{zam} (!u.east);}
  ]
  [71
   [17]
   [20]
  ]
 ]
 [11,d
  [33,edge=dotted
   [32]
  ]
  [55,d]
 ]
]
\end{forest}
\end{document}


text:
Q: What are the various pros and cons of switching my state religion to Protestant? The Protestant Reformation recently began in my game of Europa Univeraslis IV, and it's spreading quite rapidly across my nation. When it first started I was hoping to stop it, but that doesn't look like it'll be an easy task. As the percentage of Protestants in my nation started to grow I started thinking it might just be easier to wait until Protestant becomes the dominate religion and switch my state religion to Protestant.
I noticed that doing so will give me a +10% bonus to Tax, and a 10% decrease in technology costs. The bonuses are very nice, but I've also noticed I get a diplomatic relations bonus with nations of the same religion. I'm assuming there might be a wide range of consequences for switching my religion beyond just these two things, so before I make the decision I'm hoping someone can detail the various benefits and drawbacks of switching my state religion to Protestant.
What are the various pros and cons of switching my state religion to Protestant?

A: First, a small correction: Protestant faith has 10% reduced idea cost as opposed to technology cost. This is still pretty powerful bonus, as there are very few other ways to reduce the idea cost, and it's typically not very difficult to keep abreast with technological developments if you are in a Christian-following technology group.
Let's list the properties of each denomination of Catholicism first:
Catholicism

*

*Tolerance of the True Faith: +1 (i.e. -1 revolt risk in the province of your own faith)

*Tolerance of Heretics: -1 (i.e. +1 revolt risk in provinces of other Catholic denominations)

Apart from these bonuses, you also have a possibility in participating in Papal politics -- controlling cardinals and ultimately the Curia itself.
Controlling cardinals confer small, but appreciable bonuses to prestige, legitimacy, papal influence and even technology cost. The Papal controller also gets an additional diplomat, larger advisor pool, additional leader slot, more papal influence and prestige. On top of that, the Papal controller can dissolve royal marriages without a stability hit, can excommunicate catholic rulers and can call crusades (until 1650). Pretty significant laundry list of bonuses, to be sure -- only if you play and win the Papal game.
Protestant

*

*National Tax Modifier: +10% (a moderately powerful boost)

*Idea costs: -10%
Switching the state religion confers also a significant lump sum of cash, as well as a heavy stability hit. Apart from that, there's not much additional benefits for protestant nations.
Reformed

*

*Trade Efficiency: +10% (interesting choice only if you are trade-oriented)

*Advisor Pool: +1 (one additional advisor to choose from)

Similar to Protestant, you receive a substantial amount of money upon switching, together with reduced stability.

If you are a minor nation, it's going to be difficult to have more than one or at most two cardinals in the Curia at any given time, and becoming the Papal controller is probably a pipe dream. So, if you can't compete with the big boys and everybody else around has converted, it might be a good idea for you to do that too.
Countries in the Germanic, Scandinavian, British and West Slavic culture groups are much more likely to switch religion than others; conversely, Latin and Iberian cultures are much less likely to do so. If you play Bohemia, for example, it will be virtually impossible not to switch to Protestantism.
If you are the Catholic Defender of Faith and/or control the Curia, spontaneous conversion of provinces cannot occur[verification needed].
Other minor factors also control how often provinces switch, like whether you have or not Religious or Innovativeness ideas.
If you are determined to stay Catholic but a lot of your provinces start to switch, wait for the Counter-Reformation event, which fires around 20 years after the start of the Reformation. If you take the decision, you will receive additional missionaries and increased missionary strength, at the cost of slightly increased future technology expenditures.
Be advised that switching religions is going to be a tremulous time for your realm: expect events reducing stability and increased revolt activity for a number of years. Don't take the decision unless a sizeable portion of your nation has flipped or if you are in a precarious position (overextended, targeted by a coalition, depleted manpower pool).

TLDR;

*

*If you have Germanic, Scandinavian, West Slavic or British culture and are not powerful enough to consistently control the Curia, it's probably best to switch.

*If you are trade-oriented or a republic, switching might be best for you too.

*If you are a pious Catholic from France, Iberia or Italy, the Defender of Faith or control the Curia, stay catholic.

*If you are determined to stay Catholic in the face of significant province switching, consider embracing the Counter-Reformation.

A: As the Holy Roman Empire, and the curia controller, the protestant reformation started and has steadily grown, only switching to the Defender of the Faith stopped the protestant reformation.


text:
Q: How can I get heart rate data (continuous measurement) from MiBand 2 in my own app? I'm developing an android application that needs to get the user's heart rate instantly for analysis. I have a Xiaomi MiBand 2 and would like to use it as data source.
I found several codes in GitHub for applications that connect and get data from the bracelet, but none actually worked. I also tried to do this using Google Fit Api to get heartbeat data provided by the Mi Heart Rate synchronized with Google Fit, but it was not possible to get them either (the HR data is not found).
So if anyone can help me, I'll be grateful.


text:
Q: How can I optimize this getter performance issue? In an angular component using NgRX store I have this bit of template
<p>{{ someObservable | async | assertNotNull }}</p>

which comes from the following getter
get someObservable(): Observable<number> {
    return this.store.pipe(select(state => state.myObservableValue));
}

The problem is that it returns a new Observable at each change detection cycle and the async pipe unsubscribes/subscribes every time.
How can I improve this in an elegant and performance-compliant way ?

A: Make it a normal readonly property
public readonly someObservable: Observable<number> = this.store.pipe(select(state => state.myObservableValue));


text:
Q: Valgrind error with std::cin Here is my code:
 std::string getword()
 {
  std::string temp;
  std::cin >> temp;
  return temp;
 }

Valgrind throws an error on the line std::cin >> temp.
Here is the valgrind output for those who asked:
 HEAP SUMMARY:
==18490==     in use at exit: 33 bytes in 1 blocks
==18490==   total heap usage: 397 allocs, 396 frees, 12,986 bytes allocated
==18490==
==18490== 33 bytes in 1 blocks are possibly lost in loss record 1 of 1
==18490==    at 0x4C2AF8E: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18490==    by 0x4EEE3B8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==18490==    by 0x4EEF127: std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==18490==    by 0x4EEF20F: std::string::reserve(unsigned long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==18490==    by 0x4EA7D14: std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char,     std::char_traits<char>, std::allocator<char> >&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==18490==    by 0x401681: getword() (netsim.cc:29)
==18490==    by 0x401F6E: main (netsim.cc:96)
==18490==
==18490== LEAK SUMMARY:
==18490==    definitely lost: 0 bytes in 0 blocks
==18490==    indirectly lost: 0 bytes in 0 blocks
==18490==      possibly lost: 33 bytes in 1 blocks
==18490==    still reachable: 0 bytes in 0 blocks
==18490==         suppressed: 0 bytes in 0 blocks
==18490==
==18490== For counts of detected and suppressed errors, rerun with: -v
==18490== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)

netsim.cc:96 is the second call to getword() in the program. That code reads
std::string network = getword();

netsim.cc:29 is the code for getword() itself. Line 29 is the line
std::cin >> temp

I still don't understand why this happened but I managed to resolve the issue.
I had the code
std::string s = getword();

immediatly above
std::string network = getword();

I made both s and network global variables and somehow the issue was resolved.
If anyone can explain why that is though I would be grateful.

A: I'm not a valgrind Expert, but I'm tentative to say that this is a false positive. In fact, it might even be a false positive generated by valgrind itself. Looking at the Leak Summary and seeing the core origin of the leak, I get suspicious:
// The one right below this, that's at the top of that valgrind error
==18490==    at 0x4C2AF8E: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18490==    by 0x4EEE3B8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)

Now why would valgrind be reporting a memory leak from its own shared library ? Something doesn't seem right here. Either valgrind itself isn't very clean in how its allocating that memory (and valgrind has its own leak! Oh noes!) or it's throwing a really strange false positive. Unless the newest branches of GCC have produced a memory leak for std::string and the istream& operator<< recently, I can't imagine this actually leaking. std::cin and std::cout have been being used for ages, and it makes no sense that valgrind would toss an error over it, especially when your client code isn't making a single new/delete call.
So, in short, there's a few things that could be happening here:

*

*valgrind is leaking. (Maybe? It's originating from a valgrind function)

*GCC is leaking? (Hesitant to say this)

*valgrind is drunk! :[

In either case, ignore it and move on. I doubt this is going to shatter your netsim in any crucial way.
I hope it clears up soon, and I'm sorry my answer can only say this much, but these are the best shots I can give.


text:
Q: Does the subscription retry when notification fails? I would like to know about the subscription feature of Orion.
I have two Orions and have registered another Orion "/v2/op/nofity" on one.
However, if there is a momentary communication failure between the two Orions, the notification fails.
I would like to know if the subscription notification will retry?

A: Orion supports two kind of notification transports: HTTP and MQTT.
Orion doesn't retry notifications in any case, but in the case of MQTT you can specify a QoS value (qos field). If the MQTT broker in which you are publishing your notification is properly configured you can have some degree of retrial (but not provided by Orion itself, but by the MQTT broker).
More information on Orion MQTT notifications here


text:
Q: TypeError: 'builtin_function_or_method' object is not subscriptable NUM_SQ = 8
empty = 1
board = []
for sq in range(NUM_SQ):
    board.append[empty]

A: NUM_SQ = 8
empty = 1
board = []
for sq in range(NUM_SQ):
    board.append(empty)

Функции пишутся в круглых скобках.


text:
Q: Looking for: a subgroup of an uncountable simple group of countable index Consider the simple group $A_\lambda$, the alternating group on the set $\lambda$, which I will assume has regular cardinality. Recall that this is the smallest subgroup of all permutations of $\lambda$ containing the finite even permutations. In particular, only finitely many elements of $\lambda$ are moved by elements of $A_\lambda$.
I would like to find a subgroup $L \lt A_\lambda$ such that $A_\lambda/L$ is countable. I considered using the subgroup that fixes a specific countable subset $\omega \hookrightarrow \lambda$, but from my back-of-envelope scribblings this didn't seem to work out - or I just couldn't see it!
Since $|A_\lambda| = \lambda$, we need $|L| = \lambda$ also, which puts constraints on what $L$ can be.


text:
Q: Use a single pod in swift In my project I've around 20-30 PODS and all of them are in OBJECTIVE-C.
In some of the pods I've changed some pieces of code due to requirement.
Now I want to add a pod which is only written in swift. Is it possible to use swift for only that specific pod ? I don't want to use "use_framework" as it will force all other pods to use static frameworks.

A: Currently use_framework! is either all or none. There is currently an open issue to change that.
Swift static library support will be added in CocoaPods 1.5.0 so that is likely to be the soonest route to a solution for you, but still a ways off.

A: With the release of cocoapods 1.5.0. Not it's possible to use only a single swift pods. From official docs
you can add use_modular_headers! to enable the stricter search paths and
module map generation for all of your pods,
or you can add :modular_headers => true to a single pod declaration
to enable for only that pod.

By this we can improve store submission time. Here is the official doc page Cocoapods 1.5.0.


text:
Q: Displaying text in SVG using Java I am successfully drawing a line in an svg using java. The line tag or name is shown using a GWT label in a div containing the svg. Is there a way to display tag using svg itself? (without using label and div's)

A: OMSVGTextElement element;
private OMSVGSVGElement svgElement;
svgElement = doc.createSVGSVGElement();
element=doc.createSVGTextElement();
element.getElement().setInnerText("link label"); //the label
svgElement.appendChild(element);

This should do.


text:
Q: How can I restrict the size of my \multicolumn cells in a longtable? I have a really long table in LaTeX that spans several pages and is (as it is now) also too wide for the page.
I am using the longtable package with every column width specified with the p{width} command.
The problem is, that most of the rows contain a multicolumn call, and thus are not adhering to the preamble p{width} command, which causes the total width of the table to be too large.
Minimal example:
\begin{longtable}{|p{1in}|p{0.75in}|p{0.5in}|p{0.5in}|>{p{1in}|p{1in}|}
\caption{some cap} \label{somelable}\\
\hline
\multicolumn{2}{|c|}{\textbf{Text Header One}} & \multicolumn{2}{|c|}{\textbf{Text Header Two}} & \multirow{2}{*}{\textbf{Three}} & \multirow{2}{*}{\textbf{Four}} \tabularnewline \cline{1-4}
\textbf{Five} & \textbf{Six} & \textbf{Seven} & \textbf{Eight} &  & \tabularnewline \hline
Some Text String & Longer Text String Here & More Text Here & Text Example & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hlineExample Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & \multicolumn{2}{|l|}{Multi-column Text String that doesn't fit column width} & Text & Text \tabularnewline \hline
Example Text String Two & Longer Text String Example Two & width of box & text & Text & Text  \tabularnewline \hline
\end{longtable}

I am loading longtable in my preamble, and running pdflatex several times (as outlined in the longtable documentation). It compiles with 0 warnings and 0 errors.
How can I get normal "narrow" cells?

A: Have you tried using |p{<sum of widths>}| for the formatting option to \multicolumn?
Just guessing here.

A: You have to give a size parameter to multicolumns even though there is a preamble size. The next example is a multicolumn cell of the size of the table width:
\begin{tabular}{p{0.3\textwidth} p{0.7\textwidth}}
\multicolumn{2}{ p{\textwidth}} {YOUR TEXT HERE}
\end{tabular}

A: \begin{longtable}{p{2.8cm} p{2.8cm} worked for me..


text:
Q: Подсчет частоты вхождения пар значений в строках DataFrame Всем привет!
Интересует как правильно и красиво написать python code.
Возможно ли для решения ниже приведенной задачи использовать только функции pandas или другие библиотеки и не использовать циклы for/while?
Как написать с помощью for я знаю, но решение мне кажется громозким.
Задача - для всех возможных комбинаций букв AB, AC, ..., XY, XZ, YZ подсчитать в скольких строках встречалась каждая комбинация букв. Буквы в строках предварительно надо отсортировать по возрастанию и по условию задачи буквы в строке не могут повторяться.
Из результата нужно выбрать 10 наиболее часто встречаемых пар букв.
Входные данные
A, B, J, K
B, E, P, A
R, Z, A, B
K, L, M, A
X, A, J, K

Результата запроса
A,B,3
A,J,2
A,K,3
B,J,1
B,K,1

и т.д.

A: Сначала нам понадобятся все комбинации пар столбцов:
import numpy as np
import pandas as pd
from itertools import combinations

cc = list(combinations(df.columns,2))

получилось:
In [39]: cc
Out[39]: [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

теперь можно найти все встречающиеся пары букв:
t = np.concatenate([np.sort(df.loc[:, c], axis=1).sum(1) for c in cc])

получилось:
In [43]: t
Out[43]:
array(['AB', 'BE', 'RZ', 'KL', 'AX', 'AJ', 'BP', 'AR', 'KM', 'JX', 'AK', 'AB', 'BR', 'AK', 'KX', 'BJ', 'EP', 'AZ', 'LM', 'AJ', 'BK', 'AE', 'BZ', 'AL', 'AK', 'JK', 'AP', 'AB', 'AM', 'JK'],
      dtype=object)

теперь можно воспользоваться collections.Counter:
from collections import Counter

res = Counter(t).most_common(10)

результат:
In [46]: res
Out[46]:
[('AB', 3),
 ('AK', 3),
 ('AJ', 2),
 ('JK', 2),
 ('BE', 1),
 ('RZ', 1),
 ('KL', 1),
 ('AX', 1),
 ('BP', 1),
 ('AR', 1)]

Также можно создать Series из t и воспользоваться стандартными методами Pandas вместо испольования collections.Counter:
s = pd.Series(t)
res = s.groupby(s).size().nlargest(10)

результат:
In [49]: res
Out[49]:
AB    3
AK    3
AJ    2
JK    2
AE    1
AL    1
AM    1
AP    1
AR    1
AX    1
dtype: int64

Исходный DataFrame:
In [51]: df
Out[51]:
   0  1  2  3
0  A  B  J  K
1  B  E  P  A
2  R  Z  A  B
3  K  L  M  A
4  X  A  J  K


text:
Q: How to replace the tags in a XML i have a xml tag like :

Text1CPText2CP

If i have to replace the tag CPText2CP  with
<componentpresentation componentID="1234" templateID="1111" dcpID="dcp1111_1234" dcplocation="/wip/data/pub60/dcp/txt/dcp1111_1234.txt">Text2</componentpresentation>
Is any possible way to acchive this, please give suggestion/changes.
EDIT
From the above tag can i take full  tag as a string with the text in between the tags.any suggestions.

A: You can do it like this:
        string input = @"

                Text1

                    CPText2CP

";

        XDocument doc = XDocument.Parse(input);
        XNamespace ns = doc.Root.Name.Namespace;

        // I don't know what filtering criteria you want to use to
        // identify the element that you wish to replace,
        // I just searched by "componentId=1234" inside title attribute
        XElement elToReplace = doc
            .Root
            .Descendants()
            .FirstOrDefault(el =>
                el.Name == ns + "span"
                && el.Attribute("title").Value.Contains("componentId=1234"));

        XElement newEl = new XElement(ns + "componentpresentation");

        newEl.SetAttributeValue("componentID", "1234");
        newEl.SetAttributeValue("templateID", "1111");
        newEl.SetAttributeValue("dcpID", "dcp1111_1234");
        newEl.SetAttributeValue("dcplocation",
            "/wip/data/pub60/dcp/txt/dcp1111_1234.txt");

        elToReplace.ReplaceWith(newEl);

Your needs may vary but the way to go would be to create XDocument or XElement, search through it to find elements that need to be replaced and then use ReplaceWith to replace them. Note that you have to take namespaces into consideration, otherwise elements won't be retrieved.

A: Yes.
Do the following:

*

*Read the File (As XML or plain Text)

*Search for the Tag / Sequence or a substring of it

*Replace the Sequence with the new one


text:
Q: getting a custom error error message and redirect url from jqXhR in grails and ajax I'm working on a grails project and can't for the life of me figure out how to accomplish this task.  Basically I have a page that fires an ajax request to a controller.  The controller then checks to see if the resource is valid and sends back a 410 to the client implying that the resource is gone.  The client then opens a jquery dialog and tells the user he's going to get redirected because the resource is invalid. Here's the code I'm using to do that:
response.setStatus(410, message)
   def message =message(code:'default.listing.expired.message', args:[email]).toString()
    response.setStatus(410, message)
    forward action:"list"
    return

So I'm expecting to see my customer message when I do jqXHR.statusText but I just get the stock HTTP "Gone" message.  Also, how do I access the URL the server is forwarding to (forward action:"list") ?

A: You should respond with an JSON (or XML, or anything that you can easily read on client side), try:
response.setStatus(410) //set response status
def data = [
  message: message(code:'default.listing.expired.message', args:[email]).toString(),
  link: createLinkTo(action: 'list')
]
render(data as JSON) //send response data as JSON


text:
Q: Lower Right white box In Ubuntu 12.10 there is a small type box that appears in the lower right when I just start typing from the desktop.
What is it? and how am I supposed to use it?
Ric

A: The box that appears is a "type ahead" feature. It will automatically highlight items on your desktop that match your input.
In example:
As I typed "egg" it matched the first item with that filename.

A: It is used for quick searching and access to files and folders.
You can type any key on keyboard, the first file(alphabetically) starting with that character will be highlighted.You can press enter to open the file/folder.
You can use up and down arrow keys to surf between all files/folders starting with that character.


text:
Q: How can I estimate a state-action matrix for q-learning when I do not have complete knowledge of all possible spaces and actions? In this example of q-learning the "state-action" matrix R can be easily defined since there is a limited number of possible actions in each state and they are easy to identify. This example is very simple and I was able to make a simulaton using Python within minutes I read the article.
However, suppose that you do not know the entire "state-action" matrix R and consider the following complications/hypothesis:

*

*Available actions in each state are stochastic. Probabilities of what actions might be available in a certain state can be estimated by making the agent exploring the state-space.

*You do not have a full knowledge of all the possible states (say for instance it is not practical to try to gather it).

*You know the outcome you want but there isn't any, as far as you can tell, a clear deterministic strategy to get the best outcome. That is, such strategy might exist but it may not be obvious and cannot be "hard coded" For instance in the example of q-learning I mentioned, the optimal strategy can be "hard coded" using a sequence of if-else statement.

My question is, how could I get an estimate of the R matrix? Could you provide me with some of the most standard approaches (say 2 at most, although 1 is enough) used in these cases, so that I can try to make a simulation?
I wonder if Markov Chains could be useful, but I'm not really sure.
I understand that this problem is a variation of the one in the example here however I really cannot get my head around it.

A: The reward, $R: \mathcal{S} \times \mathcal{A} \rightarrow \mathbb{R}$ and transition, $T: \mathcal{S} \times \mathcal{A} \times \mathcal{S} \rightarrow \mathbb{R}$ are functions, which means in the most general sense you cannot represent them as matrices(unless you have some infinite dimensional matrices). What you can define is functions that evaluate these quantities on demand, i.e.
def R(state, action):
   # do something
   return R

You can implement your algorithms (e.g. PI, Q-learning, etc) to use such an interface and then you wont have to specify the matrices at all. This also works for continuous spaces.
For implementation examples see the following (NOTE: the package is a work in progress implementation)
https://github.com/makokal/funzo/blob/master/funzo/models/mdp.py
https://github.com/makokal/funzo/blob/master/funzo/planners/dp.py#L27


text:
Q: How do I extract the month and year from dates in a date column, within SAS? I formatted the date column within my table, using the following code;
data data1;
set data;
format Date ddmmyy10.;
run;

I want to know how I can create a new column within my table which just extracts the month and year from the dates in the "Date" column.
How do I do this please?

A: in order to create new columns calculated by existing Date column you should try this:
data data1;
set  data;
format Date ddmmyy10.;
yearNo=year(Date);
monthNo=month(Date);
run;


text:
Q: IOS Map Pins are not Showing? I am struggling with my iOS code. The overall goal of the project is to show the pins on the map, I've tried multiple ways to make the pins appear on the map such as the below, I am not sure what I am doing wrong. The code runs fine, the pins are not appearing. I've made changes to my functions but seem to get the same error. Any insight on what I may be missing?
"import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var logout: UIBarButtonItem!
@IBOutlet weak var refresh: UIBarButtonItem!
@IBOutlet weak var pinDrop: UIBarButtonItem!

var studentLocation = [StudentInformation]()
var annotations = [MKPointAnnotation]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewDidAppear (_ animated: Bool) {
    super.viewDidAppear(true)
    getStudentPins()
}

@IBAction func refresh(_ sender: UIBarButtonItem) {
    getStudentPins ()
}
@IBAction func logout(_ sender: UIBarButtonItem) {
    self.activityIndicator.startAnimating()
    UdacityClient.logout {
        DispatchQueue.main.async {
            self.dismiss(animated: true, completion: nil)
            self.activityIndicator.stopAnimating()
        }
    }
}

@IBAction func addLocation(_ sender: Any) {
    performSegue(withIdentifier: "addLocation", sender: nil)
}

func getStudentPins () {
    self.activityIndicator.startAnimating()
    UdacityClient.getStudentLocations() { locations, error in
        self.mapView.removeAnnotations(self.annotations)
        self.annotations.removeAll()
        self.studentLocation = locations ?? []
        for dictionary in locations ?? [] {
            let latitude = CLLocationDegrees(dictionary.latitude ?? 0.0)
            let longitude = CLLocationDegrees(dictionary.longitude ?? 0.0)
            let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
            let firstName = dictionary.firstName
            let lastName = dictionary.lastName
            let mediaURL = dictionary.mediaURL
            let annotation = MKPointAnnotation()
            annotation.coordinate = coordinate
            annotation.title = "\(firstName) \(lastName)"
            annotation.subtitle = mediaURL
            self.annotations.append(annotation)
        }
        DispatchQueue.main.async {
            self.mapView.addAnnotations(self.annotations)
            self.activityIndicator.stopAnimating()
        }
    }
}

private func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotation? {
    let reuseId = "pin"
    var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView!.canShowCallout = true
        pinView!.pinTintColor = .green
        pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
    }
    else {
        pinView!.annotation = annotation
    }
    return pinView?.annotation
}

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if control == view.rightCalloutAccessoryView {
        if let toOpen = view.annotation?.subtitle {
            openLink(toOpen ?? "")
        }
    }
}

}"

A: They're called annotations in the MapKit and you should instantiate them like so:
let annotation = MKPointAnnotation()

then in the viewDidLoad() method just set the coordinates and add them to the map like:
annotation.coordinate = CLLocationCoordinate2D(latitude: 11.12, longitude: 12.11)
mapView.addAnnotation(annotation)

The numbers are your coordinates. Try by adding sample coordinates on the map first and then add all coordinates which you are getting from the client.
you can also add more information using:
annotation.title = "Your text here"
//You can also add a subtitle that displays under the annotation such as
annotation.subtitle = "One day I'll go here..."


text:
Q: How to stop a program using a port I want to use the port 12345 for hosting a server for an application I have, however the port is already in use by another program.
I have already tried:
netstat -anb

However, none of the programs listed use this port. Doing some research online I found out that Trend Micro Security uses this port. though I used to have this Anti-Virus software installed on my computer, I have long ago switched to Norton, and am still not able to use this port.
I use netgear, and have no problems using other ports.
Any help will be appreciated.
Mona.

A: NetGear has been known to have problems with port 12345. Try calling their support.
Belkin and Dlink work fine. So if possible, try changing your router to see if the problem goes away. If yes, then it is a router issue. If not, then contact your ISP since they block 12345 as well.


text:
Q: Accessing the address of an object in a pointer handle I am creating a pointer class, but I can't figure out how to return the value (address of the object pointed to) of the raw pointer handled by my class. My class is like this.
template<typename T>
class Ptr {
public:
    Ptr(T t) :p{&t} { }
T* operator->() { return p; }
T& operator*() { return *p; }
T& operator[](int i) { return p[i]; }
private:
T* p;
};

If I will do:
int x = 42;
Ptr<int> y = x;
std::cout << y; //should print the address (y.p).

I absolutely don't know what operator to overload so if I use "y" in any expression it will return the address of the object pointed to, just like what a raw pointer does. What should I do?

A: First off, your code has a bug. Your constructor is taking t by value, which means that p will store the address of the temporary t which will die at constructor exit (and the pointer will become dangling). You probably want this:
Ptr(T &t) : p{&t} {}

Even so, this means your pointer wrapper will be initialised by objects and not by pointers, which looks counter-intuitive. I'd change the constructor to accept a T*.
Second, you're asking how to get the "address of the raw pointer," but I assume you really want the "address stored in the raw pointer."
With this out of the way, let's turn to your question. There are several ways you can approach this.

*

*One is to give your class an implicit conversion to T*, like this:
operator T* () const
{ return p; }

That way, an implicit conversion from Ptr<T> to T* will exist and the compiler will use it wherever necessary, but that may be a bit more than you want.

*A more restricted version is to make the conversion explicit:
explicit operator T* () const
{ return p; }

Now you have to cast to the pointer explicitly:
std::cout << static_cast<int*>(y);

*You can follow the pattern used by std smart pointers and provide a get() function:
T* get() const
{ return p; }

std::cout << y.get();

*Finally, if you only want this functionality for streaming, you can just overload operator<< for your class:
template <class T, class Char, class Traits>
std::basic_ostream<Char, Traits>& operator<< (std::basic_ostream<Char, Traits> &stream, const Ptr<T> &ptr)
{
  return stream << ptr.operator->(); // or ptr.get(), if you implement it
}

A: You should overload operator T*().
Note that the pointer you're storing is a pointer to the parameter and becomes invalid as soon as the constructor returns, so dereferencing it anywhere causes your program to be undefined.
You probably want
Ptr(T* t) : p{t} { }

and
Ptr<int> y = &x;


text:
Q: About Higher Order Fourier Analysis This quastion is about the extension of Fourier analysis to higher orders. I know this is the approach to go beyond the linear phases. I am curious to understand it better. To be specific,

*

*Is it possible to briefly explain the higher order Fourier analysis with giving some clear mathematical representation of that analysis (just like the traditional form)?

*Would you please provide some applications of the higher order Forier analysis?
Thanks.


text:
Q: sending notifications with alarmmanager and Broadcast receiver Actually I have implemented notifications for my app.Whenever I click a button it set the time for notification and call broadcast receiver.but when the request for 3 notifications like one for 3 pm,4 pm,5 pm is sent it send only 5 pm notification not 3 pm and 4 pm because 5 pm one was triggered last. I think it is related with notification id. I am passing id as 0.what I should do.please help.
my broadcast receiver
public class NotificationMessage extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent arg1) {
        Log.d("Tag","dd");
        showNotification(context);
    }

    private void showNotification(Context context) {
        Log.d("Tag", "visible");

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.logo)
                        .setContentTitle("HURRY UP!!")
                        .setContentText("You have a session in 15 minutes.");
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        int notiid = preferences.getInt("Id", -1 );

        int notification_id = notiid;
        Log.d("ID1", String.valueOf(notification_id));

        mNotificationManager.notify(notification_id, mBuilder.build());
        Log.d("Tag","fuck u");
    }
}

this is where I am calling:
holder.accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                Call<AcceptedDealResponse> call = service.acceptedDeal(acceptDealRequest);
                call.enqueue(new Callback<AcceptedDealResponse>() {
                    @Override
                    public void onResponse(Call<AcceptedDealResponse> call, Response<AcceptedDealResponse> response) {
                        AcceptedDealResponse response1 = response.body();
                        if(response.body().getMessage().equals("Successful !! Deal Booked !!")){
                            Log.d(",,", "" + " deal boooked");

                            Log.d("jkhdjksahda  ","" + newDealResponsess.getResponses().get(position).getTimeFrom() );

                            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                            try {
                                date1 = formatter.parse(String.valueOf(newDealResponsess.getResponses().get(position).getTimeFrom()));

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            cal = Calendar.getInstance();
                            cal.setTime(date1);

                            Log.d("Tag", String.valueOf(cal.get(Calendar.DATE)));

                            calendar = Calendar.getInstance();

                            calendar.set(Calendar.YEAR, cal.get(Calendar.YEAR));
                            calendar.set(Calendar.MONTH, cal.get(Calendar.MONTH));
                            calendar.set(Calendar.DATE, cal.get(Calendar.DATE));
                            calendar.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
                            calendar.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
                            calendar.set(Calendar.SECOND, cal.get(Calendar.SECOND));

                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.HOUR_OF_DAY));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.MINUTE));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.SECOND));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.DATE));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.MONTH));
                            Log.d("hdfbsdhbfs :", "" + calendar.get(Calendar.YEAR));

                            Intent notificationmassage = new Intent(v.getContext(),NotificationMessage.class);

                            Log.d("Tag","cool");

                            PendingIntent pi = PendingIntent.getBroadcast(v.getContext(), 0,notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT);

                            Log.d("Tag","cooled");
                            AlarmManager am = (AlarmManager) v.getContext().getSystemService(ALARM_SERVICE);
                            Log.d("Tag","cooooled");

                            int id = (int) calendar.getTimeInMillis();

                            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(v.getContext());
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putInt("Id", id);
                            Log.d("ID", String.valueOf(id));
                            editor.apply();

                            am.set(AlarmManager.RTC_WAKEUP, (calendar.getTimeInMillis() - 900000), pi);

A: I guess the problem is in your PendingIntent with same REQUEST_CODE. May be you have used same REQUEST_CODE with your PendingInetent for all alarm when setting an alarm using AlarmManager.

Try using different REQUEST_CODE for different PendingIntent for
  different Alarm.

Use below code for setting Alarm using AlarmManager:
    int notiId = UNIQUE_ID;

    // Intent
    Intent mIntent = new Intent(getApplicationContext(), NotificationMessage.class);
    mIntent.putExtra("NOTIFICATION_ID", notiId);

    // Pending broadcast intent
    PendingIntent mPI = PendingIntent.getBroadcast(getApplicationContext(),
                        notiId, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Alarm manager
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, TARGET_TIME_MILLISECONDS, mPI);

Hope this will work~


text:
Q: How to get MSE of ARIMA model in SAS? I am comparing two models, one with exponential smoothing and one with ARIMA.
For this specific assignment, it's enough that I compare the MSE of the two models.
So how do I compute the MSE of the ARIMA procedure?
This is the last assignment on this grueling course, help would be greatly appreciated!

A: proc arima does not specifically output the MSE, but proc model does. You can recreate the ARIMA model using proc model and the %AR and %MA macros.
proc model data=have;
    endo y;
    id date;

    y = mu;
    %AR(AR, 1, y, m=ML);
    %MA(MA, 1, y, m=ML);

    fit y;
run;

This specifies an ML-estimated ARMA(1,0,1) model with an intercept, mu.
proc model will then output the MSE of your model. Note that %MA must come after %AR, and both the %AR and %MA macros must come after the equation.
If you need a more complicated lag structure, you can specify additional options in either macro:
%AR(AR, 3, y, 1 3, M=ML)
This creates ML-estimated AR variables of order 3 whose variable prefix is AR using a subset of lags 1 and 3.
Here is an example of output using sashelp.air with the %AR macro:

Note that any differencing must be performed in a data step before entering proc model.


text:
Q: Fb like share box in drupal website I am making a drupal website and have a content type "quotation". The standard way of taking input in drupal is going to the create content in the menu which is not very user friendly considering your normal user.
I want to have an option to create content (i.e quotation) like in facebook, twitter or any other social networking site. A share box where someone can type in his status and can directly create content.
Also, I have two vocabularies associated with my content type and I want to accommodate them as well while using minimum space. So, how should I go about the problem.
Is there any module in Drupal which can help me in doing so   or  I have to write Jquery code myself.

A:
two vocabularies associated with my
  content type and I want to accommodate
  them as well while using minimum
  space.

Lol, sounds tough. If you want to use minimal space you'll need to simplify the workflow, ie, remove a vocabulary or 2.
You can also do something like this:
$('#node-edit').focus(function (){
// set your node form vocab to display:none and then show them when user actually uses the form
    $('.vocab-wrappers').show();
// set your node form  buttons to display:none and then show them when user actually uses the form
    $('#node-form buttons').show();
});

To hide the vocabularies/buttons until the user is editing the content.
To get a facebook like effect, I suggest you use: http://drupal.org/project/formblock
This should get you the form and the ability to place it anywhere.
You can use form alter to hide certain parts of the form, or a form alter module, there's various options if you look in drupal modules.
http://drupal.org/project/nodeformcols
You also want http://drupal.org/project/auto_nodetitle to make the title optional, and hidden from the form.
Lastly, theme the node form in CSS/JS, making the texarea smaller and whatever other stuff you would like, recommend setting display:none on the field labels.
This should give you the correct idea for making a decent facebook-like form setup.

A: This should be possible:
http://drupal.org/node/464906
I've never tried it myself though.