text:
Q: traefik ssl certificate generation for cname record "tls: bad certificate" Does a reverse proxy need extra configuration to generate ssl certificates, if I have a subdomain cnamed to a different server?
mydomain.com, A record to server #1 at 111.111.111.111
subdomain.mydomain.com, CNAME record to otherdomain.dynv6.net
otherdomain.dynv6.net, A record to server #2 at 222.222.222.222

As I don't know the answer to the question above, the reason for ssl certificate failing might be either that cname related stuff, or letsencrypt rate limiting (don't know how to check that unfortunately) or some misconfiguration.
I am using traefik v2 as my reverse proxy running on server #2 and this is my error:
time="..." level=debug msg="Adding route for SUBDOMAIN.MYDOMAIN.COM with TLS options default" entryPointName=websecure
time="..." level=debug msg="Try to challenge certificate for domain [SUBDOMAIN.MYDOMAIN.COM] found in HostSNI rule" rule="Host(`SUBDOMAIN.MYDOMAIN.COM`)" providerName=myresolverletsencrypt.acme routerName=whoami@docker
time="..." level=debug msg="Looking for provided certificate(s) to validate [\"SUBDOMAIN.MYDOMAIN.COM\"]..." providerName=myresolverletsencrypt.acme routerName=whoami@docker rule="Host(`SUBDOMAIN.MYDOMAIN.COM`)"
time="..." level=debug msg="Domains [\"SUBDOMAIN.MYDOMAIN.COM\"] need ACME certificates generation for domains \"SUBDOMAIN.MYDOMAIN.COM\"." providerName=myresolverletsencrypt.acme routerName=whoami@docker rule="Host(`SUBDOMAIN.MYDOMAIN.COM`)"
time="..." level=debug msg="Loading ACME certificates [SUBDOMAIN.MYDOMAIN.COM]..." providerName=myresolverletsencrypt.acme routerName=whoami@docker rule="Host(`SUBDOMAIN.MYDOMAIN.COM`)"
time="..." level=debug msg="Building ACME client..." providerName=myresolverletsencrypt.acme
time="..." level=debug msg="https://acme-v02.api.letsencrypt.org/directory" providerName=myresolverletsencrypt.acme
time="..." level=error msg="Unable to obtain ACME certificate for domains \"SUBDOMAIN.MYDOMAIN.COM\": cannot get ACME client get directory at 'https://acme-v02.api.letsencrypt.org/directory': Get \"https://acme-v02.api.letsencrypt.org/directory\": dial tcp: lookup acme-v02.api.letsencrypt.org on 127.0.0.11:53: read udp 127.0.0.1:34539->127.0.0.11:53: i/o timeout" providerName=myresolverletsencrypt.acme routerName=whoami@docker rule="Host(`SUBDOMAIN.MYDOMAIN.COM`)"
time="..." level=debug msg="Serving default certificate for request: \"SUBDOMAIN.MYDOMAIN.COM\""
time="..." level=debug msg="http: TLS handshake error from 172.22.0.1:38464: remote error: tls: bad certificate"

My services are run with docker. Here is the traefik and whoami subdomain configuration of my docker-compose file.
version: "3.7"
services:
  traefik:
    image: "traefik:v2.4.7"
    command:
      - "--log.level=DEBUG"
      - "--api=true"
      - "--api.dashboard=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.web.http.redirections.entryPoint.to=websecure"
      - "--entrypoints.web.http.redirections.entryPoint.scheme=https"
      - "--entrypoints.websecure.address=:443"
      - "--entrypoints.websecure.http.tls.certResolver=myresolverletsencrypt"
      - "--log=true"
      - "--log.filePath=/logs/traefik.log"
      - "--accesslog=true"
      - "--accesslog.filePath=/logs/access.log"
      - "--certificatesresolvers.myresolverletsencrypt.acme.tlschallenge=true"
      - "--certificatesresolvers.myresolverletsencrypt.acme.email=me@mail.com"
      - "--certificatesresolvers.myresolverletsencrypt.acme.storage=/acme.json"
    labels:
      - "traefik.enable=true"
    expose:
      - 8080
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
  whoami:
    image: "containous/whoami:latest"
    container_name: "whoami"
    restart: unless-stopped
    expose:
      - 80
    ports:
      - "8081:80"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami.rule=Host(`SUBDOMAIN.MYDOMAIN.COM`)"
      - "traefik.http.routers.whoami.entrypoints=websecure"
      - "traefik.http.routers.whoami.tls.certresolver=myresolverletsencrypt"


text:
Q: gomod, Which folders/files will be excluded? Golang use gomod, Some floder/files will be excluded. Such as example/include floder and *_test.go type file.
So, What are all the rules?

A: The Go tool documentation says:

Files in package documentation are ignored by the go command.

and

Directory and file names that begin with "." or "_" are ignored by the go tool, as are directories named "testdata".

Additionally, the documentation for the build command says:

When compiling packages, build ignores files that end in '_test.go'.

Build constraints can also be used to ignore files.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to insert image inline, in email composed with OWA? When I am composing an email message in OWA 8.1.359.2, how do I insert an image in the body of the email, inline with text (not attachment)?

A: SOLUTION to copy and paste!! (Via Ctrl+C & Ctrl+V) (ok so its a good idea to have Exchange 2007 SP1 Rollup 7 pre-installed)
FROM inside OWA (exchange 2007 - I have sp3 on my exchange servers' servers) go to options and email security and then install the Outlook web access s/mime control program works in XP and Windows 7 x64 workstation.
after install click save (probably does not but it does not hurt)
go back to new mail and you can now paste stuff off the clipboard.
This will also enable sending the previous mails as an attachment in a new mail (via drag & drop)

A: In order to insert an image into the body of an email, you will have to declare the message MIME type to be text/html. Then, your attachment image as image/[IMAGE TYPE] (depending on the type of file) with the added header field of Content-Disposition: attachment; filename=[IMAGE FILENAME], and then refer to the image using the relative filename in the HTML: <img src="[IMAGE FILENAME]" />

A: Save your image anywhere on your PC, then right click and say Open with > Internet Explorer. Click and drag image into message window and voila.  Hope that helps! :)

A: If you are not using Internet Explorer, you can use the "Insert image" button in the first line of tools of the new message window.
In my setup, it is the third icon from the left, after the "send" link.
It's icon is the small mountain & sun.


text:
Q: How grouping data with php and display it inside table (table in table)? I have problem when grouping data table in table.
I've made but I think the results are not in accordance with the expected.
This is the example script :
<?php

$conn=mysql_connect('localhost','root','');
mysql_select_db('things',$conn) or die ("Database Not Found");
$result = mysql_query("SELECT id, name, size, color FROM things ORDER BY color");
$state = -1;
$no = 1;

echo '

INDEX OF COLOR

';

    while($row = mysql_fetch_array( $result )) {

        if($state!= $row['color']) {
            $no = 1;
            echo '
'.$row['color']."
";
            echo '

no	NAME OF HERO
';
            $state = $row['color'];
        }

        echo '
'.$no.'	'.$row['name'].'
';

        $no++;

    }

    echo '

';

?>

That code produces the wrong table in the table. The desired outcome is the Color Group>> Details (Table).
I need result like this :)
+-------------------+
| INDEX OF COLOR    |
+-------------------+
|RED                |
+-------------------+
| +----------+      |
| |HERO      |      |
| +----------+      |
| |ROBIN     |      |
| +----------+      |
| |INCREDIBLE|      |
| +----------+      |
+-------------------+
|BLUE               |
+-------------------+
| +----------+      |
| |HERO      |      |
| +----------+      |
| |SPIDEY    |      |
| +----------+      |
| |SUPER MAN |      |
| +----------+      |
| |ICE MAN   |      |
| +----------+      |
+-------------------+

can anyone help me, why this code wrong?
Thank you. :)

A: I think your table is way more complex than it needs to be. I haven't tested this, but try it out.
$first_color = true;
echo '

INDEX OF COLOR
';

while($row = mysql_fetch_array( $result )) {

    if($state!= $row['color']) {
        if(!$first_color) {
            echo '

';
            $first_color = true;
        }
        $no = 1;
        echo '
'.$row['color']."
";
        echo '

no	NAME OF HERO
';
        $state = $row['color'];
    }

    echo '
'.$no.'	'.$row['name'].'
';

    $no++;

}

echo '

';


text:
Q: How to apply persist data when clicking from Vuetify Data Table? Our application shows several thousand users in a Vuetify data able. We can search and sort to find users. Then, we can click on a user's name to open their profile.
The problem is that when we click "back" in the browser, the search/sort/pagination from the table is gone and we have to start over. It's really annoying when we are trying to look at lots of users very quickly.
What is the proper way to make the table not "reset" each time the page loads?
EDIT: We were able to get it working using keep-alive. See the App.vue code below...
Our table code. The Name cell has the link to the user profile page.
<v-data-table
    v-bind:headers="headers"
    :items="users"
    :search="search"
    :rows-per-page-items="[10,25]"
    >
    <template slot="items" slot-scope="props">

            <router-link v-if="props.item.name" v-bind:to="'/staff/' + props.item.id">{{ props.item.name }}</router-link>
            <router-link v-if="!props.item.name" v-bind:to="'/staff/' + props.item.id">{{ props.item.id }}</router-link>

        {{ props.item.validState | round | percentage }}
        {{ props.item.averageScore }}

        {{ props.item.standing }}
        {{ props.item.email }}
        {{ props.item.phone}}

            Yes

        {{ props.item.city }}
    </template>
    <template slot="pageText" slot-scope="{ pageStart, pageStop }">
        From {{ pageStart }} to {{ pageStop }}
    </template>
</v-data-table>

App.vue keep-alive solution:
<template>
<v-app light>
<v-content>
  <transition name="router-anim">
    <keep-alive include="Event Reports,Users,Event Checkin,Event Jobs,Event Grades">
    <router-view/>
    </keep-alive>
  </transition>
</v-content>


text:
Q: JQuery Data table paging buttons scrunched together when bjqueryui is true Here's my data table...
 oTable = $('#example').dataTable({
       "sDom": 'T<"clear">lfrtip',
        //"sDom": 'R<"H"Tlfr>t<"F"ip>',
        // "bServerSide": true,
        "sAjaxSource": '@Url.Action("GetAllDonors", "Person")',
        /* Reduced data set */
        "bProcessing": true,
         "sScrollX": "100%",
        "sScrollXInner": "100%",
        "bScrollCollapse": true,
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "iDisplayLength": 10,
        "fnInitComplete": function (oSettings) {
            $(oTable.fnGetNodes()).click(function () {
                var iPos = oTable.fnGetPosition(this);
                var aData = oSettings.aoData[iPos]._aData;
                location.href = '/Person/Details?id=' + aData[0];
                //alert('Data at index 0: '+aData[0]);
            });
        },
        "aoColumns": [
        { "bVisible": false },
        { "sTitle": "Name" },
        { "sTitle": "Address" },
        { "sTitle": "Phone" },
        { "sTitle": "Email" },
        { "sTitle": "Company" }
    ]

    });
});

