text:
Q: modularization of code The requirement is to reduce the number of lines of code and deconstruct into smaller supporting methods.Can someone help me out in this regard.This method is basically validating different fields on a form and returning them back to a VF component.

A: I'd probably stick to the many tests in the main method but move any repeated logic into separate methods e.g.:
private Boolean isRequired(String field) {
    return String.IsNotBlank(requiredFields) && requiredFields.containsIgnoreCase(field);
}

I would also get rid of the isValidationErrorExist code that is repeated (and as it includes && false looks wrong anyway) and just assign it at the end if its needed:
isValidationErrorExist = emailError || storeLocationError || ... ;


text:
Q: ssh stuck after showing local version I am trying to ssh to a different system from my Ubuntu, but it got stuck after this log
root@akash:~# ssh -vvv root@192.168.2.219
OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "192.168.2.219" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to 192.168.2.219 [192.168.2.219] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: identity file /root/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2

and after some time I got a connection time out.
I generated the new ssh RSA key via ssh-keygen -t rsa on both the machines then, I copied my public key from id_rsa.pub to the file authorized_keys of the remote machine and vice-a-versa.
Now, one machine can login easily but the other one can't.
Can anyone tell me how to fix this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wix shortcut desktop - is this code for current user or all users I am trying to create a shortcut for all users using Wix 3.6. My InstallScope is perMachine and InstallPriviledges is elevated. I build this code ok. It runs ok. Does this produce a shortcut for all users or just the current user and what do I need to change to make a shortcut for all users?
<DirectoryRef Id="DesktopFolder">
  <Component Id="ApplicationDesktopShortcut" Guid="*">
    <Shortcut Id="MyClient_DesktopShortcut" Name="My Client"
              Description="My Client" Target="[INSTALLFOLDER]MyClient.exe"
              WokingDirectory="INSTALLFOLDER" />
    <RegistryValue Root="HKCU" Key="Software\MyServices\My Client\DesktopShortcut"
                   Name="installed" Type="integer" Value="1" KeyPath="yes" />
  </Component>
</DirectoryRef>

Thanks
Jason


text:
Q: Fetching Text from SQL and display lines How do I display text 'with line' from SQL in PHP? Below is a script similar to what I have.
$information = mysqli_query($connect, "SELECT * FROM information");
    while($new_information = mysqli_fetch_array($information)) {
        echo $new_information['information'];
    }

Whereas the text in 'information' is
'Hello world!
How are you doing?' - Two lines
However it display,
'Hello world! How are you doing?' - One line
How can I make it two lines?
The table and column name is the same; information.

A: you should give your column name or index to it with new line
 like
$information = mysqli_query($connect, "SELECT * FROM information");
    while($new_information = mysqli_fetch_array($information)) {
        echo $information[0]."
"; // as numeric  index
    }

OR
$information = mysqli_query($connect, "SELECT * FROM information");
    while($new_information = mysqli_fetch_array($information)) {
        echo $information['information']."
"; // as column name
    }


text:
Q: Vaadin table keeps showing scrollbars I have a Table component inside some layouts and I don't want it to show any scrollbars.
The table will always show only 25 rows, and the width should always be 720px. However, the table keeps showing both vertical and horizontal scrollbars and I cannot figure out how. The funny thing is(although I am rather crying now), that sometimes the scrollbars disappear. When I keep refreshing the page, sometimes they vanish and everything is ok.
Here are couple infos I have collected after hours of debugging:

*

*Sometimes, the icons/images/etc. aren't loaded and are displayed from cash, sometimes they are. And guess what, this is also switch the scrollbars on and off, although the images are still displayed.

*The width of each column is sometimes couple pixels more - and that's why the horizontal scrollbar shows up and I think that's is also why the vertical scrollbar shows up (because the horizontal takes some pixels from the height of the table)

*I have tried to call requestRepaint after filling the table, even requestRepaintAll on the parent component, and its parent, and its parent, etc...

*I have tried setting the width of each column in percentage.
100000.) I think I have tried all other things between 4 and 100000.

I must be missing something. A lot of people have this problem, and I've found a lot of threads directly on the vaadin page, but there is no THIS-DEFINITELY-WORKS solution.
EDIT CODE:
Table t = new Table();
t.setWidth("720px");
t.setImmediate(true);
t.setSelectable(true);

// Headers
t.addContainerProperty("fullName", String.class,  null, "Meno", null, null);
t.setColumnExpandRatio("fullName", 22);

t.addContainerProperty("dateOfBirth", Date.class,  null, "Narodenie", null, null);
t.setColumnExpandRatio("dateOfBirth", 18);

t.addContainerProperty("lastYearCosts", BigDecimal.class,  null, "Náklady", null, null);
t.setColumnExpandRatio("lastYearCosts", 10);

t.addContainerProperty("lastYearBalance", BigDecimal.class,  null, "Saldo", null, null);
t.setColumnExpandRatio("lastYearBalance", 10);

t.addContainerProperty("activeClient", ComparableBooleanEmbeddedIcon.class,  null, "", new ThemeResource("icons/icon-app-header-medipartner.png"), Table.ALIGN_CENTER);
t.setColumnExpandRatio("lastYearBalance", 8);

t.addContainerProperty("dmsCount", String.class,  null, "", new ThemeResource("icons/icon-app-header-heart.png"), null);
t.setColumnExpandRatio("dmsCount", 8);

t.addContainerProperty("authCount", String.class,  null, "", new ThemeResource("icons/icon-app-header-warnings.png"), null);
t.setColumnExpandRatio("authCount", 8);

t.addContainerProperty("book", CssLayout.class,  null, "Objednať", null, Table.ALIGN_CENTER);
t.setColumnExpandRatio("book", 16);

Then, I am just filling in rows with addItem(Object[] item).

A: I had the same issue - annoying scrollbars. I fixed that using my own theme and overriding css style.
To do so in your implementation of Application you have to to set your theme calling setTheme("mytheme").
Then when you define table you can use your own style (to distinguish that problematic table from others):
Table table = new Table()
table.addStyleName("mystyle")

And then you have to define your own css style in VAADIN/themes/mytheme/styles.css:
@import "../reindeer/styles.css";
.v-table-mymodel .v-scrollable {
    overflow: hidden;
}

A: you should use
table.setPageLength(0);

it's will remove all scroolbar in vaadin table.

A: try
grid.recalculateColumnWidths()


text:
Q: Show and hide Blade table rows with Alpine JS I am using Blade with Laravel 8.x and would like to show or hide table rows using x-show in Alpine JS (v3).

  @foreach($items as $item)

        <button type="button" x-on:click="show = !show">
          Toggle Show
        </button>

      {{ $item->name }}

  @endforeach

When I do this however, I get a ReferenceError: show is not defined error. Is this approach possible without using x-for as I would like to still have access to the Blade variables within the rows.

A: The problem is that you cannot place
 element in a
 element. When browser executes your code, it places the
 outside
 element, so in
 the show is not defined.
You can workaround this by replacing
 tag with
 or making the button and item name in one row as separate  and appending x-data to
.


text:
Q: creating directories from for loop I need to create directories from for loop.  I have a list.
a = [banana 1234, apple 456, orange 789]

And I need to create folders named by the numbers that are ending with numbers in list. for example.
C:\folder\1234; C:\folder\456

and so on.
code is
for length in atrinkta:
folder = re.findall(r'\d{9,}', length)
os.makedirs("D:/python_study/images/skelbimai/" + folder)

but I get an error "TypeError: cannot concatenate 'str' and 'list' objects" don't know what to do. Please someone help.
EDIT
I tried your method 2nd time. After deleting created folder for whatever reason python gives me error
WindowsError: [Error 183] Cannot create a file when that file already exists: 'D:/python_study/images/skelbimai/'

2ndEdit
shaktimaan, now i get other error AttributeError: 'NoneType' object has no attribute 'group'. What does this mean?

A: This is what you are looking for:
>>> import re
>>> pattern = re.compile(r'\d+')
>>> a = ['banana 1234', 'apple 456', 'orange 789']
>>> for item in a:
...     dir_name = 'D:/python_study/images/skelbimai/{}'.format(re.search(pattern, item).group(0))
...     if not os.path.isdir(dir_name):
...         os.mkdir(dir_name)

This is how it works. The regex finds the numbers in each of the elements of the list. You cah check it by doing:
>>> import re
>>> pattern = re.compile(r'\d+')
>>> a = ['banana 1234', 'apple 456', 'orange 789']
>>> for item in a:
...     print re.search(pattern, item).group(0)
...
'1234'
'456'
'789'

You just concatenate your base directory with each of the numbers calculated as above and call os.mkdir on each. Since you are creating directory in the loop, you do not need makedirs

A: Try this
for length in atrinkta:
    folder = re.search(r'(\d+)', length)
    os.makedirs("D:/python_study/images/skelbimai/" + folder.groups()[0])


text:
Q: Concatenating csv files with different, empty and duplicated headers I have in input several csv files, each one with hundreds of columns and thousands of rows, that I need to concatenate.
These files have in common most of the columns headers, but not all, further each file has some columns with no headers at all, and last (but not least!) there can be duplicated headers (obviously not known a priori).
The strategy I thought to use is the following:
1- read initially only the headers of each csv file, and find the common ones
2- concatenate the files by using those common headers
I have accomplished the first point, but I'm stuck in the second.
Let's consider the following data as for csv input files:
csv_1:

csv_2:

csv_3:

Here I just report the list of headers for each file:
['A', 'B', '70', 'C', '690', '', '', '0', '1', '3', '5', 'D']
['A', 'B', '5', 'C', '690', '', '', '0', '1', '3', '5', 'D']
['A', 'B', '3', 'C', '690', '', '', '0', '1', '3', '5', 'D']

So, you can see that in each csv files there are two columns (the sixth and the seventh) with no headers. The second file has the header '5' duplicated, while in the third file the duplicated header is '3'.
What I need to exactly have is the following dataframe structure:

Here there are no duplicated columns and the not-common columns are not present anymore. Additionally, there are other two columns: 'file' reporting to which file that row belongs to (i.e. one=csv_1, two=csv_2, three=csv_3, where 'one', 'two' and 'three' are nicknames I define initially and that are available in a list called file_nickname), and 'count' reporting the corresponding number of row for each file
Said this, I have started with a list called 'filenames' containing the files. To get the headers for each file I have used the following:
import csv

headers_list = []
for file in filenames:
    with open(file, 'r') as f:
        d_reader = csv.DictReader(f)
        headers_list.append(d_reader.fieldnames)

