text:
Q: Pulling info from one class into another class I am very new to Java.  For a class assignment, I need to input a sales person's name and annual sales, then display their total wages based on their fixed annual salary of $50,000. It has to include 2 classes.
I have the salesperson class working properly. The Annualwages class runs, but shows "hello null" and "your total annual compensation is $50,000" (which is just the fixed annual salary without added sales).
I cannot figure out how to pull info from salesperson when running Annualwages.
package annualwages;

import java.util.Scanner;

/** @author Rachael  */
class salesperson { //begins salesperson class
    int annualSales;
    String name;

    public static void main(String[] args) {
        int annualSales;
        String name;
        // Create a Scanner object to read input.
        Scanner keyboard = new Scanner(System. in );

        //Get the user's name.
        System.out.print("What is your name? ");
        name = keyboard.nextLine();

        //Get the amount of annual Sales
        System.out.print("How much in sales did you make in the last year? ");
        annualSales = keyboard.nextInt();
    }

} //ends salesperson class

package annualwages;

/**
 *
 * @author Laptop
 */
public class Annualwages {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) { //begins the main method
        /**Declaration Statements */
        final double COMMISSION = 0.15;
        //Sets a fixed variable for commission earned

        final double SALARY = 50000;
        //Sets a fixed variable for Salary earned

        final double SALESTARGET = 120000;
        //Sets a fixed variable for the sales target

        double totalSales, totalWages, actualCommission, accelFactor = 1.25;
        /**
         * initializes annual Sales, total Sales, Total Wages,
         * actual commission and acceleration factor as a double.
         * Sets the acceleration factor to increase by 1.25. */

        salesperson sp = new salesperson();

        //Sales incentive begins at a minimum at $96,000 in sales.
        //if less than, then no commission is earned
        if (sp.annualSales <= 96000) {
            actualCommission = 0;
        }

        // Sales incentive with $96,000 or more earns 15% commission
        else if ((sp.annualSales > 96000) && (sp.annualSales < SALESTARGET)) {
            actualCommission = COMMISSION;
        }

        //Sales incentive increases if the sales person earns more than $120,000
        //in sales with the acceleration factor of 1.25
        else {
            actualCommission = COMMISSION * accelFactor;
        }

        //Calculates total sales by multiplying sales and commission
        totalSales = sp.annualSales * actualCommission;

        //Calculates total wages by adding salary to total sales
        totalWages = SALARY + totalSales;

        //Display the resulting information.
        System.out.println("Hello " + sp.name);
        System.out.println("Your total annual compensation is $" + totalWages);
    } // ends main method

} // ends annual wages class

A: In your salesperson class, I would move all the code in your main function to a constructor. Something like what I have done below. Doing this allows you to set non-static fields so you can set your name and annualSales correctly.
import java.util.Scanner;

public class salesperson {

    int annualSales;
    String name;

    public salesperson(){
        // Create a Scanner object to read input.
        Scanner keyboard = new Scanner(System.in);

        //Get the user's name.
        System.out.print("What is your name? ");
        name=keyboard.nextLine();

        //Get the amount of annual Sales
        System.out.print("How much in sales did you make in the last year? ");
        annualSales=keyboard.nextInt();
    }
}

Notice that I removed declaring name and annualSales from the method.
After this the rest of your code in your Annualwages class should work properly.

A: The two fields
 int annualSales;
 String name;

should be made "public static". Also you should not define them again in the main method.
Lastly it does not seem you are using an IDE. Download "Eclipse IDE" for writing code in Java. It will make your life much easier

A: You have to do like that:
 import java.util.Scanner;
 class salesperson {
 protected int annualSales;
 protected String name;

 public void saleInformation() {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("What is your name? ");
    name = keyboard.nextLine();
    System.out.print("How much in sales did you make in the last year? ");
    annualSales = keyboard.nextInt();
}
}

public class Annualwages extends salesperson {

public static void main(String[] args) {
    salesperson s = new salesperson();
    s.saleInformation();

    final double COMMISSION = 0.15;
    final double SALARY = 50000;
    final double SALESTARGET = 120000;
    double totalSales, totalWages, actualCommission, accelFactor = 1.25;
    if (s.annualSales <= 96000) {
        actualCommission = 0;
    } else if ((s.annualSales > 96000) && (s.annualSales < SALESTARGET)) {
        actualCommission = COMMISSION;
    } else {
        actualCommission = COMMISSION * accelFactor;
    }
    totalSales = s.annualSales * actualCommission;
    totalWages = SALARY + totalSales;
    System.out.println("Hello " + s.name);
    System.out.println("Your total annual compensation is $" + totalWages);
}
}


text:
Q: Query with multiple joins, group_concat and million rows executes slowly Query -
    SELECT s.id,
    GROUP_CONCAT(s.song_title SEPARATOR ', ') AS titles,
    GROUP_CONCAT(a.artist_name SEPARATOR ', ') AS artists,
    GROUP_CONCAT(al.album_title SEPARATOR ', ') AS albums,
    GROUP_CONCAT(s.release_date SEPARATOR ', ') AS release_dates,
    GROUP_CONCAT(sam.role SEPARATOR ', ') AS roles
    FROM songs s
    INNER JOIN song_artist_mappings sam ON sam.song_id = s.id
    INNER JOIN artists a ON sam.artist_id = a.id
    INNER JOIN album_track_mappings atm ON atm.song_id = s.id
    INNER JOIN albums al on al.id = atm.album_id
    GROUP BY s.id

Indexes available on -
    songs - id
    song_artist_mappings - song_id, artist_id
    album_track_mappings - song_id, album_id
    albums - id
    artists - id

The query returns ~2 million rows (which is the size of songs table) and takes many minutes to execute. Is there any way to optimize?
EDIT - A song (unique song id) can belong to multiple albums as well as artists. I have to display all of those as comma separated string. A small amount of data is corrupted where a song id in different rows has different title. Choosing any of those titles would be fine so I guess GROUP_CONCAT on song_title is not necessary. But then I will have to SELECT a non aggregate variable which is not listed in GROUP BY. Due to the corrupted data, I cannot group on song_title.
The query takes many minutes on InnoDB on 30GB RAM machine, even if I append LIMIT 5 to the query. No query is cached since query_cache_size is 0
EDIT 2 - The query runs much much faster when I get the same data via CakePHP associations. CakePHP splits the query into multiple queries and executes them sequentially.
EXPLAIN SELECT

A: No.  It needs to scan 2M rows, look up several million rows in the other tables, create a multi-million row tmp table, do the GROUP BY (possibly without a filesort) and finally shovel 2M resulting rows to the client.
Well, maybe...  Which Engine are you using?  If you are using InnoDB, what is the value of innodb_buffer_pool_size?  How much RAM do you have?  That setting should be about 70% of available RAM.  That won't help when running the query on a cold cache, since there will be a lot of I/O to do.  But if you run the query a second time, it might run 10 times as fast.
Please provide EXPLAIN SELECT ... so we can verify that the indexes are being used as expected.
Lower you expectations -- 2 million rows deserves to take some time.  What the heck are you going to do with that much output?  And do you need it more than once?
Addenda
A partial speedup is to have better indexes for the many:many tables (sam and atm).  In particular, a composite query would be faster.  more details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: angular databinding 2 numbers to equal another I have 2 divs that must always equal 100%. So they each start out 50%. The one on the left, can be changed from 1-99 (as an input), and the other must match that so they both always stay 100%.
for example: div A = 35%, div B must auto-change to 65%. I know how to two databind values, but not so that they each equal another value combined.

A: just keep subtracting div a from b
first div

{{A}}

second div

{{100-A}}


text:
Q: Can we run multiple splits parallel on a Single node machine? I am using hadoop on single node machine.When I run a large file with 1GB size and split size is 128MB.So, it runs the file in 8 splits but these splits runs sequentially means one split starts executing after completion of another split. Do we have to set any property value to run the splits parallelly on single node machine.

A: Hadoop provides a distributed processing framework (batch), i.e. MapReduce, which executes the tasks in parallel. But the level of parallelism depends on number of machines in your cluster. Parallelism can also be controlled with input split size but since you have a stand alone setup, the parallelism can not be achieved.


text:
Q: Segmentation fault when try to get the 'current_execute_data' on a PHP extension I'm trying to develop a php extension for print all functions call like a backtrace. But when I'm trying to get the current function a segmentation fault is throw. What is the problem with my code?
My php test code:

function a() {
    b();
}

function b() {
    c();
}

function c() {
    var_dump(hello_world());
}

a();

My extension code:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_hello_world.h"

PHP_FUNCTION(hello_world)
{
    zend_execute_data *ptr  = NULL;
    ptr = EG(current_execute_data); // <----- Segmentation fault (core dumped)
}

const zend_function_entry hello_world_functions[] = {
    PHP_FE(hello_world, NULL)
    PHP_FE_END
};

zend_module_entry hello_world_module_entry = {
    STANDARD_MODULE_HEADER,
    "hello_world",
    hello_world_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    PHP_hello_world_VERSION,
    STANDARD_MODULE_PROPERTIES
};

#ifdef COMPILE_DL_hello_world
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(hello_world)
#endif


text:
Q: Design will not shown in my system i have install expression-bland4 at that timen silverlight 4 was installed in my system. after that i am update Silverlight version 4 to 5. visual studio 2010 can create a project base on Silverlight5 but when i open that project in my expression bland it will loaded a project but not able to display xaml desin preview only text possion shown.
also when i create new project from expression bland will show only 3.0 and 4.0 version

Thanks in Advance

A: Expression Blend 4 does not support Silverlight 5 - you'll need to install Blend for Silverlight 5 from http://www.microsoft.com/en-us/download/details.aspx?id=9503


text:
Q: Google IoT Core - How to subscribe to a topic I have developed a device that is able to connect to Google IoT Core through the MQTT protocol, I can publish MQTT messages on telemetry topics (/devices/DEVICE_ID/events).
But I can't figure out how to subscribe my device to a generic topic and send messages from cloud to device via this topic.
Through the console I created the topic MyTestTopic and a subscription MyTestTopic-sub, I guess that somehow I have to subscribe my device to the subscription MyTestTopic-sub, but I don't know to which topic I have to subscribe my device.
I tried to subscribe my device to the following topics:

