text:
Q: Javascript click event not working in Google Chrome? I have a search function in which the user selects a date range, and search box if desired, and it loads the query results dynamically into an HTML div element. When the results are displayed, there is a selection box to select a field to sort by. When the user selects a field, it triggers another AJAX request which "dynamically reloads" the page into the div element again, sorting the results by the selected field. The method I am currently using works just fine under Mozilla Firefox, but does not work under Google Chrome.
Here is the JS file that handles the AJAX request:
/*========================================================
    sendServiceRequest.js: handles ajax request for
    dynamically loading data
*/
function sendServiceRequest(file, nvpSendData, successCallback, failCallback) {
    $.ajax({
        type: "POST",
        url: file,
        data: nvpSendData,
        dataType: 'html'
    }).success(function(data, status) {
        console.log(".done");
        console.log("Return AJAX status: " + status);
        //console.log("success data: " + JSON.stringify(data));
        successCallback(data, status);
    }).fail(function(data, status, error) {
        console.log(".fail");
        console.log("Return AJAX status: " + status);
        //console.log("Return data: " + JSON.stringify(data));
        failCallback(data, status, error);
    });
}

function sendSortServiceRequest(searchType, fromDate, toDate, searchString, column, order) {
    sendServiceRequest(
        "/search/get_content.php",
        {action:"sort", search_type:searchType, from_date:fromDate, to_date:toDate, search_str:searchString, col:column, order:order},
        function(data, status) {
            $('#results-container').html(data);
        },
        function(data, status, error) {
          console.log(".fail");
          console.log("Return AJAX status: "+status);
        }
    );
}

The first function, sendServiceRequest(), is what initially loads the search results into the div element.
And here is a fragment of the code that is dynamically loaded into a div element, the selection element that triggers an event upon clicking on an option:

                Sort By:

                <select class="sort_select" id="charge_auth_sort_select" style="width:100%; padding:0; margin:0;">

                    <option onClick="sendSortServiceRequest('charge-auth', '<?php echo $fromDate; ?>', '<?php echo $toDate; ?>', '<?php echo $searchString; ?>', 0, '<?php echo $sortArgs[0]['order']; ?>')">
                        Status
                    </option>
                    <option onClick="sendSortServiceRequest('charge-auth', '<?php echo $fromDate; ?>', '<?php echo $toDate; ?>', '<?php echo $searchString; ?>', 1, '<?php echo $sortArgs[1]['order']; ?>')">
                        Order ID
                    </option>
                    <option onClick="sendSortServiceRequest('charge-auth', '<?php echo $fromDate; ?>', '<?php echo $toDate; ?>', '<?php echo $searchString; ?>', 2, '<?php echo $sortArgs[2]['order']; ?>')">
                        User ID
                    </option>
                    <option onClick="sendSortServiceRequest('charge-auth', '<?php echo $fromDate; ?>', '<?php echo $toDate; ?>', '<?php echo $searchString; ?>', 3, '<?php echo $sortArgs[3]['order']; ?>')">
                        Order Date
                    </option
                    <option onClick="sendSortServiceRequest('charge-auth', '<?php echo $fromDate; ?>', '<?php echo $toDate; ?>', '<?php echo $searchString; ?>', 4, '<?php echo $sortArgs[4]['order']; ?>')">
                        Last Updated
                    </option>
                    <option onClick="sendSortServiceRequest('charge-auth', '<?php echo $fromDate; ?>', '<?php echo $toDate; ?>', '<?php echo $searchString; ?>', 5, '<?php echo $sortArgs[5]['order']; ?>')">
                        Insurance Type
                    </option>
                    <option onClick="sendSortServiceRequest('charge-auth', '<?php echo $fromDate; ?>', '<?php echo $toDate; ?>', '<?php echo $searchString; ?>', 6, '<?php echo $sortArgs[6]['order']; ?>')">
                        Delivery Method
                    </option>
                </select>

So after the results are loaded into the div element of the 'parent' page, the user can select a field option from the selection list. When the user clicks the option, it should trigger the sendSortServiceRequest() function, reloading the results into the element, sorted by the selected field.
Again, this works just fine under Firefox, but does not want to work under Chrome. I've been stuck on this for quite a while now. Any help would be greatly appreciated.

A: I changed the way I was handling the click event, and it worked. I'm using a jquery click event in the parent page, rather than the 'onclick' method on the dynamically loaded element.
$('#results-container').on('change', '.fieldsort', function() {
    var opt = $('.fieldsort :selected');
    sendServiceRequest(
            '/search/get_content.php',
            {action:opt.attr('data-action'), search_type:opt.attr('data-searchtype'), from_date:opt.attr('data-fromdate'), to_date:opt.attr('data-todate'), search_str:opt.attr('data-searchstr'), col:opt.val(), order:opt.attr('data-order')},
            function (data, status) {
                $('#results-container').html(data);
            },
            function (data, status, error) {
                console.log('.fail');
                console.log('Return AJAX status: '+status);
            }
    );
});

Also, click events on selection options do not seem to work in google chrome. Atleast I could not get them to work at all.


text:
Q: Exclude/include folders without contents using gitignore I am currently trying to exclude all contents of those 3 folders but keep the folders themselfs:

*

*files/*

*files/private/*

*files/tmp/*

But for now just the files directory gets included.
This is what my .gitignore looks like:
default-export/files/*
default-export/files/private/*
default-export/files/tmp/*

!default-export/files/.gitkeep
!default-export/files/private/.gitkeep
!default-export/files/tmp/.gitkeep

A: You are missing the explicit un-excludes of the directories private and tmp. Without them, Git does not further process the directory structure at all.
This should work according to your described requirements:
default-export/files/*
!default-export/files/.gitkeep
!default-export/files/private/
!default-export/files/tmp/

default-export/files/private/*
!default-export/files/private/.gitkeep

default-export/files/tmp/*
!default-export/files/tmp/.gitkeep

A: Description
I shall like to clarify that the Folders don't hold great significance for Git.
Simply speaking, they are just considered as "Links" to the files inside it.
Hence, an empty directory can't be staged.
In some cases, in order to preserve the directory structure, the directory needs to be added. The same can be achieved by placing a dummy file inside it.
Over the years, the dummy file has received the name .gitkeep (You can name it anything you want to. . is for hiding the same in a LINUX/UNIX System).
Solution to your Problem
You need to create the .gitkeep file and then, add the following lines to your .gitignore.
theEmptyDirectory/*

!.gitkeep

Here is the directory structure I used to test the same

thisIsAPrivateFile represents the content I want to keep private while maintaining the directory structure.
And the git status (After staging) result.

As you can clearly see, thisIsAPrivateFile has not been staged.
UPDATE
After Matt's comment, I shall like to inform a certain limitation of git.

Basically, if the parent directory has been excluded, no matter what, any files inside the same can't be included. Since, in the above example, I have excluded everything (even nested directories) using * then, everything inside those nested directories won't be included.
We can bypass this limitation by specifying the types of files we want to exclude.
Here is the new directory structure

Updated .gitignore
theEmptyDirectory/**/*.js
theEmptyDirectory/**/*.jsx
theEmptyDirectory/**/*.ts

!.gitkeep

And the git status result (After Staging)

Clearly, the directory structured has been preserved but, the private files have been exluded.
References

*

*Difference Between .gitignore and .gitkeep

*Negating Patterns in .gitignore

*Internal Git Objects

*Reading on .gitignore

redpajama_set_name: RedPajamaStackExchange


text:
Q: QHttpResponseHeader is obsolete and removed from Qt5 In my project, I used QHttpResponseHeader in Qt4.8.6, but it became obsolete and it is not
available anymore in Qt5. What is its equivalent class in Qt5?

A: There is an equivalent already available in Qt4.8 : look at the QNetworkReply class, particularly the header() and rawHeader() functions. It should be what you are looking for.
A bit of explanation : QNetworkAccessManager is the class which allows you to send and receive requests. It is much more flexible and not limited to a single protocol, in contrast to QHttp/QFtp. Before, you had to decide on the application level which protocol to use, and now you only pass an URL to the QNetworkAccessManager, it will manage the rest.


text:
Q: SQL export of products and associated image gallery files I need to list all product entity_id, SKU and associated images from the value field of catalog_product_entity_media_gallery.
I need the output to be CSV based, so all images of each product will be listed in their relevant columns as shown below:
entity_id,sku,image1,image2,image3,image4
23321,prod1,/d/d/dsc_dasda.jpg,/d/d/dsc_d56.jpg,/d/d/dsc_d56.jpg,/d/d/dsc_542.jpg
32132,product2,/d/d/dsc_dsss.jpg,/d/d/dsc_d34s.jpg,/d/d/dsc_d432s.jpg,,

Not all products have the same number of associated images and I am not sure what the maximum is within the catalogue so the 4 images in the headers above is just an example.
Can anyone please help? I can't figure out the joins needed in the SQL but I imagine it is pretty simple if you know how.
I have tried the Magento export options and none can give the result I need.
Magento version 1.9.0.1

A: I figured it out:
SELECT  catalog_product_entity.sku,
        GROUP_CONCAT(CONCAT_WS(':', catalog_product_entity_media_gallery.value) SEPARATOR ',') AS Gallery,
        catalog_product_entity.entity_id
FROM    catalog_product_entity_media_gallery
        catalog_product_entity_media_gallery
INNER JOIN
        catalog_product_entity catalog_product_entity
ON     (catalog_product_entity_media_gallery.entity_id =
        catalog_product_entity.entity_id)
GROUP BY
        catalog_product_entity.sku


text:
Q: Parsing an array of json objects in GO I am trying to parse given API response into a struct.
It seems to be an array.
[
   {
      "host_name" : "hostname",
      "perf_data" : "",
      "plugin_output" : "All good",
      "state" : 0
   }
]

I cannot figure out how to create struct for it, I came up with:
type ServiceData struct {
    HostName     string `json:"host_name"`
    PerfData     string `json:"perf_data"`
    PluginOutput string `json:"plugin_output"`
    State        int    `json:"state"`
}

defer resp.Body.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
jsonStr := buf.String()
var servicedata ServiceData
json.Unmarshal([]byte(jsonStr), &servicedata)

But no luck.
Should I perhaps remove square brackets from the initial response?
Could somebody point me in the right direction?

A: You may unmarshal JSON arrays into Go slices. So unmarshal into a value of type []ServiceData or []*ServiceData:
var servicedata []*ServiceData

A working demo:
func main() {
    var result []*ServiceData
    if err := json.Unmarshal([]byte(src), &result); err != nil {
        panic(err)
    }
    fmt.Printf("%+v", result[0])
}

const src = `[
   {
      "host_name" : "hostname",
      "perf_data" : "",
      "plugin_output" : "All good",
      "state" : 0
   }
]`

Which outputs (try it on the Go Playground):
&{HostName:hostname PerfData: PluginOutput:All good State:0}

Also note that you may unmarshal "directly from the body", no need to read the body first.
Use json.Decoder to do that:
var servicedata []*ServiceData
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
    // handle error
}

It's much shorter, easier to read and it's more efficient.


text:
Q: I am looking for software/command to control IrDA Just like hcitool controls bluetooth, I am looking for command or software(I prefer to use console so I can make scripts) to control IrDA port. Is there any software/command that can do it? Thanks

A: IRDA is supported on ubuntu, but many individual hardware implementations are not. Install the the irda-utils package and issue the included findchip command to see if you are in luck..
sudo apt-get update ; sudo apt-get install irda-utils
sudo findchip -v

