text:
Q: My Onclick handler returns false, but my form is still submitted I have a form with a submit button, and a validator attached to it via onclick=.... When I click on the submit button, the validator is executed and returns false. Still, the form is submitted. How can this be?
To narrow the problem further, I even changed the code temporarily to:
<form id="contactform" method="post" action="cgi-bin/process_contact_form.rb">
    ....
    <input type="submit" value="Abschicken" onclick="false && k_validate('de')" />
</form>

This would just return false and bypass my validator. Indeed, even in this version, the form gets submitted.
Note that I am aware that there are means to get a form submitted with bypassing the validator. I am here only interested in the "normal" case, i.e. when a user explicitly clicks the button.
I have tested this on Mac OSX 10.6.8, using the following browsers:
SeaMonkey 2.0.14
Safari 5.1.10
Chrome 36.0
JavaScript is, of course, enabled.
The test page with the aforementioned "false" shortcut can be seen here:
http://www.tsukaeru-doitsugo.de/testing.html
It has two buttons. The first button (labelled "Abschicken") is the one within the form. Its onclick handler returns false, but the form is still submitted.

A: You are missing the return-statement:
<input type="submit" value="Abschicken" onclick="return k_validate('de')" />


text:
Q: How to set up server when curl is returning error 60 I have little problem with setting up our server.
I made XML feed for Facebook dynamic remarketing, but everytime when the Facebook is trying to download that feed it returns curl error 60. I know, that is a problem with SSL, but I was trying to update all certificates with command update-ca-certificates --fresh and it didn't help.
When I use this command, it returns proper response:
curl --url https://www.example.com --cacert /etc/ssl/certs/cacert.pem

But when I use command without exact certification authority file
curl --url https://www.example.com

it returns this response:

curl: (60) SSL certificate problem: unable to get local issuer certificate
  More details here: http://curl.haxx.se/docs/sslcerts.html
curl performs SSL certificate verification by default, using a
  "bundle"  of Certificate Authority (CA) public keys (CA certs). If the
  default  bundle file isn't adequate, you can specify an alternate file
  using the --cacert option. If this HTTPS server uses a certificate
  signed by a CA represented in  the bundle, the certificate
  verification probably failed due to a  problem with the certificate
  (it might be expired, or the name might  not match the domain name in
  the URL). If you'd like to turn off curl's verification of the
  certificate, use  the -k (or --insecure) option.

Our SSL provider is RapidSSL. I tried to add theirs ceritificate to cacert.pem, but it didn't work too.
Dou you have some suggestions how to fix this problem and how to properly set up server to correctly accept cUrl requests and correctly send response?
Thank you for your help.
Edit
Eventually I found out, that my problem was in version of SSL. Facebook is no more supporting HTTPS communication on SSL version 3 from October 2014 so we had to change our security to TLS 1.2 and that was all. Hopefully it will help to somebody :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL Foreign-Keys: Because of understanding RESTRICT & UPDATE I've 2 tables:
1) kind_basis (child-basis-data)
id              bigint(20) unsigned     NO  PRI     NULL    auto_increment
vorname         varchar(64)             NO          NULL
nachname        varchar(64)             NO          NULL
geburtsland_id  bigint(20) unsigned     NO  MUL     NULL

2) liste_land (list of countries)
id              bigint(20) unsigned     NO  PRI     NULL    auto_increment
iso             varchar(2)              NO          NULL
landname        varchar(255)            NO          NULL

There is a releation between them:
ALTER TABLE `kind_basis`
    ADD CONSTRAINT `fk_geburtsland_id`
    FOREIGN KEY ( `geburtsland_id` )
    REFERENCES `liste_land` (`id`)
    ON DELETE RESTRICT
    ON UPDATE CASCADE ;

Why is following-query is possible?
DELETE
    FROM  `liste_land`
    WHERE `liste_land`.`id` = 6

Shouldn't I get such of a message "You may not delete the row, because it is used in an another table (kind_basis) ?
If I update a row in liste_land, will it be also updated in kind_basis?

A: ON DELETE RESTRICT means you can't delete a  parent row if a child row  references the value for that parent so you probably dont have that child row.

A: Instead of trying to delete because it puts the table you are using all the data at once, avoids mistakes, avoid breaking your head and try to decipher pinching, or simply why not try to use another tool to develop these tables oracle , has mysqlWorkbench which is very good super easy and has many videos on youtube his classes, as I'm sure you already have the wisdom of creation and manipulation is easy, my tip invez try to delete or update creates a new table already entities and attributes that you need to not have to keep updating or deleting and then import it to where you want


text:
Q: what is the meaning of "leading type" here? does it means a leading article? what is the meaning of "leading type" here?
does it means a leading article?

The new-comer began to hold sittings soon after her arrival. At one of
  the first of these, on November 24, 1871, a representative of The
  Times was present, and he published a detailed account of the séance,
  which was held jointly with D.D. Home, a close friend of the medium.
  This appeared in an article entitled "Spiritualism and Science,"
  occupying three and a half columns of leading type.

from http://gutenberg.net.au/ebooks03/0301051h.html

A: To answer this question we need to learn some basic terminology in typography:

