Q:

How to generate path of a file residing on another computer

I load data from a Database on another PC in local network , and it works perfectly fine.
I just enter server name and db path and it works.
Now i am also looking for latest modified file in the folder on the server ,it works fine on local pc but when i use a server name  plus path , it generate that path concatenated with the executable folder path.
string tmpPath=string.Empty;
if (serverName != "")
  {
   tmpPath = "\\" + serverName + "\\" + TrackingPath + "\\u00" + ID;
  }

And after this i simply read the folder to get latest modified file.
But the path becomes  ....Debug\servername\trackingpath..... which is wrong.
EXAMPLE
Servename=testServer
TrackingPath= TmpFolder\SharedFolder\TrackingFolder

So according to my code it should become  \\testServer\\TmpFolder\SharedFolder\TrackingFolder but instead it make it   project....\Debug\\\testServer\\TmpFolder\SharedFolder\TrackingFolder
So how can i read this folder from testserver

A:

Use Path.Combine to work with path files and remember that the backslash is a special character in C# and it is used to escape other chars. So you need
string ID = "test";
string TrackingPath = "tracking";
string serverName = "server_name";
string tmpPath=string.Empty;
if (serverName != "")
{
    tmpPath = Path.Combine(@"\\", serverName, TrackingPath ,"u00" + ID);
}
Console.WriteLine(tmpPath);

To insert a backslash in a string you need to double it or prefix with the Verbatim string prefix character @
Using 3.5 Framework and below
    tmpPath = Path.Combine(Path.Combine(Path.Combine(@"\\", serverName), TrackingPath) ,"u00" + ID);

Well not very efficient but it works


Q:

How to get the MAC address of the visitors' PC in an ASP.NET webApp?

In an ASP.NET (C#) WebApp, I can get the IP of the visitors' PC easily, But How to get the MAC address of the visitors' PC in an ASP.NET webApp?
And this ASP.NET app is runing on the inner intranet of our company, and the visitors are also in the same inner intranet of our company.

A:

The MAC address is not part of the IP header (or any other protocols above that), and thus not available if all you see is the HTTP traffic.
EDIT (after OP's update): Since clients and servers are on the same internal network, wouldn't it be better to get a host name from the IP address instead of the MAC address? You can easily look up the host name based on the IP address.

A:

The answer that immediately comes to mind, is that this is only possible if you write an ActiveX control that runs in the client browser to obtain this information on your behalf. On the other hand it might be possible with JavaScript on the client if the javascript can instantiate a COM object that will get the information. The only other way I can think of is have a windows service that does an ARP request once the IP has been captured.


Q:

Drools Question about equality in memberOf and contains

I would appreciate if someone would explain how memberOf and contains evaluates equality between objects.
  rule "Compare orders"
  when
    $u:   User( $order: order )
    Order( $order memberOf orderLines )
  then
 //do stuff
  end

In this example I found , how does the engine determine the user's order is a memberOf the order lines?
Thank you

A:

The memberOf operator is implemented by the following method: ContainsOperator.eval(). This method uses Collection.contains() to do the check.
Hope it helps,


Q:

IllegalStateException in Google Play Game Service doesn't make sense

I have a game in the Play Market and I got the message and stacktrace back.
java.lang.IllegalStateException
Msg: (Not connected. Call connect() and wait for onConnected() to be called.)

java.lang.IllegalStateException
com.google.android.gms.internal.p.n(Unknown Source)
com.google.android.gms.internal.p.o(Unknown Source)
com.google.android.gms.internal.e.loadState(Unknown Source)
com.google.android.gms.appstate.AppStateClient.loadState(Unknown Source)
com.peerkesoftware.blockcrusher.CloudSave.load(CloudSave.java:31)
com.peerkesoftware.blockcrusher.CloudSave.setAppStateClient(CloudSave.java:26)
com.peerkesoftware.blockcrusher.MorburActivity.onSignInSucceeded(MorburActivity.java:475)
com.peerkesoftware.libgeneric.app.game.GameHelper.succeedSignIn(GameHelper.java:652)
com.peerkesoftware.libgeneric.app.game.GameHelper.connectNextClient(GameHelper.java:539)
com.peerkesoftware.libgeneric.app.game.GameHelper.onConnected(GameHelper.java:642)
com.google.android.gms.internal.p.k(Unknown Source)
com.google.android.gms.internal.bj.k(Unknown Source)
com.google.android.gms.internal.p$f.a(Unknown Source)
com.google.android.gms.internal.p$f.a(Unknown Source)
com.google.android.gms.internal.p$b.p(Unknown Source)
com.google.android.gms.internal.p$a.handleMessage(Unknown Source)
android.os.Handler.dispatchMessage(Handler.java:99)
android.os.Looper.loop(Looper.java:132)
android.app.ActivityThread.main(ActivityThread.java:4126)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:491)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
dalvik.system.NativeStart.main(Native Method)

The strange thing is the message saying that the I should call connect() and wait for the onConnected(). But as you can see in the stacktrace the call is coming from the onConnected(). So I know for sure Google Play Services is connected. Why do I still get the IllegalStateException? I doesn't make sense.

A:

There are cases where android.gms.internal throws IllegalStateException even when you use the API correctly. E.g. the trace below logs that all the clients connect and it is while handling google's succeedSignIn() callback to our code that we get that exception. (SwGameHelper is our copy of google's GameHelper code)
Note that the gms.internal stack trace appears to include some methods with the name "signOut". So this could be a bug with the google code, but my guess is it's a race condition where the connection is being lost immediately after connection. I have had to deal with similar races on other connected services. If it's a race google may just need to document better that this exception can be thrown by their methods even if you were connected when you called them.
I'm considering work-arounds where we catch this. I'll update if I find a good fix.
This is one of our most common crashing bugs with installed customers so it's not that rare.
onConnected: connected! client=1 com.lootworks.swords.screens.SwGameHelper
Connecting PlusClient. com.lootworks.swords.screens.SwGameHelper
onConnected: connected! client=2 com.lootworks.swords.screens.SwGameHelper
All clients now connected. Sign-in successful. com.lootworks.swords.screens.SwGameHelper
All requested clients connected. Sign-in succeeded! com.lootworks.swords.screens.SwGameHelper

java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
    at com.google.android.gms.internal.p.n(Unknown Source)
    at com.google.android.gms.internal.p.o(Unknown Source)
    at com.google.android.gms.internal.bj.a(Unknown Source)
                                       loadAchievements
                                       b
                                       a
                                       signOut
                                       a
                                       a
    at com.google.android.gms.games.GamesClient.loadAchievements(Unknown Source)
                                             signOut
    at com.lootworks.swords.social.SwAchievementManager.loadAndUploadAchievements(SourceFile:441)
    at com.lootworks.swords.activity.SwMap3D.onSignInSucceeded(SourceFile:3526)
    at com.lootworks.swords.screens.SwGameHelper.succeedSignIn(SourceFile:639)
    at com.lootworks.swords.screens.SwGameHelper.connectNextClient(SourceFile:530)
    at com.lootworks.swords.screens.SwGameHelper.onConnected(SourceFile:629)
    at com.google.android.gms.internal.p.k(Unknown Source)
    at com.google.android.gms.internal.bj.k(Unknown Source)
    at com.google.android.gms.internal.p$f.a(Unknown Source)
    at com.google.android.gms.internal.p$f.a(Unknown Source)
    at com.google.android.gms.internal.p$b.p(Unknown Source)
    at com.google.android.gms.internal.p$a.handleMessage(Unknown Source)
    at android.os.Handler.dispatchMessage(Handler.java:99)


Q:

Ebay API C# Cancel Order without AddDispute

So from looking at the link below I see that you can cancel an order by opening a dispute with the API.
Cancel eBay order via API
But I'm not looking to open a dispute for every cancellation.  What I would like to do is be able to programmatically cancel the order without opening a dispute.  It would seem that this should be possible since it is available in the GUI.  In the GUI if you look up your orders and click on the drop down of the orders screen you get a cancel button.  Then on the next screen it asks the reason for cancelling and gives you two options.  I can't seem to find documentation on this anywhere.  Everything I can find for cancelling an order with the API leads to the method of opening a dispute.  Does anyone know how to cancel an order with this method?

A:

I was able to figure out this can be accomplished by using the Post-Order API.
https://developer.ebay.com/Devzone/post-order/index.html
Look at the links under the Cancellation section.
UPDATING ANSWER WITH CODE EXAMPLE FOR KEVINUK:
This is my working example.  I use it as a bool to let me know whether or not the cancellation request was successful or not so that I can see where to go from there.
    /// <summary>
    ///
    /// </summary>
    /// <param name="authToken"></param>
    /// <param name="ebayFullOrderId"></param>
    /// <param name="reason">Must be BUYER_ASKED_CANCEL or ADDRESS_ISSUES</param>
    private static bool Cancellation_SubmitCancelRequest(string authToken, string ebayFullOrderId, string reason)
    {
        var status = false;
        const string url = "https://api.ebay.com/post-order/v2/cancellation";

        var cancelOrderRequest = (HttpWebRequest)WebRequest.Create(url);

        cancelOrderRequest.Headers.Add("Authorization", "TOKEN " + authToken);
        cancelOrderRequest.ContentType = "application/json";
        cancelOrderRequest.Accept = "application/json";
        cancelOrderRequest.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY_US");
        cancelOrderRequest.Method = "POST";

        //cancelOrderRequest.Headers.Add("legacyOrderId", ebayFullOrderId);

        using (var streamWriter = new StreamWriter(cancelOrderRequest.GetRequestStream()))
        {
            string json = "{\"legacyOrderId\":\"" + ebayFullOrderId + "\",\"cancelReason\":\"" + reason + "\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var response = (HttpWebResponse)cancelOrderRequest.GetResponse();

        string result;
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }
        var reader = new JsonTextReader(new StringReader(result));

        while (reader.Read())
        {
            if (reader.Value != null)
            {
                var pt = reader.Path;
                var val = reader.Value.ToString();

                var isNumeric = !string.IsNullOrEmpty(val) && val.All(Char.IsDigit);
                if (pt == "cancelId" & isNumeric == true)
                {
                    status = true;
                    break;
                }
            }
        }
        return status;
    }


Q:

Disable gzip content-encoding in android simulator

I was trying to read the HTTP messages between the browser in the Android simulator and other third party web-servers using tcpdump. However, since the browser can accept gzip content-encoding, I can't see the HTML content as plain-text in the tcpdump output. Is there a way to change the configs of the browser so that it doesn't send that Accept-Encoding: gzip header line?

A:

This post implies if you remove the
Accept-Encoding

header, you'll get raw data back... you should be able to write a custom WebView that never sends that header.  Hope that works!
http://forgetmenotes.blogspot.com/2009/05/how-to-disable-gzip-compression-in.html