If you luck out, you might find the following link useful...
http://blogs.fsfe.org/stefan.a/2011/05/24/irda_infrared_data_transfer_on_ubuntu/

A: IrDA-utils is what you are looking for. See here for more info and usage: http://www.tldp.org/HOWTO/Infrared-HOWTO/infrared-howto-s-software.html#AEN132

A: the projects official webpage can be found here as already mentioned, IrDA is not supported by many hardwaretypes anymore, as it has been replaced mostrly by bluetooth.
But the project's webpage offers you a summary of all available driverpackages for ubuntu.

A: There is an IrDA project on sourceforge including How-to.

*

*http://irda.sourceforge.net/docs/index.html

*http://tuxmobil.org/howto_linux_infrared.html
Very much depends what you want to do with IrDA, so hope this project helps.


text:
Q: Kotlin: Load/initialize next activity in the background I have an initialization activity in my app which displays the logo, then I show my next activity using
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState) // Call the parent class function
    setContentView(R.layout.activity_launcher)

    // This starts a new co-routine
    // it is important to do it this way, in order to show the UI _before_
    // all the initialization happens, otherwise launcher is pointless
    GlobalScope.launch {
        ...
        [initialization]
        ...
        startActivity(ActivityTwo)
    }
}

The transition takes about three seconds because of all the code that is running inside onCreate belonging to ActivityTwo.  Is there a way to "create" the second activity behind the scenes, and then show it.  I don't mind if the app stays on the initialization screen for those 3 seconds, but the white transition looks really ugly.

A: onCreate method is actually creating your activity. You must be doing some heavy computation if your activity is janking while rendering. If you are not satisfied with the transition between the two activities, then apply an animation between them.


text:
Q: While plotting want two columns in Y axis In python I'm able to add 1 column in Y-axis
df = pd.read_csv('file.csv')
sb.lmplot(x="age", y="salary", data=df)
plt.show()

This is working fine.
Now I want to add 2 columns in Y-axis like salary and name. How to do this?
In X-axis- age.
In Y-axis- salary and name.

A: df = pd.read_csv('file.csv')
sb.lmplot(x="age", y=["salary", "name"], data=df)
plt.show()

I believe this should work, but I have done little in this area so not 100%, can't really test until I finish work.

A: Hi here is an example of how you can do this, if I have understood correctly
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.DataFrame.from_dict({'series1': [1, 2, [enter image description here][1]3, 4, 5],
                            'series2': [3, 4, 5, 6, 7],
                            'series3': [5, 6, 4, 3, 9]})

ax = df.plot(x="series1", y="series2", legend=False)
ax2 = ax.twinx()
df.plot(x="series1", y="series3", ax=ax2, legend=False, color="r")
ax.figure.legend()
plt.show()


text:
Q: HIVE Select columns names with regular expression? I want to know if it can be queried about the columns in the hive ith term rehiliare selection for the starting columns of some description?
example:
table with this list of names of columns
pattern1 pattern2 motif3 balab1 balabal2 ma1 ma2 ma3
select (an expression for that selection columns beginners with pattern)
from table
Thank you

A: I believe you are looking to select columns based on regular expression.
Well below works:
  set hive.support.quoted.identifiers=none;
  select `patt.*` from test_table;

Above code will return columns pattern1 pattern2 among your mentioned columns  "pattern1 pattern2 motif3 balab1 balabal2 ma1 ma2 ma3"
Please see https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Select#LanguageManualSelect-REGEXColumnSpecification for more information.

A: You have to use back quote character (above tilda in the keyboard not the single quote) after select and before from to run regular expression in the hive.


text:
Q: значение переменной из ссылки Как при клике по ссылке получить значение page?

            Пред.

            2

            3


text:
Q: Disproving $ L^2(X, U(\mathbb{C},n)) = U(L^2(X,\mathbb{C}^n))$. Here $X$ is some measurable space  and  $U(L^2(X,\mathbb{C}^n))$ denotes the Banach space of unitary automorphisms of the Hilbert space $L^2(X,\mathbb{C}^n)$.
Let $U(\mathbb{C},n)$ denote the unitary matrices $n\times n$, we can consider the space of $L^2$ functions  $\phi: X\to U(\mathbb{C},n)$, denoted as $L^2(X, U(\mathbb{C},n))$.
An element $\phi$ in the latter space defines an element in $U(L^2(X,\mathbb{C}^n))$ that sends $f\in L^2(X, \mathbb{C}^n)$ to $\phi\cdot f $ such that
$\phi \cdot f(x) = \phi(x) (f(x))$.
Since $\phi(x)$ is unitary, it preserves the norms hence $\phi\cdot f\in L^2(X,\mathbb{C}^n)$ (this is why I am taking the unitary group and not $GL$) and the operator norm is $1$.
Therefore we have an inclusion
$L^2(X, U(\mathbb{C},n))\to U(L^2(X,\mathbb{C}^n)) $

Is this map an isomorphism?
Can you provide an example of an element of $U(L^2(X,\mathbb{C}^n))$ which is not in the image of the above map?

I believe the answer to the first question is negative. The LHS is an Hilbert space while the RHS is a Banach (but I cannot disprove that it can't be given an Hilbert structure, e.g. is it reflexive? I don't know).
Also, I thought that $U(L^2(X,\mathbb{C}^n))$ is contractible (at least if $\dim L^2(X,\mathbb{C}^n) = \infty$)  by Kuipers' theorem, therefore another possible way of disproving it would be show that $L^2(X, U(\mathbb{C},n))$ has more connected components.

A: There are several problems here. First, you need a measure to define $L^2(X,U(n))$, not just a measurable space. Moreover, $L^2(X,U(n))$ is not a Hilbert space or even a vector space - neither sums nor scalar multiples of unitaries are unitary in general. In fact, if the underlying measure is infinite, then $L^2(X,U(n))=\emptyset$. For similar reasons, $U(L^2(X,\mathbb{C}^n))$ is not a vector space.
Even if the underlying measure is finie, the map from the question is almost never surjective. To see this, note that a bounded linear operator of the form
$$
Tf(x)=\psi(x)f(x)
$$
with $\psi(x)\in\mathbb{C}$ for a.e. $x$ commutes with all elements of the image of $L^2(X,U(n))$, but the only operators commuting with all elements of $U(L^2(X,\mathbb{C}^n))$ are scalar multiples of the identity. So the map cannot be surjective if $\dim L^2(X)\geq 2$.


text:
Q: Phusion Passenger error with Rails 4 and ruby 2.5 Ubuntu 16.04
Rails 4.2.10
Ruby 2.5.0
SERVER_SOFTWARE = Apache/2.4.18 (Ubuntu) Phusion_Passenger/5.2.2

I installed ruby using rbenv, and when I do
ruby -v

I get
ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-linux]

I installed Phusion Passenger as follows:
sudo apt-get install -y dirmngr gnupg
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 561F9B9CAC40B2F7
sudo apt-get install -y apt-transport-https ca-certificates
sudo sh -c 'echo deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main > /etc/apt/sources.list.d/passenger.list'
sudo apt-get update
sudo apt-get install -y libapache2-mod-passenger
sudo a2enmod passenger
sudo apache2ctl restart

When I do:
sudo /usr/bin/passenger-config validate-install

I get:
 * Checking whether this Passenger install is in PATH... ✓
 * Checking whether there are no other Passenger installations... ✓
 Everything looks good. :-)

However, when I try to start my application, I get an error message:
Web application could not be started
Web application could not be started by the Phusion Passenger application server.

From the /var/log/apache2/error.log, I get:
Error ID: d8f774a0
Error details saved to: /tmp/passenger-error-ShCphj.html
Message from application: cannot load such file -- bundler/setup (LoadError)
/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
/usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:456:in `activate_gem'
/usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:323:in `block in run_load_path_setup_code'
/usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:461:in `running_bundler'
/usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:322:in `run_load_path_setup_code'
/usr/share/passenger/helper-scripts/rack-preloader.rb:100:in `preload_app'
/usr/share/passenger/helper-scripts/rack-preloader.rb:156:in `<module:App>'
/usr/share/passenger/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'
/usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>'

================================
Answer:
The answer is to uninstall stand alone Phusion Passenger, and install it as a gem, as follows:
sudo apt-get remove -y passenger libapache2-mod-passenger

Then installing the gem
gem install passenger --no-rdoc --no-ri
passenger-install-apache2-module

Follow the install directions

A: Try this,
gem install bundler

and
bundle install


text:
Q: Can you run AJAX on simple click, rather than true "submit"? I have a simple upload image form...
 <form id="form" action="upload-image-ajax.php" method="post" enctype="multipart/form-data">
  <input id="uploadImage" type="file" accept="image/*" name="image" />
  <input id="button" type="submit" value="Upload">
 </form>

And some JS...
$(document).ready(function (e) {
 $("#form").on('submit',(function(e) {
  e.preventDefault();
  $.ajax({
         url: "upload-image-ajax.php",
   type: "POST",
   data:  new FormData(this),
   contentType: false,
         cache: false,
   processData:false,
   beforeSend : function()
   {
    //$("#preview").fadeOut();
    $("#err").fadeOut();
   },
   success: function(data) {
    if(data=='invalid file') {
     // invalid file format.
     $("#err").html("Invalid File !").fadeIn();
    } else {
     // view uploaded file.
     $("#preview").html(data).fadeIn();
     $("#form")[0].reset();
    }
      },
     error: function(e)
      {
    $("#err").html(e).fadeIn();
      }
    });
 }));
});

And the PHP (upload-image-ajax.php)  ...
<?php
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory

if(isset($_FILES['image']))
{
 $img = $_FILES['image']['name'];
 $tmp = $_FILES['image']['tmp_name'];

 // get uploaded file's extension
 $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));

 // can upload same image using rand function
 $final_image = $_SESSION['poolid']. "." .$ext;

 // check's valid format
 if(in_array($ext, $valid_extensions))  {
  $path = $path.strtolower($final_image);
    //checking if file exsists, so we can overwrite it
    if(file_exists("uploads/$final_image")) unlink("uploads/$final_image");
      if(move_uploaded_file($tmp,$path)) {
       echo "";
      }
 } else {
      echo 'invalid file';
 }
}

?>

The problem is that I'd like this image upload "form" to be included in a larger form.  But when you click "upload" it tries to submit the larger, overall form.  Is there a way to edit this to maybe just have a button HTML element (not a true submit button) and when that gets clicked, it performs the same AJAX call?
Or does AJAX need to occur as a result of a true form submission?
FYI, when you upload the image, it sends to server and shows a preview.  So I'd like it to be part of a larger form with other questions. This is just one "question" where they can upload an image and see the preview BEFORE clicking to submit the overall, larger form.

A: Make your button:
    <button id="button">Upload</button>