type: The term type is used generally to mean letters and other characters assembled into pages for printing or other means of reproduction
Leading: (it's pronounced LEDing - as in the metal lead)Leading is the spacing between the baselines of type. The term leading is derived from the practice of placing lead strips between lines type on older hand set printing presses such as a letterpress.

The word 'leading' originates from the strips of lead hand-typesetters used to use to space out lines of text evenly. The word leading has stuck, but essentially it's a typographer's term for line spacing.
So leading essentially has 2 meanings, the first one means strips of lead used in typo-setting, which are obsolete now. The second one means line height or line spacing.
My guess is that leading in the text refers to the first meaning.

the article took 3.5 columns whose lines were spaced using strips of lead.

Perhaps there used to be different methods to publish texts, one of which used lead strips to space lines, hence the name leading type.


text:
Q: how can I fill my database records with these strings randomly my table is like this:
[int]
[FullSizeImageName]
[ThumbSizeImageName]
[Title]
[Alt]
[Sort]
[Size]

I want to fill [Title] and [Alt] with these strings randomly ["string1","string2","string3","string4"]

A: This does not fully work but you might be able to do something with it
SQL is not really built for generating random numbers.
declare @T table (id int, val varchar(10));
insert into @T (id, val) values (0, 'one'), (1, 'two'), (2, 'three'), (3, 'four');
select name, abs(convert(int, convert (varbinary(8), NEWID(), 1)))%4 r
     , (select top 1 t.val from @T t where id = abs(convert(int, convert (varbinary(8), NEWID(), 1)))%4) rr
from sys.all_objects


text:
Q: Fix nav bar on top on scroll down I tried to achieve something similar to here
but for me its not fixing at top on scrolling down.Someone please provide any example or resources to achieve this feature.
     .features-switcher.fixed:after,
      {
        -webkit-backface-visibility: hidden;
        backface-visibility: hidden;
        -webkit-transform: translate3d(0, 0, 0);
        transform: translate3d(0, 0, 0);
        position: fixed;
        z-index: 101;
        width: 100%;
        height: 65px;
        top: 0;
        left: 0;
        opacity: 1
    }

For my nav-bar div class features-switcher:
        $(window).scroll(function () {
            console.log("scrolled down");
            console.log($(window).scrollTop());
            if ($(window).scrollTop() > 150) {
                $('features-switcher').css('top', 0);
            }
        }
        );

A: You are missing a .
$('features-switcher').css('top', 0);
Should be...
$('.features-switcher').css('top', 0);


text:
Q: Power series expansions
The following initial-value problems has a unique solution that is
  analytic at the origin. Find the power series expansion
  $\sum_{k=0}^\infty a_kz^k$ of the solution by determining a recurrence
  relation for the coefficients $a_j$.
a.  $\begin{cases} \frac{d^2f}{dz^2}-z\frac{df}{dz}-f=0  \\ f(0)=1,\
 f'(0)=0  \end{cases}$
b.$\begin{cases} \frac{d^2f}{dz^2}+4f=0  \\ f(0)=1,\ f'(0)=1
 \end{cases}$

My attempt:
For a, I know that $f''=zf'+f \implies f''(0)=0\dot\ f'(0)+f(0)=0+1=1$, but the answer is $$\sum^{\infty}_{j=0}\frac{1}{j!}(\frac{z^2}{2})^j=e^{z^2/2}$$

A: It is is a good idea to start from
$$
f''=zf'+f.
$$
This yields
$$
\sum_{k\geq 2} k(k-1)a_kz^{k-2}=z\sum_{k\geq 1}ka_kz^{k-1}+\sum_{k\geq 0}a_kz^k
$$
hence
$$
\sum_{k\geq 0} (k+2)(k+1)a_{k+2}z^{k}=\sum_{k\geq 0}(k+1)a_kz^{k}.
$$
Equating the coefficients, we get
$$
(k+2)(k+1)a_{k+2}=(k+1)a_k\quad\Rightarrow\quad a_{k+2}=\frac{a_k}{k+2} \text{or}\ a_k=a_{k+2}(k+2)
$$
and the initial conditions yield
$$
a_0=1\qquad a_1=0.
$$
By induction, it follows readily that $a_{2k+1}=0$ for all $k\geq 0$.
Now
$$
a_{2k+2}=\frac{a_{2k}}{2k+2}=\frac{a_{2k}}{2(k+1)}.
$$
Also, another induction from the initial conditions and from $a_{k+2}=\frac{a_k}{k+2}$ shows that
$$
a_{2k}=\frac{1}{2^kk!}
$$
Therefore
$$
\sum_{k\geq 0}a_kz^k=\sum_{k\geq 0}\frac{z^{2k}}{2^kk!}=\sum_{k\geq 0}\frac{(z^2/2)^{k}}{k!}=e^{z^2/2}.
$$
Remark: so the power series $f$ has infinite radius of convergence. Moving backwards, what we have done shows that $f$ is a solution of the ODE on $\mathbb{R}$.

A: Assume that $$f=\sum_{k\geq 0} a_k x^k$$
The equation then gives you that
$$\sum_{k\geq 2} a_kk(k-1) x^{k-2}=\sum_{k\geq 1} a_kk x^k+\sum_{k\geq 0} a_k x^k$$
We can normalize this to "$k \geq 0$" to get
$$\sum_{k\geq 0} a_{k+2}(k+2)(k+1) x^{k}=\sum_{k\geq 0} a_kk x^k+\sum_{k\geq 0} a_k x^k$$
It follows $$(k+1)(k+2)a_{k+2}=(k+1)a_k$$ or equivalently $$(k+2)a_{k+2}=a_k$$
from this, the solution should be straightforward. Analyze the cases for odd and even indices.


text:
Q: What is the initrd.img.old file? When I run

$ ls /

I get back:
bin    dev   initrd.img      lib64       mnt   root  snap      sys  var
boot   etc   initrd.img.old  lost+found  opt   run   srv       tmp  vmlinuz
cdrom  home  lib             media       proc  sbin  swapfile  usr  vmlinuz.old
I'm coming from using Windows a long time and usually I delete old image files. Is this normal in Linux, I'm trying to understand. Do I leave them be or can they/should the be removed?


text:
Q: NavigationController overflow I've designed and build game based on UINavigationController. I have several ViewControllers like on the picture. You select NewGame from RootVC and you are ready to play. After finishing, you are asking to go to the next board in NextBoardVC. After 10 boards you are going to next level by NextLevelVC. There is 5 Levels. Each level contains 10 boards. The problem is that I'm pushing each ViewController using pushViewController method. After 5 levels I have 52 VCs on the stack and sometimes application crashes.
GameVC contains many png's, and some sounds so it's quite heavy. I don't have any leaks (tested by Instruments)
Sorry, I dont have reputation so I cant upload images by stackoverflow.
This is an image:
Textual representation of the view hierarchy:
RootVC
--OptionsVC
--HowToPlayVC
--NewGameVC
  --GameVC
    --NextBoardVC
      --NextLevelVC
        --GameVC
          --NextBoardVC
              --NextLevelVC
                --GameVC
                  --NextBoardVC
                    --NextLevelVC
                      --GameVC
                        --... and so on many times

Is there better way to do the navigation, and eliminate crashes?

A: Why don't you just pop the controllers back off instead of just pushing more and more controllers on top, especially at those points where you're returning in your "loop"?

A: Don't forget that you can directly set view controllers on a navigation stack, using setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated.
So rather than pushing new levels onto the navigation stack you could replace one level with the next one by creating an array containing all your view controller up to that point plus your new level, and using the setViewControllers method above.

A: You are managing your view controller hierarchy incorrectly. A navigation controller should never have a loop as your diagram suggest yours does.
Also, a navigation controller should managed a visual hierarchy first and logical one second. E.g. The contact app, where a group list view pushes a list of contacts which pushes a contact detail which pushes one of several attribute detail edit views. Everytime you leave one view you pop that view and go back "up" the hierarchy to the previous view. You would never configure it go from one contact detail view to the next contact view just by pushing another contact detail view on top of the last contract detail view.
Likewise you need to pop the existing BoardVC or LevelVC from the stack before pushing the next.
(Key: here --> means push and <-- means pop)
To setup a the first level of a new game you would:
RootVC-->NewGameVC-->GameVC-->BoardVC-->LevelOneVC

... and then to add the next level you would first:
RootVC-->NewGameVC-->GameVC-->BoardVC<--LevelOneVC

... to get:
RootVC-->NewGameVC-->GameVC-->BoardVC

... and then:
RootVC-->NewGameVC-->GameVC-->BoardVC-->LevelTwoVC

... repeat for all other levels. You can do the same for each BoardVC as needed.
The trick here is to not use the slide transition which is the default navigation controller transition. That transition tells the user to expect this logical layout:
RootVC-->NewGameVC-->GameVC-->BoardVC-->LevelOneVC-->LevelTwoVC

... which is what is causing your problem. Instead, use another transition like fade or hide the transition all together.
By popping any views that are not necessary for the user's navigation, you ensure that you view controller stack is never more than 5 view controllers deep at anyone time and that therefore only 5 view controllers are needed in memory.


text:
Q: Dynamic string generation with depending on size of array I need to generate a string based on an array of ids.
Array
["5d227c01-93dc-4f0b-abca-2f1686b6f15c", "71c20c13-ddda-4177-ac9b-cf4096577450"]

So this array could obviously be anything, but I need to take each element and generate a string that looks like this.
String
"ManagerID='5d227c01-93dc-4f0b-abca-2f1686b6f15c' OR ManagerID='71c20c13-ddda-4177-ac9b-cf4096577450'"

I'm finding this hard because I have to add the OR after each ID but not after the last one and none if there is only 1 ID
It looks something like this
Code
def normalized_manager_ids
  if manager_id_list.count <= 1
    "ManagerID='#{manager_id_list.first}'"
  else
    manager_id_list.map do |id|
      # GENERATE STRING HERE BASED ON HOW MANY IDS THERE ARE
    end
  end
end

A: def normalized_manager_ids
  if manager_id_list.count <= 1
    "ManagerID='#{manager_id_list.first}'"
  else
    manager_id_list.map{ |id| "ManagerID='#{id}'" }.join(" OR ")
  end
end

or even shorter:
def normalized_manager_ids
  manager_id_list.map{ |id| "ManagerID='#{id}'" }.join(" OR ")
end

However, if you wan't to use this in SQL query, I would rather recommend using SQL IN operator instead - for example:
.where("ManagerID IN (?)", manager_id_list)


text:
Q: What's the best way to annihiliate an enemy's family? I was playing with William the Bastard, and after conquering England, i stumbled upon the problem of how to deal with the remaining Godwinsons(a few of them died in battle). So i just granted them bishoprics, apart from Harold himself, whom i kept as a prisoner at first, then castrated and plotted to revoke his titles.
A few decades later, the Duchess of Aquitaine decided to demand my installment upon the throne of France, declared war for my cause, i joined with her and before long i was also King of France. Same story again - i had some very powerful vassals i wanted to get rid off, and since the game doesn't permit you to go all Rains of Castamere on an enemy's family, i resorted to the same policy - giving a bishopric to any male i could find, and plotting to usurp titles/insult vassals so that they start plotting/declare war and i have a claim and can easily usurp their titles.
That generally works, but it's:

*

*Slow, i need to build a lot of temples

*Costly, #1

*I have a gazillion bishops who somewhat like me(because of land grant), but are from families i don't want to be around. Currently the best candidates for Chancellor, Spymaster and Court Chaplain are bishops from either the Godwinson or Capet families. And there are even one or two of them who became Cardinals.

So, here's my question in essence - is there any good way to destroy a family without incurring significant tyranny? I can hope to imprison all characters from a family, and execute/castrate/blind most of them, but everybody else will hate me(which is wrong, a Norman Duke in Jerusalem shouldn't care that a French Count of Champagne and his family were obliterated).
If they were my courtiers, i could also marry them to whomever i want(like old, sterile, lowborn people in the middle of nowhere), and order them to take the vows, but that's not always an option.

A: The good news is that you don't have to kill absolutely everyone. Claims gradually weaken and go away as they are inherited; killing a strong claim holder gives his heirs weak claims, which are much harder to push and carry lower opinion maluses.
If you do have targets living in your realm, don't forget that you can take the Intrigue focus with Way of Life and use the Spy On action. This grants additional opportunities to abduct and murder, on top of making it more likely that you will reveal any plots they are a part of, granting you Righteous Imprisonment reasons (i.e. without tyranny).
Short of mass (read: slow, gradual) murder — including the more contrived forms of getting them killed in battle or by disease — the only other way to end a dynasty is through marriage. You can marry the males matrilineally and the females regularly, and any of their progeny will not be of the same dynasty any more. This will still allow claims to be inherited normally, but if they're marrying into your dynasty, then it's problem solved (from the game-over point of view, at least).
Unfortunately, this is ill suited to your question, as your target dynasty is probably either 1) not under your direct control or 2) unwilling to accept an invite to your court, because the claim they hold is against your realm. But it can work well for the branches of the family that aren't an immediate threat to your realm. Regular marriage to a female, even with a strong claim or actually in the line of succession, is usually accepted by the AI. But matrilineal marriage will typically only be accepted if:

*

*The man is your direct courtier — if they hold a title, you can't get power over them by making them a member of your council.

*The woman is important enough — basically, if you have a female relative close enough to grant an alliance to a sitting ruler through marriage, you can get non-inheriting members of other great houses to marry them matrilineally.