Please, note that I cannot use Pandas read_csv (headers_list = [pd.read_csv(file, engine="python", index_col=0, nrows=0).columns.tolist() for file in filenames]) because when reading in this way I would get duplicated columns specified as 'x.1', and the option mangle_dupe_cols has never been implemented and deprecated since version 1.5.0.
Given the headers_list, the list of common headers can be obtained by using the following:
headers_common = list(set(headers_list[0]).intersection(*headers_list[1:]))

I can even get the list of not common header (may be useful) with the following two lines:
headers_list_joined = list(set([item for l in headers_list for item in l]))
headers_not_in_common = [i for i in headers_list_joined if i not in headers_common]

To concatenate the files, if there were no duplicated columns I could use the following one-line:
result = pd.concat(
    [pd.read_csv(file, engine="python", skiprows= 0, usecols=lambda x: x not in headers_not_in_common)
     for file in filenames], keys=file_nickname, names=['file', 'count'])

but, for the same reason as before, Pandas cannot be used.
Thus I have used the following lines:
with open('result.csv', 'w', newline='') as output:
        csv_write_file = csv.writer(output)
        for file in filenames:
            with open(file, newline='') as f:
                for row in csv.reader(f):
                    #row.append(file)
                    csv_write_file.writerow(row)

In this way I get the three files concatenated without duplicated columns, but:
1- there are the not common columns
2- the header is repeated each time
3- I don't know how to obtain the columns 'file' and 'count' (well, by using the line row.append(file) I can get the name of the csv file, but instead I need the nickname).
I hope that my question is quite clear, thanks for any suggestion.
EDIT: I have tried to explain better where I'm stuck (points 1 to 3)


text:
Q: nginx - php connect() unix socket failing I am running alpine 3.12 container with a few custom configuration like so:
FROM alpine:3.12

[some irrelevant stuff]

# Switch to use a non-root user from here on
USER nobody

# Expose the port nginx is reachable on
EXPOSE 8080

# Let supervisord start nginx & php-fpm
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

# Make sure files/folders needed by the processes are accessable when they run under the nobody user
RUN chown -R nobody.nobody /var/www/html && \
  chown -R nobody.nobody /run && \
  chown -R nobody.nobody /var/lib/nginx && \
  chown -R nobody.nobody /var/log/nginx

# Configure a healthcheck to validate that everything is up&running
HEALTHCHECK --timeout=10s CMD curl --fail http://127.0.0.1:8080/fpm-ping