when I enable the ui theme, the paging buttons get pushed together so some are overlapping/can't click on them. Any thoughts?
Here's a screen shot of what it looks like:

A: Add the script src for jquery.ui javascript and css files to your document.


text:
Q: Telerik MVC - Numeric textbox in grid editor In my editor for insert telerik show only common textbox (not integer,decimal etc).
this is my view:
@(Html.Telerik().Grid <GamePlayer2>(Model).Name("za11").DataKeys(keys => keys.Add(c => c.Id))
.ToolBar(commands => commands.Insert()
.ButtonType(GridButtonType.ImageAndText))
.DataBinding(dataBinding => dataBinding.Server()
        .Insert("PlayerAdd", "Player", new { })
        .Update("PlayerUpdate", "Player", new { })
        .Delete("PlayerDelete", "Player", new { })
)
.Columns(columns =>
             {
                 columns.Bound(b => b.Name);
                 columns.Bound(b => b.Price);

                 columns.Command(commands =>
                 {
                     commands.Edit();
                     commands.Delete();
                 }).Width(200);

             })
.Editable(editing => editing.Mode(GridEditMode.PopUp)))

model:
public class GamePlayer2
{
    public int Id { get; set; }
    public string Name { get; set; }
    [DataType(DataType.Currency)]
    public decimal Price{ get; set; }
}

Scripts are registered on _Layout. Where is a problem? Why currency(integer,date etc) textbox won't display for fields?

A: Make sure you have added the EditorTemplates under the Shared/EditorTemplates folder. Basically they are automatically added if you have used the wizard to create your project. If not create a demo project and copy-paste them from there.


text:
Q: Rotate squares on mouse hover JavaScript I need to reposition the 5 squares in this HTML code via init()
function and the reposition() function.
I looked on the other
HTML/CSS subjects of the website, but I didn't not find anything
helpful for this information.
Here are the questions :

A. Add in the init() function the code required for the
reposition() function to be called as soon as you hover over an
element of the page associated  with the CSS class "square".
B. Modify the "reposition" function so that it allows you to
reposition the square in symmetry with respect to the diagonal.To do
this, simply reverse the horizontal and vertical positions of this
square.

Note : the pink square will not move because it is precisely on the diagonal (identical horizontal and vertical positions).
And here is my starting code :
    <!DOCTYPE html>
<html lang="fr"

    <meta charset="UTF-8">
    <title>Reposition the squares</title>

Reposition the squares

A: There are two ways you can go about this. I'm assuming you want one square to rotate when you hover over it, so, you can do this with CSS styles. Just how you would style a div or any other HTML element, you can for example, make everything with the .square class rotate on mouse hover like so:
.square:hover {
    transform: rotate(180deg);
}

If you want to smooth this out, add transition: 0.5s; to your .square selector.
If you want to do the same thing in JavaScript, make sure you add that transition I was just talking about, then you can pick out a specific square to rotate by it's id like so:
document.getElementById("carre1").addEventListener("mouseenter", function() {
    document.getElementById("carre1").style.transform = "rotate(180deg)";
});

This essentially does the same thing but doesn't revert the square when your mouse leaves the square.
Happy Coding!


text:
Q: How to get realtime updates for a subcollection in firestore? My database contains a subcollection called 'watched', for videos watched. I'd like to be able to keep track such subcollection in real time. The path looks like this: users/userDocument/watched/date/nestedObjectsForMoviesWatched
e.g. users/as7f9as98dfa/watched/June-2020/
       {name: Forrest Gump, watched: true} {name: Interstellar, watched: false}
Here's how I try to handle it
  useEffect(() => {
    const unsubscribeWatched = firebase
      .firestore()
      .collection('users')
      .doc(userId)
      .collection('watched')       //why doesn't this work?
      .doc(month)
      .onSnapshot(snapshot => {
        //how to handle snapshot received?
      })

      return () => {
        unsubscribeWatched()
      }

  }, [])

It is specifically important that my app is aware of when changes are made to the watched property in a given object.