Then add a jquery event listener:
$("#button").click(function(){
    //Make ajax call here:
    $.ajax({
           url: upload-image-ajax.php,
           type: 'POST',
           contentType: '[Type of the content being returned]',
           data: [json object with data you're sending. i.e the photo file],
           success: function(){ callback function for when call completes}
     });
});

There are more options to do whatever you'd like. Look at http://api.jquery.com/jquery.ajax/ for more info.

A: To upload just image, change button type to button from submit and try like this:
$('#button').on('click', function() {
    var imageData = new FormData();
    imageData.append('name_of_picture_file', $('#uploadImage').prop('files')[0]);

    $.ajax({
      url: 'upload-image-ajax.php',
      type: 'POST',
      processData: false, // important
      contentType: false, // important
      dataType : 'json',
      data: imageData
    });
});

And your html should look like
<form id="largerForm" action="upload-larger-form.php" method="post">
  <input id="uploadImage" type="file" accept="image/*" name="image" />
  <input id="button" type="button" value="Upload">
</form>

A: As I understand your question as I can reach, you have two main requirements.

*

*You want to upload the files from your page with ajax.

*You want to show preview to them

For the first requirement, you can use following script.

    <input type="file" id="file-select" multiple webkitdirectory/>

        <button id="btn-upload" >    Upload</button>

The above file upload function will work when you click upload button, not of form submit.
For the second requirement, refer to this question
Preview an image before it is uploaded
Goodluck.


text:
Q: Display flex doesn't work I'm trying to set a section with display: flex using CSS, but it seems I can't do it. I tried so many different combos with CSS and the result is just changing the size of my section, but the element goes outside when the section reach the max-height that I set up.
Here is my HTML code where I want to display the element in flex mode:

HipHop

        <% if (req.user) { %>
            <input type="button" value="Show Hide DIV" v-on:click="ShowHide" />
        <%}%>

            YouTube url
            <input type="text" id="youtube" v-model="text" placeholder="Paste your YouTube video link">

            <button  v-on:click="loadVideo">Add Video</button>

 {{item.count}}

            <% if (req.user) { %>

                <input type="button" id="buttonVoti" v-on:click="addVoto(item._id)">

            <%}%>

CSS:
.flex-container{
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display:flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: flex-start;
    align-content: flex-start;
}
    #BattlesH{
    /*width:700px;*/
    height: auto;
    max-height: 600px;
    margin:5px;
    padding: 10px;
    /*float:right;*/
    border-radius: 10px;
    border:2px solid black;
    background:#ccffcc;
    position: relative;
    text-align: center;
    color: black;
}

In some places there are comments; I used them to see if changing them can get some results, but nothing helped.

A: You can use this and add a scroll
.flex-container {
    overflow:auto;
}

or remove the height and the container grow together.


text:
Q: Select max value record from one-to-many join I want to join two tables, but the second table contains multiple rows of parameters on which I wish to build by join.
TABLE1
+------------+-----------+
|   Ddate    |    ROOMNO |
+------------+-----------+
| 2018-22-11 |       101 |
| 2018-22-11 |       102 |
| 2018-22-11 |       103 |
| 2018-22-11 |       104 |
+------------+-----------+

TABLE2 (Multiple rows per Room No)
+------------+-----------+------------------+
|   Ddate    |    ROOMNO |  MaxVoltage      |
+------------+-----------+------------------+
| 2018-22-11 |       101 |   230            |
| 2018-22-11 |       101 |   240            |
| 2018-22-11 |       101 |   250   -----MAX |
| 2018-22-11 |       102 |   230            |
| 2018-22-11 |       102 |   255   -----MAX |
+------------+-----------+------------------+

DESIRED RESULT (I want the Max Voltage for the Room on the Ddate)
+------------+-----------+------------+
|   Ddate    |    ROOMNO | MaxVoltage |
+------------+-----------+------------+
| 2018-22-11 |       101 |        250 |
| 2018-22-11 |       102 |        255 |
| 2018-22-11 |       103 |        235 |
| 2018-22-11 |       104 |        238 |
| 2018-22-11 |       105 |        255 |
+------------+-----------+------------+

A: SELECT t2.d, t2.roomno, max(t2.maxvolt)
FROM table1 AS t1 JOIN table2 AS t2 ON t1.ddate = t2.ddate
AND t1.roomno = t2.roomno
GROUP BY t2.d, t2.roomno;

A: use subquery
    select t1.dDate,t1.roomno,mvoltage from table1 t1 join
    (select Ddate ,roomno,max(MaxVoltage ) as mvoltage from table2
    group by Ddate,roomno
    ) t2 on t1.Ddate=t2.Ddate

A: First you will join between two tables in a regular way, using the date and room no.
then use the aggregate function max for the voltage field with over clause , then  group by Room No and Date like following
select distinct t1.Ddate, t1.RoomNo, MAX(t2.MaxVoltage) over(partition by t1.RoomNo order by t1.Ddate) MaxVoltage
from Table1 t1
join Table2 t2 on t2.Ddate = t1.Ddate and t2.RoomNo = t1.RoomNo

A: Use apply:
select t1.*, t2.maxvoltage
from table1 t1 outer apply
     (select top (1) t2.*
      from table2 t2
      where t2.roomno = t1.roomno and t2.ddate = t1.ddate
      order by maxvoltage desc
     ) t2;

A: select t1.dDate,t1.roomno, mvoltage from table1 t1 join
    (select Ddate ,roomno,max(MaxVoltage ) as mvoltage from table2
    group by Ddate,roomno
    ) t2 on t1.Ddate=t2.Ddate and t1.Roomno = t2.RoomNo


text:
Q: A question about calculus $\displaystyle\int_{ \mathbf Q} s^a \, dm $
I don't know how to start at all. Can anyone give me some hint how to calculate integral in this type?

A: HINT: You may try partitioning the integration domain as
$$
\Bbb Z_p\times\Bbb Z_p=\bigcup_{i\in{\cal I}}A_i
$$
where the function you are integrating is constant on the open-closed subdomains $A_i$. For instance, since $||xy(x+y)||=||x||\cdot||y||\cdot||x+y||$ you may take each $A_i$ inside some
$$
(p^r\Bbb Z_p\setminus p^{r+1}\Bbb Z_p)\times(p^s\Bbb Z_p\setminus p^{s+1}\Bbb Z_p)
=p^rU_p\times p^sU_p
$$
where $U_p$ is the multiplicative group of units.
With this, the problem essentially boils down to computing the measure of each $A_i$.


text:
Q: VBA: Passing values from array to range This should be fairly straightforward. But for some reason I'm getting blank cells instead of the values from the array being passed into the cells.
redim rFin (2,1)
rfin (1,1) = "Bla1"
rfin (2,1) = "Bla2"

oSht1 = activesheet
lRow = 10

With oSht1
    .Range(.Cells(lRow1 + 1, 6), .Cells(lRow1 + 2, 6)) = rFin
End With

EDIT: Also tried with rFin having values from 0 to 1 instead of 1 to 2.

A: This works for me:
Option Base 1

Sub Main()
    ReDim rfin(2, 1)
    rfin(1, 1) = "Bla1"
    rfin(2, 1) = "Bla2"

    Set oSht1 = ActiveSheet
    lRow = 10

    With oSht1
        .Range(.Cells(lRow + 1, 6), .Cells(lRow + 2, 6)) = rfin
    End With
End Sub

The important thing is the Option Base 1 because without it arrays start at 0.  Or this would work:
'default of Option Base 0

Sub Main()
    ReDim rfin(2, 1)
    rfin(0, 0) = "Bla1"
    rfin(1, 0) = "Bla2"

    Set oSht1 = ActiveSheet
    lRow = 10

    With oSht1
        .Range(.Cells(lRow + 1, 6), .Cells(lRow + 2, 6)) = rfin
    End With
End Sub

A: I found a workaround: using an empty range to make the variant match the range's format, which allows me to use a single variant of this format (thus not having to change the variants and loops I had already set up).
oSht1 = activesheet
lRow = 10

With oSht1
    rFin = .Range(.Cells(lRow1 + 1, 6), .Cells(lRow1 + 2, 6))
End With

    rfin(1, 1) = "Bla1"
    rfin(2, 1) = "Bla2"

With oSht1
    .Range(.Cells(lRow1 + 1, 6), .Cells(lRow1 + 2, 6)) = rFin
End With

Not an elegant solution, but it does work. Just use an empty range.

A: oSht1.Cells(lRow1 + 1, 6).Resize(2) = [{"Bla1";"Bla2"}]

or even shorter
[F11:F12] = [{"Bla1";"Bla2"}]


text:
Q: Can't connect to database xampp in laravel 5.6 I have used laravel before when it was 5.4 and I could easily connect to database, Now I want to work in a new project. try to connect to database and get this error.
  Illuminate\Database\QueryException  : SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = todo and table_name = migrations)

I have tried every single trick I have found on stackoverflow. NONE worked.
Why is this happening? this is my connection.
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=todo
DB_USERNAME=root
DB_PASSWORD=''

A: Try defining the DB_HOST with the actual ip address instead like
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=todo
DB_USERNAME=root
DB_PASSWORD=''

A: Are you running it on VM? If that case then try to point the DB_HOST to the right IP address of your Xampp SQL and then do php artisan config:cache & config:clear


text:
Q: Creating a line graph from array of data objects I'm trying to learn D3 and am having problems creating a simple line graph from an array of data objects.
I have an array of data objects that look like this...
[
    {date: "03/04/15", rain: "1.2"},
    {date: "03/05/15", rain: "2.3"},
    {date: "03/06/15", rain: "0.0"},
    {date: "03/07/15", rain: "4.2"},
    {date: "03/08/15", rain: "0.3"},
    {date: "03/09/15", rain: "0.0"}
]

I've tried following a simple tutorial that creates a line graph, but when I plug in the data, neither the x axes or line will display. Does this have to do with date formatting?
I have an example up on JS Bin.
I really don't understand what the problem is, please help!

A: The X axis should be d3.time.scale and since your date property are strings you will have to convert it to proper Date objects by doing new Date();

A: @Satyajit's is right. Here is an example:

 var lineData =  [
      {date: "03/04/15", rain: "1.2"},
      {date: "03/05/15", rain: "2.3"},
      {date: "03/06/15", rain: "0.0"},
      {date: "03/07/15", rain: "4.2"},
      {date: "03/08/15", rain: "0.3"},
      {date: "03/09/15", rain: "0.0"}
     ].map(function(d) {
                      return {
                        date: new Date(Date.parse(d.date)),
                        rain: d.rain
                      };
                    });

  var vis = d3.select("#visualisation"),
    WIDTH = 600,
    HEIGHT = 250,
    MARGINS = {
      top: 20,
      right: 20,
      bottom: 20,
      left: 50
    },
    xRange = d3.time.scale()
   .range([MARGINS.left, WIDTH - MARGINS.right])
  .domain([d3.min(lineData, function (d) {
        return d.date;
      }),
      d3.max(lineData, function (d) {
        return d.date;
      })
    ]),

    yRange = d3.scale.linear()
  .range([HEIGHT - MARGINS.top, MARGINS.bottom])
  .domain([d3.min(lineData, function (d) {
        return d.rain;
      }),
      d3.max(lineData, function (d) {
        return d.rain;
      })
    ]),

    xAxis = d3.svg.axis()
      .scale(xRange)
      .tickSize(3),

    yAxis = d3.svg.axis()
      .scale(yRange)
      .tickSize(3)
      .orient("left");

  vis.append("svg:g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
    .call(xAxis);

  vis.append("svg:g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + (MARGINS.left) + ",0)")
    .call(yAxis);

  var lineFunc = d3.svg.line()
  .x(function (d) {
    return xRange(d.date);
  })
  .y(function (d) {
    return yRange(d.rain);
  })
  .interpolate('linear');

vis.append("svg:path")
  .attr("d", lineFunc(lineData))
  .attr("stroke", "blue")
  .attr("stroke-width", 2)
  .attr("fill", "none");
<script src="http://d3js.org/d3.v3.min.js"></script>
<svg id="visualisation" width="600" height="400"></svg>


text:
Q: Looking for a script to save protections on sheets when copied I am creating workbooks for teachers to monitor students progress on a specific skill. We have a workbook with various templates they may need to copy the sheets/graphs they need for each child. These sheets are protected without the exception of the cells the teachers need to access in order to input student data. Right now when we use the COPY TO a new spreadsheet, we lose those protections. (Most of our K-2 teachers are not tech-savvy enough to have full access to a sheet with a graph.) There has to be a way to create some type of protection that carries over to copied files that is foolproof.  Thanks to anyone who knows how to do this.
I tried using this code and it does copy my sheet and keep it protected, BUT how can I get it to stay protected when the COPY TO is used to another existing workbook?
function duplicateProtectedSheet() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  sheet = ss.getSheetByName("B - General Info");
  sheet2 = sheet.copyTo(ss).setName("My Copy1");
  var p = sheet.getProtections(SpreadsheetApp.ProtectionType.SHEET)[0];
  var p2 = sheet2.protect();
  p2.setDescription(p.getDescription());
  p2.setWarningOnly(p.isWarningOnly());
  if (!p.isWarningOnly()) {
    p2.removeEditors(p2.getEditors());
    p2.addEditors(p.getEditors());
    // p2.setDomainEdit(p.canDomainEdit()); //  only if using an Apps domain
  }
  var ranges = p.getUnprotectedRanges();
  var newRanges = [];
  for (var i = 0; i < ranges.length; i++) {
    newRanges.push(sheet2.getRange(ranges[i].getA1Notation()));
  }
  p2.setUnprotectedRanges(newRanges);
}