I have my nginx.conf with the following data:
worker_processes 1;
error_log stderr warn;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include mime.types;
    default_type application/octet-stream;

    # Define custom log format to include reponse times
    log_format main_timed '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for" '
                          '$request_time $upstream_response_time $pipe $upstream_cache_status';

    access_log /dev/stdout main_timed;
    error_log /dev/stderr notice;

    keepalive_timeout 65;

    # Write temporary files to /tmp so they can be created as a non-privileged user
    client_body_temp_path /tmp/client_temp;
    proxy_temp_path /tmp/proxy_temp_path;
    fastcgi_temp_path /tmp/fastcgi_temp;
    uwsgi_temp_path /tmp/uwsgi_temp;
    scgi_temp_path /tmp/scgi_temp;

    # Default server definition
    server {
        listen [::]:8080 default_server;
        listen 8080 default_server;
        server_name _;

        sendfile off;

        root /var/www/html/public;
        index index.php index.html;

        location / {
            # try_files $uri $uri/ /index.php?q=$uri&$args;
            try_files $uri $uri/ /index.php$is_args$args;
        }

        # Redirect server error pages to the static page /50x.html
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /var/lib/nginx/html/public;
        }

        # Pass the PHP scripts to PHP-FPM listening on 127.0.0.1:9000
        location ~ \.php$ {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param SCRIPT_NAME $fastcgi_script_name;
            fastcgi_index index.php;
            include fastcgi_params;
        }

        location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
            expires 5d;
        }

        # Deny access to . files, for security
        location ~ /\. {
            log_not_found off;
            deny all;
        }

        # Allow fpm ping and status from localhost
        location ~ ^/(fpm-status|fpm-ping)$ {
            access_log off;
            allow 127.0.0.1;
            deny all;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
        }
    }

    gzip on;
    gzip_proxied any;
    gzip_types text/plain application/xml text/css text/js text/xml application/x-javascript text/javascript application/json application/xml+rss;
    gzip_vary on;
    gzip_disable "msie6";

    # Include other server configs
    include /etc/nginx/conf.d/*.conf;
}

and my supervisord config such as:
[supervisord]
nodaemon=true
logfile=/dev/null
logfile_maxbytes=0
pidfile=/run/supervisord.pid

[program:php-fpm]
command=php-fpm7 -F
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=false
startretries=0

[program:nginx]
command=nginx -g 'daemon off;'
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=false
startretries=0

and in my php-fpm/www.conf:
[global]
; Log to stderr
error_log = /dev/stderr

[www]
; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

; Enable status page
pm.status_path = /fpm-status

; Ondemand process manager
pm = ondemand

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI. The below defaults are based on a server without much resources. Don't
; forget to tweak pm.* to fit your needs.
; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
; Note: This value is mandatory.
pm.max_children = 100

; The number of seconds after which an idle process will be killed.
; Note: Used only when pm is set to 'ondemand'
; Default Value: 10s
pm.process_idle_timeout = 10s;

; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
pm.max_requests = 1000

; Make sure the FPM workers can reach the environment variables for configuration
clear_env = no

; Catch output from PHP
catch_workers_output = yes

; Remove the 'child 10 said into stderr' prefix in the log and only show the actual message
decorate_workers_output = no

; Enable ping page to use in healthcheck
ping.path = /fpm-ping

So my question: Where is this error log coming from???
[crit] 9#9: *2 connect() to unix:/var/run/php7.3-fpm.sock failed (2: No such file or directory) while connecting to upstream, client: 172.17.0.1, server: , request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php7.3-fpm.sock:", host: "127.0.0.1:8080"

It should really not be triggered, since I never specify php-fpm to listen to this socket. Where does it come from???


text:
Q: error 40: the type integer is not qualified with a namespace or alias Okay, this both a question and a solution.  I was having a problem deploying a solution which very simply used linq and EF to query a couple DB2 tables and display the results to a datagridview.  It worked fine on the development machine, but on the two other machines I tried, I would get "error 40: the type integer is not qualified with a namespace or alias."
After two days of trying various solutions, I decided to try debugging on one of the other machines.
Development machine is Windows XP with Visual Studio 2010.
Deployment machines both Windows 7 with VS 2010.
Well, I immediately noticed that on the deployment machine, VS would give me a list of errors (integer not qualified etc.) which weren't showing on my development machine.  The next thing I noticed was that when I double-clicked the .edmx file in the solution, it opened in xml instead of the visual display of the tables which I was using.
In this xml, every property/table column with a type of "integer" was underlined.  Well, that doesn't make sense.  Could this VS2010 not recognize the data type which was automatically generated by the other VS2010? Just out of desperation, I changed every instance of "Type='integer'" to "Type='int'"  It debugged and ran on all 3 machines like a charm.
So, my questions are:
1) Is this a bug that exists between the two development environments (XP vs. W7) or do I have my development environment set up incorrectly?
2) On my XP machine, how can I edit my .edmx file in the xml view?  Is it possible from within VS, or must I use a text editor?

A: Is there an include file for your edmx which defines the "integer" type on your development machine (or a difference in framework version)? It works when you switch to int as it is a primitive type and does not need to be defined. I've only done code first so this is not a strength for me, but I think your error message is giving you a good hint. There is no definition of the object integer in the edmx (or include files) on the other two environments. On your dev machine I think this must either exist as:

*

*A definition of an integer object somewhere in the edmx/include files

*An alias of integer to int somewhere in these same files

*A different version of .NET of EF which recognizes integer out of the box?


text:
Q: Loading and position image, when the another images are loaded I have a small problem with loading and position one of my images. The smallest one. I'm using spacegallery script (http://www.eyecon.ro/spacegallery/).
It's loading good, but i want it to position it in the corner of bigger image, and when i load my page for the first time, it's not positioned, when i reload it - it's all fine, but the first loading is wrong.
Here are the screens:
It's the first load without refreshing the site:
first load http://derivativeofln.com/withoutload.png
Second and next loads:
second load http://derivativeofln.com/withload.png
My HTML:

MY CSS:
#myGallery0 {
width: 100%;
height: 300px;
 }

#myGallery0 img {
border: 2px solid #52697E;
 }

a.loading {
background: #fff url(../images/ajax_small.gif) no-repeat center;
}

.imaz {
 z-index: 10000;
}

.imaz img{
position: absolute;
left:10px;
top:10px;
z-index: 10000;
width: 35px;
height: 35px;
}

My Jquery main script file: (the first positioning instructions are on the bottom, so feel free to scroll down : ))
(function($){
   EYE.extend({

    spacegallery: {

        animated: false,

        //position images
        positionImages: function(el) {

            var top = 0;

            EYE.spacegallery.animated = false;
            $(el)
                .find('a')
                    .removeClass(el.spacegalleryCfg.loadingClass)
                    .end()
                    .find('img.aaa')
                    .removeAttr('height')
                    .each(function(nr){
                        var newWidth = this.spacegallery.origWidth - (this.spacegallery.origWidth - this.spacegallery.origWidth * el.spacegalleryCfg.minScale) * el.spacegalleryCfg.asins[nr];

                        $(this)
                            .css({
                                top: el.spacegalleryCfg.tops[nr] + 'px',
                                marginLeft: - parseInt((newWidth + el.spacegalleryCfg.border)/2, 10) + 'px',
                                opacity: 1 - el.spacegalleryCfg.asins[nr]
                            })
                            .attr('width', parseInt(newWidth));
                        this.spacegallery.next = el.spacegalleryCfg.asins[nr+1];
                        this.spacegallery.nextTop = el.spacegalleryCfg.tops[nr+1] - el.spacegalleryCfg.tops[nr];
                        this.spacegallery.origTop = el.spacegalleryCfg.tops[nr];
                        this.spacegallery.opacity = 1 - el.spacegalleryCfg.asins[nr];
                        this.spacegallery.increment = el.spacegalleryCfg.asins[nr] - this.spacegallery.next;
                        this.spacegallery.current = el.spacegalleryCfg.asins[nr];
                        this.spacegallery.width = newWidth;
                    })

        },

        //constructor
        init: function(opt) {
            opt = $.extend({}, EYE.spacegallery.defaults, opt||{});
            return this.each(function(){
                var el = this;
                if ($(el).is('.spacegallery')) {
                    $('')
                        .appendTo(this)
                        .addClass(opt.loadingClass)
                        .bind('click', EYE.spacegallery.next);

                    el.spacegalleryCfg = opt;
                    var listunia, images2 = [], index;
                    listunia = el.getElementsByTagName("img");

                    for (index = 1; index < listunia.length; ++index) {
                        images2.push(listunia[index]);
                    }

                    el.spacegalleryCfg.images = images2.length;
                    el.spacegalleryCfg.loaded = 0;
                    el.spacegalleryCfg.asin = Math.asin(1);
                    el.spacegalleryCfg.asins = {};
                    el.spacegalleryCfg.tops = {};
                    el.spacegalleryCfg.increment = parseInt(el.spacegalleryCfg.perspective/el.spacegalleryCfg.images, 10);
                    var top = 0;

                    $('img.aaa', el)
                        .each(function(nr){
                            var imgEl = new Image();
                            var elImg = this;

                            el.spacegalleryCfg.asins[nr] = 1 - Math.asin((nr+1)/el.spacegalleryCfg.images)/el.spacegalleryCfg.asin;
                            top += el.spacegalleryCfg.increment - el.spacegalleryCfg.increment * el.spacegalleryCfg.asins[nr];
                            el.spacegalleryCfg.tops[nr] = top;
                            elImg.spacegallery = {};
                            imgEl.src = this.src;
                            if (imgEl.complete) {

                                el.spacegalleryCfg.loaded ++;
                                elImg.spacegallery.origWidth = imgEl.width;
                                elImg.spacegallery.origHeight = imgEl.height
                            } else {
                                imgEl.onload = function() {
                                    el.spacegalleryCfg.loaded ++;
                                    elImg.spacegallery.origWidth = imgEl.width;
                                    elImg.spacegallery.origHeight = imgEl.height
                                    if (el.spacegalleryCfg.loaded == el.spacegalleryCfg.images) {

                                        EYE.spacegallery.positionImages(el);

                                    }
                                };
                            }
                        });

                    el.spacegalleryCfg.asins[el.spacegalleryCfg.images] = el.spacegalleryCfg.asins[el.spacegalleryCfg.images - 1] * 1.3;
                    el.spacegalleryCfg.tops[el.spacegalleryCfg.images] = el.spacegalleryCfg.tops[el.spacegalleryCfg.images - 1] * 1.3;
                    if (el.spacegalleryCfg.loaded == el.spacegalleryCfg.images) {

                            if(el.spacegalleryCfg.images == 3){
                            $('img.imaz', this).css('top', '27px'); // HERE IS POSITIONING OF MY IMAGES, WHEN SCRIPT LOADS FOR THE FIRST TIME!
                            $('img.imaz', this).css('left', (($(el).find('img.aaa:last').width())/2 + 77) + 'px' );
                            }
                            else if(el.spacegalleryCfg.images==2){
                                $('img.imaz', this).css('top', '33px');
                                $('img.imaz', this).css('left', (($(el).find('img.aaa:last').width())/2 + 77) + 'px' ); // HERE IT ENDS:)
                            }

                        EYE.spacegallery.positionImages(el);
                    }
                }
            });
        }
    }
});
})(jQuery);

A: this seems to be a cache thing
try to specify image dimensions (width and height) on your html, because on first load (images not in cache) the browser only knows dimensions after the load and the positioning might not be correct.
in alternative you can run your positioning code when the document is loaded
$(document).ready(«your poisitioning function here»)

see http://api.jquery.com/ready/ for that jquery ready function


text:
Q: How to bring up an interface using Ansible 'nmcli' module? I can create an interface with something like:
- name: create dummy interface
  community.general.nmcli:
    type: dummy
    conn_name: '{{ item.conn_name }}'
    ifname: '{{ item.ifname }}'
    ip6: '{{ item.ip6 }}'
    state: present
  with_items:
    - '{{ nmcli_dummy }}'

But if in the server I put the interface down: ifconfig dummy0 down, what parameter or options could be used to manage the interface state, for example up or down?

A: For a connection in example named eth1 the equivalents for show, up and down are
nmcli con show eth1
nmcli con up eth1
nmcli con down eth1

Whereby in nmcli module are certain Parameters for

Manage the network devices. Create, modify and manage various connection and device type e.g., ethernet, teams, bonds, vlans etc.

a parameter for bringing a network interface up or down is not explicit named.
This might leave one to think to workaround it with
- name: Brings the interface up or down
  command:
    cmd: "nmcli con {{ CMD }} eth1"
  register: nmcli_con_cmd_result

as this is almost what the module code is doing under the hood.
However, according the NetworkManager / ansible-network-role it seems that the paramter state can have more values. In your case you could first check how it is implemented there in the project role and test after with state: up and state: down accordingly.
Regarding

I can create an interface with ...

it seems that if connection becomes created it is brought up, as well if connection becomes removed, it is brought down before.
Further Documentation

*

*Configuring IP Networking with nmcli

*NetworkManager Project - Ansible Network Role

*community.general/plugins/modules/nmcli.py


text:
Q: Problem with embeded document query, when building query dynamically I'm trying to dynamically build a query where one can query an embedded document but it fails.
If I, however, copy the content of the query and try it works.
0> query
=> {:"properties.account_id"=>"5bd046d21d41c82e7c000004"}

0> Collection.where(query).to_a
=> []

0> Collection.where({:"properties.account_id"=>"5bd046d21d41c82e7c000004"}).to_a
=> [#<Collection _id: 5bd046d21d41c82e7c000006, created_at: 2018-10-24 10:17:54 UTC, updated_at: 2018-10-24 10:17:54 UTC, properties: {"account_id"=>"5bd046d21d41c82e7c000004"}>]

0> Collection.where(:"properties.account_id"=>"5bd046d21d41c82e7c000004").to_a
=> [#<Collection _id: 5bd046d21d41c82e7c000006, created_at: 2018-10-24 10:17:54 UTC, updated_at: 2018-10-24 10:17:54 UTC, properties: {"account_id"=>"5bd046d21d41c82e7c000004"}>]

And I have tried without colon
0> query
=> {"properties.account_id"=>"5bd049651d41c872d2000004"}

0> Collection.where(query).to_a
=> []

0> Collection.where({"properties.account_id"=>"5bd049651d41c872d2000004"}).to_a
=> [#<Collection _id: 5bd049651d41c872d2000006, created_at: 2018-10-24 10:28:53 UTC, updated_at: 2018-10-24 10:28:53 UTC, properties: {"account_id"=>"5bd049651d41c872d2000004"}>]

The explain data seems fine as well
{
  "queryPlanner" => {
    "plannerVersion" => 1, "namespace" => "db_testing.coll_test", "indexFilterSet" => false, "parsedQuery" => {
      "properties.account_id" => {
        "$eq" => "5bd04bf91d41c8d153000004"
      }
    }, "winningPlan" => {
      "stage" => "COLLSCAN", "filter" => {
        "properties.account_id" => {
          "$eq" => "5bd04bf91d41c8d153000004"
        }
      }, "direction" => "forward"
    }, "rejectedPlans" => []
  }, "executionStats" => {
    "executionSuccess" => true, "nReturned" => 0, "executionTimeMillis" => 1, "totalKeysExamined" => 0, "totalDocsExamined" => 2, "executionStages" => {
      "stage" => "COLLSCAN", "filter" => {
        "properties.account_id" => {
          "$eq" => "5bd04bf91d41c8d153000004"
        }
      }, "nReturned" => 0, "executionTimeMillisEstimate" => 0, "works" => 4, "advanced" => 0, "needTime" => 3, "needFetch" => 0, "saveState" => 0, "restoreState" => 0, "isEOF" => 1, "invalidates" => 0, "direction" => "forward", "docsExamined" => 2
    }, "allPlansExecution" => []
  }, "serverInfo" => {
    "host" => "ubuntu", "port" => 27017, "version" => "3.0.15", "gitVersion" => "b8ff507269c382bc100fc52f75f48d54cd42ec3b"
  }
}

Any ideas?


text:
Q: Windows 8 located all drives and run command on each This is what I have so far
@echo off
for /f "tokens=2 delims==" %%d in ('wmic logicaldisk where "drivetype=3" get name format:value') do echo %%d

output is correct
@echo off
FORFILES /P C:\ /S /M *.* /C "cmd /c echo @path"

output is correct
@echo off
for /f "tokens=2 delims==" %%d in ('wmic logicaldisk where "drivetype=3" get name format:value') do FORFILES /P %%d\ /S /M *.* /C "cmd /c echo @path"

output seems to report an invalid drive for each drive on the system but I can not get it to
process the %%d as C:\ D:\ etc,
any suggestions

A: WMIC produces unicode output, and FOR /F converts the output to ANSI improperly such that there is an extra carriage return (<CR>) at the end of each line of output.
So your drive becomes C:<CR>\ - the carriage return is messing up the command.
One way to eliminate the unwanted character is to add an extra FOR loop, which trims exactly one trailing <CR> from the end of a line, if it exists.
Also, unless Windows 8 is different than all earlier versions, WMIC requires a slash before the FORMAT option, as in /format:value
@echo off
for /f "tokens=2 delims==" %%A in (
  'wmic logicaldisk where "drivetype=3" get name /format:value'
) do for %%B in (%%A) do forfiles /p %%B\ /s /m *.* /c "cmd /c echo @path"


text:
Q: UISlider layout ignoring width I need to add a pop up view with a UILabel and a UISlider, but I am having trouble setting the width of the UISlider.
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        frontPanel = UIView()
        frontPanel!.backgroundColor = UIColor.whiteColor()
        frontPanel!.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(frontPanel!)

        valueSlider = UISlider()
        valueSlider!.translatesAutoresizingMaskIntoConstraints = false
        valueSlider!.frame = CGRect(x: 0,
                                    y: 0,
                                    width: frontPanel!.frame.width - 16,
                                    height: 35)

        sliderLabel = UILabel()
        sliderLabel!.translatesAutoresizingMaskIntoConstraints = false

        sliderLabel!.text = "Adjust value"

        let frontPanelSubviews: [String : AnyObject] = [
            "label" : sliderLabel!,
            "slider" : valueSlider!
        ]

        frontPanel!.addSubview(sliderLabel!)
        frontPanel!.addSubview(valueSlider!)

        frontPanel?.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]-[slider]-|",
            options: [],
            metrics: nil,
            views: frontPanelSubviews)
        )
        frontPanel?.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|",
            options: [],
            metrics: nil,
            views: frontPanelSubviews)
        )
        frontPanel?.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat("H:|-[slider]-|",
            options: [],
            metrics: nil,
            views: frontPanelSubviews)
        )

    }

    override func viewDidLayoutSubviews() {
        frontPanel?.frame = CGRect(x: 0,
                                   y: view.frame.height - 75,
                                   width: view.frame.width,
                                   height: 75)
    }

    @IBOutlet weak var backPanel: UIView!
    @IBOutlet weak var valueLabel: UILabel!

    var frontPanel: UIView?
    var valueSlider: UISlider?
    var sliderLabel: UILabel?
}

In this example, the UISlider will always get the same width as the UILabel.
If I only use a horizontal layout contraint like H:|-[label]-[slider]-| the UISlider gets width == 0.
How can I make the UISlider use the full width of the parent view (minus the 8 points space on each side)?

A: frontPanel!.translatesAutoresizingMaskIntoConstraints = true

frontPanel is a subview of ViewController.view and you set exact frame. In my understanding is as follows.


text:
Q: How to rotate two objects thus they would point to each other in the 2D plane?
On the initial image, you can see two triangles pointing upwards. By how much in degrees I have to rotate them thus they would point to each other? How can I calculate angles?
Calculating dot product gives only the angle difference between the triangles, but it is not the right value to rotate.

A: You are taking the dot products of the wrong vectors. You should dot the direction of each object with the displacement vector to the other object. This will give the required angle to rotate through.

But this alone is not enough - how would you know which direction to rotate in, clockwise or anti-clockwise? You can obtain this using the cross-product:
A x B = A.x * B.y - B.x * A.y
If this quantity is negative, then A is anti-clockwise relative to B, and vice versa. Therefore if cross(direction, displacement) is negative, then rotate clockwise by the calculated angle θ, and vice versa.


text:
Q: Tool to synchronize extents of all running ArcGIS Instances I am working in 3 ArcGIS 10.0 mxd projects at the same time and am finding it laborious to always have to zoom to the same area in all 3 projects. Does anyone know of a tool or way that I can synchronize all open instances with a single click?

A: You could write a Python AddIn for ArcMap that has two buttons:

*

*write current extent to ASCII file

*read extent from ASCII and set data frame to it

However, this would require just more than one click.
On the other hand, ArcGIS Pro supports multiple maps/scenes in a project and allows you to Link Views so that is likely to be the ArcGIS for Desktop application that most easily meets this requirement.


text:
Q: How to know event added successfully in android calendar how can I know event added successfully in an android calendar,
I want to change my button which calls an edit intent to the calendar.
I am able to add the event but how can I check that user added the event or cancel that calendar event prompt.
kindly give help.
Intent intent = new Intent(Intent.ACTION_EDIT);
                    intent.setType("vnd.android.cursor.item/event");
                    intent.putExtra("title","Fajr Prayer");
                    intent.putExtra(Events.EVENT_LOCATION,parser.city+" , "+parser.country);
                    Calendar startTime = Calendar.getInstance();
                    startTime.set(Calendar.HOUR,hour);
                    startTime.set(Calendar.MINUTE,minute);
                    Calendar endTime = Calendar.getInstance();
                    endTime.set(Calendar.HOUR,hour);
                    endTime.set(Calendar.MINUTE,minute+30);
                    intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,
                    startTime.getTimeInMillis());
                    intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,
                    endTime.getTimeInMillis());
                    startActivity(intent);

I tried this code to add the event but know i am unable to find out how to get indication of successful calendar event addition.


text:
Q: woocommerce_form_field не передает в $_POST данные? Пытаюсь передать из карточки товара мета данные в корзину которые пользователь выбрал
в селекте но в масив $_POST ничего не передается в чем может быть проблема?
`$options  = array( '' => __("Выбрать опцию") );
    foreach ( (array) explode( ',',$textarea_field ) as $model ) {
        $options[$model] = $model;
    }
    woocommerce_form_field( 'model', array(
        'type'     => 'select',
        'class'    => array('form-row-wide product-color'),
        'label'    => __('Модель'),
        'options'  => $options,
        'required' => true,
    ));

    echo '<br>';

});
var_dump(esc_attr($_POST["model"]));
add_action('woocommerce_add_cart_item_data', function ( $cart_item_data, $product_id){
    $cart_item_data['attribute_model'] = esc_attr($_POST["model"]);
    return $cart_item_data;
},10 ,2 );`

A: Оказалось, что использовал не тот хук для вывода поля.
Нужно было:
woocommerce_before_add_to_cart_button

, а я использовал:
 woocommerce_before_add_to_cart_form


text:
Q: How does htaccess work when using cPanel and addon domains When you have cPanel hosting and you use addon domains, the domains are "housed" in a folder within the public_html folder (by default), for example:
A) public_html/.htaccess
B) public_html/addondomain_1/.htaccess
C) public_html/addondomain_2/.htaccess

It's my understanding that anything I put in the htaccess file A) applies to everything within it, which should include B) and C).
So, as an example, adding a blocked IP address to A) would also be blocked on B) and C).
But I query this purely because B) and C) are different domains when viewed in the browser. I've tried testing it but without much luck and going through pages of documentation hasn't helped me come to a conclusion.
If I block someones IP in A) will it block them from websites B) and C)?

A: Apache docs are pretty clear:

The configuration directives found in a .htaccess file are applied to the directory in which the .htaccess file is found, and to all subdirectories thereof. However, it is important to also remember that there may have been .htaccess files in directories higher up. Directives are applied in the order that they are found. Therefore, a .htaccess file in a particular directory may override directives found in .htaccess files found higher up in the directory tree. And those, in turn, may have overridden directives found yet higher up, or in the main server configuration file itself.

This is a feature of Apache, not of cPanel. It does not matter if you're running with cPanel or not — Apache is still going to traverse parent directories and apply their .htaccess directives.


text:
Q: How to add a string before count and create list using ansible? I need to create 10 users and each user is having 5 folder for it.
First i tried to create user like below
    - set_fact:
        user_lists: []
    - name: creating list of users
      set_fact:
        user_lists: "user-{{ user_lists + [ item] }}"
      with_sequence: count=10

I am expecting it to users to create like user-1 ,user-2 ..user-10.
but it throws error like below

fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type
error occurred on (user-{{ user_lists + [item] }}): coercing to
Unicode: need string or buffer, list found"}

How to resolve this?

A: See with_sequience. For example, the playbook below
  hosts: localhost
  tasks:
    - set_fact:
        user_lists: []
    - name: creating list of users
      set_fact:
        user_lists: "{{ user_lists + [ 'user-' ~ item ] }}"
      with_sequence: start=1 end=10
    - debug:
        var: user_lists

gives (abridged)
    "user_lists": [
        "user-1",
        "user-2",
        "user-3",
        "user-4",
        "user-5",
        "user-6",
        "user-7",
        "user-8",
        "user-9",
        "user-10"
    ]


text:
Q: f1-micro shuts down instance with high CPU usage I use f1-micro mainly for main dev environment, I connect to the instance using vscode ssh extension. But whenever I try to open a medium sized javascript file, or an extension loading up in the background, the ssh connection always timed out.
I've tried replacing the instance, but no luck, the ssh connection always reset.


text:
Q: Yii2 - unique email with custom function Inside rules method I have this rules for email:
['email', 'uniqueEmail'],
['email', 'email'],

and uniqueEmail method:
public function uniqueEmail($attribute, $email)
    {
        $user = static::findOne(['email' => Yii::$app->encrypter->encrypt($email)]);
        if (count($user) > 0)
            $this->addError($attribute, 'This email is already in use".');
    }

Email validation is working, but uniqueEmail is not working. How can I make this happen?

A: Why do you think that $email with be populated with that value? As stated by the docs, the second function param is actually parameters array, supplied at the end of the validator declaration (['email', 'uninqueEmail', 'param1' => 'value1', 'param2', 'value2'])
Try this:
public function uniqueEmail($attribute) {
    $user = static::findOne(['email' => Yii::$app->encrypter->encrypt($this->{$attribute})]);
    if ($user) { // dont use count($user) - if it's there, it's a single object, you want to check if it's not null!
        $this->addError($attribute, 'This email is already in use".');
    }
}

In Yii2 it's accepted to declare ad-hoc validation as anonymous functions:
['email', function($attribute) {
    $user = static::findOne(['email' => Yii::$app->encrypter->encrypt($this->{$attribute})]);
    if ($user) {
        $this->addError($attribute, 'This email is already in use".');
    }
}],
['email', 'email'],


text:
Q: Box Cox Transforms for regression I'm trying to fit a linear model on some data with just one predictor (say (x,y)). The data is such that for small values of x, the y values give a tight fit to a straight line, however as x values increase, the y values become more volatile. Here is an example of such data (R code)
    y = c(3.2, 3.4, 3.5, 3.8, 4.2, 5.5, 4.5, 6.8, 7.4, 5.9)
    x = seq(1,10,1)

I'm curious to know if there exists any power transform (Box cox perhaps?) that lets me get a better fit for the data than simply doing a linear fit as shown below.
    fit = lm(y ~ x)

A: The MASS package that comes with your R installed already, has the boxcox() function that you can use:  After reading in the data, do:
    library(MASS)
    boxcox(y ~ x)

Then look at the graph this produces, which shows graphically a 95% confidence interval for the boxcox transformation parameter.  But you do not really have enough data (n=10) to do this, the resulting confidence interval goes almost from -2 to 2!, with a maximum likelihood estimate of approximately 0 (a log-transform, as said before).  If your real data have more observations, you should try this.
As others have said, this transformation is really trying to stabilize variances. This is not really obvious from theory, what it does, is to try to maximize a normal-distribution based likelihood function, which assumes constant variance. One could think that maximizing a normal-based likelihood would try to normalize the distribution of the residuals, but in practice the main contribution to maximizing the likelihood comes from stabilizing the variances.  This is maybe not so surprising, given that the likelihood we maximizes is based on a constant variance normal distribution family!
I once wrote a slider-based demo in XLispStat, which demonstrated this clearly!

A: When you have a linear relationship, but unequal variances then you generally need to transform both x and y to get a linear relationship with equal variances (or just use weighted least squares regression on the untransformed variables).
The AVAS procedure can be used to suggest possible transformations.

A: Well, in R you could try this:
library(MASS)
boxcox(y~x)
plot(1/y^2~x) # since the profile likelihood has a maximum near 2

But it really depends on what you mean by 'better fit to the data'


text:
Q: Save a UIImage on Core Data How do I save a photo picked by a UIImagePickerController in core data. In my data model I have it set up as Type Binary Data and allows it to store Externally.
Here is my code so far.
- (IBAction)addPhoto:(id)sender {
_picker = [[UIImagePickerController alloc]init];
_picker.delegate = self;
_picker.allowsEditing = NO;
_picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:_picker animated:YES completion:nil];

}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];

[self dismissViewControllerAnimated:YES completion:nil];
[self.imageView reloadInputViews];

}

A: Using your code:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];

    // One option:
    NSData *imageData =  UIImageJPEGRepresentation(image, 0.7);
    // Second option.
   // NSData *imagenData2 = UIImagePNGRepresentation(image);

object.theNameOfYourBinaryDataAttribute = imageData;

[context save:nil]; // Or handling error.

[self dismissViewControllerAnimated:YES completion:nil];
[self.imageView reloadInputViews];

}

A: Since UIImage conforms to NSCoding, all you need to do is change the attribute type from "binary" to "transformable". Then you can assign a UIImage to the attribute directly, and Core Data will automatically invoke NSCoding methods on it to convert to and from binary data.
In your code, you would just add this:
[object setValue:image forKey:@"name of your image attribute here"];


text:
Q: Continuity of implicitly defined function Consider a function $g(x)$ defined implicitly via
$\int_{x}^{x + g(x)} f(\xi) d \xi - u(x) = 0$.
I know that for every $x$ a unique g(x) exists.
Furthermore $f$ is locally integrable and $u$ is some continuous function.
Will $g$ be continuous and how could I prove this?

A: Yes, $g$ will be continuous.
Defining $G(x)=x+g(x)$ and $F(x)=\int_0^x f(\xi)d\xi$ and $U(x)=F(x)+u(x)$, your equation becomes
$$F(G(x))=U(x),$$
with $F$ and $U$ continuous. The hypothesis is that there is a unique $G$ satisfying this equation, and the question is whether $G$ must be continuous.
Consider the restriction $\hat F:G(\mathbb R)\to U(\mathbb R)$. This is either strictly increasing or strictly decreasing, and $G(\mathbb R)$ is connected. To see this, consider $y_1<y_2<y_3$ with $F(y_1)<F(y_3)$ and $y_1,y_3\in G(\mathbb R)$. If $F(y_2)<F(y_1)$ then by the intermediate value theorem $F(y_1)\in F([y_2,y_3])$, contradicting the uniqueness of $G$. Similarly $F(y_2)>F(y_3)$ is impossible, so $F(y_1)<F(y_2)<F(y_3)$. This applies to all $y_2\in [y_1,y_3]$, so $F(y_2)\in [F(y_1),F(y_3)]\subseteq U(\mathbb R)$, so $y_2\in G(\mathbb R)$ by uniqueness of $G$. A similar argument applies when $F(y_1)>F(y_3)$.
It follows that $\hat F$ is an open map: the image of a relatively open interval in $G(\mathbb R)$ is relatively open in $U(\mathbb R)$. So $G=\hat F^{-1}\circ U$ is continuous.


text:
Q: C++ MSVS, what file "cleanup" should I be doing? (cl error: D8037) Working in C++ MSVS2008, I've been having increasingly irritating problems: Breakpoints executing on the wrong line, not catching, etc.  It's a really large workspace with thousands of files, so I "put up with it".
I went through the "standard" stuff (clean, "deep" clean, manually delete *.idb, *.pdb, *il*, etc.)  It didn't fix the "breakpoint-on-wrong-line" problem, but things at least compiled and I could run/debug.
THEN, (for unrelated reasons), I created a command-line program that issued a compile-one-CPP-to-OBJ command, and got a strange error:
cl : Command line error D8037 : cannot create temporary il file; clean temp directory of old il files

I never heard of that before, so a web search got me to the Microsoft site that details the error:
http://msdn.microsoft.com/en-us/library/bb385201(v=VS.90).aspx
Um, Huh?  In my system TMP dir, there were apparently too many _CL_hhhhhhhh.ss files.  Searching, yes, I had exactly 6,063 of these files in that directory, going back about one year.
I've never heard of these files before ("temporary compiler files").  Searching the Microsoft site shows that this error is possible in at least MSVS 2005, 2008, 2010.  Being "temp" files, I assume there is some kind of "cleanup" or "recycle" algorithm?

*

*How many _CL_hhhhhhhh.ss files is the limit?  (I had this error under one condition at 6,063.)

*Why do I see this error when I execute a "compile" from within an EXE, and not from within the MSVS IDE?  (I don't see this error when I execute the "compile" directly from the command line either.)

*Should I be doing "maintenance" on my development machine by cleaning up files like these periodically?

*What other "cruft" files do I need to think about finding-and-removing?
As an aside, I'm aware that the MSVS project GUIDs are cached in the registry so that the IDE can "find" project files that are manually moved around to "repair" links/dependencies with other project files.  I'd like to know how to clean out those too, if anybody has a suggestion.
This does lead to the ultimate question of, "What kinds of hidden cruft accumulates from using MSVS on a development machine?"
Win7/64, C++ MSVS 2008, NTFS

A: I'm not sure if the particular file you were having problems with was fairly large (greater than 10,000 lines), but I've had the same issue of breakpoints being on the wrong lines several times under that circumstance in MSVS2008.  The solution that worked for me (and improved the readability of the code) was to group a few of the functions logically into a class/namespace and put them into a new file.

A: cl.exe when launched via CreateProcess does not seem to have write permissions addresses your second question. Why do you only see it when launched from within an exe?
It's most likely that cl.exe is failing elsewhere. If you use Process Monitor, it will give you a good idea on all the system calls made by cl.exe and what failed.
In my case, I was overriding the environment variables when calling CreateProcess and in that process ended up resetting SystemRoot environment variable. cl.exe uses it to resolve paths for some system dlls and as a result never ended up finding the dll.
The short term fix was to add "SystemRoot=c:\windows" to the environment settings I was passing into CreateProcess.
The right long term fix is the get the environment variables, parse them and only modify/append as required and pass that whole environment variables block to CreateProcess. That way, cl.exe launched via CreateProcess inherits the environment variables that your exe launched with.


text:
Q: Shopify not calling on my fulfillment /fetch_tracking_numbers I am Developing a new warehouse integration for the company I work for as there was not existing solution.
I have gotten almost every feature to work including
fulfillment request and stock requests and even registered a carrier service for real time shipping rates however for some reason i can not get the
/fetch_tracking_numbers call to fire from shopify according to the documentation
"Once per hour Shopify will make a request to this endpoint if there are any completed fulfillments awaiting tracking numbers from the remote fulfillment service."
however I have added logs to the call so i can trouble shoot it however it seems that shopify never makes this call to the server.
If I visit the url myself i can fire the code (logs and all) however it doesn't seem like shopify is doing so
In the install I made sure to provide a valid call back url (thats why fetch stock works fine) and set the tracking support field to true but still nothing

A: One way to be sure would be ensure that a product's variant is set to your custom fulfillment company. Then complete a bogus order for the product. Now fulfill it. Once you have fulfilled it, Shopify will poll your end point for order's and their tracking numbers. It works fine for me... but I am thinking maybe you're waiting for Shopify and nothing is actually fulfilled.

A: I am probably too late to answer this but Shopify will make calls to this only if
1) you have "completed" fulfillments
2) tracking number for this completed fulfillments is pending.
You need to mark "complete" a fulfillment after shipping all the order line items


text:
Q: duplicate list is adding to gridview in android Hi in the below I am displaying calendarview.In calendarview I am selecting date and passing that date to GetAppointmentDate(selecteddate) if selecteddate and my date matches I am displaying gridview layout.but it is give multiple list with below .
Can any one help y duplicate list is displaying evrytime.
CalendarViewActivity.java:
public class CalendarViewActivity extends Activity implements DatetimeAdapter.MyItemClickListener{

    private CalendarView mCalendarView;
    private ProgressDialog progressDialog = null;
    private ArrayList<GetData> getDataArrayList;
    private ArrayList<GetSlots> getSlotsArrayList;
    private GridView gridLayout;
    private  GetData getData2;
    private GetSlots getSlots2;
    private String Id,StartTime,SlotBooked,SlotDate,EndTime,SloteTime;
    private DatetimeAdapter datetimeAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.calendar_view);
        gridLayout=findViewById(R.id.gridlayout);
        getDataArrayList=new ArrayList<>();
        getSlotsArrayList=new ArrayList<>();

        mCalendarView = (CalendarView) findViewById(R.id.calendarView);
        mCalendarView.setMinDate(System.currentTimeMillis() - 1000);
        datetimeAdapter = new DatetimeAdapter(getApplicationContext(), getSlotsArrayList,this);

        mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            Calendar calendar = Calendar.getInstance();
            int year1 = calendar.get(Calendar.YEAR);
            int month1 = calendar.get(Calendar.MONTH);
            int dayOfMonth1 = calendar.get(Calendar.DAY_OF_MONTH);

            @Override
            public void onSelectedDayChange(CalendarView CalendarView, int year1, int month1, int dayOfMonth1) {

                String date = new SimpleDateFormat("MM", Locale.getDefault()).format(new Date());
                SimpleDateFormat sdf = new SimpleDateFormat(date);

                String selecteddate = (sdf.format(month1 + 1)) + "/" + dayOfMonth1 + "/" + year1;

                GetAppointmentDate(selecteddate);
                Toast.makeText(getApplicationContext(),selecteddate,Toast.LENGTH_LONG).show();
                }
        });

    }
    private void GetAppointmentDate(String outputcurrentdate) {
//        progressDialog = new ProgressDialog(getApplicationContext());
//        progressDialog.setIndeterminate(true);
//        progressDialog.setMessage("Loading...");
//        progressDialog.setCanceledOnTouchOutside(false);
//        progressDialog.setCancelable(false);
//        progressDialog.show();
        String doctor_ids="13";
        String HospitalId="PH:193";
        final APIService service = RetroClass.getRetrofitInstance().create(APIService.class);
        Call<GetAppointmentDateModel> call = service.GetAppointmentDate(doctor_ids,HospitalId);
        Log.wtf("URL Called", call.request().url() + "");
        call.enqueue(new Callback<GetAppointmentDateModel>() {
            @Override
            public void onResponse(Call<GetAppointmentDateModel> call, Response<GetAppointmentDateModel> response) {
                Log.e("response", new Gson().toJson(response.body()));
                if (response.isSuccessful()) {
                    Log.e("response", new Gson().toJson(response.body()));
                    GetAppointmentDateModel getAppointmentDateModel = response.body();
                    ArrayList<GetData> getData = getAppointmentDateModel.getGetAppointmentList();
                    for (GetData getData1 : getData) {
                        String date1 = getData1.getDate();
                        String id=getData1.getId();
                        DateFormat inputFormatter = new SimpleDateFormat("dd MMM yyyy HH:mm-HH:mm");
                        Date date = null;
                        try {
                            date = inputFormatter.parse(date1);
                            DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
                            String output = outputFormatter.format(date);
                            getData2=new GetData(id,output);
                            getDataArrayList.add(getData2);
                            Log.d("dateString",output);
                            ArrayList<GetSlots> getSlots = getData1.getData();
                            for (GetSlots getSlots1 : getSlots) {
                                Id=getSlots1.getId();
                                SlotDate=getSlots1.getDate();
                                StartTime=getSlots1.getStartTime();
                               EndTime=getSlots1.getEndTime();
                                SloteTime=getSlots1.getSlotTime();
                                SlotBooked=getSlots1.getSlotBooked();

                                getSlots2=new GetSlots(Id,SlotDate,StartTime,EndTime,SlotBooked,SloteTime);
                                getSlotsArrayList.add(getSlots2);

                            }

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                    }
                    String current_date=getData2.getDate();
                    if(current_date.equals(outputcurrentdate)) {
                        gridLayout.setAdapter(datetimeAdapter);
                        datetimeAdapter.notifyDataSetChanged();
                    }
                }

               // progressDialog.dismiss();
            }
            @Override
            public void onFailure(Call<GetAppointmentDateModel> call, Throwable t) {
                Log.d("error", t.getMessage());
              //  progressDialog.dismiss();
            }
        });

    }

    @Override
    public void myItemClick(int position) {

    }
}

A: Your list - getSlotsArrayList is addding new values each time and it is not clearing anywhere. This is the same list that is passed to the adapter. so it is displaying multiple values.
Call clear method before this
getSlotsArrayList.clear();
GetAppointmentDate(selecteddate);


text:
Q: how to calculate the flops from tfprof in tensorflow? how can i get the number of flops from tfprof i have the code as:
def calculate_flops():
    # Print to stdout an analysis of the number of floating point operations in the
    # model broken down by individual operations.
    param_stats = tf.contrib.tfprof.model_analyzer.print_model_analysis(
    tf.get_default_graph(),
    tfprof_options=tf.contrib.tfprof.model_analyzer.
    TRAINABLE_VARS_PARAMS_STAT_OPTIONS)
    print(param_stats)

but the results says flops = 0.
how can i calculate the number of flops. can i have an example ?

A: First of all, as of now, tfprof.model_analyzer.print_model_analysis is deprecated and tf.profiler.profile should be used instead according to the official documentation.
Given that we know the number of FLOP, we can get the FLOPS (FLOP per second) of a forward pass by measuring run time of a forward pass and divide FLOP/run_time
Let's take an easy example.
g = tf.Graph()
sess = tf.Session(graph=g)
with g.as_default():
    A = tf.Variable(initial_value=tf.random_normal([25, 16]))
    B = tf.Variable(initial_value=tf.random_normal([16, 9]))
    C = tf.matmul(A,B, name='output')
    sess.run(tf.global_variables_initializer())
    flops = tf.profiler.profile(g, options=tf.profiler.ProfileOptionBuilder.float_operation())
    print('FLOP = ', flops.total_float_ops)

outputs 8288. But why do we get 8288 instead of the expected result 7200=2*25*16*9[a] ? The answer is in the way the tensors A and B are initialised. Initialising with a Gaussian distribution costs some FLOP. Changing the definition of A and B by
    A = tf.Variable(initial_value=tf.zeros([25, 16]))
    B = tf.Variable(initial_value=tf.zeros([16, 9]))

gives the expected output 7200.
Usually, a network's variables are initialised with Gaussian distributions among other schemes. Most of the time, we are not interested by the initialisation FLOP as they are done once during initialisation and do not happen during the training nor the inference. So, how could one get the exact number of FLOP disregarding the initialisation FLOP?
Freeze the graph with a pb.
The following snippet illustrates this:
import tensorflow as tf
from tensorflow.python.framework import graph_util

def load_pb(pb):
    with tf.gfile.GFile(pb, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(graph_def, name='')
        return graph

# ***** (1) Create Graph *****
g = tf.Graph()
sess = tf.Session(graph=g)
with g.as_default():
    A = tf.Variable(initial_value=tf.random_normal([25, 16]))
    B = tf.Variable(initial_value=tf.random_normal([16, 9]))
    C = tf.matmul(A, B, name='output')
    sess.run(tf.global_variables_initializer())
    flops = tf.profiler.profile(g, options = tf.profiler.ProfileOptionBuilder.float_operation())
    print('FLOP before freezing', flops.total_float_ops)
# *****************************

# ***** (2) freeze graph *****
output_graph_def = graph_util.convert_variables_to_constants(sess, g.as_graph_def(), ['output'])

with tf.gfile.GFile('graph.pb', "wb") as f:
    f.write(output_graph_def.SerializeToString())
# *****************************

# ***** (3) Load frozen graph *****
g2 = load_pb('./graph.pb')
with g2.as_default():
    flops = tf.profiler.profile(g2, options = tf.profiler.ProfileOptionBuilder.float_operation())
    print('FLOP after freezing', flops.total_float_ops)

outputs
FLOP before freezing 8288
FLOP after freezing 7200

[a] Usually the FLOP of a matrix multiplication are mq(2p -1) for the product AB where A[m, p] and B[p, q] but TensorFlow returns 2mpq for some reason. An issue has been opened to understand why.


text:
Q: How to Check for HttpStatusCode.OK in GetResponse I was just wondering how to check if the HTTP status for okay before returning a value.
Here's the code snippet
var httpResponse = await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
        dynamic data = JObject.Parse(responseText);
            shorturl = data.shortLink;
    }
return shorturl;

Was thinking of something along the lines of
if responseText.Contains(HttpStatusCode.OK)

Or
if (httpResponse.StatusCode == HttpStatusCode.OK)
return shorturl;

Anything to point me in the right direction would be appreciated!

A: Internally  HttpStatusCode is enum
public enum HttpStatusCode
{
    ...
    Moved = 301,
    OK = 200,
    Redirect = 302,
    ...
}

Then
HttpStatusCode statusCode;

//your response code

statusCode = response.StatusCode;

if ((int)statusCode == HttpStatusCode.OK)
return shorturl;


text:
Q: Command for toggling line numbers in vi I know
:set number

and
:set nonumber

I want to know whether there is any command in vi/vim
:set togglenumber

to display line number if the line numbers is not showing or hiding line numbers if line numbers is showing.

A: I use relative line numbers, for all lines above and below the current line, together with absolute line numbering for the current line.
But this is only working since Vim 7.4.
This is sometimes named "Hybrid" line numbering (e.g. in the article https://jeffkreeftmeijer.com/vim-number/)
To toggle from "no numbers at all" to "hybrid" you can use the following config:
set number relativenumber " Turn line numbering on at startup
" Toggle line numbers from none at all
" to relative numbering with current line number
noremap <F3> :set invnumber invrelativenumber<CR>

A: You can use (on VIM at least):

:set invnumber

More Info:
:set number      Turn line numbers on
:set nonumber    Turn line numbers off
:set invnumber   Toggle line numbers
:set number!     Toggle line numbers
:set number&     Set option to default value
:set number?     Show value of option

source: http://vim.wikia.com/wiki/Managing_set_options#Boolean_options

A: In vim, many options support this set pattern, (for example, foo):
"enable the option
set foo

"disable it
set nofoo

"toggle the option
set foo!

"get option's current value
set foo?

for number, map a key to :set nu! would be ok.

A: You can toggle any (boolean) option using the ! suffix, i.e. :set number! would toggle displaying line numbers.
The on-board help for this command is a bit hidden; while one would think :help toggle would get you there, it doesn't quite. Using :help set-! is the magic word.


text:
Q: Should the automated ban on questions used on SO apply to Meta as well? From this question, it appears that the same system for blocking new questions by those that have a history of bad questions used on Stack Overflow also applies to Meta Stack Overflow.  Should it?
Downvotes appear to be a significant component of this algorithm (the specifics of which are not released, for obvious reasons).  However, downvotes on Meta have a different meaning than those on the mainline sites.  On SO, a downvote typically indicates a lazy or poorly structured question.
Here, someone can put significant effort into a proposal and have it downvoted because the crowd disagreed with what was suggested.  That doesn't necessarily show laziness or malice, simply someone throwing out an idea that others think won't work.
Therefore, is it appropriate to have the same sort of automated cutoff in place here as on SO?  The traffic is much lower here, and this is less of a Google destination for people, thus there are fewer garbage questions.  For those that abuse the system, the manual moderation system already in place would seem to work.

A: Downvotes are one component, but the other component is volume and history - this block is triggered by people who continually post low-rated content. From the example user, only 6 negative questions are visible amounting to -40. However, I've seen a few additional questions which have since been deleted. This is a continual supply of negative rated content, not just a handful of incidents.
Really bad suggestions are the ones that get heavily downvoted. "The crowd" doesn't have a singular mindset - mass downvotes usually accrue because a large number of people agree that it's a bad idea. If you are getting a lot of downvotes on all of your questions, then it's time to reconsider your understanding of the site.
People who do nothing but post really bad suggestions are just as harmful to the Meta site as people who post really poor quality questions on Stack Overflow. If your suggestions are borderline or only mildly disagreeable, then it's not going to be as frequent to receive large amounts of downvotes.
I don't see a problem where individual users who are posting decent suggestions and making an effort to understand how the community works are getting overly punished with downvotes. Until that actually exists as a problem, then I believe the problem of the automated question ban is most likely to be minimal.

A: I would say no, in the absence of some statistics from data dumps showing that this is a problem.  Usually "bad users" on meta are those who repeatedly troll the site (and are eventually banned anyway), not those who have lots of downvoted questions, as you say.
I would more lean towards the idea of banning users on meta who are banned on SO for bad questions, because the type of question they are likely to ask here is simply "Why was I banned?" which will be closed as a dupe anyway.
Is anyone interested in running a query to see what a "bad question asker" on Meta looks like?

EDIT: It appears as if the automated ban applies here too: https://meta.stackexchange.com/questions/67075/can-any-human-being-read-this

A: Probably it will be enabled, with a relaxed threshold.
That said, in this particular case I am pretty sure whatever threshold we set would have been exceeded by a wide margin.


text:
Q: How to enable external request in IIS Express and MQTTnet i was able to access normal iisexpress-webservices from extern with change of
....vs\DashboardCore\config\applicationhost.config
when adding more bindings with my hostname:
/<bindings>
  <binding protocol="http" bindingInformation="*:5001:127.0.0.1" />
            <binding protocol="http" bindingInformation="*:5001:localhost" />
            <binding protocol="http" bindingInformation="*:5000:localhost" />
            <binding protocol="http" bindingInformation="*:47200:localhost" />
            <binding protocol="https" bindingInformation="*:44334:localhost" />

            <binding protocol="http" bindingInformation="*:5001:nb080.mydomain.local" />
            <binding protocol="http" bindingInformation="*:5000:nb080.mydomain.local" />
            <binding protocol="http" bindingInformation="*:47200:nb080.mydomain.local" />
            <binding protocol="https" bindingInformation="*:44334:nb080.mydomain.local" />
</bindings>

but MQTTnet from the client still works only with
var url = "localhost:5001/mqtt";
and not with
var url = "nb080.mydomain.local:5001/mqtt";
            var options = new ManagedMqttClientOptionsBuilder()
                .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                .WithClientOptions(new MqttClientOptionsBuilder()
                    .WithClientId($"Client {printer}")
                    .WithWebSocketServer(url)
                    .WithCredentials(database, hash)
                    .Build())
                .Build();

i expect that mqttnet also uses the hostname.
my launchsettings.json looks like
{
    "$schema": "http://json.schemastore.org/launchsettings.json",
    "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
            "applicationUrl": "http://localhost:5001",
            "sslPort": 44334
        }
    },
    "profiles": {
        "IIS Express": {
            "commandName": "IISExpress",
            "launchBrowser": true,
            "launchUrl": "weatherforecast",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        }
    }
}


text:
Q: Dynamically replace the grid name I have a jquery code like
"where" :   window.parent.grdRMAReport.CurrentFilter,

grdRMAReport has to be dynamic i.e. it can be grdrefundreport also. I want it to be a variable.
i tried like
window.parent.+varname+.CurrentFilter,

and
'window.parent.'+varname+'.CurrentFilter',
both does not work. 1st throws error and second becomes a string. How do i solve this problem.

A: you can try like this
window.parent[varname]['CurrentFilter']


text:
Q: Why I Am Unable to Remove Text-decoration-style from Underline to None? When I am trying to run this code on a local server m getting this error. I have already mentioned in code that text-decoration-style: none;
I am getting text decoration as an underline, I want to remove that.
<style>
    li {
        list-style-type: none;
        text-decoration-style: none;
        display: inline-block;
        color: white;
        padding: 20px;
        margin-left: 20px;
    }

    .navbar {
        max-width: 100%;
        background-color: black;
    }
</style>

Image of the Error where m getting error.

A: text-decoration-style: none; is wrong syntax, you should instead use text-decoration-style: unset; a better approach would be to use text-decoration: none;
Also The text-decoration-style property is not supported by Internet Explorer/Edge or Safari.
For further usage and syntax please check this article

A: If you are using an anchors <a> inside the li then you should apply this to a not li
.navbar ul li a{
    text-decoration: none;
}


text:
Q: Can not resolve the error: Incomplete shapefile definition in 'filename.shp' I'm trying to add a feature to draw a map but this error:
"Incomplete shapefile definition in 'eez v11.shp'" keeps popping.
Here is the code I wrote:
fname = 'eez_v11.shp'
shape_feature = ShapelyFeature(Reader(fname).geometries(),
                                ccrs.PlateCarree(), edgecolor='k',facecolor='gray')
ax.add_feature(shape_feature)

Do you know how I can solve this issue?

A: In Source code for cartopy.io.shapereader
if reader.shp is None or reader.shx is None or reader.dbf is None:
   raise ValueError("Incomplete shapefile definition "
                    "in '%s'." % filename)

So one of these files is missing


text:
Q: how to bind closest li id to php variable I want to get the closest id of the parent li and allocate it to a pre tag.
In a div, which surrounds the pre tag, there must be an onclick event with the same id.
What i have so far:
Adding the id to the pre tag from the parent li:
$('pre').each(function(){
          $(this).attr('id', $(this).closest('li').attr('id')+'_pre');
        });

The onclick event (i added this to a php variable)
$SelectButton = '[Select and Copy]
';

Prepend just above the pre tag a span with the onclick
$('.surroundpre').prepend('$SelectButton');

The only thing i don't know how to achieve: in the php variable should id1 also be replaced with the same id as already is added to the pre tag


text:
Q: java kryo 3.0.3 low object's serialization speed I'm trying to get better performance of object's serialization by usage of kryo library.
I have the next class
public class CustomClass {

  private String name;
  private int[] array;

  public CustomClass(String name, int size){
      this.name = name;
      fillArray(size);
  }

  private CustomClass(){ }

  private void fillArray(int size){
      array = new int[size];
      Random random = new Random();
      for (int i = 0; i < size; i++){
          array[i] = random.nextInt();
      }
  }
}

I'm serilizing it by this method, note I'm making serialization of single instance
public void kryoWrite(Object object){
    Kryo kryo = new Kryo();
    Output output = null;
    try {
        output = new Output(new FileOutputStream("kryo.txt"));
        kryo.writeObject(output, object);
    } catch (IOException e){
        e.printStackTrace();
    } finally {
        if (output != null) {
            output.close();
        }
    }
}

but serializing the same object using standard Java's Serializable interface works faster.
For example, when I pass 1000000 as second param to constructor kryo serialize object in 188 ms, when Serializable serializes exactly the same object in 136 ms.
So what I'm doing wrong (is it a dubstep in my song, lol)?
EDIT
Serialization of array with size of 1000000, created and serializaed by these methods appropriately
public static int[] getArray(int size){
    int[] array = new int[size];
    Random random = new Random();
    for (int i = 0; i < size; i++){
        array[i] = random.nextInt();
    }
    return array;
}

public static void kryoWriteArray(int[] array) throws FileNotFoundException   {
    Kryo kryo = new Kryo();
    Output output = new Output(new FileOutputStream("array.txt"));
    output.writeInts(array);
    output.close();
}

takes 139 ms.

A: At first it's hard to comment a benchmark if not the whole benchmark code is available. Please share it if further analysis is needed. Still, I'd already advice to pull object creation (new CustomObject) out of the benchmark if that's not already the case (and in general I'd create data of CustomObject outside and pass it into the class).
To be able to reproduce this issue I adopted Kryo's SerializationBenchmarkTest to test your CustomClass with an int[] of length 1000000 (please note that this benchmark measures serialization and deserialization combined, this could also be measured separately).
The consolidated result shows the following (check the mentioned commit for more details) for the best java serialization runs:
>>> Java serialization via Externalizable (best time): 870 ms
>>> Java serialization without try-catch via Externalizable (best time): 864 ms

For the best kryo serialization runs it shows:
>>> Kryo serialization without try-catch (best time): 835 ms
>>> Kryo unsafe serialization without try-catch, without ASM, without references (best time): 181 ms
>>> Kryo serialization without try-catch with fast streams (best time): 982 ms
>>> Kryo unmodified serialization (best time): 1,108 ms
>>> Kryo unsafe serialization without try-catch, without ASM (best time): 191 ms
>>> Kryo unsafe serialization without try-catch (best time): 193 ms
>>> Kryo serialization (best time): 989 ms

As it seems, Unsafe based serialization seems to do the trick here, so I'd say you should try Kryo's UnsafeOutput instead of Output.


text:
Q: Getting coordinates at location n meters from known point to NW and SE using ArcPy? I have a point shapefile or feature class and I want to create bounding boxes around each point.  The size of the bounding box will depend on user input, for example the user might want a bounding box of 50 x 50 meters.
The shapefiles are in WGS 84.  This boils down to getting the x/y coordinates of a point x meters away from the existing point to the South East and to the North West (bearing 135 and 315 degrees).
How can I use arcpy to get the x/y coordinates of a point n meters away to the NW and the SE?

A: As @Paul suggested, you can use some simple trig to do this:
import arcpy

def getPoly(pt, w, h, wkid):
    """calculates polygon corners

    pt -- tuple of coordinates (x, y)
    w -- width of polygon (x length)
    h -- height of polygon (y length)
    sr -- spatial reference object
    """
    x, y = pt
    ll = (x - (w * 0.5), y - (h * 0.5))
    ul = (x - (w * 0.5), y + (h * 0.5))
    ur = (x + (w * 0.5), y + (h * 0.5))
    lr = (x + (w * 0.5), y - (h * 0.5))
    return arcpy.Polygon(arcpy.Array([arcpy.Point(*coords) for coords in [ll,ul,ur,lr,ll]]), sr)

coords =(-10377711.530988107, 5617827.075599414)
sr = arcpy.SpatialReference(102100)
poly = getPoly(coords, 50, 50, sr) # make a bounding box 50x50 meters
e = poly.extent
bbox = ','.join(map(str, [e.XMin, e.YMin, e.XMax, e.YMax])) #here's the bbox

The bounding box came out as:
'-10377736.531,5617802.0756,-10377686.531,5617852.0756'


text:
Q: How can I customize the validation error message in the Symfony's Controller I have an ajax call to an url corresponding to a symfony2 coded page and in that page I have validation of one data passed to the page.
My validator :
/**
* @Assert\Regex(pattern="/^(https?:\/\/)/", message="wrong_string", groups={"searchnow_url_post"})
...
*/
public $searchstring;