A: It seems like this documentation can help you to perform the task you want. As you can see in the shared link, "If you want to receive snapshot events when the document or query metadata changes, pass a listen options object when attaching your listener". So, it is only necessary to add "includeMetadataChanges: true" in your code, as you can see below. The complete example can be found here.
useEffect(() => {
const unsubscribeWatched = firebase
  .firestore()
  .collection('users')
  .doc(userId)
  .collection('watched')
  .doc(month)
  .onSnapshot(snapshot => {
    includeMetadataChanges: true
  })

  return () => {
    unsubscribeWatched()
  }}


text:
Q: UnicodeDecodeError with Python2.7, ImportError: no module named html.entities with Python 3.4 The problem is this: my project on hosting does not work as it should.
What we have:

*

*two environments with the same set of modules - one on python 2.7, another on 3.4.

*project site (link to github):
https://github.com/Sibiryakanton/site_NL
If index.wsgi connects the path to django in 2.7, the site is displayed, but there are no css styles. Link:
http://j-star.ru/
Also, I can not give the python command manage.py migrate - it produces an error: UnicodeDecodeError: 'ascii' codec can not decode byte 0xd0 in position 0: ordinal not in range (128).
If I connect django from the environment with 3.4, the migration is fine, but the error is ImportError: no module named html.entities. I understand, this is due to BeautifulSoup4 and opening py-files "pythons" of the wrong versions. Correct, if I made a mistake.
Actually, the question: what should I do?
Just in case, I attached the code index.wsgi:
import os, sys

Sys.path.append ('/ home / c / cc54094 / django / public_html / site_NL')
Sys.path.append ('/ home / c / cc54094 / virtualenv-1.11.6 / env-2 / lib / python2.7 / site-packages /')
Os.environ ['DJANGO_SETTINGS_MODULE'] = 'project_nl.settings'
Import django
Django.setup ()

Import django.core.handlers.wsgi
Application = django.core.handlers.wsgi.WSGIHandler ()


text:
Q: Live555 OpenRTSP Client : How to delete current rtsp client properly and start new One Well,

*

*When my OpenRtsp Client lost connection with server, I dispose the
old client and other parameters then re-create new client.

*The Client send Options,Describe request successfully but failed after that... I can not   able create Session and Subsesions so I got Access Violations errors..
How to reset old OpenRtspClient properly so that get new "brand" RTSPClient?
My Current Way to Reset Old Client:
I just modify the "shutdown" method in playCommon class. I did not send Teardown...
...
  void ResetOurClient(){

    if (env != NULL) {
        env->taskScheduler().unscheduleDelayedTask(sessionTimerTask);
        env->taskScheduler().unscheduleDelayedTask(arrivalCheckTimerTask);
        env->taskScheduler().unscheduleDelayedTask(interPacketGapCheckTimerTask);
        env->taskScheduler().unscheduleDelayedTask(qosMeasurementTimerTask);
      }

      closeMediaSinks();
      Medium::close(session);
      delete ourAuthenticator;
      Medium::close(ourClient);
}

And My ReStartCode:
void StartOurClient()
{

      TaskScheduler* scheduler = BasicTaskScheduler::createNew();
      env = BasicUsageEnvironment::createNew(*scheduler);

      char* streamURL =  "XXXXXXXXX";

      // Create our client object:
      ourClient = createClient(*env, streamURL, verbosityLevel, progName);
      if (ourClient == NULL) {
        *env << "Failed to create " << clientProtocolName
            << " client: " << env->getResultMsg() << "\n";
        shutdown();
      }

      if (sendOptionsRequest) {
        // Begin by sending an "OPTIONS" command:
        getOptions(continueAfterOPTIONS);
      } else {
        continueAfterOPTIONS(NULL, 0, NULL);
      }

      // All subsequent activity takes place within the event loop:
      env->taskScheduler().doEventLoop(&continuesStream); // does not return
}

A: (Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:

Well there was a static variable setUpIter...[MediaSubsessionIterator* setupIter = NULL;] in setupstreams method...so make it global non-static variable and make it NULL at ReStart


text:
Q: What Could be Breaking scrollTo? On this page:
http://alien.devprose.com/screenfad
I'm attempting to have it scroll to a specific position using javascript when the page is loaded.  For example purposes I have this code in the head:
<script type="text/javascript">

window.scrollTo(300,300);

</script>

However, nothing is happening.  Any ideas?

A: It appears that you have jQuery, so the code should be in $(document).ready() like so:
 <script type="text/javascript">
 $(document).ready(function() { window.scrollTo(300,300); });
 </script>

This way, when the window is done loading it will scroll.

A: You can't call window.scrollTo() until after the document has loaded.  Scripts in the HTML (including both in the head and in the body) are executed before that.  This StackOverflow question should explain the best ways to run scripts after it's finished loading.  In summary:
window.onload = function() { window.scrollTo(300,300); };


text:
Q: Maximum number of dialogClass in Jquery Dialog box Am using Jquery Dialog box in my xhtml page. Since there are 2 Jquery Dialog box and look & feel of each box was different from the other, I had to use addClass attribute and this has been discussed in this post. Now I have to override many classes like ui-dialog, ui-corner-all, ui-widget-header etc. So, I went on adding the classes using addClass. Code is below,
$('.ui-widget-content').addClass('new-ui-widget-content');
$('.ui-widget').addClass('new-ui-widget');
$('.ui-dialog .ui-dialog-titlebar').addClass('new-ui-dialog new-ui-dialog-titlebar');
$('.ui-widget-header').addClass('new-ui-widget-header');
 $('.ui-helper-clearfix').addClass('new-ui-helper-clearfix');
 ....

$j("#dialog").dialog({
dialogClass: 'new-ui-widget-content',
dialogClass: 'new-ui-widget',
dialogClass: 'new-ui-dialog new-ui-dialog-titlebar',
dialogClass: 'new-ui-widget-header',
dialogClass: 'new-ui-helper-clearfix',
....

But, I noticed that only 1 of the classes is getting overridden. I mean to say, though I have overridden many classes, only new-ui-widget-content is getting overridden(which is placed first).
I also tried in below way. But it gives syntax error.
    $j("#dialog").dialog({
        dialogClass: 'new-ui-widget-content','new-ui-widget',......

Can multiple classes be overridden by addClass?
If so, how it can be done?

A: You really should overwrite unwanted styling from CSS, not by exchanging multiple CSS classes via JavaScript. All you need is some identifier for the second dialog. If #dialog is the first one, I guess the second one is named something along #dialog2.
Add a second stylesheet file to the HTML page or append to the original jquery-ui-rev.css.
You additional styles should reflect the slectors in question, but preceded by a #dialog2, which increases the specificity and sets special formattings for any such classes inside a wrapper named #dialog2.
As I couldn't find a jquery-ui-rev.css, I'll give you an example based on the jquery.ui.dialog.css.
If you want to overwrite some specific property from the selector .ui-dialog, which is in original:
.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; }

…you could do so by setting up another selector, while only re-specifying the appropriate properties:
#dialog2 .ui-dialog {
    width: 500px;
}


text:
Q: How to get dual graph with networkx? I want a dual graph of the following planar graph g.
from networkx.generators.lattice import hexagonal_lattice_graph;
g = hexagonal_lattice_graph(2,3);

Does network x have a function to return the dual graph?
I don't even know the way to get faces of g.


text:
Q: Function whose $n$-th derivative at $x=0$ is $n^3$ / evaluating the power series $\sum_{n=1}^\infty n^3\frac{x^n}{n!}$ I have troubles proving that the power series
$\sum_{n=1}^\infty n^3\frac{x^n}{n!}$
represents the function
$f(x)=e^x(x^3+3x^2+x)$.
My idea was using the identity theorem for power series and the definition of the Taylor series of a function to somehow show that the only function whose $n$-th derivative at $x=0$ equals $n^3$ is the aforementioned function, but right now I can't find the right arguments and I need some hints to point me in the right direction.

A: Hint:
$$
\frac{n^3}{n!}=\frac{n^2}{(n-1)!}=\frac{1}{(n-1)!}+\frac{n+1}{(n-2)!}=\frac{1}{(n-1)!}+\frac{3}{(n-2)!}+\frac{1}{(n-3)!}
$$

A: $\textbf{Using generating function method :}$
Define :
$$G[x,\lambda]=\sum_{n=0}^{\infty}e^{i\lambda n}_{} \frac{x^{n}_{}}{n!}=e^{x e^{i\lambda}}_{}.$$
Now note
$$\sum_{n=1}^{\infty}n^{3}_{}\frac{x^{n}_{}}{n!}=\sum_{n=0}^{\infty}n^{3}_{}\frac{x^{n}_{}}{n!}=\frac{\partial^{3}_{}}{\partial(i\lambda)^{3}_{}}G[x,\lambda]\Big|_{\lambda=0}^{}.$$


text:
Q: dask dataframe to_parquet throws error I am trying to save task dataframe to parquet on HDFS. However it fails with error :Exception: TypeError('expected list of bytes',)
I am also providing object_encoding argument as {"anomaly":"json","sensor_name":"json"}.
Here is the columns in dataframe: Index(['original_value', 'anomaly', 'anomaly_bin', 'sensor_name'], dtype='object')
Columns sensor_name and anomaly are string. Other columns are float.
eg: [18.0 'N' 0.0 'settemp']
I also tried to save it as CSV in HDFS but the api failed with error: Exception: ValueError('url type not understood:
Path to CSV as: hdfs://ip:port/some path
It will be great if some one can guide me in right direction.


text:
Q: Laravel interpreting a string in route as parameter I tried googling, but I can't phrase the question right, it is simple.
I have these 2 routes:
Route::get('admin_firme/{id_firma}/filijale/{id_filijala}', 'FilijalaAdminController@show');
Route::get('admin_firme/{id_firma}/filijale/create', 'FilijalaAdminController@create')

They call different controller actions. The problem is in the second route which calls the create method. The part /filijale/create is being interpreted as the parameter of the first route, thus calling the wrong method. How can I correct this?
I tried naming the route and generating an url to it, but it still calls the wrong method.

A: Just take the bottom one up ...
Route::get('admin_firme/{id_firma}/filijale/create', 'FilijalaAdminController@create');
Route::get('admin_firme/{id_firma}/filijale/{id_filijala}', 'FilijalaAdminController@show');

should work.

A: There's two things you can do. The first, and easiest, is to swap the order of them round so when checking matching routes it checks to see if it's create first, and if not anything else matches id_filijala.
The second thing you can do is use pattern matching for id_filijala, for example if it only contained numbers then you could use:
Route::get('admin_firme/{id_firma}/filijale/{id_filijala}', 'FilijalaAdminController@show')
    ->where('id_filijala', '[0-9]+');

You can use any regular expression in the where.


text:
Q: Working with Stellarium API I am having trouble integrating the Stellarium API with any IDE. I have tried Visual Studio 2013 and Qt Creator, and both seem to not recognize anything that has to do with Stellarium.
How do I get to a point where I can use all the classes and functions found in the Stellarium Developers Documentation and integrate them into my code?
The program I am trying to create is one which goes over a given list of dates and locations (on Earth) to output when and where a given object is seen high enough in the sky (Altitude of 30° minimum), during the night and with no moon interruption so that a successful observation could be made. For that, I need Stellarium and its functions.
Any ideas?

A: What I've done that worked was use a cmake GUI application to prepare the build, you just need to supply its dependencies and click in configure and generate, remembering to select the compiler from visual studio, like msvc 20.. 64 bits with opengl support. After that a visual studio project will be generated in the folder that you choose. When you open this project, to compile you just need to build the stellarium item on the list and after that, the install item. When it be done, just go to source's code folder and use the file install.iss, you must have installed the inno setup compiler.


text:
Q: Event-driven architecture and hooks in PHP I am planning on working on a game that has a PHP back-end to communicate with the data repository. I was thinking about it and concluded that the best design paradigm to follow for our game would be event driven. I am looking to have an achievement system (similar to the badges system of this website) and basically I would like to be able to hook these "achievement checks" into a number of different events that occur in the game. ie:
When a user does action X hook Y is fired and all attached functions are called to check against an achievement requirement.
In structuring the architecture like this I will allow for new achievements to be added easily as all I will have to do is add the checking function to the proper hook and everything else will fall into place.
I'm not sure if this is a great explanation of what I intend to do, but in any case I am looking for the following:

*

*Good reference material on how to code an event-driven application

*Code snippet(s) showing how to put a "hook" in a function in PHP

*Code snippet(s) showing how to attach a function to the "hook" mentioned in point 2

I have a few ideas as to how to accomplish 2) and 3) but I was hoping that somebody well-versed in the matter could shed some light on best practices.
Thank you in advance!

A: For PHP I've regulary integrated the Symfony Event Component: http://components.symfony-project.org/event-dispatcher/.
Here's a short example below, which you can find expanded in Symfony's Recipe section.
<?php

class Foo
{
  protected $dispatcher = null;

    // Inject the dispatcher via the constructor
  public function __construct(sfEventDispatcher $dispatcher)
  {
    $this->dispatcher = $dispatcher;
  }

  public function sendEvent($foo, $bar)
  {
    // Send an event
    $event = new sfEvent($this, 'foo.eventName', array('foo' => $foo, 'bar' => $bar));
    $this->dispatcher->notify($event);
  }
}

class Bar
{
  public function addBarMethodToFoo(sfEvent $event)
  {
    // respond to event here.
  }
}

// Somewhere, wire up the Foo event to the Bar listener
$dispatcher->connect('foo.eventName', array($bar, 'addBarMethodToFoo'));

?>

This is the system we integrated into a shopping cart to create a game-like shopping experience, hooking user actions into game-events. When the user performed specific actions, php fired events causing rewards to be triggered.
Example 1: if the user clicked a specific button 10 times, they received a star.
Example 2: when the user refers a friend and that friend signs up an event is fired rewarding the original referrer with points.

A:
Good reference material on how to code an event-driven application

You can either do this with "dumb" callbacks (Demo):
class Hooks
{
    private $hooks;
    public function __construct()
    {
        $this->hooks = array();
    }
    public function add($name, $callback) {
        // callback parameters must be at least syntactically
        // correct when added.
        if (!is_callable($callback, true))
        {
            throw new InvalidArgumentException(sprintf('Invalid callback: %s.', print_r($callback, true)));
        }
        $this->hooks[$name][] = $callback;
    }
    public function getCallbacks($name)
    {
        return isset($this->hooks[$name]) ? $this->hooks[$name] : array();
    }
    public function fire($name)
    {
        foreach($this->getCallbacks($name) as $callback)
        {
            // prevent fatal errors, do your own warning or
            // exception here as you need it.
            if (!is_callable($callback))
                continue;

            call_user_func($callback);
        }
    }
}

$hooks = new Hooks;
$hooks->add('event', function() {echo 'morally disputed.';});
$hooks->add('event', function() {echo 'explicitly called.';});
$hooks->fire('event');

Or implementing a pattern often used in event-driven applications: Observer Pattern.

Code snippet(s) showing how to put a "hook" in a function in PHP

The manual link above (callbacks can be stored into a variable) and some PHP code examples for the Observer Pattern.

A: Check out CodeIgniter as it has hooks built right in.
Simply enable hooks:
$config['enable_hooks'] = TRUE;

And then define your hook:
 $hook['post_controller_constructor'] = array(
                                'class'    => 'Hooks',
                                'function' => 'session_check',
                                'filename' => 'hooks.php',
                                'filepath' => 'hooks',
                                'params'   => array()
                                );

Then use it in your class:
<?php

    class Hooks {
        var $CI;

        function Hooks() {
            $this->CI =& get_instance();
        }

        function session_check() {
            if(!$this->CI->session->userdata("logged_in") && $this->CI->uri->uri_string != "/user/login")
                redirect('user/login', 'location');
        }
    }

?>


text:
Q: Using UIPageViewController to sign-up user I am working on the user sign-up part of an iOS app and I am trying to use page views to get user input. So, the first page view takes the user's first name, the next one takes takes last name, phone number. Then the user receives a verification code which is put in by the user in the next page view. Only when the verification code is correct the user is allowed to go to (swipe right) to the next page view.
The problem I am facing is that I am unable to trap the user input in the properties of my view controller which derives from UIPageViewController.
I am using :
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
NSUInteger index = [(SignupChildViewController *)viewController index];

    SignupChildViewController *current=(SignupChildViewController *)viewController;

    NSLog(@"%@", current.userCredentials.text);

    if(index==3)
    {
        firstPass=YES;
        if([verificationCodeUser isEqualToString:verificationCode])
        {
            verificationPassed=YES;
            index++;
        }
        else
        {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Oh snap!" message:@"You haven't entered the correct verification code." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
            return [self viewControllerAtIndex:index];
        }
    }
    if(index==3)
    {
        firstPass=YES;
    }

    index++;

    if (index == 6) {
        return nil;
    }

    [self updateInfo:index];
    return [self viewControllerAtIndex:index];
}

The updateInfo method looks something like this:
(void)updateInfo:(NSInteger)ind
{

    switch ([ind integerValue])
    {
        case 0:
            firstName=textview.text;
            break;
        case 1:
            lastName=textview.text;
            break;
        case 2:
            phoneNumber=textview.text;
            break;
        case 3:
            verificationCodeUser=textview.text;
            break;
        case 4:
            birthday=textview.text;
            break;
        case 5:
            password=textview.text;
            break;
    }
}

Here based on the index of the page, appropriate property is set. But the problem is that the property is sometimes getting set correctly, but at times it just gets an empty string in the textview even though the user has entered a string. How do I capture the user input while using pageviews?

A: viewControllerAfterViewController: is a bad place to call updateInfo: because you're assuming you've already transitioned to that index when it may not be the case. viewControllerAfterViewController: can be called during cases other than a successful transition.
Instead, try updating the info during the UIPageViewControllerDelegate methods pageViewController:didFinishAnimating:previousViewControllers:transitionCompleted: or pageViewController:willTransitionToViewControllers: so you know for sure the view has transitioned or will transition.


text:
Q: WPF window style not being applied I have a ResourceDictionary that contains Style definitions for controls used within my application.
All of the styles are applied properly to the controls in the window...but the style in the ResourceDictionary for the window itself is not being applied.
This is the XAML in my ResourceDictionary that contains the style that I want to apply to my window:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:primatives="clr-namespace:System.Windows.Controls.Primitives;assembly=PresentationFramework"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type Window}">
        <Setter Property="Background" Value="#FF121212"></Setter>
        <Setter Property="Height" Value="768"></Setter>
        <Setter Property="Width" Value="1024"></Setter>
    </Style>
<!-- .... -->
</ResourceDictionary>

This is the XAML for the window that I am working with (trying to get this style to apply):
<Window x:Class="TryingStyles"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TryingStyles">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/StylesDictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="12,12,0,0" Name="Label1" VerticalAlignment="Top" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="56,14,0,0" Name="TextBox1" VerticalAlignment="Top" Width="120" />
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <TabControl Height="206" HorizontalAlignment="Left" Margin="12,43,0,0" Name="TabControl1" VerticalAlignment="Top" Width="250">
                <TabItem Header="TabItem1" Name="TabItem1">
                    <Grid></Grid>
                </TabItem>
            </TabControl>
            <GroupBox Header="GroupBox1" Margin="268,43,12,12" Width="396"></GroupBox>
        </StackPanel>
    </StackPanel>
</Window>

It appears that the style for the window is applied when I view the window in the IDE's "Design view" but when I run the application the style is not applied.
Does anyone know what I'm doing wrong?

A: It's very strange that it works with the designer but not when the application runs.
The problem seems to be the TargetType of your Style. Wpf seems not be able to match the Window class with your derivated class TryingStyles.
Change your TargetType and it will work :
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:primatives="clr-namespace:System.Windows.Controls.Primitives;assembly=PresentationFramework"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:my="clr-namespace:WpfApplication1">
    <Style TargetType="{x:Type my:TryingStyles}">
        <Setter Property="Background" Value="#FF121212"></Setter>
        <Setter Property="Height" Value="768"></Setter>
        <Setter Property="Width" Value="1024"></Setter>
    </Style>
    <!-- .... -->
</ResourceDictionary>

A: It appears that there is no proper solution to your problem. TargetType in Styles doesn't manage derived types.
Here are two alternatives :
You can put a key in your style and apply the style to all your Windows.
    <!-- Resource file -->
    <ResourceDictionary ...>
        <Style TargetType="{x:Type Window}" x:Key="WindowDefaultStyle">
            <!-- .... -->
        </Style>
    </ResourceDictionary>

    <!-- Window file -->
    <Window Style="{DynamicResource ResourceKey=WindowDefaultStyle}">

Or you can use the BasedOn property of the Style.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:my="clr-namespace:WpfApplication1">
    <Style TargetType="{x:Type Window}" x:Key="BaseStyle">
        <Setter Property="Background" Value="#FF121212"></Setter>
        <Setter Property="Height" Value="768"></Setter>
        <Setter Property="Width" Value="1024"></Setter>
    </Style>

    <!-- Inherit from the BaseStyle and define for the MainWindow class -->
    <Style TargetType="{x:Type my:MainWindow}" BasedOn="{StaticResource ResourceKey=BaseStyle}" />
</ResourceDictionary>

A: I'm quite late to the party here, but I found a solution to have Style TargetType="{x:Type Window}" apply to every window application-wide, as one would expect. For the record, the reason this doesn't work is because each window you create is not a Window but a new type that derives from window (e.g. "MainWindow"), and Style's TargetType doesn't apply to derived classes. Anyway:
First, ensure your App.xaml has a Startup property defined; so inside the <Application> tag you'd add Startup="Application_Startup" or whatever you want to call the startup method.
Then, inside App.xaml.cs add:
private void Application_Startup(object sender, StartupEventArgs e)
{
    FrameworkElement.StyleProperty.OverrideMetadata(typeof(Window), new FrameworkPropertyMetadata
    {
        DefaultValue = Application.Current.FindResource(typeof(Window))
    });
}

where the method name matches whatever you listed as the Startup property in App.xaml. And of course, if you already have an existing startup method being run, just add the code contained within to that.
This basically just fixes it so that keyless Styles targeting "Window" will apply their changes to every window in your application, as you probably expected would occur without this code snippet. (That is of course assuming your style is already scoped application-wide, for example by containing it within a ResourceDictionary that is merged into App.xaml.)


text:
Q: Wordpress regular query not respecting sticky posts I have this query on my homepage and it works great except when I have sticky posts. The problem is that it should show only sticky posts (that are 30) and it show some of the last posts.
Also, the second page shows some of the sticky posts also.
What am I doing wrong here?
$paged = (get_query_var('page')) ? get_query_var('page') : 1;
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query('paged='.$paged.'&showposts=30&cat=-1,-4491&orderby=desc&page=$page');


text:
Q: how to get the recent uploaded file name I am parsing html document using Jsoup API in java. From the below shown html document i have filenames and time the file has created.
HTML document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">

  <meta name="GENERATOR" content="Microsoft SharePoint" />
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
   <title>
    ALL ELP REPORTS
</title>

  <link rel="shortcut icon" href=" " type="image/vnd.microsoft.icon" id="favicon" />
  <meta name="msapplication-TileImage" content=" " />
  <meta name="msapplication-TileColor" content="#0072C6" />

  <link rel="stylesheet" type="text/css" href=" " />
  <link id="CssRegistration1" rel="stylesheet" type="text/css" href=" " />
  <link id="CssRegistration2" rel="stylesheet" type="text/css" href=" 0" />

        <menu type="ServerMenu" id="zz1_ID_PersonalActionMenu" hideicons="true">
         <ie:menuitem id="zz2_ID_MyProfile" type="option" onmenuclick="" text="My Profile" menugroupid="100"></ie:menuitem>
         <ie:menuitem id="zz3_ID_Logout" type="option" onmenuclick="" text="Sign Out" description="Logout of this site." menugroupid="100"></ie:menuitem>
        </menu>
       <span id="zz4_Menu_t" class="ms-menu-althov ms-welcome-root" title="Open Menu" onmouseover="MMU_PopMenuIfShowing(this);MMU_EcbTableMouseOverOut(this, true)" hoveractive="ms-menu-althov-active ms-welcome-root ms-welcome-hover" hoverinactive="ms-menu-althov ms-welcome-root" onclick=" CoreInvoke('MMU_Open',byid('zz1_ID_PersonalActionMenu'), MMU_GetMenuFromClientId('zz4_Menu'),event,true, null, 0); return false;" foa="MMU_GetMenuFromClientId('zz4_Menu')" oncontextmenu="ClkElmt(this); return false;" style="white-space:nowrap"><a class="ms-core-menu-root" id="zz4_Menu" accesskey="/" href="javascript:;" title="Open Menu" onfocus="MMU_EcbLinkOnFocusBlur(byid('zz1_ID_PersonalActionMenu'), this, true);" onkeydown="MMU_EcbLinkOnKeyDown(byid('zz1_ID_PersonalActionMenu'), MMU_GetMenuFromClientId('zz4_Menu'), event);" onclick=" CoreInvoke('MMU_Open',byid('zz1_ID_PersonalActionMenu'), MMU_GetMenuFromClientId('zz4_Menu'),event,true, null, 0); return false;" oncontextmenu="ClkElmt(this); return false;" menutokenvalues="MENUCLIENTID=zz4_Menu,TEMPLATECLIENTID=zz1_ID_PersonalActionMenu" serverclientid="zz4_Menu">Bhavani BorraUse SHIFT+ENTER to open the menu (new window).

         <menu type="ServerMenu" id="zz5_FeatureMenuTemplate1" hideicons="true">
          <ie:menuitem id="zz6_MenuItem_ShareThisSite" type="option" onmenuclick="" description="See who's here and invite new people." menugroupid="100"></ie:menuitem>
          <ie:menuitem id="zz7_MenuItem_ViewAllSiteContents" type="option" iconsrc="" onmenuclick="STSNavigate2(event,'/_layouts/15/viewlsts.aspx');" text="Site contents" description="View all libraries and lists in this site." menugroupid="200"></ie:menuitem>
         </menu>
         Use SHIFT+ENTER to open the menu (new window).

        <input type="checkbox" class="s4-itm-cbx" />

          ECS-dailyTask

         <nobr>
          3/31/2013 11:04 AM
         </nobr>

         <input type="checkbox" class="s4-itm-cbx" />

           ECS-MontlhyTask

          <nobr>
           7/24/2016 10:09 PM
          </nobr>

         ASDF

java code:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
public class FileNamesRead {
    public static void main(String args[]) throws IOException {

        File input = new File("C:/htmlDocs/myDoc.html");
        Document doc = Jsoup.parse(input, "UTF-8");
        Elements tds = doc.select("div.ms-vb, .itx");
        for (Element td : tds) {
            System.out.println("The file class is: " + td.select("a").text());
        }

        Elements td1s = doc.select("nobr"); //select tag nobr
        for (Element td : td1s) {
            System.out.println("The date is: " + td.text());
        }
}

Output:
The file class is: ECS-dailyTask
The file class is: ECS-MontlhyTask
The date is: 3/31/2013 11:04 AM
The date is: 7/24/2016 10:09 PM

Expected output:
ECS-MontlhyTask

I want the latest uploaded filename to be returned instead of displaying all file names. How can i get the latest uploaded filename checked based on timestamp. Please advice. From my side i was trying to keep the file name and time in a List object, iterate compare the file associated time with Timestamp and return the latest file. Is there any better approach. My html document returns a huge list of filenames and its time(around 100+ filenames).


text:
Q: Routing issues in valorant Reason I'm sure it's routing issues is that I talked to riot support, makers of valorant, and after I gave them the ping plotter-results they told me to do a couple of things.
Restart the router then run some commands and disable IPv6, and try DNS. DNS did not work well but the rest yielded amazing results. I played 2 games after this and it was like I was playing a different game. Everything is smooth and I can take gunfights with people without a problem.
After this we are back to normal without me changing anything or restarting the pc or anything.
So. I'm pretty sure it's routing issues.
Also everything is new. Windows is updated. Drivers are updated. No FPS drops or packet loss, router is couple months old, internet speed is 33/6.5 and it seems stable, no overheating...etc And the basics like playing on ethernet and making sure that nothing is taking my speed...etc are covered. Overall nothing I can think of to reflect the problem.
What is the problem?
Best I can explain is that I think something happens resulting in my character freezing or 1-2 sort of lagging where I'm just sitting in place. I know for online FPS games there is a hundred things but like I said I ran tests and recorded my gameplay. Right after the fixes I was able to play normally.
But we revert back to the same old sluggish hell that makes me unable to play.
I did this twice as well, counting for placebo because it might be, and same thing. I even tried comparing results with others and it was a stark contrast between the average being 3-5 seconds to die and me dying in 1-2 seconds.
I also noticed that after doing what riot said I had pop ups of higher ping and network issues but things were smooth and I did not have those freezes, I did have higher ping. Those messages continued until my ping settled at a lower number and I did not get the messages and that's when problems were back.
Riot suggested I talk to my ISP but I'd like to know more about the issue and exactly what it is so I can try to explain it. Because you have to understand that where I'm only few have the knowledge and ability to solve my problems. The rest are expected to be braindead. I need to be able to explain it to my ISP like they are 5 all in the hopes that I might get a specialist on the phone.
Even then I should not count on my ISP at all. And obviously I don't want to restart my router, pc, and run commands every 2 games.
Edit: Router is: "ZXHN H168N V3.5" And I don't have money to upgrade it.
Game in question is valorant


text:
Q: Android 11: Broadcast Receiver don't catch incomming SMS My Broadcast Receiver don't work anymore, sice I have updated my tablet (Android 10 on Galaxy Tab Active 2). There was no update/change of the App. So I have no idea was is wrong now.
The Manifest is unchanged:
        <!-- SMS Receiver -->
        <receiver
            android:name=".services.sms.SMSReceiver_BroadcastReceiver"
            android:exported="true" >
            <intent-filter android:priority="999" >
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

The permission is still given:
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />

But the broadcast receiver don'T do its job:
public class SMSReceiver_BroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(SMS_RECEIVED)) {
               Toast.makeText(context, "SMS received", Toast.LENGTH_LONG).show();
        }
   ...

Where is the fault?
Is a Security Update responsible, for which I have to implemend additional code?

A: Old old question, but one of the first search results so figured I'd post an answer...
Android 11 couple things to be aware of:

*

*You can't make a 'toast' from a receiver anymore.  You will need to find another method for feedback - like pushing a notification, or if that is just for debugging than using the Log mechanism

*Need to add a new intent-filter action:  android.provider.Telephony.SMS_DELIVER


text:
Q: Can I rely on it that every single update statement in postgresql is atomic? I read some materials before saying that each update statement in postgresql is atomic.
For example,
update set column_1 = column_1 + 100 where column_2 = 10;

Even though I have multiple processes calling the update simultaneously, I can rely on it that they will happen in sequence because each update is atomic behind the scene and the "read_modify_write" cycle is encapsulated in a bundle.
However, what if the update statement looks like the following:
update set column_1 = myFunction(column_1) where column_2 = 10;

Here, myFunction() is a stored procedure created by me.In this function, I will apply different math operations to column_1 depending on its amount. Something like:
    if(column_1 < 10):
            // do something
    else if (column_1 < 20):
            // do something
    else
            // do something

In this case, when the single update statement contains self-defined function, does it remain atomic?

A: OK, @Schwern's knowledge of Perl may well be world class but as regards PostgreSQL transactions, I can correct him :-)
Every statement in PostgreSQL is executed within a transaction, either an explicit one you BEGIN/COMMIT yourself or an implicit one wrapping the statement. For the duration of a statement you will see a stable view of the entire database.
If you write myFunction as an in-database custom function in pl/pgsql or some such then it too will be in the same transaction as the statement that calls it. If it doesn't run its own queries, just operates on its parameters then you don't need to think any further.
If you are reading from tables within your function then you will need a passing familiarity with transaction isolation levels. In particular, make sure you understand what "read committed" implies about seeing other processes' activities.
The blog article you refer to is discussing performing operations outside of the database. The solution it proposes is exactly what you are asking about - an atomic update.

A: The update, subqueries, and queries in function calls should all see a consistent view of the data.
From Chapter 13. Concurrency Control.

Internally, data consistency is maintained by using a multiversion model (Multiversion Concurrency Control, MVCC). This means each SQL statement sees a snapshot of data (a database version) as it was some time ago, regardless of the current state of the underlying data. This prevents statements from viewing inconsistent data produced by concurrent transactions performing updates on the same data rows, providing transaction isolation for each database session.

What that means, I believe, is for each statement Postgres keeps a version of the data. Each statement sees a consistent version of the database for the entirety of its run. That includes sub-queries and function calls.
This doesn't mean you don't have to think about concurrency. It just means that update will see consistent data.


text:
Q: java script form validation wrong I have tried first time java script validation, i have done individually each field, when it comes to multiple fields,its not working,what steps i need to follow when i validate the can any one help me?

     <form action="https://www.youtube.com" name=" " onSubmit=" return validation()">

    <fieldset>
    Validation Form
        Name :      <input type="text"  name="name" id="myname">

        Password : <input type="password" name="password" id="password">

               <input type="radio" id="male" name="gender"> Male
               <input type="radio" id="female" name="gender"> Female

        <input type='submit'  value='mysubmit'>

    </fieldset>

     </form>

A: var myname=document.getElementById("myname").value;
var password=document.getElementById("password").value;
var male=document.getElementById("male").checked;
var female=document.getElementById("female").checked;
var flag = true;

// text box validation
    if(myname==""){
        alert("please enter name");
        flag = false;
    }
   else if(password==""){
        alert("please enter password");
        flag =false;
    }
   else if(male==false && female==false){
        alert("please choose gender");
        flag = false;
    }
    // returning value
    if(flag){
        return true;
    }else
    {
        return false;
    }

JS Fiddle

A: you can do this with alot less code by using preventDefault and checking for empty values/clicked radios:
$("input[type=submit]").click(function(e){

  if($("#myname").val() == ""){
    e.preventDefault();
    alert("Name cant be empty")
  }

  if($("#password").val() == ""){
    e.preventDefault();
    alert("Password cant be empty")
  }

  if(!$("input[type=radio]").is(":checked")){
    e.preventDefault();
    alert("Gender cant be empty")
  }

 });

FIDDLE

A: Why are you complicating things for yourself... Don't use javascript validation until and unless you are validating the data of fields. if the concern is only that the fields must be made compulsory..
 you can user the required = "required" attribute of the tags.
All browsers support it...

A: jmore009 already gave a good answer, but it had some issues.
Here is a better FIDDLE, made as an update to jmore009's solution.
$("input[type=submit]").click(function(e){

  if(!$("#myname").val().trim()){
    e.preventDefault();
    alert("Name can't be empty")
  }

  if(!$("#password").val().trim()){
    e.preventDefault();
    alert("Password can't be empty")
  }

    if(!$("input[type=radio]").is(":checked")){
    e.preventDefault();
    alert("Gender can't be empty")
  }

});

And in case you don't know, include scripts right before the  tag. Otherwise JavaScript might not find necessary DOM elements due to different load time.


text:
Q: use drop down value to run query without submit <form name = "rsPass" action="<%= pagePath %><%= jspPageName %>.jsp?callrspassthru=true" method="post">

         FCAT Scores by Teacher by Course with Gains and Years Growth

            This report will list all teachers, courses, and student's FCAT scores with gains.

        Active or Inactive Teachers:

        <select name="active">
        <option value="">           Select
 </option>
        <option value="IS NULL">    Active
 </option>
        <option value="IS NOT NULL">Inactive
 </option>
        </select>

            First letter of teacher's last name:
 <%

 out.println(request.getParameter("active"));
 // both of these values are NULL as if they are not being read when the drop down is selected above

    Statement db1 = con.createStatement();
    int newRecords1 = 0;

    SQL1 = " SELECT DISTINCT substring(i.lastName, 1, 1) as grade " +
    " FROM employmentAssignment e with(nolock)  " +
    " JOIN calendar c with(nolock) on c.schoolID = e.schoolID " +
    " JOIN person p with(nolock) on p.personID = e.personID " +
    " JOIN [identity] i with(nolock) on i.identityID = p.currentIdentityID and i.personID = p.personID " +
    " WHERE c.calendarID = " + calID + "" +
    " AND e.enddate is " + request.getParameter("active") + "" +
    " AND e.teacher = 1 " +
    " ORDER BY substring(i.lastName, 1, 1) ";

    result1 = db1.executeQuery(SQL1);

    out.println("<select name=grade id=15 onchange='loadStudents()'><option value='NULL' selected='true'>Select</option>");
    while(result1.next()) { grade=result1.getString(1); out.println("<option value='"+grade+"'>"+grade+"</option>");}
    out.println("</select>");

    con.close();

%>


text:
Q: Problem with comments_number() The following code:
echo '
';
while ( $query->have_posts() ) {
    $query->the_post();

    $title = get_the_title();
    echo '
' . $title . comments_number() . '
';
}
echo '
';

moves the comments ABOVE and outside of the
 like this:
1 Comment

Hello world!

A: You want to use get_comments_number() as that doesn't echo the results, while comments_number does echo


text:
Q: (gnome-control-center:24694) | bluethoot & App error | When I was trying to open settings nothing happened. So I have reinstalled the data packages with apt-get install --reinstall gnome-control-center. When I tried to manually search for settings, I could not find it so I had to run it from the console with gnome-control-center display.
I have opened the console, but every time I select the Bluetooth and apps settings I get the following errors:
BT:
(gnome-control-center:24694): Bluetooth-WARNING **: 08:58:31.260: Error setting property 'Discoverable' on interface org.bluez.Adapter1: GDBus.Error:org.freedesktop.DBus.Error.UnknownObject: Method "Set" with signature "ssv" on interface "org.freedesktop.DBus.Properties" doesn't exist (g-dbus-error-quark, 41)
Apps:
cc-applications-panel-Message: 08:54:40.704: No permissions store proxy yet, come back later
Any ideas on how to resolve these errors?


text:
Q: Minify - Composer install error I am trying to install from a composer.json file using composer install in the right directory but I am getting this error:
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package scrapbook/psr-cache could not be found in any version, there may be a typo in the package name.
  Problem 2
    - The requested package satooshi/php-coveralls dev-master exists as satooshi/php-coveralls[0.1.0, 0.2.0, 0.3.0, 0.3.1, 0.3.2, 0.4.0, 0.5.0, 1.0.x-dev, 1.1.x-dev, 2.0.x-dev, v0.6.0, v0.6.1, v0.7.0, v0.7.1, v1.0.0, v1.0.1, v1.0.2, v1.1.0, v2.0.0] but these are rejected by your constraint.

A: You have some problems:
1) There isn't any package named scrapbook/psr-cache inside packagist
2) satooshi/php-coveralls hasn't a valid version into your composer.json
I advise you to change the package psr-cache with one valid and fix the php-coveralls version
The composer error is very clear in this.
If you want to check for all valid package please refer to this:
Packagist