*

*projects/PROJECT_ID/topics/MyTestTopic

*projects/PROJECT_ID/topics/MyTestTopic-sub

*/devices/DEVICE_ID/events/MyTestTopic

*/devices/DEVICE_ID/events/MyTestTopic-sub
the subscription to these topics seems to be successful, but the device does not receive the messages I send from the console.
Any suggestions please?
I found this thread (Google Cloud IoT - Invalid MQTT publish topic) from 4 years ago, from which I understand that it is possible to subscribe only to some predefined topics, also from the various documents I have read I understand that Google IoT Core allows devices to subscribe to only two topics: /devices/{device-id}/config and /devices/{device-id}/commands/#
Has anything changed since then?

A: So to be clear, there are two different "topics" in play here. There's the MQTT topics that are described in the docs you found, config and commands. Those are subscribed to on the device using an MQTT client (e.g. Paho MQTT), and sent down to the device from somewhere else via the IoT Core Admin APIs. Then there's Pub/Sub topics. Out of the box, a device using IoT Core does not directly interact with Pub/Sub at all. They publish/receive via the MQTT topics only. So if you register a device with IoT Core, all messages come and go via the MQTT bridge (or HTTPS).
What Gambit support linked to in that github repo is a direct subscription to a Pub/Sub topic (not MQTT). If you look at the Python code, it's establishing proper Google Cloud Credentials via a json token (service account bearer token) that needs to be present on the device or a proxy device. Depending on the device you're using, that may not be possible of course (implementing GCP APIs on a microcontroller is difficult at best).
The easiest way I've seen this done is to implement a Cloud Function that subscribes to a Pub/Sub topic you want to use, and it implements the proper IoT Core Admin calls to push the Pub/Sub messages down to the device as needed. But of course, it all depends on what you're trying to do.


text:
Q: inline/embedded Image attachment is not visible in mail send by PHP Swift Mailer I'm sending an image with an attachment that has to shown as inline image.
I can't find out what's wrong with it. I don't remember this being an issue when I coded the mailer
This is the header of of the image inside the email
--_=_swift_1561449240_8047151997d755eb732462545a29a594_=_
Content-Type: image/png; name=logo.png
Content-Transfer-Encoding: base64
X-Attachment-Id: logo
Content-ID: <logo>
Content-Disposition: inline; filename=logo.png

This is the function that sends an email with attachments
public function send(MailInterface $mail, array $attachments = array())
    {
        /* @var SwiftMail $swiftMail */
        $swiftMail = new SwiftMail(
            $mail->getSubject(),
            $mail->getBody(),
            "text/html"
        );

        foreach ($attachments as $contentId => $contentPath) {
            if (null != $contentPath) {

                // prepare content to be send as an attachment
                $attachment = SwiftAttachment::fromPath($contentPath);
                $attachment->setDisposition("inline");
                $attachment->getHeaders()->addTextHeader("Content-ID", "<" . $contentId . ">");
                $attachment->getHeaders()->addTextHeader("X-Attachment-Id", $contentId);

                // add the attachment to the mail
                $swiftMail->embed($attachment);
            }
        }

    /* ... etc ... */

In the template I'm setting the source to the content ID like this:
<img src="cid:<logo>">

A: If you only want to show the image in the email as inline, use Swift_Image
$cid = $mail->embed(\Swift_Image::fromPath('/path/to/image'));
$emailView->assign('cid', $cid);

And at the Template:

But be careful:
It does not work with coincident $mail->attach(). I don´t know why yet.


text:
Q: Set value of input field based on selected option I´m creating a booking form for a group of hotels. Each hotel has a special offer page, which can be accessed by adding the parameter &ratePlanID=xxx to the request URL.
How can I add the ratePLanID dynamically when a user selects the hotel from a dropdown list?
I´ve tried to write a function that sets the value of an input field with the correct ratePlanID when a user selects the hotel, but I can´t get it to work.
This is what I came up with: http://jsbin.com/oduhet/3/edit#javascript,html,live
Any ideas what I did wrong here or another way to accomplish this?

A: $(document).ready(function() {
  $('#destination').change(function() {
    var hotel = $('#destination').val();
   $('[name=ratePlanID]').val(hotel);
  });
});

replace this in you javascript code
And for switch case
$(document).ready(function() {
  $('#destination').change(function() {
    var hotel = $('#destination').val();
   switch(hotel)
{
  case '15205':
    $('[name=ratePlanID]').val('1');
    break;
  case '15206':
    $('[name=ratePlanID]').val('2');
    break;
      case '15207':
    $('[name=ratePlanID]').val('3');
    break;
}

  });
});

A: I think the problem is in your case statement you should be looking for string values (vals are Strings not Ints).
Like:
switch(hotel)
    {
      case '15205':
        $('[name=ratePlanID]').val(1);
        break;
      case '15206':
        $('[name=ratePlanID]').val(2);
        break;
          case '15207':
        $('[name=ratePlanID]').val(3);
        break;
    }

A: Your "case" statement needs to look for "strings" not "ints". Put '' around each case.

A: A few things. I'm using a much newer version of JQuery since I'm not sure what v1.0 is missing.
I add a listener to the select list using jQuery AFTER the DOM Is ready to be manipulated. This is done by adding a listener to the 'document' waiting for the 'ready' event which, when fired, will execute the function passed to the listener. I've also given the input field the id ratePlanInput so that I can refer to it in the JavaScript.
<!DOCTYPE html><html><head>
<script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {    // add listener for document ready
    $('#destination').change(function() {     //add a listener for change
      var selectedValue = $(this).find(":selected").val();
      $('#ratePlanInput').val(selectedValue);
    });

  });

</script>

</head><body>

<form action="http://www.example.com" method="get">

  <select name="hotelID" id="destination">
    <option value="" class="first_option" selected="selected" disabled="disabled">Select a property:</option>
    <option value="15205">City Hotel</option>
    <option value="15206">Beach Hotel</option>
    <option value="15207">Business Hotel</option>
  </select>

  <input type="text" name="ratePlanID" value="" id="ratePlanInput" />

  <button type="submit">Check availability</button>

</form>

</body></html>


text:
Q: merging jquery mousenter / mouseleave animations I imagine this is pretty simple for someone in the know - but I can't figure it out.
How would i simplify these two mousenter / mouseleave animations into one piece of code?
$("#newsitem").mouseenter(function(){
$("#newsitem").stop().animate({ width: "300px", opacity: "1"     }, 300 );
});

$("#newsitem").mouseleave(function(){
$("#newsitem").stop().animate({  width: "204px", opacity: "0.5"   }, 300 );
});

Thanks!

A: $("#newsitem").bind('mouseenter mouseleave', function(e) {
    var dynamicWidth = e.type === 'mouseenter' ? 300 : 204;
    var dynamicOpacity = e.type === 'mouseenter' ? 1 : 0.5;
    $(this).stop().animate({ width: dynamicWidth, opacity: dynamicOpacity }, 300);
});

I wrote it like this simply to explicitly encompass your scenario here.  If you simply want to have a hover function, you can do that too.

A: It would be something like this:
$("#newsitem").hover(function(){
    //mousein events
},function(){
    //mouseout events
});

A: $("#newsitem").mouseenter(function(){ $(this).stop().animate({ width: "300px", opacity: "1" }, 300 ); }).mouseleave(function(){ $(this).stop().animate({  width: "204px", opacity: "0.5" }, 300 ); });

?


text:
Q: rotateY() vs matrix3d transitions in Edge I've come across a strange problem with the way Edge (and IE 11) handles my matrix3d transform. The page I'm working on has elements that already have an arbitrary transform applied to them (due to a plugin being used), however thanks to my manager I now need to apply a 180 degree rotation around the Y axis on top of this. Because of this, I could not simply use the rotateY() function as it replaced the old transform and moved the element, so I figured I'd need to use matrices. This works fine in Chrome and Firefox, but Edge doesn't seem to handle matrix3d in the same way.
Here's an example of using rotateY: http://codepen.io/anon/pen/wGqapy
(HTML)

            Test

(CSS)
.flip-container,
.front {
  width: 320px;
  height: 480px;
}

.front {
  transition: 0.6s;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  background-color: green;
}

.flip-container:hover .front
{
  transform: rotateY(180deg);
}

When you mouse over the element, it rotates around the Y axis in 3D space. And here's an example of using matrix3d, using the same matrix shown in the "computed CSS" tab in Edge: http://codepen.io/anon/pen/QNMbmV
(HTML)

            Test

(CSS)
.flip-container,
.front {
  width: 320px;
  height: 480px;
}

.front {
  transition: 0.6s;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  background-color: green;
}

.flip-container:hover .front
{
  transform: matrix3d(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1);
}

This, however, seems to spin around more than one axis. This does not occur in Firefox or Chrome. Am I supposed to use some magical vendor-specific CSS? I've been unsuccessful in searching SO or Google, so I hope someone has some insight!
Thanks in advance.

A: Matrices are very good for calculus, and for setting the transforms in an universal way. But aren't so good when you are transitioning from one state to the other.
a simple animation as
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}

is impossible to set with matrices
Also, take into account that even using matrices, you can chain them with others transforms.
All that said, let's see an example of your rotation working on a previously transformed element

.flip-container,

.front {
  width: 320px;
  height: 480px;
}

.front {
  transition: 0.6s;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  background-color: green;
  /* transform: rotate(10deg); is equivalent to matrix(0.984808, 0.173648, -0.173648, 0.984808, 0, 0) */
  transform: matrix(0.984808, 0.173648, -0.173648, 0.984808, 0, 0) rotateY(0deg);
}

.flip-container:hover .front {
  transform: matrix(0.984808, 0.173648, -0.173648, 0.984808, 0, 0) rotateY(180deg);
}

    Test


text:
Q: How to select all Dataframe columns with the same names? I am creating a dataframe based on a csv import:
ID, attachment, attachment, comment, comment
1, lol.jpg, lmfao.png, 'Luigi',
2, cat.docx, , 'It's me', 'Mario'

Basically the number of 'attachments' and 'comment' columns corresponds to the line that has the bigger number of said attachment and comment.
Since I am exporting the CSV from a third party software, I do not know in advance how many attachments and comment columns there will be.
Importing this CSV with pd.read_csv creates the following dataframe