When I build the answer to the ajax call I write it directly in the controller using JsonResponse. My problem is when validation produces an error I do something like:
return new JsonResponse(array(
    'status' => 401,
    'error_msg'=> (string)$errors
));

To be more precise, the whole controller is :
class BaseController extends Controller
{
public function searchnow_url_postAction(){
    $input_string=$_REQUEST['src'];

    $search_string= new Searchstring();
    $search_string->setSearchstring($input_string);

    //qui devo usare il validation group "search_now"
    $validator = $this->get('validator');
    $errors = $validator->validate($search_string, null, array('searchnow_url_post'));
    if (count($errors) > 0){
        $status=401;
        return new JsonResponse(
            array('status' => 401,
                'error_msg'=> (string) $errors
        ));
    }
    else
        return new JsonResponse(array('status' => 200));
    }
}

(The above validator is extracted from the entity Searchstring)
In the javascript I receive in error_msg :

"Object(MemoBundle\Entity\Searchstring).searchstring: Wrong string."

but this is not good.
I would like to receive in error_msg  only the message "Wrong string" without "Object(MemoBundle\Entity\Searchstring).searchstring:".
How can I do to receive this?

A: You haven't shown any of the code responsible for generating the output itself. As you can see, your error message showed up as expected
Somewhere you are calling your form object,
$form->getErrors( ... )
This is the relevant block.