text:
Q: "I recently heard that"? Do I need to treat the phrase "I recently heard that" as a reported speech?

"I recently heard that you went to Paris in 2000."

I'm not sure if this phrase can be completed by using simple past since I'm referencing a specific time (2000), or if this phrase should be treated as a reported speech and therefore be completed with past perfect, like this:

I recently heard that you had gone to Paris in 2000."

It seems like I can treat this phrase as a reported speech because I am talking about something I heard from someone, but I'm not sure which sentence is more grammatically correct and sounds more natural.

A: You can replace I recently heard that ... with an expression such as John told me yesterday that ..., so this can be regarded as an instance of reported speech.
As to the tense, it is possible you have learned some rules about backshift  which makes you uncertain which tense to use in the reported clause. Swan, in Practical English Usage, has some useful advice here:

Words that are spoken or thought in one place by one person may be
  reported in another place at a different time ... . Because of this,
  there are often grammatical differences between direct and indirect
  speech. These changes are mostly natural and logical, and it is not
  necessary to learn complicated rules about indirect speech in English.

So if Mary told you:

John went to Paris in 2000

you would naturally report this back to John as:

I recently heard that you went to Paris in 2000.

The past perfect is used to emphasise that something happened before another past event. So this is possible:

I recently heard that you had gone to Paris for a few months in 2000
  before starting your new job.

