text:
Q: how to make a image button that change the image when mouse over button WPF? I am trying to make an image button that changes the image when the mouse is over the button, i tried few things
this is the last thing I tried but it doesn't work:
<Button Name="fileNameLink" Margin="15,6,30,1" VerticalAlignment="Top"    Click="btnMinimize_Click" MaxWidth="250" Background="Transparent" Cursor="Hand" Visibility="Visible" Height="16">
                    <Button.Template>
                        <ControlTemplate TargetType="Button">
                            <StackPanel>
                                <Image Name="image1"  Source="{StaticResource Minimize1}" Stretch="None" Visibility="Collapsed"/>
                                <Image Name="image2" Source="{StaticResource Minimize2}" Stretch="None" Visibility="Visible"/>
                                <StackPanel.Triggers>
                                    <Trigger Property="IsMouseOver" Value="true">
                                        <Setter TargetName="image1" Property="Visibility" Value="Visible"/>
                                        <Setter TargetName="image2" Property="Visibility" Value="Collapsed"/>
                                        </Trigger>
                                </StackPanel.Triggers>
                            </StackPanel>
                        </ControlTemplate>
                    </Button.Template>
                    <Button.Style>
                        <Style TargetType="Button">
                            <Style.Triggers>
                            </Style.Triggers>
                        </Style>
                    </Button.Style>
                </Button>

i am tring to use the XAML only, without the cs file
Thanks

A: Your Trigger's are applied to the StackPanel. It needs to be set on the ControlTemplate
Try:
<Button Name="fileNameLink"
        Height="16"
        MaxWidth="250"
        Margin="15,6,30,1"
        VerticalAlignment="Top"
        Click="btnMinimize_Click"
        Background="Transparent"
        Cursor="Hand"
        Visibility="Visible">
  <Button.Template>
    <ControlTemplate TargetType="Button">
      <StackPanel>
        <Image Name="image1"
                Source="{StaticResource Minimize1}"
                Stretch="None"
                Visibility="Collapsed" />
        <Image Name="image2"
                Source="{StaticResource Minimize2}"
                Stretch="None"
                Visibility="Visible" />
      </StackPanel>
      <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver"
                  Value="true">
          <Setter TargetName="image1"
                  Property="Visibility"
                  Value="Visible" />
          <Setter TargetName="image2"
                  Property="Visibility"
                  Value="Collapsed" />
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
  </Button.Template>
</Button>

In such cases. You can just use the Trigger to set the Image's source thereby not having to play with switching Visibility on multiple UI element's.
something like:
<Button Name="fileNameLink"
        Height="16"
        MaxWidth="250"
        Margin="15,6,30,1"
        VerticalAlignment="Top"
        Click="btnMinimize_Click"
        Background="Transparent"
        Cursor="Hand"
        Visibility="Visible">
  <Button.Template>
    <ControlTemplate TargetType="Button">
      <Image Name="image"
              Source="{StaticResource Minimize1}"
              Stretch="None" />
      <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver"
                  Value="true">
          <Setter TargetName="image"
                  Property="Source"
                  Value="{StaticResource Minimize2}" />
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
  </Button.Template>
</Button>

A: You will need a helper class to attach the image source property per button state and a style for your button. Put the helper class in a Helpers folder in your WPF project.
Helper class
public static class ImageLoader
{
    public static ImageSource GetDefaultImage(DependencyObject obj)
    {
        return (ImageSource)obj.GetValue(DefaultImageProperty);
    }
    public static void SetDefaultImage(DependencyObject obj, ImageSource value)
    {
        obj.SetValue(DefaultImageProperty, value);
    }

    public static readonly DependencyProperty DefaultImageProperty =
        DependencyProperty.RegisterAttached(
        "DefaultImage",
        typeof(ImageSource),
        typeof(ImageLoader),
        new UIPropertyMetadata(null));

    public static ImageSource GetHoverImage(DependencyObject obj)
    {
        return (ImageSource)obj.GetValue(HoverImageProperty);
    }
    public static void SetHoverImage(DependencyObject obj, ImageSource value)
    {
        obj.SetValue(HoverImageProperty, value);
    }

    public static readonly DependencyProperty HoverImageProperty =
        DependencyProperty.RegisterAttached(
        "HoverImage",
        typeof(ImageSource),
        typeof(ImageLoader),
        new UIPropertyMetadata(null));

    public static ImageSource GetDisabledImage(DependencyObject obj)
    {
        return (ImageSource)obj.GetValue(DisabledImageProperty);
    }
    public static void SetDisabledImage(DependencyObject obj, ImageSource value)
    {
        obj.SetValue(DisabledImageProperty, value);
    }

    public static readonly DependencyProperty DisabledImageProperty =
        DependencyProperty.RegisterAttached(
        "DisabledImage",
        typeof(ImageSource),
        typeof(ImageLoader),
        new UIPropertyMetadata(null));
}

Button Style
<ResourceDictionary ...
                    xmlns:helper="clr-namespace:MySolution.MyWPFProject.Helpers"
                    ...
                    >

    <Style TargetType="{x:Type Button}" x:Key="MyButtonStyle">
        ...
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid>
                        <ContentPresenter Name="content"
                                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                          Margin="{TemplateBinding Padding}"
                                          RecognizesAccessKey="True"
                                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                      />
                        <Border>
                            <!-- Default image -->
                            <Image Name="image"  Source="{TemplateBinding helper:ImageLoader.DefaultImage}" />
                        </Border>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Cursor" Value="Hand" />
                            <!-- Hover image -->
                            <Setter TargetName="image" Property="Source" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Button}, Path=(helper:ImageLoader.HoverImage)}" />
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <!-- Disabled image -->
                            <Setter TargetName="image" Property="Source" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Button}, Path=(helper:ImageLoader.DisabledImage)}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Usage
<UserControl ...
             xmlns:helper="clr-namespace:MySolution.MyWPFProject.Helpers"
             ...
             >
        <UserControl.Resources >
                <ResourceDictionary Source="Path-to-my-button-style.xaml" />
        </UserControl.Resources>
        ...
        <Button helper:ImageLoader.DefaultImage="Resources/Images/MyDefaultImage.png"
                helper:ImageLoader.HoverImage="Resources/Images/MyHoverImage.png"
                helper:ImageLoader.DisabledImage="Resources/Images/MyDisabledImage.png"
                Style="{DynamicResource MyButtonStyle}" />

        ...

A: You can achieve this by Image style:
<Button Name="fileNameLink" VerticalAlignment="Top" Click="btnMinimize_Click" MaxWidth="250" Height="100">
    <Button.Content>
        <StackPanel>
            <Image Name="image1"  Source="{StaticResource Minimize1}" Stretch="None" >
                <Image.Style>
                    <Style TargetType="Image">
                        <Setter Property="Visibility" Value="Visible" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" Value="True">
                                <Setter Property="Visibility" Value="Collapsed" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Image.Style>
            </Image>
            <Image Name="image2" Source="{StaticResource Minimize2}" Stretch="None" >
                <Image.Style>
                    <Style TargetType="Image">
                        <Setter Property="Visibility" Value="Collapsed" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" Value="True">
                                <Setter Property="Visibility" Value="Visible" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Image.Style>
            </Image>
        </StackPanel>
    </Button.Content>
</Button>

A: Here is another approach to handle it using a specialized style. It should be pointed out, that this could be further improved with using attached properties for customizing the image files properly.
<Style x:Key="ButtonStyle" TargetType="Button">
    <Setter Property="VerticalContentAlignment" Value="Stretch"/>
    <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <Grid>
                    <Rectangle Fill="Transparent"/>
                    <Image x:Name="img" Width="64" Height="64" Source="a.jpg"/>
                </Grid>
                <DataTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="img" Property="Source" Value="b.jpg"/>
                    </Trigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

The Rectangle is important for the hit testing, otherwise the IsMouseOver won't trigger. And the Stretch on the ContentAlignment is necessary otherwise the ContentPresenter of the button would not span the whole button, therefore IsMouseOver wouldn't trigger again.


text:
Q: Using slashes in tel: URIs It's pretty clear that the correct way to link to a phone number from HTML is with a URI like tel:2065551212.  However many browsers also accept telephone URIs with slashes, a la tel://2065551212 even though this is AFAICT not allowed by the relevant RFC (3966).
So, my question is this: why do some people recommend using slashes?  Is it just a bad habit from http URIs?
Or... Were there actually some early mobile browsers that did not properly recognize tel: links without the slashes?  I have read at least one blogger indicating that this is the case, which is a poor but understand excuse for doing so.  Can anybody provide an example where tel://### would work but tel:### would not?

redpajama_set_name: RedPajamaStackExchange


text:
Q: CakePHP delete session on user leave How could I check if a user has left my login form? Not logging in but actually leaving it?
As I want to delete the Auth.redirect session if they choose not to login so that when they return later they are not taken to their previous session!
So essentially running this:
$this->Session->delete('Auth.redirect');
I'm thinking some kind of check in the AppController that knows when a user was referred from the login form and deletes the session auth.redirect???
Or better yet checking if the current page is the login form and if not then delete the session!!!
and for those that are interested, this is how my login method currently looks:
function login()
{
        if(!(empty($this->data)) && $this->Auth->user())
        {
            $back_to = $this->Session->read('back_to');

            $auth_redirect = $this->Session->read('Auth.redirect');

            if($auth_redirect)
            {
                $this->redirect($auth_redirect, null, true);
            }
            else if($back_to)
            {
                $this->redirect($back_to, null, true);
            }
            else
            {
                $this->redirect($this->Auth->redirect(), null, true);
            }
        }
        else
        {
            $this->Session->write('back_to', $this->referer());
        }
}

Thanks