*The man has no claims — useful for second generations who stand to inherit a claim, but haven't gotten it yet. If they aren't in the actual line of succession, the AI will usually let them go to matrilineal marriage.

*More generally, the woman has to be equal to or greater in importance than the man. So if you have a second cousin who's not getting any claims or any inheritances, you're going to have to settle for marrying them to an unimportant member of the target dynasty as well.

One other note is that it's also possible to end progeny through poor marriages. If you have someone with low fertility or nearing the end of childbearing years, they can serve as a stop-gap to prevent further procreation. Only very old men will accept a bride out of childbearing years (typically 65+, but I've seen it as low as 50), but the AI is less careful about allowing marriages to homosexual theologians or stressed, depressed or otherwise ill people. As a bonus, with the buffed up diseases in the latest patch, an unmarried small-pox sufferer might serve as a means to assassinate multiple targets!
Also keep in mind that negative congenital traits are simulated with recessive genetics in mind. If you can invite a hunchback to your court and get them to breed, you could have a set of poor spouses to draw upon for your nefarious familial wedding. If you marry enough hunchbacks into your target dynasty, it'll eventually resurface. You could also try to kill two birds with one marriage by getting the target dynasty members to marry each other. (!)
And of course, if you're Byzantine you can take a more punitive approach to reproduction – this still requires imprisonment, but doesn't seem to incur tyranny like execution. On the plus side, sieges on castles seem to have a much higher chance to result in capturing prisoners from the court, so a well timed war on a distant branch of the family or a revolting vassal could result in rounding up a bunch of claimants.
I kinda love how realistically this game rewards being a bad person... Straight up murder is frowned upon, but misogyny, sociopathy and germ warfare can help you take over the world.


text:
Q: loading images from GPX file - iOS MapKit CS193 example I'm following the example given in CS193p lecture 14 MapKit. I managed to load a gpx file (vacation.gpx that the lecturer used), but it only shows red pins and callouts without thumbnail and images when I click callouts.
In the original gpx file, all links work fine. How can I make it work? Please help.

A: oops.. I found how to make it work.
I added this in the .plist to unblock http security.
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>


text:
Q: Is there a simple way to tell if an arbitrary string is well-formed JSON in Android? We're writing an app that communicates with an internet-based CMS in JSON.  Unfortunately, some types of network connection e.g. through public Wifi have a web gateway that they require you to go through before you can use the net normally.  This means we are trying to JSON parse an HTML webpage.  I would expect it to throw an exception stating that the HTML isn't well-formed JSON but instead it tries to parse it, runs out of memory and collapses.
I have looked through the Android JSON functions and can't find a function that simply tells you if a string is JSON or not.  Is there such a function?  If not, am I simply going to have to write something heuristic to trap obviously non-JSON strings?

A: The exact way to check for its well-formed JSON is to create a JSONObject based on the string returned from HTTP Response. JSONException will occurs if the resulted string is not a well-formed JSON.
I don't know why you're running out of memory too soon. Is it because the returned string is very large? If so, you can take the advantages of the JSON format. Check the first character of the string. If it's { then it's probably JSON. Otherwise, it's not a JSON.
Please note the word "probably". It's because I don't know whether the server sometimes gives you another response with { as its first character and it's not a JSON. You decide.
You should read a JSON string formatted here.

A: You should be checking the Content-Type HTTP header of the response. If it is returning HTML, it will be text/html. If it is returning JSON, it will be application/json.

A: Telling you whether this is valid JSON or  not would require complete parsing. Android bundles vanilla JSON parse working on like XML DOM parser - those parsers try to construct complete syntax tree in  memory - thus they are prone to

*

*low performance

*heavy memory usage

I would suggest to use pull parser like  GSON  - there is also some kind of databinding which comes handy if you need objects out of your JSON or just strupped down binary ( 16KB ) to just parse ( I use it with my own databinding layer: https://github.com/ko5tik/jsonserializer )

A: Something like:
Header contentType = httpResponse.getFirstHeader("Content-Type");
if (contentType.getValue().compareToIgnoreCase("application/json") != 0) {
    // response is not JSON
    response = null;
}


text:
Q: Can't access php files copied into /var/www/ or other folders I'm on Ubuntu 12.10 with LAMP setup. I copied a subdirectory which has project files (php, html, css) from xampp/htdocs on my Windows PC into /var/www/ of my ubuntu. However, when I access those files from browser (I can see the directory listing), I get 403 Forbidden on all files within that directory.
So I create new dummy php files within that directory just to see if I can access, and it works. Any idea what might be the problem?

A: may be a ownership problem.
try do
chmod -R 775 /var/www/folder
and/or
chown -R domain:www-data /var/www/folder - where domain is the user of that particular virtualhost or www-data
for directory listing you may want to modify in /etc/apache2/sites-available/default
+Indexes
see http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/

A: This is how I solved the issue:
sudo su
chmod a+rwx /var/www/html/


text:
Q: Validating integer Input using a Mask (Asp .NET MVC 3.0)  My Model :
public virtual int? NumberTest { get; set; }

My View
@Html.LabelFor(model => model.NumberTest)
<br />
@Html.TextBoxFor(model => model.NumberTest)

I'm using Masked Input Plugin, so I have in my View :
$("#NumberTest").mask("99999-999");

My Html generated :
<input data-val="true" data-val-number="The field NumberTest must be a number." id="NumberTest" name="NumberTest" type="text" value="" />

So it automatically generated a number validation on my Integer input... And I'm using a mask with non-integer char to format number....
This validatior is always called when I fill the input ... How can I fix that?

A: What I did was set the data type to string so it would work with maskedinput, but then in a custom model binder, I stripped out all the non-numeric characters so it could save to the database as an int.  You still get both client-side and server-side protection because the user is prevented from entering non-numeric characters by maskedinput client-side and potentially bad characters are filtered out server-side.
Here's the custom model binder code:
public class CustomModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
    {
        if (value != null && propertyDescriptor.PropertyType == typeof(string))
        {
            // always trim strings to clean up database padding
            value = ((string)value).Trim();

            if ((string)value == string.Empty)
            {
                value = null;
            }
            else if ((propertyDescriptor.Attributes[typeof(PhoneNumberAttribute)] != null
                || propertyDescriptor.Attributes[typeof(ZipCodeAttribute)] != null
                || propertyDescriptor.Attributes[typeof(SocialSecurityNumberAttribute)] != null)
                && bindingContext.ValueProvider.GetValue(propertyDescriptor.Name) != null
                && bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue != null)
            {
                value =
                    Regex.Replace(bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue,
                                  "[^0-9]", "");
            }
        }

        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
    }
}

The custom attributes are just empty Attributes:
public class ZipCodeAttribute : Attribute { }

In the view model, just mark your field like this:
[ZipCode]
public string Zip { get; set; }

Here's how to do the whole thing with maskedinput, editor templates and unobtrusive validation.


text:
Q: Append line-break to tweet using JQuery I downloaded this jquery plugin in order to show my tweets on my website. However, I need to add a line break between each tweet as they are currently too close together. Please can you tell me how I can do this?
Here is my code so far:
<script type="text/javascript">
    jQuery(function($){
  $("#twitter").tweet({
    username: "so",
    avatar_size: 0,
    count: 2,
    loading_text: "loading tweets..."
  });
});

</script>

<div id="twitter" style="color: white;">
</div>

A: It looks as if the tweets are added in an unordered list, so you can do it in css:
#twitter li { margin-bottom: 15px; }


text:
Q: Convert a comma-separated value string into a list and convert all its value and keys into integer or float using comprehension suppose we have a list of list called A:
A = "1, 200, 1.9;2, 450, 8.2 ;2, 350, 0.3"

What I want to do are convert string above into a dictionary with first element as key and second as value, and after that I want to convert first and second element to int and the third to float.
So it will be as follows:
A = [[1, 200, 1.9],
     [2, 450, 8.2],
     [3, 350, 0.3]]

With first and second element converted to int and the last to float
I tried  list comprehension for this:
A = list([int(a), int(b), float(c) for a, b, c in row.split(',')] for row in A.split(';'))

Got SyntaxError: Invalid Syntax Error on it:
Any helps really appreciated

A: [[float(q) if "." in q else int(q) for q in i.split(",")] for i in A.split(";")]

output
[[1, 200, 1.9],
[2, 450, 8.2],
[2, 350, 0.3]]

A: Code like [1,2, c for c in range(2)] is invalid syntax because it is ambiguous and can mean any of these:

*

*[1,2,(0,1)]

*[1,(2,0), (2,1)]

*[(1,2,0), (1,2,1)]
It's impossible to tell what is meant by this code, so you have to be more specific.
To get any of these variants, construct the tuple explicitly:

*

*[1,2, tuple(c for c in range(2))]

*[1, *((2, c) c for c in range(2))]

*[(1, 2, c) c for c in range(2)]
You probably want the last one, so that'd be:
[(int(a), int(b), float(c)) for a, b, c in row.split(',')]

A: It's a bit ugly, but:
A = "1, 200, 1.9;2, 450, 8.2 ;2, 350, 0.3"
A = [(lambda a,b,c:[int(a),int(b),float(c)])(*x.split(',')) for x in A.split(';')]
print(A)

Output:
[[1, 200, 1.9], [2, 450, 8.2], [2, 350, 0.3]]

For more readability:
A = "1, 200, 1.9;2, 450, 8.2 ;2, 350, 0.3"

def convert(item):
    a,b,c = item.split(',')
    return [int(a),int(b),float(c)]

A = [convert(item) for item in A.split(';')]
print(A)


text:
Q: Use CSS to keep top level navigation hover effect on when mouse is over submenu I want to make my top level navigation stay on the hover state while I'm hovering on the submenu items. I read that I should apply the hover effect to the li, but there are some transitions that are confusing the situation for me. I can't figure it out. Can someone tell me where I need to adjust this?
my jsfiddle

A: You're going to want to apply the :hover effect to the li and apply the CSS to the direct a child. Applying the hover to the a won't work because the submenus of the top-level links aren't in the a element.
ul#navigation .topNav:hover > a {
    color:#acb453;
    padding-top:0;
    padding-bottom:10px;
    border-bottom: 6px solid #4dbaf2;
}