But even here I suspect that most native speakers would use the simple went.

A: Good question! In the example you gave, the same rules we use for reported speech apply here. You need to keep in mind the tense shift, which you mention with the past perfect. However, remember that the simple past is often left in the simple past, even when we report it.
What really matters is whether there is a cause and effect relationship between the actions in the past. Is there some outcome of his or her having gone to Paris in 2000? That is:

"I recently heard that you had gone to Paris in 2000, so you weren't interested in this year's trip."

vs.

"I recently heard that you went to Paris in 2000. What was it like?"

In the first sentence, there is a focus on the outcome of going to Paris, while in the second sentence, there is not. The focus is on the action itself.
This is a tricky part of reported speech, but it's quite important. The same thing happens with the past progressive, which can be reported as the past progressive or the past perfect progressive.

A: "I recently heard that you went to Paris in 2000" is fine.
There is no need for a past participle because reported speech doesn't establish that kind of relationship between two events grammatically!
Of course the event of hearing about the trip is causally connected to the trip. Because one person went on a trip, there is a chain of events which leads to the other person hearing about it, years later. However, the causal chain only exists if the report is true! It is possible to hear about someone having gone to Paris in 2000, such that the report is fabricated, exaggerated or mistaken. It could have the wrong year, the wrong person, the wrong city.
It may help to study this sentence:

The reason I recently heard that you went to Paris in 2000 is that you had, in fact, gone to Paris in 2000".

"that you went to Paris in 2000" is reported speech, and so it exists in a kind of bubble which is causally disconnected to receiving the speech: it's a quoted idea which may or may not be true, and so isn't considered in a causal relation to real events, like receiving the report.
But "that you had, in fact, gone to Paris in 2000" is not reported speech: it is the reason why the speaker received the reported speech and so it is connected to the report.
Also, another example for good measure:

I heard that you went to Paris in 2000. And so I did some digging and confirmed that, in fact, you had gone to Paris in 2000.


text:
Q: Confusion about the total bound charge of a sphere placed in dielectric There is a solved exercise in which a charged sphere of radium $r=a$ is inside a dielectric material. The surface bound charge and the volume bound charge are respectively:
$$p_{sp}=\vec{P}\cdot \hat{n}|_{r=a},\quad p_{vp}=-\nabla \cdot \vec{P}$$
where the polarization $P$ is known.
The exercise says that the total bound charge is:
$$Q_{T}=\int_{S}p_{sp}dS+\int_{V}p_{vp}dV=f(\epsilon_{r},q)\neq 0$$
But for the total bound charge it is true that:
$$Q_{T}=\int_{S}p_{sp}dS+\int_{V}p_{vp}dV=\oint_{S} \vec{P}\cdot \hat{n}dS-\int_{V}\nabla \cdot \vec{P}dV=0$$
How can this be when the total bound charge should always be equal to 0?

A: The integral over the total surface bound charge , inner and outer, of the dielectric is zero. Equivalently, the volume integral of the bound charge is zero. It is not a good idea to mix surface and volume integrals to avoid double counting.

A: You are right that net charge of a neutral dielectric body that is just polarized by external electric field is zero. However, this follows from the assumption just stated, not from any such calculation as you did.
The integrals can be assigned various values depending on where the integration surface is placed. If the integration surface is inside the dielectric, there is no single meaning to "bound charge associated with the surface", because one can mean 1) charge inside the surface or 2) charge of molecules associated with the region inside the surface (which include the surface contribution). These two interpretation do not have same value, and they are not in general zero.
You should really ask the source of the exercise what they mean, or elaborate on the exercise in the question. There is nothing there suggesting the dielectric body should have net non-zero charge.

A: Dielectrics are electrically neutral as they have no free electrons, which would otherwise make them a conductor. So the total charge should be zero with the surface and volume bound charges cancelling. When it says:
$Q_T = f(\epsilon_r,q)$
does the $q$ perhaps stand for the charge and is a more general expression applicable for non-dielectrics?


text:
Q: Reference an object's parent ruby rails I have an Opportunity model that has Links as a nested resource. I wrote a callback so that whenever I add a new link, the built-in "updated_at" attribute for my model opportunity is updated to equal Time.now. However, I'm not sure how to reference the Opportunity model. I want to do something like this:
This is what I would put in my Link model, which is a nested resource of my Opportunity model:
class Link < ActiveRecord::Base
belongs_to :opportunity

after_save :update_updated_at

def update_updated_at
  @opportunity.updated_at = Time.now #this line is where I am unsure of how to reference the link's Opportunity parent
end
end

Thanks!

A: Links in ActiveRecord are always accessed through method names. There is no instance variable called @opportunity, so that's equivalent to calling updated_at= on nil.
What you probably want is:
def update_parent
  return unless (self.opportunity)

  self.opportunity.updated_at = Time.now
  self.opportunity.save
end

From an implementation perspective this is a little rude as the Link object is bossing around the Opportunity one. That's usually something a controller should be doing.

A: If a Link object @link belongs_to an Opportunity object @opp, you can find @opp if you know @link via the ActiveRecord relation opportunity. See http://guides.rubyonrails.org/association_basics.html for more details.
Given a link record, find the parent opportunity record:
@opp = @link.opportunity
So you could write self.opportunity.updated_at = Time.now


text:
Q: How to initialize a variable with a lifetime? I have following code and don't know how to get it working:
fn new_int<'a>() -> &'a isize {
    &5
}

fn main() {
    let x = new_int();
}

Or another attempt:
fn new_int<'a>() -> &'a isize {
    let a: &'a isize = &5;
    a
}

fn main() {
    let x = new_int();
}

A: An alternative way of understanding why
fn new_int<'a>() -> &'a isize {
    &5
}

can't work is as follows. 'a is a lifetime parameter of the function; that is, it is the caller who chooses the actual value of this parameter, not the function itself. For example, the caller can choose 'static lifetime:
let i: &'static isize = new_int();

However, &5 can not have the 'static lifetime so the function is rejected.
In other words, such declaration essentially says "I can give you a reference of any lifetime you want". Naturally, this is only valid if the reference returned from the function is of 'static lifetime, which is the largest lifetime possible. That's what DK. is telling about, by the way.

A: Lifetimes only describe what the code is already doing. They don't affect behavior of the code in any way.
They're not an instruction to make something live as long as required, but a consistency check that ensures the code actually does what is says it does.
In fact, Rust strips all lifetimes from the code after checking them, and then compiles the code without any knowledge of lifetimes.
Variables are destroyed at the end of their scope, and that is their lifetime. You can't say declare that they're not doing this.

A: You can't. A lifetime parameter does not allow you to choose how long a value lives, it only allows you to communicate to the compiler that two or more references are "related" to the same memory and are expected to share the same lifetime.
A function (like new_int in your case) can allocate memory in two ways:

*

*locally in an area that is allocated to the function itself and is destroyed when you return from the function (the stack)

*dynamically in an area of memory that is common to all functions (the heap)

A reference (&) is a pointer to an area of memory. It can point to the local stack, or to the heap. Since dynamic allocations are much more expensive in terms of performance than writing on the stack, Rust uses the stack by default (you have to use a Box to perform a dynamic allocation).
So, in a nutshell, this is why your code is illegal:
fn new_int<'a>() -> &'a isize {
    let a: &'a isize = &5; // write 5 on the function's local stack
    a // return a pointer to that area of memory
} // the function ends and its stack (where I wrote 5) is destroyed
  // so the pointer I'm trying to return is no longer valid

You can either return the value
fn new_int() -> isize {
    5
}

fn main() {
    let a = new_int(); // the value 5 (not a pointer) is copied into a
}

