text:
Q: Backbone.js - How to get an array of object literals out of a collection? I'm trying to keep an array of object literals in sync with server data.  These objects are being placed on a Google map via backbone.googlemaps extension.
I have a collection:
var LocationList = Backbone.Collection.extend({ model: Location, url: '/locations' })
How can I grab an array of object literals from this LocationList collection?  My goal is such:
[{name: "Home", address: "123 Pleasant St"}, {name: "Work", address: "123 Unpleasant St"}]

A: use underscore.js pluck method: http://underscorejs.org/#pluck

A: You are looking for the .toJSON() method of the collection, see here:
var locations = new LocationList();

locations.toJSON();


text:
Q: Problemas com callback Javascript Tenho uma div modal do bootstrap que fica na "masterpage" _Layout.csthml.

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Atenção

                    Houve alteração de dados nesta tela, as demais informações das telas seguintes serão apagadas.

                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
                <button id="btnConfirmarAlteracao" type="button" class="btn btn-primary">Salvar</button>

Criei uma função que é chamada em várias Views diferentes, para abrir essa modal, e ao clicar no botão Salvar, seja executado uma função javascript passada por parâmetro.
function confirmarAlteracao(callback) {
        $("#btnConfirmarAlteracao").click(function () {
            callback();
            $('#ModalAlteracao').modal('hide');
        });

        $('#ModalAlteracao').modal('show');
 }

Exemplo de chamada dessa função:
function salvarPlaca() {
    if (!houveAlteracaoPlaca()) {
        efetivarAlteracaoPlaca();
    }
    else {
        // exibe o dialog de confirmação, e passa a função de callback caso o usuário clique em "sim"
        confirmarAlteracao(efetivarAlteracaoPlaca);
    }

}

O problema é que se o usuário clicar em Cancelar, e depois clicar de novo no botão que executa salvarPlaca, e nessa segunda vez confirmar, a função efetivarAlteracaoPlaca está sendo executada duas vezes.

A: Você está associando um evento novo ao elemento btnConfirmarAlteracao toda vez que chama a função confirmarAlteracao. Ou você aplica o unbind da função registrada anteriormente, ou adota outra estratégia. Aqui está um exemplo usando closures para resolver o problema:
var currentCallback = $.noop;

$("#btnConfirmarAlteracao").click(function () {
    currentCallback();
    $('#ModalAlteracao').modal('hide');
});

function confirmarAlteracao(callback) {
    currentCallback = callback;
    $('#ModalAlteracao').modal('show');
}

NOTA: Eu iria preferir usar Promises nesse cenário... como estou saindo do trabalho agora, quando chegar em casa edito essa resposta para lhe passar uma solução usando Promises.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap: collapsed text conflicts with footer Hi I have this page, built upon Bootstrap, and the thing is that if you click the "See Wikipedia" button, the content will flush the whole page, however the page height does not change and the footer is overwritten in a very funny ugly way. Is it possible to change this? I have tried to set some overflow but it does not help much.

A: You can do this small changes :
Change

By

Change

By


text:
Q: Haskell function for list length To calculate length of a list, using a foldr, one would do something like:
foldr (\_ acc -> acc + 1) 0