Q:

projective tensor product of smooth functions

Let $M$ and $N$ be compact smooth manifolds. Is it true, that
$C^{\infty}(M) \otimes_{\pi} C^{\infty}(N) \cong C^{\infty}(M \times N)$ as topological vectorspaces if endowed with the familiy of seminorms given by the suprema of differentials of the function over the respective spaces? If yes, is there a reference or easy explanation for this?

A:

This is indeed true and can be found in many texts,e.g., "Topological vector spaces, distributions and kernels" by F Treves, but also in Köthe's two volume treatise or Pietsch' "Nuclear spaces".  If you are interested in the original citation, it is probably "Espaces de fonctions différentiables a valeurs vectorielles" Jour. d' Anal. Math. 4 (1954-6) 88-148 by L. Schwartz.  Such topics are also discussed in detail in Grothendieck's thesis (appeared in the series "Memoirs of the American Math. Soc.") Warning: some of these texts might confine themselves to the case of subsets of euclidean space rather than the abstract setting of smooth manifolds---I have no access to the sources to check this at the moment---but the transition from the concrete setting to the abstract one is a standard partition of unity argument.


Q:

Sending a file through FTP to a share-drive (UNC)

I have a particular file which needs to be sent to a share drive location through FTP.
I know there is a method by writing contents on a flat file and executing with shell script. Sadly that is not working since my send location is weird and I don't know how to interpret it, its like this.
//corporate.abc.com/data/ac/ny/log

I have no idea what the above thing means. Is there any way to send data to that location?
PS: I opened it through my Windows Run command and its opening up. It is not asking for any user authentication.
Update: I tried to open using explorer but I am getting error" runtime  error 75 , path/file access error"
Sub FtpFileto()
Dim vFile As String
Dim vFTPServ As String
Dim fNum As Long
vPath = "C:\macro/pop.txt"
vFile = "C:\macro/post.xlsx"
vFTPServ = "corporate.abc.com"
Open "//corporate.abc.com/data/NA/US/OC/Common/HOSTDL/CatSpec" For Output As #1
Close
Shell "ftp -n -i -g -s:" & vPath & "\FtpComm.txt " & vFTPServ, vbNormalNoFocus
End Sub

A:

If the UNC path can be opened in Windows Explorer, it means that it is directly accessible and can be worked with as if it were a local path.
Open "\\corporate.abc.com\data\ac\ny\log\test.ext" For Output As #1
Write #1, Data
Close #1

You do not need (cannot) use FTP to work with it.

Note that the UNC is a Windows convention, so it uses backslashes, not forward slashes (though in many cases Windows will accept the forward slashes too).


Q:

Inner div 100% width of parent div exceeds bounds

My inner #div_mainPanel is 100% width, but if you look at the right-bottom corner it's over the parent div. I have tried removing width: 100 from the inner div and the width problem is solved, but not height.
Why does it display outside of the parent div if I have set width to 100% and margin/padding is set to 0px?
Thanks in advance

#div_mainContainer {
  width: 500px;
  height: 300px;
  background-color: #f8f8f8;
  border: 1px solid red;
  margin: 0px;
  padding: 0px;
}

#div_mainPanel {
  width: 100%;
  height: 100%;
  margin: 0px;
  border: 1px solid yellow;
}

A:

Borders count for sizing calculations. Your inner div picks up 100% of the height/width of the parent, so it becomes 500x300, but then adds 2px all around for the border, so it's really 502x302 and leaks over the parent's border on the right/bottom edges.

A:

This is correct behaviour. The inner div is set to 100% width of the parent, but this does not include the border on it, so it is 100% + 2px.
To prevent the inner div being displayed outside the bounds of the parent, add box-sizing: border-box to both the parent and the child:

#div_mainContainer {
  width: 500px;
  height: 300px;
  background-color: #f8f8f8;
  border: 1px solid red;
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

#div_mainPanel {
  width: 100%;
  height: 100%;
  margin: 0px;
  border: 1px solid yellow;
  box-sizing: border-box;
}

A:

There is now a much better way to solve this problem: use border-box sizing for your CSS:
http://paulirish.com/2012/box-sizing-border-box-ftw/
Now 100% will be a much more natural way to set sizes of child elements.


Q:

How does Liliana's Standard Bearer work if Kaervek the Spiteful is on the battlefield?

Let's say one creature has died this turn. I have Kaervek, the Spiteful on the battlefield, and then I flash in Liliana's Standard Bearer. This card has an enters-the-battlefield trigger which says "draw X cards where X is the number of creatures that died this turn".
Obviously the Standard Bearer is going to die immediately to Kaervek's static ability. When the enters-the-battlefield trigger resolves, does it count the Standard Bearer as a creature that died this turn?

A:

Yes, you will draw a card for the Standard Bearer as well. This is explained in the rulings under the card in Gatherer:

The value of X is determined only as the triggered ability resolves. If Liliana’s Standard Bearer dies while that ability’s on the stack, it will count itself.


Q:

MagSafe Power Cable Going Yellow

Well, my MBP cable has gone yellow after a while. I've tried cleaning it with water, and also toothpaste (with whitening) and that doesn't seem to have removed the yellow stains. I guess I'll try mouthwash next; I may have to gargle that myself first. Anyone have the same problem? I haven't been keeping it in unusual places, in my bag and on the desk.
On the left is the whiter clean cable.

A:

I got it replaced at the Apple Store. The "genius" explained that the old ones (pre-2011?) were softer and contained halogen from memory, whereas the new ones were more rigid and environmentally friendly. This probably means they don't change colour as easily and break.


Q:

Connect to FTP site using SFTP and download files

I need to download all the files from a FTP site. But i need to connect SFTP to connect. I am unable to find examples/tutorials to download files from the FTP site using SFTP to connect.
Can someone please point me to a tutorial or provide some sample code to begin with ?

A:

Tamir's SharpSSH library handles SFTP pretty well.  And there are plenty of examples, but the gist is:
Sftp sftp = new Sftp(sftpHost, sftpUser);
Console.WriteLine("success");

// assuming public/private key authentication here...
sftp.AddIdentityFile(privateKeyFileName, privateKeyFilePassPhrase);
sftp.Connect(sftpPort);
ArrayList files = sftp.GetFileList(".");
foreach (string file in files)
{
Console.WriteLine("\t{0}", file);
}

sftp.Close();


Q:

Redirect old links with parameters by .htaccess

Still working on my Joomla 2.5-site, now I realized old links on Google and on other sites I'd like to 301 rewrite:
http://www.my-site.com/index.php?p=26

to lead to
http://www.my-site.com/new-link.html

I tried
RewriteRule ^index.php?p=26$ /new-link.html [L,R=301]

but this didn't work.
I'd like to add that I need specific rewrites, e.g. index.php?p=26 --> new-link.html, ...p=99 --> another-link.html etc.

A:

No that won't work since you can't match QUERY_STRING in RewriteRule.
Try this rule:
RewriteCond %{THE_REQUEST} \s/+index\.php\?p=([^\s&]+) [NC]
RewriteRule ^ /new-link.html? [L,R=301]

EDIT:
Writing rules specific IDs:
RewriteCond %{THE_REQUEST} \s/+(?:index\.php)?\?p=26(?:&|\s) [NC]
RewriteRule ^ /new-link.html? [L,R=301]

RewriteCond %{THE_REQUEST} \s/+(?:index\.php)?\?p=12345(?:&|\s) [NC]
RewriteRule ^ /another-link.html? [L,R=301]


Q:

How to Toggle (or Scale) to reduce a DIV's vertical size (but only to 30% of initial height)

So I've got a DIV (a map) that goes across the width of the page, but i'd like to have a button users can click to "Hide/Unhide" the DIV that will basically do three things when clicked:

scale the vertical height of the div to 25% of the original height...
Change the DIV to have opacity .3 so its faded when at its reduced height...
Revert back to normal height & opacity (1) when clicked again

Here's what I've got so far: Currently it only scales down to the correct vertical height
Really appreciate the help...

    Map Content Is Here

HIDE MAP

A:

Try something like this:
var orig_height = $('#map').height();

$('.hidemap').click(function()
{
    if($('#map').height() == orig_height)
    {
        var new_height = Math.floor(orig_height * .25) + 'px';
        var new_opacity = '.3';
    }
    else
    {
        var new_height = orig_height + 'px';
        var new_opacity = '1';
    }
    $('#map').animate(
    {
        height: new_height,
        opacity: new_opacity
    },1000);
});

Working example: http://jsfiddle.net/X4NaV/


Q:

Calculating data transfer rate

Iv been given a question regarding data transfer rates and i am unsure of how to calculate to get the answer. If someone could explain the formula to be that would be great.
A disk with 2 double-sided platters rotates at 6000 rpm, has two hundred sectors per track,
and 500 bytes per sectors. The data transfer rate is: ___

A:

number of platters x (bytes x sectors)/(60/RPM) =
This is the formula.


Q:

Trying to avoid bad MySQL database design - can't figure out how to avoid too many columns

I am pretty much a beginner having only created a few small php web applications relying on a MySQL database. I am now working on a somewhat larger project. I am in the planning stages of setting up the database and am having difficulty wrapping my mind around one issue.
The database will be used for Lego. The main tables will be parts and sets. Under the sets table I will require a listing of the part numbers that are in each set as well as a listing for the quantity of those parts in the set. My limited knowledge of how to set this up would see me setting up something like...   part_1, part_2, part_3... etc & qty_1, qty_2, qty_3... etc. The problem with this is that there will be some sets that have hundreds of parts which makes the method I can think of unfeasibly messy. Also I would like to have the functionality for a user to be able to query the database and recover all sets that have a particular part. With the setup I have in mind I can't see this as possible as it would potentially require a search through 100+ columns.
I am sure there is a simple solution that my noobness cannot see and one which I cannot find online via the keyword searches I have been making (I am 4 hours into that search and have learned a lot but not what I wanted...). Any advice would be very greatly appreciated.
Apologies for not giving you code. The website will be done in PHP with a MySQL database. At the moment I am at the stage of drawings in a notebook and do not have anything coded down.

A:

Anytime you'd start getting a col1, col2, col3 in a database design, you "typically" want to consider those columns as rows in another table.  (typically, there are always exceptions - doubtful this is the case ;) )
So you have a LEGO_SETs and LEGO_PARTs table already ?
Sounds like you have something like this:
table: LEGO_SET
SET_ID
name
... etc ..
PART_1
QTY_1
PART_2
QTY_2
... etc.

table: LEGO_PART
PART_ID

You have here a many to many relationship. (ie A Lego_Set has many Lego_parts. A Lego_Part may belong to many Lego_sets).
You should have an interim table to help resolve this:
Remove the PART_1, QTY_1, etc. from LEGO_SET table and do this:
table: LEGO_PART_SET
SET_ID
PART_ID
QTY