http://jsfiddle.net/zwVwh/12/


text:
Q: Не удается обработать нажатия клавиш экранной клавиатуры в Android Доброго времени суток! В своем приложении мне понадобилось реализовать ввод текста с экранной клавиатуры без использования EditText. Я хочу, чтобы текст, введенный пользователем, рисовался с помощью Canvas на SurfaceView.
Сама клавиатура вызывается следующим кодом:
InputMethodManager imm = (InputMethodManager) mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mainActivity.getCurrentFocus(),InputMethodManager.RESULT_SHOWN);

Фокусом является объект класса, унаследованного от SurfaceView и реализующего OnKeyListener. Проблема в том, что метод onKey() вызывается не во всех случаях, например, если переключить клавиатуру на русский язык, или использовать нестандартную клавиатуру, то onKey() вызываться не будет. Однако, все прекрасно работает с раскладкой qwerty (стандартной клавиатуры). Как в таком случае лучше получать информацию о вводимых символах? Где можно почитать про взаимодействие IME и EditText? Как последний получает от клавиатуры символы? Заранее спасибо!


text:
Q: Select 2 JS - Ignoring HTML Markup I'm using Select2 with Bootstrap. I have my HTML markup, As follows :

            Student
            <select class="form-control" name="student_id" id="student" style="width: 100%;">

            Firstname
            <input name="firstname" value="" class="form-control form__input" placeholder="First Name" data-error="Please enter a first name" required>

