text:
Q: Airflow Add Google Cloud Connection I'm finding the documentation here:
https://airflow.apache.org/docs/apache-airflow-providers-google/stable/connections/gcp.html
to be about as clear as mud and would be very grateful for some clarifications, please.
I am simply trying to create a connection to my gcp project from my airflow (running out of docker locally). I have a keyfile generated from a suitable service account, but don't know where I should put it.

What is the 'Keyfile path' relative to? Is that from the airflow webserver or the scheduler? Also the documentation suggests that the 'Keyfile JSON' takes the content of the keyfile, but whatever I try I still just get 'bad request' when I try to test the connection.
I am putting the project id in the appropriate field - the screen snip just doesn't show that.
Can anyone clarify, please?

A: Looks like the Keyfile JSON should the content of your Service_account .json file. Usually in the form of:
{"private_key": "r4nd0m_k3y"}

The Keyfile PATH should always be absolute - you just have to make sure it is available for the "workers" (or "scheduler" in case of Local executor - so basically for the entity that executes tasks). In Airflow 2.2 there is also a feature to "test" connections from the UI - if you want to use it, you will have to make it available under this path for Webserver.
Your bad request might come for a different reason BTW. - for example you might have to specify scopes - but you will need to debug it and make sure you have all configurations right. You can test it by providing the key via absolute path if unsure.
Finally - kind request when you get it working, i'd appreciate if you improve the documentation and add those working examples and explanation to make it clearer. It is super simple - go to the docs page and there is the "Suggest a change to this page" button which will open directly a PR and you wil be able to update the docs using GitHub UI. Very simple and straightforward and nice way not only to thank those who make the software available for free - but you can also become one of the more than 1700 contributors to Airflow and "clear the path" for others who had the same problem.

A: What is the 'Keyfile path' relative to?

Copy the service account JSON key file that you downloaded into the
data/ directory of your environment's Cloud Storage bucket. Then, in
Keyfile Path, enter the local file path on the Airflow worker to the
JSON keyfile's location, such as /home/airflow/gcs/data/keyfile.json.
Link

Is that from the airflow webserver or the scheduler?
I'm not sure enough about the second question, but this configuration is made in the airflow webserver.
Consider reviewing the complete tutorial on Managing Airflow Connections. This might be useful with your connection issue.
Regarding the message "Bad request" you can review this document about Error messages in GCP.


text:
Q: Autocomplete issue: Content is not displaying Content is not displaying is autocomplate list as you can see in screenshot below.

I am getting this response.

[{"emp_number":1,"fname":"Arslan","lname":"Hassan"},{"emp_number":2,"fname":"Muneeb","lname":"Janjua"
  },{"emp_number":3,"fname":"hr","lname":"user"},{"emp_number":4,"fname":"test","lname":""} .......... REMOVED TO MAKE IT LOOK BETTER HERE .......]

My JS Code:
$( "#search-emp" ).autocomplete(
{
    source: function (request, response)
    {
        var form_data = {
            ajax                : '1',
            name                : $("#search-emp").val(),
            actioncall          : 'search-emp'
        };

        $.ajax({
            //contentType: "application/json",
            type: "POST",
            dataType: 'json',
            url: "_ajax.php",
            data: form_data,
            success: function( data )
            {
                response( data );
            }
        });
    },
    minLength:3,
    select:function(evt, ui)
    {
        alert(ui.item.emp_number);
    }
});

I want to display fname and lname on selected into input field.

A: The problem it's because jQuery autocomplete wants to have 2 fields named label and value. The content from label will be displayed in the autocomplete.
Because your server return other name for the keys you have 2 options:

*

*Change the server to return a json like:
[{"emp_number":1,"fname":"Arslan","lname":"Hassan", "label":"Arslan Hassan", "value": "Arslan Hassan"},....]

*Or on the success callback from ajax create an array with this fields (label and value) and pass this array to response() callback.
You can find more informations here: http://api.jqueryui.com/autocomplete/#option-source

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unet model for segmentation runs out of data I'm trying to train a segmentation model with Keras but i keep running out of data.
I have 29 pictures in the dataset, and I made 1400 pictures.
So the model is
inputs = tf.keras.layers.Input((512,512,1))
conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)
conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)
conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)
conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)
drop4 = Dropout(0.5)(conv4)
pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)

conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)
conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)
drop5 = Dropout(0.5)(conv5)

up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))
merge6 = concatenate([drop4,up6], axis = 3)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)

up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))
merge7 = concatenate([conv3,up7], axis = 3)
conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)
conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)

up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))
merge8 = concatenate([conv2,up8], axis = 3)
conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)
conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)

up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))
merge9 = concatenate([conv1,up9], axis = 3)
conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)
conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)
conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)
conv10 = Conv2D(1, 1, activation = 'sigmoid')(conv9)

and the parameters I tried last are:
history = model_v2.fit(x=X_train, y=y_train, steps_per_epoch=700, epochs=2, callbacks=[model_checkpoint], validation_data=(X_test, y_test), batch_size=4)
The error I get is:
WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least steps_per_epoch * epochsbatches (in this case, 1400 batches). You may need to use the repeat() function when building your dataset.
Any idea how to improve it? Should I make even more pictures with data augmentation? I would prefer to maybe change something to the model or the parameters.

A: You have :
steps_per_epoch=700
batch_size=4
so you need : 700 * 4 = 2800 pictures.
You should change the parameters so as not to exceed your total number of images (1400).
You can try with 350 steps per epoch (as 350 * 4 = 1400), or with a smaller batch size.


text:
Q: PHP: как одномерный массив преобразовать в двумерный? Есть массив вида:
Array (
  [ФРУКТЫ] => Array()
  [0] => Яблоки
  [1] => Груши
  [2] => Бананы
  [3] => Апельсины
  [4] => Сливы
  [ОВОЩИ] => Array()
  [5] => Лук
  [6] => Помидоры
  [7] => Огурцы
  [8] => Картофель
  [ЗЕЛЕНЬ] => Array()
  [9] => Укроп
  [10] => Петрушка
  [11] => Кинза
)

Какой есть оптимальный способ преобразовать его в двумерный массив вида:
Array (
  [ФРУКТЫ] => Array(
    [0] => Яблоки
    [1] => Груши
    [2] => Бананы
    [3] => Апельсины
    [4] => Сливы
  )
  [ОВОЩИ] => Array(
    [5] => Лук
    [6] => Помидоры
    [7] => Огурцы
    [8] => Картофель
  )
  [ЗЕЛЕНЬ] => Array(
    [9] => Укроп
    [10] => Петрушка
    [11] => Кинза
  )
)

Возможно, имеются какие-то специальные php-функции для подобного преобразования?

A: Нет, никаких специальных php-функций нет.
Чтобы преобразовать массив, требуются обсолютно не специальные функции, цикл: 1 шт, условный переход: 1 шт.
Перебираем массив в цикле, получая ключ и значение в переменные используя foreach
проверяем тип значения
если это массив - присваиваем значение из ключа в особую переменную.
иначе добавляем в новый массив новый элемент, используя особую переменную и текущий ключ в качестве ключей двумерного массива.

A: Решение вашего велосипеда по описанию ответа Ипатьева:
$array = [
    'Фрукты' => [], 'Яблоки', 'Груши', 'Бананы', 'Апельсины', 'Сливы',
    'Овощи' => [], 'Лук', 'Помидоры', 'Огурцы', 'Картофель',
    'Зелень' => [], 'Укроп', 'Петрушка', 'Кинза'
];

foreach ($array as $key => $value)
    is_array($value) ? $so = $key : $new[$so][] = $value;

print_r($new);


text:
Q: Is It Possible for a number that is greater than Integer.MAX_VALUE for both Integers? int x = ?;
if(x > Integer.MAX_VALUE)
{
    System.out.println(x);
}

when the above condition gets true??? what is the value of x?
Integer.MAX_VALUE = 0x7fffffff, I tried x with 0x80000000 in hexa decimal. But x is now negative number.

A: Java integers are 32-bit, and anything above the maximum value for a 32-bit number will get rolled over and become negative. This is known as integer overflow.
If you have:
int x = Integer.MAX_VALUE;
x += 1;

x will equal -2147483648, or Integer.MIN_VALUE.

A: There is no such x.
From the Java docs:

int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -2^31 and a maximum
value of 2^31-1.

That max 32-bit value is equal to 0111 1111 1111 1111 1111 1111 1111 1111.
It's a 2's complement representation, so setting the 1st bit to 1 will result to a negative number (0x80000000 = 1000..0000). So, there's really no possible value for the x you're looking for.


text:
Q: Multiline Caption I want a caption of two lines, with the second line not centered but aligned to the left.

This is the result of the following code, \captionsetup{justification=raggedright} doesn't seem to work. What am I doing wrong?
\documentclass[a4paper,twoside,12pt]{scrreprt}
\usepackage{fontspec}
\usepackage{caption}
\usepackage{booktabs}
\begin{document}
\begin{table}
  \centering
  \captionsetup{justification=raggedright}
\begin{tabular}{cc}
  \toprule
  A & B
\\ \midrule
  11111111111111111  & 1111111111111111\\
  22222222222222222  & 2222222222222222\\
  33333333333333333  & 3333333333333333\\
  44444444444444444  & 4444444444444444\\
  55555555555555555  & 5555555555555555\\
  66666666666666666  & 6666666666666666\\
\bottomrule
\end{tabular}
\caption{Caption caption caption caption\\
caption caption}
\end{table}
\end{document}

A: If you use a threeparttable environment, it computes the width of your table, and it works either with the plain or the hang formats:
 \documentclass[a4paper,twoside,12pt]{scrreprt}
\usepackage[utf8]{inputenc}
\usepackage{fourier, heuristica}
\usepackage{caption}
\usepackage{booktabs}
\usepackage{threeparttablex}

\begin{document}

\begin{table}[!h]
\captionsetup{format =plain}%
\centering
\begin{threeparttable}
\begin{tabular}{cc}
\toprule
A & B
\\ \midrule
11111111111111111 & 1111111111111111\\
22222222222222222 & 2222222222222222\\
33333333333333333 & 3333333333333333\\
44444444444444444 & 4444444444444444\\
55555555555555555 & 5555555555555555\\
66666666666666666 & 6666666666666666\\
\bottomrule
\end{tabular}
\caption{Caption caption caption caption\\
caption caption. }
\end{threeparttable}
\end{table}

\begin{table}[!h]
\captionsetup{format =hang}%
\centering
\begin{threeparttable}
\begin{tabular}{cc}
\toprule
A & B
\\ \midrule
11111111111111111 & 1111111111111111\\
22222222222222222 & 2222222222222222\\
33333333333333333 & 3333333333333333\\
44444444444444444 & 4444444444444444\\
55555555555555555 & 5555555555555555\\
66666666666666666 & 6666666666666666\\
\bottomrule
\end{tabular}
\caption{Caption caption caption caption\\
caption caption. }
\end{threeparttable}
\end{table}\end{document}