A: I've got the solution. The issue was very simple but being new to Symfony2 I had some difficulties to focalize my problem.
I need to use the getMessage() method of ConstraintViolation object , where a list of this objects is returned from validate method of validator object.
To write some code lines the controller above now  sounds like this:
public function searchnow_url_postAction(){
    $input_string=$_REQUEST['src'];

    $search_string= new Searchstring();
    $search_string->setSearchstring($input_string);

    //qui devo usare il validation group "search_now"
    $validator = $this->get('validator');
    $errors = $validator->validate($search_string, null, array('searchnow_url_post'));
    if (count($errors) > 0){

        $error_ret_msg='';
        foreach ($errors as $error){
            $error_ret_msg.=$error->getMessage()."|";
        }

        $status=401;
        return new JsonResponse(
            array('status' => 401,
                'error_msg'=> $error_ret_msg,
        ));
    }
    else
        return new JsonResponse(array('status' => 200));
}

I've used a foreach cycle in the case there are more validation constraints violated for the same variable, separating each error message with a "|".


text:
Q: Python decrementing loop i have a loop but its incrementing. what is the syntax for decrementing the loop?
for item2 in textPad.get(itemindex,END):
    tagnames = textPad.tag_names(str(curline)+"."+str(curchar))
    if not "phpsingqoute" in tagnames and not "phpdoubqoute" in tagnames and not "phpcomment" in tagnames:
        if item2 == theopenandclose[1]:
            opencount -= 1
            if opencount == 0:
                textPad.tag_add(tagname,str(curline)+"."+str(curchar))
                textPad.tag_config(tagname,foreground="white",background="#000")
                break
        if item2 == theopenandclose[0]:
            opencount += 1
    if re.match(r'\n',item2):
        curline += 1
        curchar = -1
    curchar += 1