A: I am not familiar with CakePHP but your question sounds a bit strange to me. You are talking about PHP, a server side scripting language. A PHP script gets executed only when a request comes in (please correct me if there is something I don't know yet).
So, when a user calls the login page, the script gets executed. Now think of the following: Just after the login page has been loaded, the user closes the browser-tab with the login page. This does not trigger a request, so there is no possibility to inform the server about that action.
Maybe CakePHP can do such magical things, but I think we are talking about stateless HTTP, so I can't imagine how to realize something like that.

A: You could add a timestamp to the session of when you have last received a request from the user. For example, in AppController::beforeFilter, just add $this->Session->write('lastSeen', time()). You can then check how much time elapsed between the last time the user opened any page, and discard the Auth.redirect value if that interval was too long.
That's basically the same as expiring the session, just in a more controlled fashion. If you want to count the time a user simply has your page displayed on his screen as "activity" as well, you can use some Javascript AJAX to keep sending requests to the server to signal "I'm active!"
That's all quite a lot of work for very little benefit though. HTTP is stateless and doesn't allow you to track the user easily, period. Actually tracking whether a user is "actively" watching your page or not incurs a huge overhead and in this case seems like misplaced effort for the extraordinarily narrow purpose you want to use it for.

A:         if($this->here != '/admin/login')
        {
            $this->Session->delete('Auth.redirect');
        }

or this:
if($this->here != Router::url(array('admin'=>true,'controller'=>'users','action'=>'login')))
            {
                $this->Session->delete('Auth.redirect');
            }


text:
Q: Starting ddd with remote gdbserver I'm debugging a program that runs on a remote target using ddd ( the remote gdbserver is running on localhost over port 1234 for example, but still acts as remote).
I know you can connect to the gdbserver by opening ddd, then calling target remote localhost:1234 on the gdb command line of ddd, as described in:
http://www.gnu.org/software/ddd/manual/html_mono/ddd.html#Remote%20Program
However, I hate having to call the target remote localhost:1234 command every time I open ddd, and I'd like to set it to connect to the gdbserver automatically with an alias. I tried running ddd --rhost localhost:1234 program, but once ddd launches a window pops stating that "GDB could not be started", and in the shell written:

sh: 1: exec: localhost:1234: not found

Anyone knows how can I attach to the remote gdbserver right on launch?
Tnx!

A: Choose one of:

*

*ddd --eval-command="target remote localhost:1234"

*put target remote localhost:1234 into a file and use --command
to execute it

*put target remote localhost:1234 into your .gdbinit


text:
Q: Is CouchDB proxy authentication implemented in IBM Cloudant? As stated by Apache CouchDB documentation:

Proxy authentication is very useful in case your application already uses some external authentication service and you don't want to duplicate users and their roles in CouchDB.

Hence a reverse proxy can authenticate a user and send the username (as X-Auth-CouchDB-UserName HTTP header) along with a token (as X-Auth-CouchDB-Token) generated from this username and a general shared secret (not related with this particular user).
As stated:

This authentication method allows creation of a User Context Object for remotely authenticated user.

This user context can be useful in a validate_doc_update function (for authorizations) or in an update function (for accounting).
Among third party CouchDB hosts, IBM cloudant is one of the most famous. However the product is slightly different, especially concerning security (see matrix).
Whereas I am familiar with proxy authentication in Apache CouchDB, I didn't manage to setup a similar feature in Cloudant nor to find documentation about it. In particular, IBM "API keys" (composed by a key and a password) don't seem to be compatible with setting a different username as X-Auth-CouchDB-UserName.
Does anyone succeeded in setting up (in Cloudant) a user context different from the credentials used for authentication? Or is there a doc anywhere saying that it is not possible?

A: @robert-newson confirms that:

Cloudant does not enable the proxy authentication handler nor supports
externalising authentication/authorization decisions in any other way.
Use either IBM IAM or the CouchDB _users database within your account
(note that the _users database option is not available for Transaction
Engine instances).


text:
Q: Unity5 OnTriggerEnter2D not called after collision (2D game) I'm brand new to Unity3D 5 and I'm having issues with my first 2D game involving collision detection. My moving object is a ball and has Rigidbody2D and CircleCollider2D. My stationary "collider or trigger" is a BoxCollider and has a script attached. The OnTriggerEnter2D should be fired when the ball passes through the stationary box. I've also tried OnCollisionEnter2D but I'm fairly certain I should use OnTriggerEnter2D because my stationary box is marked as a trigger.
My code:
public class LoseCollider : MonoBehaviour {

public LevelManager levelManager;

void OnCollisionEnter2D(Collision2D collision)
{
    print("collide");
    levelManager.LoadLevel("Lose");
}

void OnTriggerEnter2D(Collider2D trigger)
{
    print("trigger");
    levelManager.LoadLevel("Lose");
}

void OnCollisionEnter(Collision collision)
{
    print("collide");
    levelManager.LoadLevel("Lose");
}

void OnTriggerEnter(Collider trigger)
{
    print("trigger");
    levelManager.LoadLevel("Lose");
}
}

As you can see I'm testing all variations and none are being called. Here are my Unity properties for my objects:

And

I'm sure I'm missing something simple if anyone can please point it out to me.

A: If you are going to to use OnTriggerEnter2D, you must also use a 2D Collider. You are currently using BoxCollider as shown in your second screenshot.
Change that to BoxCollider2D and your Collision callback functions should be called.

A: I know you already solved it, but I ran into the same problem and found your post. I was using the correct 2D collider, I was missing the Ridgedbody 2D component. It took me a while to find that so I wanted to add it here in case someone else comes across the same problem.


text:
Q: Accidentally deleted openssl lib packages and can't get yum or wget to work again So I was trying to upgrade openssl and decided to remove the existing openssl packages because it was from a different repository.
Once removed, I can't no longer get either yum or wget to work again because they all seem to rely on ssl
I'm missing the files
libssl.so.10
libcrypto.so.10

I was able to recover libssl.so.10 by using libssl3.so that existed locally, but not with libcrypto.so.10 yet (since this file probably need to be downloaded from a remote location).
yum:
The error leading to this problem was:
libcrypto.so.10: cannot open shared object file: No such file or directory

wget:
wget: error while loading shared libraries: libcrypto.so.10:

In other words, I'm now in a catch-22; I can't use yum, wget, curl, rpm (with url), or rsync (by connecting to a backup server instance) because they all require ssl lib files.
I can't even open a new SSH to the problematic server since SSL lib files is now gone. (can only access with existing Putty prompt).
I try "copy and paste" the file content with VIM editor using another snapshot backup but doesn't seem working.
I'm thinking if there is a way to download a rpm or even a single file over plain http using existing tools not listed above...

A: NOT SO GOOD. Try and avoid --force in RPM command unless you know what you're doing.
To try and recover to a decent state so you can attempt proper recovery, run from the backup or another identical server:
# tar cfz - $(rpm -ql openssl) | base64 > oh_my_god_what_did_I_do

Copy the output of that (in the oh_my_god_what_did_I_do file) into the clipboard and paste it into the other server:
# cat > oh_my_god_what_did_I_do
(paste here)
^D
# cd /; base64 -d < oh_my_god_what_did_I_do | tar xfz -

Good luck.
(if you're savvy, you can come up with other ways to move that file. NFS, netcat, it's not hard to find something)


text:
Q: How to get index value for specific table from mysql? How to get mysql index value for specific table from MySQL?

"Most MySQL indexes (PRIMARY KEY, UNIQUE, INDEX, and FULLTEXT) are
  stored in B-trees."

As you can check out in documentation it is B-trees?

A: Study BTrees.  More specifically, B+Trees.
Let's search for a single item by the BTree index.  A BTree has a root node; start there.  It has perhaps 100 links to subnodes and information on range of value to be found in each.  You go into the appropriate subnode.  For a small table, you are finished.  But for a huge table, you repeat the process a few times.  (Perhaps 6 iterations for a table with a trillion rows.)  Done.  You have found the one row you wanted.
Now, let's fetch a "range" of rows.  (Example:  WHERE id BETWEEN 1234 and 9876 or WHERE name LIKE 'T%'  Do the above to find the first of the range, then go to the 'next' record in the bottom ("leaf") node you are in.  This is fine until you run out of records in the leaf node.
How the + in B+Tree kicks in.  It means that there is a link from this node to the 'next' node at the bottom level.  So it is quite quick to continue the range query.
Statistics for a million-row table with a "fan-out" of 100:
To find a particular item:  3 nodes (16KB blocks in the case of InnoDB) need to be touched.
To fetch 500 consecutive rows:  3 nodes to get to the start; then about 5 more to scan forward.
Compare...  If there were no index, you would need to scan the entire table of about 10,000 blocks (1M/100).  This would be required for either of the hypothetical queries above.
In InnoDB (in MySQL), nearly all of the keys you ever make will be PRIMARY KEY, UNIQUE, and INDEX.  Those are B+Trees; there is no option (unlike other vendors).  Other than that, there are SPATIAL in FULLTEXT; they are more complex.
If you do SHOW CREATE TABLE foo, you get some info about the indexes.  `information_schema has further info.


text:
Q: Using $@ properly I am trying to write a tiny script that accepts any number of command line arguments that prints out the rwx permissions for a file (not directory)
What I have is
file=$@
if [ -f $file ] ; then
ls -l $file
fi

This accepts only one command line argument however.  Thanks for any help.

A: Here is a demonstration of the some of the differences between $* and $@, with and without quotes:
#/bin/bash
for i in $*; do
    echo "\$*: ..${i}.."
done; echo
for i in "$*"; do
    echo "\"\$*\": ..${i}.."
done; echo
for i in $@; do
    echo "\$@: ..${i}.."
done; echo
for i in "$@"; do
    echo "\"\$@\": ..${i}.."
done; echo

Running it:
user@host$ ./paramtest abc "space here"
$*: ..abc..
$*: ..space..
$*: ..here..

"$*": ..abc space here..

$@: ..abc..
$@: ..space..
$@: ..here..

"$@": ..abc..
"$@": ..space here..

A: How about this one:
for file
do
    test -f "$file" && ls -l "$file"
done

The for loop by default will work on $@, so you don't have to mention it. Note that you will need to quote "$file" in case if the file name has embedded space. For example, if you save your script to 'myll.sh':
$ myll.sh "My Report.txt" file1 file2

Then "My Report.txt" will be passed in as a whole token instead of 2 separate tokens: "My" and "Report.txt"

A: The variable you want is indeed $@ - this contains all command-line arguments as separate words, each passed on intact (no expansion). ($* treats all of them as a single word - good luck sorting it out if you have spaces in filenames).
You can loop, if you like. This is easily expanded to more complex actions than ls.
for file in "$@"; do
    if [ -f "$file" ]; then
        ls -l "$file"
    fi
done

Note: you should quote $@ to protect any special characters inside! You should also quote $file for the same reason - especially inside the test. If there is an empty string in $@, file will also be empty, and without quotes, -f will attempt to act on the ']'. Errors ensue.
Also, if all you need to do is ls (skipping your if) you can just do this:
ls -l "$@"

A: You could usefully loop over any files specified like this:
for file in "$@"; do
  ls -l "$file"
done

If you want to double-check that the name specified is not a directory, you could do this:
for file in "$@"; do
  if [ ! -d "$file" ]; then
    ls -l "$file"
  fi
done

A: the bash variable for all arguments passed to a script is "$*".  Try:
for file in $*; do
  if [ -f $file ] ; then
    ls -l $file
  fi
done

(not tested)


text:
Q: WCF RIA Services domain service over https client access policy problems We have a WCF RIA domain service with
[EnableClientAccess(RequiresSecureEndpoint = true)]

We have the website set to use http and https. We have a client access policy file in the root of the website like this:
<access-policy>
<cross-domain-access>
<policy>
  <allow-from http-request-headers="*">
    <domain uri="http://*"/>
    <domain uri="https://*"/>
  </allow-from>
  <grant-to>
    <resource include-subpaths="true" path="/"/>
  </grant-to>
</policy>
</cross-domain-access>
</access-policy>

When we access the Silverlight application over https everything is fine. When we access it over http we get the following error:

Invoke operation 'Working' failed. An error occurred while trying to make a request to URI 'https://localhost/ClientBin/SilverlightApplication3-Web-DomainService1.svc/binary/Working'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.

Which implies that our policy file is incorrect, but can't see what. Any ideas?

A: The reason that it wasn't working was that we were using a self-signed certificate, generated withe the machine name and then using localhost on the url. The url has to match to ensure that the ssl gets no certificate errors.
A good way to check this was to run the entire site over https and ensure that the browsers do not give a certificate error.


text:
Q: updated contact-form-7 and now other pages crashed I have an old site, and my contact-form-7 plugin was corrupted. I upgraded the contact form 7 plugin.
Now all a sudden 1 of my pages looks funny.
I traced it back to the includes/script.js file.
If I use this version:
http://merkaztorah.org/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=4.2.1
then I get this funny page :
http://merkaztorah.org/category/programs/
but if I take out the html and change the version back to the old one:
http://merkaztorah.org/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=3.5.1
the page works like here:
http://merkaztorah.org/what%20we%20offer%202nd-bu.php
What would be in the JS file that would cause my css to fail somewhere?
How should I get around the problem? Or should I just try to get contact-form-7 version 3.5.1 and put a clean version of that one?

A: It might be jQuery conflict. Open your website and right click on page and click on inspect element or use shortcut key CTRL+SHIFT+I and on the right top click on errors you will see some errors. If it says $ is not a function then change the $ sign with jQuery where function start. I was facing this type of error and when I change the $ sign with jQuery errors have gone and my script is working.


text:
Q: Does inheritance in generics work the same way as concrete and abstract classes, InvalidCaseException I have three classes: Post, Post<T> and WallPost.
Post is an abstract class representing a blog post with properties like name , text, user, etc.
The second abstract class is Post<T>, the generic version of post so I can implement a generic GetChildren(T Post) to get the children of a post and build a hierarchal list.
The third class is the concrete 'WallPost' which is a specific post for a user's profile.
public class WallPost : Post<WallPost>

And finally a Member class which contains a collection of WallPosts.

I wrote a control that takes a collection of posts and displays it in a tree. One of the proerties I have on that control is
public IList<Post<Post>> Posts
        {
            get; set;
        }

(I use generics because I need to get the children, GetChildren(T Post)). and I set the type parameter as Post so it will accept any class that inherits from post, wallpost, blogpost, etc
Now my problem is that I want to pass a user's collection of WallPosts of type IList<WallPost> to the function and I get this error:
     Unable to cast object of type 'NHibernate.Collection.Generic.
PersistentGenericBag`1[BO.WallPost]'
 to type 'System.Collections.Generic.IList`1[BO.Post`1[BO.Post]]'.

I'm guessing this is because although you can write something like Post p = new WallPost() you can't have List<Post> posts = new List<WallPost>()
Anyways I'm completely baffled and I hope I made myself clear.
Thank you in advance
E
P.S. I use NHibernate and there is no mention whatsoever of a bag.

A: You're trying to use generic covariance in a way that is not type-safe.
What would happen if you write
List<WallPost> wallList = new List<WallPost>();
List<Post> pList = wallList;
pList.Add(new OtherPost());        //Not a WallPost!

You can only do with with read-only interfaces (IEnumerable<Post>), or arrays.

A: You need to check your NHibernate mappings.  NHibernate is treating your collection as a bag instead of as a list.
From the NHibernate perspective, a list may not be the appropriate choice.  A list gives you index-based access to the members of your collection, but you must have a list index column in your table in order for NHibernate to map it as a list.
You should probably check out the NHibernate collection mapping options and choose the one that best matches your case (set, bag, list, etc.).

A: In order to work, you could use:
public IList<Post<WallPost>> Posts
{
    get; set;
}

and casting when assigning it:
bla.Posts = posts.Cast<Post<WallPost>>();


text:
Q: jQuery addOption and selectOptions I have to deal with some old Javascript code that is throwing an error at addOption and selectOptions

Error: Object has no method selectOptions

Can someone explain me why is it not working? I am using jQuery 1.3
$("some_id").addOption(nodeId, nodeName); // add to list
$("some_id").selectOptions(/^~~/i, true); // clear selection

I solved the addOption line by this
$("some_id")[0].options.add( new Option(nodeName,nodeId));

but I'm still stuck with selectOptions error.
UPDATE
just found out the application is also using Dojo. Could that be the problem? Are these methods Dojo specific?
Thanks!

A: use Jquery Append to add options like this
$("yourid/class here").append($("<option></option>").attr("value", youroption-value).text(youroption-text));

A: try this, you can write your own methods:
$.fn.addOption = function(optText, optValue){
    var option = new Option(optText, optValue);
    return this.append(option);
};

$.fn.selectOption = function(toSelect){
 var $option = this.find("option[value='"+toSelect+"']");
    if($option.length > 0){
        //if option with the value passed on found then select it
        $option.prop("selected","selected");
    }else{
        alert("option not found");
    }
};

var $select = $("#selectOption");
$select.addOption("Dummy1",2);
$select.addOption("Dummy2",3);

$select.selectOption(231);

working fiddle here: http://jsfiddle.net/maverickosama92/rGzPS/1/

A: Finally found whats wrong with it.
These methods come from a jquery plugin by TexoTela.
Why would someone do that just for select boxes?? Beats me

Thanks everybody for the responses. They taught me something indeed.


text:
Q: How do I fix inconsistent accessibility: property type FFT_Plotter is less accessible than How do I create a variable that has a global scope throughout a form? Here's what I have so far...
namespace FFT_Plotter
public partial class Form:form1
{
public void chart1_DragDrop(...)
 {
     FFT myFFT = new FFT();
     myFFT.SomeFunction();
  }
   ...
 public void radioButton1_CheckChanged(...)
 {
  foreach( Series s in chart1.Series)
     {
      myRadix.DoesSomething
      }
 }
 public class FormData
 {
    public FFT fft;
  }
 public class AllFormData
 {
    List<FormData> myList
 }
}

For clarification. I would like to be able to get myFFT in all of the form controls. The FFT class goes
  namespace FFT_Plotter
  {
    class FFT
    {
     public int pInt
     private int prInt
     }
    ...
  }

So far my research has shown that the FormData class should be set to public but I've done that and it's still giving me the same error.

inconsistent accessibility: property type FFT_Plotter is less accessible than...

A: You cannot have a public field of a type that is not also public.
The field;
public FFT fft;

is public, of type FFT;
class FFT
{
    ...
}

...which is not since it's missing the public keyword.
Make the class FFT public or lower the accessibility of the field, and your problem should be fixed.


text:
Q: How to structure the JS? Put the code in a unique file or require the necessary JS code in the file where its used? Do you know if is better to have a unique file with all JS or is better in each file require the specific JS that is necessary for that specific page?
The project sould stay better structured requiring the JS specific for each file.
But in terms of performance do you know if is basically the same or not?

A: For a small JS snippets is always better to implement it only on pages you need.
But, for big classes, framework or huge functions is better use single file with an CDN. That way is better performance and finaly better to maitenance and for developing is better to stay organized.
As second, in single file you can easily do minified version fully automated.

A: I prefer creating a unique JavaScript file and then linking it to the html file. It is the most efficient and organized way of structuring your code. But if the amount of code is very small and only required for that single page, inline JavaScript is preferred.
Performance: External JavaScript is always faster because the browser can cache an external file but Inline JavaScript will always be loaded afresh and hence is slower.


text:
Q: How can i filter salary in table columns in HTML table and show matched condition from checked checkbox filter? I have DataTable in HTML .
I have 3 checkboxes->Less Than 5000 , Less Than 4000,Less Than 3000
I want to get all the record/records according to checkbox checked
For Ex: if Less Than 5000 checkbox checked user should get only those rows in table having the record less than 5000.

$(document).ready( function () {
  var table = $('#example').DataTable();

 $('input:checkbox').on('change', function () {
   //build a regex filter string with an or(|) condition
   var positions = $('input:checkbox[name="pos"]:checked').map(function() {
     return '^' + this.value + '$';
   }).get().join('|');

   //filter in column 1, with an regex, no smart filtering, not case sensitive
   table.column(1).search(positions, true, false, false).draw(false);

   //build a filter string with an or(|) condition
   var offices = $('input:checkbox[name="ofc"]:checked').map(function() {
     return this.value;
   }).get().join('|');
   var s2 = offices.substring(1);
var office_int=parseInt(s2.replace(/,/g, ''));
   console.log(office_int);
   //now filter in column 2, with no regex, no smart filtering, not case sensitive
   table.column(5).search(office_int).draw(false);

 });

} );
body {
  font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
  margin: 0;
  padding: 0;
  color: #333;
  background-color: #fff;
}
<!DOCTYPE html>

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />

    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>

        <input type="checkbox" name="ofc" value="4999">Less Than 5000
        <input type="checkbox" name="ofc" value="3999">Less Than 4000
        <input type="checkbox" name="ofc" value="2999">Less Than 3000

            Name
            Position
            Office
            Age
            Start date
            Salary

            Name
            Position
            Office
            Age
            Start date
            Salary

            Tiger Nixon
            System Architect
            Edinburgh
            61
            2011/04/25
            4999

            Garrett Winters
            Director
            Edinburgh
            63
            2011/07/25
            3120

            Ashton Cox
            Integration Specialist
            San Francisco
            66
            2009/01/12
            2500

            Cedric Kelly
            Javascript Developer
            Edinburgh
            22
            2012/03/29
            2200

            Jenna Elliott
            Javascript Developer
            Edinburgh
            33
            2008/11/28
            1900

            Brielle Williamson
            Integration Specialist
            New York
            61
            2012/12/02
            4800

            Herrod Chandler
            Javascript Developer
            San Francisco
            59
            2012/08/06
            3675

            Rhona Davidson
            Integration Specialist
            Edinburgh
            55
            2010/10/14
            4422

            Colleen Hurst
            Javascript Developer
            San Francisco
            39
            2009/09/15
            3222

I tried by many ways but not succeded.
Does anyone has any solution ?


text:
Q: How would i get a point on a sphere? So im trying to get a point on a sphere via an angle.
double X = Math.Cos(pitch * (Math.PI / 180));
double Y = Math.Sin(pitch * (Math.PI / 180)) * Math.Sin(yaw * (Math.PI / 180));
double Z = Math.Sin(pitch * (Math.PI / 180)) * Math.Cos(yaw * (Math.PI / 180));

I've tried this, but the point it outputs seems to be clamped to the XZ axis, and increasing/decreasing the yaw doesn't do anything to the point it spits out.
I cant figure out whats wrong with this code? Could someone help me identify the problem?


text:
Q: Python Choice Not In List while True:

print "Please choose from one of the five following options:"

print " 1. 10^1\n 2. 10^2\n 3. 10^3\n 4. 10^4\n 5. 10^5\n"
    choice = raw_input()

    if choice == 1:
        print "1"
    elif choice == 2:
        print "2"
    elif choice == 3:
        print "3"
    elif choice == 4:
        print "4"
    elif choice == 5:
        print "5"

    while choice not in [1,2,3,4,5]:
        print "Not a valid choice!\n"
        break

What syntax should I be using? I keep getting not a valid choice. Its like Python is placing every choice even 1,2,3,4,5 in the list of points outside of that list.

A: You need to cast the raw_input to an int:
choice = int(raw_input())

the type of choice from raw_input will be a str which is why there are no matches, so you need to either change all your if to compare with the character or convert choice to an int
EDIT
In light of the comments, it would be better to change your comparison's to compare against the single character string, for one this is what you're intending anyway, and secondly it protects against invalid conversions for instance if you enter an input value that cannot be cast to an int then this will throw an exception so I'd modify your code to this:
choice = raw_input()

if choice == "1":
    print "1"
elif choice == "2":
    print "2"
elif choice == "3":
    print "3"
elif choice == "4":
    print "4"
elif choice == "5":
    print "5"

while choice not in ["1","2","3","4","5"]:
    print "Not a valid choice!\n"
    break

A: I would use a dict, check if the key/choice is in the dict, if it is print the choice and break else print the "Not a valid choice!\n" message:
# map choice to whatever you want to print

d = {"1": "1", "2": "2", "3": "3", "4": "4", "5": "5"}
while True:
    choice = raw_input("Please choose from one of the five following options:\n"
                       "1. 10^1\n 2. 10^2\n 3. 10^3\n 4. 10^4\n 5. 10^5\n")
    # if the key is in the dict, the choice is valid
    # so print the choice value and break.
    if choice in d:
        print(d[choice])
        break
    # if we get here choice was invalid
    print "Not a valid choice!\n"

There would be no point converting choice to an int, leave it as a string and do the lookup on the dict also using strings as keys. You can store whatever value you want for each choice as a value in the dict.

A: while True:

   print "Please choose from one of the five following options:"

   print " 1. 10^1\n 2. 10^2\n 3. 10^3\n 4. 10^4\n 5. 10^5\n"
choice = raw_input()

if choice == 1:
    print "1"
elif choice == 2:
    print "2"
elif choice == 3:
    print "3"
elif choice == 4:
    print "4"
elif choice == 5:
    print "5"

else:
    print "Not a valid choice!\n"

this should be the easiest fix


text:
Q: [PHP] Как убить полностью аутенфикацию через header? Привет народ! Кто знает как убить аутентификацию через header не выходя из браузера?
У меня есть стандартная аутентификация через
Header ("WWW-Authenticate: Basic realm=\"Hello, world!.\"");

и переменные
$_SERVER['PHP_AUTH_USER']
$_SERVER['PHP_AUTH_PW']

я пытаюсь их стереть спомощь unset();
Но после этого они всеравно появляются или я что то не так делаю?
Заранее спасибо.
A: Надо отправить статус 401

header('HTTP/1.0 401 Unauthorized');


text:
Q: How do I use Google doc picker with html service I am working on a Google apps script that uses html service. I want to provide the user with a file chooser so they can choose a file from their Google drive.
I have seen two different API's that seem to do this, Google Picker and Google DocsListDialog.
I am unable to get either to work. I have copied the example code exactly as is from both doc pages, but I can't get the picker to appear.
Google Picker I tried calling from javascript in my html page. I copied the Hello World example from the document page. Nothing appeared.
I then tried the DocsListDialog in the script itself (called by pressing a button in the html using google.script). Nothing appeared this time either - though the example code returns the the picker to the doGet function - which returns it as well. My doGet returns the html since I am using html service.
I just want anyway to integrate a simple doc picker into my app. Sample code that I can cut and paste and then modify would be really helpful since I can probably figure it out from there.
Thanks.

It may help to explain what I am trying to do since someone may have a different approach suggestion.
I am a teacher at a school and an amature programmer. We use google sites and google drive at our school. I want to create an app on an internal site page that teachers can use to copy and share a template file with a whole class automatically.
The only way I know how to do this is to create a google apps script that uses html service. I can then combine html and javascript to create an easy to use form to get the information from the teacher. I know how to have the script get the file, copy it, add viewer or editors, etc.
Right now that only way I know how to have the teacher identify their file is to enter the file id. Many of the teachers at my school are not overly profiicient with computers, and I would like to make this part simpler, since explaining how to identiy and copy the id from the web address is not so easy.
I saw a few references to the google doc picker and this seemed liked a nice way to do it if there was some way to make it work with what I need (or some other easy way to accomplish what I need).
Any helpful suggestions would be much appreciated.

A: You actually can get it to work in HTML Service. Here's how...
Create a new apps script project and make the following files in the project:
Code.gs file:
function doGet() {
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE)
.setTitle('Picker');
}