that's it.
So if you have SET_ID 123, having Lego_parts 333 and 444.
You would have 2 rows in this table:
SET_ID  PART_ID  QTY
123     333       12
123     444       4

Hope that helps.
[edit]
Edited based on comments: Don't use SET table, avoid reserved words.
[/edit]


Q:

comparing, !== versus !=

I know that !== is used to compare variable types too, while != only compares values.
But I see that many people use !== when they compare values, for example:
$stuff = 'foo';
if($stuff !== 'foo') // do...

Is there any reason they do this? Is !== faster than != or what?

A:

It is wrong to say that != does only compare the value. Because it rather compares the types, applies a type conversion if necessary (see table of Comparison with Various Types) and then compares the (converted) values.
In contrast to that, !== fails earlier if the types are not equal and no type conversion is done.

A:

The != operator is a bit slower because it includes an implicit conversion if necessary,
while !== compares the types before and then the values (only if types are equals)
Also, follow this answer for further infos on the differences between the two operands

A:

If you do know in advance that both variables are of the same type, then it won't make any difference. I think the speed difference is just so negligible that the speed argument can (and should) be completely ignored, and you should focus on your application rather than focusing on premature (and unnecessary) optimization.
However, if you do have a requirement that and argument should be exactly what you expect (for example, === false when you don't want 0 to pass the equality test), then use === or !==.
As mentioned by Headshota, if you are working with objects, then === checks that the two variables actually point to the same object instance, whereas == tries to match them by value, which might lead to unexpected results and should be used with great care. Here the strict operator will be used because it means something to the application.
To answer your question, if in your particular context some people are using === or !== where you do know that both variables are of the same (scalar) type, then I guess it's just a matter of coding style, and shows a bit of strictness in the code, enforcing the idea that both variables are of the same type, probably not with performance in mind.
The strict operators have to be used when it means something to do so, not as a performance optimization.
Update: to reply to the speed argument, let's consider this small benchmark:
$a = "test";
$b = "test";

$t = microtime(true);
for ($i=0; $i<1e6; $i++) {
    ($a == $b);
    // (100x the equality test, omitted for clarity purposes,
    //  to lower the speed impact of the loop itself)
    ($a == $b);
}
printf('%.3f', microtime(true)-$t);

I roughly get:
6.6 seconds for ==
4.3 seconds for ===

Now if I use $b = 1; to force an implicit conversion, I get roughly:
4.4 seconds for ==
2.4 seconds for ===

This means roughly a 2 seconds gain in both cases. You might think, and you will be right in some way, that this is a demonstration of the speed advantage of the strict comparison operator. But don't forget that we are talking about 1e6 * 100 = 100 million iterations.
That means that a single strict comparison will speed up your script by 0.00000002 seconds.
If you think that this is something you should consider when writing your script, then do so. But you'll soon encounter other tiny optimizations that will give you 1000 times this speed gain, and make such "optimizations" look useless. This is a textbook case of premature optimization.
Again, use the strict comparison operators if you have to, because it is a requirement in your code. Do not use it for performance reasons.


Q:

Is there a tool to convert from a programming language to another?

Is there a solution [online or app] to convert a programming language to another one?
For example:

I have XAML code and I want to convert it to javaScript and otherwise.
I have C# code and I want to convert it to javaScript and otherwise.

A:

when doing web development you're able to translate ASP.NET and C# code to JavaScript using Script# http://projects.nikhilk.net/ScriptSharp
I think you should review the ideas behind each of the languages to get an understanding of their goals.

A:

In order to convert code both languages must be identical, for example C# to VB.
Converting languages that serve different purposes is not feasible, and the only options are tricky and full of errors.
You can look at this one: http://michaelsync.net/2007/10/29/script-c-to-javascript-converter

A:

look at this project (claims to do C#>Javascript :) also look at Script# see video here


Q:

How to change to another tab from inside of a tab?

Below is my html code,
what i wanna do is to give navigate from one tab to another from inside of any tab,by keeping link in it,as u can see below,but this is not happening when i try,instead nothing happens when i click links,i am unable to find any reason for this,
Pls. give me a simple solution for this,thank you, in advance.

Tab 1

Tab 2

Tab 3

        Your content goes here for tab 1
        Tab 2
        Tab 3

        Your content goes here for tab 2
        Tab 1
        Tab 2

        Your content goes here for tab 3
        Tab 1
        Tab 2

A:

Here is a jquery example using the data tag attribute that should get you pointed in the right direction jsFiddle.
HTML

Tab 1

Tab 2

Tab 3

        Your content goes here for tab 1
        Tab 2
        Tab 3

        Your content goes here for tab 2
        Tab 1
        Tab 3

        Your content goes here for tab 3
        Tab 1
        Tab 2

Javascript
$(document).on('click', '#tabs a', function(_e) {
    _e.preventDefault()
    // Get the tab to select
    var tabToSelect = $(this).data('tab');
    // Hide all the tabs
    $('#tabs > div').hide();
    // Show the selected tab
    $('#tabs-' + tabToSelect).show();
});


Q:

Use of "-wise" in phrases or words

What is -wise in phrases or words that end with it? How do we use it correctly?

Floor is obscenely expensive computational-wise.

I found a similar thread here
but I don't understand much.

A:

The question you referred to in yours gives more usage notes on when you should use the "-wise" suffix, but not so much in terms of what it means. In this case, "wise" is supposed to serve as a suffix which means:

with reference to: profitwise ; businesswise

The example you quoted would be less ambiguous if they had used "computation-wise". (Computational-wise seems ungrammatical to me). That is, the sentence is saying that:

Floor is obscenely expensive [in terms of] computation

or,

Floor is obscenely expensive computationally

A:

To quote a different source from the cited question, I'll use Dictionary.com:

a suffixal use of wise - in adverbs denoting manner, position, direction, reference, etc.: counterclockwise; edgewise; marketwise; timewise.

To simplify this definition, you can think of -wise as "in the direction of", "in the manner of" or "with regard to", depending on the situation.
The sentence you provided falls obviously in the third case.


Q:

wp insert post not working

my wp insert post not working. In post_title and post_name he not save the variable. So  at place of Service + variable , i get only "Service", why?
function mic_create_new_page() {
    global $user_ID;
        $new_post = array(
            'post_title' => 'Service ' . $secteur,
            'post_content' => '[makeitseo-keyword]',
            'post_status' => 'publish',
            'post_date' => date('Y-m-d H:i:s'),
            'post_author' => $user_ID,
            'post_type' => 'page',
            'post_name' => $slugmic
        );
    global $wpdb;
    $tableau_post = array ();
    $tableau_post = mic_stock_in_array($tableau_post);
$res = $wpdb->get_results('select * from wp_secteurs');
foreach ( $res as $ville ) {
    $id = $ville->id_secteurs;
    $secteur = $ville->libelle;
    $slugmic = strtolower(str_replace(" ","-",$secteur))."-s". $id ;
    if(!in_array(normalize($slugmic), $tableau_post))
        $post_id = wp_insert_post($new_post);
 }
}

A:

This is not how variables work in PHP. You're using them before they are defined.  They're not templates that will be replaced later. If you want to use those variables in $new_post then you need to define $new_post inside your loop after those variables are defined.
function mic_create_new_page() {
    global $user_ID, $wpdb;

    $tableau_post = array ();
    $tableau_post = mic_stock_in_array($tableau_post);

    $res = $wpdb->get_results('select * from wp_secteurs');

    foreach ( $res as $ville ) {
        $id       = $ville->id_secteurs;
        $secteur  = $ville->libelle;
        $slugmic  = strtolower( str_replace( " ", "-", $secteur ) ) . "-s" . $id;
        $new_post = array(
            'post_title'   => 'Service ' . $secteur,
            'post_content' => '[makeitseo-keyword]',
            'post_status'  => 'publish',
            'post_date'    => date('Y-m-d H:i:s'),
            'post_author ' => $user_ID,
            'post_type'    => 'page',
            'post_name'    => $slugmic
        );

        if ( ! in_array( normalize( $slugmic ), $tableau_post ) ) {
            $post_id = wp_insert_post( $new_post );
        }
    }
}

There's a few code smells in your code that stick out to me that I also want to point out:
Firstly, you're relying on a global variable, $user_ID. This is a bad idea because now your function is overly reliant on the global state, which makes its results unpredictable and hard to test. You should pass in the user ID as an argument to the function from somewhere where it's reliably defined as the user you want to use. For example, if you want to create this page whenever a user is registered using the user_register hook, then you should use the user ID that is passed into its callbacks:
function mic_create_new_page( $user_id ) {
    // Now $user_id is guaranteed to be the ID of the user being registered.
}
add_action( 'user_register', 'mic_create_new_page' );

Secondly, I can't figure out what this is supposed to do:
 $tableau_post = array ();
 $tableau_post = mic_stock_in_array($tableau_post);

I can't think of any reason why you'd initialise a variable like this, then pass it into a function only to replace the variable. I don't know enough about the code to offer any suggestions though, but I can't see any reason why just this wouldn't work:
 $tableau_post = mic_stock_in_array( array() );

But I suspect you might not even need all of that.


Q:

EWS error when retrieving complex property

We have an Exchange Web Services application that is throwing errors when an email is referenced that doesn't have a subject.
Our automated process needs to use the subject of the email, so the code is trying to reference it. However, when the subject is missing for an email in the inbox, instead of throwing an error, I want to change the behaviour.
Here is my code:
//creates an object that will represent the desired mailbox
Mailbox mb = new Mailbox(common.strInboxURL);

//creates a folder object that will point to inbox fold
FolderId fid = new FolderId(WellKnownFolderName.Inbox, mb);

... code removed fro brevity ...

// Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS.
FindItemsResults<Item> results = service.FindItems(fid, searchFilterCollection, view);

if (results.Count() > 0)
    {
    do
        {
        // set the prioperties we need for the entire result set
        view.PropertySet = new PropertySet(
            BasePropertySet.IdOnly,
            ItemSchema.Subject,
            ItemSchema.DateTimeReceived,
            ItemSchema.DisplayTo, EmailMessageSchema.ToRecipients,
            EmailMessageSchema.From, EmailMessageSchema.IsRead,
            EmailMessageSchema.HasAttachments, ItemSchema.MimeContent,
            EmailMessageSchema.Body, EmailMessageSchema.Sender,
            ItemSchema.Body) { RequestedBodyType = BodyType.Text };

        // load the properties for the entire batch
        service.LoadPropertiesForItems(results, view.PropertySet);

so in that code, the error is being thrown on the complex property get on the line service.LoadPropertiesForItems(results, view.PropertySet); at the end.
So, I know I am going to have to do something like a Try..Catch here, however, I would need to check that the Subject property of the mail item exists before I can reference it to see what it is - some kind of chicken and egg problem.
If there is no subject, I need to mark the email as read, send a warning email off to a team, and then gon onwith the next unread email in the mailbox.
Any suggestions about the best way to approach this would be appreciated.
Thanks

A:

Is the Subject not set or is it blank ?
You should be able to isolate any of these type of Emails with a SearchFitler eg use an Exists Search filter for the Subject property and then negate it so it will return any items where the Subject is not set
        SearchFilter sfSearchFilteri = new SearchFilter.Exists(ItemSchema.Subject);
        SearchFilter Negatesf = new SearchFilter.Not(sfSearchFilteri);

        service.FindItems(WellKnownFolderName.Inbox, Negatesf, new ItemView(1000));

Then just exclude those items from your LoadPropertiesForItems
Cheers
Glen


Q:

LINQ Order by column x and if empty take column y

I'm building a simple messaging system with the following data model:
public partial class Conversation
{
    public Conversation()
    {
        this.Messages = new HashSet<Message>();
        this.Customers = new HashSet<Customer>();
        this.MessagingHubConnections = new HashSet<MessagingHubConnection>();
    }

    public int Id { get; set; }
    public int BoatId { get; set; }
    public System.DateTime TimeCreated { get; set; }

    public virtual ICollection<Message> Messages { get; set; }
    public virtual Boat Boat { get; set; }
    public virtual ICollection<Customer> Customers { get; set; }
    public virtual ICollection<MessagingHubConnection> MessagingHubConnections { get; set; }
}

public partial class Message
{
    public int Id { get; set; }
    public int ConversationId { get; set; }
    public string Text { get; set; }
    public bool IsRead { get; set; }
    public System.DateTime TimeSend { get; set; }
    public int CustomerId { get; set; }

    public virtual Conversation Conversation { get; set; }
    public virtual Customer Customer { get; set; }
}

When a customer opens his account dashboard, I want to display a list of all the conversations. This should be ordered according to the following rule: The first conversation in the list is the one with a message with the latest Message.TimeSent. If the conversation has no messages, it has to pick the Conversation.TimeCreated.
The code below is what I have right now but this is obviously not working when a Conversation has no messages. The variable conversations in the code below is an IQueryable<Conversation>.
var orderedConversations = conversations.OrderByDescending(c => c.Messages.Max(m => m.TimeSend));

Anyone who can help me out?

A:

By projecting the TimeSend into DateTime? before Max()-ing it, you can obtain a (DateTime?)null when the collection is empty instead of getting an InvalidOperationException. And then, you can null-coalesce this result with TimeCreated:
var orderedConversations = conversations
    .OrderByDescending(c =>
        c.Messages
            .Select<Message, DateTime?>(x => x.TimeSend)
            .OrderByDescending(x => x)
            .FirstOrDefault() ??
        c.TimeCreated);


Q:

Passing custom List of data using Bundle

I'm developing a simple app, that contains tabview with fragment. I am stuck at the place, where i have to pass data to my newly created fragment on tabselect.
I have a List of  lists of my custom class objects:
List<List<NewsObjectClass>> myList;

Here is where I got stuck:
public static class PlaceholderFragment extends ListFragment{

    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment(){

    }

    public static PlaceholderFragment newInstance(int sectionNumber, List<List<NewsObjectsClass>> data)  {

        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);

        // Here i want to pass my List<List<NewsObjectClass>> to the bundle

        fragment.setArguments(args);
        return fragment;
    }
...

So specifically i need a way how to pass my list of lsits of myCustomObjects to the fragment, so there I could use it for lsitview adapter.
Any syggestions on how to pass this type of data would be great.
Thanks.

A:

args.putParcelableArrayList(DATA_KEY, new ArrayList<>(data));

A:

Make your NewObjectClass Parcelable or Serializable and then create a new class, effectively, containing your list, also Parcelable or Serializable. Then use Bundle.putSerializable (or putParcelable)
Or, simpler, make NewObjectClass Parcelable then use putParcelableArrayList if you can do with ArrayList instead of generic List
Or, simplest, make NewObjectClass Serializable and use putSerializable passing ArrayList<NewObjectClass> because ArrayList is Serializable
In the last case perhaps you only will have to ad implements Serializable to your class.
Alternatively, if your data seem to be large, consider keeping them in a custom Application-derived object instead. You extend Application and then such object will exist all the time your app exist. Don't forget to register it in manifest.
class MyApplication extends Application {
   public static Object myData;
}

Or you can do with shared preferences
PreferenceManager.getDefaultSharedPreferences().edit().putInt("a", 1).commit();
PreferenceManager.getDefaultSharedPreferences().getInt("a");

A:

use putSerializable method to pass your custom list.
args.putSerializable(KEY, ArrayList<Type>);

and fetch it using getSerializable
ArrayList<Type> list = (ArrayList<Type>) getArguments().getSerializable(KEY);


Q:

Why does autofit row VBA code in Excel keep causing #value error in my formula?

I have a concatenate based on offset array code that I'm using to combine data.
Public Function concatPlusIfs(rng As Range, sep As String, lgCritOffset1 As Long, lgCritOffset2 As Long, varCrit1 As Variant, lgCritOffset3 As Long, lgCritOffset4 As Long, varCrit2 As Variant, Optional noDup As Boolean = False, Optional skipEmpty As Boolean = False) As String

Dim CL As Range, strTemp As String

If noDup Then 'remove duplicates, use collection to avoid them

Dim newRow As New Collection

On Error Resume Next

For Each CL In rng.Cells
If skipEmpty = False Or Len(Trim(CL.Text)) > 0 Then
    If CL.Offset(lgCritOffset1, lgCritOffset2) = varCrit1 And CL.Offset(lgCritOffset3, lgCritOffset4) = varCrit2 Then newRow.Add CL.Text, CL.Text
End If
Next

For i = 0 To newRow.Count
strTemp = strTemp & newRow(i) & sep
Next

Else

For Each CL In rng.Cells
If skipEmpty = False Or Len(Trim(CL.Text)) > 0 Then
    If CL.Offset(lgCritOffset1, lgCritOffset2) = varCrit1 And CL.Offset(lgCritOffset3, lgCritOffset4) = varCrit2 Then strTemp = strTemp & CL.Text & sep
End If
Next

End If

concatPlusIfs = Left(strTemp, Len(strTemp) - Len(sep))

End Function

The code works great. It's not mine, but I tweaked someone else's code. The problem is that it will sometimes return a small amount of text and other times a large amount of text. I need the rows to autofit height. Before I started using the new concatPlusIfs formula, I used a code on the worksheet to autofit row height, but it cause a weird problem with the above code and only the above code and I can't find any mention of this type of problem. It works fine with all other arrays or non array formulas that I'm using. Basically what happens is that for a fraction of a second I can see the correct output in the cell and then I get #value!. I have no idea what's going on. I've tried autofit rows as a macro instead and it had the same effect. If I manually autofit the row everything is fine, but that's not a viable option.
Does anyone understand what would cause a problem like this? Or How can I fix it?
I'm not using any merged rows anywhere on the sheet.
Here are a few of the autofit strategies I've tried. One as a macro:
Sub AutoFit()

Worksheets("Sheet1").Range("A2:A" & Rows.Count).Rows.AutoFit

End Sub

Also as a code on the sheet,
Private Sub Worksheet_Change(ByVal Target As Range)
        Target.EntireRow.AutoFit
    End Sub

And,
Private Sub Worksheet_Calculate()
Application.EnableEvents = False
Me.Rows.AutoFit
'or be specific
Me.Rows("1:33").AutoFit
Application.EnableEvents = True
End Sub

Thank you for any help with this.

A:

You most likely get #VALUE! error when your formula tries to convert the ### from the .Text property to value. That is why you should use .Value2 or .Value instead.


Q:

How do I select all items in a listbox on checkbox checked?

I need to select all items in a ListBox when a CheckBox is clicked. Is it possible to select all items in the ListBox using a single line of code? Or will I have to loop through all items and set selected to true for each one of them?

A:

The fact is that ListBox.Items is a plain object collection and returns plain untyped objects, which cannot be multi-selected (by default).
If you want to multi-select all items, then this will work:
   for (int i = 0; i < myListBox.Items.Count;i++)
   {
       myListBox.SetSelected(i, true);
   }

A:

I have seen a number of (similar) answers all which does logically the same thing, and I was baffled why yet they all dont work for me. The key is setting listbox's SelectionMode to SelectionMode.MultiSimple. It doesn't work with SelectionMode.MultiExtended. Considering to select multiple items in a listbox, you will have selection mode set to multiple mode, and mostly people go for the conventional MultiExtended style, this answer should help a lot. And ya not a foreach, but for.
You should actually do this:
lb.SelectionMode = SelectionMode.MultiSimple;
for (int i = 0; i < lb.Items.Count; i++)
    lb.SetSelected(i, true);
lb.SelectionMode = //back to what you want

OR
lb.SelectionMode = SelectionMode.MultiSimple;
for (int i = 0; i < lb.Items.Count; i++)
    lb.SelectedIndices.Add(i);
lb.SelectionMode = //back to what you want

A:

As far as I can tell, using any of the .NET methods to select a large number of items is far slower than making a direct PInvoke call, passing the LB_SETSEL message (0x185) to the control, with a flag indicating whether you want to Select (1) or Unselect (0) as well as the magic value (-1) which indicates that the change should apply to all items.
  [DllImport("user32.dll", EntryPoint = "SendMessage")]
  internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);

  // Select All
  SendMessage(listBox.Handle, 0x185, (IntPtr)1, (IntPtr)(-1));

  // Unselect All
  SendMessage(listBox.Handle, 0x185, (IntPtr)0, (IntPtr)(-1));


Q:

ValueError: need more than 0 values to unpack (python lists)

I'm learning python from Google code class. I'm trying out the exercises.
def front_x(words):
  x_list, ord_list = []
  for word in words:
    if word[0] == 'x':
      x_list.append(word)
    else:
      ord_list.append(word)
  return sorted(x_list) + sorted(ord_list)

I believe the error is thrown because of initializing two empty lists on a single line. If if initialize them on separate lines, no more errors occur. Is this the reason?

A:

You are trying to use tuple assignment:
x_list, ord_list = []

you probably meant to use multiple assignment:
x_list = ord_list = []

which will not do what you expect it to; use the following instead:
x_list, ord_list = [], []

or, best still:
x_list = []
ord_list = []

When using a comma-separated list of variable names, Python expects there to be a sequence of expressions on the right-hand side that matches the number variables; the following would be legal too:
two_lists = ([], [])
x_list, ord_list = two_lists

This is called tuple unpacking. If, on the other hand, you tried to use multiple assignment with one empty list literal (x_list = ord_list = []) then both x_list and ord_list would be pointing to the same list and any changes made through one variable will be visible on the other variable:
>>> x_list = ord_list = []
>>> x_list.append(1)
>>> x_list
[1]
>>> ord_list
[1]

Better keep things crystal clear and use two separate assignments, giving each variable their own empty list.

A:

Change the line
x_list, ord_list = []

to

x_list, ord_list = [], []


Q:

Best Practice for creating user-defined command names

I want to let the users of a package define the name of command into which some unique content will be stuffed, so that they can then recall that content using the command name that they prefer.  Is it a better practice to make them provide me a string, from which I create the command and stuff the content (as in \tokify in my MWE) or is it preferable to let them tell me the actual (as yet undefined) command name and merely have me stuff the content (as in \populate in my MWE)?
The MWE is simple enough that you might say "just let them create the \def", but for the actual application, it will save them more keystrokes to let me create the content of the command.
\documentclass{article}
\usepackage{stringstrings}
\makeatletter
\newcommand\tokify[1]{%
  \expandafter\def\csname#1\endcsname{Content: #1}%
}
\newcommand\populate[1]{%
  \edef\sv@name{\expandafter\@gobble\detokenize{#1}}%
  \noblanks[q]{\sv@name}%
  \expandafter\def\csname\thestring\endcsname{Content: \thestring}%
}
\makeatother
\begin{document}

\tokify{xyz}
\xyz

\populate{\abc}
\abc

\end{document}

A:

I would use whichever you think more natural but use the same form for declaration and use.
So LaTeX counters use a name form
\newcounter{foo}
\arabic{foo}
\setcounter{foo}{1}

but LaTeX lengths use a command form:
\newlength\foo
\setlength\foo{3pt}

There isn't really any logical reason why these are different but at least they are individually consistent.
Similarly of course commands which use the command form
\newcommand\foo{..}
\foo

and environments which use a name
\newenviroment{foo}{..}{..}
\begin{foo}

So I would not have
\tokify{xyz}
\xyz

but
\tokify{xyz}
\usething{xyz}

is OK.
But in that case I would not use \csname#1\endcsname use \csname my-#1\endcsname or some such to avoid accidentally clashing with stuff (cf counters which use c@...)


Q:

Same kernels for homomorphisms of free modules

Let $f: R^n \rightarrow R^m$ be an isomorphism of free $R$-modules ($R$ commutative with unity) and $\pi_1: R^n \rightarrow R^n/\mathfrak m^n$, $\pi_2: R^m \rightarrow R^m/\mathfrak m^m$ the canonical projections where $\mathfrak m$ is an arbitrary maximal ideal in $R$.
How to see $\ker \pi_1 = \ker \pi_2 \circ f$?
If $x=(x_1, ..., x_n) \in \ker \pi_1$ then $x_i \in\mathfrak m$ for all $i$.
Since $f$ is an isomorphism we can "identify" $R^n$ with $R^m$, thus "$(\pi_2 \circ f) (x) = \pi_2 (x) = 0$". Similarly the other inclusion can be "shown". But I do not see how to prove the equation without using this heuristic argument (for example by doing it concretely elementwise).
context: proof of $R^n \cong R^m \Rightarrow m=n$ via reduction to fields.

A:

The submodule $\mathfrak{m}^n$ is exactly the same as
$$
\mathfrak{m}R^n=\{a_1x_1+\dots+a_kx_k: a_i\in\mathfrak{m}, x_i\in R^n\}
$$
Indeed, if $x\in\mathfrak{m}R^n$, then $x\in\mathfrak{m}^n$, by looking at the components. If $x=(a_1,\dots,a_n)\in\mathfrak{m}^n$, then
$$
x=a_1(1,0,\dots,0)+\dots+a_n(0,\dots,0,1)\in\mathfrak{m}R^n
$$
Since $f$ is an isomorphism, it maps $\mathfrak{m}R^n$ onto $\mathfrak{m}R^m$.
This can be seen more easily with a homomorphism $f\colon M\to N$; if $x\in M$ and $a\in\mathfrak{m}$, then $f(ax)=af(x)\in\mathfrak{m}N$.


Q:

Colors not varying - python graphics

I'm trying to reproduce something to this effect.

import graphics
from graphics import color_rgb
import random
window= graphics.GraphWin("x", 600, 400)
stripes = input("How many stripes should be on the flag")
stripes = int(stripes)
count = 0
count = int(count)
P1=graphics.Point(0,0) #left corner - anchor point
for x in range(stripes): #loop for number of stripes
    col= random.randint(1,255)
    stepdim = 400/stripes #size of divisions
    stepdim = int(stepdim)
    shrink = count*stepdim
    shrink = int(shrink)
    stepdim = stepdim*10 #enlarge to an increment below the last
    stepdim = stepdim-shrink
    stepdim = int(stepdim)
    P2=graphics.Point(600,stepdim) #bottom right corner - ever shrinking
    outsiderec=graphics.Rectangle(P1,P2) #
    outsiderec.setFill(color_rgb(100, col, 0))
    outsiderec.draw(window)
    count= count + 1
    count= int(count)
window.getMouse()
window.close()

I'm instead receiving one flat color.

I assume the problem is in my rand(int). I don't really know the ins and outs of it. Is it not running more than once?

A:

Using your code as base I have tried to reproduce the expected result.
import graphics
from graphics import color_rgb
import random

window= graphics.GraphWin("x", 600, 400)
stripes = input("How many stripes should be on the flag")
stripes = int(stripes)
#count = 0
#count = int(count)
#P1=graphics.Point(0,0) #left corner - anchor point
stepdim = 400/stripes #size of divisions
for x in range(stripes): #loop for number of stripes
    #col= random.randint(1,255)
    #stepdim = int(stepdim)
    #shrink = count*stepdim
    #shrink = int(shrink)
    #stepdim = stepdim*10 #enlarge to an increment below the last
    #stepdim = stepdim-shrink
    #stepdim = int(stepdim)
    #P2=graphics.Point(600,stepdim) #bottom right corner - ever shrinking
    P1=graphics.Point(0, stepdim * x) #left corner - anchor point
    P2=graphics.Point(600,stepdim * (x + 1)) #bottom right corner - ever shrinking
    outsiderec=graphics.Rectangle(P1,P2)
    #outsiderec.setFill(color_rgb(100, col, 0))
    red = random.randint(1, 255)
    green = random.randint(1, 255)
    blue = random.randint(1, 255)
    outsiderec.setFill(color_rgb(red, green, blue))
    outsiderec.draw(window)
    #count= count + 1
    #count= int(count)
window.getMouse()
window.close()

I have:

commented out all those statement that aren't needed
moved stepdim = 400/stripes from inside the loop to outside because you don't need to compute the same value for every loop
moved the P1=graphics.Point(0,0) inside the loop with a slight modification just to point to the top left corner of the stripe
modified the P2=graphics.Point(600,stepdim) to point to the bottom right corner of the stripe
added a random calculation for the three color components red = random.randint(1, 255), green = random.randint(1, 255), and blue = random.randint(1, 255)

Observations:
I have changed a little bit the way the stripes are drawn. Instead of drawing a shrunk version for every loop, the modified version just draws a fixed size stripe in consecutive positions.


Q:

Setting Column Width with PHPExcel Not Working

I am trying to format the cell widths of a document that I am creating with PHPExcel, yet when I use the getColumnDimension('A')->setWidth(7) method, it is not being produced accurately in the generated xlsx file.
I formatted the document in Excel so that I could find the values of the cells that I want and I get two values, one in Excel Units and the other in Inches.
For example:
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth('7');

will end up giving me a column width of 6.17 instead of 7. I have already tried using both strings and int values for, nothing changes. Any ideas?

A:

This is because MS Excel adjusts the figure itself to its own internal units: there's a whole section in the developer documentation (section 4.6.28, entitled "Setting a column’s width") that explains this.
Quoting from the sidebar in that section:

The measure for column width in PHPExcel does not correspond exactly
  to the measure you may be used to in Microsoft Office Excel. Column
  widths are difficult to deal with in Excel, and there are several
  measures for the column width.

Inner width in character units (e.g. 8.43 this is probably what you are familiar with in Excel)
Full width in pixels (e.g. 64 pixels)
Full width in character units (e.g. 9.140625, value -1 indicates
  unset width)

PHPExcel always operates with 3) "Full width in character units" which
  is in fact the only value that is stored in any Excel file, hence the
  most reliable measure. Unfortunately, Microsoft Office Excel does not
  present you with this measure. Instead measures 1) and 2) are computed
  by the application when the file is opened and these values are
  presented in various dialogues and tool tips.
The character width unit is the width of a '0' (zero) glyph in the
  workbooks default font. Therefore column widths measured in character
  units in two different workbooks can only be compared if they have the
  same default workbook font.
If you have some Excel file and need to know the column widths in
  measure 3), you can read the Excel file with PHPExcel and echo the
  retrieved values.

(my emphasis in bold)


Q:

JQM (jQueryMobile) HTML5 pattern validation with Alternate button type (Not Submit)

Using HTML5 Pattern for form field validation, how does one stop a submission if the form is invalid? Maybe I should ask, how does one create a custom valid/invalid form handler?
Documentation on the changePage()
$('#form-submit-button').click( function() {
    event.preventDefault(); // This is undefined

        // This submits my form and values via ajax, handles page transition
    $.mobile.changePage({
        url: 'request.php?page=one',
        type: 'post',
        data: $('form#test_form').serialize()
    },'slide',false,false);
});

Example HTML Form Field
<input type="text"
       name="first_name"
       id="first_name"
       placeholder="First Name*"
       pattern="[\w .-]"
       required />

Example HTML Button (Not Submit type)
<input type="button"
       data-theme="z"
       data-icon="forward"
       data-inline="true"
       name="form-submit-button"
       id="form-submit-button"
       value="Next Step"/>

A:

http://marxsoftware.blogspot.com/2011/01/html5-form-field-validation.html
According to this, it shouldn't let you submit your form till it validates.


Q:

Color palette conversion like in XTerm

In xterm we can have 256, 88 or 16 colors. I was wondering, is there an algorithm that can get color from 256 color chart and find the match / equivalent color in 88 color chart?
Moreover, is there an algorithm that can convert color from 256 color chart to a color from 16 color chart?
For example: if the color is #00D700 (Light Green) -> #00FF00 (Light Green in 16 color chart)

A:

Color quatization
In computer graphics, color quantization or color image quantization is a process that reduces the number of distinct colors used in an image, usually with the intention that the new image should be as visually similar as possible to the original image.
Posterization
This process is used in the Posterization of an image, which entails conversion of a continuous gradation of tone to several regions of fewer tones, with abrupt changes from one tone to another, originally done with photographic processes to create posters.

Algorithms
The process you are describing, to create a palette with fewer but similar colors than the original, falls in to this category despite not exactly being an image. You will find lots of possible implementations of this algorithm as either 'posterization' or 'quantization'.
The most popular algorithm by far for color quantization and palette optimization, invented by Paul Heckbert in 1980, is the median cut algorithm.
You can find Java examples in this site from the University of Illinois


Q:

Why my navigation container not has the same height as logo and search container

I'm doing some practise with flexbox because I want to know how it works and how is to work without using floats, display inline or block and so on, but I'm having a problem and I don't know how to solve it.
I have the header section with three containers: logo, navigation links and search. The container for the logo and the search have the same height (104px) but the navigation container no (41px).
Here's my current code, I added a background-color to the elements to show the height difference. I would like to know if there's a way to make the naviation container get the same height as the others (104px).

body {
  font-family: Arial, sans-serif;
}
/* reset styles */

body,
ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
a {
  text-decoration: none;
}
/* main wrappers */

.page-wrapper {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
.header {
  width: 100%;
  background-color: darkblue;
  padding: 10px 2%;
}
/* header styles */

header {
  display: flex;
}
header .header-logo,
header .header-search-npt {
  width: 20%;
}
header .header-logo {
  background-color: dodgerblue;
  margin: 10px 0;
}
header .navigation-links {
  width: 60%;
  align-self: center;
  background-color: deepskyblue;
}
header .navigation-links ul {
  display: flex;
  justify-content: center;
}
header .navigation-links ul li {
  margin: 0 15px;
  padding: 10px 0;
}
header .navigation-links ul a {
  color: #000;
  font-size: 18px;
  font-weight: bold;
  padding: 30px 0;
  text-transform: uppercase;
}
header .header-search-npt {
  background-color: dodgerblue;
}
header .header-search-npt input {
  font-size: 16px;
}

Item 1

Item 2

Item 3

Item 4

Item 5

        <input type="search" name="search-btn" placeholder="Search..." />

I think there should be a solution without specifying a height for the container because I will try to make responsive the layout.

A:

The reason that flexbox is able to provide equal height columns by default is that the align-items property is set to stretch by default.
In your code, you have overridden the default setting for the nav links with align-self: center:
header .navigation-links {
    width: 60%;
    align-self: center;
    background-color: deepskyblue;
}

In order to restore the flex item to equal height with its siblings, you need to remove that line of code (or make it align-self: stretch).
header .navigation-links {
    width: 60%;
    /* align-self: center; <-- REMOVE */
    background-color: deepskyblue;
}

DEMO 1
Then, if you want to center the nav links, make .navigation-links a nested flex container and center its flex items:
header .navigation-links {
    width: 60%;
    /* align-self: center; <-- REMOVE */
    background-color: deepskyblue;

    /* NEW */
    display: flex;
    justify-content: center;
    align-items: center;
    }

DEMO 2
Then, to restore equal height to the first column (the logo), remove the top and bottom margins:
header .header-logo {
    background-color: dodgerblue;
    /* margin: 10px 0; <-- REMOVE */
    }

DEMO 3


Q:

Creating vector with minimum values of another vector [R]

I have a problem that is very simple, but curiously it is taking me longer than I imagined. I'll put it generically here, and in the end I put an example. I hope to be clear:
I have a numeric vector X1, with N observations. I need to create another vector, X2, based based on minimum value of vector X1.
But the condition is a little strange: every observation of this vector X2 must be the minimum value of the last 126 observations of vector X1, in the same position.
In other words, each observation i of vector X2 is the result of the minimum between (i-125):i of vector X1.
I have tried in many ways, by for, creating functions and using apply, using index, but it did not work.
Consider the example:
set.seed(1)
x1<-rnorm(500,2,3)
i<-seq(126,length(x1))
x2<-min(x1[(i-125):i])

and the warning msgs:
Warning messages:
1: In (i - 125):i :
  numerical expression has 375 elements: only the first used

or
for(j in 126:length(x1)){
  x2<-rep(NA,length(x1))
  x2[j]<-(min(x1[j-125:j]))
}

In this case, only the last observation (500) which does not result in NA.

A:

The for loop should have had the same parentheses you had in the attempt that prompted the warnings (and should NOT have initialized the vector inside the for-loop, since that erased the prior values.):
x2<-rep(NA,length(x1))
for(j in 126:length(x1)){

  x2[j]<-(min(x1[(j-125):j]))
}


Q:

Issue with for loop with sqlite data insertion

I need to insert 5 rows where only one column values gets changed and remaining are same in all rows.
var Category1_fr ="one";
var Category2_fr ="one";
var Category3_fr ="one";
var Category4_fr ="one";
var Category5_fr ="one";

for(int i=1; i<=5; i++)
{
 tx.executeSql('INSERT INTO testTable(Language, Standard, Category, QuestionID, SubmitText, HeaderText) VALUES (?,?,?,?,?,?)',[Language_fr,Standard_fr,Category"'+i+'"_fr,Question_fr,Submit_fr,Header_fr]);
     }

I am getting the syntax error. What is the correct syntax in java script for Category'"+i+"'_fr so that on each iterate I need to store all the Category1_fr,Category2_fr,Category3_fr,Category4_fr,Category5_fr

A:

You could try to store the value as text in a variable and use it in the query like this :
for(int i=1; i<=5; i++)
{
    var catFr = 'Category' + i + '_fr';
    tx.executeSql('INSERT INTO testTable(Language, Standard, Category, QuestionID, SubmitText, HeaderText) VALUES (?,?,?,?,?,?)',[Language_fr,Standard_fr,catFr,Question_fr,Submit_fr,Header_fr]);
}


Q:

Is consolidating/reducing HTTP requests worth the logistical complexity?

Some examples:

CSS image sprites
Compiling JS needed on every webpage to one file
Implementing lazy-loading for images
Consolidating all meta information (username, CDN address, etc) into one request
Specifically for AWS S3 browser uploads using signed policy documents: grabbing all the policy documents from the server in one request instead of one request per policy document

Some of these are easier to implement than others. Some of these need to be done only once, and others need to be done with every update or change. It seems that not doing any of this would be easier from a logistical perspective, however I'm also concerned about server performance.
I hope to avoid the boilerplate "avoid premature optimization root of all evil blah blah" comment here. My project is in the early stages, and I see now that establishing the wrong or inefficient API format would be difficult to change later. So, I'd like to ask for advice from those with experience in this matter:

How much loading time would be saved for the user for each request that's consolidated? (i.e. what is the overhead of each request excluding the time spent downloading the actual payload)
Does consolidating HTTP requests substantially reduce server usage/costs? If so, were you able to quantify it? (i.e. what is the overhead of each request excluding database access and "the code that actually does stuff")

Possibly relevant for the second part of the question: my back-end server is nginx serving Django Rest Framework running on Gunicorn hosted on EC2 behind the AWS Load Balancer. Static assets will be hosted on S3 and served from Cloudfront.

A:

Your question is too broad to simply answer it yes/no.
Usually it depends.
My crystal ball is currently out of order, which makes it hard to give concrete advice ;)

My project is in the early stages

So, why bother with this question at all? The unspecific type of your question is a sign, that you do not have pain points. Otherwise your question would be like »My initial page load time is awful. How to deal with a ton of Javascript?«
This falls into the category of premature, i.e. without practical necessity. Of course it is always good to think about the future, but it is not necessary to think about it now. Start out straightforward. Do your application layout, have a look at webpack as a bundler. And get things going.

Does consolidating HTTP requests substantially reduce server usage/costs?

The obvious answer is yes. But again: Why bother?
As long as you aren't GoogleFacebookAmazon, why deal with their problems?
I understand the fear of technical debt; but look from it the other way:
Say you hack together some Javascript alongside with a Django-Backend. The overall architecture is crap - but it works. When you have a successfull business, you are able to hire qualified engineers, which help you putting your application in shape.
If you take Amazon as an example, it was AFAIR a bunch of Perl-scripts, which did the job at the time. Of course you couldn't run Amazon today (only) on the scripts from then (besides it would be interesting to know if there are some artifacts still running). The system evolved over time.
Here are three takeaways:
1) Get a business going
2) There is no right way to do it.
3) YAGNI - Or do not optimize for a use case, which is irrelevant now.
Or if you want a concrete technical advice:
Give a good first impression of your page:

Deliver minimal Javascript which helps to bootstrap your application
Few images on the landing page. There has to be a balance between delivering images (increase initial loadtime) and dynamically loading images (which could take some time on mobile internet). You have to choose between a slower or a maybe incomplete page, which effects both the first impression.
Few/no animations - helps keeping the impression of a fast page; although processing power shouldn't matter as much as it did years ago.


Q:

Application Cache : why Chrome show some files underlined in the console log?

During an application cache update, Chrome logs :

Application Cache Progress event (1 of 2) https://example.com/file1.css
Application Cache Progress event (2 of 2) https://example.com/file2.js

Sometimes the URL is underlined (event 3/4 in this example), sometimes not. Why ?

A:

It seems that underlined resources will be opened in developer tools when clicked on. Those that are not underlined, are still hyper-links but Chrome will launch them in a separate tab.
What I don't understand is why Chrome sometimes decides to treat resources like this and sometimes not. Even loading the same page several times changes the resources that are underlined occasionally.
Very odd. At a guess I'd say a bug.


Q:

C++ Instantiating a class, within a class. The correct way?

I'm struggling to instantiate a class, within another class. My main concern is... Where do I place the constructor? In the header file? In the class file? Or in both? Nothing seems to work right. I'll try to put this as simple as possible. Let me know if it's too simple ;)
This is how I would THINK it should be:
GameWorld.h:
#include "GameObject.h"