Note that it doesn't seem to work with the ThreePartTableenvironment (from threeparttablex), so that you can't break your tables through pages.

A: Hang is the standard caption format in KOMA-Script classes. Therefore you only have to measure the width of the float und to set \setcapwidth to the result. The caption package is not needed.
\documentclass[twoside,12pt]{scrreprt}
\usepackage{fontspec}
\usepackage{booktabs}

\newlength\floatwidth
\newcommand\MyFloat[1]{%
  \settowidth\floatwidth{#1}%
  \setcapwidth[c]{\floatwidth}%
  #1%
}

\begin{document}
\begin{table}
  \centering
  \MyFloat{%
    \begin{tabular}{cc}
      \toprule
      A & B\\
      \midrule
      11111111111111111  & 1111111111111111\\
      22222222222222222  & 2222222222222222\\
      33333333333333333  & 3333333333333333\\
      44444444444444444  & 4444444444444444\\
      55555555555555555  & 5555555555555555\\
      66666666666666666  & 6666666666666666\\
      \bottomrule
    \end{tabular}%
  }
  \caption{Caption caption caption caption caption caption.}
\end{table}
\end{document}

Note: If there should be a manual line break inside the caption you have to use
  \caption{Caption caption caption caption \protect\\ caption caption.}

or maybe better
  \caption[Caption caption caption caption caption caption.]{%
           Caption caption caption caption \\ caption caption.}


text:
Q: Haproxy CORS No 'Access-Control-Allow-Origin' header is present on the requested resource I want to configure haproxy to handle CORS by returning the following in response to being called:
*
Origin, X-Requested-With, Content-Type, Accept, Authorization, JSNLog-RequestId, activityId, applicationId, applicationUserId, channelId, senderId, sessionId
3628800
GET, DELETE, OPTIONS, POST, PUT

However, instead I get "No 'Access-Control-Allow-Origin' header is present on the requested resource". Note I'm using haproxy 1.7.9 and can't compile with lua.
I've reviewed https://www.haproxy.com/blog/enabling-cors-in-haproxy/ but can't recompile with lua.
Also HAProxy CORS OPTIONS header intercept setup
global
  log 127.0.0.1   local0
  log-send-hostname

  chroot /etc/haproxy
  pidfile /var/run/haproxy.pid
  maxconn 40000
  user haproxy
  group haproxy

  daemon
  nbproc 2
  tune.ssl.cachesize 100000
  tune.ssl.default-dh-param 2048

defaults
  log     global
  log-format  %ci:%cp\ [%t]\ %ft\ %b/%s\ %Tq/%Tw/%Tc/%Tr/%Tt\ %ST\ %B\ %U\ %CC\ \ %CS\ %tsc\ %ac/%fc/%bc/%sc/%rc\ %sq/%bq\ %hrl\ %hs\ %{+Q}r
  mode    http
  retries 3
  timeout check 60s
  timeout client 1m
  timeout client-fin 10s
  timeout connect 10s
  timeout http-keep-alive 60s
  timeout http-request 60s
  timeout queue 1m
  timeout server 1m
  timeout server-fin 10s
  option dontlognull
  option forceclose
  option forwardfor
  option http-server-close
  balance  roundrobin

# Set up application listeners here.
resolvers dns
  nameserver            dns1 XXXXXXXXXXXXXXXXXXXXXXXXXX
  resolve_retries       3
  timeout retry         1s
  hold valid            10s

frontend http_frontend
  mode http
  bind XXXXXXXXXXXXXXXXXXX:80 accept-proxy

  capture request header Authorization len 64
  .
  .
  default_backend dead_end

frontend https_frontend
  mode http
  bind XXXXXXXXXXXXXXXX:443 accept-proxy ssl crt /etc/haproxy/crt/ ssl verify optional ca-file /etc/haproxy/ca-file/ca-haproxy-stage.crt ciphers ECDHE-RSA-AES256-SHA:!RC4-SHA:!RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM no-sslv3

  capture request header Host len 64
  capture request header Authorization len 128
  .
  .
  capture request header Content-Length len 64
  capture request header Content-Type len 64

# BEGIN CORS

  capture request header origin len 128

  http-response add-header Access-Control-Allow-Origin %[capture.req.hdr(0)] if { capture.req.hdr(0) -m found }
  rspadd Access-Control-Allow-Headers:\ Origin,\ X-Requested-With,\ Content-Type,\ Accept,\ Authorization,\ JSNLog-RequestId,\ activityId,\ applicationId,\ applicationUserId,\ channelId,\ senderId,\ sessionId  if { capture.req.hdr(0) -m found }
  rspadd Access-Control-Max-Age:\ 3628800 if { capture.req.hdr(0) -m found }
  rspadd Access-Control-Allow-Credentials:\ true  if { capture.req.hdr(0) -m found }
  rspadd Access-Control-Allow-Methods:\ GET,\ DELETE,\ OPTIONS,\ POST,\ PUT  if { capture.req.hdr(0) -m found }

 # END CORS

  use_backend bkservice

backend bkservice
  mode http

  option tcp-check
  option log-health-checks
  tcp-check connect port 80
  tcp-check send GET\ /hap_health HTTP/1.0\r\n
  tcp-check send \r\n
  tcp-check expect rstring HTTP/1.0\ 200\ OK
  server BK_SERVICE myservice.stage.com:443 ssl verify none sni str(myservice.stage.com) check resolvers dns

backend dead_end
  mode http
  server de 127.0.0.1:9001

Access to XMLHttpRequest at 'https://myservice.stage.com/endpoint' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

A: If you want to allow everything, you can remove the CORS block in your configuration and set the headers you want for every response:
frontend https_frontend
    ...
    # BEGIN CORS
    http-response set-header Access-Control-Allow-Origin "*"
    http-response set-header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization, JSNLog-RequestId, activityId, applicationId, applicationUserId, channelId, senderId, sessionId"
    http-response set-header Access-Control-Max-Age 3628800
    http-response set-header Access-Control-Allow-Methods "GET, DELETE, OPTIONS, POST, PUT"
    # END CORS

But you should make sure that using wildcard is okay for your service.  If it isn't, then it probably makes sense to find a way to use HAProxy compiled with Lua support.


text:
Q: how to find the common word from given input in laravel 5.2? Here i am getting stuck on this. Here is my problem:-
I have one table Service
Service table
id     searchservice
1        waxing
2        Waxing
3        American Service
4        Waxing

Now i have one input is:-
 $searchKeyword = Indian waxing

Now i want to find all the records having waxing text i.e. i want to fetch the ids 1,2,4
enter code here
Service::Where('searchservice','like','%'.$searchKeyword.'%')->get();

It gives me empty result. I know in this i have to use some another sql function. Can anyone help me thanks in advance :) . I am using laravel 5.2 framework

A: You are searching for "Indian waxing" if you want to search for each word individually you would have to do:
$searchKeyword = "Indian waxing"
$keywords = explode(" ", $searchKeyword);

$service = Service::query();
foreach($keywords as $word){
    $service->orWhere('searchservice', 'LIKE', '%'.$word.'%');
}

$services = $service->distinct()->get();


text:
Q: 18.04 to 18.10 upgrade failure I have a DELL laptop and I have upgraded Ubuntu on this machine without issue until now. I have tried several times to upgrade from 18.04 to 18.10 and I've tried some of the recommendations on this site to try and get it installed, but it always  fails. I tried from Terminal and got more detail on the attempted upgrade when it failed which I have pasted below. Any ideas on what I'm doing wrong or could do to fix this? Thanks.
do-release-upgrade
Checking for a new Ubuntu release
Get:1 Upgrade tool signature [819 B]
Get:2 Upgrade tool [1,255 kB]
Fetched 1,256 kB in 0s (0 B/s)
authenticate 'cosmic.tar.gz' against 'cosmic.tar.gz.gpg'
extracting 'cosmic.tar.gz'
[sudo] password for steve:

Reading cache

Checking package manager
Reading package lists... Done
Building dependency tree
Reading state information... Done
Hit ie.archive.ubuntu.com/ubuntu bionic InRelease
Ign dl.google.com/linux/chrome/deb stable InRelease
Hit ppa.launchpad.net/gencfsm/ppa/ubuntu bionic InRelease
Get:1 dl.google.com/linux/chrome/deb stable Release [943 B]
Get:2 dl.google.com/linux/chrome/deb stable Release.gpg [819 B]
Hit ppa.launchpad.net/klaus-vormweg/pan/ubuntu bionic InRelease
Hit ppa.launchpad.net/morphis/anbox-support/ubuntu bionic InRelease
Get:3 ppa.launchpad.net/ondrej/php/ubuntu bionic InRelease [20.8 kB]
Hit ppa.launchpad.net/ozmartian/apps/ubuntu bionic InRelease
Get:4 ppa.launchpad.net/ondrej/php/ubuntu bionic/main i386 Packages [43.6 kB]
Get:5 ppa.launchpad.net/ondrej/php/ubuntu bionic/main amd64 Packages [43.6 kB]
Fetched 109 kB in 0s (0 B/s)

(appstreamcli:15338): GLib-CRITICAL **: 14:05:45.946: g_variant_builder_end: assertion '!GVSB(builder)->uniform_item_types || GVSB(builder)->prev_item_type != NULL || g_variant_type_is_definite (GVSB(builder)->type)' failed

(appstreamcli:15338): GLib-CRITICAL **: 14:05:45.947: g_variant_new_variant: assertion 'value != NULL' failed

(appstreamcli:15338): GLib-ERROR **: 14:05:45.947: g_variant_new_parsed: 11-13:invalid GVariant format string
Trace/breakpoint trap (core dumped)
Reading package lists... Done
Building dependency tree
Reading state information... Done

Updating repository information

Third party sources disabled

Some third party entries in your sources.list were disabled. You can
re-enable them after the upgrade with the 'software-properties' tool
or your package manager.

To continue please press [ENTER]

Hit http://ie.archive.ubuntu.com/ubuntu cosmic InRelease
Fetched 0 B in 0s (0 B/s)

(appstreamcli:15614): GLib-CRITICAL **: 14:06:55.537: g_variant_builder_end: assertion '!GVSB(builder)->uniform_item_types || GVSB(builder)->prev_item_type != NULL || g_variant_type_is_definite (GVSB(builder)->type)' failed

(appstreamcli:15614): GLib-CRITICAL **: 14:06:55.538: g_variant_new_variant: assertion 'value != NULL' failed