Here is an example of my current workbook with the templates teachers will be copied to their own workbooks.
https://docs.google.com/spreadsheets/d/1JB95bdu4Qatx7uMZrQFP7GkiKBuuB47PCV8ZjyQWmHo/edit?usp=sharing

A: try this:
function test(){
  var ss = SpreadsheetApp.getActiveSheet();
  var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  var newSheet = ss.copyTo(SpreadsheetApp.getActive());
  var prot;
  var p;
  var editors;

  for (var i = 0; i < protections.length; i++){
    prot  = protections[i];
    p = newSheet.getRange(prot.getRange().getA1Notation()).protect();
    p.setDescription(prot.getDescription());
    editors = prot.getEditors();
    for (var j = 0; j < editors.length; j++){
      p.addEditor(editors[i]);
    }
  }
}

This code copies the sheet and stores the original's protections, then it set the same protections in the newly-created sheet. for you it would be a matter of setting ss and newSheet to the ones you intend to use.


text:
Q: Installing github version of package with Anaconda I have Sympy installed with Anaconda, my version (of Sympy) is 0.7.6 .
I want to be able to use the git version of Sympy. Do you know how can I tell to Anaconda to substitute the 2 versions ?
I've tried using the git clone command, but the Sympy folder from git and Anaconda doesn't look the same at all, so I can't replace one with another.
git clone git://github.com/sympy/sympy.git

Is there a command like : "conda update-git sympy" ?

I found that answer, but I didn't understand how to do it.
Possible to do "conda build" from github branch?
UPDATE: I've used the following command and it worked
python setup.py develop

in my sympy directory.
Thanks to @asmeurer

A: my previous answer was based on long time ago experiance
this is the correct proccess (that worked for me based on the latest anaconda on a windows machine)
I have updated the meta.yaml only with the following changes:
changing to get the source from git
including mpmath in build run and test
removing some libraries of sympy that seemed to have been removed from the latest version
i have all the files in the following gist
https://gist.github.com/srgrn/622cf61b03b7321503cc
hope it helps

A: you can try the following:

*