class GameWorld
{
protected:
    GameObject gameobject;
}

GameWorld.cpp:
#include "GameWorld.h"

void GameWorld::GameWorld()
{
    GameObject gameObject(constrctor parameters);
}

//When I compile the program, the values in the gameObject, are not set to anything.

So that's one of the things I've tried. Putting the constructor in the header, won't work either, for obvious reasons; I can't give it any parameters from GameWorld.
What is the correct way to do this?
Edit: Oops. Removed something useless.

A:

You need to initialize the GameObject member in the containing class' initializer list.
// In the GameWorld.h header..
class GameWorld
{
public:
    GameWorld(); // Declare your default constructor.

protected:
    GameObject gameobject; // No () here.
}

// In the GameWorld.cpp implementation file.
GameWorld::GameWorld() // No 'void' return type here.
  : gameObject(ctorParams) // Initializer list. Constructing gameObject with args
{
}


Q:

How did Bryan Singer intend to introduce the Phoenix?

In the original X-Men movie, when Magneto's device

 explodes

at the end, there is a quick shot of Jean Grey looking sort of stunned as the wave of energy goes through her. No other characters are shown having similar reactions.
When we pick up with Jean and Scott in X-2: X-Men United, Scott and Jean have a conversation about her powers specifically since the Liberty Island incident.