(appstreamcli:15614): GLib-ERROR **: 14:06:55.538: g_variant_new_parsed: 11-13:invalid GVariant format string
Trace/breakpoint trap (core dumped)
Hit http://ie.archive.ubuntu.com/ubuntu cosmic InRelease
Fetched 0 B in 0s (0 B/s)

(appstreamcli:15829): GLib-CRITICAL **: 14:07:05.466: g_variant_builder_end: assertion '!GVSB(builder)->uniform_item_types || GVSB(builder)->prev_item_type != NULL || g_variant_type_is_definite (GVSB(builder)->type)' failed

(appstreamcli:15829): GLib-CRITICAL **: 14:07:05.466: g_variant_new_variant: assertion 'value != NULL' failed

(appstreamcli:15829): GLib-ERROR **: 14:07:05.466: g_variant_new_parsed: 11-13:invalid GVariant format string
Trace/breakpoint trap (core dumped)
Hit http://ie.archive.ubuntu.com/ubuntu cosmic InRelease
Fetched 0 B in 0s (0 B/s)

(appstreamcli:16059): GLib-CRITICAL **: 14:07:13.383: g_variant_builder_end: assertion '!GVSB(builder)->uniform_item_types || GVSB(builder)->prev_item_type != NULL || g_variant_type_is_definite (GVSB(builder)->type)' failed

(appstreamcli:16059): GLib-CRITICAL **: 14:07:13.383: g_variant_new_variant: assertion 'value != NULL' failed

(appstreamcli:16059): GLib-ERROR **: 14:07:13.383: g_variant_new_parsed: 11-13:invalid GVariant format string
Trace/breakpoint trap (core dumped)

Error during update

A problem occurred during the update. This is usually some sort of
network problem, please check your network connection and retry.

E:Problem executing scripts APT::Update::Post-Invoke-Success 'if
/usr/bin/test -w /var/cache/app-info -a -e /usr/bin/appstreamcli;
then appstreamcli refresh-cache > /dev/null; fi', E:Sub-process
returned an error code

Restoring original system state

Aborting
Reading package lists... Done
Building dependency tree
Reading state information... Done

Tried the update through the Distribution Upgrade popup which appeared onscreen. It also failed with the following message:
Error during update
A problem occurred during the update. This is usually some sort of network problem, please check your network connection and retry.
E:Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/cache/app-info -a -e /usr/bin/appstreamcli; then appstreamcli refresh-cache > /dev/null; fi', E:Sub-process returned an error code.
I'm just thinking - if a couple of people have mentioned my internet connection was running, which it was, or if I was using a proxy, which I'm not and the latest try at upgrade showed that there may be a connection issue, could the laptopwifi adapter be getting switched off as it tries to update?

A: I had the same error (on an acer notebook) when trying
    sudo do-release-upgrade

What then worked without errors was
    sudo su -
    apt dist-upgrade
    do-release-upgrade


text:
Q: Multiple inputs on a single mapper in hadoop I'm developing an algorithm that needs to run two sequential mapreduce jobs, where the second one takes in input the input and the output of the first one at the same time. I found four ways to do it and I want to know witch of these is the most efficient or if there are other methods.
Distributed Cache
Merging all the reducer output into a single file and loading it on Distributed Cache
FileSystem fs = FileSystem.get(confi);

    Path pt = new Path(output.toString() + "/out.txt");
    try{
        FileStatus[] status = fs.listStatus(output);
        BufferedWriter brOut=new BufferedWriter(new OutputStreamWriter(fs.create(pt,true)));

        for (int i=0;i<status.length;i++){

            BufferedReader brIn=new BufferedReader(new InputStreamReader(fs.open(status[i].getPath())));
            String line;
            line=brIn.readLine();

            while (line != null){
                brOut.write(line + "\n");
                line=brIn.readLine();
            }
        }
        brOut.close();

    }catch(Exception e){
        e.printStackTrace();
    }
    job.addCacheFile(pt.toUri());

Adding it as a resource to the configuration class
As before I merge the output saving it on a String and than:
Configuration conf = new Configuration();
conf.setStrings("input2ndjob", outputFromReducer);
Job job = Job.getInstance(conf,"Second Job");

Reading from hdfs
The second map reads the output files of first reducers directly from hdfs
Passing two values as input
I have found on this webpage this pseudocode where it seems that they are passing two arguments as input to the second mapper but I don't know how to do that.
map(key, value):
    // value is the candidate itemsets and a chunk of the full dataset
    Count occurrences of itemsets in the chunk.
    for itemset in itemsets:
        emit(itemset, supp(itemset))

reduce(key, values):
    result = 0
    for value in values:
        result += value
    if result >= s:
        emit(key, result)


text:
Q: Magento 2 : Disallow Specific Phone Number We would like to disallow some specific phone numbers, especially in the checkout.
For example the phone number: 0000000000 or 1111111111.
How can we disallow these phone numbers?


text:
Q: Controller return `false` while DashboardController return `true` I am running laravel 6.11
and by default we have this
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
        dd(Auth::check());
    }
}