A: If textPad.get returns a list, you can use reversed
for item2 in reversed(textPad.get(itemindex,END)):

This will also work for some other iterable types, but not all. See the documentation. If you get a TypeError, try converting the result of textPad.get to a list first.:
for item2 in reversed(list(textPad.get(itemindex,END))):

A: can not add a comment
the answer is reversed(...)
Post before in this forum


text:
Q: How can I replace a word with text from earlier in the same line? I have a text file that looks like this:
_map[0x00000044] = "screen";
_map[0x00000059] = "map";
_map[0x0000006e] = "info";

I would like to replace the words at the end of each line so my output looks like this:
_map[0x00000044] = "0044";
_map[0x00000059] = "0059";
_map[0x0000006e] = "006e";

I would like to update the file in-place. I tried the following but there must be a simpler way.
my $infile = 'newnumbers.txt';
open my $input, '<', $infile or die "Can't open to $infile: $!";
my @finaldata = ();

while (<$input>){
    chomp;

    print "$1\n" if ($_ =~ /(0x0000.*])/);
    push(@finaldata, $1);
}

A: use strict;
use warnings;

my $infile = 'newnumbers.txt';

local @ARGV = ($infile);
local $^I = '.bac';
while( <> ){
    s/(_map\[0x[[:xdigit:]]{4}([[:xdigit:]]{4})\] = )".*"/$1"$2"/;
    print;
}