When I run the jQuery initialisation, It generates and breaks the HTML.
$('#student').select2(
    {
        placeholder: "Search For A Student",
        tokenSeparators: [','],
        ajax: {
            url: '/search/students/'+school_id+'',
            dataType: 'json',
            delay: 250,
            data: function (params)
            {
                return {
                    q: params.term, // search term
                };
            },
            processResults: function (data, params)
            {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;

                return {
                    results: $.map(data, function (item)
                    {
                        return {
                            id: item.id,
                            text: item.name
                        }
                    })
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        minimumInputLength: 3
    }
)

See attached screenshot
The HTML it produces is as follows :

            Student
            <select class="form-control select2-hidden-accessible" name="student_id" id="student" style="width: 100%;" tabindex="-1" aria-hidden="true">

           Firstname
            </select>

                            Search For A Student

            <input name="firstname" value="" class="form-control form__input" placeholder="First Name" data-error="Please enter a first name" required="">

Would anyone know a fix for this? Or have come across a similar issue in the past?
Thanks

A: I've not tested it, but I saw, that you haven't closed your select box for student in html markup. Maybe this helps.
<select class="form-control" name="student_id" id="student" style="width: 100%;"></select>


text:
Q: Поиск строк по заданному слову\букве\цифре Есть код для поиска строк:
procedure Form4.button1_Click(sender: Object; e: EventArgs);
var F:TextFile;// Переменной присваивается значение TextFile
Str:string;// Переменной присваивается значение String
begin
  Assign(F,'C:\Users\Неизвестен\Desktop\Записная\nomer.txt');
  reset(F);// Открывает текстовый файл для чтения
  while not eof(F) do// Цикл, который перебирает строки
   begin
      readln(F, Str);// Ввод слова\буквы\цифры для поиска строки
      if pos(textbox1.text, Str)>0 //  есть ли слово\буква\цифра в строке
      then
      textbox2.text:= str; // Вывод строки в текстбокс
   end;
   CloseFile(F);// Закрыть файл
end;

Код работает но возникла проблема. Допустим у меня есть в файле такая информация:
12345 Максим

67890 Максим

При вводе "Максим" мне выдает только посл. строку. А надо все строки в которых есть это слово. Как это организовать?
A: вместо
textbox2.text:= str;

написать
textbox2.Text:= textbox2.Text + #13#10 + str;

Если писать textbox2.text:= str;, то вы каждый раз будете затирать прошлую запись в текстбоксе. А когда напишете textbox2.Text:= textbox2.Text + #13#10 + str;, то к предыдущей записи будете прибавлять новую. Такая операция сложения строк называется конкатенацией.

Гуглите конкатенацию и прочие операции со строками.


text:
Q: Append data from one pandas dataframe into other one I'm trying to append latitude and longitude data from df table:
dict = {'city':['Wien', 'Prague','Berlin','London','Rome'],
        'latitude': [48.20849, 50.08804, 52.52437, 51.50853, 41.89193 ],
        'longitude': [16.37208, 14.42076, 13.41053, -0.12574, 12.51133]
       }
df = pd.DataFrame(dict)

# creating non duplicated pairs of cities
df_pair = pd.DataFrame(list(combinations(df.city, 2)), columns=['start_city', 'end_city'])

into df_pair's columns start_latitude, start_longitude, end_latitude, end_longitude (which will be created while appending):
    start_city  end_city
0   Wien        Prague
1   Wien        Berlin
2   Wien        London
3   Wien        Rome
4   Prague      Berlin
5   Prague      London
6   Prague      Rome
7   Berlin      London
8   Berlin      Rome
9   London      Rome

so the final dataframe (lets call df_pair_geo) look like this:
  start_city    end_city    start_latitude  start_longitude end_latitude end_longitude
0   Wien        Prague      48.20849        16.37208        50.08804     14.42076
1   Wien        Berlin      48.20849        16.37208        52.52437     13.41053
2   Wien        London      48.20849        16.37208        51.50853     -0.12574
3   Wien        Rome        48.20849        16.37208        41.89193     12.51133
4   Prague      Berlin      50.08804        14.42076        52.52437     13.41053
5   Prague      London      50.08804        14.42076        51.50853     -0.12574
6   Prague      Rome        50.08804        14.42076        41.89193     12.51133
7   Berlin      London      52.52437        13.41053        51.50853     -0.12574
8   Berlin      Rome        52.52437        13.41053        41.89193     12.51133
9   London      Rome        51.50853        -0.12574        41.89193     12.51133

But so far I was not able to do that. Is there a way how to do this? Thank you.

A: use merge.
df1 = df_pair.merge(df.set_index('city'), left_on='start_city', right_index=True, how='left')
df2 =     df1.merge(df.set_index('city'), left_on='end_city',   right_index=True, how='left', suffixes=['_start', '_end'])

# result
print(df2)

  start_city end_city  latitude_start  longitude_start  latitude_end  \
0       Wien   Prague        48.20849         16.37208      50.08804
1       Wien   Berlin        48.20849         16.37208      52.52437
2       Wien   London        48.20849         16.37208      51.50853
3       Wien     Rome        48.20849         16.37208      41.89193
4     Prague   Berlin        50.08804         14.42076      52.52437
5     Prague   London        50.08804         14.42076      51.50853
6     Prague     Rome        50.08804         14.42076      41.89193
7     Berlin   London        52.52437         13.41053      51.50853
8     Berlin     Rome        52.52437         13.41053      41.89193
9     London     Rome        51.50853         -0.12574      41.89193

   longitude_end
0       14.42076
1       13.41053
2       -0.12574
3       12.51133
4       13.41053
5       -0.12574
6       12.51133
7       -0.12574
8       12.51133
9       12.51133

A: Use DataFrame.join with DataFrame.add_suffix:
df1 = (df_pair.join(df.set_index('city').add_prefix('start_'), on='start_city')
              .join(df.set_index('city').add_prefix('end_'), on='end_city'))

print (df1)
  start_city end_city  start_latitude  start_longitude  end_latitude  \
0       Wien   Prague        48.20849         16.37208      50.08804
1       Wien   Berlin        48.20849         16.37208      52.52437
2       Wien   London        48.20849         16.37208      51.50853
3       Wien     Rome        48.20849         16.37208      41.89193
4     Prague   Berlin        50.08804         14.42076      52.52437
5     Prague   London        50.08804         14.42076      51.50853
6     Prague     Rome        50.08804         14.42076      41.89193
7     Berlin   London        52.52437         13.41053      51.50853
8     Berlin     Rome        52.52437         13.41053      41.89193
9     London     Rome        51.50853         -0.12574      41.89193

   end_longitude
0       14.42076
1       13.41053
2       -0.12574
3       12.51133
4       13.41053
5       -0.12574
6       12.51133
7       -0.12574
8       12.51133
9       12.51133


text:
Q: HTML + CSS for Centering Vertical Text next to an Image Hi Everybody and tks in advance for your help... I'm looking for the best practice to resolve a simple question:

.left {
  float: left;
  width: 79%;
  margin-right: 1%;
}
.left img {
  float: right;
}
.right {
  float: right;
  width: 20%;
}

A TEXT

How should I center the text vertically at the middle of the image (obviusly not using px in margin-top or bottom, because the width/height of the image will be dinamic).
Thanks!

A: You could use flexbox. See the example:
.main{
   display: flex;
   align-items: center;
}

https://jsfiddle.net/zb2ozq1k/1/

A: I'd get rid of float and use table-cells instead.  Then, use vertical-align:middle for the text.
Like this:

.main{
  display: inline-table;
  border: 1px solid blue;
}

.left {
  width: 79%;
  margin-right: 1%;
  display: table-cell;
  border: 1px solid green;
}

.right {
  width: 20%;
  border: 1px solid red;
  display: table-cell;
  vertical-align: middle;
}

A TEXT

A: h1 {
  display: inline;
   vertical-align:top;
}

A TEXT


text:
Q: PHP: Directly compare two times in H:i and determine if the new time is before 00:00 I currently have a start and end time in this format '00:00' e.g. H:i. I am currently trying to remove 4 hours from the time and then determine if the new time is the day before, e.g. before 00:00.
An example:
$oldStart =  '00:00';
$oldStart = date("H:i", strtotime($oldStart));
$oldEnd = '00:30';
$oldEnd = date("H:i", strtotime($oldEnd));
$newStart = date("H:i", strtotime('-4 hours', $oldStart));
$newEnd = date("H:i", strtotime('-4 hours', $oldEnd));
$dayStart = date("H:i", strtotime('00:00'));
if($newStart < $dayStart) {
    echo 'day before
';
} else {
    echo 'current day
';
}

I'm expecting this to echo 'day before' as the hours are now 4 hours behind, however it is echoing 'current day'. I can't see where I'm going wrong...

A: Just use this:
$old = "4:00";
$dt = new DateTime($old);
$dt->modify("-4 hours");
$new = $dt->format("Y-m-d");
if(date("Y-m-d", strtotime($old)) > $new){
    echo "Day before";
} else {
    echo "Same day";
}


text:
Q: Why will my MEAN app only (partially) run when I set the Angular build directory to /src/ instead of /dist/? I'm following Heroku's tutorial to create a contact list using the MEAN stack (Heroku's running example here). I'm able to deploy it to Heroku and it works there. But when I run it locally on my machine, the browser (Chrome 67.0.3396.87 on macOS High Sierra) only displays a "Cannot GET /" message.
I believe it's related to how the Angular build directory /dist/ referenced in line 12 of server.js does not exist (as far as I can tell). The beginning of server.js looks like this:
var express = require("express");
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var ObjectID = mongodb.ObjectID;

var CONTACTS_COLLECTION = "contacts";

var app = express();
app.use(bodyParser.json());

// Create link to Angular build directory
var distDir = __dirname + "/dist/";
app.use(express.static(distDir));

// Create a database variable outside of the database connection callback to reuse the connection pool in your app.
var db;

I looked into it and found that Angular deletes the /dist/ directory upon ng serve. I also found that there is a flag --delete-output-path whose default is true.
I set the --delete-output-path flag to false in .angular-cli.json as recommended by this answer as well as in /node_modules/@angular/cli/lib/config/schema.json. Despite those changes (trying to set the flag in one file, or the other file, or both files at the same time), I'm still getting the "Cannot GET /" message and the /dist/ directory still doesn't appear to be there.
The only way I've been able to even run part of the app is to change server.js's line 12 reference from /dist/ to /src/. This allows /src/index.html to begin loading at localhost:5000/ (the browser displays the text "Loading..." as specified in line 16 of index.html) and gets the contacts API up and running at localhost:5000/api/contacts/. But the Angular components (the list of contacts that is the purpose of the tutorial) don't load. Maybe because I changed the build directory to a totally different location.
Is there something with the /dist/ directory that I'm missing? Or does my issue with getting the app to run locally have nothing to do with /dist/ at all?

A: Notice that you don't have a way of handling requests to the route '/' since the line:
app.use(express.static(distDir));

only ensures that all bundled files generated in your "dist" folder are accessible when your index.html requires them, but you still have to serve the index.html itself. When using the MEAN stack one normally would do something like this:
app.use ('/api', yourApiRouter);
//and for everything else let the client-side routing handle the route:
app.get ('*', function(req, res) {
    res.sendFile(distDir + 'index.html');
}

I recommend to use the native "path" module to join your __dirname with your "dist" folder and your index.html location rather than simple concatenation.
You can use an arrow function instead of a callback when using app.get function if you are using ES6


text:
Q: How do I use common templates with $stateProvider? I'm quite new to AngularJS so please bear with me.
I have an app and I want to have common templates in it, for example a toolbar.
I've seen working examples in similar (but not exact) cases :

*

*Declare a state parent with "abstract" set to true and declare the common templates

*Declare a state child with "parent" set to true or using the dot notation and declare a template specific to the page

But those examples always use the index.html as the container for the common elements.
In my case, those common elements only appear in a certain section of the site.
Here's an example:
http://plnkr.co/edit/MMAoBXy9btGSqni2dRqL?p=preview
I could move the toolbar declaration to the "hello" state but then the common template would have to be linked to each state, like so:
$stateProvider

    .state('listmedias', {
        url : '',
        abstract : 'true',
        views : {
            'main@' : {
                templateUrl : 'hello.tpl.html'
            }
        }
    })

    .state('hello', {
        url : '/hello',
        parent : 'listmedias',
        views : {
            'toolbar' : {
                templateUrl : 'commonelement.tpl.html'
            }
            'container': {
                templateUrl : 'container.tpl.html'
            }
        }
    });

What can I do to have some sub section of the site use some common elements?
Thank you in advance!

A: Try this out,
.state('listmedias', {
  url : '',
  abstract : 'true',
  views : {
    'main@' : {
      templateUrl : 'hello.tpl.html'
    },
    'toolbar@listmedias' : {
      templateUrl : 'commonelement.tpl.html'
    }
  }
})


text:
Q: Android Studio: Parsing XML not well-formed error. <LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:orientation="horizontal"

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/hint_message"
        />

</LinearLayout>

That is my code. In Android Studio 1.2.1.1, it returns the errors:

*

*Error:(8) Error parsing XML: not well-formed (invalid token)

*Error:Execution failed for task ':app:processDebugResources'.
com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\hayden\AppData\Local\Android\sdk\build-tools\22.0.1\aapt.exe'' finished with non-zero exit value 1

I am using windows 8.My Code Encoding is set for windows-1252.
Please help.

A: <LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:orientation="horizontal" >

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/hint_message"
        />
</LinearLayout>

A: <LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:orientation="horizontal"> <!-- Here is the error you forgot to close LinearLayout-->

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/hint_message"
    />

</LinearLayout>

you forgot to write > after defining the properties in LinearLayout and this error you might have caught if you properly notice the color in the IDE. or you read the Error carefully.


text:
Q: Solving DLP by Baby Step, Giant Step I want to solve the DLP $6\equiv 2^x\pmod {101}$ using Baby Step, Giant Step.
$$$$
I have done the following:
We have that $n=\phi (101)=100$, since $101$ is prime.
$m=\lceil \sqrt{100}\rceil=10$.
For each $j\in \{0,1,\ldots , 9\}$ we calculate $(j,2^j)$:
\begin{align*}j \ \ \ & & \ \ \ 2^j \\ 0 \ \ \ & & \ \ \ 1 \\ 1 \ \ \ & & \ \ \ 2 \\ 2 \ \ \ & & \ \ \ 4 \\ 3 \ \ \ & & \ \ \ 8 \\ 4 \ \ \ & & \ \ \ 16 \\ 5 \ \ \ & & \ \ \ 32 \\ 6 \ \ \ & & \ \ \ 64 \\ 7 \ \ \ & & \ \ \ 27 \\ 8 \ \ \ & & \ \ \ 54 \\ 9 \ \ \ & & \ \ \ 7\end{align*}
It holds that $2^{-10}=1024^{-1}\equiv 65$.
For each $i\in \{0,1,\ldots , 9\}$ we calculate $6\cdot 65^i$:
\begin{align*}i \ \ \ & & \ \ \ 6\cdot 65^i \\ 0 \ \ \ & & \ \ \ 6 \\ 1 \ \ \ & & \ \ \ 87 \\ 2 \ \ \ & & \ \ \ 100 \\ 3 \ \ \ & & \ \ \ 36 \\ 4 \ \ \ & & \ \ \ 17 \\ 5 \ \ \ & & \ \ \ 95 \\ 6 \ \ \ & & \ \ \ 14 \\ 7 \ \ \ & & \ \ \ 1\end{align*}
Therefore for $i=1$ and $j=0$we get the same result, and so \begin{equation*}\log_26=7\cdot 10+0=70\end{equation*}
Is everything correct?

A: Using An Introduction to Mathematical Cryptography, J. Hoffstein, J. Pipher, J. H. Silverman, let's use Shank's Babystep, Giantstep Algorithm:

*

*Let $G$ be a group and let $g \in G$ be an element of order $N \ge 2$. The following algorithm solves the discrete logarithm problem in $\mathscr{O}(\sqrt{N} . \log N)$ steps.

*$(1)$ Let $N$ be the multiplicative order of $p$ and then $n = 1 + \lfloor \sqrt{N} \rfloor$, so in particular $n \gt \sqrt{N}$.

*$(2)$ Create two lists,
List $1: g, g^2, g^3, \ldots, g^n$,
List $2: h, h g^{-n}, h g^{-2n},h g^{-3n},\ldots, hg^{-n^2}$.

*$(3)$ Find a match between the two lists, say $g^{i} = h g^{-j\cdot n}$.

*$(4)$ Then, $x = i + jn$ is a solution to $g^x = h \pmod {p}$.
For this problem, we want to perform the algorithm to solve for $x$ in
$$2^x\equiv 6\pmod {101}$$
We have
$$g = 2, h = 6, p = 101$$
For $p = 101$, we have order $N = \phi{(101)} = 100$ in $\mathbb{F}^*_{101}$, so set $$n =  1 + \lfloor \sqrt{N} \rfloor = 1 + \lfloor\sqrt{100}\rfloor = 11$$
Set
$$u = g^{-n}\pmod{101} = 2^{-11} \pmod{101} = 83$$
Create the table
$$\begin{array}{|c|c|c|} \hline
 \text{k} & g^k & h u^k \\ \hline
 1 & 2 & 94 \\ \hline
 2 & 4 & 25 \\ \hline
 3 & 8 & 55 \\ \hline
 4 & 16 & 20 \\ \hline
 5 & 32 & 44 \\ \hline
 6 & 64 & 16 \\ \hline
 7 & 27 & 15 \\ \hline
 8 & 54 & 33 \\ \hline
 9 & 7 & 12 \\ \hline
 10 & 14 & 87 \\ \hline
 11 & 28 & 50 \\ \hline
\end{array}$$
From the table, we find the collision at $16$, so we have
$$x = i + jn = 4 + (6)(11) = 70$$
Hence, $x = 70$ solves the problem $2^x \equiv 6 \pmod{101}$ in $\mathbb{F}^*_{101}$.
Aside: Here is a calculator and nice description of the algorithm to verify or you can solve this using Wolfram Alpha.


text:
Q: How to integrate these pieces of code to protect against session hijacking I'm using these docs to integrate a certain level of protection against session hijacking (bottom of page).
While I can understand the basics of what the article explains, I'm still new to all this and I'm just not able to pin-point what I should do.
I get how this would work:
<?php

session_start();

if (isset($_SESSION['HTTP_USER_AGENT']))
{
    if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
    {
        /* Prompt for password */
        exit;
    }
}
else
{
    $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}

?>

... and I kinda understand how this can make the above more secure:
<?php

$string = $_SERVER['HTTP_USER_AGENT'];
$string .= 'SHIFLETT';

/* Add any other data that is consistent */

$fingerprint = md5($string);

?>

However, I'm stuck at combining the two into one working script. The docs state:

we should pass this fingerprint as a URL variable.

What does that mean? Do I need to pass the fingerprint in the URL and then use $_GET on each page? Anyone who can help me combining these two snippets of code into one file that I can include in all my PHP files?

A: yes, you'd need to add this token to any urls and then check it on every page.
Basically what you're trying to accomplish is what cryptographers call a NONCE
(number used once). The idea is to generate the NONCE using the params and then validate that the params haven't been tampered with.
Ideally this should be a hash salted with something random
and used once. There are many libraries that will take care of it for you.
Remember that hashes are not symmetric, i.e you can't un-hash request variables to see that it's the same thing.
What you can do is take a hash of the parameters and compare the hashes. It's important to remember about salts, because  without them you'd be susceptible to rainbow tables.
Also if you use  $_REQUEST  rather than  $_GET  you can reuse the same logic for both  $_POST  and  $_GET
You can take a look at this library for example,  http://fullthrottledevelopment.com/php-nonce-library
you can also borrow the nonce generating code from Wordpress


text:
Q: Creating Spinning Numbers until total is reached I had some help yesterday to achieve this:
http://jsfiddle.net/hopkins_matt/513ng07d/ (Thanks to Matt Hopkins) -----
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function timeSince() {
    var prevTime = new Date(2015,8,8,0,0);
    var thisTime = new Date();
    return (thisTime.getTime() - prevTime.getTime()) / 1000;
}

function parcelCount() {
    var secDiff = timeSince();

    var leftNum = document.getElementById("left");
    var midNum = document.getElementById("mid");
    var leftNumCount = Math.round(((76/60) * secDiff) + 40093794);
    var midNumCount = Math.round(((43/60) * secDiff) + 22874098);

    leftNum.innerHTML = numberWithCommas(leftNumCount);
    midNum.innerHTML = numberWithCommas(midNumCount);
}
parcelCount();
setInterval(parcelCount, 1000);

I also want to create a spinning total until the final figure is reached...
I.E.
We have shipped to 190 countries, is it possible to spin this number from 0-190 when the text is reached on screen?
So it would spin numbers until it reached the 190, then stop.
Any help would be appreciated :)

A: If you want just an animation from 0 - 190 you can use this.
Just loop one function increasing your display variable.

var totalShipped = 190;
var shippedDisplay = 0;
var shippedStep = totalShipped / (2 * 1000 / 100); // Animation duration 2 sec
function animateShipped() {
  if (shippedDisplay > totalShipped)
    shippedDisplay = totalShipped;
  document.getElementById("shipped").innerHTML = Math.round(shippedDisplay);
  if (shippedDisplay < totalShipped) {
    shippedDisplay += shippedStep;
    setTimeout(animateShipped, 100);
  }
}
animateShipped();

Shipped


text:
Q: Trying to receive a message from os x message w/ applescript Hey I'm running the following script:
using terms from application "Messages"
    on message received this_message from this_buddy for this_chat
        display dialog "test"
    end message received
end using terms from

But I get the following error every time in Messages when i get a message:
Event: Message Received in Active Chat
File: registerToReceiveMessages.applescript
Error: Error -1708

I can't find that error anywhere on the internet. It seems to work for every chat except the active chat. Any ideas?
Also I'm trying to add the events for "addressed message received" but everytime I compile applescript replaces that to "received remote screen sharing invitation"

A: You will get an Error -1708 whenever you have chosen an AppleScript which doesn't handle the specified event.
For example, if your script has only implemented on message sent, but you set this script to run every time you receive a message, you will get Error -1708. This is because your script only knows how to handle outgoing, not incoming messages, therefore, Error -1708.
Now here is something interesting...
If you attempt to use the default script Mix Message Case.applescript for the events Message Received, Message Received in Active Chat, and Message Sent. The first and last work fine, but you will get a -1708 error for the active chat event. We can deduce that this means the script isn't handling the event Message Received in Active Chat. And so it appears that not even Apple can handle this event right now.
OS X Mavericks Update:
This update fixes the previously mentioned bug. If you select Apple's sample script Speak Events.applescript, you will notice that it handles messages received to the active chat room flawlessly. If you examine the code, you will notice that it is using the on active chat message received method. We can now use that in our scripts. Since I no longer have the old version installed, I cannot test if this same method works in the previous version.
Here is the code from Speak Events.applescript:
on active chat message received with eventDescription
    say eventDescription
end active chat message received

Also notice how you no longer specify individual scripts to be run for specific events. Instead, you specify a single script handler for Messages events. This means that you must implement all the events in order to avoid getting -1708 methods. Notice how in the sample scripts, Apple even has the comment # The following are unused but need to be defined to avoid an error. Here is a template which can be used as a starting point for scripts:
using terms from application "Messages"
    # The following are unused but need to be defined to avoid an error

    on message sent theMessage with eventDescription
    end message sent

    on message received theMessage with eventDescription
    end message received

    on chat room message received with eventDescription
    end chat room message received

    on active chat message received with eventDescription
    end active chat message received

    on addressed message received theMessage from theBuddy for theChat with eventDescription
    end addressed message received

    on received text invitation with eventDescription
    end received text invitation

    on received audio invitation theText from theBuddy for theChat with eventDescription
    end received audio invitation

    on received video invitation theText from theBuddy for theChat with eventDescription
    end received video invitation

    on received local screen sharing invitation from theBuddy for theChat with eventDescription
    end received local screen sharing invitation

    on buddy authorization requested with eventDescription
    end buddy authorization requested

    on addressed chat room message received with eventDescription
    end addressed chat room message received

    on received remote screen sharing invitation with eventDescription
    end received remote screen sharing invitation

    on login finished with eventDescription
    end login finished

    on logout finished with eventDescription
    end logout finished

    on buddy became available with eventDescription
    end buddy became available

    on buddy became unavailable with eventDescription
    end buddy became unavailable

    on received file transfer invitation theFileTransfer with eventDescription
    end received file transfer invitation

    on av chat started with eventDescription
    end av chat started

    on av chat ended with eventDescription
    end av chat ended

    on completed file transfer with eventDescription
    end completed file transfer

end using terms from

If you begin with this script and implement only the methods you need (while leaving the rest intact), then you should avoid all -1708 errors.

A: I looks to me like the message received event handler only works when it feels like it in Messages. I had the same problem with a slightly different script. After finding another example on another website, copy-pasting it into a new AppleScript editor window and saving it over the AppleScript file copied to ~/Library/Scripts/Messages by Messages, it started to work.
There doesn't seem to be a problem with your script. If I replace my current script with your code and save the script, it works as expected, displaying a dialog containing the text test.
It may also be enough to just set the script to run to None and back to the script you created in the Messages Settings.


text:
Q: How can I make certain parts of my html not selectable? How can I make certain parts of my html not selectable?
I have some absolutely positioned divs that keep getting selected if a user tries to select the content of my page.
Is there a way to make it so certain elements (such as those divs) aren't selectable?
EDIT: The main issue is when someone copies these absolute div's and then pastes them into the rich text editor on my site, the rich text editor breaks on IE.

A: For IE, add the attribute unselectable="ON".  (EDIT: Although it won't completely help)
For Gecko, add the CSS style -moz-user-select: none.
For WebKit, add the CSS style -webkit-user-select: none.

A: If you want to just hide selection rectangle, you can use
element::selection { background: transparent }

and it's counterpart for Gecko
element::-moz-selection { background: transparent }

If you want to help your users select right text to copy to clipboard, you can move the element away. Usually browsers retain order of elements as they are defined in HTML when selecting. While it is not perfect solution, you can place the element's code in HTML either at the very beginning or very end of <body> tag. This way, if user selects something in the middle of the page, the element will be too "far away" to interfere.

A: this article might help with a cross-browser solution: (uses jQuery)
http://aleembawany.com/2009/01/20/disable-selction-on-menu-items-with-this-jquery-extension/
in theory, you can extend the jQUery core using this:
jQuery.fn.extend({
    disableSelection : function() {
            return this.each(function() {
                    this.onselectstart = function() { return false; };
                    this.unselectable = "on";
                    jQuery(this).addClass('unselectable');
            });
    }
});

and applying it like this:
// disable selection on selected objects
$('.myClass').disableSelection();

you must make sure you have this in your stylesheet:
.unselectable {
    user-select: none;
    -o-user-select: none;
    -moz-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
}

looks as if it basically does what SLaks and Sime have mentioned.
i haven't tried it, but i'd be interested to know if it works

A: You can use the ::selection pseudo-element to make the selection of a certain element "invisible":
p::selection { background-color:transparent; }
p::-moz-selection { background-color:transparent; }

However, that doesn't work in IE.

A: jQuery Solution:
$(".unselectable").disableSelection();


text:
Q: How do I insert a web page within my web page using frames I am trying to insert a iframe on my website, http://freefreemarkets.com, that allows me to insert the website showing what I am selling on eBay.
I have never created an iframe before.

A:

And you can edit how you want by adding stuff like:
width="400" height="215" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" etc..

A: You need to use an iframe, by specifying the src attribute:

Some websites doesn't support to be embedded in iframe, be careful.


text:
Q: What are file descriptors, explained in simple terms?
*

*What would be a more simplified description of file descriptors compared to Wikipedia's? Why are they required? Say, take shell processes as an example and how does it apply for it?

*Does a process table contain more than one file descriptor. If yes, why?

A: Other answers added great stuff. I will add just my 2 cents.
According to Wikipedia we know for sure: a file descriptor is a non-negative integer. The most important thing I think is missing, would be to say:
File descriptors are bound to a process ID.
We know most famous file descriptors are 0, 1 and 2.
0 corresponds to STDIN, 1 to STDOUT, and 2 to STDERR.

Say, take shell processes as an example and how does it apply for it?

Check out this code
#>sleep 1000 &
[12] 14726

We created a process with the id 14726 (PID).
Using the lsof -p 14726 we can get the things like this:
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF    NODE NAME
sleep   14726 root  cwd    DIR    8,1     4096 1201140 /home/x
sleep   14726 root  rtd    DIR    8,1     4096       2 /
sleep   14726 root  txt    REG    8,1    35000  786587 /bin/sleep
sleep   14726 root  mem    REG    8,1 11864720 1186503 /usr/lib/locale/locale-archive
sleep   14726 root  mem    REG    8,1  2030544  137184 /lib/x86_64-linux-gnu/libc-2.27.so
sleep   14726 root  mem    REG    8,1   170960  137156 /lib/x86_64-linux-gnu/ld-2.27.so
sleep   14726 root    0u   CHR  136,6      0t0       9 /dev/pts/6
sleep   14726 root    1u   CHR  136,6      0t0       9 /dev/pts/6
sleep   14726 root    2u   CHR  136,6      0t0       9 /dev/pts/6

The 4-th column FD and the very next column TYPE correspond to the File Descriptor and the File Descriptor type.
Some of the values for the FD can be:
cwd – Current Working Directory
txt – Text file
mem – Memory mapped file
mmap – Memory mapped device

But the real file descriptor is under:
NUMBER – Represent the actual file descriptor.

The character after the number i.e "1u", represents the mode in which the file is opened. r for read, w for write, u for read and write.
TYPE specifies the type of the file. Some of the values of TYPEs are:
REG – Regular File
DIR – Directory
FIFO – First In First Out

But all file descriptors are
    CHR – Character special file (or character device file)
Now, we can identify the File Descriptors for STDIN, STDOUT and STDERR easy with lsof -p PID, or we can see the same if we ls /proc/PID/fd.
Note also that file descriptor table that kernel keeps track of is not the same as files table or inodes table. These are separate, as some other answers explained.

You may ask yourself where are these file descriptors physically and what is stored in /dev/pts/6 for instance
sleep   14726 root    0u   CHR  136,6      0t0       9 /dev/pts/6
sleep   14726 root    1u   CHR  136,6      0t0       9 /dev/pts/6
sleep   14726 root    2u   CHR  136,6      0t0       9 /dev/pts/6

Well, /dev/pts/6 lives purely in memory. These are not regular files, but so called character device files. You can check this with: ls -l /dev/pts/6 and they will start with c, in my case crw--w----.
Just to recall most Linux like OS define seven types of files:

*

*Regular files

*Directories

*Character device files

*Block device files

*Local domain sockets

*Named pipes (FIFOs) and

*Symbolic links

A: In simple words, when you open a file, the operating system creates an entry to represent that file and store the information about that opened file. So if there are 100 files opened in your OS then there will be 100 entries in OS (somewhere in kernel). These entries are represented by integers like (...100, 101, 102....). This entry number is the file descriptor.
So it is just an integer number that uniquely represents an opened file for the process.
If your process opens 10 files then your Process table will have 10 entries for file descriptors.
Similarly, when you open a network socket, it is also represented by an integer and it is called Socket Descriptor.
I hope you understand.

A: All answer that are provided is great here is mine version --
File Descriptors are non-negative integers that act as an abstract handle to "Files" or I/O resources (like pipes, sockets, or data streams). These descriptors help us interact with these I/O resources and make working with them very easy. The I/O system is visible to a user process as a stream of bytes (I/O stream). A Unix process uses descriptors (small unsigned integers) to refer to I/O streams. The system calls related to the I/O operations take a descriptor as as argument.
Valid file descriptor ranges from 0 to a max descriptor number that is configurable (ulimit, /proc/sys/fs/file-max). Kernel assigns desc. for std input(0), std output(1) and std error(2) of the FD table. If a file open is not successful, fd return -1.
When a process makes a successful request to open a file, the kernel returns a file descriptor which points to an entry in the kernel's global file table. The file table entry contains information such as the inode of the file, byte offset, and the access restrictions for that data stream (read-only, write-only, etc.).

A: Any operating system has processes (p's) running, say p1, p2, p3 and so forth. Each process usually makes an ongoing usage of files.
Each process is consisted of a process tree (or a process table, in another phrasing).
Usually, Operating systems represent each file in each process by a number (that is to say, in each process tree/table).
The first file used in the process is file0, second is file1, third is file2, and so forth.
Any such number is a file descriptor.
File descriptors are usually integers (0, 1, 2 and not 0.5, 1.5, 2.5).
Given we often describe processes as "process-tables", and given that tables has rows (entries) we can say that the file descriptor cell in each entry, uses to represent the whole entry.
In a similar way, when you open a network socket, it has a socket descriptor.
In some operating systems, you can run out of file descriptors, but such case is extremely rare, and the average computer user shouldn't worry from that.
File descriptors might be global (process A starts in say 0, and ends say in 1 ; Process B starts say in 2, and ends say in 3) and so forth, but as far as I know, usually in modern operating systems, file descriptors are not global, and are actually process-specific (process A starts in say 0 and ends say in 5, while process B starts in 0 and ends say in 10).

A: Addition to above all simplified responses.
If you are working with files in bash script, it's better to use file descriptor.
For example:
If you want to read and write from/to the file "test.txt", use the file descriptor as show below:
FILE=$1 # give the name of file in the command line
exec 5<>$FILE # '5' here act as the file descriptor

# Reading from the file line by line using file descriptor
while read LINE; do
    echo "$LINE"
done <&5

# Writing to the file using descriptor
echo "Adding the date: `date`" >&5
exec 5<&- # Closing a file descriptor

A: File descriptors are nothing but references for any open resource. As soon as you open a resource the kernel assumes you will be doing some operations on it. All the communication via your program and the resource happens over an interface and this interface is provided by the file-descriptor.
Since a process can open more than one resource, it is possible for a resource to have more than one file-descriptors.
You can view all file-descriptors linked to the process by simply running,
ls -li /proc/<pid>/fd/ here pid is the process-id of your process

A: File Descriptors (FD) :

*

*In Linux/Unix, everything is a file. Regular file, Directories,
and even Devices are files. Every File has an associated number called File Descriptor (FD).

*Your screen also has a File Descriptor. When a program is executed
the output is sent to File Descriptor of the screen, and you see
program output on your monitor. If the output is sent to File
Descriptor of the printer, the program output would have been
printed.
Error Redirection :
Whenever you execute a program/command at the terminal, 3 files are always open

*
*standard input
*standard output

*standard error.
These files are always present whenever a program is run. As explained before a file descriptor, is associated with each of
these files.
File                                        File Descriptor
Standard Input STDIN              0
Standard Output STDOUT       1
Standard Error STDERR          2

*For instance, while searching for files, one
typically gets permission denied errors or some other kind of errors. These errors can be saved to a  particular file.
Example 1

$ ls mydir 2>errorsfile.txt

The file descriptor for standard error is 2.
If there is no any directory named as mydir then the output of command will be save to file errorfile.txt
Using "2>" we re-direct the error output to a file named "errorfile.txt"
Thus, program output is not cluttered with errors.
I hope you got your answer.

A: More points regarding File Descriptor:

*

*File Descriptors (FD) are non-negative integers (0, 1, 2, ...) that are associated with files that are opened.

*0, 1, 2 are standard FD's that corresponds to STDIN_FILENO, STDOUT_FILENO and STDERR_FILENO (defined in unistd.h) opened by default on behalf of shell when the program starts.

*FD's are allocated in the sequential order, meaning the lowest possible unallocated integer value.

*FD's for a particular process can be seen in /proc/$pid/fd (on Unix based systems).

A: As an addition to other answers, unix considers everything as a file system. Your keyboard is a file that is read only from the perspective of the kernel. The screen is a write only file. Similarly, folders, input-output devices etc are also considered to be files. Whenever a file is opened, say when the device drivers[for device files] requests an open(), or a process opens an user file the kernel allocates a file descriptor, an integer that specifies the access to that file such it being read only, write only etc. [for reference : https://en.wikipedia.org/wiki/Everything_is_a_file ]

A: A file descriptor is an opaque handle that is used in the interface between user and kernel space to identify file/socket resources. Therefore, when you use open() or socket() (system calls to interface to the kernel), you are given a file descriptor, which is an integer (it is actually an index into the processes u structure - but that is not important). Therefore, if you want to interface directly with the kernel, using system calls to read(), write(), close() etc. the handle you use is a file descriptor.
There is a layer of abstraction overlaid on the system calls, which is the stdio interface. This provides more functionality/features than the basic system calls do. For this interface, the opaque handle you get is a FILE*, which is returned by the fopen() call. There are many many functions that use the stdio interface fprintf(), fscanf(), fclose(), which are there to make your life easier. In C, stdin, stdout, and stderr are FILE*, which in UNIX respectively map to file descriptors 0, 1 and 2.

A: Hear it from the Horse's Mouth : APUE (Richard Stevens).
To the kernel, all open files are referred to by File Descriptors. A file descriptor is a non-negative number.
When we open an existing file or create a new file, the kernel returns a file descriptor to the process.  The kernel maintains a table of all open file descriptors, which are in use. The allotment of file descriptors is generally sequential and they are allotted to the file as the next free file descriptor from the pool of free file descriptors. When we closes the file, the file descriptor gets freed and is available for further allotment.
See this image for more details :

When we want to read or write a file, we identify the file with the file descriptor that was returned by open() or create() function call, and use it as an argument to either read() or write().
It is by convention that, UNIX System shells associates the file descriptor 0 with Standard Input of a process, file descriptor 1 with Standard Output, and file descriptor 2 with Standard Error.
File descriptor ranges from 0 to OPEN_MAX. File descriptor max value can be obtained with ulimit -n. For more information, go through 3rd chapter of APUE Book.

A: File descriptors

*

* To Kernel all open files are referred to by file descriptors.

* A file descriptor is a non - negative integer.

*When we open an existing or create a new file, the kernel returns a file descriptor to a process.

* When we want to read or write on a file, we identify the file with file descriptor that was retuned by open or create, as an argument to either read or write.

* Each UNIX process has 20 file descriptors and it disposal, numbered 0 through 19 but
    it was extended to 63 by many systems.

*
    The first three are already opened when the process begins
       0: The standard input
       1: The standard output
       2: The standard error output

* When the parent process forks a process, the child process inherits the file descriptors of the parent

A: I'm don't know the kernel code, but I'll add my two cents here since I've been thinking about this for some time, and I think it'll be useful.
When you open a file, the kernel returns a file descriptor to interact with that file.
A file descriptor is an implementation of an API for the file you're opening. The kernel creates this file descriptor, stores it in an array, and gives it to you.
This API requires an implementation that allows you to read and write to the file, for example.
Now, think about what I said again, remembering that everything is a file — printers, monitors, HTTP connections etc.
That's my summary after reading https://www.bottomupcs.com/file_descriptors.xhtml.


text:
Q: Homogeneous linear and quadratic inequalities I have a bunch of vectors $b_i \in R^n$ for $i = 1,\ldots,N$ and a bunch of (indefinite) matrices $A_j$ for $j = 1,\ldots,M$. Let's consider the set $S \subset R^n$ of $x \in R^n$ vectors such that
$$ (x,b_i) \geq 0 $$
$$ (x,A_j x) \geq 0 $$
for all $i$ and $j$. Clearly $0 \in S$ and since both conditions are homogeneous, $\lambda x \in S$ if $x \in S$ for $\lambda \geq 0$. So $S$ contains the origin and is connected. It is either the origin only (trivial case) or a set with positive dimension (non-trivial case).
Are there general theorems for finding out if for given $b_i$ and $A_j$ data the situation is trivial or not?


text:
Q: Problem getting XML elements in an SVG file I am trying to read a very basic SVG file which has the following contents:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="600" height="300" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <g stroke="black" >
        <line x1="75" y1="160" x2="525" y2="160" stroke-width="10"/>
    </g>
</svg>

I am trying to get a collection of line elements.  However, the following code does not work:
XDocument XD = XDocument.Load(PathToFile);
XElement SVG_Element = XD.Root;
var adam = SVG_Element.Elements("line");

Upon inspecting the variables, the document is loaded properly, but the variable "adam" remains null, as if it does not find any elements with that name.  Any help is appreciated.
Edit: Using Descendants does not fix this.  It still comes up empty.

A: Alright guys, I did figure this out.  Apparently I need to specify the namespace as part of the QName:
var adam = SVG_Element.Descendants("{http://www.w3.org/2000/svg}line");

A: The line element is a grandchild of the root, not a child.  Try the Descendants() method of the XDocument instead.

A: Try something like this:
Dim xmldoc As XDocument = XDocument.Load(Server.MapPath("PathtosvgFile"))

        Dim Info As IEnumerable(Of XElement) = _
            From typeElement In xmldoc.Descendants.Descendants
            Where typeElement.Parent = "g"
            Select typeElement

        Dim tel As XElement

        For Each tel In Info.DescendantsAndSelf.Distinct()
         'Access each descendant here and do something.
        Next

A: I never used XDocument to parse Xml files. I use XmlDocument. But I believe both work on a similar fashion.
My guess is that you should first query for the "g" element, and then for the "line" element, something like the following:
XDocument XD = XDocument.Load(PathToFile);
XElement SVG_Element = XD.Root;
var gs = SVG_Element.Elements("g");
var adam = gs[0].Elements("line");
Hope it helps.

A: XDocument SVGDoc = XDocument.Load(yourfile);
XElement svg_Element = SVGDoc.Root;

IEnumerable<XElement> gElement = from e1 in svg_Element.Elements("{http://www.w3.org/2000/svg}g")
                                 select e1;
int nCounter = 0;
foreach (XElement myElement in gElement)
{
    ...
}


text:
Q: Having trouble understanding this error creating a thread      HANDLE  hThread;
     DWORD   dwThreadId;

         hThread = CreateThread(
     NULL,                   // default security attributes
     0,                      // use default stack size
     MyThreadFunction,       // thread function name
     0,                      // argument to thread function
     0,                      // use default creation flags
     &dwThreadId);           // returns the thread identifier  <--Debugger takes me to this line?

The error specifies the 3rd parameter but when i double click on the error it takes me to the last parameter?
Trying to run the msdn CreateThread example http://msdn.microsoft.com/en-us/library/ms682453%28VS.85%29.aspx
error C2664: 'CreateThread' : cannot convert parameter 3 from 'void (void)' to 'unsigned long (__stdcall *)(void *)'
        None of the functions with this name in scope match the target type

A: The debugger is just taking you to the end of the statement.
In any case, your function signature is wrong and needs to match the function pointer type. For CreateThread, it should be:
DWORD WINAPI ThreadProc(LPVOID lpParameter);

A: Your function signature does not match the expected signature.
Your MythreadFunction function should return ULONG.
Something like:
DWORD WINAPI MyThreadFunction(LPVOID lpParameter) {
}

A: When you double-click the error, it brings up the source for where the error occurred.  Since the function call expression spans multiple lines, it will select the last line of the expression.
The problem is that MyThreadFunction does not have the correct function type.  MyThreadFunction is a function that takes no arguments and returns nothing.  You need to pass a pointer to a function that takes one argument (a void*) and returns an unsigned long.

A: Clicking on the error takes you to the last parameter because the go-to-error function can only go by statements, and the entire function call is one statement.
Basically, your problem is that MyThreadFunction has the wrong signature. It should be unsigned long __stdcall MyThreadFunction(void*) (or the equivalent thereof), but you wrote void MyThreadFunction(void) (or the equivalent thereof).