index.html file:
<script type="text/javascript">
// Use the Google Loader script to load the google.picker script.
google.setOnLoadCallback(createPicker);
google.load('picker', '1');
// picker info here
function createPicker() {
// Create default view to folders
var view = new google.picker.View(google.picker.ViewId.FOLDERS);
// Use DocsUploadView to upload documents to Google Drive.
var uploadView = new google.picker.DocsUploadView();
var picker = new google.picker.PickerBuilder().
addView(view).
addView(uploadView).
setAppId('YOUR APP ID').
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
// callback implementation.
function pickerCallback(data) {
    if (data.action == google.picker.Action.PICKED) {
        var fileId = data.docs[0].id;
        alert('The user selected: ' + fileId);
    }
}
</script>

*

*Save the project and publish it and run.

*Include apps script subroutines in the pickerCallback(data) function.
Adapted from: Google Apps Developer's Blog Post

A: DocsListDialog is clearly part of uiservices and not html service. Why do you expect it to work there?
Also filepicker uses a library that is not caja compliant. Read the docs about htmlservice and caja.
Edit: with the new aps script iframe mode you should be able to use the regular filepicker library.


text:
Q: Get taxonomy terms only of the WP_Query current posts I'm trying to find a way to not show all the terms of a taxonomy, but only the terms of the current displayed posts of the wp_query.
The code below displays all terms for 'brands' taxonomy and the query displays all products of the current category, i want to display only the terms that are set on the products that are displaying.
$marcas_terms = get_terms([
  'taxonomy' => 'brands'
]);

foreach ($brands_terms as $brand_term) {
  <input type="checkbox" id="<?php echo $brand_term->term_id; ?>" name="marca" value="<?php echo $brand_term->term_id; ?>">
  <label for="<?php echo $brand_term->term_id; ?>"><?php echo $brand_term->name; ?>
}

$args = array(
  'post_type' => 'product',
  'product_cat' => get_queried_object()
);

$query = new WP_Query( $args );
   if ( $query->have_posts() ) {
     while( $query->have_posts() ) : $query->the_post();

        get_template_part("templates/product-content-category");

     endwhile;
   } wp_reset_postdata();

A: You'd probably do something like this
$args = array(
  'post_type' => 'product',
  'product_cat' => get_queried_object()
);
$query = new WP_Query( $args );

$termsInPosts = array();
if ( $query->have_posts() ) {
    while( $query->have_posts() ) : $query->the_post();
        $postTerms = wp_get_post_terms(get_the_ID(), 'brands', array('fields' => 'term_id'));
        foreach ($postTerms as $postTerm)
            if (!in_array($postTerm->term_id, $termsInPosts))
                $termsInPosts[] = $postTerm->term_id;
    endwhile;
}

$marcas_terms = get_terms([
  'taxonomy' => 'brands',
  'include' => $termsInPosts
]);

foreach ($brands_terms as $brand_term) {
  <input type="checkbox" id="<?php echo $brand_term->term_id; ?>" name="marca" value="<?php echo $brand_term->term_id; ?>">
  <label for="<?php echo $brand_term->term_id; ?>"><?php echo $brand_term->name; ?>
}

if ( $query->have_posts() ) {
    while( $query->have_posts() ) : $query->the_post();
        get_template_part("templates/product-content-category");
    endwhile;
}

wp_reset_postdata();

What you're doing is just running through the loop before hand, getting the id's of terms within the posts, adding to an array, then when you call get_terms() you're using include to include only the terms you found.
I haven't tested this code, it's freehand, but it should work, or at least steer you in the right direction.
Hope that helps.

A: I think we can simplify it with the object_ids argument of get_terms(), with post IDs plucked from the given posts array.
Here's an untested skeleton, if I understand the problem correctly:
// Your post query
$query = new WP_Query( $args );

if( $query->have_posts() ) {

    // Get terms from the post IDs of the above post query
    $brand_terms = get_terms( [
        'taxonomy'   => 'brands',
        'object_ids' => wp_list_pluck( $query->posts, 'ID' ),
    ] );

    // Your terms loop
    foreach ( $brands_terms as $brand_term ) {
        // ...
    }

    // Your posts loop
    while( $query->have_posts() ) {
        $query->the_post();
        get_template_part( "templates/product-content-category" );
    }

    wp_reset_postdata();
}

Hope it helps.


text:
Q: How to switch content of a center panel in by check and uncheck checkbox I have buttons in west region and by clicking on buttons I am getting different charts in center region(using border layout). In last button click, I created a window with checkbox. When I check the box I want to destroy the the chart in center and create a new chart with controllpanel : true. If it is unchecked then it should be controllpanel:false.
My code for regions is
Ext.define('MyApp.view.main.Main', {
requires: ['Mgo.*', 'MyApp.view.main.MainModel', 'Ext.plugin.Viewport'],
extend: 'Ext.container.Container',
ui: 'navigation',
height: '100%',
width: '100%',
layout: 'border',
floating: true,
controller: 'MainController',
items: [{
    xtype: 'toolbar',
    height: 50,
    region: 'north',
    split: true, // enable resizing
    //margin: '0 5 5 5',
    items: [{
        xtype: 'image',
        width: 160,
        src: 'resources/images/newpowered.gif',
        style: "height: 30px;  left: auto; right: 1066px; top: 20px; margin: 0px;"
    }, '->', {
        xtype: 'image',
        height: 30,
        width: 30,
        tooltip: 'About',
        position: 'right',
        margin: '0 4 0 0',
        hidden: false,
        src: 'resources/images/a.png'
    }]

}, {
    title: 'Charts',
    region: 'west',
    xtype: 'panel',
    width: 230,
    split: true,
    items: [{
        xtype: 'button',
        height: 50,
        width: 220,
        text: 'Line Chart',
        name: 'linechart',
        icon: 'resources/images/line.png',
        iconAlign: 'left',
        textAlign: 'left',
        scale: 'large',
        margin: '5 0 0 5',
        handler: 'onLineChartClick'
    }, {
        xtype: 'button',
        height: 50,
        width: 220,
        text: 'Bar Chart',
        textAlign: 'left',
        name: 'barchart',
        icon: 'resources/images/bar.png',
        iconAlign: 'left',
        scale: 'large',
        margin: '5 0 0 5',
        handler: 'onBarChartClick'
    }, {
        xtype: 'button',
        height: 50,
        width: 220,
        text: 'Settings',
        textAlign: 'left',
        name: 'settings',
        icon: 'resources/images/settings.png',
        iconAlign: 'left',
        scale: 'large',
        margin: '5 0 0 5'
    }]
}, {
    xtype: 'panel',
    region: 'center',
    id: 'abc',
    layout: 'card',
    border: true,
    items: [{
        xtype: 'mgoPanel', // My own xtype
        itemId: 'igp1',
        showZoom: false,
        showLegends: true,
        showSlider: false,
        showDataGrid: true,
        chartType: 'groupedBoxPlot',
        controlPanel:false, // this should be true when checkbox is checked
        orientation: 'x'
    }, {
        xtype: 'mgoPanel',
        itemId: 'igp4',
        showZoom: false,
        showLegends: true,
        showSlider: false,
        showDataGrid: true,
        chartType: 'line',
        controlPanel:false, // this should be true when checkbox is checked
        orientation: 'x'
    }]
}]});

Handler for Checkbox is
Ext.define('MyApp.view.main.CheckBox', {
extend: 'Ext.form.Panel',
alias: 'widget.checkboxPanel',
height: 300,
width: 400,
layout: 'fit',
bodyPadding: 10,
items: [{
    xtype: 'fieldcontainer',
    fieldLabel: 'Select Panels',
    defaultType: 'checkboxfield',
    items: [{
        boxLabel: 'Control Panel',
        name: 'ctrlPanel',
        inputValue: '1',
        id: 'checkbox1',
        handler: function(field, value) {
            debugger;
            if (this.checked == true) {
                var xyz = Ext.getCmp('abc').items.items;
                for (i = 0; i <= xyz.length-1; i++) {
                    xyz[i].destroy(); // destroying center element. Need to true controllpanel
                }
            }
        }
    }]
}],
renderTo: Ext.getBody()});

Any help will apreciated.

A: To remove elements and replace with new ones:
        handler: function(field, checked) {
            var centerContainer = Ext.getCmp('abc');

            Ext.suspendLayouts();
            centerContainer.removeAll();
            centerContainer.add([{
                xtype: 'mgoPanel', // My own xtype
                itemId: 'igp1',
                showZoom: false,
                showLegends: true,
                showSlider: false,
                showDataGrid: true,
                chartType: 'groupedBoxPlot',
                controlPanel: checked,
                orientation: 'x'
            }, {
                xtype: 'mgoPanel',
                itemId: 'igp4',
                showZoom: false,
                showLegends: true,
                showSlider: false,
                showDataGrid: true,
                chartType: 'line',
                controlPanel: checked,
                orientation: 'x'
            }]);
            Ext.resumeLayouts(true);
        }


text:
Q: Related to proving Goldbach's Conjecture How significant would it be to prove that every even number larger than $49$ can be written as the sum of two integers co-prime to $2, 3, 5,$ and $7$?
I came across this result incidentally when working on Goldbach's Conjecture. I was trying to prove that every even number less than $P_n^2$ could be written as the sum of two numbers co-prime to the set of consecutive primes $P = \{2, 3, ..., P_{n-1}\}$, which would in fact prove a result slightly stronger than Goldbach's Strong Conjecture, namely that every even number can be written as the sum of two primes greater than or equal to $P_n$. But working on this also gets you the result that $E > P_n^2$ can be written as the sum of two numbers co-prime to the set $P$, which is how I got the result in the first line. I'm having trouble getting past $7$, but perhaps someone (or eventually I) could figure out how to do it. Extending my proof would result in proving Goldbach's Conjecture, but I do not know if this result is significant enough to try and publish. From what I've seen, there hasn't been major progress in Goldbach's Strong Conjecture. I think that following my method would be easier than starting from scratch.
EDIT: It is also a proof showing that every even number can be written as the sum of two primes or the difference of two numbers coprime to the set $P$


text:
Q: AMP: Custom font using font-face not working I am trying to use a custom font using font-face in my AMP pages, but the font is not rendered. The console says "Font download timed out for icons".

@font-face {
  font-family: 'icons';
  src: url('/fonts/icos2/icomoon.ttf?126oo9') format('truetype');
  font-weight: normal;
  font-style: normal;
}
[class^="icon-"], [class*=" icon-"] {
    font-family: 'icons';
    speak: none;
    font-style: normal;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
.icon-clock:before {
    content: "\e94e";
}

<amp-font layout="nodisplay"
  font-family="icons"
  timeout="2000"
  on-error-remove-class="icons-loading"
  on-error-add-class="icons-missing"
  on-load-remove-class="icons-loading"
  on-load-add-class="icons-loaded">
</amp-font>

Text

The font is being fetched via HTTPS.
Any help will be strongly appreciated.
Thanks!

A: Here is working Url
Js on Head

Css on Head

HTML
  Hello Font!

  Hello Font!

Text


text:
Q: How we can get under development dependency in maven I encounter an issue that, I have 3 projects porject_1,porject_2 and porject_3.
porject_1 contains one abstract class for example ClassDef.java, and porject_2 and porject_3 are implementing ClassDef.java in there code some where.
 If ClassDef.java has added some new API in  porject_1(under development means not released yet  ) which should be verified by porject_2 & porject_3.
But in maven  porject_2 & porject_3 need  porject_1 dependency to get new implementation and we can not add porject_1 development jar into class path of porject_2 & porject_3 project in maven hence I can't take latest change in both dependent project at same time. how could I resolve this issue?


text:
Q: recipes.map is not a function in reactjs I'm trying to output the elements in an array as components in reactjs but i'm getting an error 'recipes.map is not a function'
below is my code
    fetchRecipes() {
    var recipes = localStorage.getItem('recipes');

    return recipes.map((i) => {
        return <ListItem key={i.recipeName} edit={this.props.edit} delete={this.props.delete} name={i.recipeName}/>
      });
  }
  render() {
    return (
      <div>
        {this.fetchRecipes()}
      </div>
    );
  }

and this is recipes
 [{"recipeName":"Tomatoes","recipeIngredients":"somtheng, something"}, {"recipeName":"test","recipeIngredients":"somtheng, something"}]

A: localStorage stores strings so you need to convert the string to an array.
var recipes = JSON.parse(localStorage.getItem('recipes'));

and when you store it, I hope you are using stringify
localStorage.setItem('recipes', JSON.stringify(recipes));

A: And with ES2017 it's even easier with Object.values()
 var json =  [{"recipeName":"Tomatoes","recipeIngredients":"somtheng, something"}, {"recipeName":"test","recipeIngredients":"somtheng, something"}];
 var objects = Object.values(json);
 objects.map((value) => {
     console.log(value.recipeName);
  })

Logs:
Tomatoes
test

Same with ES2015
 Object.keys(json).map((i) => console.log((json[i].recipeName)));


text:
Q: Memory Management - When to release? I have been learning Objective C on my own for some time already and still don't quite get the hang of memory management. When should I release properties?
Example, I have a class that will handle 2 (register & updateParticulars) different URLRequest connections. updateParticularsConnection will be performed when registerConnection finishes.
@interface ConnectionViewController : UIViewController {

}
@property (nonatomic, retain) NSURLConnection *registerConnection;
@property (nonatomic, retain) NSURLConnection *updateParticularsConnection;
@property (nonatomic, retain) NSMutableData *responseData;
@property (nonatomic, retain) NSMutableURLRequest *requestURL;

@end

@implementation ConnectionViewController
@synthesize registerConnection, updateParticularsConnection, responseData, requestURL,

(void)performRegistration {
    // other here to prepare the data.
    requestURL = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myURL"]];
    registerConnection = [[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:YES];
}

(void)updateParticulars {
    // other here to prepare the data.
     [requestURL setURL:[NSURL URLWithString:@"http:myURL.com"]];
     updateParticularsConnection = [[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:YES];
}

Handling delegate callbacks
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [SVProgressHUD dismissWithError:@"Unable to connect"];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    if (responseData == nil) {
        responseData = [[NSMutableData alloc] init];
    }
    [responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (connection == registerConnection) {
        NSMutableString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"Register connection recieved data reads : %@", responseString);
        if ([responseString isEqualToString:@"-1"]) { // error. stop connection
            [self.requestURL release]; // remember to release requestURL since we would not be continuing on.
        }
        else if ([responseString isEqualToString:@""]) { // error. stop connection

            [self.requestURL release]; //remember to release requestURL since we would not be continuing on.
        }

        else {
            [self updateParticulars]; // perform next connection, updateParticulars

        }
        responseData = nil; // clear the current stored data in preparation for the next connection.
        [self.registerConnection release];
        [responseString release];
    } // end of definition for register connection

    else if (connection == updateParticularsConnection) {
            // do stuff with data received back here
        self.responseData = nil;
        [self.requestURL release];
        [self.updateParticularsConnection release];
    }
}

My question is should I be releasing my properties as soon as I can, which is what I think I am doing now? Or only during the dealloc method? Do advise if I am not doing it right.

A: you sort of need to take it on a case by case basis. the general answer is "as soon as you are done with it", unless it is a trivial allocation. for trivial allocations (e.g. NSString * firstName), you can just wait until dealloc or it is replaced (e.g. setFirstName:). this merely simplifies the implementation.
your example is slightly different.
// typically, you will set these to nil right when they
// have finished and you have grabbed what you need.
// that's pretty common for an async one shot request.
@property (nonatomic, retain) NSURLConnection *registerConnection;
@property (nonatomic, retain) NSURLConnection *updateParticularsConnection;
@property (nonatomic, retain) NSMutableURLRequest *requestURL;

and
// in the context of your program, this allocation could be large.
// in many cases, you'll simply convert it to the destination (if
// it's an image, just turn it into an image without holding onto
// the data representation), then dispose of it.
@property (nonatomic, retain) NSMutableData *responseData;

important: you are handling your instance's ivars directly in the OP - use the accessors, they will save you a ton of headaches. these are the changes you'd make to write your program using the accessors:
- (void)performRegistration {
    self.requestURL = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myURL"]] autorelease]; // use setter and autorelease
    self.registerConnection = [[[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:YES] autorelease]; // use setter and autorelease
}

- (void)updateParticulars {
    [self.requestURL setURL:[NSURL URLWithString:@"http:myURL.com"]]; // use getter
    self.updateParticularsConnection = [[[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:YES] autorelease]; // use setter and autorelease
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    if (self.responseData == nil) { // use getter
        self.responseData = [NSMutableData data]; // use setter and autorelease
    }
    [self.responseData appendData:data]; // use getter
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (connection == self.registerConnection) { // use getter
        NSMutableString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding]; // use getter
        NSLog(@"Register connection recieved data reads : %@", self.responseString); // use getter
        if ([responseString isEqualToString:@"-1"]) {
            self.requestURL = nil; // use setter
        }
        else if ([responseString isEqualToString:@""]) {
            self.requestURL = nil; // use setter
        }
        else {
            [self updateParticulars];
        }
        self.responseData = nil; // use setter
        self.registerConnection = nil; // use setter
        [responseString release];
    }
    else if (connection == self.updateParticularsConnection) { // use getter
        self.responseData = nil; // use setter
        self.requestURL = nil; // use setter
        self.updateParticularsConnection = nil; // use setter
    }
}

A: I use the @property only for public class variables which can be get/set from outside this class.
For private variables like the requestURL that you have, no need to create a retained property.
For every variable declared as retain in the definition, setting self.variable increases the retain count by one. This has to be kept in mind as most common leakage issue is setting a property to already retained value, like self.myString = [[NSString alloc] init]. Here, myString will have retain count of 2 even when you don't expect it.
So your question of when to release?
For @property: in the class's dealloc method and for private variables: whenever you are done using it.

A: You should generally attempt to keep the alloc/retain and release in the same scope.  If the value is a property, it's scope is global to the object instance, and it should be released in the dealloc method.  If the value is a local variable in a method (and isn't subsequently assigned to a variable of more global scope) then obviously you must release it in that method, and you should attempt to do the release within the same {} brackets as where you did the alloc/retain.
If you, eg, find that you no longer need a property after some point in your code you may nil it at that point, but it's still wise to leave the release in the dealloc method.
For objects with delegates, it occasionally works to do the release of the object in the delegate method, but you should always document this at the alloc location, and should be 100% sure that all "final" paths through the delegate do the release.
These aren't hard/fast rules, but they will keep you out of trouble.  It's appallingly easy, in the course of modifying a program, to change control flow or some such and cause a "cleverly placed" release to be missed.  By observing scope rules you rarely have such a problem.  (And document any exceptions to the scope rules.)

A: Your cheat sheet on release:

If the method you use to create an object contains the words new, copy or alloc then you won it and will have to release it once you do not need a reference any more.

A: You are right.
You can create them when (and if) you need them and release them as soon as you do not need them anymore, this way you will conserve memory.
allocating memory for all properties and iVars in init can slow the instantiation process.
Finding memory for an object is one of the slowest tasks in Cocoa, you have to try to get the perfect balance between CPU usage and Memory consumption–You won't need to worry about CPU usage at this level.
in Cocoa if you send messages to nil objects nothing happens, so if you are sure that you called release for every copy/alloc/retain, then you should set it to nil.
in iOS 5.0 you can use ARC which completely removes the need to do memory management for cocoa yourself, you will still need to do create/retain/release for corefoundation and other C based APIs though.


text: Q: Using both cookies and tokens different web api endpoints in the same app Is it possible to have both token based authentication and cookie based authentication for different web api end points in the same app? Can we use app.map to do such a thing?


text:
Q: HTML5 Regex Pattern for textbox validation: allow alphabet, spaces, and hyphens only I am creating a form in html and for my first and last name text inputs, I want to have a regex validation on them that only allows the user to input: letters of the alphabet, spaces, and hyphens.
I have tried this pattern but to no avail:
[A-Za-z -]

My HTML code:
<input type="text" id="first_name" name="first_name" maxlength="25" required="required" pattern="[A-Za-z -]"/>

I know how to get only alphabet characters, but allowing spaces and hyphens only is something I'm unable to manage.

A: Add anchors and a quantifier:
^[A-Za-z -]+$


text:
Q: Why do I get such code like this What does the "compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6" means?

A: It sounds like there was an error in creating the binaries for pip, hopefully it will be fixed soon (alternatively python 3.5 seems to work)
https://github.com/tensorflow/tensorflow/issues/14182

A: Looks like your machine is running Python 3.6, but the version of the software you are running was built with an earlier version of Python.


text:
Q: SQL Server 2008 One-Way Mirroring I'm new to DB admin but learning fast. We have a large SQL Server 2008 setup and I've just implemented a three-stage testing system - Alpha, Beta and Live servers. All three run the same version of SQL Server (though Alpha is x86 while the others are x64).
As Alpha is our it'll-probably-break test machine the data doesn't have to be up-to-date, but I'd like to set up Beta to be as close to Live as possible for obvious reasons, for example pulling new data from Live every hour or similar. I've investigated Replication and set up Transactional from Beta to Alpha (I will not touch Live until I know it works), but performing transactions (selects and inserts) on Beta didn't filter back to Alpha, so I'm not sure if I've set it up properly. It goes without saying that data should only be flowing one way, Live -> Beta (and ideally Beta -> Alpha, something like daily at midnight).
Can someone point me to a tutorial on setting up such a system, or help me set the system up?
Any help much appreciated!
Cheers,
Gargravarr

A: Here is the Microsoft up to date MSDN article on Log Shipping.
http://msdn.microsoft.com/en-us/library/ms187103.aspx
Read over the Secondary Server section of the article I think that will help point you in the right direction.
You have mentioned you don't want all of the data to be exact replicas? Because if that is not the case then I would recommend using Database Mirroring from within SQL rather then transactional replication.


text:
Q: Retrieving Django model value based on another model I was following a youtube's django database model queries but try doing it with different context to see if I understand the model concept and not just blindly following (and it turns out i do not understand it at all).
I was trying to retrieve the "views" values in the model based on the tag name.
I manage to pull the individual item but i do not know how to retrieve the view count based on the tag name.
The table look similar to this:

title
author
body
views
tags

title a
author a
blog post a
10
apple, orange, pear

title b
author a
blog post b
100
banana, orange

title c
author a
blog post c
50
banana, pear, apple, orange

title d
author a
blog post d
1
grape

the value i hope to retrieve is the sum of views that the tags are associated, like this
tags|count
--|--
apple|60
orange|160
banana|150
grape|1
pear|51
This is the current model
class Tag(models.Model):
    name = models.CharField(max_length=100, null=True)

    def __str__(self):
        return f'{self.name}'

class Blog(models.Model):
    title = models.CharField(max_length=255)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    views = models.IntegerField(default=0)
    tags = models.ManyToManyField(Tag)

    class Meta:
        verbose_name_plural = "Blogs"

    def __str__(self):
        return f'{self.title} | {self.author} | {self.date_created}'

By running a = Blog.objects.all() in the shell i can retrieve the views by indexing a (a[0].views), but that only return the views of the particular blog, how do I return the view counts based on tag associated with the blog?

A: You need to use the Sum function [Django docs] to sum the views of the related Blog instances. You can do this by passing the default related query name (<model_name_in_lowercase>) along with __ being used to traverse the relationship, i.e. blog__views to Sum:
from django.db.models import Sum

tags = Tag.objects.annotate(view_sum=Sum('blog__views'))

for tag in tags:
    print(tag.name, tag.view_sum)


text:
Q: update multiple form fields from inputs with a click of a button using java I want to update multiple form fields from multiple inputs with the click a button.  Here is the start of the code:
<form id="frmFive9">

                     IF CASH - CLICK SET TO CASH:

        <input type="button" onclick="UpdatePaymentType('Cash')" value="Set to Cash">

I would also like to update the Payment Amount, Base Amount and Upsell Amount from inputs.  Is this feasible to do this in javascript?

A: you should look into jQuery as this will be a good thing for you to learn and will simplify any manipulation you want.
a simple jQuery example would be something like
if($('#IdOfInputWithValueToMakeChoiceWith').val() === "SomthingToCompareTo")
{
    $('#IdOfAControlToChange').val('new value');
}

starting there you can based on what you are looking to do, google anything you are trying to manipulate and how you are trying to change it and should find what you are looking for.
want more help then we need more info.
Hope this helps


text:
Q: Adding attribute to an element Javascript I am JavaScript begginer and could use your help with the query below:
I had to find all li placed in nav tag in html. Now I have to check if li has data-direction attribute and if it doesn't - set this attribute to "top". I tried to do it using simple loop, but it doesn't seem to be working - I keep getting info from console that "direction is not defined" so it seems that it doesn't see "data-direction" as an attribute. Maybe I should indicate this attribute differently? Here is my code:
   var navLi = document.querySelectorAll("nav li");

   for (i = 0; i < navLi.length; i++) {
       if (navLi[i].data-direction === " ") {
       navLi[i].data-direction = "top";
      }
   }

Thanks in advance!

A: You're looking for hasAttribute()/setAttribute().
for (i = 0; i < navLi.length; i++) {
   if ( !navLi[i].hasAttribute('data-direction') ) {
     navLi[i].setAttribute('data-direction', 'top')
  }
}

A: getAttribute() will return null or an empty string so you need to use the hasAttribute() method to handle the null case.
for (var item of document.querySelectorAll("nav li")) {
  if (!item.hasAttribute("data-direction") || item.getAttribute("data-direction").trim() === "") {
    item.setAttribute("data-direction", "top");
  }
}


text:
Q: Connect Google Compute Engine to Cloud SQL I have an ubunut Compute Engine instance and a postgres Cloud SQL instance, both part of the same project and both in the same zone. I want to connect to the Cloud SQL from the Compute Engine but am having some trouble
My postgres has the default user setup and a new DB added. I have reserved a static IP for my Compute Engine and added this IP to authorised list in postgres. I've tried connecting (from the cloud shell) both with a python script using psycopg2 and directly from bash using psql. The error messages I get in both cases:
Connection timed out
Is the server running on host "xx.xxx.xxx.xx" and accepting
TCP/IP connections on port 5432?

Address omitted, but it is correct. The thing I can't be sure of is whether postgres is listening on the port as there is no (?) config option for this from the dashboard - though I would assume it to be running on 5432 (default)
Is there anything, either postgres or Google Cloud Infrastructure specific that I have missed?

A: The most resilient and portable way of connecting to a CloudSQL instance is through the CloudSQL Proxy.
There are several options for using the proxy, but in the docs there are specific instructions for using it from a GCE instance. I encourage you to check that option, as it will allow you to move your infrastructure anywhere without the need to change your code, you'll only need to configure the proxy properly wherever you're deploying your app.


text:
Q: Date-Time Formatting in XSLT 2.0 I have an XML which has a field with Date-Time stamp as below:
<?xml version='1.0' encoding='UTF-8'?

<root>
    <row>
        A1
        <ID>20202020</ID>
        <Date-Changed>April 01, 2021, 1:13 pm</Date-Changed>
    </row>
    <row>
        A1
        <ID>20202020</ID>
        <Date-Changed>April 01, 2021, 1:14 pm</Date-Changed>
    </row>
</root>

I need to convert this to a format which the XSLT understands so that I can filter only the rows which have the latest Date-time stamp. I have figured out a way to filter on the records with the latest Date-time stamp. However, the Date-time stamp format in the XML is throwing the logic off where I am filtering on the latest changed record.
What can I do so that my XSLT can understand the Date-time format in the above XML and output the below XML?
   <?xml version="1.0" encoding="UTF-8"?>
    <root xmlns:xs="http://www.w3.org/2001/XMLSchema">
       <row>
          A1
          <ID>1234ABCD</ID>
          <Date-Changed>2021-04-01T13:14:00</Date-Changed>
       </row>
    </root>

My XSLT looks like below:
<?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xsl:output method="xml" indent="yes" omit-xml-declaration="no"/>

        <xsl:template match="/">
            <root>
                <xsl:for-each select="root">
                    <xsl:for-each-group select="row" group-by="(concat(ID, Code))">
                        <xsl:variable name="Mod_Dt">
                            <xsl:value-of select="max(current-group()/Date-Changed/xs:dateTime(.))"/>
                        </xsl:variable>
                        <row>

                                <xsl:value-of select="(current-group()[Date-Changed=$Mod_Dt]/Code)"/>

                            <ID>
                                <xsl:value-of select="(current-group()[Date-Changed=$Mod_Dt]/ID)"/>
                            </ID>
                            <Date-Changed>
                                <xsl:value-of select="(current-group()[Date-Changed=$Mod_Dt]/Date-Changed)"/>
                            </Date-Changed>
                        </row>
                    </xsl:for-each-group>
                </xsl:for-each>
            </root>
        </xsl:template>
    </xsl:stylesheet>

Any help will be greatly appreciated!

A: You can define a function to convert the given string to a valid dateTime - for example:
<xsl:function name="my:string-to-dateTime">
    <xsl:param name="string"/>

    <xsl:variable name="parts" select="tokenize($string, ',\s|\s|:')"/>

    <xsl:variable name="m" select="index-of(('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), substring($parts[1], 1, 3))" />
    <xsl:variable name="H12" select="number($parts[4]) mod 12" />
    <xsl:variable name="H" select="if($parts[6]='pm') then $H12 + 12 else $H12" />

    <xsl:sequence select="xs:dateTime(concat($parts[3], format-number($m, '-00') , '-', $parts[2], format-number($H, 'T00'), format-number(number($parts[5]), ':00'), ':00'))" />
</xsl:function>

Demo: https://xsltfiddle.liberty-development.net/6qaHaQz/2

A: It looks as if it might be amenable to parsing using the parse-ietf-date() function in XSLT 3.0


text:
Q: Sistema de grid, calculos Antes de eu iniciar minha pergunta, quero deixar claro, já vi alguns tópicos relacionados.
Este é um deles, onde Guilherme Nascimento explica como funciona media queries, e a resposta que foi aceita na pergunta já explica como fazer o calculo, mas tem um porém...
Seguindo as dicas da resposta aceita, eu tentei mas não consegui, no Bootstrap tem a col-md-5, tentei chegar nesse resultado:
.col-md-5   { width: 41.66666667%; }

Mas não consegui, como foi feito o calculo da coluna de grid MD do Bootstrap?

A: O padrão do bootstrap é dividir o layout em 12 colunas de tamanhos iguais. Nesse caso, o 5 no nome da classe indica que o elemento deve ocupar 5 colunas, ou seja 5/12 que equivale a 41.66667%.


text:
Q: iTerm2 : Adapting zshrc prompt to get the same one than with .bashrc I switched from bash shell to zsh. After sourcing a main part of my old .bashrc to .zshrc, I am faced a problem concerning the rendering of prompt with zsh (which works with bash) :
function ps1 {
        # PROMPT SECTION
        BLUE='\[\033[0;34m\]'
        LIGHT_CYAN='\[\033[1;36m\]'
        DEFAULT='\[\033[0m\]'
        PURPLE='\[\033[0;35m\]'
        LIGHT_PURPLE='\[\033[1;35m\]'
        LIGHT_GREEN='\[\033[0;32m\]'
        PINK='\[\033\[0;31m\]'

        # \! - History number of last command
        # $? - Exit value of last command
        # \t - Exit time of last command
        # \w - Current directory (relative)

PS1="$PURPLE|$DEFAULT$LIGHT_GREEN\u@$DEFAULT$LIGHT_CYAN\h$DEFAULT$PURPLE|$DEFAULT\t$PURPLE|$DEFAULT$LIGHT_PURPLE\w$DEFAULT$PURPLE|$DEFAULT "
}

ps1

Here a screen capture of my old bash prompt :

Now, I would like to have the same prompt but with zsh using exe zsh :

How to get with zsh the same prompt than with the bash prompt ? Which modifications have I to do ?
UPDATE 1:
I tried the following PS1 for zsh but the rendering is not the expected one :
autoload -U colors && colors
PS1="$fg[purple]|{$fg[green]%u@$fg[cyan]%m$fg[purple]|$fg[purple]%*$fg[purple]|$fg[purple]%~$fg[purple]| "

here's the capture :

Any idea to the same ?

A: Here you go:
# %F/%f: start/end Foreground color
# %F{m}/%F{g}/%F{c}: short for %F{magenta}/%F{green}%F{cyan}
# %B/%b: start/end Bold/Bright (depending on your terminal)
# %n: user Name
# %m: Machine name
# %*: 24h time w/ seconds
# %~: pwd, abbreviated
local I='%F{m}|%f'
PS1="$I%B%F{g}%n@%F{c}%m%b$I%*$I%B%F{m}%~%b$I "

This recreates the exact same prompt.
Documentation can be found at http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html


text:
Q: From C to Assembly Suppose that we have the following piece of C code for an avr-8bit:
int v1=1;
int v2=2;
v2=v2+v1;

I expected the following disassemble
ldi r18, 1;
ldi r19, 2;
add r19, r18;

but after I ran:
avr-gcc -mmcu=atmega2560 Test.c -o Test.elf

and
avr-objdump -S Test.elf > Test.lss

I got the following disassemble
    ldi r24, 0x01   ; 1
    ldi r25, 0x00   ; 0
    std Y+2, r25    ; 0x02
    std Y+1, r24    ; 0x01
    ldi r24, 0x02   ; 2
    ldi r25, 0x00   ; 0
    std Y+4, r25    ; 0x04
    std Y+3, r24    ; 0x03
    ldd r18, Y+3    ; 0x03
    ldd r19, Y+4    ; 0x04
    ldd r24, Y+1    ; 0x01
    ldd r25, Y+2    ; 0x02
    add r24, r18
    adc r25, r19
    std Y+4, r25    ; 0x04
    std Y+3, r24    ; 0x03

is there anyone that can help me to understand the result of the disassembler?
Edit:
Using char the assembly become:
ldi r24, 0x01
std Y+1, r24
ldi r24, 0x02
std Y+2, r24
ldd r25, Y+2
ldd r24, Y+1
add r24, r25
std Y+2, r24

When is there std instruction?

A: As I found some example code I'll make my comment an answer - others have already explained the problem.
A lot of embedded code I work with defines extra types which are specific to their size, such as "uint8, uint16, uint32" for the unsigned ints, for example. That way you always know exactly which sort of variable you're dealing with. Especially in small embedded, signed, float, "int" of undefined size/signedness will all cost you CPU cycles at best and cause serious bugs at worst.
Here's our current #defines:
/*
 * Example - the basic data types from our embedded code
 */
typedef unsigned char       uint8;  /*  8 bits */
typedef unsigned short int  uint16; /* 16 bits */
typedef unsigned long int   uint32; /* 32 bits */

typedef char                int8;   /*  8 bits */
typedef short int           int16;  /* 16 bits */
typedef int                 int32;  /* 32 bits */

typedef volatile int8       vint8;  /*  8 bits */
typedef volatile int16      vint16; /* 16 bits */
typedef volatile int32      vint32; /* 32 bits */

typedef volatile uint8      vuint8;  /*  8 bits */
typedef volatile uint16     vuint16; /* 16 bits */
typedef volatile uint32     vuint32; /* 32 bits */

A: Short answer: your registers are 8-bit and your values are 16-bit. It's therefore handling them in two pieces.
Long answer:
    ldi r24, 0x01   ; 1
    ldi r25, 0x00   ; 0

Store the 16-bit value 1 in 8-bit registers r24,r25.
    std Y+2, r25    ; 0x02
    std Y+1, r24    ; 0x01

Store it at stack locations Y+1, Y+2.
    ldi r24, 0x02   ; 2
    ldi r25, 0x00   ; 0

Store the 16-bit value 2 in 8-bit registers r24,r25.
    std Y+4, r25    ; 0x04
    std Y+3, r24    ; 0x03

Store it at stack locations Y+3, Y+4.
    ldd r18, Y+3    ; 0x03
    ldd r19, Y+4    ; 0x04
    ldd r24, Y+1    ; 0x01
    ldd r25, Y+2    ; 0x02

Copy them back from the stack to (r18,r19) and (r24,r25)
    add r24, r18
    adc r25, r19

Add (r18,r19) to (r24,r25), including the carry on the second addition
    std Y+4, r25    ; 0x04
    std Y+3, r24    ; 0x03

Store it back on the stack.
To get your original assembly, try two things:

*

*use "char" variables

*use "-O2" compiler option

Edit: the reason the compiler stores variables to the stack rather than keeping them in registers is because they're stored with the default "auto" storage type. It may optimise them into registers but it doesn't have to, even if you declare them with "register" storage class.
While this isn't a strict requirement of the language it's normal compiler behaviour. If at some point you take the address of v1 then it must be assigned a storage location, and saved back there whenever the value of "v1" changes. So to save the bookkeeping of whether or not v1 should be stored in a register or on the stack, it keeps it on the stack and treats each line of code separately.

A: Your C code uses 16bit integer variables (int). The compiler can't read your mind, so it compiles exactly what is in the source file. So, if you want 8bit variables, you have to use respective type.
As a result you still will get storing the values in the memory (although more simple). I am not so good in C, but IMHO, there is some options to assign the variable to some register, if you want some variables to be in the registers instead of RAM. Something like:
register unsigned char VARNAME asm("r3");

Note that not all registers are available for such tricks.
So, the conclusion? Write your programs in assembly. They will always be smaller, faster and easy for reading/supporting.


text:
Q: gem install sinatra keeps fetching wrong version when i type "gem install sinatra" it keeps pulling 0.9.4 instead of the new 1.0
why does this happen?

A: gem update --system
gem install sinatra

A: Have you tried turning it off and on again?
gem uninstall sinatra
gem install sinatra

Or updating the specific gem?
gem update sinatra

Alternatively, you can try:
gem install --pre sinatra

But that gets you the 1.0.b version (beta version, I think), not the actual 1.0 release.


text:
Q: IIS looking for .cs file in compiled .net site I am building my first ASP.Net web application project in VS2010. The site has a master page which all the content pages use.
I have published it to a local Windows 2008 R2 server running IIS 7.5 - so other members of the team can have a look.
I published it using 'File System' to a directory on the server. If I look in the directory on the server, all I see are .aspx files and a few dlls - which is what I would expect.
If I go into IIS and try to browse the web application (or open a browser on my local box and go to http://myserver/Contacts - I get a Server Error - 'the file Contacts/MasterPage1.master.cs' does not exist.
I don't understand - why is IIS looking for a .cs file when, in a web application project - all the .cs files are compiled into a dll?

A: Check few things:

*

*Check if you are you referring to master page type using CodeFile="..." or CodeBehind="..." attributes. If you are using CodeFile change to CodeBehind, or even better right click on your project and click Convert to Web project

*Try adding namespace when referring to master page ( Inherits="Project.MasterPage" )


text:
Q: rails 3 tutorial : rspec + factory_girl_rails problem i've been following the Rails tutorial (http://railstutorial.org/chapters/beginning , Rails 3 version), and i've stopped at 11th chapter when using Factory Girl and Rspec, I have a test that isn't passing and I feel I'm doing something wrong but I don't see what.
First of all there is a git repository on Github with the code that doesn't pass that test.
http://github.com/Monomachus/ch3_static_pages
So I got users model
class User < ActiveRecord::Base
  attr_accessor :password
  attr_accessible :name, :email, :password, :password_confirmation

  has_many :microposts
  .
  .
  .

I got microposts model
class Micropost < ActiveRecord::Base
  attr_accessible :content

  belongs_to :user

  default_scope :order => 'microposts.created_at DESC'
end

Then I got Factory girl settings
Factory.define :user do |user|
  user.name                  "Michael Hartl"
  user.email                 "mhartl@example.com"
  user.password              "foobar"
  user.password_confirmation "foobar"
end

Factory.define :micropost do |micropost|
  micropost.content "Foo bar"
  micropost.association :user
end

And finally Rspec code
require 'spec_helper'

describe Micropost do
    .
    .
  describe "microposts associations" do

    before(:each) do
      @user = User.create(@attr)
      @mp1 = Factory(:micropost, :user => @user, :created_at => 1.day.ago)
      @mp2 = Factory(:micropost, :user => @user, :created_at => 1.hour.ago)
    end

    it "should have a microposts attribute" do
      @user.should respond_to(:microposts)
    end

    it "should be in the reverse order of appearing" do
      @user.microposts.should == [@mp2, @mp1]
    end
  end
end

And I got the error which definitely tells me that I do something wrong.
Failures:

  1) Micropost microposts associations should be in the reverse order of appearing
     Failure/Error: @user.microposts.should == [@mp2, @mp1]
     expected: [#<Micropost id: 2, content: "Foo bar", user_id: nil, created_at: "2010-12-24 12:47:02", update
d_at: "2010-12-24 13:47:02">, #<Micropost id: 1, content: "Foo bar", user_id: nil, created_at: "2010-12-23 13:
47:02", updated_at: "2010-12-24 13:47:02">],
          got: [] (using ==)
     Diff:
     @@ -1,3 +1,2 @@
     -[#<Micropost id: 2, content: "Foo bar", user_id: nil, created_at: "2010-12-24 12:47:02", updated_at: "20
10-12-24 13:47:02">,
     - #<Micropost id: 1, content: "Foo bar", user_id: nil, created_at: "2010-12-23 13:47:02", updated_at: "20
10-12-24 13:47:02">]
     +[]
     # ./spec/models/micropost_spec.rb:42:in `block (3 levels) in <top (required)>'

As you can see even the user_id property is not set correctly +
apparently @user.microposts doesn't have any elements.
Please help me with this issue thanks.

A: Well the answer was simple :)
I included microposts associations in the Micropost spec.
And clearly
describe "microposts associations" do

  before(:each) do
    @user = User.create(@attr)
    @mp1 = Factory(:micropost, :user => @user, :created_at => 1.day.ago)
    @mp2 = Factory(:micropost, :user => @user, :created_at => 1.hour.ago)
  end

  it "should have a microposts attribute" do
    @user.should respond_to(:microposts)
  end

  it "should be in the reverse order of appearing" do
    @user.microposts.should == [@mp2, @mp1]
  end
end

@attr did not contain the user properties but the micropost properties and of course @user = nil and then everything makes sense. So if you do have the same problem, include this code into User spec.
Now all my tests pass :)

A: By the time I had finished the pagination chapter, the tutorial was creating 100 sample users using Faker (listing 10.25 on page 390), and in RubyMine I was able to see my test was failing because the program was throwing an exception on duplicate user email address (which has a unique constraint).  The @attr on line 8 of user_spec.rb has :email => "user@example.com", however this throws an exception since it's a duplicate email (I guess because Faker has already created it).
For me the fix was to copy @attr from line 8 and paste it into the describe "micropost associations" block (user_spec.rb), and change the email address to :email => "user@example999.com".  I'm sure this is a total hack but I'm a n00b.
Update:
Another fix for me was to comment out the line @user = User.create(@attr), and simply create @mp1 and @mp2.

A: I was also getting test failure in this section, even though I already had "micropost associations" in user_spec.rb.  Turns out I needed to restart spork and autotest in order to get them to use the new "micropost" factory in factories.rb.


text:
Q: Make CruiseControl.NET projects show what changes were made since last run I have a chain of CruiseControl.NET targets like the ones below.  The first project pulls the changesets from a repository and runs fast unit tests on these changes.  If these unit tests succeed, the full product is built, and if that succeeds, a large test suite is run on the newly compiled product.
<project name="pullAndRunUnitTests">
    <triggers>
        <intervalTrigger seconds="300"/>
    </triggers>
    <sourcecontrol repo="$(Repo)" type="hg" revertModifications="true"/>
    <tasks>
        <nant>
            <targetList>
                <target>unitTests</target>
            </targetList>
        </nant>
    </tasks>
</project>
<project name="product">
    <triggers>
        <projectTrigger project="pullAndRunUnitTests"/>
    </triggers>
    <tasks>
        <nant>
            <targetList>
                <target>all</target>
            </targetList>
        </nant>
    </tasks>
</project>
<project name="regressionTests">
    <triggers>
        <projectTrigger project="product"/>
    </triggers>
    <tasks>
        <nant>
            <targetList>
                <target>regressiontests</target>
            </targetList>
        </nant>
    </tasks>
</project>

The problem with this setup is that only the unit tests will correctly identify who broke the the build;  if succeeding projects in the chain break, it can get hard to identify who/what actually made things break.
Is there a way to make CruiseControl.NET projects show what changes were made since the last time they were run, or alternatively, "inherit changes" from the projects that trigger them?

A: It is possible to let the depending CCNET project "inherit" the changes:

*

*Add a Modification Writer Task to project pullAndRunUnitTests

*Add a Modification Reader Task to project product
Do the same for product-regressionTests dependency:

*

*Modification Writer Task to project product

*Modification Reader Task to project regressionTests
Like this:
<project name="pullAndRunUnitTests">
    ...
    <tasks>
        <modificationWriter>
            <filename>changes-product.xml</filename>
            <path>..</path>
            <appendTimeStamp>True</appendTimeStamp>
        </modificationWriter>
        <nant>...</nant>
    </tasks>
</project>
<project name="product">
    ...
    <tasks>
        <modificationReader>
            <filename>changes-product.xml</filename>
            <path>..</path>
            <deleteAfterRead>True</deleteAfterRead>
        </modificationReader>
        <modificationWriter>
            <filename>changes-regressionTests.xml</filename>
            <path>..</path>
            <appendTimeStamp>True</appendTimeStamp>
        </modificationWriter>
        <nant>...</nant>
    </tasks>
</project>
<project name="regressionTests">
    ...
    <tasks>
        <modificationReader>
            <filename>changes-regressionTests.xml</filename>
            <path>..</path>
            <deleteAfterRead>True</deleteAfterRead>
        </modificationReader>
        <nant>...</nant>
    </tasks>
</project>


text:
Q: SQL + Return null record when no records meet the condition Below is the structure of my table. I want to retrieve records even if the condition do not match.
I have been using left join but the record is dropping since the condition do not match. Instead of dropping the record, I want to display a null value for tht column.
As far as checked, left outer join is the way to go. I am doing the same but still not getting the desired output.
table 1
Col1      Col2          Col3                  Col4
1           74          Desc 1          10/01/2015
2           85          Desc 2           09/01/2016
3           96          Desc 3           12/01/2015

table 2
Col4            Col5          Col6
AB               1            10/01/2015
CD               2            09/01/2016
EF               3            7/01/2015
GH               3            08/01/2015

Expected:
c1          dt                 exp
1            10/01/2015         AB
2            09/01/2016         CD
3            12/01/2015

Getting:
c1          dt                  exp
1            10/01/2015         AB
2            09/01/2016         CD

select tab1.col1 as c1, tab1.col4 as dt, tab2.col4 as exp
from tab1, tab 2
where tab1.col1 = tab2.col5
and tab1.col4 = tab2.col6(+)

Thanks,

A: Not sure about your goal. But here is my guess:
http://sqlfiddle.com/#!9/8422d/2
SELECT *
FROM t1
LEFT JOIN t2
ON t1.col1 = t2.col5
AND t1.col4 = t2.col6

A: What you want is called a left join, in your example you can get the expected result with;
select *
from tab1 left join tab2
        on tab1.id = tab2.tab1_id and ...etc