or if you're using a newer version of perl, the regex could be the following
s/_map\[0x[[:xdigit:]]{4}([[:xdigit:]]{4})\] = \K".*"/"$1"/;

A: How about this:
my $infile = $ARGV[0] || 'newnumbers.txt';
open FH, $infile;
my @lines = <FH>;
s/(_.*(\w{4})] = ")\w+(";)/$1$2$3/ foreach @lines;
print join '', @lines;


text:
Q: Hello I want to equip my web service with Jivity but I have a problem My key is generated successfu I want to equip my web service with Jivity but I have a problem
My key is generated successfully but when requested it is not verified and I get the following error:
Fatal error: Uncaught TypeError: Key material must be a string, resource, or OpenSSLAsymmetricKey in G:\xampp\htdocs\vendor\firebase\php-jwt\src\Key.php:31 Stack trace: #0 G:\xampp\htdocs\users.php(12): Firebase\JWT\Key->__construct(NULL, 'HS256') #1 {main} thrown in G:\xampp\htdocs\vendor\firebase\php-jwt\src\Key.php on line 31
what is the problem?
Thanks.
Hello
I want to equip my web service with Jivity but I have a problem
My key is generated successfully but when requested it is not verified and I get the following error:
Fatal error: Uncaught TypeError: Key material must be a string, resource, or OpenSSLAsymmetricKey in G:\xampp\htdocs\vendor\firebase\php-jwt\src\Key.php:31 Stack trace: #0 G:\xampp\htdocs\users.php(12): Firebase\JWT\Key->__construct(NULL, 'HS256') #1 {main} thrown in G:\xampp\htdocs\vendor\firebase\php-jwt\src\Key.php on line 31
what is the problem?
Thanks.