Scott: Jean? You OK?
Jean: Yeah, I'm fine. It's just a headache.
Scott: It's not just a headache, is it? I wasn't sure how to say this, but since Liberty Island you've been...
Jean: Scott.
Scott: You've been different.
Jean: My telepathy's been off lately. I can't focus. I hear everything.
Scott: Jean, it's not just your telepathy. A month ago you had to concentrate just to levitate a book. Now when you have a nightmare the entire bedroom shakes.
Jean: My dreams are getting worse. I keep feeling something terrible's about to happen.
Scott: I would never let anything happen to you.

This, of course, is a foreshadowing of the end of X-2 where

 Jean sacrifices herself and we are teased with a vague Phoenix shape in the water in the last frames of the film.

Putting together just these bits, it's not a far stretch to think that Bryan Singer originally intended the energy wave of X-Men to have been some sort of catalyst in the Phoenix Force being drawn to Jean.
Unfortunately, director Bryan Singer abandoned X-Men: The Last Stand early into pre-production and the writing staff changed. In the final version of the third X-Men movie,

 the Phoenix is merely a repressed personality of Jean's and not a cosmic force.

In this storyline, to my recollection, it is never stated that the Liberty Island incident helped unlock

 the Phoenix personality,

but it is possible.
Has Bryan Singer, or anyone else stated how the Liberty Island incident changed Jean, or how he intended to merge Jean and the Phoenix Force?