or perform a dynamic allocation (which is overkill in case of an isize but might make sense if you're actually working with a big structure)
fn new_int() -> Box<isize> {
    Box::new(5) // a Box allocates memory and writes in the heap
}

fn main() {
    let a = *new_int();
}

alternatively, you can allocate memory outside of the function and mutate it in the function. You don't typically do it for a primitive type, but it makes sense in some scenarios (e.g. streaming of data):
// new_int does not return anything. Instead it mutates
// the old_int in place
fn new_int(old_int: &mut isize) {
    *old_int = 5;
}

fn main() {
    let mut a = 2; // memory for an int is allocated locally
                   // in main()
    new_int(&mut a); // a mutable reference to that memory is passed
                     // to new_int, that overwrites it with another value
}

As @dk mentions in the comment below,, in this specific case (i.e. your function always returns 5 or some other statically known value, not something calculated dynamically by the function) you can also return a reference with a 'static lifetime:
fn new_int<'a>() -> &'a isize {
    static FIVE: isize = 5;
    &FIVE
}

You can read more about 'static in the Rust Reference.
As of Rust 1.21, this "static promotion" is now performed for you automatically and your original code compiles. It creates the equivalent of the static FIVE.


text:
Q: How can i display form data in echo php? How can i display form data in echo php ?
My code is:
<?php
    echo " Bust:
    <?php
        echo $_POST["bust"];
    ?>

 Waist:
    <?php
        echo $_POST["waist"];
    ?>

 	";
?>

But this doesn't work, please guide me with correct steps.

A: There are a lot of problems with your code.

*

*You're using " in $_POST["bust"] but you opened echo with " as well, causing a conflict.

*You're using <?php instead an echo... which is already PHP. There's no need to do this.

It is best to isolate variable printing from your code. Use string concatenation with . as such:
echo " Bust: ".$_POST["bust"]."
 Waist: ".$_POST["waist"]."
 	";


text:
Q: How to add watermark to an image in unity? I was following this solution Unity watermark on image after screenshot to add watermark to the image but it does not go forward from a line. I am using unity 2018.3.8f. If someone can help it is the matter of my job I am stuck in this for five days.
Color[] whatermarkPixels = whatermarkTexture.GetPixels();

A: Most probably you get the same error as the OP of the linked question, Something like

texture not readable, the texture memory cannot be accessed from scripts. You can make the texture readable in the texture import settings

Just as it says you have to mark that texture as readable. Otherwise GetPixels fails.
For the one you have as an image file (the watermark) you can do it via the  Import Settings simply enable the Read/Write Enabled option and hit Apply


text:
Q: Добавление параметров метода в запрос Spring JPA Имеется приложение на Spring Boot'е, БД PostgreSQL.
Пытаюсь отправить следующий запрос в БД:
    @Query(value = "select ROW_number() over() as id" +
        ", count(P.\"Id\") AS winsCount" +
        ", sum(P.\"Price\") AS contractSum" +
        ", count(H.\"Id\") AS guarCount" +
        ", sum(H.\"Value\") as guarSum" +
        " from \"Protocols\" AS P" +
        " left join \"HtmlItemsValues\" AS H" +
        " ON P.\"HtmlItemId\" = H.\"HtmlItemId\"" +
        " AND H.\"Type\" = 2" +
        " WHERE (P.\"Price\" <= :p1 or :p1 is null)" +
        " AND (P.\"Price\" >= :p2 or :p2 is null)" +
        " AND (H.\"Value\" <= :p3 or :p3 is null)" +
        " AND (H.\"Value\" >= :p4 or :p4 is null)" +
        " AND (P.\"Dt\" <= :p5 or :p5 is null)" +
        " AND (P.\"Dt\" >= :p6 or :p6 is null)", nativeQuery = true)
WinInfo getFilteredInfo(@Param("p1") Long minContrSum, @Param("p2") Long maxContrSum, @Param("p3") Long guarMinSum
                        , @Param("p4") Long guarMaxSum
                        , @Param("p5") LocalDate dateBefore, @Param("p6") LocalDate dateAfter);

В БД уходит следующий запрос:
select ROW_number() over() as id, count(P."Id") AS winsCount, sum(P."Price") AS contractSum, count(H."Id") AS guarCount, sum(H."Value") as guarSum from "Protocols" AS P left join "HtmlItemsValues" AS H ON P."HtmlItemId" = H."HtmlItemId" AND H."Type" = 2 WHERE (P."Price" <= ? or ? is null) AND (P."Price" >= ? or ? is null) AND (H."Value" <= ? or ? is null) AND (H."Value" >= ? or ? is null) AND (P."Dt" <= ? or ? is null) AND (P."Dt" >= ? or ? is null)

Соответственно Spring JPA не видит параметры, передаваемые в запрос, и кидает исключение:
org.postgresql.util.PSQLException: ERROR: operator does not exist: double precision <= bytea

A: В общем проблему решил создав функцию в БД, которая в качестве аргумента принимает строку, в строке уже передаю json. С передачей в БД null значений, увы, так и не смог найти решение.


text:
Q: Using SDL_BlitScaled to created scaled copies of surfaces So I'm working on some SDL2 Wrapper stuff, and I'm trying to use SDL_BlitScaled to copy the data in a src surface into a destination surface which I've already created, like so
SDL_Surface *loaded = IMG_Load("test.png");
SDL_SetSurfaceBlendMode(loaded, SDL_BLENDMODE_NONE);
SDL_Surface *out = SDL_CreateRGBSurface(0, 100, 100, loaded->format->BitsPerPixel,
                                        loaded->format->Rmask, loaded->format->Gmask, loaded->format->Bmask, loaded->format->Amask);
SDL_BlitScaled(loaded, NULL, out, NULL);
SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, out);
SDL_Rect rec = {10, 10, 110, 110};
SDL_RenderCopy(ren, tex, NULL, &rec);

Don't worry about my renderer or window etc. I've isolated the problem to somewhere in this code. The image does not appear on the screen, however it does if I create a texture from the loaded surface. Thoughts? I imagine I'm misusing either CreateRGBSurface, or BlitScaled (I did see another question about this, however the solution was unclear).

A: For me I had to do:
SDL_SetSurfaceBlendMode(loaded , SDL_BLENDMODE_NONE);
SDL_SetSurfaceBlendMode(out, SDL_BLENDMODE_NONE);

For it to work, otherwise some strange blending happens.
The docs page for this function says:

To copy a surface to another surface (or texture) without blending with the existing data, the blendmode of the SOURCE surface should be
  set to 'SDL_BLENDMODE_NONE'.

So setting loaded is probably enough.
Edit: In the end I came up with this:
struct FreeSurface_Functor
{
    void operator() (SDL_Surface* pSurface) const
    {
        if (pSurface)
        {
            SDL_FreeSurface(pSurface);
        }
    }
};

typedef std::unique_ptr<SDL_Surface, FreeSurface_Functor> SDL_SurfacePtr;

class SDLHelpers
{
public:
    SDLHelpers() = delete;

    static SDL_SurfacePtr ScaledCopy(SDL_Surface* src, SDL_Rect* dstSize)
    {
        SDL_SurfacePtr scaledCopy(SDL_CreateRGBSurface(0,
            dstSize->w, dstSize->h,
            src->format->BitsPerPixel,
            src->format->Rmask, src->format->Gmask, src->format->Bmask, src->format->Amask));

        // Get the old mode
        SDL_BlendMode oldBlendMode;
        SDL_GetSurfaceBlendMode(src, &oldBlendMode);

        // Set the new mode so copying the source won't change the source
        SDL_SetSurfaceBlendMode(src, SDL_BLENDMODE_NONE);

        // Do the copy
        if (SDL_BlitScaled(src, NULL, scaledCopy.get(), dstSize) != 0)
        {
            scaledCopy.reset();
        }

        // Restore the original blending mode
        SDL_SetSurfaceBlendMode(src, oldBlendMode);
        return scaledCopy;
    }
};


text:
Q: OpenCV blur creating linesblob like areas I'm using OpenCV with a very high kernel (50 and higher) to get a very exaggerated blur effect.
I am getting these weird line/area like effects on the generated imagery. Please refer to the wall area on the image below.
Is this something that is inherent to blurring at a very high kernel size?
What would be some techniques to smooth out and eliminate this effect?
I am using OpenFrameworks with the ofxCV addon. The relevant part of my code is just
 blur(camScaled, 51);

If you are not familiar ofxCV is essentially a bridge and maps back to this OpenCV call in the end.
CV_EXPORTS_W void blur( InputArray src, OutputArray dst,
                    Size ksize, Point anchor=Point(-1,-1),
                    int borderType=BORDER_DEFAULT );

A: This effect is pretty normal because blurring means averaging the pixels value through the Kernel.
You should try an edge-preserving filter such as bilateral filter.
If you still want to use a "classic" blur you could try the median blur instead of mean blur, that should give you at least a more attenuated result.


text:
Q: Bash script TAR by Filetype is not gzipping the specified filetypes on recursive command Simply put, I did an exhaustive library update on my network to be compatible with XBMC. Now that it's done, I thought it wouldn't hurt to periodically make a backup of the nfo,bub,srt,jpg,tbn files (everything except any video file) that are in the various directories and subdirectories in my TV Shows folder. I also wanted to zip it by date. After playing around, I got this to semi-work:
find '/volume2/MyMedia/TV Shows/' -type f \( -name \*\.sub -o -name \*\.srt -o -name \*\.nfo -o -name \*\.jpg -o -name \*\.tbn \) -print0 | xargs -0 tar -pvczf '/volume2/Backups/XBMC Backups/'XBMC-TVShows-NFO-JPG-TBN-SUB-Backup-$(date +%m-%d-%y).tar.gz

It goes through the motions (scanning every directory and finding the files), and I see the zip file grow, but then suddenly the tar.gz goes down to 0 bytes and counts up again. I think it's doing that once it hits a new directory to scan.
At the end, I get a 1.8MB file with only the last directory it scanned through. Inside that, is almost everything, except it omitted 1 of the subdirectories. IE: It zipped up '30 Rock' and all of the files I specified, but, it did that for all folders except Season 2.
So I am at a loss. Everything looks clear to me in the code. For some reason it's not running properly. I think I have tunnel vision on the project now. A fresh set of eyes would be magnificent!
Here is an output: http://pastebin.com/ywctQ5Sf
Here is what the final tar.gz contained: http://s23.postimg.org/6pc22h7yz/output.png
Final note: The directories of the shows that it backs up do have whitespaces in them. So there is a directory structure like so:
>volume2
->MyMedia
-->TV Shows
--->Fullmetal Alchemist Brotherhood
---->Season 1
----->Fullmetal Alchemist Brotherhood.S01E01.Fullmetal Alchemist.nfo

Thank you for any help!

A: That's because xargs splits the huge list of files across multiple tar commands, which each try to create a new file. Try using the -A option instead of -vczf ... and pipe the whole command to gzip:
find ... -print0 | xargs -0 tar -A | gzip - > "....tar.gz"

A: So after revisiting this, I tried l0b0's method. It comes back with:
tar: Options `-Aru' are incompatible with `-f -'

So I looked into another way and came up with this script:
#!/bin/bash
find /volume1/Media/TV\ Series/ -iname "*.sub" -exec tar rvfP /volume1/Backups/TestBackup.tar {} \;
find /volume1/Media/TV\ Series/ -iname "*.srt" -exec tar rvfP /volume1/Backups/TestBackup.tar {} \;
find /volume1/Media/TV\ Series/ -iname "*.nfo" -exec tar rvfP /volume1/Backups/TestBackup.tar {} \;
find /volume1/Media/TV\ Series/ -iname "*.jpg" -exec tar rvfP /volume1/Backups/TestBackup.tar {} \;
find /volume1/Media/TV\ Series/ -iname "*.tbn" -exec tar rvfP /volume1/Backups/TestBackup.tar {} \;
gzip /volume1/Backups/TestBackup.tar

It takes a long time, but I let it run in the middle of the night when nothing else is going on, and it works. I only need to run this backup very infrequently anyway.
If you were so inclined, you can also add an elapsed timer:
#!/bin/bash
date1=$(date +"%s")
# Script stuff here. Uncommented...
date2=$(date +"%s")
diff=$(($date2-$date1))
echo "$(($diff / 60)) minutes and $(($diff % 60)) seconds elapsed."


text:
Q: all possible combinations of bits given n max length and a known count of 1 bits I'm attempting to roll my own compression algorithm as an experiment. For part of my solution I need to count the number of 1 bits in the input bytes. Input bytes are currently required to be 8 bytes or 64 bits long. This would imply that I could have a count of 1 bits from zero up to 64.
What I'm struggling to understand and calculate is the max number of combinations I might run into with this approach?
Example 1:
1 bits count = 1
this would imply that there are 63 zero bits
meaning there are 64 total combinations in this scenario
What I'm not understanding
What happens when there are 32 one bits? My approach so far was simply multiplication: so for 32 one bits and 32 zero bits (remember we have a 64 bit max) so 64 x 32 = 2048.
Is this math correct?
This honestly seems too low but I'm just not sure. What's further confusing about this is how the fact that I know the number of 1's and zeroes but not their exact position, how that reduces the max possible combinations. Clearly if this was a simple how many total combinations are in 64 bits, that would be 2^64, which is a huge number. Giving me the doubt that my previous math is accurate.