*download the conda recipes (https://github.com/conda/conda-recipes)

*update the meta.yaml for getting the source from github as explained in the stack overflow question you linked to.

*run conda build.


text:
Q: SQL Equivalent to pandas.merge_asof Is there an SQL equivalent of pandas.merge_asof where I can join two tables on a datetime and by a given field as well as specify a direction and a tolerance?
I'm trying to replicate something similar to the following:
df = pd.merge_asof(df1, df2, on='time', left_by='index_A', right_by='index_B', tolerance=pd.Timedelta('15 minutes'), direction='nearest')

A: I have already solved that with PySpark but you can use the same trick in SQL. You can see the code below to imitate the Pandas merge_asof.
-- Compute the absolute difference between two timestamp
CREATE TEMPORARY MACRO ABS_DIFF(t1 TIMESTAMP, t2 TIMESTAMP)
ABS(UNIX_TIMESTAMP(t1) - UNIX_TIMESTAMP(t2));

-- Create two examples of table
WITH df1 AS (
    SELECT 1 AS index_A, CAST('2018-01-01 00:00:00' AS TIMESTAMP) AS `time`
    UNION
    SELECT 2 AS index_A, CAST('2018-01-05 00:00:00' AS TIMESTAMP) AS `time`
),
df2 AS (
    SELECT 1 AS index_B, CAST('2018-01-01 00:11:00' AS TIMESTAMP) AS `time`
    UNION
    SELECT 1 AS index_B, CAST('2018-01-01 00:14:00' AS TIMESTAMP) AS `time`
    UNION
    SELECT 2 AS index_B, CAST('2018-01-05 00:20:00' AS TIMESTAMP) AS `time`
)
SELECT `index`, time1, time2
FROM
    (SELECT
        df1.index_A AS `index`, df1.`time` AS time1, df2.`time` AS time2,
        -- Order the duplicates on index by time ascending
        ROW_NUMBER() OVER(PARTITION BY df1.index_A ORDER BY ABS_DIFF(df1.`time`, df2.`time`) ASC) AS nth_row
    FROM df1, df2
    WHERE
        -- Equal join on index
        df1.index_A = df2.index_B
        -- Join on absolute difference lowest than 15 minutes
        AND ABS_DIFF(df1.`time`, df2.`time`) / 60 <= 15) AS df3
-- Select the rows with the nearest times
WHERE nth_row = 1

So, as you can see you must follow these steps:

*

*Join the tables on index and time if the absolute difference is lowest than 15 minutes.

*Apply the window function ROW_NUMBER to eliminate the duplicated rows.

To do that you need to use a subquery because you aren't allow to use a window function in the WHERE clause.
I have only tested this code on Hive 3.1.3000.7.1.7.88-2.


text:
Q: reprojecting and resampling rasters This python script for qgis should reproject all the raster files in a folder and resample it to 10 m. Raster file type should be Float32. The script doesn't produce any result.
import os
import processing
from qgis.core import *

inputDir = "R:\\LAI_Biom_Maps\\kriging_Gladys\\in"

outputDir = "R:\\LAI_Biom_Maps\\kriging_Gladys\\out"

for i in os.listdir(inputDir):

    layercount = os.path.join(inputDir, i)
    raster_layer = QgsRasterLayer(layercount, "raster")

    fileOut = outputDir + "\\" + i

    processing.runalg("gdalogr:warpreproject", \
    raster_layer, \
    "EPSG:4326", \
    "EPSG:27700", \
    10, \
    0, \
    None, \
    5, \
    fileOut)

A: This works
import os
import processing
from qgis.core import *

raster_filepath = "R:\\LAI_Biom_Maps\\kriging_Gladys\\in"

outputDir = "R:\\LAI_Biom_Maps\\kriging_Gladys\\out"

for i in os.listdir(raster_filepath):

    layercount = os.path.join(raster_filepath, i)
    raster_layer = QgsRasterLayer(layercount, 'raster')

    fileOut = outputDir + "\\" + i

    processing.runalg("gdalogr:warpreproject", \
    raster_layer, \
    "EPSG:4326", \
    "EPSG:27700", \
    "0", \
    10, \
    0, \
    None, \
    None, \
    5, \
    0, \
    75, \
    6, \
    1, \
    False, \
    0, \
    False, \
    "", \
    fileOut)


text:
Q: Pseudo :before Dynamic Background-image Forgive me if this has been asked elsewhere. I don't know enough about what I don't know to yield effective search results.
The idea is that, based on user input, a div is assigned the .flipped class and it's background-image is rotated 180 deg. The div itself cannot be rotated. Is it possible to have the background-image in the pseudo element dynamically set based on the actual elements current background-image?
I have the actual image rotation set just fine:
.flipped:before {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    z-index: -1;
    background-image: url('../../images/cards/back.png');
    background-size: contain;
    transform: rotate(180deg);
}

Works great if I manually set the background-image as shown above but this does not work for my application.
Thank you in advance.


text:
Q: Is $S_{10}$ generated by the group of $6$ cycles?
Is $S_{10}$ generated by the subgroup of $6$ cycles?

I'll denote that subgroup by $H$.
We know that by conjugation permutations remains with the same cycle structure, and therefore $H$ is closed to conjugation. It is easy to see from here that $H$ is normal subgroup.
The only normal subgroup of $S_{10}$ is  $A_{10}$, therefore $H$ must be either  $S_{10}$ or $A_{10}$.
How can i determine which one from here?
Are the specific numbers $10,6$ even relevant?

A: Each $6$-cycle has sign equal to $-1$. Therefore, $H\not\subset A_{10}$.


text:
Q: Describe a partition of $\mathbb{N}$ that divides $\mathbb{N}$ into $\aleph_0$ countably infinite subsets. Does anyone have any hints on how to describe the following partition?

Describe a partition of $\mathbb{N}$ that divides $\mathbb{N}$ into $\aleph_0$ countably infinite subsets.

A: Hint:
How many numbers are coprime to $2$?  How many numbers have exactly one factor of $2$?  How many numbers have exactly two factors of $2$?  $\dots$


text:
Q: How to print elements of array that start with a particular number? I have a Numpy array
a= [[[ 6, -1, -1]],

       [[ 8, -1,  3]],

       [[10,  1,  1]],

       [[10, -1, -1]],

       [[10,  1, -1]]]

I wish to retain only those rows that start with 10; so I wish my output array to be
a_out= [[[10,  1,  1]],

           [[10, -1, -1]],

           [[10,  1, -1]]]

I'm trying to iterate over the first element of the array to do so but if I try a[0,0:] or a[0:,0] I get the entire row or column.

A: Use a boolean mask:
>>> arr
array([[[ 6, -1, -1]],

       [[ 8, -1,  3]],

       [[10,  1,  1]],

       [[10, -1, -1]],

       [[10,  1, -1]]])
>>> mask = arr[:,:,0] == 10
>>> arr[mask]
array([[[10,  1,  1]],

       [[10, -1, -1]],

       [[10,  1, -1]]])

A: Make sure your a is a numpy array instead of a Python list. Then you can use this:
a[a[:,:,0] == 10]

where the inner one is a bool list to select rows.

A: If it is a list and not an array you can do:
filter(lambda x: x[0][0] == 10, a)


text:
Q: How extract text from epub in Python (from an url source) I want to extract the content from an epub, but I don't know how to do that from an url source. My code is like this for now: (ebooklib)
import urllib.request
import ebooklib
from ebooklib import epub

myurl = "https://diegooli.s3.us-east-2.amazonaws.com/Cabana.epub"

with urllib.request.urlopen(myurl) as url:
    s = url.read()

book = epub.read_epub(s)

for image in book.get_items_of_type(ebooklib.ITEM_IMAGE):
    print(image)

error, obviously:
    AttributeError: 'bytes' object has no attribute 'seek'

Can anyone give me a light?

A: Save the epub file first then open the file using the ebook library

*

*Use urllib to download the ebook

*Use ebooklib to open the ebook and get the images

Here's the code:
import urllib.request
import ebooklib
from ebooklib import epub

myurl = "https://diegooli.s3.us-east-2.amazonaws.com/Cabana.epub"

with urllib.request.urlopen(myurl) as url:
    s = url.read()

with open(r"c:\tmp\test.epub", "wb") as f:
    f.write(s)

book = epub.read_epub(r"c:\tmp\test.epub")

for image in book.get_items_of_type(ebooklib.ITEM_IMAGE):
    print(image)


text:
Q: Issue with tomcat I changed date of Linux machine to Sat Jul 13 00:26:56 IST 2019 using date command. Post that I am receiving below error in Tomcat Catalina
java.security.KeyStoreException: Uninitialized keystore


text:
Q: How do I connect two solar panels in series? I've got two solar panels which each provide 9V. I need them to provide 18V, and according to different sources (such as this forum thread) that should simply be a matter of connecting them in series.
So I did. I connected the negative on panel A with positive on panel B, and positive on panel A with negative on panel B. As far as I understand, this is how you connect solar panels in series.
However, I came across a surprising observation. Each of the panels produce about 10V - 11V each on a good sunny day. I've checked (and double checked) readings on my multimeter. However, when I connect them in series the voltage drops to 4V - 5V. I get this reading on both solar panels by connecting my multimeter to the connectors on any two of the solar panels. As you've probably figured out, I don't understand why this happens.
Now, the panels have 4 soldering connectors each (see below picture). The first two are positive and negative (which according to my multimeter outputs nothing) and the two second ones have some chinese letters next to them which I've got no idea what means. However, these connectors (the ones with chinese symbols next to them) are the ones giving 10V - 11V. These are also the ones I've used to create a connection from panel A to panel B.
Since I could not figure this thing out, I called a friend. I was advised to put Schottky diodes in between them in case the panels somehow was discharging through each other. So I did. However, still only 4V - 5V when i put them in series.

Right now, I'm at loss what to do. How do I connect these panels in series to get 18V from them?
To summarize:

*

*Each panel outputs 10V - 11V

*Connecting my multimeter to the bottom and top right hand (or left hand) connectors indicates resistance, so these can't be the same connectors as that should give zero resistance as far as I've been told.

*The connected solar panels give 4V - 5V regardless of whether I've got the Schottky diodes in the middle or not.

What am I doing wrong?

A:
I connected the negative on panel A with positive on panel B

This is a good start

and positive on panel A with negative on panel B

But what is with this?

This is how it should be done.
And what is with the diodes? You should only use a diode when having a dual supply (panel and other supply) and you want to prevent current from the supply going into the solar panel.

A: If I've understood correctly, you connected positive to negative and positive to negative. In other words, you've connected both wires on one panel to both wires on the other. This is almost what you want. You want to make one connection between the two panels, positive-to-negative but leave the other two wires free. You connect your load to the two open wires.
You've basically shorted out the two panels. The only reason nothing burned up is that the panels cannot generate much current.

A: You are shorting your panels.  And panels do not "discharge" panels.  They could possibly discharge a battery if there is no light, and yes the Schottky would help that instance.
The diodes are only really a good idea if you expect power to return to the panels, e.g. from charging a battery.
This is what you want:
Neg 18V - panel +- panel + Pos 18V
If you are using these directly connected to a battery then the Diode is a good idea:
Neg 18V - panel +- panel +__[>|]__ Pos 18V

I also see your panels have the wiring mixed in colouring, so do not assume polarity based on the wire colour...

A: Certainly, 18 V are required to run some toys, torches, etc.
On the plates, connect:

*

*the left hand brown (+ve) to the right hand brown (-ve);

*the outer left hand blue (+ve) to the toy's +ve input and;

*the right hand blue (-ve) to the toy's -ve input.

Now the toy will get the required voltage and runs at 18 V,
Replace the toy with an AVO to test V=18 V.
There is a colour notation error by the manufacturer. Brown should always be used at positive terminal.


text:
Q: Fixing a Cross App Scripting Vulnerability Cтолкнулся с этой проблемой. В приложение используется Webview, у которого стоят интент-фильтры для открытия приложения по ссылке. Соответственно первое решение поставить exported = false не представляется возможным, как быть?
в onCreate
        webViewSettings.displayZoomControls = true
        webViewSettings.javaScriptEnabled = true
        webViewSettings.domStorageEnabled = true
        webViewSettings.databaseEnabled = true
        webView.addJavascriptInterface(jsInterface,"JSInterfaceDev")

в Manifeste
            android:name=".webView.WebViewActivity"
            android:exported="true"
            android:launchMode="singleTask"
            android:screenOrientation="portrait">

            <intent-filter >
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE" />

                <data
                    android:scheme="http"
                    android:host="${hostName}" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data
                    android:scheme="https"
                    android:host="${hostName}" />
            </intent-filter>

Fixing a Cross App Scripting Vulnerability.
What's happening.
  One or more of your apps contain a WebView Cross-App Scripting issue which can allow malicious apps to steal user cookies and other data. Please refer to the notice on your Play Console. After the deadlines shown in your Play Console, any apps that contain unfixed security vulnerabilities may be removed from Google Play.
**Action required **.
  1. Sign in to your Play Console, and navigate to the Alerts section to see which apps are affected and the deadlines to resolve these issues.
  2. Update your affected apps and fix the vulnerability.
  3. Submit the updated versions of your affected apps.
  Upon resubmission, your app will be reviewed again. This process can take several hours. If the app passes review and is published successfully, then no further action is required. If the app fails review, then the new app version will not be published and you will receive an email notification.
Additional details.
  WebViews that enable JavaScript and load data read from untrusted Intents can be tricked by malicious apps into executing JavaScript code in an unsafe context. We recommend that you prevent this vulnerability in one of the following ways:
Option 1: Ensure that affected activities are not exported.
Find any Activities with affected WebViews. If these Activities do not need to take Intents from other apps you can set android:exported=false for the Activities in your Manifest. This ensures that malicious apps cannot send harmful inputs to any WebViews in these Activities.
Option 2: Protect WebViews in exported activities.
If you want to set an Activity with an affected WebView as exported then we recommend that you make the following changes:

*

*Update your targetSdkVersion.
  Ensure that your targetSdkVersion meets Google Play's target API level requirement. Apps with a targetSdkVersion of 16 or lower evaluate JavaScript URLs passed to loadUrl in the currently loaded page context. Targeting SDK version 16 or lower and calling loadUrl using unsanitized input from untrusted Intents lets attackers execute harmful scripts in the affected WebView.

*Protect calls to evaluateJavascript.
  Ensure that parameters to evaluateJavascript are always trusted. Calling evaluateJavascript using unsanitized input from untrusted Intents lets attackers execute harmful scripts in the affected WebView.

*Prevent unsafe file loads.
  Ensure that affected WebViews cannot load the cookie database. WebViews that load unsanitized file:// URLs from untrusted Intents can be attacked by malicious apps in the following way. A malicious web page can write  tags into the cookies database and then a malicious app can send an Intent with a file:// URL pointing to your WebView cookies database. The malicious script will execute if the cookies database is loaded in a WebView and can steal session information.
  You can ensure that affected WebViews cannot load the WebView cookies database in two ways. You can either disable all file access or you can verify that any loaded file:// URLs point to safe files. Note that an attacker can use a symbolic link to trick checks on the URL path. To prevent such an attack, be sure to check the canonical path of any untrusted file:// URL before loading instead of just checking the URL path.


text:
Q: Reference elements in matrices in Julia while assigning values in other matrices I have a vector X whose elements are zeros and ones. I want to create another vector Z of the same size as X where each element of Z is 0 if the corresponding element in X is zero, otherwise it is a random draw from a. uniform distribution. In Matlab I can easily do this by:
n = 1000;
X = randi([0, 1], [1, n]);
Z(X) = rand(); #Here wherever X takes a value of 1, the element of Z is a draw from a uniform distribution.

I want to implement this in Julia. Is there a cleaner way of doing this instead of using if conditionals. Thanks!!

A: Here's one way to do it:

julia> n = 1000;

julia> x = rand(Bool, n);

julia> z = zeros(n);

julia> using Distributions

julia> z[x] .= rand.(Uniform(-10, 10));

julia> z
100-element Vector{Float64}:
 -2.6946644136672004
  0.0
  0.0
  ⋮

You can adjust the parameters of the Uniform distribution to what you need, or leave that argument out if the default [0, 1) range is what you need.
The line z[x] .= rand.(Uniform(-10, 10)) uses Julia's logical indexing (same as MATLAB) and broadcasting features - for every x value that is true, the rand call is made and the result assigned to that element of z.
The advantage of using the broadcast (compared to creating rand(Uniform(-10, 10), count(x)) and assigning that to z[x] for eg.) is that the values are directly assigned in-place to their destination in z, and so there's no extra unnecessary memory allocated (as mentioned by @DNF in the comments).

A: First of all, your Matlab code doesn't work in Matlab, for two reasons: Firstly because logical indices must be boolean, they cannot be 0 and 1. And secondly, because Z(X) = rand() will draw only a single random number and assign it to all the corresponding elements of Z.
Instead, you may want something like this Matlab code:
X = rand(1, n) > 0.5
Z(X) = rand(sum(X), 1)

In Julia you could do
X = rand(Bool, n)
Z = float.(X) # you have to initialize Z
Z[X] .= rand.()

Edit: Here's an alternative with a comprehension, where you don't need to initialize Z:
X = rand(Bool, n)
Z = [x ? float(x) : rand() for x in X]

A: Technically, what you are sampling from here is a left-censored uniform distribution -- equivalent to the mixture of a Dirac distibution at 0 and Uniform(0, 1).  The next release of Distributions.jl will have an implementation for censored, which will remove the need to do any fancy assignment at all:
Z = rand(censored(Uniform(-1.0, 1.0), lower=0.0), N)

where the extent to the left is chosen so that the mixture components have equal weight.


text:
Q: Why does pager not opening with less command? I am running this python script to execute a command and connect it's input and output to a client on the port.
import getpass
import socket
import subprocess
username = getpass.getuser()
host = socket.gethostbyname('')
port = 443
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection = None
while connection is None:
    try:
        connection = s.connect((host, port))
        s.send("[+] We are connected to %s" % username)
        while True:
            try:
                exec_code = s.recv(1024)
                if exec_code == "quit":
                    break
                else:
                    print "1"
                    proc = subprocess.Popen("less data.txt", shell=True, stdout=s, stdin=s)
                    proc.wait()

                    print "2"
            except Exception, err:
                print err
    except Exception, e:
        print e
s.close()

The problem I am facing is that less command prints output on the client side but does not opens a pager.
Any ideas on how to resolve this thing.

A: The problem is the program less does not use stdin and stdout as plain streams. The less is a terminal program and uses terminfo or termcap to control the terminal get terminal capabilities. When the python program executes the less then its stdout and stdin are not bound to any terminal but to a socket. The less has no chance to get terminal size for example so it cannot execute paging. It similar to situation when you call these trivial commands:
less data.txt
less data.txt | cat

The former command does paging. The later command just prints the file to stdout because the stdout of the less is not a terminal but a pipe and less cannot do paging.
When the paging is required on the server side then the server should implement paging.


text:
Q: Apache Http Client 5.1.3 takes too long to execute a http request I'm building an online payment platform API backend using spring boot. In the pay process, the backend will send a https request to a pay service like stripe (not stripe exactly in my case). I'm using Apache Http Client 5.1.3 to make the https request.
In my pom.xml, the dependency is as follows:
        <dependency>
            <groupId>org.apache.httpcomponents.client5</groupId>
            <artifactId>httpclient5</artifactId>
            <version>5.1.3</version>
        </dependency>

The helper method that makes the https request is as follows:
    @Override
    public String makeHttpsRequest(String requestXMLString) throws IOException, ParseException {
        // request
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost postRequest = new HttpPost(PAY_GATEWAY_URL);
        StringEntity requestStringEntity = new StringEntity(requestXMLString, StandardCharsets.UTF_8);
        postRequest.setEntity(requestStringEntity);

        // response
        CloseableHttpResponse postResponse = httpClient.execute(postRequest);
        HttpEntity responseEntity = postResponse.getEntity();
        String responseXMLString = EntityUtils.toString(responseEntity);

        // close resources
        postResponse.close();
        httpClient.close();

        return responseXMLString;
    }

Sometimes the line CloseableHttpClient httpClient = HttpClients.createDefault(); takes about 2 seconds to finish, and the line CloseableHttpResponse postResponse = httpClient.execute(postRequest); always takes about 3 seconds to finish, which in total gives the user really bad pay experience.
I'm wondering if there's any way that I can customize the http request to make it faster. By contrast, we had another system that was built on .NET and makes the same https request to the same service, the system always takes about 1 second to process the payment. These two systems run under the same network settings.
Please help, thanks.

A: You can define following
CloseableHttpClient httpClient = HttpClients.createDefault();

at instance level and don't need to close it after each and every call. Apache Commons Http Clients are thread safe and will support multiple requests. This way you can reduce a lot of latency. Apart from that you can not do much in terms of performance improvement.


text:
Q: C# Color Blend and calculating opacity / alpha like Photoshop I have an image I'm trying to process into a very specific look. I found a tutorial in Photoshop and have been slowly, step by step, recreating the Photoshop effects. The latest one is a color blend mode which I was able to get working, but they add an alpha to it and it's got me stumped.
Photoshop does this by creating a filter, setting the color, selecting "Blend" and then applying the alpha. The alpha applies to the filter and not the base image.
What I'm doing is taking two colors, the base image and the overlay color to blend, and converting them to HSL. I'm figuring the Blend by taking the Hue/Saturation from the overlay and the Luminosity from the base and creating a new HSL color. I then convert that to RGB and write that pixel to the bitmap over the original base color.
What I don't know how to do is apply the alpha. It seems like I should be take the base color and the product of the blend and figure the alpha between them. I'm not sure if this is correct though, or where to find the proper calculation between the colors.
I don't see the need for code for this question but if you need it, I can post some.
Thanks

A: I just solved this problem like this (background.png and colorWithAlpha.png have the same dimensions):
Bitmap bg = new Bitmap("background.png");
Bitmap overlay = new Bitmap("colorWithAlpha.png");
float m = 0;
Color c;
for (int i = 0; i < bg.Width; i++)
{
    for (int j = 0; j < bg.Height; j++)
    {
        m = overlay.GetPixel(i, j).A / 255f;
        c = HSVtoRGB(overlay.GetPixel(i,j).GetHue(), overlay.GetPixel(i,j).GetSaturation(), bg.GetPixel(i, j).GetBrightness());
        c = Color.FromArgb((int)(m * c.R + (1 - m) * bg.GetPixel(i, j).R), (int)(m * c.G + (1 - m) * bg.GetPixel(i, j).G), (int)(m * c.B + (1 - m) * bg.GetPixel(i, j).B));
        bg.SetPixel(i, j, c);
    }
}

public static Color HSVtoRGB(float hue, float saturation, float value)
{
    // HSV contains values scaled as in the color wheel:
    // that is, all from 0 to 255.

    // for ( this code to work, HSV.Hue needs
    // to be scaled from 0 to 360 (it//s the angle of the selected
    // point within the circle). HSV.Saturation and HSV.value must be
    // scaled to be between 0 and 1.

    double h;
    double s;
    double v;

    double r = 0;
    double g = 0;
    double b = 0;

    // Scale Hue to be between 0 and 360. Saturation
    // and value scale to be between 0 and 1.
    h = ((double)hue / 255 * 360) % 360;
    s = (double)saturation / 255;
    v = (double)value / 255;

    if (s == 0)
    {
        // If s is 0, all colors are the same.
        // This is some flavor of gray.
        r = v;
        g = v;
        b = v;
    }
    else
    {
        double p;
        double q;
        double t;

        double fractionalSector;
        int sectorNumber;
        double sectorPos;

        // The color wheel consists of 6 sectors.
        // Figure out which sector you//re in.
        sectorPos = h / 60;
        sectorNumber = (int)(Math.Floor(sectorPos));

        // get the fractional part of the sector.
        // That is, how many degrees into the sector
        // are you?
        fractionalSector = sectorPos - sectorNumber;

        // Calculate values for the three axes
        // of the color.
        p = v * (1 - s);
        q = v * (1 - (s * fractionalSector));
        t = v * (1 - (s * (1 - fractionalSector)));

        // Assign the fractional colors to r, g, and b
        // based on the sector the angle is in.
        switch (sectorNumber)
        {
            case 0:
                r = v;
                g = t;
                b = p;
                break;

            case 1:
                r = q;
                g = v;
                b = p;
                break;

            case 2:
                r = p;
                g = v;
                b = t;
                break;

            case 3:
                r = p;
                g = q;
                b = v;
                break;

            case 4:
                r = t;
                g = p;
                b = v;
                break;

            case 5:
                r = v;
                g = p;
                b = q;
                break;
        }
    }
    // return an RGB structure, with values scaled
    // to be between 0 and 255.
    return Color.FromArgb((int)(r * 255), (int)(g * 255), (int)(b * 255));
}

The function HSVtoRGB is taken from https://bytes.com/topic/c-sharp/answers/236124-how-would-i-change-hue-bitmap, slightly adjusted as the original function expects all inputs as values from 0-255, so the scaling has to be removed.


text:
Q: unable to input text in multiple tabs in ie using vba I am new to VBA !! I am trying to automate a specific process Which is "Copying the customer details from the excel sheet and opening a IE and going to a specific URL and then pasting the information and clicking the Search button and getting into customers records" I have successfully completed the process but it opens in multiple window as I have to do this for many customers, which was not Nice, so I searched online and successfully opened the customer's records page in multiple TABS in the same WINDOW of IE.
Now the real problem is I am unable to enter the customer's information in each window separately, it just enters the details in the very "FIRST WINDOW" and searches it
Below is the code I used :
Set IE = CreateObject("InternetExplorer.application")
IE.Visible = True
IE.Navigate ThisWorkbook.Sheets("Sheet4").Range("Link")
Do
If IE.ReadyState = 4 Then
Exit Do
Else
DoEvents
End If
Loop
On Error Resume Next
IE.document.all("admin_name").Value = ThisWorkbook.Sheets("Sheet4").Range("User")
IE.document.all("admin_pass").Value = ThisWorkbook.Sheets("Sheet4").Range("Pass")
Set ElementCol = IE.document.getElementsByTagName("button")
For Each link In ElementCol
If link.innerHTML = "LOGIN" Then
link.Click
Exit For
End If
Next
Application.Wait (Now + TimeValue("0:00:04")) ' Utill this line the IE opens the URL (and it is password protected)
' From here on the code opens the customer's records page
x = Range("J1").CurrentRegion.Rows.Count
Y = x - 1
For i = 1 To Y
ActiveCell.Offset(1, -1).Select
Dim navi As String
navi = "Sample URL"
IE.Navigate navi, CLng(2048) ' This is code which i used to open webpages in multiple TABS
Application.Wait (Now + TimeValue("0:00:04"))
Dim Firstname As Variant
Firstname  = ActiveCell.Value
IE.document.getelementsbyname("cc_first_six").Item.innertext = Firstname
ActiveCell.Offset(0, 1).Select
Dim Lastname As Variant
Lastname = ActiveCell.Value
IE.document.getelementsbyname("cc_last_four").Item.innertext = Lastname
Set ElementCol = IE.document.getElementsByTagName("a")
For Each link In ElementCol
If link.innerHTML = "Show Results" Then
link.Click
End If
Next
Next i

End Sub
The Code runs fine but it only uses the first TAB and searches for the all the customers, what I want to do is, it should use the second TAB for the First customer in the excel file and Third TAB for the Second customer in the excel file and so on .... (I am able accomplish my need if i use multiple window option but, i want to do it in the same window but multiple TABS)

A: I did lot of research but i can't find suitable solution for this problem. But you can use sendkeys for moving from one tab to other tab.
SendKeys "^{TAB}", True
Application.Wait (Now() + TimeValue("00:00:10"))


text:
Q: What is the difference between installing a software from deb file, and installing it from the software market as snap package? Recently, I was planning to install Opera browser on my system, so I visited the official website, and downloaded the .deb file, and installed it.
However, to my concern, for every update, I will be needing to download the .deb file again and again, since I have not updated the repository in Software & Updates section. At this point I thought, Chrome itself added the repository, so maybe Opera must have done it too, but it didn't.
Same issue with the Discord application, i.e., I have to visit the official website and download the .deb file for timely-updates.
However, I found that the Ubuntu software market ships both, Opera and Discord, but as snap packages. So I thought to give it a try, since it would relief me of downloading the .deb files from the official website, and I can update them with just a command.
Here, I was recommended by some friends of mine that I shouldn't opt for the snap, because of some errors or something, which I am currently completely unaware of, and instead go for the official .deb files.
Can someone explain me the differences?
EDIT: Since past few months, Chromium has too moved itself to the snap packages. Does this have any difference from past when it was in apt-get package system?


text:
Q: mainwindow.cpp:(.text+0x9): undefined reference to, QT project fails during unit tests I'm in the middle of submitting a QT project, but the automated unit testing on my course is giving me the following error. I've been trying to figure out what the issue and I can't figure out why. The full error is as follows.
/usr/local/bin/moc -DQT_DEPRECATED_WARNINGS -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_TESTLIB_LIB -DQT_CORE_LIB -DQT_TESTCASE_BUILDDIR='"/submission-repo/student/12/timer"' --include ./moc_predefs.h -I/usr/local/mkspecs/linux-g++ -I/submission-repo/student/12/timer -I/usr/local/include/QtWidgets -I/usr/local/include/QtGui -I/usr/local/include/QtTest -I/usr/local/include/QtCore -I/usr/include/c++/5 -I/usr/include/x86_64-linux-gnu/c++/5 -I/usr/include/c++/5/backward -I/usr/lib/gcc/x86_64-linux-gnu/5/include -I/usr/local/include -I/usr/lib/gcc/x86_64-linux-gnu/5/include-fixed -I/usr/include/x86_64-linux-gnu -I/usr/include tst_timer.cpp -o tst_timer.moc
g++ -c -pipe -O2 -std=gnu++11 -Wall -W -D_REENTRANT -fPIC -DQT_DEPRECATED_WARNINGS -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_TESTLIB_LIB -DQT_CORE_LIB -DQT_TESTCASE_BUILDDIR='"/submission-repo/student/12/timer"' -I. -isystem /usr/local/include/QtWidgets -isystem /usr/local/include/QtGui -isystem /usr/local/include/QtTest -isystem /usr/local/include/QtCore -I. -isystem /usr/include/libdrm -I. -I/usr/local/mkspecs/linux-g++ -o tst_timer.o tst_timer.cpp
g++ -c -pipe -O2 -std=gnu++11 -Wall -W -D_REENTRANT -fPIC -DQT_DEPRECATED_WARNINGS -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_TESTLIB_LIB -DQT_CORE_LIB -DQT_TESTCASE_BUILDDIR='"/submission-repo/student/12/timer"' -I. -isystem /usr/local/include/QtWidgets -isystem /usr/local/include/QtGui -isystem /usr/local/include/QtTest -isystem /usr/local/include/QtCore -I. -isystem /usr/include/libdrm -I. -I/usr/local/mkspecs/linux-g++ -o mainwindow.o mainwindow.cpp
g++ -c -pipe -O2 -std=gnu++11 -Wall -W -D_REENTRANT -fPIC -DQT_DEPRECATED_WARNINGS -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_TESTLIB_LIB -DQT_CORE_LIB -DQT_TESTCASE_BUILDDIR='"/submission-repo/student/12/timer"' -I. -isystem /usr/local/include/QtWidgets -isystem /usr/local/include/QtGui -isystem /usr/local/include/QtTest -isystem /usr/local/include/QtCore -I. -isystem /usr/include/libdrm -I. -I/usr/local/mkspecs/linux-g++ -o moc_mainwindow.o moc_mainwindow.cpp
g++ -Wl,-O1 -Wl,-rpath,/usr/local/lib -o tst_timer tst_timer.o mainwindow.o moc_mainwindow.o   -L/usr/local/lib -lQt5Widgets -lQt5Gui -lQt5Test -lQt5Core -lGL -lpthread
mainwindow.o: In function `MainWindow::on_startButton_clicked()':
mainwindow.cpp:(.text+0x9): undefined reference to `Stopwatch::isRunning()'
mainwindow.o: In function `MainWindow::on_stopButton_clicked()':
mainwindow.cpp:(.text+0x39): undefined reference to `Stopwatch::isRunning()'
mainwindow.o: In function `MainWindow::MainWindow(QWidget*)':
mainwindow.cpp:(.text+0xf7): undefined reference to `Stopwatch::Stopwatch()'
mainwindow.o: In function `MainWindow::update()':
mainwindow.cpp:(.text+0x592): undefined reference to `Stopwatch::isRunning()'
mainwindow.cpp:(.text+0x5c5): undefined reference to `Stopwatch::getTime()'
mainwindow.o: In function `MainWindow::on_startButton_clicked()':
mainwindow.cpp:(.text+0x1e): undefined reference to `Stopwatch::start()'
mainwindow.o: In function `MainWindow::on_stopButton_clicked()':
mainwindow.cpp:(.text+0x4e): undefined reference to `Stopwatch::stop()'
mainwindow.o: In function `MainWindow::on_resetButton_clicked()':
mainwindow.cpp:(.text+0x88): undefined reference to `Stopwatch::reset()'
collect2: error: ld returned 1 exit status
Makefile:245: recipe for target 'tst_timer' failed
make: *** [tst_timer] Error 1

Here are my files.
mainwindow.hh
#ifndef MAINWINDOW_HH
#define MAINWINDOW_HH

#include <QMainWindow>
#include <QTimer>
#include "stopwatch.hh"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    // Normally this member should be in private part of the
    // class, but due to the automated tests it must be more
    // accessible.
    QTimer* timer;

private slots:
    // Add your slots here
    void on_startButton_clicked();
    void on_stopButton_clicked();
    void on_resetButton_clicked();
    void update();

signals:

private:
    Ui::MainWindow *ui;
    Stopwatch* watch;
    // Add other necessary members here
};

#endif // MAINWINDOW_HH

stopwatch.hh
#ifndef STOPWATCH_HH
#define STOPWATCH_HH

#include <QAbstractItemModel>
#include <QTime>

class Stopwatch
{
public:
    explicit Stopwatch();
    void start();
    void stop();
    void reset();
    qint64 getTime();
    bool isRunning();
    void setRunning(bool running);

private:
    bool mRunning;
    qint64 mTotalTime;
    qint64 mTempTime;
    QDateTime mStartTime;
    QTime *time;
signals:

public slots:
};

#endif // STOPWATCH_HH

mainwindow.cpp
#include "mainwindow.hh"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QTime>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    watch(new Stopwatch())
{
    ui->setupUi(this);

    auto lcdpalette = new QPalette;
    lcdpalette->setColor(QPalette::Background, QColor(0, 0, 0));
    lcdpalette->setColor(QPalette::Base, QColor(255, 160, 122));
    lcdpalette->setColor(QPalette::AlternateBase, QColor(255, 160, 122));

    ui->lcdNumberMin->setPalette(*lcdpalette);
    ui->lcdNumberMin->setAutoFillBackground(true);
    ui->lcdNumberSec->setPalette(*lcdpalette);
    ui->lcdNumberSec->setAutoFillBackground(true);

    QObject::connect(ui->startButton, &QPushButton::clicked,
                     this, &MainWindow::on_startButton_clicked);
    QObject::connect(ui->stopButton, &QPushButton::clicked,
                     this, &MainWindow::on_stopButton_clicked);
    QObject::connect(ui->resetButton, &QPushButton::clicked,
                     this, &MainWindow::on_resetButton_clicked);

     timer = new QTimer(this);
     connect(timer, SIGNAL(timeout()), this, SLOT(update()));
     timer->start(1);

}

MainWindow::~MainWindow()
{
    delete ui;
    delete watch;
}

void MainWindow::on_startButton_clicked()
{
    if(not (watch->isRunning()))
    {
        watch->start();
    }
}

void MainWindow::on_stopButton_clicked()
{
    if(watch->isRunning())
    {
        watch->stop();
    }
}

void MainWindow::on_resetButton_clicked()
{
    ui->lcdNumberMin->display(00);
    ui->lcdNumberSec->display(00);
    watch->reset();
}

// Triggers every 10 milliseconds (every hundredth of a second)
// Updates the time displayed on the stopwatch.
void MainWindow::update()
{
    if(watch->isRunning())
    {
        qint64 time = watch->getTime();
        int hour = time / 1000 / 60 / 60;
        int minutes = (time / 1000 / 60) - (hour * 60);
        int seconds = (time / 1000) - (minutes * 60);

        if(seconds < 10) {
            ui->lcdNumberSec->display(QStringLiteral("0%1").arg(seconds));
        }
        else {
            ui->lcdNumberSec->display(QStringLiteral("%1").arg(seconds));
        }
        if(minutes < 10) {
            ui->lcdNumberMin->display(QStringLiteral("0%1").arg(minutes));
        }
        else {
            ui->lcdNumberMin->display(QStringLiteral("%1").arg(minutes));
        }
    }
}

stopwatch.cpp
#include "stopwatch.hh"

// Default constructor
Stopwatch::Stopwatch() :
    mRunning(false),
    mTotalTime(0),
    mTempTime(0)
{
}

// Starts the stopwatch.
// Instantiates the start time and declares the watch to be running.
void Stopwatch::start()
{
    mStartTime = QDateTime::currentDateTime();
    mRunning = true;
}

// Pauses the stopwatch.
// Saves the current time and declares the watch to not be running.
void Stopwatch::stop()
{
    mTotalTime += mTempTime;
    mRunning = false;
}

// Resets the stopwatch.
// Resets the saved time and declares the watch to not be running.
void Stopwatch::reset()
{
    mTotalTime = 0;
    mRunning = false;
}

// Returns whether the stopwatch is running.
bool Stopwatch::isRunning()
{
    return mRunning;
}

// Sets the state of the stopwatch (running/not running)
void Stopwatch::setRunning(bool running)
{
    mRunning = running;
}

// Returns the current time of the running stopwatch
qint64 Stopwatch::getTime()
{
    mTempTime = mStartTime.msecsTo(QDateTime::currentDateTime());
    qint64 time = mTotalTime + mTempTime;
    return time;
}

timer.pro
QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = timer
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
        main.cpp \
        mainwindow.cpp \
        stopwatch.cpp

HEADERS += \
        mainwindow.hh \
        stopwatch.hh

FORMS += \
        mainwindow.ui

I've cleaned and rebuilt project multiple times and it hasn't solved anything.


text:
Q: how to convert a list in python to a set according to index number I have a list y=[0,2,1,2,1,1,2,1] and it has 8 elements (from 0 to 7).
And since it has three unique elements, so three sets will be created.
I want the output to be
s1={0}
s2={1,3,6}
s3={2,4,5,7}

A: If I understood correctly, what you want to do is to get a set for each unique value in your list that will return indexes of all occurrences of this value in the list.
We can't tell how many sets we will need, therefore we should create a new set for each unique value and hold these sets in a list.
y = [0,2,1,2,1,1,2,1]

y_set = set(y)

set_list = []

for unique_value in y_set:
    new_set = set()
    for i, value in enumerate(y):
        if unique_value == value:
            new_set.add(i)
    set_list.append(new_set)

This is the result you will get from this approach:
[{0}, {2, 4, 5, 7}, {1, 3, 6}]

A: Try something like this:
y = [0,2,1,2,1,1,2,1]
d = {}
for i in set(y):
   d[i] = []
for j in range(len(y)):
   d[y[j]].append(j)
print d

Output:
{0: [0], 1: [2, 4, 5, 7], 2: [1, 3, 6]}

A: You can use enumerate and defaultdict:
from collections import defaultdict

my_dict = defaultdict(list)

for index, element in enumerate(y):
    my_dict[element].append(index)

result = my_dict.values()

A: I think it's better to use the value as the key, it's more clear for further steps.
y=[0,2,1,2,1,1,2,1]
dict = {}
for i, x in enumerate(y):
    if x not in dict.keys():
        dict[x] = [i]
    else:
        dict[x].append(i)
print dict

{0: [0], 1: [2, 4, 5, 7], 2: [1, 3, 6]}
And if you prefer to get the exactly output as mentioned -
from collections import OrderedDict
y= [0, 2, 1, 2, 1, 1, 2, 1]
dict2 = OrderedDict()
dict_seq = OrderedDict()
sequence = 1
list = []
for i, x in enumerate(y):
    if x not in dict2.keys():
        dict2[x] = [i]
        dict_seq['S{0}'.format(sequence)] = dict2[x]
        sequence+=1
    else:
        dict2[x].append(i)
print("dict2 = {0}".format(dict2))
for key, value in dict_seq.items():
    print("{0} = {1}\n".format(key, value))

dict2 = OrderedDict([(0, [0]), (2, [1, 3, 6]), (1, [2, 4, 5, 7])])
S1 = [0]
S2 = [1, 3, 6]
S3 = [2, 4, 5, 7]

A: You can try manual approach:
y=[0,2,1,2,1,1,2,1]

groub_by={}

for i,j in enumerate(y):
    if j not in groub_by:
        groub_by[j]=[i]
    else:
        groub_by[j].append(i)
print(groub_by.values())

or you can also try itertools grouby approach:
list_with_index=[(j,i) for i,j in enumerate(y)]

import itertools
for i,j in itertools.groupby(sorted(list_with_index),key=lambda x:x[0]):
    print(list(map(lambda x:x[1],j)))

output:
[0]
[2, 4, 5, 7]
[1, 3, 6]

A: try like this :
from collections import defaultdict

lst = [0,2,1,2,1,1,2,1]
lst_indxs = dict(enumerate(lst))
final_dict = defaultdict(list)
for i,j in lst_indxs.items():
    final_dict[j].append(i)
print(dict(final_dict))


text:
Q: How to call the function in design page which is in the code behind file of the web page in the asp.net? I 'm new to the asp.net. I have created one web page in that web page i designed the with the help of table tag. I have filled datatable in the code behind file. I accessed the datatable fields in the design of web page for displaying values in the table. The code for accessing value is as follows--

            MD Priority :

    <img src='<%GetImage(dtCompany.Rows[0]["MDPriority"]);%>' alt=""/>
    <%Response.Write(dtCompany.Rows[0]["MDPriority"].ToString());%>

the format of GetImage function is as follows--
public string GetImage(object ImageID)
   {
        if (ImageID != null | ImageID != DBNull.Value)
        {
            int imageID = 0;
            if (ImageID != DBNull.Value)
            {
                imageID = Convert.ToInt32(ImageID);
            }

            switch (imageID)
            {
                case 0:
                    strPath = "../images/not assigned.jpg";
                    break;
                case 1:
                    strPath = "../images/low.jpg";
                    break;
                case 2:
                    strPath = "../images/midium.jpg";
                    break;
                case 3:
                    strPath = "C:/Inetpub/wwwroot/VinserverWebTemplate2/images/high.jpg";
                    break;
                case 4:
                    strPath = "../images/not assigned.jpg";
                    break;
            }

            return strPath;

        }
        else
        {
            return "";
        }
    }

I want to display the image by using above function. But i'm unable to get the image path at the src attribute of img tag.
When i run my web page then following html code is rendered by the browser--

                MD Priority :

                1

How to solve this issue?
thanks.

A: You can accomplish pretty much the same thing doing this:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
    <Columns>
        <asp:ImageField HeaderText="Image" DataImageUrlField="ImagePath" />
    </Columns>
</asp:GridView>

And binding data to your gridview like this:
private void bindGridView()
{
    DataTable t = new DataTable();
    t.Columns.Add("ImagePath");
    DataRow r = null;
    for (int i = 0; i < 5; i++)
    {
        r = t.NewRow();
        r.ItemArray = new object[] { "images/couple24.png"};
        t.Rows.Add(r);
    }
    GridView1.DataSource = t;
    GridView1.DataBind();
}

That, will produce something like:

I know this doesn't answer your question but my intention is to give you an example of the power of ASP.NET; there are very rare occasions where you need to do Response.Write from your markup.
UPDATE:
Very well, you want to do it the wrong way. Your error is here:
<img src='<%GetImage(dtCompany.Rows[0]["MDPriority"]);%>'

It needs to be (notice = after <%):
<img src='<%=GetImage(dtCompany.Rows[0]["MDPriority"])%>'

Test case
///code behind
public string GetImage(object ImageID)
{
    return "images/couple24.png";
}

markup:
<img src='<%=GetImage("test")%>' />

Renders like this on the HTML:


text:
Q: How do I call "operator->()" directly? For some strange reason, I need to call the operator->() method directly. For example:
class A {
    public:
        void foo() { printf("Foo"); }
};

class ARef {
    public:
        A* operator->() { return a; }
    protected:
        A* a;
};

If I have an ARef object, I can call foo() by writing:
aref->foo();

However, I want to get the pointer to the protected member 'a'. How can I do this?

A: You can call the operator directly using the following syntax:
aref.operator->()

You should probably overload both -> and *, so that usage is consistent with the usage of a pointer:
class ARef {
    public:
        A* operator->() { return a; }
        A& operator*() { return *a; }
    protected:
        A* a;
};

Then you can use the following to get the pointer value:
&*aref

You can also implement a get() member function that returns the A* directly, which is much, much cleaner than either of these solutions (most smart pointer classes provide a get() member function).

A: You can call operator->() directly.
A* result = a.operator->();

A: I would probably not call it together, but instead create a new member which does the same work since it would read better:
class ARef {
public:
    A* operator->() { return get(); }
    A* get() const { return a; }
protected:
    A* a;
};

A: Absent any friends, you cannot get a "pointer to the protected member a" outside class A or one of its descendants. Operator -> will not help you here, regardless of how you call it.
Given the current interface of ARef, the only way to get a pointer to a is to do something like A **pa = &a inside one of the methods of class A or some descendant class.
I don't know why you need to get a pointer to a, and frankly it doesn't seem to make much practical sense to me, but if you really need it, you can add a separate method that does exactly that
class ARef {
public:
  ...
  A** get_ptr_to_a() { return &a; }
  ...
};

A: aref.operator->(); // Returns A*

Note that this syntax works for all other operators as well:
// Assuming A overloads these operators
A* aref1 = // ...
A* aref2 = // ...
aref1.operator*();
aref1.operator==(aref2);
// ...

For a cleaner syntax, you can a implement a Get() function or overload the * operator to allow for &*aref as suggested by James McNellis.


text:
Q: Sync between UserProfile Store and User Information List One of the users has updated his photo/picture on his My Site and it is showing the updated photo (on his My Site) as well as the picture property (user profile property) in SSP is updated with the new url (http://...).
However, the new picture is not displaying in the other sharepoint web-applications. I have verified that the user has already contribute/uploaded a document into the document library in the site-collection.
I even removed the user from the sharepoint member group and re-added the user using people picker window however still the result is same.
I run the "stsadm -o sync" and it did not fix the issue.
Do we have any specific method or command to fix this ?

A: A PS code to fix this.

$url = "http://hulmossteam:25000/"

$site= new-Object Microsoft.SharePoint.SPSite($url )

$web = $site.OpenWeb();

$myUser = $web.SiteUsers["c1\Administrator"]

$myUserInfo = $web.SiteUserInfoList.Items.GetItemById($myUser.ID)

$myUserInfo["Picture"]= "http://mysite/personal/Administrator/Shared%20Pictures/c781e650-0bc1-4c63-bb47-00f51398fd80.jpg"

$myUserInfo.Update()

A: I think this is related to a similar issue that Andrew Pointed to here
Profile Sync doesn't filter to all users on all sites
EDIT: url now points to migrated site

A: I seen this frequently, but overnight it is fixed... I think it's spart of a daily job.


text:
Q: In kotlin,parameter variables are created as local 'val' variables that can't be reused for other values hi i am newbie in kotlin and have a confusion about parameter variables they are created as local 'val' variables that can't be reused for other values.
for example:
fun myFunction(mesg:String){
 mesg="hi" //local val variables that can't be reused for other values
}

but the below code is working fine
fun main(args: Array<String>) {
    val abc = arrayOf("A", "B", "C")
    updateArray(abc)

    println(abc[2])// print Z
}

fun updateArray(abcParam: Array<String>) {
    abcParam[2] = "Z" //
}

A: Keep in mind that in kotlin everything is passed to functions by values. For primitive types it is okay and pretty obvious that you can not change variable passed by value. But if we talk about objects, its reference is getting passed to function, so you can not change only reference passed to function, but free to change object that reference points to.
Thats why you are able to change elements of array but can not change string.


text:
Q: Should numbers from user input be quoted in MySQL queries to help avoid SQL injection attacks? Should numbers from user input be quoted in MySQL queries to help avoid SQL injection attacks?
Say i have a form on a page asking for someone's age. They enter their age and hit submit. The following php code deals with the form submission: (age is an int field in the db table.)
$Number = mysqli_real_escape_string($dbc, $_POST["age"]);
$Query = "INSERT INTO details (age) VALUES ($Number)";
$Result = mysqli_query($dbc, $Query);

Instead of this, is there anything to be gained to enclosing the user input in single quotes, even though it is not a string? Like this:
...
$Query = "INSERT INTO details (age) VALUES ('$Number')";  <-- quotes
...

What about performing a SELECT? Is this:
$ID = mysqli_real_escape_string($dbc, $_POST["id"]);
$Query = "SELECT * FROM users WHERE id = '$ID'";
$Result = mysqli_query($dbc, $Query);

better than:
$ID = mysqli_real_escape_string($dbc, $_POST["id"]);
$Query = "SELECT * FROM users WHERE id = $ID";      <-- no quotes
$Result = mysqli_query($dbc, $Query);

NOTE: I am aware of prepared statements and usually use them over string concatenation but this is legacy code i'm dealing with. I want to secure it as best as i can.

A: If you add numbers, use the intval/floatval functions, don't use mysql_real_escape_string for those.
For everything you use mysql_real_escape_string for, you must use quotes, example:
$input = "foo'bar";
$input = mysql_real_escape_string($input);
//foo\'bar
mysql_query("SELECT $input");
//SELECT foo\'bar
//which is still an SQL syntax error.

A: You really shoud use sprintf, even if in legacy code it takes 2 mins to modify and is in my opinion totally worth the time.
Shamelessly ripped from php.net:
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
                 WHERE  firstname='%s' AND lastname='%s'",
                 mysql_real_escape_string($firstname),
                 mysql_real_escape_string($lastname));

// Perform Query
$result = mysql_query($query);

Your query is now pretty much safe from being passed the wrong types to it's fields and unescaped caracters.

A: You SHOULD use the PHP filters, and filter for numbers - even for ranges, regular expressions; with default values, NULL on failure, etc.
http://hu.php.net/manual/en/ref.filter.php
if the values come from a request variable, e.g. $_POST, see:
http://hu.php.net/manual/en/function.filter-input.php


text:
Q: jQuery - Show/hide has problems with centered items All I want is, as the code says, to loop a show-hide animation. Somehow it seems to automatically move to the left and back to the center.
What's happening and how do I keep it fixed to the center?

Hiding...

A: show and hide are both just changing the display CSS property, which seems to be causing block issues with the center element. You could use fadeIn and fadeOut instead:

    Hiding...


text:
Q: MySQL partitioning table by date and hour I have a table with a timestamp field. This table will have millions of rows every day so the idea is to create partitions by date and hour. Every day I will delete partitions older than 10 days and create the partitions for next day.
   Can you someone tell me how to define partitions for this case? I could not figure it out.
   Thanks in advance.

A: Use 12 partitions -- 10 days, plus one at each end.  REORGANIZE PARTITION to split the empty, future, partition at the end before the new day; drop the oldest.  All the details, including code, are spelled out in http://mysql.rjweb.org/doc.php/partitionmaint .
Hourly partitions would lead to over 240 partitions; that large a number slows things down.


text:
Q: Por qué recibo el error File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) y como lo puedo solucionar? Hola estoy tratando de instalar django pero para ello primero debo instalar el setuptools y pip cuando ejecuto el el primero me sale el error, que puedo hacer, gracias de antemano.

A: Te da ese error por que tienes instalado python 2.7 y esa versión de setuptools requiere python 3.x
Creo que la version 44.0.0 todavía funciona para python 2.7, puedes instalarla con pip, pypi.org/project/setuptools/44.0.0


text:
Q: Why do objects have to be initialized first before use ? Constructor function vs Object.create I made my object a constructor function cause I did not want to put my code in another file or my object on top. Why do objects have to be initialized before use if a function does not and a function is considered an object ?
var foo_f = new Foo_methods;
var foo_o = Object.create(null);
foo_o = Object.create(foobar_obj);

foo_f.name() //Works, functions can be initialized anywhere.
foo_o.name() // Error you have to put the object on top

function Foo_methods(){

  this.name = function(){ console.log("I am foo in Foo_methods")}
}

//If I put this on top or in another file it works. If I don't I get an error
//Type Error: Object prototype may only be an Object or null: undefined

var foobar_obj = {

         name:function(){ console.log("I am foo in foobar_obj")}
}


text:
Q: Jade includes and blocks I have many template pages (index.jade, catalog.jade, contacts.jade and so on), where I include some extra pieces of code (like header_piece.jade and footer_piece.jade) by include.
What I'm trying to do - I want to include something to the code, which is included by include. Hope it can be done using jade.
Here is my code:
index.jade:
body
  .wrapper
    include inc/header_piece

    append header
      .someextradiv
        | text

inc/header_piece.jade:
  block header
    .header
      a(href = '/') Home

What I expect to get:

Home

Text

What I really get:

Home

Home

What I'm doing wrong and how to get desired result?

A: I was able to get your desired results by doing the following:
index.jade:
body
  .wrapper
  include inc/header_piece

  append inc/header
    .someextradiv
    | text