A:

There is some information about ideas that were considered for the third X-Men movie in this podcast. Found this via this forum post, here's a transcript of the relevant part:

 “The idea was that you open up with Alkali Lake but it’s completely barren and dried up and there are these odd reports of strange phenomena going on around the world accompanied by bright lights in the sky.
“The idea would be that both the X-Men and the Brotherhood realise that essentially a very god-like force had entered their reality and that it was causing disruptions around the world, you know mutant prisons being decimated, I had pitched an idea about a fleet of cargo ships getting torn apart in the Atlantic and you found out that they were shuttling mutants as slave labour.
“You found out was that Phoenix was going round the world taking things into her own hands and that she had basically returned as a god, which they did in X3. She had viewed herself as above the conflict, that she was here to end things on her terms, she was sick of the fighting and she was going to take things into her own hands and she did not give a s**t what the X-Men or the Brotherhood had to say about it.
“And ultimately the way it was going to end, at least the version I was pushing for, would be that Phoenix was kind of like the Starchild at the end of 2001, she didn’t just get stabbed and die again, but she kind of chose to leave.
“The one idea that I loved, that I really wanted to do, was that Cyclops would build the Danger Room. He felt guilty that because the X-Men were too weak, they weren’t strong enough or fast enough, that was the reason Jean died. If they were a little bit better at fighting, then she might still be alive. It was all about this guilt he had about her death and he built the Danger Room to train them to be better. In the end it really was about him not being able to let go of her and that causes the chaos and disruption in the movie and in the end it’s about him letting her go.
“Ultimately she kind of becomes that cosmic force that Phoenix is known to be, she leaves Earth and becomes a god or at least a higher level of intelligence and she goes into the cosmos possibly to kick-start life somewhere else. The final scene for me would have been her telling Cyclops or her telling the X-Men ‘I’ll be watching.'”


Q:

Altering CKEditor HTML content after instanceReady and paste

I need to add contenteditable="false" on all CKEditor content elements having CSS class="readonly" and contenteditable="true" to elements having CSS class="writable". Preferably on paste and instance ready.
I know of config.on.instanceReady and config.on.paste but what should I write into the function just eludes me ;)
Btw. I'm not using inline editor.
editor.document is listed as read only property in the documentation so I cannot use that.
Final solution thanks to Oleq for showing me to the right path. applyToAll is required if writables are within readonly.
 // Add custom rule to dataFilter (when data comes *into* editor).
 on{pluginsLoaded: function (evt){
 this.dataProcessor.dataFilter.addRules( {
     elements: {
         $: function ( element ) {
             if (element.hasClass('readonly'))
             {
                 element.attributes.contenteditable = 'false';
             }

             if (element.hasClass('writable'))
             {
                 element.attributes.contenteditable = 'true';
             }
         }
     }
  },{applyToAll: true});

  this.dataProcessor.htmlFilter.addRules( {
      elements: {
          $: function ( element ) {
              if(element.hasClass('readonly') || element.hasClass('writable'))
              {
                  delete element.attributes.contenteditable;
              }
          }
      }
  },{applyToAll: true});

  });

A:

You should use CKEditor's dataProcessor.dataFilter. This is the standard mechanism used by the editor to filter input (JSFiddle). It handles data set with editor.setData, data pasted by the user and, of course, initial HTML from textarea or any element to which CKEditor is attached.
CKEDITOR.replace( 'my-editor', {
    // See http://stackoverflow.com/a/15659962/1485219
    extraAllowedContent: 'span(readonly)',

    // Just to make the interface clear.
    toolbarGroups: [
        {"name":"document","groups":["mode"]},
        {"name":"basicstyles","groups":["basicstyles"]}
    ],
    on: {
        // When all plugins were loaded but editor data is not yet processed.
        pluginsLoaded: function( evt ) {
            // Add custom rule to dataFilter (when data comes *into* editor).
            this.dataProcessor.dataFilter.addRules( {
                elements: {
                    // Check all elements. Rules can be specific, i.e. for img or h2.
                    $: function( element ) {
                        if ( element.hasClass( 'readonly' ) ) {
                            element.attributes.contenteditable = "false";
                        }
                    }
                }
            } );
        }
    }
} );

EDIT: I created you a widget (JSFiddle) because I feel this is what you really wanted to do:
// This plugin brings a widget into editor.
CKEDITOR.plugins.add( 'myFirstWidget', {
    // Widget plugin must be loaded (must be present in the build of CKEditor).
    requires: 'widget',

    init: function( editor ) {
        editor.widgets.add( 'myFirstWidget', {
            button: 'My First Widget Button',

            // http://stackoverflow.com/a/15659962/1485219
            allowedContent: 'span(readonly)',
            requiredContent: 'span(readonly)',

            // Make all <span class="readonly"> a non-editable widget.
            upcast: function( element ) {
                return element.name == 'span' && element.hasClass( 'readonly' );
            }
        } );
    }
} );

CKEDITOR.replace( 'my-editor', {
    // Use the plugin.
    extraPlugins: 'myFirstWidget',

    // Just to make the interface clear.
    toolbar: [ [ 'Source', '-', 'MyFirstWidget' ] ]
} );

Learn more about widgets and awesomeness they bring.


Q:

Syntax for an instance of a class template as a non-type template parameter

I can't find the right syntax even after reading cppreference on template params. The following doesn't compile, but hopefully describes what I want to do. What's the correct syntax?
template <class DisplayType>
class DisplayAdapter : public DisplayType
{

};

template<template <typename> DisplayAdapter>
class Painter // Takes an instance of DisplayAdapter, not a type!
{
}

Here is how it's supposed to be used:
struct S{};

int main()
{
    DisplayAdapter<S> concreteAdapter;
    Painter<concreteAdapter> p;

    return 0;
}

Here's Ideone snippet for the whole thing: https://ideone.com/dvbYt8

A:

What you're wanting is not a template template parameter.
A template template parameter is used to pass templates around, like this:
template<template<typename> typename Container>
struct foo {
    Container<int> container;
};

int main() {
    foo<std::vector> f;
}

As you can see, you can pass template names around with that. Remember that templates are not types, but a blueprint for type, and the language (and the standard) is not treating templates the same way as types.

I assume with your examples your trying to use non-type template parameters?
A non-type template parameter is a template parameter that is a value instead of a type. It can be of any integral types, reference type and pointer type.
For example, look at std::array:
std::array<int, 10> tenInts;

Notice the second parameter is a number. This is because std::array look something like this:
template<typename T, std::size_t N>
struct array { /* ... */ };

The second parameter is an unsigned long int.
You can also pass references and pointers as template parameter:
template<int& i> struct foo {};
template<int* i> struct bar {};

int main() {
    // Need at least internal linkage in C++14 and older
    // No linkage required since C++17, only static needed.
    static int num = 0;

    foo<num> f;
    bar<&num> b;
}

You can even pass a pointer to any type as reference template parameter:
struct stuff {};
template<stuff& s> struct foo;

int main() {
    static stuff s{};
    foo<s> f; // works!
}

This seem to be closer to what you wanted. However, you seem to have many many different type you want to send as template parameter, as the type of the instances you want to pass around are templated. For that you'll need C++17 template auto feature:
template<auto& da>
struct Painter {
    // ...
};

int main() {
    static DisplayAdapter<S> concreteAdapter;
    Painter<concreteAdapter> p;
}

And done!
If you don't have C++17 with you don't worry, and simply pass the display type along with your instance (C++14 example):
template<typename DT, DisplayAdapter<DT>& da>
struct Painter {};

// Internal linkage
DisplayAdapter<S> da;

int main() {
    Painter<S, da> painter;
}


Q:

Store Clojure REPL lines

Maybe this is a newbee question, sorry if so!
Is it possible to store all lines I typed into the REPL in a file? Maybe one can configure it to do so or do this before closing the REPL session.
Thanks for your answer!

A:

Leiningen stores history by default when in a project:
$ lein new hello
$ cd hello
$ lein repl
user=> (+ 1 2 3)
user=> (exit)
$ cat .lein-repl-history

Boot always stores history by default:
$ boot repl
boot.user=> (+ 1 2 3)
boot.user=> (exit)
$ cat .nrepl-history


Q:

Type '{}[]' is not assignable to type 'AngularFireList'

I'm new with Angular and Firebase, I'm trying to get all of my items of a node to an AgularFireList, but I get this error:
Type '{}[]' is not assignable to type 'AngularFireList'.
  Property 'query' is missing in type '{}[]'.
My code is:
my_notes: AngularFireList<any[]>;

constructor(public afDB: AngularFireDatabase) {
    this.getNotes()
      .subscribe(
        notas => {
          this.my_notes = notas;
        }
      );
  }

  getNotes(){
    return this.afDB.list('/notas').valueChanges();
  }

Thanks for the help.

A:

Try this:
constructor(public afDB: AngularFireDatabase) {
this.getNotes()
  .subscribe(
    (notas: AngularFireList<any[]>) => {
      this.my_notes = notas;
    }
  );
}