A: This is a problem in combinations. You have 64 positions and want to choose 32 of them to place the 1 bits. The choices cannot have any repetition, and the order of the choices does not matter. That makes it a combinations problem.
The answer is the binomial coefficient of 64 over 32, which can be calculated by the formula
64! / (32! * (64-32)!)

where the exclamation point is the factorial function.
The calculated result is
1832624140942590534

which is much larger than your attempted answer.
For just one bit, the result is binomial 64 over 1, which indeed is 64, so you got that right. There are many packages in many computer languages that can calculate binomial coefficients.
Note that this is more of a mathematics question than a programming one. Since this does come directly from a programming issue, I did not just direct you to the Mathematics Stack Exchange, but in the future you should ask such questions there.


text:
Q: Excel 2013 - "Cannot complete this task with available resources" We have a Windows 7 workstation running Office 2013 that receives the following error when using Office files from a network share.

Excel cannot complete this task with available resources. Choose less
  data or close other applications. Continue without Undo?

MS Office has been uninstalled / re-installed.
I have followed this microsoft KB:

*

*All latest Updates have been installed.

*Preview/Details pane has been disabled.

*The PC has 8 GB of memory.

Below is a screenshot of PowerPoint. While working on files the ribbon loses its buttons.


text:
Q: Criar procedure no phpmyadmin Estou tentando criar um procedure que altera entre insert e update no phpmyadmin mas me retorna um erro na linha do if EXISTS, depois tentei criar pelo painel grafico e me retorna erro na ultima linha sempre... Alguém sabe oque está errado?
Erro quando tento pelo painel(Sem sql)

Erro quando tento por sql

Query
CREATE PROCEDURE SEND_ITEMS(
  IN i_item_id int(11),
  IN i_customer_id VARCHAR(11),
  IN i_quantity SMALLINT)
  AS
  BEGIN
  IF(EXISTS(SELECT item_id,customer_id FROM wpcheap_items_selected WHERE (item_id = i_item_id AND customer_id = i_customer_id)))
 THEN Update wpcheap_items_selected SET quantity = i_quantity WHERE (item_id = i_item_id AND customer_id = i_customer_id)
 ELSE
   INSERT INTO wpcheap_items_selected(item_id,customer_id,quantity) VALUES (i_item_id, i_customer_id, i_quantity)
END

A: Você possui vários erros de sintaxe nessa procedure, segue o código correto:
Faltavam alguns ;
DROP PROCEDURE IF EXISTS SEND_ITEMS;
DELIMITER |
CREATE PROCEDURE SEND_ITEMS(
        IN i_item_id int(11),
        IN i_customer_id VARCHAR(11),
        IN i_quantity SMALLINT
)
BEGIN
    IF(EXISTS(SELECT item_id,customer_id FROM wpcheap_items_selected WHERE (item_id = i_item_id AND customer_id = i_customer_id))) THEN

        UPDATE wpcheap_items_selected
            SET quantity = i_quantity
        WHERE (item_id = i_item_id
            AND customer_id = i_customer_id);

     ELSE

         INSERT INTO wpcheap_items_selected(
                item_id,
                customer_id,
                quantity)
        VALUES (
                i_item_id,
                i_customer_id,
                i_quantity);

    END IF;
END
|
DELIMITER ;


text: Q: Deploy war with two web.xml For some application was build a war with two web.xml files inside. I want to deploy that application in different servers, on of that being Jetty and other GlassFish for instance. For Jetty I try to deploy in jetty.xml, and I want it to load both web.xml descriptors files. It would be useful at least some tips for that. This question I consider that is a general one and I will not provide a concrete code for it.


text:
Q: HTML5 Canvas - text not written on first load I've being doing a technical test for a recruiter and have come across and extremely annoying bug with html5/canvas/javascript.
The problem only occurs intermittently and usually only on the first load of the page.
The images all load ok but the 3 character code only loads when I reload the page manually.
I've tried adding callbacks and even a setTimeout but there appeasr to be something happening on the initial load but I can't trap it.
Here's my code:
function Rectangle() {

    this.w = 111;
    this.h = 111;
    this.font_color = "white";
    this.font_family = "18pt Novecentowide";

}

Icon.prototype = new Rectangle();

function Icon(data) {

    this.code = data['code'];
    this.bg_color = data['bg_color'];
    this.x = data['x'];
    this.y = data['y'];
    this.code_x = data['code_x'];
    this.code_y = data['code_y'];
    this.icon_src = data['icon_src'];
    this.icon_x = data['icon_x'];
    this.icon_y = data['icon_y'];

    this.drawIcon = function () {

        // setup canvas
        var c = document.getElementById("canvasId");
        var ctx = c.getContext("2d");

        // draw rectangle
        ctx.fillStyle = this.bg_color;
        ctx.fillRect(this.x, this.y, this.w, this.h);

        // apply icon
        var img = new Image();
        img.src = this.icon_src;

        var icon_x = this.icon_x;
        var icon_y = this.icon_y;

        // get text values
        var font_color = this.font_color;
        var font_family = this.font_family;
        var code = this.code;
        var code_x = this.code_x;
        var code_y = this.code_y;

        img.onload = function () {
        // Once the image has finished loading, draw the
        // image and then the text.

            function DrawScreen() {
                ctx.drawImage(img, icon_x, icon_y);
            }

            DrawScreen();

        };

        function DrawText() {
            ctx.fillStyle = font_color;
            ctx.font = font_family;
            ctx.fillText(code, code_x, code_y);
        }

        DrawText();

    }

}

var icon1 = new Icon({code: "ABC", bg_color: "c64918", x: 0, y: 0, code_x: 13, code_y: 98, icon_src: "images/shape_icon.png", icon_x: 0, icon_y: 0 });

var icon2 = new Icon({code: "DEF", bg_color: "d37724", x: 195, y: 0, code_x: 208, code_y: 98, icon_src: "images/shape_icon.png", icon_x: 195, icon_y: 0 });

var icon3 = new Icon({code: "GHI", bg_color: "556a70", x: 0, y: 151, code_x: 13, code_y: 249, icon_src: "images/hand_icon.png", icon_x: 0, icon_y: 151 });

var icon4 = new Icon({code: "JKL", bg_color: "55777f", x: 195, y: 151, code_x: 208, code_y: 249, icon_src: "images/hand_icon.png", icon_x: 195, icon_y: 151 });

var icon5 = new Icon({code: "MNO", bg_color: "68a03d", x: 0, y: 303, code_x: 13, code_y: 400, icon_src: "images/dollar_icon.png", icon_x: 0, icon_y: 303 });

icon1.drawIcon();

icon2.drawIcon();

icon3.drawIcon();

icon4.drawIcon();

icon5.drawIcon();

Can anyone shed some light on why this is happening.
Link to demo is: http://www.mpwa.co/html5
Any help would be very much appreciated.

Resolved the problem.
I wasn't checking to see if the document had loaded and so the first attempt at drawing on the canvas was failing.
Basics!!
Here's the key part of the working code...

function init() {
icon1.drawIcon();

icon2.drawIcon();

icon3.drawIcon();

icon4.drawIcon();

icon5.drawIcon();

}
var readyStateCheckInterval = setInterval(function () {
if (document.readyState === "complete") {

    init();

    clearInterval(readyStateCheckInterval);

}

}, 10);

A: You should do it like this:
    img.onload = function () {
    // Once the image has finished loading, draw the
    // image and then the text.
        DrawScreen();
        DrawText();
    };
    function DrawScreen() {
        ctx.drawImage(img, icon_x, icon_y);
    }
    function DrawText() {
        ctx.fillStyle = font_color;
        ctx.font = font_family;
        ctx.fillText(code, code_x, code_y);
    }


text:
Q: Configspec in string ConfigObj I have read that you can pass the configspec as a string and not as a file for the ConfigObj module. The question more than anything is how is the right way? Because I made several attempts, but they are wrong, for sure because I did not understand. More than anything else I need the configspec to check when the data is loaded.
My configspec is this at the moment:
cfs = """
    set default = boolean()
    width = integer(min=800, max=1920)
    height = integer(min=600, max=1080)
    fullscreen = boolean()
    music = integer(min=0, max=100)
    sound = integer(min=0, max=100)
    voice = integer(min=0, max=100)
    ambient = integer(min=0, max=100)
    other audio = integer(min=0, max=100)
    """

In case you do need more information, I shall change my question, adding that information.


text:
Q: MATCH-formula where 'lookup_value' is array I have 3 Excel-files (automated exports) that contain the following information:
1. The total list of shelves in one particular store:
| Shelf_code |
|------------|
| AB01       |
| AA02       |

2. The total list of all shelves linked to each article
| SKU_code | Shelf_code |
|----------|------------|
| 111      | AA01       |
| 111      | AB01       |
| 111      | AC01       |
| 112      | AA01       |

3. The list of all available SKUs
| SKU_code | Other stuff |
|----------|-------------|
| 111      | ...         |
| 112      | ...         |
| 113      | ...         |
| 114      | ...         |

And what I want to do is to link the Shelf_codes from that specific store to the total available SKU-list, so it will look like this:
| SKU_code | Other stuff | Shelf_code_store1 |
|----------|-------------|-------------------|
| 111      | ...         | AB01              |
| 112      | ...         |                   |
| 113      | ...         |                   |
| 114      | ...         | AB01              |

I have tried to embed the MATCH formula within another INDEX/MATCH formula (see code below) which was partially successful since this will only work if the shelf_code in file 2 happens to be the first one to match the SKU_code.
Since this will be mostly not the case, it will return a #N/A error
MATCH(
  INDEX({file2_shelfcode},MATCH(file3_skucode,{file2_skucode},0)),
  {file1_shelfcode}
)

Does anyone has a solution for this?
Since these files contain over 1000 articles, 200 shelves, 6 stores, and will be frequently updated I don't think using a Pivottable on file 2 will fit my needs.


text:
Q: Curve overlay on a Surface Matplotlib I am interested in plotting curves on surfaces of revolution and have done so, but the surface is over-layed over the curve, does anyone know how to do the opposite?
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def surface_of_rev(u,v):
    f = v
    x = f*np.cos(u)
    y = f*np.sin(u)
    z = np.exp(-v**2)
    return x,y,z

U = np.linspace(0,2*pi,n)
V = np.linspace(0.,3,n)
U,V = np.meshgrid(U,V)
x,y,z = surface_of_rev(U,V)

# curve
a = 3
b = 1
T = np.linspace(0,3,100)
xx,yy,zz = surface_of_rev(a*T+b,2*T)

# plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
curve = ax.plot(xx, yy, zz, 'o-', lw=2)
surface = ax.plot_surface(x, y, z,color= 'g')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.view_init(50, 10)
plt.show()

Thank you