Expanding further on the idea that the folding function needs to increment the second argument, i came up with this (and it's wrong):
foldr ((+1) . (flip const)) 0`

Further inspection of the type reveals this:
(+1) . (flip const) :: Num (c -> c) => a -> c -> c

Haskell higher order function to calculate length
There's an interesting comment on that page, which i can't understand really
foldr (((+1).).(flip const)) 0

Can someone explain how does that composition actually work ?

A: First of all, let's focus why foldr ((+1) . (flip const)) 0 is wrong. You want to increment the second argument only and forget the first one. Semantically, that's
\_ a -> a + 1

However, you wrote the following:
(+1) . flip const
= (+1) . (\_ a -> a)
= \x -> (+1) . (\_ a -> a) $ x
= \x -> (+1) $ (\_ a -> a) $ x
= \x -> (+1) $ \a -> a
= \_ -> (+1) (\a -> a)
= const ( (+1) (\a -> a))

Which is why you suddenly need Num (c -> c), since you're trying to apply (+1) on id.
But you actually meant:
\_ a -> a + 1
= \_ a -> (+1) a
= \_   -> (+1)
= const (+1)

After all, you want to forget the first argument and use a function f on the second. All you have to to is to use const f.
The composition ((+1).).(flip const) is overly verbose and probably generated by pointfree:
((+1).).(flip const)
= ((\x -> x + 1).) . (\a _ -> a)
= \c -> ((\x -> x + 1).) . (\a _ -> a) $ c
= \c -> ((\x -> x + 1).) $ \_ -> c
= \c -> \f -> (\x -> x + 1) . f $ \_ -> c
= \c ->   (\x -> x + 1) . \_ -> c
= \_ c -> (\x -> x + 1) $ c
= \_ c -> c + 1

A: This is really a comment, but much too long for one.
Unless you're dealing with weird numbers like lazy Nats, you really want
length xs = foldl' (\acc _ -> 1 + acc) 0 xs

Making this pointless,
length = foldl' (\acc -> const ((1+) acc)) 0
length = foldl' (const . (1+)) 0

If you like, you can transform the original foldl' expression into a foldr form like so:
length xs = foldr go id xs 0 where
  go _ r acc = r $! 1 + acc

Chewing on go,
go _ r acc = ($!) r $ (+) 1 acc
go _ r = ($!) r . (+1)
go _ r = (. (+1)) (($!) r)
go _ = (. (+1)) . ($!)
go = const ((. (+1)) . ($!))

Chewing on length,
length = flip (foldr go id) 0

Putting it all together,
length = flip (foldr (const ((. (+1)) . ($!))) id) 0

I, for one, find this point-free form utterly opaque.


text:
Q: How do I htaccess redirect index.html to index.php and index.php to / I recently changed my index.html to index.php - I want to be able to do a redirect to reflect this, and then also a rewrite that forces foo.com/index.php to just be foo.com/ and have it access the .php file.
I also have a separate site i.e. bar.com located in a subdirectory under foo.com that I want to remain unaffected.
This is what I had, which results in a redirect loop:
RedirectMatch 301 ^/index.html?$ /index.php
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\.php\ HTTP/
RewriteRule ^(.*)index\.php$ /$1 [R=301,L]

Is there a way to do this? Thanks!

A: The RedirectMatch directive matches after the internal redirect that takes the / request and redirects it to /index.html, then it get put through the URL-file mapping pipeline again and thus matches your redirect directive.
You can try including a:
DirectoryIndex index.php

to prevent this automatic internal redirect. You should also use the %{THE_REQUEST} match with the index.html file like you're doing with index.php:
Options +FollowSymLinks
DirectoryIndex index.php

RewriteEngine on

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\.php\ HTTP/
RewriteRule ^(.*)index\.php$ /$1 [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\.html\ HTTP/
RewriteRule ^(.*)index\.html$ /$1index.php [R=301,L]

Or you can bypass index.php entirely:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\.html\ HTTP/
RewriteRule ^(.*)index\.html$ /$1 [R=301,L]


text:
Q: Unix 11i v2 Script to detect new files within directory I was hoping someone can point me in the right direction. I would like to create a script to check for new files (files with today's date) within a directory and then print the results to a text file. Could I use cron or bash?
edit:
Updated original thread. I tried the following on my Linux Mint VM and I got it to work. The only problem is:
1) when i create a new file (using "sudo vi newtextfile.txt" and then ":w") i receive the notification email 4 times.
2) am i triggering multiple IN_CREATE events by creating a new file using the method i mentioned above?
/xyz/jon >>>
total 12
786436 drwxr-xr-x 2 root root 4096 Jul 13 20:43 .
786434 drwxr-xr-x 4 root root 4096 Jul 13 19:45 ..
786441 -rwxr-xr-x 1 root root 48 Jul 13 20:32 mylogger.sh
786437 -rw-r--r-- 1 root root 0 Jul 13 20:22 mylogtoday.txt

"incron.table-jonincron" >>>
/xyz/client IN_CREATE /xyz/jon/mylogger.sh

/xyz/jon/mylogger.sh >>>
sudo mail -s "testing script" emailaddress@domain.com

A: Do you want something that monitors a directory? incron can be quite handy for that:
1. Install incron from a repo
2. Enable incrond:
sudo systemctl enable incrond.service
sudo systemctl start incrond.service

3.Create appropriate incrontab:
incrontab -e

and add as content:

/path/to/watch IN_CREATE /path/to/mylogger.sh $@/$#

4.Create the logger script:
cat <<EOF>> /path/to/mylogger.sh
#!/bin/bash
echo $1 >> /path/to/logfile
EOF
chmod +x /path/to/mylogger.sh

Thats it.

A: Hello I was hopping someone with better skill could answer. HP-UX has quite an old System V toolbox so you will not have the recent GNU tools.
HP-UX posix shell, which is /usr/bin/sh  is very close to ksh93. So you can compare the age of two files with [[ file1 -nt file2 ]] wich returns true if file1 is newer than file2. Don't use /usr/bin/ksh on HP-UX it is a very old standard korn-shell (perhaps 1982).
Here is a simple script that you can run periodically. It should be hardened better to support files with specials characters in the names and other possible errors but I'm not good at that.
The files being watched are in DIR, the new files list is /tmp/newfile. The list is created while comparing all the file in DIR to the youngest file found during the last run so it supports new files being created while it runs.
The script does not support multiple execution at the same time, you may have to implement locks or to space each execution with enough time.
#!/usr/bin/sh

previous=/tmp/previous
new=/tmp/newfiles
DIR=/tmp/aa

if [[ ! -s $new ]]
then
    mv "$new" "$previous"
fi

if [[ ! -f "$previous" ]]
then
    ls -rt "$DIR" > "$new"
    exit
fi

ref=$(tail -1 "$previous")

if ! cd "$DIR"
then
    echo cannot cd "$DIR"
    exit 1
fi

ls -rt | while read file
do
        if [[ "$file" -nt "$ref" ]]
        then
             echo "$file"
        fi
done > "$new"

You could run it in cron, for instance :
every five minutes (note that hp-ux crontab do not support *5 syntax)
0,5,10,15,20,25,30,35,40,45,55 * * * * /myscript.sh >>/var/adm/myscript.log 2>&1

every hour
0 * * * * /myscript.sh >>/var/adm/myscript.log 2>&1

once a day
0 0 * * * /myscript.sh >>/var/adm/myscript.log 2>&1


text:
Q: How can I change the language on the ubisoft store in the Browser from French to Dutch? I live in Flanders, in Belgium. I got linked a free game on the US version of the Ubisoft store, and when I opened the link, it asked me whether I wanted to go to the Belgian version of the store. I agreed, but it sent me to the French version of the store: https://store.ubi.com/fr/home. Usually it should first send me to a language select interstitial slide (usually 2, even) before it moves on. I managed to redeem the free game somehow, but I now want to browse the rest of the store in Dutch, because I'm Flemish and I I'd rather not have to deal with any more French than I really have to.
I know I can change the url and replace the fr with nl (and this time I ended up just caving and doing that), but I don't know if that would bring me to the Dutch version of the store from the Netherlands instead of the Dutch version from Belgium. Hell, I don't even know if the two stores are different. Also, url manipulation like that is something I'd rather avoid because of how finnicky it can be at time to guess what the url would be, and I'd prefer to use methods native to the website I'm visiting, such as a country or language select option.
So is there a native way to change the Ubisoft Store language, or country if that's what I need to change here?

A: It seems the store page they offer is based on the country they think you are coming from.  For example, if I open the French link in the question, it suggests a location change.

As far as language changing, this seems to be based on the country you end up using.  For example, the US store has a dropdown at the bottom of the page to switch between English and Spanish.

Likewise, the CA page has options for English and French.  However, this language selection is not on all versions, such as the mentioned FR link nor the NL link.
As for how to switch to the correct store page, there's doesn't seem to be a built-in method at the moment.  Best option is probably to use a search engine looking for "Ubisoft [COUNTRY / LANGUAGE] store", with country appearing to give better results.  As far as I can tell, there is no BE version of the store.


text:
Q: change (denominations) calculator I'm looking for a solution to calculate denominations of change.
My problem has the denominations: 50 & 20.
So given the amount: 130, there should be 1x50 + 4x20,
and amount: 80, there should be 0x50 + 4x20, etc.
I have tried looking up the coin problem but cannot get a decent answer, and when there are more than 2 types on denominations, there seems to be a brick wall for the coin problem (from what I've read).
Is there any complete solution to this? Or preferably a solution to more than 2 denomination types?
I would also like to be able to supply an amount of each available denomination.
Bonus if you can solve in pseedo code

A: If you have only two denominations the problem becomes:
find x and y such that
a*x + b*y = c

This can be solved using the Extended Euclidean Algorithm

If you have more than 3 denominations, the most common solution uses uses dynamic programming to "brute force" the possibilities. You can check this similar question

A: Check the relative but more general question looking-to-understand-the-rationale-for-money-denomination at math.stackexchange.com.
Also making-change-for-a-dollar-and-other-number-partitioning-problems, which nicely explains how generating functions are the solution to the general problem.
If your problem is restricted to two coins, it's far more easier.

A: here is a code solution: http://www.codeproject.com/KB/recipes/coinChangeProblem.aspx
unfortunately the code is really ugly but should be able to clean up easily

A: u can use simple "greedy algorithm"
http://en.wikipedia.org/wiki/Greedy_algorithm

A: Just keep subtracting the biggest denomination you can. IE keep subtracting 50s until whats left is <50, then keep subtracting 20s. This works no matter how many denominations you have.


text:
Q: Binned scatterplot -- how to ensure the top 'viewable' is the item in the bin with the lowest value in a column? I have a binned scatterplot:
scatterplot = alt.Chart(locations).mark_circle(
    size=300
).encode(
    alt.X('reprLong:Q', bin=True),
    alt.Y('reprLat:Q', bin=True),
    color=alt.Color('featureType:N', legend=None),
    tooltip=['minDate:Q', 'title:N', 'featureType:N']
).interactive().add_selection(selector)

For each item in the bin, this seemingly layers on circles for every item, with no apparent order. I'd like the top item (the 'visible' one you can click) to be the item in the bin with the lowest minDate (column in pandas dataframe locations) value. How do I do that? I have it interactive, so I need only those items to be viewable / clickable.


text:
Q: Custom control and TemplateBinding in WinRT I'm trying to create a simple custom control that shows a circle. This control has a Radius property but unfortunately it doesn't apply to the control. Here is a template:
<Style TargetType="local:SizedCircle">
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:SizedCircle">
                <Border
                    Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">
                    <Ellipse Width="{TemplateBinding Radius}" Height="{TemplateBinding Radius}">
                        <Ellipse.Fill>
                            <SolidColorBrush Color="Red"/>
                        </Ellipse.Fill>
                    </Ellipse>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And
    namespace CustomControls
{
    public sealed class SizedCircle : Control
    {
        public SizedCircle()
        {
            this.DefaultStyleKey = typeof(SizedCircle);
        }

        public string Radius
        {
            get { return (string)GetValue(RadiusProperty); }
            set { SetValue(RadiusProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Radius.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty RadiusProperty =
            DependencyProperty.Register("Radius", typeof(string), typeof(SizedCircle), new PropertyMetadata(null));
}
}

Then I try to use this control:
 <local:SizedCircle Radius="50" />

But I see nothing on the screen. This Radius property is not applyed. What am I douing wrong?

A: Try changing the property type to double instead of string.


text:
Q: cpu high usage with postgres.exe I work with PostgreSQL 9.0
I used windows server 2008
I have problem with cpu high usage  it arrived to 100 %
my application it used between by 600 and 700 users
I have this config in postgres.conf
max_connections = 750
shared_buffers = 8GB
temp_buffers = 32MB
work_mem = 64MB
maintenance_work_mem = 1GB
effective_cache_size = 24GB

and this is my config in applicationContext-db.xml

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
   <property name="driverClassName" value="org.postgresql.Driver"/>
     <property name="url" value="jdbc:postgresql://srvdatabase:5432/DBTest"/>
    <property name="username" value="postgres"/>
    <property name="password" value="postgres"/>
    <property name="maxActive" value="750"/>
    <property name="maxIdle" value="30"/>
    <property name="maxWait" value="20000"/>
    <property name="defaultAutoCommit" value="true"/>
    <property name="removeAbandoned" value="true"/>
    <property name="removeAbandonedTimeout" value="300"/>
</bean>

sametime the cpu it's performence is lower than 50%
but sametimes it arrived to 100% and in this time my application will be down


text:
Q: Free RAM disappears - Memory leak? On a fresh started system, free reports about 1.5G used RAM (8G RAM alltogether, Ubuntu 12.04 with lightdm and plasma desktop, one konsole window started). Having the apps running I use, it still consumes not more than 2G. However, having the system running for a couple of days, more and more of my free RAM disappears -- without showing up in the list of used apps: while smem --pie=name reports less than 20% used (and 80% being available), everything else says differently. free -m for example reports on about day 7:
             total       used       free     shared    buffers     cached
Mem:          7459       7013        446          0        178        997
-/+ buffers/cache:       5836       1623
Swap:         9536        296       9240

(so you can see, it's not the buffers or the cache). Today this finally ended with the system crashing completely: the windows manager being gone, apps "hanging in the air" (frameless) -- and a popup notifying me about "too many open files". Syslog reports:
kernel: [856738.020829] VFS: file-max limit 752838 reached

So I closed those applications I was able to close, and killed X using Ctrl-Alt-backspace. X tried to come up again after that with failsafeX, but was unable to do so as it could no longer detect its configuration. So I switched to a console using Ctrl-Alt-F2, captured all information I could think of (vmstat, free, smem, proc/meminfo, lsof, ps aux), and finally rebooted. X again came up with failsafeX; this time I told it to "recover from my backed-up configuration", then switched to a console and successfully used startx to bring up the graphical environment.
I have no real clue to what is causing this issue -- though it must have to do either with X itself, or with some user processes running on X -- as after killing X, free -m output looked like this:
             total       used       free     shared    buffers     cached
Mem:          7459       2677       4781          0         62        419
-/+ buffers/cache:       2195       5263
Swap:         9536         59       9477

(~3.5GB being freed) -- to compare with the output after a fresh start:
             total       used       free     shared    buffers     cached
Mem:          7459       1483       5975          0         63        730
-/+ buffers/cache:        689       6769
Swap:         9536          0       9536

Two more helpful outputs are provided by memstat -u. Shortly before the crash:
User     Count     Swap      USS      PSS      RSS
mail         1        0      200      207      616
whoopsie     1      764      740      817     2300
colord       1     3200      836      894     2156
root        62    70404   352996   382260   569920
izzy        80   177508  1465416  1519266  1851840

After having X killed:
User     Count     Swap      USS      PSS      RSS
mail         1        0      184      188      356
izzy         1     1400      708      739     1080
whoopsie     1      848      668      826     1772
colord       1     3204      804      888     1728
root        62    54876   131708   149950   267860

And after a restart, back in X:
User     Count     Swap      USS      PSS      RSS
mail         1        0      212      217      628
whoopsie     1        0     1536     1880     5096
colord       1        0     3740     4217     7936
root        54        0   148668   180911   345132
izzy        47        0   370928   437562   915056

Edit: Just added two graphs from my monitoring system. Interesting to see: everytime when there's a "jump" in memory consumption, CPU peaks as well. Just found this right now -- and it reminds me of another indicator pointing to X itself: Often when returning to my machine and unlocking the screen, I found something doing heavvy work on my CPU. Checking with top, it always turned out to be /usr/bin/X :0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch -background none.
So after this long explanation, finally my questions:

*

*What could be the possible causes?

*How can I better identify involved processes/applications?

*What steps could be taken to avoid this behaviour -- short from rebooting the machine all X days?

I was running 8.04 (Hardy) for about 5 years on my old machine, never having experienced the like (always more than 100 days uptime, before rebooting for e.g. kernel updates). This now is a complete new machine with a fresh install of 12.04. In case it matters, some specs:
AMD A4-3400 APU with Radeon(tm) HD Graphics, using the open-source ati/radeon driver (so no fglrx installed), 8GB RAM, WDC WD1002FAEX-0 hdd (1TB), Asus F1A75-V Evo mainboard. Ubuntu 12.04 64-bit with KDE4/Plasma. Apps usually open more or less permanently include Evolution, Firefox, konsole (with Midnight Commander running inside, about 4 tabs), and LibreOffice -- plus occasionally Calibre, Gimp and Moneyplex (banking software I'm already using for almost 20 years now, in a version which did fine on Hardy).
Edit:
Today I found one of the "evil guys": KDE4s plasma-desktop. Used memory was again up to 5GB, when I did a killall plasma-desktop && plasma-desktop. This freed up 1.3GB RAM! ps says:
                             RSS    SIZE   VSZ
plasma usage before restart  120988 526472 1300816
plasma usage after restart   92352  495972 1263632

So where have those 1.3GB been? The diff between those values, if added up, amount to 96MB -- not 1.3GB.
And this can only be one part, as still 3.7GB are in use (should be less than 2GB). I monitored this during the past 6 days using several tools: used memory (not talking about cache and buffers) increases slowly but steadily. Even if I'm not at my desk to run anything...
As to monitoring processes with open files, I currently use the following 1-liner (I love shell and especially bash) to get the top-5:
echo "$(for pid in $(ls -a /proc|egrep '^([0-9])*$'|sort -n 2>/dev/null); do \
if [ -e /proc/$pid/fd ]; then FHC=$(ls -l /proc/$pid/fd|wc -l); \
if [ $FHC -gt 0 ]; then PNAME="$(cat /proc/$pid/comm)"; \
echo "$FHC files opened by $pid ($PNAME)"; fi; fi; done)"|sort -r -n|head -n5

Command here in 4 lines for better readability. Nothing much yet from there -- except that Skype doesn't like have the Internet connection broken. Each disconnect causes a slight increase of its open files, but nothing dramatic. On the other hand it seems like plasma is also responsible for that:

See the drop of file handles at the end? That was the plasma restart.

A: *

*The huge number of open files is a good clue that something is going wrong. My guess would be some KDE system daemon.

*Open a console and run "top". Then use < and > to change the sorting column to VIRT or RES and see which programs are using the most memory. A memory leak will show up as a massively inflated virtual memory use, as once the pointer to the leaked memory is lost it won't be used and will be swapped out. Also run "lsof" and look for a process with lots of open files, since this seems to really be a file descriptor leak.

*Track down the program and report a bug.

A: I think thats normal system behaivor. Most likely everything is fine.
You may read this brilliant paper (linux ate my ram) to understand, how linux is managing your ram and why there is no need to worry:
http://www.linuxatemyram.com/


text:
Q: What is the approximation to the probability a mouse has weight less than 8? Suppose the weight of mice is normally distributed with mean 10 and standard deviation 2. What is the approximation to the probability a mouse has weight less than 8?
I am looking to see the process how to solve this problem using the 68-95-99.7 stats rule. So far I have P(x<8) and 2 standard deviations from the mean would be .95 How would I put this in the mathematical form to solve it?
Thank you

A: This is only one standard deviation away from the mean.
Using the 68-95-99.7 rule, you can find $P[8\leq X \leq 12]$.
Which complement to 1 is $P[X<8$ or $X>12]$.
Using the symetry of normal distribution, you finally divide by 2 to find $P[X<8]$

A: The $2$ is the value of one standard deviation.
So, there is a $0.68$ probability that a mouse has a weight between $8$ and $12$ grams, and thus there is a $0.32$ probability that the weight of a mouse is outside that interval, i.e. below $8$ or above $12$. By symmetry, this means that there is a $0.16$ probability it is below $8$.


text:
Q: AWK is not producing an output when used in PHP <?php
$dd="/root/report/lastDate-28-11-2013.csv";
$c_row=exec("awk 'BEGIN { FS = \",\" } ; { print $1 }'" .$dd);
//echo $c_row;
print_r($c_row);
?>

When i run this code it simply hangs and does not print any output.

A: Have a look at the manual, you're missing an output and/or return_var parameter.
To get the output of the executed command, be sure to set and use the output parameter.
Syntax:
string exec ( string $command [, array &$output [, int &$return_var ]] )

output
If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing
  whitespace, such as \n, is not included in this array. Note that if
  the array already contains some elements, exec() will append to the
  end of the array. If you do not want the function to append elements,
  call unset() on the array before passing it to exec().
return_var
If the return_var argument is present along with the output argument, then the return status of the executed command will be
  written to this variable.

In your case, it might look something like...
$csv = "/your/file.csv";
$comm = "awk 'BEGIN { FS = \",\" } ; { print $1 }'" .$dd;
exec($comm, $output);
var_dump($output);

(I haven't checked your awk command so far, I suspect it returns the desired result)


text: Q: Showing that $\mathbb{Z}[\phi]$ is a UFD, where $\phi^2+\phi+1=0$. I would like to show that $\mathbb{Z}[\phi]$ is a UFD, where $\phi^2+\phi+1=0$. I started with a division with remainder to determine the irreducibles, but I could not finish that, and I do not know how to approach this problem. Could you provide me with some resources or show how I can solve this? Thanks in advance.


text:
Q: Kendo Window - Use Custom Update I have the following Kendo grid:
 @(Html.Kendo().Grid<Mizuho.AMS.Models.AMSServiceProcessNotificationModel>()
    .Name("grd")
    .ToolBar(toolBar =>
    {
        toolBar.Create();
    })
    .Sortable()
    .Scrollable(a => a.Height("auto"))
    .Filterable(s => s.Enabled(false))
    .Selectable(s => s.Enabled(false))
    .Pageable(p => p.Enabled(true).Refresh(true).PageSizes(new List<string> { "all", "10", "15", "20", "50" }))
    .HtmlAttributes(new { style = "width: 100%;" })
    .Editable(e => e.Mode(GridEditMode.PopUp).TemplateName("NotificationEditor").Window(w => w.Width(700)))
    .Columns(columns =>
    {
        columns.Bound(s => s.ProcessId).Width(90);
        columns.Bound(s => s.NotificationType).Width(140);
        columns.Bound(s => s.NotificationAction).Width(140);
        columns.Bound(s => s.Parameters).Width(680);
        columns.Command(cmd => { cmd.Edit(); cmd.Destroy(); });
    })
    .DataSource(dataSource => dataSource
        .Ajax()
        .Batch(true)
        .ServerOperation(false)
        .PageSize(15)
        .Events(events => events.Error("error_handler"))
        .Model(model =>
        {
            model.Id(s => s.ID);
        })
        .Read(read => read.Action("Read", "Notification"))
        .Create(create => create.Action("Create", "Notification"))
        .Update(update => update.Action("Update", "Notification"))
        .Destroy(destroy => destroy.Action("Destroy", "Notification"))
    )
    .Resizable(resize => resize.Columns(true))
)

As you can see, I am using a popup dialog to edit a row. This creates a Kendo window with an update button, which will cause the Update method of the Notification controller to fire. If there is an error there, the error_handler specified above is called. This is it:
function error_handler(e) {
    if (e.errors) {
        var message = "";
        $.each(e.errors, function (key, value) {
            if ('errors' in value) {
                $.each(value.errors, function () {
                    message += this + "\n";
                });
            }
        });
    }
}

I display any errors, and the Kendo window is dismissed (actually, the order is, dismiss window, then errors are displayed).
What I want to do instead:
If there is an error after the user clicks the Update button, call the update method, get the error and display it, and NOT DISMISS THE WINDOW. This will allow the user to correct the error and try again.
Thanks for reading.


text:
Q: Cordova FileTransfer and Cordova Camera I'm working in Ionic with some cordova plugins (FileTransfer, Camera, File, etc).
view - screenshot
On the view works great, I can show images(camera and gallery) but I get a FileTransfer error code = 1 when try to upload and it means File not found. So when I check my app directory (cordova.file.dataDirectory and cordova.file.cacheDirectory) is empty.
Camera Code:
$scope.takePhoto = function(){
var optionsCamera = {
  quality: 100,
  destinationType: Camera.DestinationType.FILE_URI,
  sourceType: Camera.PictureSourceType.CAMERA,
  saveToPhotoAlbum: false,
  correctOrientation: true
};

$cordovaCamera.getPicture(optionsCamera)
  .then(function(imageData){

    console.log(imageData);

    var currentName = imageData.replace(/^.*[\\\/]/, '');
    var namePath = imageData.substr(0, imageData.lastIndexOf('/') + 1);
    console.log(currentName);
    console.log(namePath);
    //move from cache to files
    $cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, 't_s'+currentName)
      .then(function(successMove){
        console.log(successMove);
        $scope.imagenes.push('t_s'+currentName);
        console.log($scope.imagenes);
      }, function(errorMove){
        console.log(errorMove);
      });

  }, function(errorCamera){
    console.log(errorCamera);
  })}

Upload code:
$scope.sendData = function() {

var server = Config.serverUrl() + '/product_image_upload/';

console.log($scope.imagenes);
//first image in array
var targetPath = $scope.imagenes[0];
var filename = ($scope.imagenes[0]).replace(/^.*[\\\/]/, '');
console.log(targetPath);
console.log(filename);

var options = {
  httpMethod: 'POST',
  fileKey: 'file',
  filename: filename,
  chunkedMode: false,
  mimeType: 'multipart/form-data'
};

var params = {
  'fileName' : filename,
};
//JWT token
var headers = {
  'Authorization': $rootScope.token
};
options.headers = headers;
options.params = params;
console.log(options);
$cordovaFileTransfer.upload(server, targetPath, options).then(
  function(result) {
    // Success!
    console.log('upload ok');
    console.log(result);
  }, function(err) {
    // Error
    console.log(err);
  }, function(progress) {
    // constant progress updates
    console.log(progress);
    $scope.progress = progress;
  })}

I want to know, where  are the files?


text:
Q: How to remove UITableViewCell NSIBPrototypingLayoutConstraint and Add my own to subviews? What is the proper way to remove NSIBPrototypingLayoutConstraints from UITableViewCell subviews and add my own constraints without seeing error messages in the simulator log?
For example, I want to dynamically change the size of a UILabel inside a UITableViewCell by adding a width constraint. I don't even know if this the preferred method of doing this. Is there some way for me to find the constraint and update that directly?

A: You can remove all of the constraints for an object, then add back in the ones you want.
To remove them:
[yourView removeConstraints:yourView.constraints];

Then you can manually add your own constraints.
(here is a more detailed link on adding view width constraints)
To just modify the existing constraints:
for(NSLayoutConstraint *constraint in yourView.constraints) {
    //you can inspect these to see if their .firstAttribute or .secondAttribute correspond to the type of NSLayoutAttribute you are looking for.
 }


text:
Q: PythonAnywhere Django 404 Page Not Found for Homepage I know there is a similar post like this one. I've reviewed it and it is quite different from what I'm experiencing at the moment on Pythonanywhere.com
I'm trying to deploy my rango tutorial project that I completed through tangowithdjango.com onto Pythonanywhere.com. When I try to open the site (url is ragzputin.pythonanywhere.com), I get this page:

Here's my urls.py file for my project:
from django.conf.urls.defaults import *
from django.conf import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',

    url(r'^rango/', include('rango.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

if settings.DEBUG:
urlpatterns += patterns(
    'django.views.static',
    (r'media/(?P<path>.*)',
    'serve',
     {'document_root': settings.MEDIA_ROOT}), )

If you guys need some extra information, here's my app urls.py (app name is rango):
from django.conf.urls import patterns, url
from rango import views

urlpatterns = patterns('',
    url(r'^$', views.index, name="index"),
    url(r'^about/$', views.about, name="about"),
    url(r'^add_category/$', views.add_category, name="add_category"),
    url(r'^category/(?P<category_name_url>\w+)/add_page/$', views.add_page,   name="add_page"),
    url(r'^category/(?P<category_name_url>\w+)/$', views.category, name="category"),
    url(r'^register/$', views.register, name="register"),
    url(r'^login/$', views.user_login, name="login"),
    url(r'^restricted/$', views.restricted, name="restricted"),
    url(r'^logout/$', views.user_logout, name="logout"),
    url(r'^profile/$', views.profile, name="profile"),
    url(r'^goto/$', views.track_url, name="track_url"),
    url(r'^like_category/$', views.like_category, name="like_category"),
    url(r'^suggest_category/$', views.suggest_category, name="suggest_category"),
    url(r'^auto_add_page/$', views.auto_add_page, name="auto_add_page"),
)

As you can see from the 404 page above, the server is not able to get to the main page which starts with '^rango/'. Any suggestions?

A: You should add url for home page into the project's urls.py:
urlpatterns = patterns('',
    url(r'^$', 'rango.views.index', name="index"),
    url(r'^rango/', include('rango.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

And don't forget to remove the same (first) url from rango/urls.py.
The other option is to add redirect from / to /rango/. If you choose this option then project's urls.py should be:
from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(url='/rango/')),
    url(r'^rango/', include('rango.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

Of course in this case rango/urls.py should be untouched.


text:
Q: Haskell: get memory address of a list is there a way to get the address of data element (say a list element) in Haskell.
combineLists :: [a] -> [a] -> [a]

combineLists [] y = y
combineLists (x:xs) y = x : combineLists xs y

*Main> let x=[1,23, 12, 45]
*Main> x
[1,23,12,45]
*Main> let y =[90, 56, 78]
*Main> y
[90,56,78]
*Main> let z = combineLists x y
*Main> z
[1,23,12,45,90,56,78]

Now would z be constructed completely by copying elements from x and y (internal haskell representation) or
would z be something like: z = [ [copy of all elements from x] y]
I wanted to see if &y == &z[4] (z[4] = 90).
Also is there a way to dump the internal representation using something similar to ctypes in Python.
Thanks.

A: You can use StableName or reallyUnsafePointerEquality# (note the name and don't use in real programs; you'll also need MagicHash extension to call it) to check whether two expressions refer to the same object. See What advantages do StableNames have over reallyUnsafePtrEquality#, and vice versa? for the differences.


text:
Q: Computer malware attack while connecting to file with OLEDB I want to know if while trying to connect to a file with OlEDB and this file contains malware, if this malware can be activated.
Even if the answer is yes or no, could you please explain me why and/or how this happens?
I read the sentence below in this article but I'm not sure that while trying to connect with OLEDB that this connection will not activate the entry point of the exe hidden under the xls file in my case:
Almost all viruses are attached to an executable file, which means the virus may exist on a system but will not be active or able to spread until a user runs or opens the malicious host file or program. When the host code is executed, the viral code is executed as well.
Note that I use OLEDB in c# with System.Data.Oledb and with a connection string like this one:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;
Extended Properties="Excel 12.0 Xml;HDR=YES";
Thank you.

A:
could you please explain me why and/or how this happen?

In order to do so, you must understand how malware works. Just like any regular program, it must be executed in order to do its damage. You can rename an infected .exe to .jpg and open it in a photo viewer, nothing will happen.
The same goes for your data source. If you just display its contents, nothing will happen. Unless of course the malware is targeting the display system, which is frequently used for dropping malware: for example known buffer overflows in PDF-, photo- or other document viewers, where a specially crafted file leaks executable code into the stack of the hosting program, so it can run its "installer" or do its damage by running once.


text:
Q: Jetpack compose onClickLabel for Button and IconButton Working on accessibility enhancements for my app.
From Docs, I can see that Card has both onClick and onClickLabel as part of the API.
And for composables without onClick, we can use Modifier.clickable or Modifier.semantics.
But what about Button, IconButton, FloatingActionButton, TextButton and OutlinedButton?
Composables which have onClick as part of API but no onClickLabel.
This works as expected. But is this the correct way to write this code?
IconButton(
    onClick = navigateUp,
    modifier = Modifier.clickable(
        onClickLabel = "Navigate up",
        onClick = {},
    )
) {
    Icon(
        imageVector = Icons.Rounded.ArrowBack,
        contentDescription = stringResource(
            id = R.string.top_app_bar_content_description_navigate_up,
        ),
    )
}

This seems too confusing as IconButton expects onClick. So I cannot go with completely Modifier.clickable or Modifier.semantics.
Similarly Modifier.clickable also expects onClick.
So, I have two onClick for a single composable component which could easily cause a lot of hard to debug bugs.
Reason for the change,
To read "Double tap to Navigate up" instead of the default "Double tap to activate".
P.S:
Compose version - 1.0.4

A: You don't need the Modifier.clickable in this scenario because:

*

*the IconButton already handles clicks via its onClick lambda

*the Icon has a contentDescription field for accessibility

So all you need is this
IconButton(
    onClick = navigateUp,
) {
    Icon(
        imageVector = Icons.Rounded.ArrowBack,
        contentDescription = stringResource(
            id = R.string.top_app_bar_content_description_navigate_up,
        ),
   )
}

A: It doesn't seem to be the prettiest solution but I ended up doing:
      IconButton(
        modifier = Modifier.size(40.dp).clearAndSetSemantics {
            this.onClick(label = closeLabelDescription, action = null)
            this.contentDescription = closeDescription
            this.role = Role.Button
        },
        onClick = onClickClose,
    ) {
        Icon(
            painter = painterResource(R.drawable.ic_close),
            tint = RiotWhite,
            contentDescription = null
        )
    }


text:
Q: How to preserve the ending values of an animation? I use API 10.
I have an ImageView nested inside of a LinearLayout. The ImageView has an OnClickListener (or an OnTouchListener, I'm sure which one I ll use at the end). The ImageView is centered on the screen, and when clicked it performs the following animation.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillEnabled="true"
    android:fillAfter="true"
    >
    <alpha
        android:fromAlpha="1"
        android:toAlpha="0"
        android:duration ="500"
        />

    <translate
        android:fromXDelta="0%"
        android:toXDelta="-100%p"
        android:duration ="1000"
    />
</set>

The problem is that after the animation ends, it returns to its first position, faded out to 0, but it is still clickable even if it doesn't show up. I click on an empty space where the ImageView was first positioned, and it performs the the animation again. Like clicking a ghost.
How do I make it so that the ImageView stays at the position written at android:toXDelta ??

A: You can set an animationListener to your animation to tackle the problem, I created this simple fonction:
public void startAnimation(final View v, final int animationResourceId, AnimationListener l){
    Animation anim;

    if(v!=null){    // can be null, after change of orientation
        anim = AnimationUtils.loadAnimation(v.getContext(),resId);
        v.setAnimation(anim);
        anim.setAnimationListener(l);
        v.startAnimation(anim);
    }
}

Then every time I need to animate an view, I can do something like this:
startAnimation(myView, R.anim.my_anim, new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                myView.setVisibility(View.GONE);
            }
        });


text:
Q: Why custom DialogPreference doesnt trigger on onSharedPreferenceChanged listener? I am trying to make dialog preference in preferences, where user just click positive button to trigger some action. (Clear database? No | Yes)
public class MyDialogPreference extends DialogPreference {

    public MyDialogPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        Log.d(MainActivity.TAG, "# onDialogClosed: " + positiveResult);
    }

}

I dont actually want to persist anything, just trigger  onSharedPreferenceChanged listener, so I can handle it in the activity. But I cant figure out how to trigger it
//SOLUTION
@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);
    if(positiveResult) {
        persistBoolean(!getPersistedBoolean(true));
    }
    Log.d(MainActivity.TAG, "# onDialogClosed: " + positiveResult);
}

A: onSharedPreferenceChanged is called because of the inbuilt callback registered on the sharedpreference, so unless you change the key associated with dialogPreference you are not going to get the onSharedPreferenceChanged callback.
So what you could do is everytime dialog is closed, you could change the value in key. Something like below
text = getPersistedString("1")
if(text.length() > 10)
   text = "1";
persistString(text+"1");

Make sure your dialogPreference has a key and android:persistent as true in xml


text:
Q: Convert PDF to word without using third party software? How to convert PDF to word without using third party software? I found several tools that claim they can convert PDF to word, but most of them are not free. Moreover those tools do not work well on the converting thing.

A: You haven't specified which version of MS Word you are using however if you have Word 2013 or newer it will automatically convert a PDF to Word if you open a pdf document with it.
Alternatively if you have an older version of Word you can open a free account at OneDrive, upload the pdf in your drive and then use the option to convert and download the file as word: http://newtechworld.net/convert-pdf-to-word-using-onedrive/

A: You could simply do that from the pdf file itself.


text:
Q: Cross table query I have a table with a foreign key assigned to a master table. Usually, in SSMS, I'd get data from the foreign key table like so:
SELECT * from COMDATE
WHERE COMDATE.FORNLINK = MASTER.LINK

Or something similar.
In MS Access, this doesn't work. In fact, Access asks me to provide a value for MASTER.LINK. Is there a way to do this? Also, why is it so different in T-SQL?

A: You forgot MASTER table
SELECT COMDATE.* from COMDATE, MASTER
WHERE COMDATE.FORNLINK = MASTER.LINK

I'll encourage to use INNER JOIN instead
SELECT C.* FROM COMDATE C
  INNER JOIN MASTER M ON C.FORNLINK = M.LINK


text:
Q: How to remove image url from sitemap.xml Magento 2? I have created sitemap.xml in the website. In which, Image URL coming with cdn link.
I have change setting from admin but still is showing.
I don't want to use CDN URL in the sitemap.
How to remove product image URLs from the sitemap.xml?

A: You don't need any custom code to disable the image from sitemap.xml.
Magento has a setting at admin from where you can disable product image from the sitemap.
Logging at admin.
Then navigate to STORE>Configuration>Catalog>XML Sitemap>Products Options
and here you see a  setting Add Images into Sitemap and Make it toNO to remove images from the sitemap.


text:
Q: Onload() handler not responding in IE I'm creating a canvas and using drawImage() to draw an inline svg. Everything works okay but I'm stuck because of the below problem...
My problem is that the onload handler not responding in IE?? Rhis works in FF and chhrome. How do I fix it to work in IE 9 upwards?
img2.onload = function() {
     console.log("load");
}

jsFiddle
function createme() {
      var test = $('<canvas />', { id : 'mycanvs' })
      $('#album').append(test);

      var svg2 = document.getElementById('sSource').innerHTML,
          vms = test[0], //canvas
          ctx2 = vms.getContext('2d');

      svgToImage(svg2);

      function svgToImage(svg2) {
        var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
            img2 = new Image;
          alert("just before onload")
          img2.onload = function() {
              console.log("load"); // does not show
          }
          img2.src = nurl;
      }
}

A: I don't have an IE VM running at the moment, but according to their docs the handler has to be defined before the object itself:

To ensure that an event handler receives the onload event for these
  objects, place the script object that defines the event handler before
  the object and use the onload attribute in the object to set the
  handler.

I don't see why your code wouldn't work in IE, but this fiddle tweaks it slightly so your handler is defined before you create the image object... give this a try:
function createme() {
      var test = $('<canvas />', { id : 'mycanvs' });
      var onloadHandler = function() {
          console.log("load");
      };
      $('#album').append(test);

      var svg2 = document.getElementById('sSource').innerHTML,
          vms = test[0], //canvas
          ctx2 = vms.getContext('2d');

      function svgToImage(svg2) {
        var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
            img2 = new Image;

          img2.onload = onloadHandler

          img2.src = nurl;
      }
      svgToImage(svg2);
}
createme();

https://jsfiddle.net/z769z7af/10/


text:
Q: Load Related Entities With EF 5 Context.Database.SqlQuery I have this SP,
ALTER PROCEDURE [dbo].[GetPageByID]
(
    @ID INT
)
AS

    SELECT  P.*
            ,A.*
    FROM    Page P
            LEFT OUTER JOIN [dbo].[Application] A ON P.ApplicationVersion = A.[Version]
    WHERE   P.ID = @ID;

and I am using this code to load into objects,
        return context.Database.SqlQuery<Page>(@"EXEC GetPageByID {0}", new object[] { id }).FirstOrDefault();

This only loads properties of Page but not loading Page.Application property. Any way to tell EF to do this.

A: No. SqlQuery is able to load only the main entity you are asking for - in your case the Page. If you want to load children as well you cannot use SqlQuery. EF5 with EDMX provides mapping for stored procedures with multiple result sets (that means you will need stored procedure with two queries - one for pages and second for applications). It is not supported with code first yet.


text:
Q: Vuetify Datatable Actions Row Is it possible to left align the rows per pages and page navigation and put a button in its place in the same row?

A: The actions row are aligned right by default. There is a way to achieve what you want though. You can use custom pagination and hide the current one:
 <v-data-table
    :headers="headers"
    :items="desserts"
    :search="search"
    hide-actions
    :pagination.sync="pagination"
  >

And add this after the datatable:
<v-layout row justify-center>
    <v-pagination v-model="pagination.page" :length="pages"></v-pagination>
    <v-btn class="test">test</v-btn>
</v-layout>

See more here.
Here is a Codepen in action.

A: I found the easiest way is to add the button to some data table slot you use and just position the button relatively to the table.
<v-data-table
    style="position: relative;">

    <template slot="footer">
        <v-btn style="position: absolute; left: 10px; bottom: 10px;">
            test
        </v-btn>
    </template>

</v-data-table>

A: Simplest way by CSS :
template in your datatable :
<template v-slot:actions-prepend>
    <v-btn>
        Click me !
    </v-btn>
</template>

CSS :
.my-grid .v-datatable__actions > div:first-child {
   flex: 1;
}

Working snippet :

new Vue({
  el: '#app',
  methods: {
    onClick() { this.dark = !this.dark; }
  },
  data: {
    dark: true,
    headers: [{
        text: 'Dessert (100g serving)',
        value: 'name'
      },
      {
        text: 'Calories',
        value: 'calories'
      },
      {
        text: 'Fat (g)',
        value: 'fat'
      },
      {
        text: 'Carbs (g)',
        value: 'carbs'
      },
      {
        text: 'Protein (g)',
        value: 'protein'
      },
      {
        text: 'Iron (%)',
        value: 'iron'
      }
    ],
    desserts: [{
        name: 'Frozen Yogurt',
        calories: 159,
        fat: 6.0,
        carbs: 24,
        protein: 4.0,
        iron: '1%'
      },
      {
        name: 'Ice cream sandwich',
        calories: 237,
        fat: 9.0,
        carbs: 37,
        protein: 4.3,
        iron: '1%'
      },
      {
        name: 'Eclair',
        calories: 262,
        fat: 16.0,
        carbs: 23,
        protein: 6.0,
        iron: '7%'
      },
      {
        name: 'Cupcake',
        calories: 305,
        fat: 3.7,
        carbs: 67,
        protein: 4.3,
        iron: '8%'
      }
    ]
  }
})
.my-grid .v-datatable__actions > div:first-child {
    flex: 1;
}
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@1.x/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">

  <v-app :dark="dark">
    <v-content>
      <v-data-table :headers="headers" :items="desserts" class="my-grid">
        <template v-slot:items="{item}">

              {{item.name}}
              {{item.calories}}
              {{item.fat}}
              {{item.carbs}}
              {{item.protein}}
              {{item.iron}}

          </template>
        <template v-slot:actions-prepend>
              <v-btn @click="onClick">
                  Switch mode
              </v-btn>
          </template>
      </v-data-table>
    </v-content>
  </v-app>


text:
Q: how to add mysql jdbc connector in classpath I have upgraded to solr 3.6 to SOLR 4.0. i am using dataimporthandler to extract data from database.
I have copied mysql-connector-java-5.1.20-bin.jar into apache-solr-4.0.0-ALPHA/example/lib folder.
I have also added it in classpath using cmd
export CLASSPATH=.:$JAVA_HOME/lib/classes.zip:/usr/solr4/apache-solr-4.0.0-ALPHA/example/lib/mysql-connector-java-5.1.20-bin.jar

When i browse solr/admin page and click on java properties it shows all .jar files from solr-home/lib folder in java.class.path but doesnt add mysql-connector-java-5.1.20-bin.jar
What will be the reason that mysql-connector-java-5.1.20-bin.jar not getting added in java classpath?
let me know if i am missing anything.


text:
Q: Does Hyperledger Fabric need Docker? This may be the stupid question.
Does Hyperledger Fabric require Docker for its operations.
I'm just wondering that Docker is needed only if we need to run Fabric peer, orderer or couchDB as virtual machine in the same physical machine. I think Docker might not be necessary if we install those sofwares (peer, order, couchDB, etc) natively on the separate and same server.
Thank you.

A: The question as to whether Docker is required to run a peer, orderer, fabric-ca, etc. depends on what effort you are willing to expend.
The Hyperledger Fabric community publishes stable, tested Docker images for X86, PowerPC and s390 (mainframe) architectures for each of its releases. These images are based on Ubuntu.
To use the Hyperledger Fabric published release images, you need Docker and some form of orchestration support. For sample use cases, we provide some simple Docker Compose definitions. Hyperledger Cello and other provisioning platforms such as the IBM sandbox, provide kubernetes helm charts.
It is possible to build the binaries outside of their Docker images without modification of the source. However, if you wish to build for an alternative OS (e.g. Windows, RHEL or CENTOS, etc) then you will need to modify the build process. However, it can and has been done. Suggest you reach out to the hyperledger-fabric@lists.hyperledger.org mailing list to see if any in the community that have built for alternative deployment will share their work.

A: Starting HLF 2.0 things have changed. According to documentation, chaincode can be in 'external containers' also.
https://hyperledger-fabric.readthedocs.io/en/release-2.0/cc_launcher.html

A: Just so this point does not go unnoticed, while you do not need to run the peer in a Docker container, endorsing peers (the ones which run chaincode) need access to a Docker daemon (ideally on the same host).  Chaincode is currently only deployed via Docker containers.

A: Yes, it is the second heading on the prerequisites page at http://hyperledger-fabric.readthedocs.io/en/latest/prereqs.html

Docker and Docker Compose


text:
Q: Matrix direct sum Is there a function in MATLAB that allows us to do matrix direct sum? For example,
A = [1 2 3
     3 4 5]
B = [5 6
     7 8
     9 8]

and we want the direct sum A ⊕ B that gives us:
directSum(A,B) = [1 2 3 0 0
                  3 4 5 0 0
                  0 0 0 5 6
                  0 0 0 7 8
                  0 0 0 9 8]

If there is not, what are some quick ways to implement this?

A: Use blkdiag to compute the direct sum of matrices:
A = [1 2 3; 3 4 5];
B = [5 6; 7 8; 9 8];
blkdiag(A, B)

% ans = 5x5
%
%      1     2     3     0     0
%      3     4     5     0     0
%      0     0     0     5     6
%      0     0     0     7     8
%      0     0     0     9     8


text:
Q: Why any event (e.g Changing QLabel or QPushButton's Text) is reverting moved widget to it's first position in the Layout? I have extended a class from QpushButton in my Qt Program that overrides mousepress & mousemove events and cause the parent widget to move with left mouse click in the layout. but when I change some widget's properties in parent widget for example QLabel's text or QpushButton's text ,the parent widget goes back to it's original position in the layout , what's wrong with my code & how can I prevent this ?
any help is appreciated
here is My code :
MainWidget::MainWidget(QWidget *parent)
   : QWidget(parent)
   , ui(new Ui::MainWidget)
{
   ui->setupUi(this);

   MoveButton *movebut = new MoveButton(this);
   ui->horizontalLayout->addWidget(movebut);

   connect(movebut , &MoveButton::positionChanged , ui->widgetMove , [this](const QPoint &newPos){
       ui->widgetMove->move(ui->widgetMove->mapToParent(newPos));
       currentPos = mapToParent(newPos);;
   });
}

MainWidget::~MainWidget()
{
   delete ui;
}

MoveButton::MoveButton(QWidget *parent) : QPushButton(parent)
{
   setText("Draggable Button");
   setMouseTracking(true);
   setContentsMargins(0 , 0 , 0 , 0);
   setMaximumHeight(30);
}

QSize MoveButton::minimumSizeHint() const
{
   return QSize(100 ,30);
}

void MoveButton::mousePressEvent(QMouseEvent *event)
{
   if (event->button() == Qt::LeftButton)
   {
       offset = event->pos();
       qDebug() << offset;
   }
}

void MoveButton::mouseMoveEvent(QMouseEvent *event)
{
   //this->setCursor(Qt::OpenHandCursor);
   if(event->buttons() & Qt::LeftButton)
   {
       emit positionChanged(event->pos() - offset);
   }
}

void MainWidget::on_pushButton_clicked()
{
   ui->pushButton->setText("Clicked");
}

I have removed all spacers , but I have this issue again


text:
Q: How can I run migration on Heroku Cloud databases(ClearDB) in Laravel I'm facing a problem on databases migration on Heroku .Im trying to deploy my laravel project with mysql databases using clearDB on Heroku. I have deploy my web app successfully on heroku it work fine on pages that has no interaction with databases but the problem is the pages that have interaction with databases would get 500 server error.So it is the problem with databases I think because I haven't run migration but I have already put Config Vars value for clearDB on heroku Config Vars.So I have tried to run migration on Heroku CLI
heroku run php artisan migrate --app <app Name>

the first two time I run this command Its show an error
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schem  a = forge and table_name = migrations and table_type = 'BASE TABLE')

SQLSTATE[HY000] [2002] Connection refused

pic for error
I keep trying to migrate it but after that I got this error that I dont have access to an app.
Error: You do not have access to the app laravel-test-demo.

Error ID: forbidden
but I have already login in heroku cli
second error


text:
Q: To get current ip address in c# from client side In my application,i need to get the ip address of user who loads the application
I tried various way to get ip address.But when try to load application ,not getting current ip address.
 protected string GetIPAddress()
    {
        System.Web.HttpContext context = System.Web.HttpContext.Current;
        string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (!string.IsNullOrEmpty(ipAddress))
        {
            string[] addresses = ipAddress.Split(',');
            if (addresses.Length != 0)
            {
                return addresses[0];
            }
        }

        return context.Request.ServerVariables["REMOTE_ADDR"];
    }

string ipAddress=Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(o => o.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).First().ToString()

string ipAddress=(HttpContext.Current.Request.UserHostAddress != null) ? HttpContext.Current.Request.UserHostAddress : null;

  using (WebClient wc = new WebClient())
        {
            ipAddress = wc.DownloadString("https://api.ipify.org/");
        }

A: Try this:
public static string GetLocalIPAddress()
{
    var isConnected = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
    if(isConnected){
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
    }
    throw new Exception("No network adapters with an IPv4 address in the system!");
}


text:
Q: JS: Display image from numpy array I have a binary file that I read using python numpy, and for the moment I display this file as an image using matplotlib:

I need to display this image in my App (Electron JS App), but not as a .jpg, as a dynamic image (so I can use the mouse to see the data).
I know there are some python libraries for this (like plotly), but couldnt find something similar for js.
My main idea is to do all the process using javascript not python:
so I will need to read the binary files, reshape the array, and display it...
Any ideas are welcome.


text:
Q: Failing to populate column 'method' in a factory I need to define a factory for a database table which contains column named 'method'.
I've tried something like this:
FactoryGirl.define do
  factory :notification_baby_offset, class:'NotificationTemplate' do
    ...
    method {{ 'email' => false, 'notification' => true }}
    ...
  end
end

But, when I tried to build it, I got an error saying:
`method': wrong number of arguments (0 for 1) (ArgumentError)

It appears to identify 'method' as a function rather than a database column. I tried to emphasize this by :method or "method", but that didn't work.
So, I have to build this factory like this for it to work:
FactoryGirl.create(:notification_baby_offset, method: { 'email' => false, 'notification' => true })

Is where a way to avoid this hack and define this column properly in a factory?

A: Try this:
FactoryGirl.define do
  factory :notification_baby_offset, class:'NotificationTemplate' do
    ...
    after(:build) do |notification|
      notification.method = { 'email' => false, 'notification' => true }
    end
    ...
  end
end

Or even (if your new supports passing attributes):
FactoryGirl.define do
  factory :notification_baby_offset, class:'NotificationTemplate' do
    ...
    initialize_with { new(method: { 'email' => false, 'notification' => true }) }
    ...
  end
end


text:
Q: Jquery selector by width Would it be possible to select a table with a specific width ?
Thanks

A: Yes like this:
$('table[width="700"]')

Or you can get all tables having width with whatever value like this:
$('table[width]')

A: Or create your own selector
$.expr[':'].atLeast700px = function(obj){
  return $(obj).width() >= 700;
};

$('table:atLeast700px');  // returns all your tables 700px or wider

A: Use the filter() function:
$('table').filter(function() {
    return $(this).width() > 700;
});


text:
Q: How do I decorate a partially applied function in Python 3? I created a decorator factory that is parameterized by a custom logging function like so:
def _log_error(logger):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except Exception as e:
                logger(e)
                return None
        return wrapper
    return decorator

Which I now want to use to decorate a partially-applied function foo:
foo = partial(bar, someparam)

I've tried all of the following:
@_log_error(logger)
foo = partial(bar, someparam)

log_error = _log_error(logger)
@log_error
foo = partial(...)

foo = partial(...)
@log_error
foo

@log_error
(foo = partial(...))

AFAICT both log_error = _log_error(logger) / @log_error and @_log_error(logger) seem totally valid ways of producing the decorator and it works fine on normally declared functions. But when trying to use on the partially applied function I get syntax errors at the start of foo =, and googling while yielding excellent resources on working with decorators and functools.partial in general have not given me anything on this specific case.

A: Decorators don't work on assignments. But since using a decorator is the same thing as calling the decorator, you can do
foo = _log_error(logger)(partial(bar, someparam))

A: Either way works
Here's another way you can do it using Either – This answer gets its inspiration from Brian Lonsdorf's egghead series: Professor Frisby Introduces Composable Functional JavaScript
We'll take some of what we learned there and write some super sweet functional python codes
class Map (dict):
  def __init__(self, **xw):
    super(Map, self).__init__(**xw)
    self.__dict__ = self

def Left (x):
  return Map(
    fold = lambda f, g: f(x),
    bimap = lambda f, g: Left(f(x))
  )

def Right (x):
  return Map(
    fold = lambda f, g: g(x),
    bimap = lambda f, g: Right(g(x))
  )

Note: This is a very incomplete implementation of Left and Right but it's enough to get this specific job done. To take advantage of the full power of this super-powered data type, you'll want a complete implementation.

Generics promote code reuse
We'll setup a few more generic functions
def identity (x):
  return x

def try_catch (f):
  try:
    return Right(f())
  except Exception as e:
    return Left(e)

def partial (f, *xs, **xw):
  def aux (*ys, **yw):
    return f(*xs, *ys, **xw, **yw)
  return aux

Now we have enough to define log_error – the syntax is a little wonky for writing curried functions in Python, but everything works as expected.
In plain English: we try applying f and get back a value. If the value is an error (Left), call logger, otherwise return the value (identity)
def log_error (logger):
  def wrapper (f):
    def aux (*xs, **xw):
      return try_catch (lambda: f(*xs, **xw)).bimap(logger, identity)
    return aux
  return wrapper

Putting it all together
Now let's try it with a little function
def foo (x,y,z):
  return (x + y) * z

What you wanted to do was wrap a partially applied function in your using your custom logger
foo_logger = log_error(lambda err: print("ERROR:" + str(err))) (partial(foo,'a'))

foo_logger('b',3).fold(print, print)
# ('a' + 'b') * 3
# 'ab' * 3
# => ababab

foo_logger(1,3).fold(print, print)
# ('a' + 1) * 3
# ERROR: Can't convert 'int' object to str implicitly
# => None

Understanding the results
As you can see, when there is no error present (Right), evaluation just keeps on moving and the computed value is passed to print.
When an error occurs (Left), the logger picks it up and logs the error message to the console. Because the logging function has no return value, None is passed along to print


text:
Q: Rename a File Every Day, Using the Current Date as Part of the File Name I have a file that has the name BackupFile-08072018.cvs, where the 06072018 represents yesterday's date. Each morning I would like to run my daily code and at the end the out put name of my file should uses today's date: BackupFile-09072018.cvs. How can I code that ?
output_wb <- paste(output_dir,"BackupFile-08072018.cvs",sep="")

A: Something like this?
df1 <- mtcars
setwd("...") # replace the dots with the appropriate folder where you want to save your file each day
write.csv(df1, paste0("BackUpFile-", format(as.Date(Sys.Date() - 1), "%d.%m.%Y"), ".csv"))

A: You can create both folder and file name using current date by using paste() function.
 mainDir <- "C:/File-Path/"  ### Define main Directory
 subDir <- paste("outputDirectory-",Sys.Date()) ### Define sub Directory using current date
 dir.create(file.path(mainDir, subDir), showWarnings = FALSE) ### Create sub directory inside main directory
 setwd(file.path(mainDir, subDir)) ### change the working directory
 write.csv(df,paste("C:/File-Path/",subDir,"/request--",Sys.Date(),".csv",sep = ""),row.names = F) ### write your csv file inside sub directory.

You may ignore the top 4 steps if you do not want to create a new folder each day.


text:
Q: Zooming of image view in not working correctly in ios This is the point where I got stuck for the past one week.
I'm displaying an image in a UIImageView. Users have an option for zooming the images.
The images is being fetched from a server.
When the user zooms the image, we are sending x1,x2,y1,y2 (of imageview) points to the server and the corresponding zoomed image is fetched from the server and being displayed.
The zoom is working only for the first time. When the user tried to zoom again and again, it is not working.
For this, I have set a bool value named windowPanZoomOccured.
- (void)pinchGestureHandler:(UIPinchGestureRecognizer *)sender
{
            windowPanZoomOccured = TRUE;

                [self handleGestureEventWebserviceForGesture:@"zoom-out" withGestureObject:gesture_ andframeId:currentFrame_];

}//gesture_ object contains the points and velocity.

//Code for checking whether zoom event fired or not.
if (windowPanZoomOccured)
        {
            NSLog(@"The value of the bool here in unpackdata %@\n", (windowPanZoomOccured ? @"YES" : @"NO"));
            NSLog(@"enter here");
            imageView.image = Nil;

            imageView.image = image;
           // [self.imageView setNeedsDisplay];

            windowPanZoomOccured = FALSE;
        }

I tried by  // [self.imageView setNeedsDisplay]; But its not working. Any ideas ???

A: You can put the imageview into a scrollView and do the zoom callback in

*

*(void)scrollViewDidZoom:(UIScrollView *)scrollView


text:
Q: How to ensure AJAX encoding will work I'm using Jquery to submit the value of a <textarea> through AJAX to a PHP script. This value may contain punctuation characters (!,?,#,@) as well as single and double quotes, and other non-alphanumeric characters. Does Jquery take care of encoding all this stuff or do I need to do it myself? How can I be certain that whatever the user typed in the <textarea> would be submitted?

A: I use encodeURIComponent for that. If there's a risk the text contains a '%'-sign, i replace that with it's htmlcode (&#something) before encoding.

A: Yes, jquery will care about that. but always add the correct encoding to the page you are browsing at.
in my case I try to use always utf-8
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


text:
Q: EF Core - Discriminator is Guid? When a School entity is added to the database, the discriminator is being set to a guid instead of "school".  Subsequent reads where the type is School does not return the new row.  Why is it a Guid?  I don't define/set the discriminator in my code.
Using EF Core 1.1.2 with VS 2017 15.2 with SQL 2016.

A: Thanks for your response and sorry for taking so long to respond.  The project is rather large and difficult to isolate the issue.
The solution was to add Microsoft.EntityFrameworkCore.SQLServer version 1.1.1 to my project.  Prior to that, the project had no reference to it.
When the project was inserting a guid for a discriminator, I could VS => Debug => Windows => Modules and see that Microsoft.EntityFrameworkCore.SqlServer.dll was version 1.00.4.30428 (presumably from a child project).
When the project was inserting the class name for a discriminator (my desired behavior), I could VS => Debug => Windows => Modules and see that Microsoft.EntityFrameworkCore.SqlServer.dll was version 1.01.1.30217.
Thanks again.


text:
Q: How to use getFilter form Listadapter I try to filter in Listview where the adapter is ListAdapter, I couldn't find getFilter() , Is there any work around? Below is my code.
// Adding menuItems to ListView
            final ListAdapter adapter = new SimpleAdapter(this, songsListData,
                    R.layout.playlist_item, new String[]{"songTitle"}, new int[]{
                    R.id.songTitle});

            setListAdapter(adapter);

            sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    //adapter.getFilter
                    return false;
                }
            });