If the issue still persists, try also adding this bit of code:
getNotes(){
    return <Observable<AngularFireList<any[]>>>this.afDB.list('/notas').valueChanges();
  }


Q:

unwanted  tags appearing on web page that are visible using google chrome inspect, but not visible in the app's code

I'm having an issue where my web page is being effected with multiple br tags. I have checked through all my code but they only appear when I inspect the code via google chrome inspect.
I've tried to delete them using the google console but they keep coming back. Any ideas how to fix this would be greatly appreciated.
invisable  tags are appearing in the console but not in the apps code
google console with  tags

A:

A
 is not allowed inside of a
. Looks like Chrome tries to make sense out of the
 in one of your
s.
Just remove the
 after
<%= order.record.Label %>

and you should be fine.
Hint: A
 is only allowed to contain one or more  or  elements.


Q:

Textview disappers but listview is visible

I tried to put textview at top of listview in layout, but the content of textview is not visible. In the design view there is space of the relative layout but I don't see the content.
Here is my layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<!-- TODO: Update blank fragment layout -->
<RelativeLayout
    android:id = "@+id/relativeLayout1"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width = "0dp"
        android:layout_height = "wrap_content"
        android:layout_weight = "1"
        android:gravity = "center"
        android:padding = "5dp"
        android:text = "@string/product"
        android:textColor = "#ffffff" />

    <TextView
        android:layout_width = "0dp"
        android:layout_height = "wrap_content"
        android:layout_weight = "2"
        android:gravity = "center"
        android:padding = "5dp"
        android:text = "@string/category"
        android:textColor = "#ffffff" />

    <TextView
        android:layout_width = "0dp"
        android:layout_height = "wrap_content"
        android:layout_weight = "1.5"
        android:gravity = "center"
        android:padding = "5dp"
        android:text = "@string/quantity"
        android:textColor = "#ffffff" >
    </TextView>
    <TextView
        android:layout_width = "0dp"
        android:layout_height = "wrap_content"
        android:layout_weight = "1"
        android:gravity = "center"
        android:padding = "5dp"
        android:text = "@string/price"
        android:textColor = "#ffffff" >
    </TextView>
</RelativeLayout>
<ListView
    android:id = "@+id/listview"
    android:layout_width = "match_parent"
    android:layout_height = "fill_parent"
    android:layout_weight = "1"
    android:layout_below="@+id/relativeLayout1"/>
</RelativeLayout>

Please guide.
Screenshot

A:

       <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- TODO: Update blank fragment layout -->
    <LinearLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:lines="1"
            android:maxLines="1"
            android:padding="5dp"
            android:text="Product"
            android:textColor="#000000" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:lines="1"
            android:maxLines="1"
            android:padding="5dp"
            android:text="Category"
            android:textColor="#000000" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:lines="1"
            android:maxLines="1"
            android:gravity="center"
            android:padding="5dp"
            android:text="Quantity"
            android:textColor="#000000" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:lines="1"
            android:maxLines="1"
            android:gravity="center"
            android:padding="5dp"
            android:text="Price"
            android:textColor="#000000" />
    </LinearLayout>

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/relativeLayout1"
        android:padding="5dp" />
</RelativeLayout>

Change Your layout with this will solve your problem.One More thing when you want to manage your layout with weight then always use LinearLayout because the weight concept is not supported by RelativeLayout.


Q:

group_by to select first two rows, then spread()

I'm trying to reformat this so I can generate a dataframe of all instances of On Hold Begins and the next event immediately after it. On Hold Begins is the start an event, and I'd like to capture its Timestamp and Deviation as well as the Timestamp and Deviation for the next event immediately after it (i.e. Below Thresold, Stage Enabled).
If possible, I only want to include slices that have On Hold Begins as the first event (so the ideal solution would not include rows 1 &2 above), do not want the additional X columns, and would want it to be formatted as I described.
This is similar to: How can I spread repeated measures of multiple variables into wide format?, but I ran into errors asking for a dictionary when I tried it.
Thank you all so much for the help.

A:

Simple solution using base R:
first_idx <- which(df$Flag == "On Hold Begins")
second_idx <- first_idx + 1
df_1 <- df[first_idx,]; colnames(df_1) <- paste("Flag 1 ", colnames(df_1))
df_2 <- df[second_idx,]; colnames(df_2) <- paste("Flag 2 ", colnames(df_2))
cbind(df_1, df_2)

   Flag 1  Stage   Flag 1  Flag Flag 1  Timestamp Flag 1  x Flag 1  Deviation Flag 2  Stage    Flag 2  Flag Flag 2  Timestamp Flag 2  x Flag 2  Deviation
3              a On Hold Begins     4/29/17 15:34         1             1.200             a Below Threshold     4/29/17 15:35         1            0.0000
6              a On Hold Begins     4/29/17 21:49         5             1.200             a Below Threshold     4/29/17 21:50         5            0.0000
10             a On Hold Begins     4/29/17 23:29         6             1.200             a Below Threshold     4/29/17 23:30         6            0.0000
12             a On Hold Begins     5/16/17 17:22         8             1.774             a   Stage Enabled     5/16/17 17:39         8            1.8973
15             a On Hold Begins     5/16/17 19:14         9             1.095             a Below Threshold     5/16/17 19:15         9           -0.2252
21             b On Hold Begins     4/28/17 22:05       125             1.200             b    On Hold Ends     4/28/17 22:07       125            1.2000
24             b On Hold Begins     4/28/17 23:29       128             1.200             b Below Threshold     4/28/17 23:30       128            0.0000
26             b On Hold Begins      4/29/17 1:53       133             1.200             b Below Threshold      4/29/17 1:55       133            0.0000
29             b On Hold Begins      4/29/17 2:40       135             1.200          <NA>            <NA>              <NA>        NA                NA


Q:

Show whether a question was "reddited"

I sometimes find a question has like 50000 views and later I find most of those were reddit users that got in rage or glee about something of it.
Yesterday there was an answer of a page-one user that upset reddit folks, and within minutes that post were downvoted to -70. It looks like reddit has a deep impact on SO posts.
May it make sense to mark a question as "reddited" if the system finds that a large part of visitors were directed from reddit to this question?

A:

I like this, but would tend to extend it to any relevant incoming traffic.
Maybe it would be worth introducing a "externally linked" column to the right hand side, showing incoming links from (a list of trusted) external sites with more than 10, 100, or 1000 views? Including Twitter (in the unlikely event that that is possible - bit.ly and co. probably drop the referer.)

A:

Huge traffic coming from Reddit is barely different from surges of traffic coming from a Coding Horror link, a tweet from one of the big names employed or otherwise, or any other sort of large publicity hit. It's hit everything from HTML parsing in Regex to floppy disk drives to Angry Birds, from all sorts of sources. Reddit simply makes a more commonly larger impact by virtue of its size and frequency. In the end, it's just natural fluctuation of net traffic from large promotion.
So, to that end... why highlight Reddit? What exactly is the point of noting that a post got linked specifically by Reddit? Glory? Shame? Anomaly? What do we do in identifying these posts, what purpose do we have to advertise this knowledge?


Q:

HTML-JS : Plethora of buttons that each spawn a different form

In my main page, i want to have a plethora of buttons (at least four) that each of will spawn a form with a different action each.
At any time only one form will be visible.
What is the best way to do this?
Should i creare four forms and when a button is selected will make all the other forms with "visibility=hidden" and just expose the one i want?
This is the code i used:

        <button id="btn_1" class="editbutton" > 1 </button>
        <button id="btn_2" class="editbutton" > 2 </button>
        <button id="btn_3" class="editbutton" > 3 </button>
        <button id="btn_4" class="editbutton" > 4 </button>

        <form id="editForm_1"  action="" method="post" name="editForm">
            <input type="text" name="txtname" placeholder="1">
        </form>

        <form id="editForm_2"  action="" method="post" name="editForm">
            <input type="text" name="txtname" placeholder="2">
        </form>

        <form id="editForm_3"  action="" method="post" name="editForm">
            <input type="text" name="txtname" placeholder="3">
        </form>

        <form id="editForm_4"  action="" method="post" name="editForm">
            <input type="text" name="txtname" placeholder="4">
        </form>

A:

"The best way" is clearly subjective.
That said, note that setting style.visibility = "hidden" makes the element invisible but leaves empty space for it on the page.
For a cleaner UI, you might want to use style.display = "none".

The algorithm for the solution suggested below is:
--- Start with all forms hidden (using CSS).
 --- Listen for any clicks in the document.
 --- Whenever a click targets one of the form-related buttons:
 ------ - Loop through all the forms, and for each form:
 --------- - Hide the form.
 --------- - Compare the form's id attribute to the (clicked) button's data-form attribute.
 --------- - If the form is a match for the button, show the form again.

const forms = document.querySelectorAll("form"); // Remembers a list of all the forms

document.addEventListener("click", changeForm); // Runs the function on clicks

function changeForm(event){

  // Makes sure a form button was clicked before proceding
  if(event.target.classList.contains("formBtn")){

    // Remembers which button was clicked
    const formBtn = event.target;

    // Converts the `forms` NodeList to an Array so we can use the `.forEach` method
    const formsArray = Array.from(forms);

    // `forEach` takes one argument: a function that we provide using `=>` notation.
    //    Our function (which `forEach` calls once for EACH form in `formsArray`)
    //    gets each form as an argument, hides the form, then possibly reveals it again
    formsArray.forEach(form =>{
      form.style.display = "none"; // Hides the current form

      // Relies on the button's `data-form` attribute matching the form's `id`
      if(form.id == formBtn.dataset.form){
        // Reveals the current form if it matches the button
        form.style.display = "block";
      }
    });
  }
}
form{ height: 2em; width: 20em; border: 1px solid gray; display: none; }

    <button data-form="form1" class="formBtn">Form 1</button>
    <button data-form="form2" class="formBtn">Form 2</button>
    <button data-form="form3" class="formBtn">Form 3</button>
    <button data-form="form4" class="formBtn">Form 4</button>

    <form id="form1">This is Form 1</form>
    <form id="form2">This is Form 2</form>
    <form id="form3">This is Form 3</form>
    <form id="form4">This is Form 4</form>


Q:

Design Pattern of a MVC3 web based application

I am NEW in MVC3 and designing a web based application and kind of in learning phase. I am building a project where I need to show a list of customers in a web grid.
Now, I need to email a list of customers everyday, whose info (Name) is not updated for more than 6 months. How should I design the application? Do I need to use SQL Server Agent jobs for picking up the list of customers?
Any discussion or idea will be of great help. Thanks!

A:

What you are actually seeking is how to run background tasks in asp.net mvc. There are many ways this can be done, but Jeff Atwood explained a simple version here well here when designing the badge system for stack overflow.
There are other stuff such as windows services for more intensive processes but you will have a problem when hosting on shared servers.