and I have defined my controller like this,
class DashboardController extends Controller
{
    /**
     * Display dashboard
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        dd(Auth::check());
    }
}

Now the user successfully login,
and visiting same page, dashboard at different time
Controller return false while DashboardController return true
Why is that?

A: As of Laravel 5.3, you can't access the session (including Auth) in the controller constructor. You can, however, define a middleware closure in the constructor that will have access to the session.
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            dd(Auth::check());
        });
    }
}


text:
Q: how to delete directory from openshift data directory? I have some folders/directories inside $OPENSHIFT_DATA_DIR. Now, I want to remove that directories.
Which command I should use to delete the directories.
 Please help me. Thank you.

A: Google Linux commands
rm <folder or filename>


text:
Q: How to use more than one Constant Timer with different values in one Thread Group? I'm trying to run a test by the following scenario:

*

*500 users try to login to the server for 2,5 hours.

*After login they start to send 2 different types of requests to server and logout at the same time.

*After they logout process begins, they immediately start to login again.

This whole thing has the following parameters:

*

*1 login happens every 8,5 sec;

*1-st type of request happens every 15 sec;

*2-nd type of request happens every 10 sec;

*logout happens every 8,5 sec.

I've tried to use Throuput Controller, but it works for all Thread Group.
Also I've tried to use IF Controllers with Groovy timer, but Groovy timer doesn't work.
Expected result:

*

*1 login happens every 8,5 sec;

*1-st type of request happens every 15 sec;

*2-nd type of request happens every 10 sec;

*logout happens every 8,5 sec.

Actual result:

*

*first 2.5 hours the login is executed every 8,5 sec;

*when the requests phase begins, timers for logins and logouts don't work correctly;

*timers for 2 types of requests don't work correctly too.


text:
Q: Method some() doesn't work as expected in Angular 8 I have an Angular app and I want to add follow/unfollow functionality for users. I'm trying to add isFollowed flag, so I will be able to know if user is followed or no, and depending on that I will show 2 different buttons: Follow and Unfollow. I'm using some() method for this purposes but it doesn't work. It shows me that isFollowed flag is undefined although it should show true or false. I don't understand where the problem is, here is my HTML relevant part:
<button *ngIf="!isFollowing; else unfollowBtn" class="btn" id="btn-follow" (click)="follow(id)">Follow </button>
<ng-template #unfollowBtn><button class="btn" id="btn-follow" (click)="unFollow(id)">Unfollow</button></ng-template>

TS component relevant part:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";

import { AuthenticationService } from '@services/auth.service';
import { FollowersService } from '@services/followers.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
  user;
  id;
  followers;
  isFollowing: boolean;

  constructor(
    private authenticationService: AuthenticationService,
    private followersService: FollowersService,
    private router: Router,
    private route: ActivatedRoute,
  ) { }

  ngOnInit() {
    this.id = this.route.snapshot.paramMap.get("id");
    this.authenticationService.getSpecUser(this.id).subscribe(
      (info => {
        this.user = info;
      })
    );
    this.followersService.getFollowing().subscribe(
      data => {
        this.followers = data;
        this.isFollowing = this.followers.some(d => d.id == this.user.id);
      }
    );
  }

  follow(id) {
    console.log('follow btn');
    this.followersService.follow(id).subscribe(
      (data => console.log(data))
    )
    this.isFollowing = true;
  }

  unFollow(id) {
    console.log('unFollow btn');
    this.followersService.unFollow(id).subscribe(
      (data => console.log(data))
    )
    this.isFollowing = false;
  }
}

Any help would be appreciated.

A: If you want it called everytime and to make sure this.user is populated. Then you could use a forkJoin
forkJoin(
    this.authenticationService.getSpecUser(this.id),
    this.followersService.getFollowing()
  ).pipe(
    map(([info, data]) => {
      // forkJoin returns an array of values, here we map those values to the objects
      this.user = info;
      this.followers = data;
      this.isFollowing = this.followers.some(d => d.id == this.user.id);
    })
  );

Not tested this because I didn't have time. If you make a StackBlitz we could see it in action and try from there.
Hope this helps.


text:
Q: Correct multiprocessing to treat UDP in Python I am trying to implement a simple UDP client and server. Server should receive a message and return a transformed one.
My main technique for server is to listen UDP messages in a loop, then spawn multiprocessing.Process for each incoming message and send the reply within each Process instance:
class InputProcessor(Process):
    ...

    def run(self):
        output = self.process_input()
        self.sock.sendto(output, self.addr) # send a reply

if __name__ == "__main__":
    print "serving at %s:%s" % (UDP_IP, UDP_PORT)

    sock = socket.socket(socket.AF_INET,    # Internet
                         socket.SOCK_DGRAM) # UDP
    sock.bind((UDP_IP,UDP_PORT))

    while True:
        data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
        print "received message: %s from %s:%s" % (data, addr[0], addr[1])
        p = InputProcessor(sock, data, addr)
        p.start()

In test client, I do something like this:
def send_message(ip, port, data):
    sock = socket.socket(socket.AF_INET,    # Internet
                         socket.SOCK_DGRAM) # UDP
    print "sending: %s" % data
    sock.sendto(data, (ip, port))
    sock.close()

for i in xrange(SECONDS*REQUESTS_PER_SECOND):
    data = generate_data()
    p = multiprocessing.Process(target=send_message, args=(UDP_IP,
                                                           UDP_PORT,
                                                           data))
    p.start()
    time.sleep(1/REQUESTS_PER_SECOND)

The problem I am having with the code above is that when REQUESTS_PER_SECOND becomes higher than certain value (~50), it seems some client processes receive responses destinated to different processes, i.e. process #1 receives response for process #2, and vice versa.
Please criticize my code as much as possible, due to I am new to network programming and may miss something obvious. Maybe it's even worth and better for some reason to use Twisted, hovewer, I am highly interested in understanding the internals. Thanks.

A: As per previous answer, I think that the main reason is that there is a race condition at the UDP port for the clients. I do not see receiving at the client code, but presumably it is similar to the one in server part. What I think happens in concrete terms is that for values under 50 requests / second, the request - response roundtrip gets completed and the client exits. When more requests arrive, there may be multiple processes blocking to read the UDP socket, and then it is probably nondeterministic which client process receives the incoming message. If the network latency is going to be larger in the real setting, this limit will be hit sooner.

A: Thanks guys a lot! It seems I've found why my code failed before. I was using multiprocessing.Manager().dict()  within client to check if the results from server are correct. However, I didn't use any locks to wrap a set of write operations to that dict(), thus got a lot of errors though the output from server was correct.
Shortly, in client, I was doing incorrect checks for correct server responses.


text:
Q: arithmetic expression Math.random in java the purpose of this program is to let the user try to guess a number up to 20 randomly chosen by the computer. The user inputs their guess. The computer then tells the user if their guess is too high or too low. The user keeps inputting their guess until theu guess correctly. Then they are told how many guesses it took them. The problem is that I am not understanding whether the arithmetic expression in the program generates random numbers from 1 to 20 because when I am inputting numbers from 1 to 20, the pop-up says 'number is too big'.
package pkTopic6Exercise13;
import javax.swing.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Font;
public class Topic6Exercise13
{
private GuessingGame MyGuessingGame = new GuessingGame();
private Topic6Exercise13()
{//constructor
}
public static void main(String[] args)
{
    Topic6Exercise13 myTopic6Exercise13 = new Topic6Exercise13();
    myTopic6Exercise13.go();
}
private void go()
{
    T6Ex13GUIin myT6Ex13GUIin = new T6Ex13GUIin();
}
private class GuessingGame
{
    private int NumToGuess=0;
    private int Guess=0;
    private int NumGuesses=0;
    private GuessingGame()
    {//constructor
    }
    private void GenerateNum()
    {
        NumToGuess = 1+(int)(20*Math.random());
    }
    private String CheckNum()
    {
        NumGuesses = NumGuesses + 1;
        if (Guess > NumToGuess)
        {
            JOptionPane.showMessageDialog(null, Guess + " is too BIG!");
            return "NotGuessed";
        }
        else if (Guess < NumToGuess)
        {
            JOptionPane.showMessageDialog(null, Guess + " is too SMALL!");
            return "NotGuessed";
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Well done! " + Guess +" is correct, it took " + NumGuesses + " goes.");
            return "Guessed";
        }
    }
}
private class T6Ex13GUIin extends JFrame
{
    private JLabel lblGuess;
    private JTextField txfGuess;
    private JButton btnPickNumber;
    private JButton btnQuit;

    private T6Ex13GUIin()
    {//constructor
        Font fontDialog = new Font("Dialog", Font.BOLD,24);
        this.setSize(1000,500);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocation(100,0);
        this.setTitle("Guessing Game");
        this.setLayout(null);
        lblGuess = new JLabel("Type Guess:");
        lblGuess.setFont(fontDialog);
        lblGuess.setBounds(100,200,200,50);
        lblGuess.setVisible(false);
        this.add(lblGuess);
        txfGuess = new JTextField("");
        txfGuess.setBounds(300,200,100,50);
        txfGuess.setFont(fontDialog);
        txfGuess.setVisible(false);
        ReturnListener MyReturnListener = new ReturnListener();
        txfGuess.addKeyListener(MyReturnListener);
        this.add(txfGuess);
        ClickListener MyClickListener = new ClickListener();
        btnPickNumber = new JButton("Pick Number");
        btnPickNumber.setBounds(100,100,750,50);
        btnPickNumber.setFont(fontDialog);
        btnPickNumber.addActionListener(MyClickListener);
        this.add(btnPickNumber);
        btnQuit = new JButton("Quit");
        btnQuit.setBounds(750,300,100,50);
        btnQuit.setFont(fontDialog);
        btnQuit.addActionListener(MyClickListener);
        this.add(btnQuit);
        this.setVisible(true);
    }
    private class ClickListener implements ActionListener
    {
        private ClickListener()
        {//constructor
        }
        public void actionPerformed(ActionEvent e)
        {
            if (e.getSource() == btnPickNumber)
            {
                MyGuessingGame.GenerateNum();
                MyGuessingGame.NumGuesses=0;
                btnPickNumber.setVisible(false);
                lblGuess.setVisible(true);
                txfGuess.setVisible(true);
                txfGuess.setText("");
            }
            if (e.getSource() == btnQuit)
            {
                System.exit(0);
            }
        }
    }
    private class ReturnListener implements KeyListener
    {
        private ReturnListener()
        {//constructor
        }
        public void keyPressed(KeyEvent e)
        {
        }
        public void keyReleased(KeyEvent e)
        {
        }
        public void keyTyped(KeyEvent e)
        {
            if (e.getKeyChar() == '\n')
            {
                MyGuessingGame.Guess =
                Integer.parseInt(txfGuess.getText());
                if (MyGuessingGame.CheckNum().equals("Guessed"))
                {
                    lblGuess.setVisible(false);
                    txfGuess.setVisible(false);
                    btnPickNumber.setVisible(true);
                }
                else
                {
                    txfGuess.setText("");
                }
            }
        }
    }
}

}

A: Have you tried any testing?  Like, debugging and seeing what value is getting set for NumToGuess?  Or perhaps simply displaying the value being set?  Then if you know what the random number is, you can test out your logic.
Based on your core logic, I ran this simple code below and didn't experience any problems.
public static void main(String[] args) {
    int NumToGuess = 1+(int)(20*Math.random());
    int myGuess    = Integer.parseInt("10");
    System.out.println("Value is: " + NumToGuess);
    System.out.println("My Guess: " + myGuess);

    if (myGuess > NumToGuess) {
        System.out.println("Too Big");
    }
    else if (myGuess < NumToGuess) {
        System.out.println("Too Small");
    }

}

A: Math.rand() generates a random number between 0 and 1 exclusive. So by multiplying by 20 you get a value between 0 and 20 exclusive. By rounding down with the (int) cast it becomes between 0-19 inclusive and by adding one it becomes between 1-20 inclusive. So yes, your number is being generated correctly. However, you do add 1 again at the beginning of the checkNum() method so that could be a problem. Hope this helps.


text:
Q: What streams to choose and where to place them correctly for processing url-addresses, receiving these images data and displaying them in a tableview? The situation is simple and very common. But unfortunately, for a specific situation, the answer is impossible to find on the Internet.
Hi guys, please help!
There is a function that receives a model data and also URL data, processes and store this data to array [interviewDataResponse]:

private func getInterviewResults() {
    guard let url = URL(string: self.interviewURL) else {
        debugPrint("URL is nil!")
        return
    }
    URLSession.shared.dataTask(with: url) { (data, _, error) in
        if data != nil, error == nil {
            do {
                let result = try JSONDecoder().decode([InterviewModel].self, from: data!)
                self.interviewDataResponse = Array(result.reversed())
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            } catch let error {
                debugPrint(error)
            }
        }
    }.resume()
}

Further:
As you can see in the following code, the getInterviewResults() function receives a data and subsequently processes additional data in custom cell, in cellConfigure() method to get this data for an images. The data is then displayed in the tableView with call method cellConfigure(). The actual data comes in, but not all images are displayed in the tableview.
public func cellConfigure(interview: [InterviewModel], for indexPath: IndexPath) {

    dateLabel.text = String((interview[indexPath.row].date)!.dropLast(6))
    tagsLabel.text = (interview[indexPath.row].tags).joined(separator: " #")
    titleTextView.text = interview[indexPath.row].title

    let webAddressURL = WebAddressURL.url
    guard let url = URL(
        string: webAddressURL + (interview[indexPath.row].picture!)) else {
            return
    }
    DispatchQueue.global().async {
        if let data = try? Data(contentsOf: url) {
            DispatchQueue.main.async {
                self.photoImageView.image = UIImage(data: data)
            }

        }
    }
}

In this case, the data is processed, but not all pictures are displayed in the tables.

A: CODE IN CUSTOM CELL:
public func cellConfigure(interview: [InterviewModel], for indexPath: IndexPath) {

    dateLabel.text = String((interview[indexPath.row].date)!.dropLast(6))
    tagsLabel.text = (interview[indexPath.row].tags).joined(separator: " #")
    titleTextView.text = interview[indexPath.row].title

    let webAddressURL = WebAddressURL.url
    guard let url = URL(
        string: webAddressURL + (interview[indexPath.row].picture!)) else {
            return
    }
    DispatchQueue.global().async {
        if let data = try? Data(contentsOf: url) {
            DispatchQueue.main.async {
                self.photoImageView.image = UIImage(data: data)
            }

        }
    }
}

CODE IN CLASS:
private func getInterviewResults() {
    guard let url = URL(string: InterviewURL.url) else {
        debugPrint("URL is nil!")
        return
    }
    URLSession.shared.dataTask(with: url) { (data, _, error) in
        if data != nil, error == nil {
            do {
                let result = try JSONDecoder().decode([InterviewModel].self, from: data!)
                self.interviewDataResponse = Array(result.reversed())
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            } catch let error {
                debugPrint(error)
            }
        }
    }.resume()
}


text:
Q: How to view information about a newly loaded external Linux kernel module? I have a simple Hello World kernel module from http://www.tldp.org/LDP/lkmpg/2.6/html/x121.html
I added a few lines with MODULE_AUTHOR, and MODULE_DESCRIPTION
It builds successfully, I'm able to insert it with insmod into the current kernel, view logs with dmesg, check that the module exists with lsmod.
However, I want to be able to view the module's info with modinfo but it doesn't work.
I get modinfo: ERROR: Module hello not found.
I tried running depmod and depmod -A but they didn't make a difference.
Is there any way to make modinfo "reload" so that I can view info for newly added modules?

A: From the man page:

modinfo extracts information from the Linux Kernel modules given on the command line. If the module name is not a filename, then the /lib/modules/version directory is searched, as is also done by
         modprobe(8) when loading kernel modules.

So it looks like this command just uses the kernel module files to get this information, so you can either run:
modinfo hello.ko

or you could put your kernel module in the /lib/modules/version/ directory


text:
Q: Hibernate Unidirectional One-to-One annotation mapping How to use One-to-One mapping to do lazy load the Adress if studentId exist in Address table.

*

*Student is the Parent table

*Address the child table

*Not all student will have Address. If they do then based studentId from  address table do lazy Load.

I tried mapping but when try to ftch only student, i ended up with the below exception
org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.abcCompany.AddressVO. Expected: class java.lang.Integer, got class java.lang.String
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:134)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1070)
    at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:989)
    at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:716)
    at org.hibernate.type.EntityType.resolve(EntityType.java:502)
...

According to the Exception I can say, it is trying to map the Address with with addressId instead of studentId. So I tried this in Student Entity bean
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "student_id", referencedColumnName = "student_Id")
private AddressVO address;

PS: Is this is possible to have bidrectional mapping too to get the Student from address by StudentId of address table.


text:
Q: Running Unit-test with Maven Now I am learning Junit5 framework, and I found out there is an option to run my unit-test not only with IDE (I am using IntelijIdea), but with Maven surefire plugin. A lot of articles in the Ethernet advice me to use Maven plugin to run my test. Perhaps, I am not understand something, but whats the point? Actually, I can use my default IDE options to run it, am I wrong? Thanks a lot!

A: While inside IntelliJ, use that to run your unit tests. That's where you write your code, run the unit tests there too, while working on your code.
If you're just starting with this, that may be the only place where you ever run your unit tests. But in any kind of mature development project, particularly when collaborating on code, you want a way to build your project outside your editor or IDE. While an IDE is often tainted with personal preferences and such, a build (script) on the command-line is seen as more authoritative.
If you have a good build (script) on the command-line, you can also run it in a Continuous Integration environment ("build server"), and properly automate builds, testing, reporting and deployments.
In this age, do not make your own build script for Java projects. Maven is the gold standard.
At the bare minimum, Maven will offer you:

*

*Dependency management: you are likely to bring in (external) dependencies into your project. Relying on an IDE for dependency management is another source of inconsistencies. Maven does this in a predictable, reproducible way. Along with other properties about your project, this is managed in Maven's POM (file), which is pom.xml.

*A default build lifecycle: basic things you are likely to need in a build. In your case: dependency resolution, then compilation, then test execution. You can reconfigure in the POM (file) the plugins that are executed, but for your question the defaults should work fine.

This is some official documentation about dependency management, and this about the POM (file). But don't get overwhelmed by all the options. Instead, rather rely on Maven's sane defaults.
For example, if you are using IntelliJ, I recommend using it to create your first Maven project, since it will set up a few things in a working POM (file) without you having to immediately understand the format of the POM entirely. (Choose "New Project", select "Maven", skip over archetype selection, and so on.)
Important things to keep in mind here are the POM (file), in the root of the project, and Maven's Standard Directory Layout, most notably for your question src/main/java and src/test/java for your production code resp. test code.


text:
Q: Torch mnist simple I'm trying to run the torch tutorial for the mnist dataset and don't quite understand the error. Here is my code (pretty much just the tutorial with mnist and added padding to correct for 28!=32):
load data
mnist = require 'mnist'

trainset = mnist.traindataset()
testset = mnist.testdataset()

setmetatable(trainset,
    {__index = function(t, i)
                    return {t.data[i], t.label[i]}
                end}
);
trainset.data = trainset.data:double() -- convert the data from a ByteTensor to a DoubleTensor.

function trainset:size()
    return self.data:size(1)
end

normalisation
mean = {}
stdv  = {}
mean = trainset.data[{ {}, {}, {}}]:mean()
trainset.data[{ {}, {}, {}  }]:add(-mean)
stdv = trainset.data[{ {}, {}, {}  }]:std()
trainset.data[{ {}, {}, {}  }]:div(stdv)

define network
require 'nn'

net = nn.Sequential()
net:add(nn.SpatialConvolution(1, 6, 5, 5, 1, 1, 2, 2)) -- 1 input image channel, 6 output channels, 5x5 convolution kernel
net:add(nn.ReLU())                       -- non-linearity
net:add(nn.SpatialMaxPooling(2,2,2,2))     -- A max-pooling operation that looks at 2x2 windows and finds the max.
net:add(nn.SpatialConvolution(6, 16, 5, 5))
net:add(nn.ReLU())                       -- non-linearity
net:add(nn.SpatialMaxPooling(2,2,2,2))
net:add(nn.View(16*5*5))                    -- reshapes from a 3D tensor of 16x5x5 into 1D tensor of 16*5*5
net:add(nn.Linear(16*5*5, 120))             -- fully connected layer (matrix multiplication between input and weights)
net:add(nn.ReLU())                       -- non-linearity
net:add(nn.Linear(120, 84))
net:add(nn.ReLU())                       -- non-linearity
net:add(nn.Linear(84, 10))                   -- 10 is the number of outputs of the network (in this case, 10 digits)
net:add(nn.LogSoftMax())                     -- converts the output to a log-probability. Useful for classification problems

training
criterion = nn.ClassNLLCriterion()
trainer = nn.StochasticGradient(net, criterion)
trainer.learningRate = 0.001
trainer.maxIteration = 5 -- just do 5 epochs of training.
trainer:train(trainset)

and now i get the following error msg.
    # StochasticGradient: training .../torch/install/share/lua/5.1/nn/Container.lua:67:
    In 1 module of nn.Sequential:
   .../torch/install/share/lua/5.1/nn/THNN.lua:109: bad argument #2 to 'v' (3D or 4D (batch mode) tensor expected at .../torch/extra/nn/lib/THNN/generic/SpatialConvolutionMM.c:70)
    stack traceback:
        [C]: in function 'v'
        .../torch/install/share/lua/5.1/nn/THNN.lua:109: in function 'SpatialConvolutionMM_updateOutput'
        ...sm/torch/install/share/lua/5.1/nn/SpatialConvolution.lua:111: in function <...sm/torch/install/share/lua/5.1/nn/SpatialConvolution.lua:107>
        [C]: in function 'xpcall'
        .../torch/install/share/lua/5.1/nn/Container.lua:63: in function 'rethrowErrors'
        .../torch/install/share/lua/5.1/nn/Sequential.lua:44: in function 'forward'
        ...sm/torch/install/share/lua/5.1/nn/StochasticGradient.lua:35: in function 'train'
        [string "trainer:train(trainset)..."]:1: in main chunk
        [C]: in function 'xpcall'
        .../torch/install/share/lua/5.1/itorch/main.lua:209: in function <.../torch/install/share/lua/5.1/itorch/main.lua:173>
        .../torch/install/share/lua/5.1/lzmq/poller.lua:75: in function 'poll'
        ...rs/.../install/share/lua/5.1/lzmq/impl/loop.lua:307: in function 'poll'
        ...rs/.../install/share/lua/5.1/lzmq/impl/loop.lua:325: in function 'sleep_ex'
        ...rs/.../install/share/lua/5.1/lzmq/impl/loop.lua:370: in function 'start'
        /Users/.../install/share/lua/5.1/itorch/main.lua:381: in main chunk
        [C]: in function 'require'
        (command line):1: in main chunk
        [C]: at 0x0109becd10

    WARNING: If you see a stack trace below, it doesn't point to the place where this error occured. Please use only the one above.
    stack traceback:
        [C]: in function 'error'
        .../torch/install/share/lua/5.1/nn/Container.lua:67: in function 'rethrowErrors'
        v/torch/install/share/lua/5.1/nn/Sequential.lua:44: in function 'forward'
        ...sm/torch/install/share/lua/5.1/nn/StochasticGradient.lua:35: in function 'train'
        [string "trainer:train(trainset)..."]:1: in main chunk
        [C]: in function 'xpcall'
        .../torch/install/share/lua/5.1/itorch/main.lua:209: in function </Users/.../install/share/lua/5.1/itorch/main.lua:173>
        .../torch/install/share/lua/5.1/lzmq/poller.lua:75: in function 'poll'
        ...rs/.../install/share/lua/5.1/lzmq/impl/loop.lua:307: in function 'poll'
        ...rs/.../install/share/lua/5.1/lzmq/impl/loop.lua:325: in function 'sleep_ex'
        ...rs/.../install/share/lua/5.1/lzmq/impl/loop.lua:370: in function 'start'
        .../torch/install/share/lua/5.1/itorch/main.lua:381: in main chunk
        [C]: in function 'require'
        (command line):1: in main chunk
        [C]: at 0x0109becd10

I don't quite understand whats wrong, but I am also still not sure about the torch data structures.
Thanks for your help.

A: As stated by the error message, a 3D or 4D (batch mode) tensor is expected. Here the data provided by mnist is 28x28 (= 2D tensor).
You can add an extra dimension by changing:
t.data[i]

With:
t.data[i]:view(1, 28, 28)


text:
Q: sorting rows when exporting pandas csv file I have a CSV file that contains 700k rows and what I need to do is create an additional CSV that has taken the data I need and sorted it into order.
So for example my original csv file has data that looks a bit like this.
Name     Code   Date        Area
Peter     01    01/01/2016  Wales
Peter     02    01/02/2017  England
Peter     34    25/02/2018  Wales
Paul      65    01/12/2015  Scotland
Paul      12    02/12/2015  Scotland
Simon     12    23/08/2016  England
Simon     12    28/09/2016  Wales
Simon     12    27/10/2018  England

What I need to do is create a unique row for a person but list the codes based on when the code was made (oldest date first). I should point out that I sorted the dataset in Excel to list the dates in the correct order (oldest first) to see if that would help.
So the output I need should look like this:
Name   Codes
Peter  01,02,34
Paul   65,12
Simon  12,12,12

The codes are listed in order by oldest date.
I'm not interested in the Area as it has no relevance to final answer.
I have successfully managed to get the names and codes into the relevant columns but for some reason the codes are not listed by oldest date.
I have tried searching for this but can't seem to word it correctly to get a relevant result.
Does anyone know why the sequence does not export correctly?
The code I am using is:
df2 = df2.groupby ('Name')['Code'].apply(', '.join).reset_index()
df2
export_csv = df2.to_csv(r'Filelocation.csv', index = None, header = True)

Thanks

A: I guess the following might work:
df2.groupby('Name')['Code'].apply(lambda x: " " % ', '.join(x))

A: As I'm not aware of what df2 holds for you, so I created a dataframe and verified your code which gives me the correct sequence. Implement and let me know what doesn't work for you:
df = pd.DataFrame({'Name': ['Peter', 'Peter', 'Peter', 'Paul', 'Paul', 'Simon', 'Simon', 'Simon'],
                   'Code': ['01', '02', '34', '65', '12', '12', '12', '12']})
df

    Code    Name
0   01  Peter
1   02  Peter
2   34  Peter
3   65  Paul
4   12  Paul
5   12  Simon
6   12  Simon
7   12  Simon

dfn = df.groupby ('Name')['Code'].apply(', '.join).reset_index()
dfn

    Name    Code
0   Paul    65, 12
1   Peter   01, 02, 34
2   Simon   12, 12, 12

dfn.index = dfn.Name # Mapping index with column Name
dfn.drop(columns=['Name'], inplace=True) # Dropping column Name
dfn

        Code
Name
Paul    65, 12
Peter   01, 02, 34
Simon   12, 12, 12

dfn = dfn.loc[df.Name.unique()] # Bringing dataframe into your desired order
dfn

        Code
Name
Peter   01, 02, 34
Paul    65, 12
Simon   12, 12, 12

dfn.to_csv('sample.csv')

Is this what you need? If not, comment.

A: The problem is likely you didn't specify dayfirst=True when converting your series to datetime:
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)

You can then sort by Date and perform a groupby operation as normal:
res = df.sort_values('Date')\
        .groupby('Name')['Code']\
        .agg(lambda x: ','.join(map(str, x)))


text:
Q: Enforce tag policy for all services in aws I need a AWS IAM policy to enforce Tagging for all the services. (Not One By One).
Is that possible?
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyCreateSecretWithNoProjectTag",
      "Effect": "Deny",
      "Action": "secretsmanager:CreateSecret",
      "Resource": "*",
      "Condition": {
        "Null": {
          "aws:RequestTag/Project": "true"
        }
      }
    },
    {
      "Sid": "DenyRunInstanceWithNoProjectTag",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": [
        "arn:aws:ec2:*:*:instance/*",
        "arn:aws:ec2:*:*:volume/*"
      ],
      "Condition": {
        "Null": {
          "aws:RequestTag/Project": "true"
        }
      }
    },
    {
      "Sid": "DenyCreateSecretWithNoCostCenterTag",
      "Effect": "Deny",
      "Action": "secretsmanager:CreateSecret",
      "Resource": "*",
      "Condition": {
        "Null": {
          "aws:RequestTag/CostCenter": "true"
        }
      }
    },
    {
      "Sid": "DenyRunInstanceWithNoCostCenterTag",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": [
        "arn:aws:ec2:*:*:instance/*",
        "arn:aws:ec2:*:*:volume/*"
      ],
      "Condition": {
        "Null": {
          "aws:RequestTag/CostCenter": "true"
        }
      }
    }
  ]
}

This is from AWS Documentation. I need all aws services together.

A: There is no way to enforce tagging for all possible resources up front. I recommend reading AWS white paper:

*

*Tagging Best Practices - Amazon Web Services (AWS)
Even with AWS Organization and TagPolicies you can't fully enforce tags since:

Enforcement has no effect on resources that are created without tags.

Also with AWS Organization's TagPolicies only some resources are supported, not all resources available in AWS.
The white paper recommends using CloudFormation and Service Catalog to proactively tag resources.

A: If the account is part of an Organisation it can be enforced through tagging policies: https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html.
If not you can use the AWS config rule of required tags: https://docs.aws.amazon.com/config/latest/developerguide/required-tags.html


text:
Q: Subtraction in the Excel I would like to create an excel template for warehouse. In this template are integrated warehouse, sellings and invoices.
I already wrote a code that  transfers data to sellings every time I create an invoice and click a button. I would like to integrate in my code function that can do corrections in my warehouse i.e. when I fill an invoice I put items ID, description, amount and a price. After I click a button I want the items amount in the warehouse sheet to decreased by the same amount as in invoice.
The biggest issue for me was how to write a code that takes information from invoice sheet (ID and items amount), look for exact matches in the warehouse sheet and in the warehouse sheet column "I"(stock) decrease stock with the same amount.
sheet1 - name sheet "warehouse". ID in the column "C"; stock - column "I"; data starts from row "4"
sheet3 - name sheet "invoice". ID in the merged column "A""B"(column 1); amount that I sell in the merged column "S""T""U" (column 4); data starts from row 15 as you can see in the code below.
My code that transfers data to sellings (sheet2). I need to integrate function into this code without creating another button.
Sub Button4_Click()
Dim x As Long
Dim erow As Long

'Calculate starting rows
x = 15
With Worksheets("Sellings")
    erow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
End With

With Worksheets("Invoice")
    Do While .Cells(x, 1) <> ""

        'The next line copies values to Sheet2
        Worksheets("Sellings").Range("A" & erow & ":Z" & erow).Value = .Range("A" & x & ":Z" & x).Value
        'increment row counters
        x = x + 1
        erow = erow + 1
    Loop
End With
End Sub


text:
Q: Como usar o "import" adequadamente em uma aplicação node.js com typescript Boa tarde. Estou escrevendo uma API Rest usando node.js e typescript, porém estou tendo problemas em usar o import em algumas partes do programa.
por exemplo em minha server.ts eu tenho:
const connectDB = require("./config/db");

(Que funciona sem problemas.)
e eu queria muda-lá para:
import { connectDB } from "./config/db";

porém eu recebo o seguinte erro:

Could not find a declaration file for module './config/db'. 'd:/documentos/projetos/node/Contact_Keeper/config/db.js' implicitly has an 'any' type.ts(7016)

db.js:
const mongoose = require("mongoose");
const config = require("config");
const db = config.get("mongoURI");

const connectDB = async () => {

try{
    await mongoose.connect(db, {
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false,
        useUnifiedTopology: true
    });

    console.log("MongoDB Connected.")

}catch(err){
    console.log(err.message);
    //ends with a failure
    process.exit(1);
}
}

module.exports = connectDB;

Eu estou usando module.exports, então não entendo porque ele não reconhece como um modulo.

Agora, em uma outra parte do meu código, eu estou tendo outro problema com o import, na rota de user Eu estou tentando trazer uma model user do mongoose, Mas quando eu tento mudar de const user = require("../models/User"); para import { user }  from "../models/User"; eu recebo o seguinte erro:

Module '"../../Contact_Keeper/models/User"' has no exported member 'UserSchema'.ts(2305)

Porém eu tenho sim um exports ali, tanto que com require() funciona sem problemas.
Model User Mongoose
import mongoose, {Schema} from 'mongoose';

const UserSchema: Schema = new Schema({
    name:{
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true,
        unique: true
    },
    password:{
        type: String,
        required: true
    },
    date:{
        type: Date,
        default: Date.now
    }
});

module.exports = mongoose.model('user', UserSchema);


text:
Q: Django: How to get a static file's filepath in a development environment? Some background first.  I'm employing the following "trick" to prevent undesired browser caching of static files (CSS, JS, etc.):
<script src="{{ STATIC_URL }}js/utils.js?version=1302983029"></script>

When the version string changes on a subsequent page load, it makes the browser re-fetch the static file from the server.  (Google "css caching" for articles on this trick.)
I want the browser to get the latest version of a static file, but I also want to allow browser caching when the file hasn't changed.  In other words, I want the version string to change if and only if the static file has been updated.  I also would like to generate the version string automatically.
To do this, I'm using the last-modified time of the static file as the version string.  I'm making a custom template tag to do this:
<script src="{% versioned_static 'js/utils.js' %}"></script>

And here's how the template tag works:
import os.path
from django import template
from django.conf import settings

class VersionedStaticNode(template.Node):
    ...
    def render(self, context):
        # With the example above, self.path_string is "js/utils.js"
        static_file_path = os.path.join(settings.STATIC_ROOT, self.path_string)
        return '%s?version=%s' % (
            os.path.join(settings.STATIC_URL, self.path_string),
            int(os.path.getmtime(static_file_path))
            )

To get the static file's last-modified time, I need to know its filepath on the system.  I get this filepath by joining settings.STATIC_ROOT and the file's relative path from that static root.  This is all well and good for the production server, since all static files are collected at STATIC_ROOT.
However, on a development server (where the manage.py runserver command is being used), static files aren't collected at STATIC_ROOT.  So how do I get the filepath of a static file when running in development?
(To clarify my purpose: the caching situation I want to avoid is the browser using a mismatch of new HTML and old CSS/JS.  In production, this can greatly confuse users; in development, this can confuse me and other developers, and forces us to refresh pages/clear the browser cache frequently.)

A: If using django.contrib.staticfiles, here's an extract of the findstatic command (django/contrib/staticfiles/management/commands/findstatic.py) that should help. It uses the finders.find to locate the file.
    from django.contrib.staticfiles import finders

    result = finders.find(path, all=options['all'])

    path = smart_unicode(path)
    if result:
        if not isinstance(result, (list, tuple)):
            result = [result]
        output = u'\n  '.join(
            (smart_unicode(os.path.realpath(path)) for path in result))
        self.stdout.write(
            smart_str(u"Found '%s' here:\n  %s\n" % (path, output)))


text:
Q: combine array and lis of tuples please check this - multiply numpy row with all elements in list

utl = np.array(  [[  3.  ,134.49999389648437,  134.1, -0.02]])

all_ltp = [(0, 134.30000305175778), (1, 133.80000305175778), (2, 134.14999389648438), (3, 134.39999389648438), (4, 134.30000305175778),(5, 134.14999389648438), (6, 134.19999694824222)]

a = np.array([np.hstack(tpl) for tpl in it.product(upper_trend_line, all_ltp)])
a = np.array(list(it.product(upper_trend_line, all_ltp)), dtype=object).T
a = np.hstack((np.vstack(a[0]), np.vstack(a[1])))
print(a)

output is  -

[[  3.         134.4999939  134.1         -0.02         0.  134.30000305]
 [  3.         134.4999939  134.1         -0.02         1.  133.80000305]
 [  3.         134.4999939  134.1         -0.02         2.  134.1499939 ]
 [  3.         134.4999939  134.1         -0.02         3.  134.3999939 ]
 [  3.         134.4999939  134.1         -0.02         4.  134.30000305]
 [  3.         134.4999939  134.1         -0.02         5.  134.1499939 ]
 [  3.         134.4999939  134.1         -0.02         6.  134.19999695]]

what i want is take the 4th value from a and go to all_ltp take its next element and combine it to a  i.e
for kk in range(len(a)):
    if a[kk][4]+1 <len(all_ltp):
        print(a[kk], (all_ltp[int(a[kk][4]+1)]))

output is working but i want it without loop and list elements  inside the array-

[  3.    134.4999939  134.1         -0.02     0. 134.30000305] (1, 133.80000305175778)
[  3.    134.4999939  134.1         -0.02     1. 133.80000305] (2, 134.14999389648438)
[  3.    134.4999939 134.1        -0.02        2. 134.1499939] (3, 134.39999389648438)
[  3.    134.4999939 134.1        -0.02        3. 134.3999939] (4, 134.30000305175778)
[  3.    134.4999939  134.1         -0.02     4. 134.30000305] (5, 134.14999389648438)
[  3.    134.4999939 134.1        -0.02        5. 134.1499939] (6, 134.19999694824222)

expected - if possible without following the reference question answer of stacking it first

[  3.    134.4999939  134.1         -0.02     0. 134.30000305  1  133.80000305175778]
[  3.    134.4999939  134.1         -0.02     1. 133.80000305  2  134.14999389648438]
[  3.    134.4999939 134.1        -0.02        2. 134.1499939  3  134.39999389648438]
[  3.    134.4999939 134.1        -0.02        3. 134.3999939  4  134.30000305175778]
[  3.    134.4999939  134.1         -0.02     4. 134.30000305  5  134.14999389648438]
[  3.    134.4999939 134.1        -0.02        5. 134.1499939  6  134.19999694824222]

A: I suggest to fill each row of a with its previous content concatenated (+) with what you already identified as the correct elements to "stack" (all_ltp[int(a[kk][4]+1)])
for kk in range(len(a)):
    if a[kk][4]+1 <len(all_ltp):
        a[kk] = [i for i in a[kk]] + all_ltp[int(a[kk][4]+1)]
        print(a[kk], (all_ltp[int(a[kk][4]+1)]))


text:
Q: Qt resize child rectangles Working on a school project, but I'm completely stuck. I have to write a paint application, in which you can draw Rectangles & Ellipses, select them, group them, move and resize them. After that I have to start implementing several design patterns.
I have to following problem. I have an abstract class Figure which inherits QRect, then there are the classes Rectangle, Ellipse and Group which all inherit the Figure class.
I am able to resize a single figure (ellipse or shape), by clicking on the corner of a selected shape, but the problem is resizing a group which contains several other figures (group, rectangle or ellipse), they have to resize relatively to their parent figure:
Mouse move event
void MainWindow::OnPaintBoxMouseMove(PaintBox *sender, QMouseEvent *event) {
    //Mouse move event based on which tool is selected
    switch(tool){
        //When rectangle tool is selected, update rectangle size to mouse position
        //in command
        case rectangle: {
            tempCmd->update(event->pos());
            break;
        }
        //When ellipse tool is selected, update ellipse size to mouse position
        //in command
        case ellipse: {
            tempCmd->update(event->pos());
            break;
        }
        //When select tool is selected
        case select: {
            //If moving is selected, update shape in command
            if (moving){
                sRect->move(startPoint,event->pos());
                tempCmd->update(event->pos());
                startPoint = event->pos();
            }
            //If resizing is selected, update shape in command
            else if (resizing){
                sRect->resize(startPoint,event->pos());
                tempCmd->update(event->pos());
                startPoint = event->pos();
            }
            //Otherwise update size of selection rectangle
            else if (sRect != nullptr) {
                sRect->updateDimensions(event->pos());
            }
            break;
        }
    }
    paintBox->update();
}

Resize method in resize command
called 'update' here
void ResizeCmd::update(QPoint mousePosition) {
    switch (direction){
        case 1: {
            _figure->setTopLeft(_figure->topLeft()+mousePosition-startMousePosition);
            break;
        }
        case 2: {
            _figure->setTopRight(_figure->topRight()+mousePosition-startMousePosition);
            break;
        }
        case 3: {
            _figure->setBottomLeft(_figure->bottomLeft()+mousePosition-startMousePosition);
            break;
        }
        case 4: {
            _figure->setBottomRight(_figure->bottomRight()+mousePosition-startMousePosition);
            break;
        }
    }
    startMousePosition = mousePosition;
}

So the question is, how am I going to implement the resize method in the group class, which may contain other child groups as well?

A: I think you are looking for something like this Repo :
https://github.com/cl0ne/resizer-item
For doing your project you should use graphics libs of Qt like QGraphicsItem ,QGraphicsScene, and QGraphicsView
you shouldn't separate all your Items and write a resizer.
this repo is general for all QGraphicsItems which means that If you want Rectangle you should define one QGraphicsRectItem and add this resizer to it like this :
QGraphicsScene *scene = new QGraphicsScene(this);
    QGraphicsRectItem *item = new QGraphicsRectItem(QRectF(0, 0, 100, 100));
    item->setPos(10, 10);
    item->setFlag(QGraphicsItem::ItemIsMovable);
    item->setPen(QColor(102, 102, 102));
    item->setBrush(QColor(158, 204, 255));
    scene->addItem(item);

    GraphicsItemResizer *resizer = new GraphicsItemResizer(item);
    resizer->setBrush(QColor(64, 64, 64));
    resizer->setMinSize(QSizeF(30, 30));
    resizer->setTargetSize(item->boundingRect().size());
    resizer->setHandlersIgnoreTransformations(true);
    QObject::connect(
        resizer,
        &GraphicsItemResizer::targetRectChanged,
        [item](const QRectF & rect)
        {
            QPointF pos = item->pos();
            item->setPos(pos + rect.topLeft());
            QRectF old = item->rect();
            item->setRect(QRectF(old.topLeft(), rect.size()));
        }
    );

    ui->graphicsView->setScene(scene);


text:
Q: How store data on a special id and get this data from this id? I would say I'm a newbie in programming and I need to store some data on an Id.
And then get the right data to an Id.
How can I do this?

A: Have you heard about Map and its Implementation. It stores the value in (Key,Value) pair.
Read this.
You can use your id as a key and its value in Map. and retrieve it using id easily.

A: if you need to store data in ID in android u flallow [http://developer.android.com/guide/topics/manifest/meta-data-element.html]
then you get the result
(or)
Cheak this link : (Canvas, animated text rotation)

A: Use HashMap. it key value date structure and stores data on the basis of id


text:
Q: Gatsby Images in different folder to markdown I've got an issue trying to reference images that are not in my md folder with AllMarkdownRemark. I've tried and failed to find solutions, including:

*

*Using relative paths

*Using string syntax

*Trying to create an alternative source with the file-system plugin

In my src folder I have a md folder containing markdown files, and an images folder containing the images. The head of an md file looks like this:
---
path: "/blog/2018"
date: "2018-11-07"
title: "My first blog post - THIS IS A TEST!"
image: "../images/space2.jpg"
--

My graphql query on the blog page looks like this:
query {
  allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC}) {
    totalCount
    edges {
      node {
        id
        html
        frontmatter {
          title
          path
          date(formatString: "dddd, MMMM Do YYYY")
          image {
                childImageSharp {
                fluid(maxWidth: 1440) {
                ...GatsbyImageSharpFluid
                }
          }

       }
        }
      }
    }
  }

This is returning a string because the images folder can't be found by allmarkdownremark. But I have this in my gatsby-config, meaning it should work:
{
        resolve: `gatsby-source-filesystem`,
        options: {
            path: `${__dirname}/src/md/`,
            name: "markdown-pages"
        },
    },
    {
        resolve: `gatsby-source-filesystem`,
        options: {
            path: `${__dirname}/src/images/`,
            name: "images"
        },
    },

I'd really appreciate it if anyone could point me in the right direction.


text:
Q: Update controller scope from ng-includes / ng-repeats I have a basic question regarding angular scopes (which probably was answered before, but i cant find a solution):
In my app views are multiple ng-includes with other angular-elements which create sub-scopes, (e.g. ng-repeats) in them. I want to managed them all in one controller, but in the ng-include templates, I have to use $parent.variable_name, to access/change variables from the controller. Inside a ng-repeat inside a ng-include, I have to use $parent.$parent.variable_name to access/change it. That gets confusing realy fast, as its hard to tell, how deep you sub-scopes are.
Is there a better way to reference the controllers variables and functions inside the subviews?

A: Create a service/factory (service/factory are singleton).
angular.module('moduleName')
  .factory('factoryName', function() {
    return {
      variableName: 1
    };
  });

Then go in your controller (you can use it in all your other controllers) and use the factory.
angular.module('moduleName')
  .controller('controllerName', function($scope, factoryName) {
    $scope.data = factoryName;
  });

Then in your HTML you can simply bind it.
<div ng-controller="controllerName">
  {{ data.variableName }}
</div>

Didn't test it tho. but it should work :)


text:
Q: Implementation of a web-server I had like to implement my own web-server in pure Java
the web-server should support only static resources (i.e. html, js, css, pics, movies etc..)
Can you recommend a tutorial or an article on how to implement such a thing?
should I use few processes or a thread-pool or should I consider a loop-event oriented like NodeJS?
I know there are free web-servers that does exactly what I am looking for, but I had like to do it as an exersice to my self.

A: If you're doing this as an exercise, I'd recommend an event-driven model.
I don't think there's one tutorial on this topic because the knowledge required is so far-ranging - the HTTP protocol, file access, threading and concurrency, configuration-file management, socket communication, logging, error handling, MIME types...  Yeah, even just sharing static resources, it's still a biggie.
Read up, and good luck!

A: I think that this is what you want
http://java.sun.com/developer/technicalArticles/Networking/Webserver/

A: I recommend familiarizing yourself with the HTTP request format http://datatracker.ietf.org/doc/rfc2616/.  Implementing HTTP from scratch is no small feat, but it is certainly a good learning exercise.
Within Java itself for simplicity I recommend using a thread-per-request server - http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html - that using java.nio for serving files.  In a concurrent setting java.nio is preferable to java.io because it balances load better.  You will likely find benchmarks that suggest that java.io is faster, but that is for sequential single-threaded code.

A: You might find the ACME web server interesting as a starting point.  We use it for ad-hoc file transfers. When you have familarized yourself with it, you can see if you can discover its bottlenecks and then ponder on how to fix it :)
http://acme.com/java/software/Acme.Serve.Serve.html

A: I would suggest Apache MINA to do the job. It lets you specify Encoders/Decoders to deal with the HTT Protocol properly and calls a method when a request arrives etc. It handles thread management internally. I never start a networking project without it.


text:
Q: Migrate RCP project from 3.6 to 4.4 I am upgrading an RCP project to Eclipse 4 (4.4.2) from Eclipse Helios (3.6.1).
I had a problem with plug-in configuration. Here is the stack trace: http://pastebin.com/SHEY4iYq.
The stack trace told: Import-Package: javax.annotation; version="1.0.0". But i think i already had this library in plug-in dependency. http://prntscr.com/7taz9m
Any solution about this case? Or any suggestion would be appreciated. Thank you very much.

A: The Import-Package just says that you need this package. The error is telling you that the javax.annotation import cannot be found when you run the application.
You probably need to update your RCP build to include the javax.annotation plugin (and possibly other plugins). How you do this depends on the type of build you are using.


text:
Q: Ejecutar codigo PHP dentro de Javascript Me podrían ayudar co un problema:
Deseo ejecutar código PHP dentro de Javascript.

La salida html:

El error en la consola del navegador:

Uncaught SyntaxError: Unexpected identifier

A: Asi como lo tienes es un error de sintaxis.  Si quieres escribir algo puedes usar la consola asi:
<?php echo "console.log('hola como estan');"

O tambien un alert asi:
<?php echo "alert('hola como estan');"

A: Creo que hay un error de concepto a la hora de estructurar la tarea que quieres hacer.
Realmente no se ejecuta PHP dentro de Javascript, sino que Javascript hará uso de lo que PHP imprima dentro de sus etiquetas o funciones. Dado que PHP es lenguaje de servidor, se ejecutará antes que Javascript.
Básico para que se entienda, el orden en el que se ejecutan:
1º PHP (servidor)
2º HTML (navegador)
3º Javascript (navegador)
Entonces el flujo iría de la siguiente forma:
1.- ¿Qué resultado queremos conseguir?

2.- ¿Qué parte de ese resultado va a gestionar PHP?
hola como estan

3.- ¿Cómo imprime PHP este texto dentro de html?
<?php echo "hola como estan"; ?>

4.- ¿Cómo se pone todo en funcionamiento?

Ojo con la sintaxis, las comillas de Javascript hay que mantenerlas.

Un ejemplo sencillo:
<?php
// varios textos en un array
$txt = array(
    "Hola como estan",
    "Hola que tal va",
    "Hola ke ase XD",
);
// desordena el contenido del array
shuffle($txt);
?>

A: Puedes usar type (nota el uso de type="php" en el script que contiene código php). El ejemplo es muy inseguro porque usa eval sin filtro, así que cuidado.
(Básicamente es lo que usan bibliotecas como Babel):
<?php
if(isset($_POST['ev']) && $_POST['ev']=='1' && isset($_POST['que']) && !empty($_POST['que'])){
    eval($_POST['que']);
    exit;
}
?>
<!DOCTYPE html>

            <meta charset="UTF-8">
            <title>test</title>

A: Actualmente yo mando así
    $.post("<?php echo URL ?>/enviarRevisionDocumental",

o dime mas sobre tu inquietud con gusto te ayudo.

A: En el código del script tú lo habías puesto como:

Ahí el problema, al poner echo haces que el navegador quite las etiquetas php y pone solo el hola mundo. Lo que tienes que hacer tendrías que mezclar código php con js.
Por ejemplo:
Si quieres hacer que salga un console.log tienes que hacer lo
siguiente.


text:
Q: Running tcsh scripts on startup in bash env I have a user called foo which is using tcsh by default in /etc/passwd. I cannot change that default shell. Foo has a service called xyz running, for which all the startup scripts and .(dot) file containing ENV variables are in home dir of foo.
Now a startup script is also created to run that service and placed in /etc/init.d/xyz which is written in bash.
Now the issue is that the service is not starting on boot and I cannot run it from my default user on login too. It is only possible to run when I su into foo user and execute the script to start the service.
If I do like this
sudo su foo /home/foo/xyz it will show me errors like then: then/endif not found..
So what I want to run a tcsh program to run on boot from a init.d script which is in bash. At present I tried to do this
su - foo -c "source /home/foo/.env_vars && /home/foo/bin/xyz start" but this is not starting the service at the time of boot.
I am not sure how to make a tcsh script execute on boot time.

A: You can either:

*

*use tcsh -c $script to run the scripts with tcsh

*set the shebang (first line) in the script to #!/bin/tcsh and set it executable; you can then just start it with $script as the command.


text:
Q: Composer install package in front of vendor folder not inside as a third party I am developing a PHP package and I have added a testing version to packagist so now I can install my package simply like this composer require timino/timino dev-master the package is installed correctly However the package is installed inside the vendor folder like so
timino
└── vendor
    ├── composer
    └── timino
        └── timino
            ├── App
            │
            └── pub

So it is completely different to my desired structure and in this case i need to point the server root to a very long path furthermore i need to generate another composer autoload  inside . so if it is possible i want to let composer install the package outside vendor to look exactly the same as my local version of the project like so
   timino
    ├── App // business logic
    │
    ├── pub  // public root dir for servers (apache or nginx)
    │
    └── vendor // 3rd party

I have seen so far the get composer website documentation on how to install a package in a custom location but i cant seem to find a practical example to my issue.
How can i let composer do so ? thanks.

A: Run
$ composer create-project timino/timino foo-bar-baz "dev-master"

to create a new project based on timino/timino:dev-master in the directory foo-bar-baz.
For reference, see:

*

*https://getcomposer.org/doc/03-cli.md#create-project
Example
I ran
$ composer create-project timino/timino foo-bar-baz "dev-master"

which results in
Installing timino/timino (dev-master 3db1cda092af6bdf9bdb754c353f97d7e3121141)
  - Installing timino/timino (dev-master master): Cloning master from cache
Created project in foo-bar-baz
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Writing lock file
Generating autoload files
Do you want to remove the existing VCS (.git, .svn..) history? [Y,n]? Y

and then
$ tree -L 1 --dirsfirst foo-bar-baz

which results in
foo-bar-baz
├── App
├── pub
├── vendor
├── README.md
├── composer.json
└── composer.lock

3 directories, 3 files


text:
Q: partial derivatives in three variables for implicitly defined function
Assume that $F(x,y,z)=0$ defines $z$ implicitly as a function of $x$ and
  $y$. Show that

$\frac{\partial z}{\partial x} = - \frac{\frac{\partial F}{\partial x}}{\frac{\partial F}{\partial z}}$

and

$\frac{\partial z}{\partial y} = - \frac{\frac{\partial F}{\partial y}}{\frac{\partial F}{\partial z}}$

now for

$F(x,y,z(x,y))=0$
$\frac{d}{dx}F(x,y,z(y,x)) = \frac{\partial 0}{\partial x}$
$F_x\frac{\partial x}{\partial x} + F_z\frac{\partial z}{\partial x}=0$
$F_x+F_z\frac{\partial z}{\partial x}=0$
$\frac{\partial z}{\partial x}= - \frac{F_x}{F_z}$

and similarly for $\frac{\partial z}{\partial y}$
  so far so good - but how do I use these formulas to find $\frac{\partial z}{\partial x}$
  and $\frac{\partial z}{\partial y}$ for

$x^2-3yz^2+xyz-2=0$

can I say

$-\frac{F_x}{F_z}= -\frac{2x+yz}{xy-6yz}$

and

$-\frac{F_y}{F_z}= -\frac{xy-3z^2}{xy-6yz}$


text:
Q: how to set different environment variables of Deployment replicas in kubernetes I have 4 k8s pods by setting the replicas of Deployment to 4 now.
apiVersion: v1
kind: Deployment
metadata:
  ...
spec:
  ...
  replicas: 4
...

The POD will get items in a database and consume it, the items in database has a column class_name.
now I want one pod only get one class_name's item.
for example pod1 only get item which class_name equals class_name_1, and pod2 only get item which class_name equals class_name_2...
So I want to pass different class_name as environment variables to different Deployment PODs. Can I define it in the yaml file of Deployment?
Or is there any other way to achieve my goal?(like something other than Deployment in k8s)

A: I would not recommend this approach, but the closest thing to do what you want is using the stateful-set and use the pod name as the index.
When you deploy a stateful set, the pods will be named after their statefulset name, in the following sample:
apiVersion: v1
kind: Service
metadata:
  name: kuard
  labels:
    app: kuard
spec:
  type: NodePort
  ports:
  - port: 8080
    name: web
  selector:
    app: kuard
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: kuard
spec:
  serviceName: "kuard"
  replicas: 3
  selector:
    matchLabels:
      app: kuard
  template:
    metadata:
      labels:
        app: kuard
    spec:
      containers:
      - name: kuard
        image: gcr.io/kuar-demo/kuard-amd64:1
        ports:
        - containerPort: 8080
          name: web

The pods created by the statefulset will be named as:
kuard-0
kuard-1
kuard-2

This way you could either, name the stateful-set according to the classes, i.e: class-name and the pod created will be class-name-0 and you can replace the _ by -. Or just strip the name out to get the index at the end.
To get the name just read the environment variable HOSTNAME
This naming is consistent, so you can make sure you always have 0, 1, 2, 3 after the name. And if the 2 goes down, it will be recreated.
Like I said, I would not recommend this approach because you tie the infrastructure to your code, and also can't scale(if needed) because each service are unique and adding new instances would get new ids.
A better approach would be using one deployment for each class and pass the proper values as environment variables.

A: For distributed job processing Deployments are not very good, because they don't have any type of ordering or consistent pod hostnames. You'd better use StatefulSet for it, because they have consistent naming, like pod-0, pod-1, pod-2. You can rely on that hostname index.
For example, if your class_name_idx - is the index of class name in class names list, num_replicas - is the number of replicas in StatefulSet and pod_idx - is the index of pod in StatefulSet, then pod should run the job only if: class_name_idx % num_replicas == pod_idx.
Unfortunately number of StatefulSet replicas cannot be obtained within the pod dynamically using Downward API, so you can either hardcode it or use Kubernetes API to obtain it from cluster.

A: Neither Deployment nor anything else won't help to achieve your goal. Your goal is some kind of logic and it should be implemented via code in your application.
Since the Deployment is some instances of the same application the only thing that might be useful for you is: using multiple deployments, each for its own task. The first could get class_name_1 item, while other class_name_2, class_name_3 etc. But it is not a good idea


text:
Q: How can I check for string values in a Dictionary>() object? To keep it simple, I have the following Dictionary that I fill with an unknown amount of strings for every string key. I also have the following list of strings.
var dict = new Dictionary<string, List<string[]>>();
IList<string> headerList = new List<string>();

How can I check if a string from the list is a value in the dictionary?
My data looks like similar to this:
 Key           Value
 -----         ------------------
 Car           honda, volks, benz
 Truck         chevy, ford

I need to check if "honda", for example, is a contained int the dictionary values. I am thinking I need  to do something like the following to see if the values contain a list, which contain the string in question. Keep in mind I am fairly new to C#.
    foreach (string header in headerList)
    {
        // This is wrong, I don't know what to put in the if statement
        if (dict.ContainsValue(r => r.Contains(header)))
        {
            // do stuff
        }
    }

A: John Odom is correct, you need a List.
What I would suggest is that you use a HashSet<string> internally for the value of the Diictionary. E.g. Dictionary<string, HashSet<string>>
Then when it comes to querying it you can do something like this:
 headerList.Where(x => dict.Values.Any(d => d.Contains(x))).ToList()

Have a look at .NET Nested Loops vs Hash Lookups for a performance comparison

A: If you only want to know if the dictionary contains the car bran (e.g. "honda") you can use this query:
bool isInDict = dict.Values
                    .SelectMany(lst => lst)
                    .Any(car => car == "honda");

To return the key under which the value is stored you can use something like this:
string containingKey = dict.Keys
                           .Where(key => dict[key].Contains("honda"))
                           .FirstOrDefault();

And to get the whole list in which the value occurs run this:
List<string> containingList = dict.Values
                                  .Where(v => v.Contains("honda"))
                                  .FirstOrDefault();

In the first case all you do you flatten all the lists and check them all if any value is the searched car name. If true the value is in the dictionary.
Second one: get all the keys. Apply each key to the dictionary to get respective list and check the list if it contains the car name. Return the first key under which the car name has been found.
Third one - similar to the second one, but we run the search on the values. Check if the value (i.e. List) contains the car name. Return the first collection that does contain the name.