text:
Q: Getting always null value async task I am passing the value to another activity but getting always null value
public class SatelliteDirectActivity extends Activity {
private Intent intent;
private Bundle b;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    intent = new Intent(SatelliteDirectActivity.this,ClsMainActivitySatelliteDirect.class);
    b = new Bundle();
    setContentView(R.layout.initial_splash_screen);
    boolean bCheckInternetConnectivity = checkInternetConnection();
    if(!bCheckInternetConnectivity)
    {
        Toast.makeText(this, "Please ensure that you have a internet connectivity", Toast.LENGTH_SHORT);
        finish();
    }
    else
    {
        new GetCountryInformation().execute();

    }
    startActivity(intent);
        finish();
}
private boolean checkInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    // test for connection
    if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        Log.v("ERROR_LOG", "Internet Connection Not Present");
        return false;
    }
}
public class GetCountryInformation extends AsyncTask<String, Void,String> {

   protected void onPreExecute() {
        super.onPreExecute();

    }

   /*   protected void onProgressUpdate(Integer... progress) {
        //setProgressPercent(progress[0]);
    }*/
    @Override
    protected String doInBackground(String... params) {
        JSONObject mJsonObject = ClsGetJsonFunction.getJSONfromURL("http://www.sachdevbros.com/sdandroid/videos/country.php");
        String [] sCountryNames = null;
        String [] sCountryCid = null ;
        try
        {
        JSONArray mJsonArray = mJsonObject.getJSONArray("results");
        sCountryNames= new String[mJsonArray.length()];
        sCountryCid= new String[mJsonArray.length()];
        for(int icount = 0 ; icount <mJsonArray.length()-1; icount++)
        {
            JSONObject mJsonObject2 = mJsonArray.getJSONObject(icount);
            sCountryNames [icount] = mJsonObject2.getString("country");
            sCountryCid[icount] = mJsonObject2.getString("cid");
        //  Log.v("JSON", ClsGlobalConstants.sGLB_sCountryNames[icount]+ClsGlobalConstants.sGLB_sCountryCid[icount]);
        }

        }catch(JSONException je)
        {
            Log.v("ERROR_TAG", ""+je);
        }
        b.putStringArray("cou", sCountryNames);
        b.putStringArray("cid", sCountryCid);

        intent.putExtras(b);

        return null;
    }

    protected void onPostExecute(Void... aa) {
       super.onPostExecute(null);
        //  showDialog("Downloaded " + result + " bytes");

     }
}

and receiving this as
        final String country[] =this.getIntent().getStringArrayExtra("cou");
    String cid[] =this.getIntent().getStringArrayExtra("cid");

A: This is because, you are starting other activity immediately after start the AsyncTask, It cause bundle empty, So if possible put your staring other activity code in AsyncTask's postExecute().. Then you can get values in other activity..
For this pass your activity reference in AsyncTask and using that reference call startActivity()..
protected void onPostExecute(Void... aa) {
       super.onPostExecute(null);
        //  showDialog("Downloaded " + result + " bytes");
       mContext.startActivity(intent);
       mContext.finish();
     }

A: You passing the value in a bundle
 b.putStringArray("cou", sCountryNames);
 b.putStringArray("cid", sCountryCid);
 intent.putExtras(b);

So you should get the bundle value like this.
 Bundle b = getIntent().getExtras();
 String  mJsonvalue[] = b.getStringArrayList("cou");

I think this will solve your problem.


text:
Q: legends position multiplot gnuplot I am using Windows 10 and Gnuplot 5.0.
I have a script to plot several graphs simultaneously:
GNUTERM = "wxt"
set terminal wxt
set termoption enhanced
set encoding iso_8859_1
set multiplot layout 1,3
set xtics out
set ytics out
set xtics nomirror
set ytics nomirror
set xzeroaxis linetype 2 linewidth 1.5
show xzeroaxis
# Graph1
set key center right
set xrange [3.3:9.0]
set yrange [-0.1:1.10]
set title "Title 1"
set xlabel "x"
set ylabel "y"
plot \
"results_1.dat" u 1:2:4 title "exp." with e pointtype 9 pointsize 0.5 linecolor rgb "red" , \
"results_1.dat" u 1:3 title "fit." with line linecolor rgb "black" linewidth 2 dashtype 2 smooth bezier
# Graph2
set xrange [3.3:9.0]
set yrange [-0.1:1.10]
set key top right
set title "Title 2"
set xlabel "x"
set ylabel "y"
plot \
"results_2.dat" u 1:2:4 title "exp." with e pointtype 9 pointsize 0.5 linecolor rgb "blue", \
"results_2.dat" u 1:3 title "fit." with line linecolor rgb "black" linewidth 2 dashtype 2 smooth bezier
# Graph3
set xrange [3.3:9.0]
set yrange [-0.1:1.10]
set key outside vertical top right
set title "Title 3"
set xlabel "x"
set ylabel "y
plot \
"results_3.dat" u 1:2:4 title "exp." with e pointtype 9 linecolor rgb "red", \
"results_3.dat" u 1:3 title "fit." with line linecolor rgb "black" linewidth 2 dashtype 2 smooth bezier
unset multiplot
pause 3
reread

However, instead of getting the legend outside only for the graph 3, all legends are shown outside the graphs (see attached image)

I want legends 1 and 2 inside the graphs and legend 3 outside. What's wrong in my script?
Any help is appreciated.
Supernono06

A: It's hard to say without being able to run your script, but if I had to guess I'd say that you request the legend to be outside for graph 3, and when you reread the script you don't put it back inside. Try something like
set key inside center top

for the first graph (or add a reset statement to the beginning of your script).