A: I find myself, It's simple.
final SimpleAdapter adapter = new SimpleAdapter(this, songsListData,
                    R.layout.playlist_item, new String[]{"songTitle"}, new int[]{
                    R.id.songTitle});

    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    adapter.getFilter().filter(newText);
                    return false;
                }
            });


text:
Q: Use Go goto label on Err I want to use label to minimize err part like this:
package main
import (
    "fmt"
    consul "github.com/hashicorp/consul/api"
    "os"
)
func main(){
    client,err := consul.NewClient(consul.DefaultConfig())
    if err != nil {
        goto Err
    }
    agent := client.Agent()
    checkReg := agent.AgentCheckRegistration{
        ID:   "test-check",
        Name: "test-check",
        Notes: "some test check",
    }
    if err = agent.CheckRegister(checkReg); err !=nil{
        goto Err
    }
Err:
    fmt.Println(err)
    os.Exit(2)
}

so i could have one place to put all the err handling in one place, but seems not working as
./agent.CheckRegister.go:10:8: goto Err jumps over declaration of checkReg at
./agent.CheckRegister.go:13:19: agent.AgentCheckRegistration undefined (type *api.Agent has no field or method AgentCheckRegistration)

is there a way to use goto to make it work?

A: The reason why the compiler is complaining is defined in the Go spec:

Executing the "goto" statement must not cause any variables to come
into scope that were not already in scope at the point of the goto.
For instance, this example:
  goto L  // BAD
  v := 3
L:

is erroneous because the jump to label L skips the creation of v.

So you'll need to restructure your code. If you want to keep using goto here (as opposed to, say, if-else statements), then you'll have to move all the declarations up.
Note that you can split it like this:
   var v Type
   ...
L: ...
   v = FunctionThatReturnsType()

It should be OK to goto L here.


text:
Q: SDDM was broken after system update I'm using Arch Linux with KDE and SDDM for about 6 months. A few days ago I got a usual system update. On next day, after reboot, system stuck at a black screen with Starting version 243.0-1-arch. Then I press Ctrl+Alt+F2 and inter tty terminal, logged in and $startx - GUI was loaded. Next time when I try to start sddm manually in tty terminal with $ systemctl start sddm nothing happened. That's what  journalctl -b -1 | grep sddm says about it:
сен 23 02:48:55 jenkins audit[1]: SERVICE_START pid=1 uid=0 auid=4294967295 ses=4294967295 msg='unit=sddm comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? terminal=? res=success'
сен 23 02:48:55 jenkins sddm[630]: Initializing...
сен 23 02:48:55 jenkins sddm[630]: Starting...
сен 23 02:48:55 jenkins sddm[630]: Logind interface found
сен 23 03:00:03 jenkins sddm[630]: Signal received: SIGTERM
сен 23 03:00:03 jenkins systemd[1]: sddm.service: Succeeded.
сен 23 03:00:03 jenkins audit[1]: SERVICE_STOP pid=1 uid=0 auid=4294967295 ses=4294967295 msg='unit=sddm comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? terminal=? res=success'
сен 23 03:00:03 jenkins kernel: audit: type=1131 audit(1569196803.849:47): pid=1 uid=0 auid=4294967295 ses=4294967295 msg='unit=sddm comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? terminal=? res=success'