ID
attachment
attachment.1
comment
comment.1

0
1
lol.jpg
lmfao.png
'Luigi'

1
2
cat.docx

'It's me'
'Mario'

Is there a simple way to select all attachment/comment columns?
Such as attachments_df = imported_df.attachment.all or comments_df = imported_df['comment].??
Thanks.

A: Use DataFrame.filter for columns starting by string by ^ and optionaly . with \d for comma with decimal for end of string is used $:
attachments_df = imported_df.filter(regex='^attachment\.*\d*$')
comments_df = imported_df.filter(regex='^comment\.*\d*$')

A: Another possible solution:
attachments_df = imported_df.loc[:,imported_df.columns.str.startswith('attachment')]
comments_df = imported_df.loc[:,imported_df.columns.str.startswith('comment')]

A: you also can use like atribute of filter function:
imported_df.filter(like='attach')
'''
  attachment attachment.1
0    lol.jpg    lmfao.png
1   cat.docx          NaN


text:
Q: Magento modify collection object element value I want to modify collection object element value without using $collection->getData() as getData() is returning an array. But I want an object to be returned.
$collection = Mage::getModel('test/test')
                ->getCollection();

$i = 0;
foreach ($collection as $key => $value) {
    //$collection[$i]['flat_last_order_amount'] = '39.99';
    //$collection[$i]['products_sku'] = '4361-4361';
    $i++;
}

I tried with commented code(with using getData()) but its not working. Any other way to do this please.

A: You need to use the magic getters / setters from Varien_Object.
You can do something like this:
foreach ($collection as $object) {
    $object->setFlatLastOrderAmount("39.99");
    $object->setProductsSku('4361-4361');
    $object->save();
}

Only call the save method if you need to save the changes in the database.
If you need to reuse that collection with updated values you can do the following after the loop:
$collection->clear();
$collection->load();


text:
Q: how to logout from both facebook and devise I have the following scenario:

*

*User logs in with Facebook connect (devise, omniauth)

*User starts browsing around the site

*User logs out from Facebook

*User can still browse around. <-- how can I prevent this from
happening?

Update:
I followed gist.github.com/848721 but still i cannot solve

A: You can redirect user to facebook logout page with access token.
redirect_to "https://www.facebook.com/logout.php?next=#{YOUR_REDIRECT_URL}&access_token=#{USER_ACCESS_TOKEN}"

You can integrate with devise like that:
controllers/application_controller.rb
def after_sign_out_path_for(resource_or_scope)
  "https://www.facebook.com/logout.php?next=#{YOUR_REDIRECT_URL}&access_token=#{USER_ACCESS_TOKEN}"
end


text:
Q: How to make a repeat move in javascript? I'm using JavaScript to make a progres bar when downloading files. I have done it to move from server to client as a picture, but I don't know how to make it to repeat so the progress will continue. I have used this script. What do I have to do?

<form>

Click the buttons below to handle animation

<input type="button" value="Shkarko" onclick="moveRight();" />
</form>

A: Use setInterval() instead of setTimeout():
function animate(){
    animateInterval = setInterval(moveRight,200);
}

When you are ready for it to stop animating, call clearInterval(animateInterval)
Make sure to rename your animate variable so that it does not conflict with the animate() function.  You'll also need to actually call animate() at some point to get it started.
Edit:  You need to crack open your JavaScript console and look at the error messages you get (hint: hit the f12 key).  You get an error on the second statement of moveRight() because left is not defined.
Also, animate() is never called, so any interval or timeout you set up would never be triggered.
There is a logic error in moveRight().  Even if left were defined, your else if statement would never be called.  If left is greater than 500, it is also greater than 10.  The first if will be called and the else if will thus be ignored.
Your HTML is invalid.  You have a close  tag with no matching open  tag. And you have an open  tag without a closing  tag.  If you did have those tags, you'd be in other trouble - the
 elements would be in the , and thus wouldn't even be rendered. The last
 element's closing tag would appear in the  even though the open tag is in the .


text:
Q: Affine connection on a Lie group - interaction with left-multiplication Let $X, Y$ be left invariant vector fields on a Lie group $G$, equipped with come arbitrary connection $\nabla$. Also, let $L_g : G \to G$ be left-multiplication by $g \in G$, so that for example $X \circ L_g (.) = X_{L_g(.)} : G \to TG$. I would assume that the following identity holds;
$$\nabla_{(X \circ L_g)} (Y\circ L_g) = \nabla_X Y \circ L_g\hspace{2mm}.$$
It seems really simple to prove, but I'm stuck. Could someone give a hint?
I know that the value of $\nabla_X Y |_p$ is determined by the value of $X$ only at p and on Y on a neighbourhood of p. However I can't figure out how to handle the "$\circ L_g$" in $\nabla_X Y \circ L_g$.
Edit: the vector fields X and Y are assumed to be left-invariant.

A: You are trying to prove the impossible.
Counterexample: let $G=\mathbb{R}$, with global coordinate $t$.  What you are asserting is that every connection has to be
$$
\nabla_{\frac{\mathrm{d}}{\mathrm{d}t}}\frac{\mathrm{d}}{\mathrm{d}t}=c\frac{\mathrm{d}}{\mathrm{d}t}
$$
where $c$ is constant.  But this is not true, e.g., $\nabla_{\mathrm{d}/\mathrm{d}t}\frac{\mathrm{d}}{\mathrm{d}t}=\sin(t)\frac{\mathrm{d}}{\mathrm{d}t}$ is a connection (and descends to a connection on $S^1$ if you want a compact example).


text:
Q: QtCreator error: QMYSQL driver not loaded When I try to access mysql I get the following error:
QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QODBC QODBC3

I have installed mysql in C:\Program Files (x86)\MySQL.
I googled this problem and i was given this link: http://www.qtcentre.org/threads/45295-using-mysql-plugin
however, I cant locate any of the files that inbush was talking about. I get lost starting here:

For ease of execution of commands in a terminal to a system variable
  Path: "C: \ Qt \ 2010.05 \ qt \ bin \; C: \ Qt \ 2010.05 \ mingw \ bin
  \". These directories are executable files qmake, mingw32make, g + +.
  REBOOT.
In the terminal, go to QTDIR / src / plugins / sqldrivers / mysql (cd
  C: \ Qt \ 2010.05 \ qt \ src \ plugins \ sqldrivers \ mysql)
Perform qmake-o Makefile "INCLUDEPATH + = C: / MySQL / include" "LIBS
  + = C: / MySQL / lib / opt / libmysql.lib" mysql.pro

Location of my Qt files etc:
Compiler:
http://puu.sh/3mdR0.png
Actual Qt:
http://puu.sh/3mdSA.png
Please help.

A: if @FrankOsterfeld is right, http://doc.qt.io/qt-4.8/sql-driver.html#supported-databases should help

A: I may be a few years too late, but this is how I got it working in windows.
Add the  following line in the .pro file.(Modify the path to fit your MySQL)
LIBS += -L"C:\\Program Files\\MySQL\\MySQL Server 5.6\\lib" -llibmysql


text:
Q: Create a password encrypted and store it in sqlite to use in authentication I have a WinForms application, with login form, and I want to store the username and password encrypted in a SQLite database. I saw that I can use salt and hash, but I don't know how to encrypt the password in the code, and compare it when we authenticate.
Any help please?

A: You will need to take the username and password (the password from a masked text box, preferably with a second box for confirmation) salt it, and create a hash from the password, and then insert the plaintext username and salted hash of the password in to the database. You can then verify the users password in future by comparing the database stored version with a salted (same salt!) hash of what the user enters.
Note that each user should have their own salt which you randomly generate for that user when they create their account. (This is more secure that a global salt value which a hacker could discover).
Take a look at this article. It pretty much covers all the bases, but don't use SHA-1 as recommended in the article. You want a slow hash function that is computationally expensive such as BCrypt, or PBKDF2 (which is included in .NET). See "What makes a good hash function for passwords". (Thanks @CodeInChaos for pointing this out).
You can use Rfc2898DeriveBytes in System.Security.Cryptography to create the salted hash of the password, PBKDF2 style.
byte[] salt = Guid.NewGuid().ToByteArray[];
Rfc2898DeriveBytes saltedHash = new Rfc2898DeriveBytes("P@$$w0rd", salt, 1000);

A good rule of thumb is that the number of iterations should cause the hashing operation to take about a second.

A: You need to storage the hashed password and the salt in the database. Use a random salt for each user (A GUID should be fine)
You can hash your passwords with something like that:
Remember to add the using System.Security.Cryptography; namespace.
    public static string ComputeHash(string passwordPlainText, string saltString)
    {
        // Convert plain text into a byte array.
        byte[] saltBytes = Encoding.UTF8.GetBytes(saltString);

        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        // Allocate array, which will hold plain text and salt.
        byte[] plainTextWithSaltBytes =
                new byte[plainTextBytes.Length + saltBytes.Length];

        // Copy plain text bytes into resulting array.
        for (int i = 0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];

        // Append salt bytes to the resulting array.
        for (int i = 0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

        // Because we support multiple hashing algorithms, we must define
        // hash object as a common (abstract) base class. We will specify the
        // actual hashing algorithm class later during object creation.
        HashAlgorithm hash;

        hash = new SHA256Managed();

        // Compute hash value of our plain text with appended salt.
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

        // Create array which will hold hash and original salt bytes.
        byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                            saltBytes.Length];

        // Copy hash bytes into resulting array.
        for (int i = 0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];

        // Append salt bytes to the result.
        for (int i = 0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(hashWithSaltBytes);

        // Return the result.
        return hashValue;
    }

You can change SHA256Managed for any other supported hash algorithm.
Update: I think you need to understand the concept first. I'll try to explain it:
Before login you need to have the users created in your database. To create them you need username and password.

*

*Generate a random SALT, Guid.NewGuid().ToString(); for example.

*Now you add this salt to your password and hash the result, the meaning of this is increase the security of your password against brute force attacks. (This step can be done with the function string ComputeHash(string passwordPlainText, string saltString) I posted before.

*Save username(provide by user), salt(guid) and password(result of computeHash) in the database.

*Login using the table with the user data!


text:
Q: 'String cannot have zero length' error when using EF Tracing Data Provider I am trying to incorporate 'EF Tracing Data Provider' into an existing MVC2 app using VS2010, .NET 4.0 in order to log all SQL commands. I have no interest at this time in the caching provider. I beleive I have followed all the steps listed in the blog posting. BLOG POST  My project does compile without error, however when I attempt to run the project I get the following error:
'String cannot have zero length.' The error points to Extended_JCIMS_MVC2_EF_Entities.cs     Line:  25
Line 25:         public ExtendedJCIMS_DevEntities(string connectionString)
Line 26:             :base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(

I am unable to determine what is causing this error. I assume the error is referring to the connection string from the Web.Config file. It does not like the 'connectionString' variable.  I'm obviously doing something worng. I would appreciate a push in the right direction.
The relevant bits are as follows:
Web.config
--------------------------------------------------------------------------

  <add name="JCIMS_DevEntities"
   connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=MyServer;Initial          Catalog=MyDatabase;User ID=MyUser;Password=myPassWord;MultipleActiveResultSets=True""
   providerName="System.Data.EntityClient"/>

<system.data>
 <DbProviderFactories>
  <add name="EF Tracing Data Provider" invariant="EFTracingProvider" description="Tracing Provider Wrapper"
     type="EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
   <add name="EF Generic Provider Wrapper" invariant="EFProviderWrapper" description="Generic Provider Wrapper"
     type="EFProviderWrapperToolkit.EFProviderWrapperFactory, EFProviderWrapperToolkit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
 </DbProviderFactories>
  </system.data>

Global.ascx
-----------------------------------------------------------------------

protected void Application_Start()
{
 AreaRegistration.RegisterAllAreas();
 RegisterRoutes(RouteTable.Routes);
 //EFTracingProviderConfiguration - LOG ALL Sql commands
 EFTracingProviderConfiguration.LogToFile = Server.MapPath("~/JCIMS_MVC2_EF_SQL_Logfie.txt");
}

Extended_JCIMS_MVC2_EF_Entities.cs
        --------------------------------------------------------------------------
namespace JCIMS_MVC2_EF.DomainModel
{
 /// <summary>
 /// Partial calss that Extends the EF Datacontext Class
 /// </summary>
 public partial class ExtendedJCIMS_DevEntities : JCIMS_DevEntities
 {
  private TextWriter logOutput;

  public ExtendedJCIMS_DevEntities()
   : this("name=JCIMS_DevEntities")
  {
  }

  public ExtendedJCIMS_DevEntities(string connectionString)
   : base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(
     connectionString,
     "EFTracingProvider"
   ))
  {
  }

  //... and more
}
}

  SearchRepository.cs
 ------------------------------------------------------------------
public class SQLSearchRepository : ISearchRepository
{
 //Database connection
   private ExtendedJCIMS_DevEntities db = new ExtendedJCIMS_DevEntities(); // tracing version

 public IEnumerable<SearchResults> ListAll(string strSearch, string chkSearch)
   {
  return (from s in db.Schools....
  // and more...
   }

Appreciate any assistance anyone can give me...

A: Have you debugged and confirmed that the connectionString passed into the ExtendedJCIMS_DevEntities method is not null or empty?  That's what the error seems to indicate.


text:
Q: Power and Ground planes The Henry Ott way or split ground planes Seeing a lot of mixed infomation around involving ground planes on multilayer boards. For a mixed signal mulitlayer PCB which is the preferred method? I know every board is different and it depends what your board is doing but I see alot of people with isolated ground planes yet Henry Otts advice is to do the exact opposite and partition the board in segments. Any advice or comments on this would be great!

A: It really depends on your design. Henry Ott says it will simplify your design in general.
Off the top of my head there are a few reasons you don't want split planes:
1) It turns your board into a dipole antenna
2) Crossing a split plane with a trace is bad because it increases inductance and complicates the paths for return currents.

There are reasons for splitting planes, in some cases it can reduce common mode noise or noise on the analog side of the ground plane. If your isolating your analog section completely (which I would not recommend, but is sometimes necessary) then you will need split planes.

A: I'm preparing some blog pages/content about this topic. But I'll summarize here.
If no charge moves between the analog and the digital sections, then you can pick either options.
Given mixed-signal systems tend to NEED to move digital data and control signals back and forth between the Analog and the Digital sections, there are several approaches;
1) use fiber optics to move data; I saw this used on an IR camera head inside a gymbol (track incoming missiles) with noise floor achieved of 17 nanoVolts/rtHz. There were no beathotes in the images.
2) adjust system timing
3) minimize the digital-interface charge injection; I once used +I and -I and Iref/2 (to set threshold) between FractionalN Synthesizer core-algorithm and the PLL charge pump; reference spur was shockingly low at -105dBc. The key is the balanced +I and -I, where lotta charge was moved but nearly nulled.
4) study the system ringing; understand why your silicon parts have ringing and study how to manage that ringing.
Just some thoughts.


text:
Q: How to add date at name of file txt I am using curl to get an information of eurobasket2017 this works correct but I launch this curl everyday with a cron.
curl -o dailyGameCode http://live.fibaeurope.com/www/KeyFacts.ashx?acc=0&lng=en&full=1

How can I pass the following format to a name of the file ?
date +%d-%m-%y

Regards !

A: You can do shell substitution to get the date and then append it to the file name.
Example
$ today=$(date +%d-%m-%y)
$ curl -o "dailyGameCode-$today" http://live.fibaeurope.com/www/KeyFacts.ashx?acc=0&lng=en&full=1
$ ls
dailyGameCode-01-09-17


text:
Q: How to post a binary image from desktop app to ashx handler and receive it? I am developing a WinForms application and  want to send a binary image data to web application. How does it work?
I coded this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

request.AllowWriteStreamBuffering = true;
request.KeepAlive = true;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;

var fc = GetFileContent(varsayilanResimGuid);
byte[] postBytes = fc.Dosya;
request.ContentLength = postBytes.LongLength;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string content = new StreamReader(response.GetResponseStream()).ReadToEnd();

and how to receive this binary image content by me in .ashx ?

A: I question and I answer.
how to receive a binary image:
Stream gelenResim = context.Request.InputStream;

if (gelenResim.Length == 0)
{
    e.Resim = "/Content/EmlakDetayImaj/Noimages.jpg";
}

string guidim = Guid.NewGuid().ToString().Substring(0, 4);
var KaydetResimDosya = "/Content/EmlakDetayImaj/" + guidim + ".jpg";

using (FileStream fileStream = System.IO.File.Create(context.Server.MapPath("~/Content/EmlakDetayImaj/" + guidim + ".jpg"), (int)gelenResim.Length))
{
    byte[] bytesInStream = new byte[gelenResim.Length];
    gelenResim.Read(bytesInStream, 0, (int)bytesInStream.Length);
    fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}


text:
Q: Loader like this with jQuery Please, can you checkout http://svpply.com , move the pointer on a image and click + when it appears. If you're careful you can see a very nice loader when you've clicked +, and after some moments appear a v.
How can I implement something like that? In that process there's not "white view" between the three step (+, loading, v). Ideas?
Actually I've this code:
$(".add_button").live("click", function() {
    var element = $(this),
        data = "id=" + this.id;

    element.css("background-image", "url(/media/images/loader.gif)")

    $.ajax({
        type: "POST",
        url: "/product/add/",
        data: data,
        success: function(result) {
            element.css("background-image", "")
            element.removeClass("add_button").addClass("del_button");
        }
    });

    return false;
});

But between the three steps I see an ugly "white image". Why?
UPDATE
Now I've:
$(".add_button").live("click", function() {
    var element = $(this),
        data = "id=" + this.id;

    element.removeClass("add_button").addClass("spinner");

    $.ajax({
        type: "POST",
        url: "/product/add/",
        data: data,
        success: function(result) {
            element.removeClass("spinner").addClass("del_button");
        }
    });

    return false;
});

But still the same problem. Unfortunately I cannot find the interested source in the svpply source code.
UPDATE

A: Oh yessss, this is a good question :)
So basically it has to do with AJAX and the different kind of settings!  You need to use ajax:beforeSend and ajax:success (or ajax:complete if you're doing more loading after success).  Which means you can do something like (assuming your button is wrapped in a form)
$(".add_button").parent("form").bind("ajax:beforeSend",function(e,data,status,xhr) {
        $("#someDiv").append("");
        // and any other things you want to do like removing the button or disabling it
});

That function will execute BEFORE the client (your computer) sends the request to the server.  You can also add a lot of stuff in there and modify the option to request you are actually sending to the server!
Then you can have
$(".add_button").parent("form").bind("ajax:success",function(data,textStatus,jqXHR) {
        $("#loading").remove();
        // and any other things like adding your del button
});

Which is called after the server sends back the object to the client for you to play with, in which case you can remove your #loading img and do other cool things!
I really suggest you reading on the link and completely understand how AJAX works, and how the client interacts with the server.  Once you understand that, you can do a lot of cool things like this!  Good luck.
EDIT
You can check out a working example of this (which doesn't use a loading gif but instead disables input) at this prototype I'm building.  Click on the animating circle and try to submit a comment.  You'll notice that after you hit enter, the comment input box is disabled until the comment is rendered back on your screen!
In your case, your code would look like
$.ajax({
    type: "POST",
    url: "/product/add/",
    data: data,
    beforeSend: function(msg) {
        // do the stuff you want to do
    },
    success: function(result) {
        element.removeClass("spinner").addClass("del_button");
    }
});


text:
Q: How to make one game object to be in front of another in unity I heard that game objects are drawn in the same order they appear in the Hierarchy. But in my case it doesn't work.
For example I wanted the wolf is placed in front of the rabbit, but it doesn't work.
Is there some way to make it with sorting objects according in hierarchy or I can make it only with layers?

A: The hierarchy sorting you speak of only works in the canvas - so for example with RectTransforms and Images. However I guess you want to use Sprites. SpriteRenderer component has a Order in layer property. Plus Sprites are more lightweight than Images with Transparency. Or you could just move Transforms closer and further away from the camera (even if your game is 2D/ using an orthogonal camera). If everything fails you could change the RenderQueue of the Materials.


text:
Q: Merging Start and durations with timeslots I have a data file containing several TV broadcasts with their start and duration time in minutes, and I have to merge it with another file containing some 2 hours timeslot.
Here's a sample of what it looks like:
File1:

*

*date      |start   |duration

*19/05/2014|15:25:00|55

*19/05/2014|16:20:00|30

*19/05/2014|16:50:00|25

*19/05/2014|17:15:00|55

*19/05/2014|18:10:00|30

File2:

*

*timeslot     |timeslot_info

*05:00 - 07:00|info_to_merge

*07:00 - 09:00|info_to_merge

*09:00 - 11:00|info_to_merge

*11:00 - 13:00|info_to_merge

*13:00 - 15:00|info_to_merge

*15:00 - 17:00|info_to_merge

*17:00 - 19:00|info_to_merge

*19:00 - 21:00|info_to_merge

*21:00 - 23:00|info_to_merge

*23:00 - 25:00|info_to_merge

*25:00 - 27:00|info_to_merge

*27:00 - 29:00|info_to_merge

Now what I have to do is, for each occurrence of file 1, find the timeslot of the file 2 corresponding following those rules:
- The timeslot in which the occurrence is "the most included" into has to be selected
- If the occurrence covers more than one timeslot entirely, the last entirely covered timeslot should be selected
I've tried a lot of heavy codes, but I couldn't find how to deduce the correct timeslot..
I figured a logic where I'm browsing each occurrence of the first file and try to assign it a timeslot key for further matching but no more:
private string GetTimeSlot(string line)
{
    string result = "";

    string[] tab = line.Split('\t');
    string start = tab[LogsStartTimeColumnIndex];
    string[] starttab = start.Split(':');

    TimeSpan StartTime = new TimeSpan(Int32.Parse(starttab[0]), Int32.Parse(starttab[1]), Int32.Parse(starttab[2]));
    TimeSpan Duration = new TimeSpan(0, Int32.Parse(tab[LogsDurationColumnIndex], 0), 0);
    TimeSpan EndTime = StartTime + Duration;

    //don't know how to do it from here..

    return result;
}

A: The way I would approach this is to separate the parsing of the input data files, from the logic that finds the required Timeslot.
In terms of the logic to find the correct Timeslot, you could use the following as a start. It implements the logic you have detailed above ie "The timeslot in which the occurrence is "the most included" into has to be selected - If the occurrence covers more than one timeslot entirely, the last entirely covered timeslot should be selected":
UPDATED - to support the 'night' timeslots I have introduced a TimeInHours class to represent what the Timespan was previously doing
public class TimeslotsFinder
{
    private readonly IEnumerable<Timeslot> _allTimeslots;

    public TimeslotsFinder(IEnumerable<Timeslot> allTimeslots)
    {
        _allTimeslots = allTimeslots;
    }

    public Timeslot FindTimeslot(Broadcast broadcast)
    {
        var found = _allTimeslots
            .Select(t => new { Timeslot = t, DurationInTimeslot = DurationInTimeslot(broadcast, t) })
            .Where(x => x.DurationInTimeslot > TimeInHours.Zero)
            .OrderByDescending(x => x.DurationInTimeslot.Value)
            .ThenByDescending(x => x.Timeslot.Start.Value)
            .FirstOrDefault();

        return found == null ? null : found.Timeslot;
    }

    private static TimeInHours DurationInTimeslot(Broadcast broadcast, Timeslot timeslot)
    {
        if (!(InTimeslot(broadcast, timeslot) || CoversEntireTimeslot(broadcast, timeslot))) return TimeInHours.Zero;

        var endToUse = broadcast.EndTime >= timeslot.End
                        ? timeslot.End
                        : broadcast.EndTime;

        var startToUse = broadcast.StartTime <= timeslot.Start
                        ? timeslot.Start
                        : broadcast.StartTime;

        return endToUse.Subtract(startToUse);
    }

    private static bool InTimeslot(Broadcast broadcast, Timeslot timeslot)
    {
        var startsInTimeslot = timeslot.Start <= broadcast.StartTime && broadcast.StartTime < timeslot.End;
        var endsInTimeslot = timeslot.End < broadcast.EndTime && broadcast.EndTime <= timeslot.End;

        return startsInTimeslot || endsInTimeslot;
    }

    private static bool CoversEntireTimeslot(Broadcast broadcast, Timeslot timeslot)
    {
        return broadcast.StartTime <= timeslot.Start && broadcast.EndTime >= timeslot.End;
    }
}

The logic above obviously uses these classes:
These have also been updated to use the TimeInHours class
public class Broadcast
{
    public DateTime StartDateTime { get; set; }
    public TimeSpan Duration { get; set; }

    public TimeInHours StartTime
    {
        get
        {
            return TimeInHours.FromTimeSpan(StartDateTime.TimeOfDay);
        }
    }

    public TimeInHours EndTime
    {
        get
        {
            return TimeInHours.FromTimeSpan(StartDateTime.Add(Duration).TimeOfDay);
        }
    }
}

public class Timeslot
{
    public TimeInHours Start { get; set; }
    public TimeInHours End { get; set; }

    public TimeInHours Duration
    {
        get
        {
            return End.Subtract(Start);
        }
    }
}

public class TimeInHours
{
    public TimeInHours(int value)
    {
        Value = value;
    }

    public int Value { get; private set; }

    public TimeInHours Subtract(TimeInHours x)
    {
        return new TimeInHours(Value - x.Value);
    }

    public static TimeInHours FromTimeSpan(TimeSpan ts)
    {
        return new TimeInHours(ts.Hours);
    }

    public static TimeInHours Zero
    {
        get
        {
            return new TimeInHours(0);
        }
    }

    public static bool operator < (TimeInHours t1, TimeInHours t2)
    {
        return t1.Value < t2.Value;
    }

    public static bool operator >(TimeInHours t1, TimeInHours t2)
    {
        return t1.Value > t2.Value;
    }

    public static bool operator <=(TimeInHours t1, TimeInHours t2)
    {
        return t1.Value <= t2.Value;
    }

    public static bool operator >=(TimeInHours t1, TimeInHours t2)
    {
        return t1.Value >= t2.Value;
    }
}

You can test this logic with something like this:
Also updated to use the TimeInHours class
        var timeslots = new List<Timeslot>
        {
            new Timeslot{Start = new TimeInHours(5), End = new TimeInHours(7)},
            new Timeslot{Start = new TimeInHours(7), End = new TimeInHours(9)},
            new Timeslot{Start = new TimeInHours(9), End = new TimeInHours(11)},
            new Timeslot{Start = new TimeInHours(11), End = new TimeInHours(13)},
            new Timeslot{Start = new TimeInHours(13), End = new TimeInHours(15)},
            new Timeslot{Start = new TimeInHours(15), End = new TimeInHours(17)},
            new Timeslot{Start = new TimeInHours(17), End = new TimeInHours(19)},
            new Timeslot{Start = new TimeInHours(19), End = new TimeInHours(21)},
            new Timeslot{Start = new TimeInHours(21), End = new TimeInHours(23)},
            new Timeslot{Start = new TimeInHours(23), End = new TimeInHours(25)},
        };

        var finder = new TimeslotsFinder(timeslots);

        var broadcast = new Broadcast { StartDateTime = DateTime.Parse("19/05/2014 09:00"), Duration = TimeSpan.FromMinutes(250) };
        var timeslot = finder.FindTimeslot(broadcast);

With this logic in place, it should then just be matter of parsing the data files to create the required Broadcast and Timeslot instances. I will leave this part to you as I believe it will beneficial for you to create the parsing code yourself.


text:
Q: Using a file with specific IDs to extract data from another file into separate files and then using them to get values I have a file with some IDs listed like this:
id1
id2
id3
etc

I want to use those IDs to extract data from files (IDs are occurring in every file) and save output for each of these IDs to a separate file (IDs are protein family names and I want to get each protein from a specific family). And, when I have the name for each of the protein I want to use this name to get those proteins (in .fasta format), so that they would be grouped by their family (they'll be staying in the same group)
So I've tried to do it like this (I knew that it would dump all the IDs into one file):
#! /bin/bash

for file in *out
do grep -n -E 'id1|id2|id3' /directory/$file >> output; done

I would appreciate any help and I will gladly specify if not everything is clear to you.
EDIT: i will try to clarify, sorry for the inconvenience:
so theres a file called "pfamacc" with the following content:
PF12312
PF43555
PF34923

and so on - those are the IDs that i need to acces other files, which have a structure like that "something_something.faa.out"
<acc_number> <aligment_start> <aligment_end> <pfam_acc>
RXOOOA 5 250 PF12312
OC2144 6 200 PF34923

i need those accesion numbers so i can then get protein sequences from files which look like this:
>RXOOOA
ASDBSADBASDGHH

>OC2144
SADHHASDASDCJHWINF

A: With the assumption there is a file ids_file.txt in the same directory with the subsequent content:
id1
id2
id3
id4

And in the same directory is as well a file called id1 with the following content:
Bla bla bla
id1
and id2
is
here id4

Then this script could help:
#!/bin/sh

IDS=$(cat ids_file.txt)
IDS_IN_ONE=$(cat ids_file.txt | tr '\n' '|' | sed -r 's/(\|)?\|$//')
echo $IDS_IN_ONE

for file in $IDS; do
 grep -n -E "$IDS_IN_ONE" ./$file >> output
done

The file output has then the following result:
2:id1
3:and id2
5:here id4

A: Reading that a list needs to be cross-referenced to get a 2nd list, which then needs to be used to gather FASTAs.
Starting with the following 3 files...
starting_values.txt
PF12312
PF43555
PF34923

cross_reference.txt
<acc_number> <aligment_start> <aligment_end> <pfam_acc>
RXOOOA 5 250 PF12312
OC2144 6 200 PF34923

find_from_file.fasta
>RXOOOA
ASDBSADBASDGHH
>OC2144
SADHHASDASDCJHWINF
SADHHASDASDCJHWINF
>NC11111
IURJCNKAERJKADSF

for i in `cat starting_values.txt`; do awk -v var=$i 'var==$4 {print $1}' cross_reference.txt; done > needed_accessions.txt

If multiline FASTA change to single line. https://www.biostars.org/p/9262/
awk '/^>/ {printf("\n%s\n",$0);next; } { printf("%s",$0);}  END {printf("\n");}' find_from_file.fasta > find_from_file.temp

for i in `cat needed_accessions.txt`; do grep -A 1 "$i" find_from_file.temp; done > found_sequences.fasta

Final Output...
found_sequences.fasta
>RXOOOA
ASDBSADBASDGHH
>OC2144
SADHHASDASDCJHWINFSADHHASDASDCJHWINF


text:
Q: Convert FormFile to Java.io.File I have an object FormFile recovered through a Struts Form .
I have to convert Java side in the java.io.File
How can I do? The casting in this way by exception:
File myFile = (File) fileFormFile

A: Here, I found something you might use:
http://www.coderanch.com/t/54902/Struts/Struts-FormFile-java-io-File

A: Read the API document of FromFile class what methods it all provides. Use getInputStream() method.


text:
Q: Participial adjectives & verb participles Q) She is much liked by everybody.
This is about the possibility of using degree adverb to participial adjectives and verb participles.
In this sentence, is 'liked' used as a participial adjective? or a verb participle?
The answer in this book is that 'liked' is used as a participial adjective, so it can be modified by the degree adverb 'much'. However, there is a explicit personal agent 'everybody', so I think it should be a verb participle.

A: A 'participle' is a verb form that is nonfinite and an adjective or adverb.   So, "liked" is certainly both a "participle verb form" and a "participle adjective" as well!  Those can both be true, and are both true in this sentence.
"Liked" is /not/ a finite verb form here, and 'everybody' is not its subject!
This is a little confusing, because "liked" spelled just the same can be a past tense finite verb form with a subject, sometimes:

Everybody liked her.

Here, unlike you example sentence, "liked" is not a participle.
But in your sentence, it is a participle, and your book is correct that the use of 'much' is permitted because of this.
So, "by everyone" is a just a prepositional phrase.  Compare the following sentences, which are grammatically identical:

She is liked by everyone.

The soup is cooked with wine.

It should be clear that "wine" is not a verb subject.  The wine is certainly not doing the cooking.  But the grammar is exactly the same in both sentences - "everyone" is not a verb subject either in the first sentence.

A:
She is much liked by everybody.

The degree AdvP "much" indicates that "liked" is an adjective here. If it was a verb, the active counterpart would be the ungrammatical *"Everybody much likes her".
The clause does have a by phrase with "everybody", but such phrases are permitted in adjectival passives when the meaning of the corresponding verb is stative, as it is in your example  (the verb "like" is stative).
Compare also "Ed was worried by the prospect of redundancy", where "worried is an adjective because the corresponding verb "worry" has a stative meaning.
Edit: there's a lot of confusion about participles and whether they are verbs or adjectives. The simplest way round this is to use the term 'participial adjective' for the adjectives, reserving the term 'participle'for the verbs.


text:
Q: Apache, mod_*, PHP, Perl, Python, Ruby; Learning backwards I started web development some time ago, but have invested essentially all my time in learning PHP, MySQL/SQLite, (X)HTML/XML (XPath, XQuery, XSL), etc. I went with an out-of-the-box XAMPP install, everything was pretty straightforward, and I could focus my learning on languages.
Now, however, I'm looking to learn Ruby and Python (and more Perl) but to my dismay, have discovered that I know essentially nothing about Apache configuration, or any related tasks associated with setting up an environment for embedded PHP, Perl, Python and Ruby.
I posted recently a question that I thought would take me in the correct direction. Having read the mod_wsgi and mod_rails docs, I'm more confused than I was to start.
I'm running Windows 7 x64 with an existing XAMPP installation, just grabbed Ruby and Python, just installed NetBeans; and I'm wondering:

*

*Should I start with a fresh Apache install, or is XAMPP fine to pile additional modules on?

*Where can I find some information about configuring Apache to support these modules? I'm thinking step-by-step to build an environment that supports some of, all of, or more than the aforementioned languages.
I suppose my question can be summarized to; What are some suggested reading/learning resources for configuring an Apache based multi-language web application development environment?
I hope this question isn't regarded with high subjectivity or generality; I'm just lost and don't want to waste time staring blankly at configuration files or the like.
I really appreciate any insight, and forgive my noob factor. I am surprised I am as unfamiliar with this territory as I am, and quickly need to change that.

A: I would recommend the following:
Make your home in the Ubuntu environment within the VM you mentioned
Essentially all of the technologies you mentioned started out in Unix-based systems, and, while the playing field is leveling, there are still significant advantages to developing with these technologies in a Unix-based OS (such as the Ubuntu install you mentioned.)
Additionally, Ubuntu is very well documented online, has active forums, and has very nice install systems (apt-get, aptitude.)
Learn Nano
You can use other IDE's or text editors, but Nano is really, really easy to use, so you can focus on learning the technologies you're interested in, not a complex text editor such as vim or emacs (which are both fantastic, but learning sessions in and of themselves.)
Get yourself a cheap cloud server to pound on
Many companies offer great cloud servers. The nice thing about this is that you can play with the every aspect of the environment, including the networking capabilities, such as getting a firewall running, etc.
For instance, Rackspace Cloud Servers work great and the Wiki pages walk you through a vast number of installs and configurations (I just pointed you to the Ubuntu docs cuz that's what you mentioned already running):
Rackspace Cloud Server Wiki
Build up your web server from scratch (and keep a log of the build steps, so if something doesn't go well, you could redo things quickly.)
Start building (and breaking) your next great app
Start making a cool app using the technology of choice. If you want to focus on Ruby next, crank out an ROR app, or even dig down and use RACK to set up you're own baby framework for handling web requests:
Rack: a Ruby Webserver Interface
Or, if python is your next learning project, try out Django, or even jump down to CherryPy for a low level web server implementation that helps you see all the moving parts:
CherryPy
Join the mailing lists of the technologies you're most interested in
Mailing lists provide great insights into the strengths and weaknesses of technologies. Just joining a list to listen to the daily banter can significantly help your understanding of the technology and the challenges that you'll likely face in the future.
These are all things I've done (different language focuses, but same techniques) and they've helped me greatly. Hopefully, they help you, too :) Happy coding!

A: Just an additional info, XAMPP has mod_perl included since version 1.7.2.
To setup this quickly on Windows, already prepared stacks built by BitNami can help:

*

*Ruby + Rails

*Python + Django


text:
Q: Qt: init-repository aborts with "fatal: Needed a single revision" I'm trying to build revision 5.9 of Qt5 from git sources but updating the submodules fails:
git clone https://github.com/qt/qt5.git
cd qt5
git checkout 5.9
./init-repository
...
... lots of submodules being updated successfully
...

fatal: Needed a single revision
Unable to find current revision in submodule path 'qtnetworkauth'
git submodule update --force --no-fetch exited with status 256 at ./init-repository line 198.
    Qt::InitRepository::exe(Qt::InitRepository=HASH(0x1fa94b0), "git", "submodule", "update", "--force", "--no-fetch") called at ./init-repository line 429
    Qt::InitRepository::git_clone_all_submodules(Qt::InitRepository=HASH(0x1fa94b0), "qt/qt5", 0, "preview", "essential", "addon", "deprecated") called at ./init-repository line 644
    Qt::InitRepository::run(Qt::InitRepository=HASH(0x1fa94b0)) called at ./init-repository line 655

So it looks like qtnetworkauth is somehow mis-configured but I don't know how to solve it.
I tried to remove the qtnetworkauth module by deleting references inside .gitmodules, qtdoc and the folder itself but then other modules fail.
Strangely - when I run ./init-repository -f after removing and adding references to qtnetworkauth I can see it being checked out, but the submodules folder is still empty:
...
+ git clone --no-checkout https://github.com/qt/qtnetworkauth qtnetworkauth
Cloning into 'qtnetworkauth'...
remote: Counting objects: 283, done.
remote: Compressing objects: 100% (14/14), done.
remote: Total 283 (delta 3), reused 0 (delta 0), pack-reused 269
Receiving objects: 100% (283/283), 200.12 KiB | 0 bytes/s, done.
Resolving deltas: 100% (139/139), done.
Checking connectivity... done.
+ git config commit.template /home/frans/_HOME/0000_android_dev/qt5/.commit-template
+ git config remote.gerrit.url ssh://codereview.qt-project.org/qt/qtnetworkauth
...

What can I have done wrong? Or if it's a Qt bug - how can I workaround it?

A: You're changing branches before actually getting all the repositories. That probably breaks something in the ./init-repository script.
I've checked that this sequence works:
git clone git://code.qt.io/qt/qt5.git
cd qt5/
./init-repository
git checkout 5.9
git submodule update


text:
Q: XCode Main Thread Checker: Google Maps SDK I'm getting this compiler warning :

Main Thread Checker: UI API called on a background thread:
  -[UIApplication applicationState] PID: 2250, TID: 542348, Thread name: com.google.Maps.LabelingBehavior, Queue name:
  com.apple.root.default-qos.overcommit, QoS: 21

Running:

*

*XCode Version 9.0 (9A235).

*GoogleMaps-2.4.0.

I guess this is a bug..?


text:
Q: Locate Java path from Delphi Does anyone know how to locate java.exe path using Delphi?
I'm starting Java application in Delphi program and I need java.exe path. I used google, but I didn't find anything :(
I can't use constant path because some systems have 64 bit java, some 32 bit, some people install java on D: drive...

I will use this http://jstart32.svn.sourceforge.net/viewvc/jstart32/trunk/src/template/
Thank you everyone!


text:
Q: AzureDevOps yaml template - expression as parameter default value I want to have an expression as a default value for a parameter but I get "a template expression is not allowed in this context"
Since templates cannot have variables unless they ONLY have variables (another thing I don't get...), I am looking for other alternatives. Anyone has any idea?
What I'm trying is this:
parameters:
  - name: paramOne
    default: ${{ lower(replace('$(System.TeamProject)',' ','')) }}
    type: string

EDIT
Here's a full example. This is azure-pipelines.yml
trigger:
- main

pool:
  vmImage: windows-2019

steps:
- template: test-template.yml

This is test-template.yml:
parameters:
  - name: paramOne
    default: ${{ lower(replace(variables['System.TeamProject'],' ','')) }}
    type: string
steps:
- task: PowerShell@2
  displayName: "Run PowerShell script"
  inputs:
    targetType: 'inline'
    script: Write-Host "${{parameters.paramOne}}"

This results in the error:
"a template expression is not allowed in this context"
Variables cannot be added to test-template.yml, as indicated here:
https://learn.microsoft.com/en-us/azure/devops/pipelines/process/templates?view=azure-devops#variable-reuse
"If you are using a template to include variables in a pipeline, the included template can only be used to define variables"

A: Ok, then I would propose the following workaround
parameters:
  - name: paramOne
    displayName: 'My param. Leave empty to populate with default value (project name). bla bla...'
    default: ''
    type: string

steps:

- task: PowerShell@2
  name: 'setVar'
  inputs:
    targetType: inline
    script: |
      if( "${{ parameters.paramOne }}" -eq "") {
        $val = "$(System.TeamProject)".ToLower().Replace(" ","")
      } else {
        $val = "${{ parameters.paramOne }}"
      }
      echo "##vso[task.setvariable variable=varOne]$val"

and from there on use varOne instead of paramOne

A: It looks that this is not possible. I tested with this:
parameters:
  - name: paramOne
    default: $[lower(replace(variables['System.TeamProject'],' ',''))]
    type: string
  - name: paramTwo
    default: $(runtimeVar)
    type: string
  - name: paramThree
    default: $(compileVar)
    type: string
steps:
- task: PowerShell@2
  displayName: "Run PowerShell script"
  inputs:
    targetType: 'inline'
    script: |
      Write-Host "${{parameters.paramOne}}"
      Write-Host "${{parameters.paramTwo}}"
      Write-Host "${{parameters.paramThree}}"

and
trigger: none

variables:
  runtimeVar: $[lower(replace(variables['System.TeamProject'],' ',''))]
  compileVar: ${{ lower(replace(variables['System.TeamProject'],' ','')) }}

pool:
  vmImage: windows-2019

steps:
- template: parameter-with-default-runtime-template.yml

and I got:
$[lower(replace(variables['System.TeamProject'],' ',''))]
devopsmanual
devopsmanual

So you see, the same syntax which is used to populate variable doesn't do the same when you use it as default for parameter.


text:
Q: NSURLSession didFinishDownloadingToURL temporary downloaded file not found I'm having a strange issue with NSURLSession on the delegate method didFinishDownloadingToURL.
First thing I'm doing is check if the temporary downloaded file exist:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
                                            didFinishDownloadingToURL:(NSURL *)location
{
    if (![[NSFileManager defaultManager] fileExistsAtPath: [location path]])
    {
        NSLog(@"Error. File not found");
        return; // is giving error when the app is wake up by the system
    }
    ...
}

It works normally when the app is in foreground and download finishes. But when the app is in background and is killed forcedly by the operating system, it returns false.
Does anyone have any idea about what might be happening? I know that there is a time limit for the execution of this delegate method when the app is wake up by the operating system, by it makes no sense for the temporary file to be not there. I can't even copy it to another location...
Does it make sense to be because of the size of the file? I'm downloading a file of +-130MB.
Thanks.

A: I solved the same problem by installing app after uninstall app. It seems that the NSURLSession leaves debris on system when forced shutdown happens while a network session working.

A: From the Apple Docs:
(location is..) "A file URL for the temporary file. Because the file is temporary, you must either open the file for reading or move it to a permanent location in your app's sandbox container directory before returning from this delegate method.
If you choose to open the file for reading, you should do the actual reading in another thread to avoid blocking the delegate queue."


text:
Q: Dijkstra's Algorithm for Negative Weights Okay, first of all I know Dijkstra does not work for negative weights and we can use Bellman-ford instead of it. But in a problem I was given it states that all the edges have weights from 0 to 1 (0 and 1 are not included). And the cost of the path is actually the product.
So what I was thinking is just take the log. Now all the edges are negative. Now I know Dijkstra won't work for negative weights but in this case all the edges are negative so can't we do something so that Dijkstra would work.
I though of multiplying all the weights by -1 but then the shortest path becomes the longest path.
So is there anyway I can avoid the Bellman-Ford algorithm in this case.
The exact question is: "Suppose for some application, the cost of a path is equal to the product all the weights of the edges in the path. How would you use Dijkstra's algorithm in this case? All the weights of the edges are from 0 to 1 (0 and 1 are not inclusive)."

A: If all the weights on the graph are in the range (0, 1), then there will always be a cycle whose weight is less that 1, and thus you will be stuck in this cycle for ever (every pass on the cycle reduces the total weight of the shortest path). Probably you have misunderstood the problem, and you either want to find the longest path, or you are not allowed to visit the same vertex twice. Anyway, in the first case dijkstra'a algorithm is definitely applicable, even without the log modification. And I am pretty sure the second case cannot be solved with polynomial complexity.

A: So you want to use a function, let's say F, that you will apply to the weights of the original graph and then with Dijkstra's algorithm you'll find the shortest product path. Let's also consider the following graph that we start from node A and where 0 < x < y < 1:

In the above graph F(x) must be smaller than F(y) for Dijkstra's algorithm to output correctly the shortest paths from A.
Now, let's take a slightly different graph that we start again from node A:

Then how Dijkstra's algorithm will work?
Since F(x) < F(y) then we will select node B at the next step. Then we'll visit the remaining node C. Dijkstra's algorithm will output that the shortest path from A to B is A -> B and the shortest path from A to C is A -> C.
But the shortest path from A to B is A -> C -> B with cost x * y < x.
This means we can't find a weight transformation function and expect Dijkstra's algorithm to work in every case.

A: You wrote:

I though of multiplying all the weights by -1 but then the shortest
  path becomes the longest path.

To switch between the shortest and the longest path inverse the weights. So 1/3 will be 3, 5 will be 1/5 and so on.

A: If your graph has cycles, no shortest path algorithm will find an answer, because those cycles will always be "negative cycles", as Rontogiannis Aristofanis pointed out.
If your graph doesn't have cycles, you don't have to use Dijkstra at all.
If it is directed, it is a DAG and there are linear-time shortest path algorithms.
If it is undirected, it is a tree, and it's trivial to find shortest path in trees. And if your graph is directed, even without cycles, Dijkstra still won't work for the same reason it doesn't work for negative edge graph.
In all cases, Dijkstra is a terrible choice of algorithm for your problem.


text:
Q: I can't get my favicon to change I need help with my website's favicon.
The current code I use for my favicon is:

<link rel="shortcut icon" href="Logo.png" type="image/x-icon"></link>

But for some reason it's not working,
does anyone have a solution for my problem?

A: try this code <link rel="icon" type="image/png" href="myicon.png">

A: You say the icon is of the type "icon" (image/x-icon). Just change x-icon to say png instead. The full snippet:
<link rel="shortcut icon" href="Logo.png" type="image/png"></link>


text:
Q: How to find Cell index inside kendo-grid & how to set dirty property as true I just want to select Check Box on Icon 'A' click. So how will I find check box control.

file.js
var GridArchiveAction = function (id) {
    if (confirm("Are you sure you want to archive this item?")) {
        var grid = $('#Grid').data("kendoGrid");
        var item = grid.dataSource.get(id);
        var dataRow = grid.dataSource.getByUid(item.uid);
        if (dataRow != undefined) {
            dataRow.addClass("k-state-selected")
                .find(".isLockedchkbx")
                .prop("checked", "checked");

        } else {
            alert("You Must Select A Row To Archive A Record!");
        }
    }
};

A: Why you need checkbox control?
Generally you can get it passing this like
onclick="GridArchiveAction(this, #: id #); "
//OR
var GridArchiveAction = function (this, id);`

You can get checkbox control by $(this).

A: Please try with the below code snippet.

Let me know if any concern.


text:
Q: Carofredsel and jQuery UI tabs elements hidden I have set up caroufredsel inside of a jQuery tabs, but all of the elements inside the tabs are invisible. It seems that the caroufredsel wrapper height and width are both set to 0, and the overflow is set to hidden.
I can see that caroufredsel is creating the proper wrapper and including my content into it, but the content is invisible. Anyone had this issue before?

A: Anyone else facing such an issue, I was able to resolve the issue by using the jQuery('#carousel').trigger('updateSizes'); on tab click


text:
Q: Makefile still returns error I still get error when i try run this
OS=$(shell uname -s)

#################################################################
printVar:
        ifeq ($(OS),Darwin)
        @echo $(OS)
        endif

all:
        make -j3 -f $(MAKEFILE)

terminal
$ make printVar
ifeq (Darwin,Darwin)
/bin/sh: -c: line 0: syntax error near unexpected token `Darwin,Darwin'
/bin/sh: -c: line 0: `ifeq (Darwin,Darwin)'
make: *** [printVar] Error 2

A: You don't want a tab before ifeq/endif as they are not commands:
OS=$(shell uname -s)

#################################################################
printVar:
ifeq ($(OS),Darwin)
    @echo $(OS)
endif

all:
    make -j3 -f $(MAKEFILE)


text:
Q: boost::gregorian::date with time? So far it looks like boost::gregorian::date only has day/month/year. I need to also store hour/minute/second. Can this object handle both? I'm having difficulty understanding how to represent all of this data.

A: No, this object cannot handle that (because then boost::gregorian::date wouldn't be a ... date).
If you need a datetime, use boost::posix_time::ptime (which is a tuple of gregorian::date, time_duration).
If you also need a timezone look at boost::local_time::local_date_time or Boost Locale's date_time


text:
Q: Count number of entries based on month and year I have the following sample data:
test={{{2020, 1, 1}, Brazil}, {{2020, 1, 2}, Brazil}, {{2020, 1, 1}, Brazil}, {{2020, 2, 1}, Brazil}, {{2020, 1, 1}, Brazil},{{2019, 1, 1}, Brazil}}

I would like to first group the data by month and year, and then count how many entries are in each group.
I would like the output to look something like this:
<|{{2020, 1},4}, {{2020, 2},1},{{2019, 1},1}|>

A: You can use CountsBy for this:
CountsBy[test[[All, 1]], d |-> d[[;; 2]]]

<|{2020, 1} -> 4, {2020, 2} -> 1, {2019, 1} -> 1|>


text:
Q: Regular Expression to match someting that starts with I am trying to get a Match from this string
"Dial [Toll Free 1800 102 8880 ext: 246] to connect to the restaurant.  <a class='tooltip' title='Foodiebay has now introduced value added calling features through the website. You just need to dial this number and we ..."

Where I want to check if a variable starts with the string Dial
$a = 'Dial [Toll Free 1800 102 8880 ext: 246] to connect to the restaurant.  <a class='tooltip' title='Foodiebay has now introduced value added calling features through the website. You just need to dial this number and we';

preg_match('/[^Dial]/', $a, $matches);

A: I'd rather to use strpos instead of a regexp :
if (strpos($a, 'Dial') === 0) {
    // ...

=== is important, because it could also returns false. (false == 0) is true, but  (false === 0) is false.
Edit: After tests (one million iterations) with OP's string, strpos is about 30% faster than substr, which is about 50% faster than preg_match.

A: Lose the square brackets:
/^Dial /

This matches the string "Dial " at the start of a line.
FYI: Your original regex is an inverted character class [^...], which matches any character that isn't in the class. In this case, it will match any character that isn't 'D', 'i', 'a' or 'l'. Since almost every line will have at least character that isn't one of those, almost every line will match.


text:
Q: Is it possible to delete data from webpage but do not delete from database? I wish to know that whether is there any possible that can allow me to delete or hide the data on my php website but when I go inside my database, the record that is being deleted will still store inside the original database?

A: You have to add a deleted flag to your table
For deleting you set the flag:
UPDATE table SET deleted=1 WHERE id=xy

For geting the data from the database you have to check the flag:
SELECT * FROM table WHERE deleted=0


text:
Q: Spring, MVC and strategy to reuse parts of the model I'm struggling to understand what would be the best strategy to reuse some code. Normally, I my have controllers in Spring as:
@Controller
public class PageX1{
  @Autowired
  HeaderService header;

  @Autowired
  CatalogService catalog;

  @RequestMapping("/test1")
  public String controller(Map<String, Object> model)  {

    setHeaderObjectsIntoModel(model, "a param");
    setCatalogObjectsInyoModel(model, "another param", 1212, "more params");
  }

   private setHeaderObjectsIntoModel(Map<String, Object> model, String aParam){
     Object value = header.getObjectWithParam(aParam);
     model.put("key", value);
   }

   ....
}

I may need to reuse the part related to service S1 in another controller, e.g.
@Controller
public class PageX2{
  @Autowired
  HeaderService s;

  @RequestMapping("/test2")
  public String controller(Map<String, Object> model)  {
    setHeaderObjectsIntoModel(model, "a new param");
  }
}

and the same for S2, and again and again.
I don't want to duplicate code. I had some idea in my mind, but nothing good I think (like having a class annotated with @Component that implements an interface aimed to handle the model, but I should make the parameters generic and I would like to have it specific to minimize mistakes).
What should be the right approach?
Any example is more than welcome

A: You have two options. First option you can have a base controller which provides the common functionality which will be inherited by your controllers
public abstract class AbstractPage{

   @Autowired
   private HeaderService s;

   protected Object retrieveObjectWithParam(String param){
      return s.getObjectWithParam(param);
   }
}

@Controller
public class PageX1 extends AbstractPage{

  @RequestMapping("/test1")
  public String controller(Map<String, Object> model)  {
    Object headerParam = retrieveObjectWithParam("a param");
    model.put("key" , headerParam);
  }
}

Second option is to use @ControllerAdvice annotated class that provides common model attributes for your controllers
@ControllerAdvice
public class PageAdvice{

    @Autowired
    private HeaderService s;

   @ModelAttribute("headerParam")
   public Object retriveHeaderParm(){
      return s.getObjectWithParam("a param");
   }
}


text:
Q: How to direct custom DuckDuckGo search to specific site in html? I'm coding a custom search bar in HTML and jQuery.
The code I have so far:

$(document).ready(function() {
  $('.submit_on_enter').keydown(function(event) {
    // enter has keyCode = 13, change it if you want to use another button
    if (event.keyCode == 13) {
      this.form.submit();
      return false;
    }
  });
});

    <form action="https://google.com/" method="get">
      <input autocomplete="off" class="submit_on_enter" type="text" name="q" placeholder="Search Art">
    </form>

What I'm looking to do is limit searches to a specific site purely in html/in the URL itself. On the actual Google webpage this is easy - you could just enter "site:website.com" and it would be done. But in this setup I have, name="q" is already appended to any searches. If I get rid of the name="q" section, the search doesn't work properly (it just goes to google's homepage) and if I tamper with the url, then it just searches for whatever I add. DuckDuckGo is acceptable too.

A: You need to put the site:website.com as part of the value of q not the key.

$(document).ready(function() {
  $('.submit_on_enter').keydown(function(event) {
    // enter has keyCode = 13, change it if you want to use another button
    if (event.keyCode == 13) {
      this.form.q.value = "site:website.com " + this.form.q.value
      this.form.submit();
      return false;
    }
  });
});

    <form action="https://google.com/" method="get">
      <input autocomplete="off" class="submit_on_enter" type="text" name="q" placeholder="Search Art">
    </form>

Side note: the snippet won't actually redirect because of stackoverflow's security on the iframe.


text:
Q: Toggle menu left I've tried making a menu that toggles left to right and I copied some of the script from the suggestion on this post: http://jsfiddle.net/QDUQk/1/
however, when I plug in my specific Class and Id names, I didn't seem to work. The menu will open up but it doesn't seem to want to close. I am not sure what I am doing wrong. Any help would be greatly appreciated.
My Jquery:
$(function() {
$('.menuBars').click(function () {
if($('.menuBars').is(':visible')){
    $('.menuBars').fadeOut(function () {
    $('.menuItems').toggle('slide', {
        direction: 'left'
    }, 1000);
});
}
else{
    $('.menuItems').toggle('slide', {
        direction: 'left'
    }, 1000, function() { $('.menuBars').fadeIn();});
}
});

This is my CCS:
.menuItems {
position:relative;
float: right;
display:none;
top: 50%;
margin-top:-9px;
background-color:#DEDEDE;
border-radius:4px;
padding-left:20px;
padding-top:2px;
padding-bottom:2px;}

and my HTML:

Richard

Projects

About

Contact

A: First, your code occurs Uncaught TypeError: jQuery.easing[this.easing] is not a function error.
You need to include jQuery UI for the extended easing options.
and your div will not close, because close button has no any event for that.
Fixed code
$(function() {
  $('#closer').click(function () {
    $('.menuBars').fadeIn(function () {
      $('.menuItems').toggle('slide', {
        direction: 'left'
      }, 1000);
    });
  });
  $('.menuBars').click(function(){
   $('.menuItems').toggle('slide', {
          direction: 'left'
      }, 1000, function() { $('.menuBars').fadeOut();});
  });
});

Fiddle

A: You just missed a small part while applying your classes, the click event should be applied to both .menuBars  and .menuItems. This has to be done cause  when the menu is shown and the title is hidden you can't click on the title, you click on the menu and this should trigger the slide and the fade.
Simply correct the function to be:
$('.menuBars, .menuItems').click(function () {

This should solve your problem
http://jsfiddle.net/wf0fpzy6/


text:
Q: xcode 4.2 soundboard thread 1 hi i have created a Xcode soundboard but when i run it on my iPhone i get this error and not to sure how to solve it can you help ?
//
//  main.m
//  sound
//
//  Created by Paul masters on 27/04/2012.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

#import "AppDelegate.h"

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

the error is
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));

thread 1: signal SIGABRT
THANKS
this is the view controller.h
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>

@interface ViewController : UIViewController
- (IBAction)yooo:(id)sender;

- (IBAction)boom:(id)sender;

@end

this is the view controller.m
- (IBAction)yooo:(id)sender {

    CFBundleRef mainbundle = CFBundleGetMainBundle();
    CFURLRef soundFileUrlRef;
    soundFileUrlRef = CFBundleCopyResourceURL(mainbundle, (CFStringRef) @"tb1", CFSTR ("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileUrlRef, &soundID);
    AudioServicesPlaySystemSound(soundID);}

- (IBAction)boom:(id)sender {

    CFBundleRef mainbundle = CFBundleGetMainBundle();
    CFURLRef soundFileUrlRef;
    soundFileUrlRef = CFBundleCopyResourceURL(mainbundle, (CFStringRef) @"ta1", CFSTR ("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileUrlRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}

@end

this is my code with that thread 1 error!!

A: what you need to do is locate build phases and then click + and add audio.framework
and then try to run and build and all should be good.

A: You need to set an exception breakpoint. See "Run > Stop on Objective-C exception" in Xcode 4?. If you don't have an exception breakpoint and an exception occurs, all you will see is just a SIGABRT with no stack, so you can't find out, what really happened.


text:
Q: Application didFinishLaunchingWithOptions or applicationDidBecomeActive I would like to know how I can provide the way to user for downloading the content from server.
If the user subscribes for one month, I want to deliver them a new content (songs) every day. But I am not sure how to work on this.
Do I need to call the webservice in application didFinishLaunchingWithOptions or in the - (void)applicationDidBecomeActive:(UIApplication *)application {
Which one should I use for this kind of situation?

A: If you're planning on starting a new connection when the app launches, then you'll want to use
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    return YES;
}

However, applicationDidBecomeActive is better suited for resuming a download that you paused when your application was backgrounded. Starting the download here COULD also be acceptable too.
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


text:
Q: How to solve this issue "Standard outputs should not be used directly to log anything " I need a print statement. But sonar not allowed this type.
String txt="Something";
System.out.println("Print: "+txt);

Expected output:
Print: Something

I tried this format logger.log().its not working for our requirement.

A: If logger is not meeting your requirements, make it to do so by configuring it.
There are some widely used logging frameworks that are highly configurable and I doubt that they will not be able to do whatever you are doing with plain System.out.println
For example, check out very popular SLF4J and Logback as logging provider.
http://www.slf4j.org/
http://logback.qos.ch/

A: Sonarqube does not like it if you use System.out, or if you have string concatenation or other computation in the arguments you pass to the logging function. Construct the full message on a separate line before logging it:
String txt = "Print: " + "Something";

String logMessage = "Print: " + txt;
logger.log(Level.INFO, logMessage);