And another listing systemctl status sddm:
● sddm.service - Simple Desktop Display Manager
   Loaded: loaded (/usr/lib/systemd/system/sddm.service; enabled; vendor preset: disab>
   Active: active (running) since Mon 2019-09-23 10:30:06 MSK; 6h ago
     Docs: man:sddm(1)
           man:sddm.conf(5)
 Main PID: 427 (sddm)
    Tasks: 2
   Memory: 12.8M
   CGroup: /system.slice/sddm.service
           └─427 /usr/bin/sddm

сен 23 10:30:06 jenkins systemd[1]: Started Simple Desktop Display Manager.
сен 23 10:30:06 jenkins sddm[427]: Initializing...
сен 23 10:30:06 jenkins sddm[427]: Starting...
сен 23 10:30:06 jenkins sddm[427]: Logind interface found

What could go wrong?

A: This seems to be a race condition. SDDM starts, while the video driver is not ready yet.
A proper solution is to add your graphics driver to /etc/mkinitcpio.conf to the MODULES key. Then you have to rebuild the ramdisk that loads on startup: mkinitcpio -p linux. After that, reboot.
The graphic driver to add depends on your hardware. For me it is (as I use an Intel card), it is i915. Type lsmod to get a list of all loaded kernel modules.

A: Thank you dritter for your answer, unfortunately I can't verify its correctness because I found another solution, even two (I checked both options - all are working). So, first solution is to downgrade Linux-lts core (in my case from 4.19.73-1 to 4.19.72-1 or lower). Another solution (that I settled on) is to install nvidia-dkms drivers.


text:
Q: To get the values from the custom settings in picklist based on selected picklist value On select of particular region the countries under that specific region has to display under country picklist.I have tried doing that but in country picklist i am not getting any values.Below is the apex class and visualforce.
VisualForce
 <apex:page Controller="testing_custom">
   <apex:form >
     <apex:selectList label="Region" value="{!region}" size="1" multiselect="false">
      <apex:selectOptions value="{!regionsSelectList}"/>
      <apex:actionSupport event="onchange" action="{!fetchCountry}" rerender="contrySelect"/>
     </apex:selectList>
  <apex:outputPanel id="contrySelect">Country
         <apex:selectList label="Country" value="{!country}" size="1" multiselect="false" >
         <apex:selectOptions value="{!lstCountriesSelectList}"/>
        </apex:selectList>

        </apex:outputPanel>

   </apex:form>
  </apex:page>

apex
  public class testing_custom
 {
   public String region{get;set; }
   public String country{get;set;}
    public List<SelectOption> lstCountriesSelectList {get;set;}
    public testing_custom{
    lstCountriesSelectList = new List<SelectOption>();
    }
  //For getting region list from custom settings object
    public List<SelectOption> getregionsSelectList(){
    List<SelectOption> options = new List<SelectOption>();
   set<String> setUniqueRegion = new set<String>();
   for(OppCountryRegionMapping__c setting :         OppCountryRegionMapping__c.getAll().values()){
   if(!setUniqueRegion.contains(setting.Region__c)){
    options.add(new SelectOption(setting.Region__c, setting.Region__c));
    setUniqueRegion.add(setting.Region__c);
   }
  }

    return options;
  }

     //For getting country list based on selected region from custom settings object
    public List<SelectOption>  getCountriesSelectList() {

    List<SelectOption> options = new List<SelectOption>();

     for(OppCountryRegionMapping__c setting : OppCountryRegionMapping__c.getAll().values()) {

      if (setting.Region__c== this.region) {
        options.add(new SelectOption(setting.Region__c,setting.Country__c));

        }

      }
       system.debug('*****selected value inside'+options);
       return options;
      }

Thanks
When i click on region ASIA,its displaying the corresponding country value.Below is the screenshot.

When i click on another region LATAM the corresponding country is appending with the ASIA region's country values.I have encircled the value which is appending.Below is the screenshot

When the page loads for the first time

A: You would need to send an ajax request in order to get the updated countries values.
You can use actionsupport for this purpose, try the below code:
<apex:page Controller="testing_custom">
   <apex:form id="frmId">
     <apex:selectList label="Region" value="{!region}" size="1" multiselect="false">
      <apex:selectOptions value="{!regionsSelectList}"/>
      <apex:actionSupport event="onselect" action="{!getCountriesSelectList} rerender="frmId" status="SearchStatus />
     </apex:selectList>
 <apex:selectList  label="Country" value="{!country}" size="1" multiselect="false">
      <apex:selectOptions value="{!CountriesSelectList}}"/>
     </apex:selectList>
   </apex:form>
  </apex:page>

In your controller there is a mismatch between the things you are saving in the selectOptions and compairing:
you need to change this if condition :
if (setting.Region__c== this.region)

to
if (setting.name == region)

as you the value which is passed is "setting.name":
options.add(new SelectOption(setting.name, setting.Region__c));

updated code:
public List<SelectOption>  getCountriesSelectList() {

    List<SelectOption> options = new List<SelectOption>();

     for(OppCountryRegionMapping__c setting : OppCountryRegionMapping__c.getAll().values()) {

      if (setting.name == region) {
        options.add(new SelectOption(setting.name,setting.Country__c));

        }

      }
       system.debug('*****selected value inside'+options);
       return options;
      }

A: try with this.. In your controller you are giving select option value = name
and comparing in another method Region ... that is the error
So now assign selectoption value to region and compare with that in another method
also you need to add action support so when you change the region then controller method should called
<apex:page Controller="testing_custom">
   <apex:form >
     <apex:selectList label="Region" value="{!region}" size="1" multiselect="false">
      <apex:selectOptions value="{!regionsSelectList}"/>
      <apex:actionSupport event="onchange" action="{!fetchCountry}" rerender="contrySelect"/>
     </apex:selectList>
     <apex:outputPanel id="contrySelect">
         <apex:selectList label="Country" value="{!country}" size="1" multiselect="false" >
      <apex:selectOptions value="{!lstCountriesSelectList}"/>
     </apex:selectList>

     </apex:outputPanel>

   </apex:form>
  </apex:page>

Controller
 public class testing_custom
 {
   public String region{get;set; }
   public String country{get;set;}
   public List<SelectOption> lstCountriesSelectList {get; private set;}
   public testing_custom(){
    lstCountriesSelectList=new  List<SelectOption>();
    if(OppCountryRegionMapping__c.getAll().values().size()> 0)
        region = OppCountryRegionMapping__c.getAll().values()[0].Region__c;
    fetchCountry();
  }

  //For getting region list from custom settings object
    public List<SelectOption> getregionsSelectList(){
    List<SelectOption> options = new List<SelectOption>();
   set<String> setUniqueRegion = new set<String>();
   for(OppCountryRegionMapping__c setting :         OppCountryRegionMapping__c.getAll().values()){
   if(!setUniqueRegion.contains(setting.Region__c)){
       options.add(new SelectOption(setting.Region__c, setting.Region__c));
       setUniqueRegion.add(setting.Region__c);
   }
  }

    return options;
  }

   public void fetchCountry(){
       lstCountriesSelectList = new List<SelectOption>();
       system.debug('========this.region======='+this.region);
       for(OppCountryRegionMapping__c setting : OppCountryRegionMapping__c.getAll().values()) {

      if (setting.Region__c== this.region) {
            lstCountriesSelectList.add(new SelectOption(setting.name,setting.Country__c));
        }
      }
   }
 }


text:
Q: GOOGLE SHEETS - How do i copy a checkbox value and keep the cell editable? This is my first post, and I'd like to preface that I'm not a programmer: I know some Excel and Google Sheets formulas, and that's it.
Here's my problem. In a Google Sheets page, I have some checkbox values that I need to copy to another set of checkboxes in another page in the same file. The problem is that I need to keep the  receiving checkboxes editable, while Google Sheets doesn't allow me this.
Basically, what I've done is: in a cell in page 2 (the receiving one) I've inserted a checkbox, and then added a formula to that cell to copy the corrisponding value from a checkbox in page 1 (the starting one):
=page1!A1
With this formula, the receiving checkbox copies the value from the starting one, but becomes uneditable (= I can't manually change the value of that checkbox), while I need it to remain editable. It's not a problem to lose the formula, but I need the receiving checkbox to remain editable.
Is there a way around this problem without complicated codes or macros? Thanks everyone :)


text:
Q: Magento 2: Obtaining an order object by an increment id in a loop using repositories and SearchCriteriaBuilder This is my first stack exchange question, so I apologise in advance if I've not asked it in the correct way. I've just begun the process of getting to grips with Magento 2 in preparation for a migrating a few sites from Magento 1.
I've been reading quite a few posts on the best way to load an order from an increment id and it appears that that the recommended way is using repositories and SearchCriteriaBuilder objects as per this post Magento 2.1.1 How to load Order with Increment ID using OrderRepository object. The post suggests passing the SearchCriteriaBuilder object into the constructor.
private $orderRepository;
private $searchCriteriaBuilder;

public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Sales\Model\OrderRepository $orderRepository,
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
){
    $this->orderRepository = $orderRepository;
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    parent::__construct($context);
}

and then obtaining the order using something like
$searchCriteria = $this->searchCriteriaBuilder
    ->addFilter('increment_id', '000000001', 'eq')->create();
$orderList = $this->orderRepository->getList($searchCriteria)->getItems();

$order = $orderList[0];

My question, however, is whether this would work in a loop
foreach ($incrementIds as $incrementId) {
    $searchCriteria = $this->searchCriteriaBuilder
        ->addFilter('increment_id', $incrementId, 'eq')->create();
    $orderList = $this->orderRepository->getList($searchCriteria)->getItems();
    $order = $orderList[0];

    ...Do some work on order...
}

It doesn't look like there is an obvious method to reset the searchCriteriaBuilder object on each iteration, so on the second iteration I believe the second filter would get applied as well as the first and no rows would be returned.
Is the way round this to instantiate a new SearchCriteriaBuilder instance using a SearchCriteriaBuilderFactory on each iteration of the loop?
Would I be better just instantiating \Magento\Sales\Model\Order objects  and loading those instead using the built in loadByIncrementId method?
Regards Mark

A: Have you tried the loop? Might work.
Alternative is to rewrite your query so can pass array plus encapsulate in single method to promote reusability.
public function getProducts(array $productIds): array
    {
        $this->searchCriteriaBuilder->addFilter('entity_id', $productIds, 'in');
        $searchCriteria = $this->searchCriteriaBuilder->create();
        $products = $this->productRepository->getList($searchCriteria)->getItems();
        return $products;
    }

Interfaces and repositories should be preferred instead of factory methods simply because although more verbose the code should never change despite framework changes and updates underneath.
That said I learnt from magento 1 so my brain is hard wired to write factory methods.
If you directly instantiate entity models outside of factory pattern stuff will break.


text:
Q: what's the function of tag '#' while using python string format option I am using python string format option, and after reading document, i am still confused by '#' cause i really don't know the meaning of this phrase 'The value conversion will use the "alternate form" (where defined below).'. Great thanks to someone that helps me.
Here is some test:
print '%#sabc' % 'ABC'

'ABCabc'

print '%#fabc' % 1.2

1.200000abc

That will be great if there are some examples of usage of '#' here.

A: As per the notes on that document, an 'alternate form' is defined for some conversion types.
e.g. in your example with %#f

3.The alternate form causes the result to always contain a decimal point, even if no digits follow it.

There is no defined 'Alternate form' for strings so %s and %#s are equivalent

A: The "alternative form" changes the behavior of the selected conversion slightly.
Your Example for floating point representation:

'f': Floating point decimal format.

>>> print("%.0f" % 1)
1

The alternate form causes the result to always contain a decimal point, even if no digits follow it.

>>> print("%#.0f" % 1)
1.

Example for hexadecimal representation:

'x': Signed hexadecimal (lowercase).

>>> print("%x" % -11)
-b

The alternate form causes a leading '0x' [...] to be inserted before the first digit.

>>> print("%#x" % -11)
-0xb


text:
Q: How do I parse this JSON with jQuery? So I had this structure in xml and I was able to parse it successfully. Now what I have done is that I converted this xml into a JSON using www.xmltojson.org but I am not able to parse it . I am setting these files locally on we localhost web server:
<script>
        $(function() {
            $.ajax({
                url:'feed.json',
                dataType:'json',
                type:'GET',
                success:function(json) {
/// what to do here
}.
error: {
 alert("Parse Failed");
}
});
});
</script>

I am trying to learn JSON, so I am little unsure as to where I am doing wrong, or even if that is the correct approah.
Thanks Mikey.

A: There is no need to parse anything because you already specify dataType:'json'; If the url exists and returns a valid json string, jQuery will parse it for you, so the success callback would get an actual object:
$(function() {
    $.ajax({
        url:'feed.json',
        dataType:'json',
        type:'GET',
        success: function(data) {
            console.log(data.propertyone);
            console.log(data.propertytwo);
        },
        error: function() {
            console.log("Parse Failed");
        }
    });
});

(Also you had a couple of syntax errors in your original code, fixed above)

A: Your best bet is jQuery.parseJSON

A: See an example:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
Another example:
$.each(json, function(i,e){
alert(e.data); // data is the key for value
}

A: you dont need 3rd party tools.
jquery can convert it for you automagically by setting dataType:'xml json'

[...] a shorthand string such as "jsonp xml" will first attempt to convert
  from jsonp to xml, and, failing that, convert from jsonp to text, and
  then from text to xml.

documentation: http://api.jquery.com/jQuery.ajax/

A: If you set dataType to json then the json response will be parsed internally by jQuery and the parameter passed to the success function will be the object resulting from the parsed json.


text:
Q: ¿Cómo leer archivo linea por linea en javascript? ¿Hay manera de leer un file en javascript sin el uso de un input file y poderlo leer linea a linea?
La duda surge porque en este caso la ruta del archivo la extraigo de la base datos y quisiera leerlo linea por linea sin el uso de los input file

A: Para leer el archivo sin usar un input file puedes usar una función en jquery  $.get:
$.get( "archivo.txt", function( data ) {
    $( ".result" ).html( data );
});

Para mayor información sobre la función, puedes dar click aquí


text:
Q: Tuning buffer length for reading small data from NetworkStream How to fine tune the bufferSize while reading small data from the TcpClient/NetworkStrem?
If the bufferSize is big like 1024, 4096 the Read/BeginRead blocks.
If I set the bufferSize to 16, 32 it works without blocking.

*

*Does setting the bufferSize to 1 guarantee there won't be any blocks? Will the performance impact be very bad?

*It looks like setting the ReadTimeout to values like 1000, 2000 has
no effect over blocking. Is there any other way to make the blocking
be short? (NoDelay = true doesn't work)
public static IObservable<byte[]> AsyncReadChunk(this Stream stream, int bufferSize)
{
    var buffer = new byte[bufferSize];

    return Observable.FromAsyncPattern<byte[], int, int, int>(stream.BeginRead, stream.EndRead)(buffer, 0, bufferSize)
        .Select(cbRead =>
                    {
                        var dataChunk = new byte[cbRead];

                        Buffer.BlockCopy(buffer, 0, dataChunk, 0, cbRead);

                        return dataChunk;
                    });
}

public static IObservable<byte[]> AsyncRead(this NetworkStream stream, int bufferSize)
{
    return Observable.Defer(() => stream.DataAvailable ? AsyncReadChunk(stream, bufferSize) : Observable.Return(new byte[0]))
        .Repeat()
        .TakeWhile((dataChunk, index) => dataChunk.Length > 0);
}

A:
It looks like setting the
  ReadTimeout to values like 1000, 2000 has no effect over blocking.

Msdn says, that ReadTimeout has no effect when using the async BeginRead method.

Does setting the bufferSize to 1 guarantee there won't be any blocks?

No, of cause not. When not a single byte is sent over the connection, the Read call will block regardless of the buffersize.

Will the performance impact be very bad?

I guess you are talking about the 1 byte buffer here.
It depends on the amount and frequency of data you receive and what code you execute on EndRead. When processing a stream with a high bandwidth, the impact can be big. You have to try and watch your cpu while receiving data.
I'm not really sure what you want to achieve respectively what your concern about blocking is.
When you start a Receive (or Networkstream.Read) with a buffer of say 1024 bytes, and you receive 10 Bytes on the socket, the Read call will return that 10 Bytes after a short delay but will not block until the whole buffer is filled.

Is there any other way to make the blocking be short?

What do you mean with short. As i say, even with a big buffer, the Read won't block endlessly when receiving small amounts of data.

(NoDelay = true doesn't work)

That a completely different story but is might be interesting to set it to true on your senders side (if you are in control of that, too).
When set to false (the default), it will combine small datachunks being sent into bigger ones to reduce the overhead of one tcp packet (40 Bytes header).
EDIT

I mean NetworkStream.BeginRead to return immediately if there is no data.

What about using stream.DataAvailable? It should return false when there is no data.
In addition, when using the async pattern, isn't it expected behaviour that the calls will block until there is something to do? Otherwise you will get active polling in a busy loop.

When the buffer is big it sometimes waits 60 seconds to return (when it is not fully filled or filled to some amount)

Hm, can't believe that. What kind of data are you sending over the channel? 1 byte every minute? 1000 bytes per second?