text:
Q: zmq make seems to be failing on ubuntu 22.04 LTS Build and install ZeroMQ
Previously zmq 4.3.2 was succesfully build on ubuntu 18.04.6 LTS but after upgrading ubuntu 22.04 LTS and zmq version to 4.3.4 installation seems to be failing.
Environment
libzmq version : v4.3.4
Ubuntu 22.04 LTS (Jammy )
GCC : 12.0.1
G++ : 12.0.1
Make : 4.3
Minimal test code / Steps to reproduce the issue

*

*Clone 4.3.4 source code

*cd zeromq

*./autogen.sh

*chmod +x configure

*./configure --prefix=/XXX/XXX --enable-shared --with-libsodium --disable-static --
disable-werror --without-docs make -j8

What's the actual result?
Making all in doc
make[1]: Entering directory '/mnt/zeromq/doc'
make[1]: Nothing to be done for 'all'.
make[1]: Leaving directory '/mnt/zeromq/doc'
make[1]: Entering directory '/mnt/zeromq'
  CXX      tools/curve_keygen.o
  CXX      src/libzmq_la-curve_client.lo
  CXX      src/libzmq_la-rep.lo
  CXX      src/libzmq_la-req.lo
  CXX      src/libzmq_la-router.lo
  CXX      src/libzmq_la-scatter.lo
  CXX      src/libzmq_la-select.lo
  CXX      src/libzmq_la-server.lo
  CXX      src/libzmq_la-session_base.lo
  CXX      src/libzmq_la-signaler.lo
  CXX      src/libzmq_la-socket_base.lo
  CXX      src/libzmq_la-socks.lo
  CXX      src/libzmq_la-socks_connecter.lo
  CXX      src/libzmq_la-stream.lo
In file included from /usr/include/string.h:535,
                 from src/err.hpp:39,
                 from src/msg.hpp:37,
                 from src/curve_client.cpp:35:
In function 'void* memcpy(void*, const void*, size_t)',
    inlined from 'static int zmq::curve_client_tools_t::produce_initiate(void*, size_t, uint64_t, const uint8_t*, const uint8_t*, const uint8_t*, const uint8_t*, const uint8_t*, const uint8_t*, const uint8_t*, const uint8_t*, size_t)' at src/curve_client_tools.hpp:186:16:
/usr/include/x86_64-linux-gnu/bits/string_fortified.h:29:33: error: 'void* __builtin_memcpy(void*, const void*, long unsigned int)' offset [0, 79] is out of the bounds [0, 0] [-Werror=array-bounds]
   29 |   return __builtin___memcpy_chk (__dest, __src, __len,
      |          ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
   30 |                                  __glibc_objsize0 (__dest));
      |                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1plus: all warnings being treated as errors
  CXX      src/libzmq_la-stream_connecter_base.lo
make[1]: *** [Makefile:5394: src/libzmq_la-curve_client.lo] Error 1
make[1]: *** Waiting for unfinished jobs....
make[1]: Leaving directory '/mnt/zeromq'
make: *** [Makefile:8216: all-recursive] Error 1
----------------------------------------
[ ERROR(2) ]

What's the expected result?
As steps mentioned in installation documents make shoud have been succesfull.


text:
Q: How to use Kinesis to broadcast records? I know that Kinesis typical use case is event streaming, however we'd like to use it to broadcast some information to have it in near real time in some apps besides making it available for further stream processing. KCL seems to be the only viable option to use Kinesis as stream API is too low level.
As far I understand to use KCL we'd have to generate random applicationId so all apps could receive all the data, but this means creating a new DynamoDB table each time an application starts. Of course we can perform clean up when application stops but when application doesn't stop gracefully there would be DynamoDB table hanging around.
Is there a way/pattern to use Kinesis streams in a broadcast fashion?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uploading PDF files from the front-end I am working on a Wordpress site that has a custom front-end form for submitting posts. I need to add a field in the form to allow users upload a single PDF file along with the post. How can I achieve this?

A: I have done a simple function for that, but i allow all types of media. So this could be a start:
function insert_attachment( $file_handler, $post_id, $settpdf='false' ) {

  // check to make sure its a successful upload
  if ( $_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK ) __return_false();

  require_once( ABSPATH . 'wp-admin' . '/includes/image.php' );
  require_once( ABSPATH . 'wp-admin' . '/includes/file.php' );
  require_once( ABSPATH . 'wp-admin' . '/includes/media.php' );

  $attach_id = media_handle_upload( $file_handler, $post_id );

  if ( $settpdf ) update_post_meta( $post_id,'_pdf_id', $attach_id );

  return $attach_id;
}

and then a input like: <input type="file" name="uploaded_pdf">
You can retrive the meta like this:
$pdf = get_post_meta($post->ID, '_pdf_id', true);
echo '<?php __('Download PDF','mytheme'); ?>';


text:
Q: Grabbing a list of nodes in a tree? How would you go about grabbing a list of nodes from a tree structure that meet a certain criteria using ocaml? Since everything's created anew, there's no saved data structure. Any type of function that tries to return a list could only return one element when it hits a node, not a list.

A: Here's a tree type:
type tree = Leaf of int | Node of int * tree * tree

Here's a function that returns all the even values from the nodes of a tree:
let evens t =
    let rec go sofar = function
    | Leaf k -> if k mod 2 = 0 then k :: sofar else sofar
    | Node (k, lt, rt) ->
         let sofar' = if k mod 2 = 0 then k :: sofar else sofar in
         let sofar'' = go sofar' lt in
         go sofar'' rt
    in
    go [] t


text:
Q: specifying git branch for remote I'm trying to update my webbynode pulling from github but I got the message below:

You asked to pull from the remote 'git@github.com:sigbackup/gsapp.git', but did not specify
  a branch. Because this is not the default configured remote for your current branch, you must specify a branch on the command line.

So I have checked out this forum for help and I found some comments regarding .git/config file but mine looks already fine (at least to me):
[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
[remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = git@github.com:sigbackup/gsapp.git
[branch "master"]
        remote = origin
        merge = refs/heads/master
[branch "origin"]
        remote = origin
        merge = refs/heads/master

Am I missing something?
Any ideas how I can solve it?
PS I also tried git pull origin git@github.com:sigbackup/gsapp.git and I got

fatal: Couldn't find remote ref git@github.com

A: It's strange that you have a branch called origin. origin is used to name a remote automatically created during git clone; you will get in troubles having to disambiguate origin-the-branch and origin-the-remote. Did you add the branch manually to the .git/config? What commands did you run? I suspect that you messed this up.

A: What local branch have you checked out?
What git status shows?
You are probably working on some other branch than the local master branch. If you want to fetch new commits from github and merge them to the local master branch, you have to:
git checkout master
git pull

If you want those commits in the branch, on which you are working, you need:
git pull origin master

You were close in your try from PS, but the last param should be branch name, not the repo url.

You can also just fetch new commits from github, and do not merge it into any local branch, with:
git fetch origin

Then review those changes with git diff, git log, etc, and merge later to the currently checked out branch with:
git merge origin/master


text:
Q: написание строки из массива double[] array Имеется массив дробных чисел.
{100.35, 200.46, 300.1, 400.89}
требуется написать метод, который преобразует массив в строку, который перечисляет все элементы массива через запятую. При этом необходимо, чтобы форматирование было с двумя знаками после запятой. Написал код следующего характера. Просьба сильно не смеяться, т.к. я только начал учить джаву.
StringBuffer stringBuffer = new StringBuffer("");
DecimalFormat df = new DecimalFormat("###.##");
if (array.length != 0) {
    for (int i = 0; i < array.length; i++) {
        stringBuffer.append(df.format(array[i]) + ",");
    }
    stringBuffer.deleteCharAt(stringBuffer.lastIndexOf(","));
}
return stringBuffer.toString();

но вот вместо "100.35, 200.46, 300.10, 400.89" - мне выдается строка: "100.35, 200.46, 300.1, 400.89".

A: public class Test {

    private final static DecimalFormat FORMATER = new DecimalFormat("#.00");

    public static void main(String[] args) {
        Double [] array = {100.35, 200.46, 300.1, 400.89};
        System.out.println(arrayToString(array));
    }

    private static String arrayToString(final Double[] array) {
        return Arrays.stream(array)
                .map(d -> FORMATER.format(d))
                .collect(Collectors.joining(", "));
    }
}

A: Используйте 0 (показывает начальные/конечные нули) вместо # (скрывает их) в форматной маске.
double d = 100.10;
String fMask = "###.##";
DecimalFormat df = new DecimalFormat(fMask);
System.out.println(d + "(" + fMask + "): " + df.format(d));
fMask = "###.00";
df = new DecimalFormat(fMask);
System.out.println(d + "(" + fMask + "): " + df.format(d));
d = 0.10;
System.out.println(d + "(" + fMask + "): " + df.format(d));
fMask = "##0.00";
df = new DecimalFormat(fMask);
System.out.println(d + "(" + fMask + "): " + df.format(d));


text:
Q: Fetching data from Google Calendar into Java I'm very new to coding and I want to create my very own project, but I'm not sure how to start.
I want to create a program that will:

*

*Grab the calendar event name from my Google calendar

*Take only the relevant parts I need

*Organize it into Excel

*Print me the resulting graph from the given data.
So, to begin, are there any resources I might look at first?
I did some searching, found this, but I don't quite understand what to do with that.
Thank you for reading!

A: Get an IDE like visual studio code or eclipse to code. I recommend Visual Studio Code.
Become familiar with Java in the IDE:
https://code.visualstudio.com/docs/java/java-tutorial#_create-the-program
Then follow those Google instructions.


text:
Q: Powers of matrices equality let $A$ be a $3$ by $3$ matrix with two eigenvalues $\lambda _1, \lambda _2$ such that $\lambda _1$ has algebraic multiplicity $2$ and $\lambda _2$ has multiplicity $1$.
I want to prove that $(A-\lambda _1I)^{n+2}=(\lambda _2-\lambda _1)^n(A-\lambda _1I)^2$.
As a hint I'm given
$$A-\lambda _2I=A-\lambda _1I-(\lambda _2-\lambda _1)I$$
$$(A-\lambda _1)^2(A-\lambda _2)=0$$
How can I use the above to prove that $$(A-\lambda _1I)^{n+2}=(\lambda _2-\lambda _1)^n(A-\lambda _1I)^2 \text{for all }n\in \mathbb N?$$
I have tried powering $A-\lambda _2I=A-\lambda _1I-(\lambda _2-\lambda _1)I$ but it didn't help at all.

A: Notice that $(A-\lambda_1I)$ and $(A-\lambda_2I)$ commute and use the binomial formula.
We have by the binomial formula
$$(\lambda_2-\lambda_1)^nI=((A-\lambda_1I)-(A-\lambda_2I))^{n}=\sum_{k=0}^{n}{n\choose k}(A-\lambda_1I)^{n-k}(-1)^k(A-\lambda_2I)^k\\=(A-\lambda_1I)^{n}+(-1)^{n-1}n(A-\lambda_1I)(A-\lambda_2I)^{n-1}+(-1)^n(A-\lambda_2I)^n$$
Now multiply this equality by $(A-\lambda_1I)^2$.

A: Try using induction on $n$, noting that $$(A - \lambda_1 I)^{n+1+2} = (A - \lambda_1 I)^{n+2}(A - \lambda_2 I + (\lambda_2 - \lambda_1) I)$$


text:
Q: Click a button on floating window using AppleScript I'm having issues getting an AppleScript to run for an app called AutoRate. The script below was originally made for version 1.5.5. I've already tried to mess with AppleScript to get it to run on 1.6, but because I've never really used AppleScript before I'm not getting anywhere. The picture shows 1.6 on top and 1.5.5 on the bottom. The 2nd photo shows the hierarchy for 1.6. Any help is appreciated.
tell application "AutoRate"
    activate
    -- Hide app
     tell application "System Events" to key code 4 using {command down}
    -- Press 'begin rating'
     tell button "Begin" of window 2 "main" to perform action
    -- Try to quit afterwards
     quit
end tell

A: I just tested this on version 1.6. This code is for clicking the button "Begin Rating"
tell application "AutoRate"
    activate
end tell
delay 2
tell application "System Events"
    click button "Begin Rating" of window "AutoRate" of application process "AutoRate"
end tell

And this code is for clicking the button "Revert Ratings"
tell application "AutoRate"
    activate
end tell
delay 2
tell application "System Events"
    click button "Revert Ratings" of window "AutoRate" of application process "AutoRate"
end tell


text:
Q: How to solve error: failed linking file resources The error says that:

C:\Users\user\AndroidStudioProjects\hamm\app\src\main\res\drawable\black_gradient.xml:4:
  error: '00000000' is incompatible with attribute endColor (attr)
  color.
  C:\Users\user\AndroidStudioProjects\hamm\app\src\main\res\layout\home_item.xml:8:
  error: '#e6e6e6' is incompatible with attribute srcCompat (attr)
  reference [weak]. error: failed linking file resources.

This is the black_gradient.xml file:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <gradient android:angle="90" android:startColor="#121212"
        android:endColor="00000000" />

</shape>

This is my home_item.xml:
    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="250dp">

    <ImageView
        android:id="@+id/card_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="#e6e6e6" />

    <Button
        android:background="@drawable/btn_news_style"
        android:id="@+id/btn_news"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        android:text="News And Highlight"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="102dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:srcCompat="@drawable/black_gradient"
        tools:layout_editor_absoluteX="175dp"
        tools:ignore="MissingConstraints" />

    <ImageView
        android:id="@+id/news_img"
        android:layout_width="48dp"
        android:layout_height="68dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/card_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginBottom="56dp"
        android:text="Title"
        android:textColor="#fff"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/news_img" />

</android.support.constraint.Constrain

A: it reads:

error: '00000000' is incompatible with attribute endColor (attr) color.

you need to use hexadecimal notation:
android:endColor="#000000"


text:
Q: Как вывести данные за квартал в зависимости от заданной даты? Допустим в а , мы, в зависимости от полученной даты, выводим данные и в b выводим количество количество этих данных по месяцам.
with a as
(
  select *
   from table_1 t1
    where trunc(t1, 'Q') = trunc(:add_data, 'Q')  -- Полученная дата
),
b as
(
  select table_id
  , (select count(*)
      from a
       where t2.table_id = a.table_id) january -- Разбивка по месяцам
  , (select count(*)
      from a
       where t2.table_id = a.table_id) february -- Разбивка по месяцам
  , (select count(*)
      from a
       where t2.table_id = a.table_id) march  -- Разбивка по месяцам
        ...
  from table_2 t2

Как в запросе можно вывести только месяцы, которые относяться к определённому кварталу в зависимости от искомой даты?
Например:
trunc(to_date('01.02.2021', 'dd.mm.yyyy'),'Q')

          1 кв

декабрь   январь   февраль

A: Судя по последней правке ТС, ожидается результат с транспонированием строк в столбцы.
Это можно достичь функцией PIVOT, но ввести только дату недостаточно, имена месяцев, соответствующие этой дате, должны быть сформированы заране до парсинга запроса SQL интерпретатором. Другими словами, на чистом SQL и одним запросом задачу решить нельзя.
Вот пример на PL/SQL. Часть с формированием имён столбцов (FOR...LOOP),  может быть аналогично аналогично реализована на любом языке в клиенте при формировании полного запроса.
var rc refcursor
declare
    qmon date := trunc (date'2021-02-01', 'q');
    cols varchar2 (96);
    mons varchar2 (16);
begin
    for i in 1..3 loop
        mons := rtrim (to_char (add_months (qmon, (i-1)), 'Month'));
        cols := cols||''''||mons||''' "'||mons||'",';
    end loop;
    cols := rtrim (cols, ',');
    open :rcdata for q'[
        select *
        from (
            select trim (to_char (dt, 'Month')) mon
            from t1 where :qmon=trunc (dt, 'q'))
        pivot (count (*) for mon in (]'||cols||'))' using qmon;
end;
/

Результат:
   January   February      March
---------- ---------- ----------
        31         28         31

A:
как в селекте можно вывести только месяцы, которые относяться к определённому кварталу в зависимости от искомой даты

Вот так, искоммая дата 2021-02-01, это первый квартал с 3 первыми месяцами года:
create table t1 (id, dt) as
    select rownum, date'2021-01-01'+rownum-1
    from dual connect by level<=365
/

with a as (
    select trunc (dt, 'mm') mm
    from t1
    where trunc (dt, 'Q') = trunc (date'2021-02-01', 'Q')
)
select count (*) total, to_char (mm, 'Month') mon
from a
group by mm
order by mm
/

Результат:
     TOTAL MON
---------- ------------------------------------
        31 March
        31 January
        28 February


text:
Q: jQuery - Getting an elements "left" position and then change it I am trying to manipulate a slider script with custom jquery. I need to grab and elements "left" css style position and then change it by adding 300px.
Here is my jquery:
var slCon = $('.slides-control');
var pos = slCon.css("left");
slCon.css({'left': pos + '300px'});

If I "alert(pos)" it does give me the inline left position of say -1000. But I need to be able to add 300px to that inline style to make it -700 when a button is clicked. I can't seem to get it to alter the inline style of the element after it grabs the initial value.
Please Help. I'm still learning jQuery.

A: Soo. I got it working cause the elements width matches the elements left position but the left is in a negative number. So I just grabbed the elements width and then set the left position with that using this:
var slCon = $('#slides-control');
var width = slCon.width();
slCon.css({'left': - width + 300 + 'px'});

Thanks for all the help taxicala

A: You should do as follows:
var slCon = $('.slides-control').first();
var pos = slCon.css("left");
slCon.css({'left': pos + 300});

Or better, change to id (remember to update the dom accordingly):
var slCon = $('#slides-control');
var pos = slCon.css("left");
slCon.css({'left': pos + 300});

A: Try this:
$('.slides-control').css('left','+=300px');


text:
Q: table of "mean of combined columns" and join with original table in R I have a file (tekoopl) with 300,000 rows and 16 columns. Column 2 is PRICE and column 13 is DISTRICT. (In the DISTRICT column there are different districts in London; for example 2000 rows with district Westend, 4000 rows with district London etc.. The rows are interchangeable).
Now I get stuck on the following questions:
a. Generate a table with the average PRICE per DISTRICT
b. Join this with the original table 'tekoopl). (So the final table is not aggregated but has the same number of rows as the original table)
c. Create a new column (PRICE-DISTRICTPRICE) with the difference between the PRICE and the DISTRICT average.
I only manage to calculate the average/mean PRICE of the column PRICE, but I need to have the average PRICE of all rows 'district a', all rows district b'and the number of rows of the new table (dfl07) must be equal to the number of rows in 'tekoopl'. Because after that, I have to join them. Which of course I cannot do.  :-( Can someone help me?
tekoopl <- read.csv("datafiles/ppd_london_15161718.csv",
                    stringsAsFactors = FALSE)
str(tekoopl)
dfl07 <- select(tekoopl, PRICE, DISTRICT) %>%
GEM = round(mean(tekoopl$PRICE, na.rm = TRUE))

(I am currently using the packages dplyr and tidyr)

A: To generate a seperate table for the average price per district:
dfl07 %>% dplyr::group_by(DISTRICT) %>% summarise(mean_price=mean(PRICE, na.rm=T))

If you want to have it in your original table (so a column with an average prize per district, which I think is what you want to achieve), then:
dfl07 %>% dplyr::group_by(DISTRICT) %>% mutate(mean_price=mean(PRICE, na.rm=T))

To create mean price per district and the difference between the price and mean price for district (for the reference tekpool data frame):
tekoopl %>% dplyr::group_by(DISTRICT) %>% mutate(mean_price=mean(PRICE, na.rm=T), price_diff=PRICE-mean_price)


text:
Q: SQL user not associated with a trusted connection I just set up a new server with SQL Server Express 2005, and I want to connect remotely.

*

*I set both Windows and SQL logins.

*I modified so both local and remote connections are allowed.

*I restarted the server.

*Windows firewall is not connected; I have an external firewall with a hole at port 1443.

*The user account is active and there is no password policy or forcing to change on next login (etc).

If I even try to connect using this username locally on the server using 'File | Connect to object explorer', I get the same message: that the user is not associated with a trusted connection.

A: Did you add the user as a SQL login?

A: Here is the Microsoft KB (http://support.microsoft.com/default.aspx?scid=kb;EN-US;914277)for connecting remotely using SQL Express 2005. I would say go through the exact steps as described just one more time to make sure nothing has been left out. Good luck and I hope it helps!


text:
Q: Why 400 Bad Request when creating TeamCity cloud profile? I'm trying to create a cloud profile to start an EC2 instance in TeamCity. But I get Failed to connect to Amazon EC2. null (Service: AmazonEC2; Status Code: 400; Error Code: 400 Bad Request; Request ID: null)  There is no any explanations about this. As you can see I have changed serverURL to https://google.com, but it produces the same error even when using the correct TeamCity server.

I checked outbound connections of the EC2 instance where TeamCity is deployed and it's fine. Also tried by changing the region.
Any thoughts?
Cheers!


text:
Q: How to get latin extended characters sort properly on Parse Latin extended characters do not sort properly on Parse.com (screenshot: https://www.dropbox.com/s/sc9uozrav9fsslo/Screen%20Shot%202014-07-04%20at%2012.22.54%20AM.png).
This is common behaviour for a database. With MySQL this problem is solved with Collation.
Anyone else had this problem?
Thanks

A: This is not currently possible.  You can try opening a Bug Report via the Bug Tool here:  https://parse.com/help


text:
Q: Issue Installing entity framework 7 I'm learning entity framework , but I'm having hard time to install it on my visual studio 2013. The guy on the video which I'm watching on he doesn't explain if I need extra components , he just says that they're gonna use SQLSERVER EXPRESS, so I downloaded SQLSERVER EXPRESS and when I try to perform the commands that he said to do in order to install entity I got issue, look at this :
Install-Package EntityFramework.MicrosoftSqlServer -Version 7.0.0-rc1-final -Pre
Attempting to resolve dependency 'EntityFramework.Relational (≥ 7.0.0-rc1-final)'.
Attempting to resolve dependency 'EntityFramework.Core (≥ 7.0.0-rc1-final)'.
Install-Package : 'EntityFramework.Core' already has a dependency defined for 'Ix-Async'.
At line:1 char:1
+ Install-Package EntityFramework.MicrosoftSqlServer -Version 7.0.0-rc1 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPac
   kageCommand
Does everyone have any idea how to solve it ?
Should I install a SQLSERVER EXPRESS plugin first then try to perform it ?


text:
Q: Python XML check next item Here is a little xml example:
<?xml version="1.0" encoding="UTF-8"?>
<list>
    <person id="1">
        <name>Smith</name>
        <city>New York</city>
    </person>
    <person id="2">
        <name>Pitt</name>
    </person>
    ...
    ...
</list>

Now I need all Persons with a name and city.
I tried:
#!/usr/bin/python
# coding: utf8

import xml.dom.minidom as dom

tree = dom.parse("test.xml")

for listItems in tree.firstChild.childNodes:
    for personItems in listItems.childNodes:
        if personItems.nodeName == "name" and personItems.nextSibling == "city":
            print personItems.firstChild.data.strip()

But the ouput is empty. Without the "and" condition I become all names. How can I check that the next tag after "name" is "city"?

A: use element tree check this element tree
import xml.etree.ElementTree as ET
tree = ET.parse('a.xml')
root = tree.getroot()

for person in root.findall('person'):
    name = person.find('name').text
    try:
        city = person.find('city').text
    except:
        continue
    print name, city

for id u can get it by id= person.get('id')
output:Smith New York

A: You can do this in minidom:
import xml.dom.minidom as minidom

def getChild(n,v):
    for child in n.childNodes:
        if child.localName==v:
            yield child

xmldoc = minidom.parse('test.xml')
person = getChild(xmldoc, 'list')
for p in person:
    for v in getChild(p,'person'):
        attr = v.getAttributeNode('id')
        if attr:
            print attr.nodeValue.strip()

This prints id of person nodes:
1
2

A: Using lxml, you can use xpath to get in one step what you need:
from lxml import etree

xmlstr = """
<list>
    <person id="1">
        <name>Smith</name>
        <city>New York</city>
    </person>
    <person id="2">
        <name>Pitt</name>
    </person>
</list>
"""

xml = etree.fromstring(xmlstr)

xp = "//person[city]"

for person in xml.xpath(xp):
    print etree.tostring(person)

lxml is external python package, but is so useful, that to me it is always worth to install.
xpath is searching for any (//) element person having (declared by content of []) subelement city.


text:
Q: how to associate child table values with parent table row and inserts child tables values corresponds to parent table row in php I have 2 nested tables. Parent table row contains child table. Both tables can add rows if needed by add button. parent table values insert in a product_size table in database and child table values inserts in a product_color table. Parent table contains sizes and child table contains color and quantity of items of that size. I want to insert child table values(color & quantity) across parent table row. Means parent first row child table values should insert across parent first row only and the child table values that is in the second row of parent table should insert across parent second row. Currently, my code takes all Child table values from all rows of the parent table and inserts in the database across the first row and then takes all Child table values from all rows of parent table again and inserts in the database across the second row of the parent table. Please Check my code and help me point out where is the problem in my code.
/PHP CODE/
if (isset($_POST['submit']))
{
    $con=mysqli_connect("localhost", "root", "");
    mysqli_select_db($con,"login");

    for ($i=0; $i<count($_POST['size']); $i++){

        $size = $_POST['size'][$i];

        $qry1="INSERT INTO product_size (product_size) VALUES ('$size')";

        $result1=mysqli_query($con,$qry1);
        $product_size_id = mysqli_insert_id($con);

        for ($j=0; $j<count($_POST['color']); $j++){

            $quantity = $_POST['dress_quantity'][$j];

            $color = $_POST['color'][$j];

            $qry2="INSERT INTO product_color (product_size_id, product_color, product_quantity) VALUES ('$product_size_id', '$color', '$quantity')";

            $result2=mysqli_query($con,$qry2);
            if($result2)
            {
                echo '<script>alert("Record Added Successfully!")</script>';
                echo '<script>window.location="try.php"</script>';
            }
            else
            {
                die("Error While Adding Stock! Please Try Again.");
            }
        }
    }
}

A: I tested on my local server.work's fine
    $con=mysqli_connect("localhost", "root", "");
    mysqli_select_db($con,"login");
  // $size1 = array("50", "60", "70");
  // $color1 =array("red", "blue", "green");
  // $quantity1 = array("10", "20", "30");
    for ($i=0; $i<count($_POST['size']); $i++){

        $size = $size1[$i];

        $qry1="INSERT INTO product_size (product_size) VALUES ('$size')";
        $result1=mysqli_query($con,$qry1);
        var_dump($result1);
        echo "<br>";

        $product_size_id = mysqli_insert_id($con);

        for ($j=0; $j<count($size); $j++){

            $quantity = $_POST['dress_quantity'][$i];

            $color = $_POST['color'][$i];

            $qry2="INSERT INTO product_color (product_size_id, product_color, product_quantity) VALUES ('$product_size_id', '$color', '$quantity')";

            $result2=mysqli_query($con,$qry2);
            if($result2)
            {
                echo '<script>alert("Record Added Successfully!")</script>';
             //   echo '<script>window.location="try.php"</script>';
            }
            else
            {
                die("Error While Adding Stock! Please Try Again.");
            }
        }
    }


text:
Q: What data type to use for the buffer of a custom stack-based allocator? I want to create my own game engine so I bought a few books one being Game Engine Architecture Second Edition by Jason Gregory and in it he suggests implementing a few custom allocators. One type of allocator the book talked about was a stack-based allocator, but I got confused when reading it. How do you store data in it? What data type do you use? For example, do you use a void*, void**, an array of char[]? The book says you're meant to allocate one big block of memory using malloc in the begining and free it in the end, and "allocate" memory by incrementing a pointer. If you could help explain this more that would be great because I can't seem to find a tutorial that doesn't use std::allocator. I also thought this might help others interested in a custom allocator so I posted the question here.
This is the header file example they give in the book:
class StackAllocator
{
 public:
    // Represents the current top of the stack.
    // You can only roll back to the marker not to arbitrary locations within the stack
    typedef U32 Marker;

    explicit StackAllocator(U32 stackSize_bytes);

    void* alloc(U32 size_bytes); // Allocates a new block of the given size from stack top
    Marker getMarker(); // Returns a Marker to the current stack top
    void freeToMarker(Marker marker); // Rolls the stack back to a previous marker
    void clear(); // Clears the entire stack(rolls the stack back to zero)

private:
    // ...
}

EDIT:
After a while I got this working but I don't know if I'm doing it right
Header File
typedef std::uint32_t U32;

struct Marker {
    size_t currentSize;
};

class StackAllocator
{
private:
    void* m_buffer; // Buffer of memory
    size_t m_currSize = 0;
    size_t m_maxSize;

public:
    void init(size_t stackSize_bytes); // allocates size of memory
    void shutDown();

    void* allocUnaligned(U32 size_bytes);

    Marker getMarker();
    void freeToMarker(Marker marker);

    void clear();
};

.cpp File
void StackAllocator::init(size_t stackSize_bytes) {
    this->m_buffer = malloc(stackSize_bytes);
    this->m_maxSize = stackSize_bytes;
}

void StackAllocator::shutDown() {
    this->clear();

    free(m_buffer);
    m_buffer = nullptr;
}

void* StackAllocator::allocUnaligned(U32 size_bytes) {
    assert(m_maxSize - m_currSize >= size_bytes);

    m_buffer = static_cast<char*>(m_buffer) + size_bytes;
    m_currSize += size_bytes;
    return m_buffer;
}

Marker StackAllocator::getMarker() {
    Marker marker;
    marker.currentSize = m_currSize;
    return marker;
}

void StackAllocator::freeToMarker(Marker marker) {
    U32 difference = m_currSize - marker.currentSize;
    m_currSize -= difference;
    m_buffer = static_cast<char*>(m_buffer) - difference;
}

void StackAllocator::clear() {
    m_buffer = static_cast<char*>(m_buffer) - m_currSize;
}

A: Okay for simplicity let's say you're tracking a collection of MyFunClass for your engine. It could be anything, and your linear allocator doesn't necessarily have to track objects of a homogenous type, but often that's how it's done. In general, when using custom allocators you're trying to "shape" your memory allocations to separate static data from dynamic, infrequently accessed vs. frequently accessed, with a view towards optimizing your working set and achieving locality of reference.
Given the code you provided, first, you'd allocate your memory pool. For simplicity, assume you want enough space to pool 1000 objects of type MyFunClass.
StackAllocator sa;
sa.Init( 1000 * sizeof(MyFunClass) );

Then each time you need to "allocate" a new block of memory for a FunClass, you might do it like this:
void* mem = sa.allocUnaligned( sizeof(MyFunClass) );

Of course, this doesn't actually allocate anything. All the allocation already happened in Step 1. It just marks some of your already-allocated memory as in-use.
It also doesn't construct a MyFunClass. Your allocator isn't strongly typed, so the memory it returns can be interpreted however you want: as a stream of bytes; as a backing representation of a C++ class object; etc.
Now, how would you use a buffer allocated in this fashion? One common way is with placement new:
auto myObj = new (mem) MyFunClass();

So now you're constructing your C++ object in the memory space you reserved with the call to allocUnaligned.
(Note that the allocUnaligned bit gives you some insight into why we don't usually write our own custom allocators: because they're hard as heck to get right! We haven't even mentioned alignment issues yet.)
For extra credit, take a look at scope stacks which take the linear allocator approach to the next level.


text:
Q: reCAPTCHA V2 not working with www.recaptcha.net According to developer FAQ I've tried to use "www.recaptcha.net" in circumstances when "www.google.com" is not accessible and it is not working as expected as internally still using some reCAPTCHA APIs from "www.google.com" only. Is there anything we can do here?
Thanks,
Ankit
Network calls for loading reCAPTCHA V2


text:
Q: Cufon Superfish hide dropdown text in IE8  I am using Cofunized text in my drop downs with superfish. But dropdown text is hidden in IE8. I try this fix but no luck instead it stopped working in every browser. The fix is: https://forum.jquery.com/topic/jquery-fix-superfish-cufon-in-ie8.
   <script type="text/javascript">
    Cufon.CSS.ready(function(){

        $("ul#nav_709109").supersubs({
            minWidth:    12,   // minimum width of sub-menus in em units
            maxWidth:    27,   // maximum width of sub-menus in em units
            extraWidth:  1     // extra width can ensure lines don't sometimes turn over
                               // due to slight rounding differences and font-family
        }).superfish({
            autoArrows:  true, // disable generation of arrow mark-up
            dropShadows: false // disable drop shadows
        });
    });
   Cufon.replace('#main-nav li a', {fontFamily:'GRMedium',hover: true});

   </script>

A: specify a height for your element might fix your problem. If not, could you provide us your code or an url or something so we can take a closer look?


text:
Q: Django: Problems related Many-to-many relationships code of models.py
from django.db import models

class a(models.Model):
    name=models.CharField(max_length=20)

class b(models.Model):
    roll=models.IntegerField()
    a=models.ManyToManyField(a)

Actually i'm learning Django.As i have defined a many-to-many relationship in b model with a model.I'm trying to do some experiment with these models so that i can get better understanding of many-to-many relationship.
doing some experiments with my models in Django shell.
In [1]: from payment.models import a,b

In [2]: x=a(name="test")

In [3]: x.save()

In [4]: y=b(roll=4)

In [5]: y.save()

In [6]: y.a.add(x)

In [13]: x=b.objects.filter(a__id=4)

In [14]: x[0].a
Out[14]: <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager at 0x6a833a60f0>

In [15]: x[0].a.name

In [16]:

When i run x[0].a.name in shell it does not return anything why?Do we cannot access name attribute like this.How to know which objects of a model are in relation with y object of b model.


text:
Q: How to retrieve a document in Firebase using just the id I have not been able to find a reference in the documentation on how to get a document reference when you know the id of it in firebase.
I am passing the id to a webpage to lookup a QR code. Rather than storing a secondary unique id for each qrcode document I am relying on the firebase unique id.
Here is the lookup I tried but which seems to fail.
firebase.firestore().collection('cues').doc(id).get().then(function (docsnapshot) {
        console.info('About: ' + docsnapshot.get('text'));
    });

A: I was able to get my original code to work with this modification to the query
firebase.firestore().collection('cues').doc(id).get().then((doc) => {

... and then just use doc.get("field") to get values form my document

A: you can access to data like this:
const { id } = docsnapshot
const data = docsnapshot.data()
const myDoc = { id, ...data }

myDoc.text
myDoc.anything...


text:
Q: GraalVM native-image jvm metrics When running a native-image of a Micronaut application retrieving Prometheus metrics fails because it cannot get jvm metrics.
Of course native-image pre-compiles the application and includes only what's actually being used, but what kind of JVM is used when running a native-image? I assume it's also a greatly reduced version of the standard hotspot vm.
So is it even possible to get jvm metrics when running a native image or should other means be used to retrieve cpu and memory stats of the running application?
In this case I used Micronaut but I recon it is common for getting metrics from any native-image application with prometheus metrics.
To reproduce:
- install Micronaut cli (e.g. via Homebrew on Mac)
- install GraalVM 19.2.0 (e.g. via Sdkman on Mac)
- install GraalVM native-image tool: gu install native-image
- create application: mn create-app --features=management,micrometer-prometheus,graal-native-image --build maven metrics-graalvm-image
- update src/main/resources/application.yml to allow anonymous access to prometheus endpoint:

endpoints:
  all:
    enabled: true
    sensitive: false

- run application: man exec:exec
- check prometheus metrics can be retrieved: open http://localhost:8080/prometheus
- build application: mvn clean verify
- create native image: native-image --no-server -jar target/metrics-graalvm-image-0.1.jar
- run native image: ./metrics-graalvm-image
- get prometheus metrics: open http://localhost:8080/prometheus

No with the native image, this exception is thrown:
11:06:51.186 [pool-2-thread-4] ERROR i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: ThreadMXBean methods
com.oracle.svm.core.jdk.UnsupportedFeatureError: ThreadMXBean methods
    at com.oracle.svm.core.util.VMError.unsupportedFeature(VMError.java:102)
    at com.oracle.svm.core.jdk.SubstrateThreadMXBean.getAllThreadIds(ManagementSupport.java:448)
    at io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics.getThreadStateCount(JvmThreadMetrics.java:85)
    at io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics.lambda$bindTo$0(JvmThreadMetrics.java:75)
    at io.micrometer.core.instrument.internal.DefaultGauge.value(DefaultGauge.java:40)
    at io.micrometer.prometheus.PrometheusMeterRegistry.lambda$newGauge$3(PrometheusMeterRegistry.java:245)
    at io.micrometer.prometheus.MicrometerCollector.collect(MicrometerCollector.java:69)
    at io.prometheus.client.CollectorRegistry$MetricFamilySamplesEnumeration.findNextElement(CollectorRegistry.java:183)
    at io.prometheus.client.CollectorRegistry$MetricFamilySamplesEnumeration.nextElement(CollectorRegistry.java:216)
    at io.prometheus.client.CollectorRegistry$MetricFamilySamplesEnumeration.nextElement(CollectorRegistry.java:137)
    at io.prometheus.client.exporter.common.TextFormat.write004(TextFormat.java:22)
    at io.micrometer.prometheus.PrometheusMeterRegistry.scrape(PrometheusMeterRegistry.java:95)
    at io.micrometer.prometheus.PrometheusMeterRegistry.scrape(PrometheusMeterRegistry.java:80)
    at io.micronaut.configuration.metrics.micrometer.prometheus.management.PrometheusEndpoint.scrape(PrometheusEndpoint.java:52)
    at io.micronaut.configuration.metrics.micrometer.prometheus.management.$PrometheusEndpointDefinition$$exec1.invokeInternal(Unknown Source)
    at io.micronaut.context.AbstractExecutableMethod.invoke(AbstractExecutableMethod.java:144)
    at io.micronaut.context.DefaultBeanContext$BeanExecutionHandle.invoke(DefaultBeanContext.java:2792)
    at io.micronaut.web.router.AbstractRouteMatch.execute(AbstractRouteMatch.java:235)
    at io.micronaut.web.router.RouteMatch.execute(RouteMatch.java:122)
    at io.micronaut.http.server.netty.RoutingInBoundHandler.lambda$buildResultEmitter$19(RoutingInBoundHandler.java:1408)
    at io.reactivex.internal.operators.flowable.FlowableCreate.subscribeActual(FlowableCreate.java:71)
    at io.reactivex.Flowable.subscribe(Flowable.java:14918)
    at io.reactivex.Flowable.subscribe(Flowable.java:14865)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
    at io.reactivex.Flowable.subscribe(Flowable.java:14918)
    at io.reactivex.internal.operators.flowable.FlowableMap.subscribeActual(FlowableMap.java:37)
    at io.reactivex.Flowable.subscribe(Flowable.java:14918)
    at io.reactivex.Flowable.subscribe(Flowable.java:14865)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
    at io.reactivex.Flowable.subscribe(Flowable.java:14918)
    at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty.subscribeActual(FlowableSwitchIfEmpty.java:32)
    at io.reactivex.Flowable.subscribe(Flowable.java:14918)
    at io.reactivex.Flowable.subscribe(Flowable.java:14865)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
    at io.reactivex.Flowable.subscribe(Flowable.java:14918)
    at io.reactivex.Flowable.subscribe(Flowable.java:14868)
    at io.micronaut.http.context.ServerRequestTracingPublisher.lambda$subscribe$0(ServerRequestTracingPublisher.java:52)
    at io.micronaut.http.context.ServerRequestContext.with(ServerRequestContext.java:52)
    at io.micronaut.http.context.ServerRequestTracingPublisher.subscribe(ServerRequestTracingPublisher.java:52)
    at io.micronaut.configuration.metrics.binder.web.WebMetricsPublisher.subscribe(WebMetricsPublisher.java:122)
    at io.reactivex.internal.operators.flowable.FlowableFromPublisher.subscribeActual(FlowableFromPublisher.java:29)
    at io.reactivex.Flowable.subscribe(Flowable.java:14918)
    at io.reactivex.Flowable.subscribe(Flowable.java:14865)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
    at io.reactivex.Flowable.subscribe(Flowable.java:14918)
    at io.reactivex.Flowable.subscribe(Flowable.java:14865)
    at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.run(FlowableSubscribeOn.java:82)
    at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker$BooleanRunnable.run(ExecutorScheduler.java:288)
    at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker.run(ExecutorScheduler.java:253)
    at io.micrometer.core.instrument.composite.CompositeTimer.record(CompositeTimer.java:79)
    at io.micrometer.core.instrument.Timer.lambda$wrap$0(Timer.java:144)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
    at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:460)
    at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:193)

A: The GraalVM native-image in the standalone executables uses SubstrateVM - a partial VM.
You can find more details about it on its official GitHub repo here.
Additionally according to the SubstrateVM limitations document, the standard management and debugging interfaces that Java offers are not supported. This is because they require access to Java bytecode, which is not longer available at runtime, in case of the native image.


text:
Q: How to access in map having a pair inside it I am using the map with pair inside it,
but not able to figure out how to access with iterator of map
my map declaration
  map<ll,pair<ll,ll> > val;
  map<ll,pair<ll,ll> > ::iterator it;

What i am using for accessing inserted values is
   cout<<it->first<<" " <<it->second->first<<" " <<it->second->second<<endl;

But the compiler is showing this error
error: base operand of '->' has non-pointer type 'std::pair<long long unsigned int, long long unsigned int>'|

A: Use . to access the elements of a pair.
cout<<it->first<<" " <<it->second.first<<" " <<it->second.second<<endl;

A: Use -> to access the element pointed to by a pointer and a . to access a member variable. In this case, map is a container and pair a struct so you have to access the elements of both with ..
cout << it->first << " " << it->second.first << " " << it->second.second << endl;

A: You can also return pair values together.
map<ll,pair<ll,ll> > val;

auto [pair_first_element,pair_second_element]=val[key_value];


text:
Q: Firebase HTTP cloud function .send() what does it return? I'm trying get a value from a firebase cloud function with my Android App.
The cloud function is the following:
 exports.checkIfNumberExists = functions.https.onRequest((request, response) => {
    var db = admin.database();
    var ref = db.ref("numbers");
    var query = ref.orderByKey();
    var exists = "false";
    query.once("value" ,function(snapshot){
            snapshot.forEach(function(childSnapshot){
                if(childSnapshot.key === request.query.number){
                    exists = "true";
                }
            });
            response.send(exists);
        });
 });

I don't understand what type of data does that .send() function return,
I asume it is plain text, but yesterday firefox got it as json when the exist value was boolean and not string.
Opening the url with firefox returns true or false, but when I try to make an http get request from Android or Javascript it denies access to it.
What is the return type of .send() function?


text:
Q: Can't store too lengthy int type Consider the problem:
It can be shown that for some powers of two in decimal format like:
2^9 = 512
2^89 = 618,970,019,642,690,137,449,562,112

The results end in a string consisting of 1s and 2s. In fact, it can be proven that for every integer R, there
exists a power of 2 such that 2K where K > 0 has a string of only 1s and 2s in its last R digits.
It can be shown clearly in the table below:
R Smallest K 2^K
1 1 2
2 9 512
3 89 ...112
4 89 ...2112

Using this technique, what then is the sum of all the smallest K values for 1 <= R <= 10?
    Proposed sol:
    Now this problem ain't that difficult to solve. You can simply do
    int temp = power(2, int)
and then if you can get the length of the temp then multiply it with
(100^len)-i or (10^len)-i

// where i would determine how many last digits you want.
Now this temp = power(2,int) gets much higher with increasing int that you can't even store it in the int type or even in long int....
So what would be done. And is there any other solution based on bit strings. I guess that might make this problem easy.
Thanks in advance.

A: No, I doubt there are any solutions based on "strings of bits". That would be quite inefficient. But there are Bignum Libraries like GMP which feature variable types either fixed-size much bigger than int types, or of arbitrary size limited only by memory capacity, plus matching sets of math operations, working similarly to software FPU emulation.
Quoting after reference with a minor paraphrase.
 #include <gmpxx.h>

 int
 main (void)
 {
   mpz_class a, b, c;

   a = 1234;
   b = "-5676739826856836954375492356569366529629568926519085610160816539856926459237598";
   c = a+b;
   cout << "sum is " << c << "\n";
   cout << "absolute value is " << abs(c) << "\n";

   return 0;
 }

Thanks to C++ operator overloading, it is much easier to use than ANSI C version.

A: Since you are only interested in the the n least significant digits of your result, you could try to devise an algorithm that only calculates those. Based on the standard algorithm for written multiplication you can see that the n least significant digits of the product are entirely determined by the n least significant digits of the multiplicands. Based on this it should be possible to create an algorithm that calculates as many digits of R^K as fit into a long int.
The only problem you might run into is that there may be numbers that end in a matching sequence that is longer that a long int can hold. In that case you can still resort to calculating additional digits using your own algorithm or a library.
Note that this is basically the same thing that big-number libraries do, only your approach might be more efficient, because you are calculating less digits that you are unlikely to need.

A: Try GMP, http://gmplib.org/
It can store a number with any size if it fits in the memory.
Altough you might be better off with less brute force approach.

A: You can store binary strings in std::bitset or in std::vector
www.cplusplus.com/reference/bitset/bitset/
I think bitset is your choice.
Using big arithmetic for operations on powers of 2 is not though


text:
Q: How to work with checkbox and how to insert the records which is checked Here in my oracle apex report i am having 2 apex_items ,checkbox and textfield..
I need to insert the records which is checked in report if I have selected 5 checkbox then it should insert all the 5 records, currently only one record is getting inserting, please help..
SQL in interactive report query:
select  APEX_ITEM.CHECKBOX(1,pdcq.CHEQUE_NUMBER)"SELECT",
pdc.CUST_NAME ,pdr.RECEIPT_NUMBER ,pdcq.INSTALLMENT,
pdcq.CHEQUE_NUMBER,pdcq.CHEQUE_AMOUNT, APEX_ITEM.TEXT(2,null) Remarks
from pdc_customer pdc,pdc_receipt pdr,pdc_cheques pdcq
where pdc.CUST_ID=pdr.CUST_ID and pdc.CUST_ID=pdcq.CUST_ID and pdcq.status='Pending'  AND pdcq.RECEIPT_NUMBER=pdr.receipt_number
 and pdcq.APPROVER=NVL(SYS_CONTEXT('APEX$SESSION','APP_USER'), USER)

Code
begin
select NVL(SYS_CONTEXT('APEX$SESSION','APP_USER'), USER) into v_user from dual;
FOR I in 1 ..APEX_APPLICATION.G_f01.COUNT
LOOP
   FOR J in 1 ..APEX_APPLICATION.G_f02.COUNT
   LOOP
       UPDATE PDC_STATUS_HISTORY SET STATUS='Approved',
          REMARKS=APEX_APPLICATION.G_F02(j),
          APPROVED_DATE=sysdate ,
          APPROVED_BY=v_user
          WHERE APPROVAL_LEVEL=1 and
          CHEQUE_NUMBER=APEX_APPLICATION.G_f01(i);
    END LOOP;
END LOOP;
end;

A: The issue you're probably running into is the following. The array for the checkbox only contains elements for the selected rows, whereas the array for the text element will contain an element for every row. So the index for the selected rows will not match the text row if not all checkboxes are checked. To work around that you can add a 3rd column of type APEX_ITEM.HIDDEN
select
  APEX_ITEM.CHECKBOX(1,pdcq.CHEQUE_NUMBER)"SELECT",
  pdc.CUST_NAME ,
  ...
  APEX_ITEM.TEXT(2,null) Remarks,
  APEX_ITEM.HIDDEN(3,pdcq.CHEQUE_NUMBER) hidden_checkno
 from pdc_customer pdc
      JOIN pdc_receipt pdr ON pdc.CUST_ID=pdr.CUST_ID
      ...

The process would then become:
BEGIN
  FOR I in 1 ..APEX_APPLICATION.G_f01.COUNT
  LOOP
   FOR J in 1 ..APEX_APPLICATION.G_f03.COUNT
   LOOP
     IF APEX_APPLICATION.G_F01(i) = APEX_APPLICATION.G_F03(j) THEN
       UPDATE PDC_STATUS_HISTORY
          SET STATUS='Approved',
              REMARKS=APEX_APPLICATION.G_F02(j),
              APPROVED_DATE=sysdate ,
              APPROVED_BY=NVL(SYS_CONTEXT('APEX$SESSION','APP_USER'), USER)
        WHERE APPROVAL_LEVEL = 1 AND
              CHEQUE_NUMBER = APEX_APPLICATION.G_f01(i);
      END IF;
    END LOOP;
  END LOOP;
END;

Note1: The SELECT FROM DUAL is not needed, you can use that expression in your update statement directly.
Note2: Use ANSI JOIN style syntax instead of the very very old oracle syntax.


text:
Q: Package pgfplots error could not read table file in figure Hello the following tikz picture works when by itself but when I put it into a figure like in the following code this error comes up:

Package pgfplots Error: ! Package pgfplots Error: Could not read table
  file '" x y z 10 -1 -1 10 1 -1 1 0 1 1 10 -1 1 10 -1 -1 "' in 'search
  path=.'

Code
\documentclass[test]{report}
\usepackage[T1]{fontenc}
\usepackage[latin9]{luainputenc}
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}

\makeatletter
\usepackage{bohr}
\usepackage{carbohydrates}
\usepackage{chemfig}
\usepackage{tikz}
 \usepackage{pgfplots}

\pgfplotsset{compat=1.12}

\@ifundefined{showcaptionsetup}{}{%
 \PassOptionsToPackage{caption=false}{subfig}}
\usepackage{subfig}
\makeatother

\usepackage{babel}
\begin{document}
\begin{figure}
\subfloat[]{\begin{tikzpicture}[
declare function={squarex(\t) =
    (\t < 0.25) ? 1 : (
        (\t < 0.5) ? (1 - (\t-0.25) * 8) : (
            (\t < 0.75) ? -1 : (-1 + (\t - 0.75) * 8)
    )
;},
declare function={squarey(\t) =
    (\t < 0.25) ? (-1 + \t*8) : (
        (\t < 0.5) ? 1 : (
            (\t < 0.75) ? (1 - (\t - 0.5) * 8) : -1
    )
;}
]
\begin{axis}[
axis equal image,
z buffer=sort,
hide axis,
domain=0:1, y domain = 0:10, samples y = 25,
ylabel =y, xlabel=x,     clip=false
]
\addplot3 [
z buffer=none, domain=0:330, samples y=1,
ultra thick, black, -latex] (
-0.5,
{sin(x)*1.5},     {cos(x)*1.5}
);
\addplot3 [surf, shader=flat, fill=black!10, draw=black] (
y,
{squarex(x) * cos(y*9) - squarey(x) * sin(y*9)},
{squarex(x) * sin(y*9) + squarey(x) * cos(y*9)}
);
\addplot3 [z buffer=auto, fill=black!30, draw=black] table {
x y z
10 -1 -1
10 1 -1
10 1 1
10 -1 1
10 -1 -1
};
\addplot3 [
z buffer=auto, domain=-60:270, samples y=1,
ultra thick, black, latex-] (
10.5,
{sin(x)*1.5},
{cos(x)*1.5} );
\draw [ultra thick,-latex] (3.5,0,2) -- (6.5,0,2);
\node[rotate=-12] (label) at (5,0,2.7) {wave motion};
\end{axis}
\end{tikzpicture}

}\hfill{}\subfloat[]{Other figure goes here

}

\caption{Torsional wave. a) a cuboid figure undergoing torsional         distortion
b) the bending and bucking in this bridge is caused by torsional waves}
\end{figure}

\end{document}

Edit: I did not make the tikz image, it has been adapted from Here

A: Oh wow, that's a really cool figure! I think you have mixed up the syntax for plotting table data, you used the one for files. To "repair" your code I create the file, alternatively you could adjust the syntax.
\documentclass[test]{report}
\usepackage[T1]{fontenc}
\usepackage[latin9]{luainputenc}
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}

\makeatletter
\usepackage{bohr}
\usepackage{carbohydrates}
\usepackage{chemfig}
\usepackage{tikz}
\usepackage{pgfplots}

\pgfplotsset{compat=1.12}

\@ifundefined{showcaptionsetup}{}{%
 \PassOptionsToPackage{caption=false}{subfig}}
\usepackage{subfig}
\makeatother

\usepackage{filecontents}
\begin{filecontents*}{mytable.dat}
x y z
10 -1 -1
10 1 -1
10 1 1
10 -1 1
10 -1 -1
\end{filecontents*}

\usepackage{babel}
\begin{document}
\begin{figure}
\subfloat[]{\begin{tikzpicture}[
declare function={squarex(\t) =
    (\t < 0.25) ? 1 : (
        (\t < 0.5) ? (1 - (\t-0.25) * 8) : (
            (\t < 0.75) ? -1 : (-1 + (\t - 0.75) * 8)
    )
;},
declare function={squarey(\t) =
    (\t < 0.25) ? (-1 + \t*8) : (
        (\t < 0.5) ? 1 : (
            (\t < 0.75) ? (1 - (\t - 0.5) * 8) : -1
    )
;}
]
\begin{axis}[
axis equal image,
z buffer=sort,
hide axis,
domain=0:1, y domain = 0:10, samples y = 25,
ylabel =y, xlabel=x,     clip=false
]
\addplot3 [
z buffer=none, domain=0:330, samples y=1,
ultra thick, black, -latex] (
-0.5,
{sin(x)*1.5},     {cos(x)*1.5}
);
\addplot3 [surf, shader=flat, fill=black!10, draw=black] (
y,
{squarex(x) * cos(y*9) - squarey(x) * sin(y*9)},
{squarex(x) * sin(y*9) + squarey(x) * cos(y*9)}
);
\addplot3 [z buffer=auto, fill=black!30, draw=black] table {mytable.dat};
\addplot3 [
z buffer=auto, domain=-60:270, samples y=1,
ultra thick, black, latex-] (
10.5,
{sin(x)*1.5},
{cos(x)*1.5} );
\draw [ultra thick,-latex] (3.5,0,2) -- (6.5,0,2);
\node[rotate=-12] (label) at (5,0,2.7) {wave motion};
\end{axis}
\end{tikzpicture}

}\hfill{}\subfloat[]{Other figure goes here.}

\caption{Torsional wave. a) a cuboid figure undergoing torsional         distortion
b) the bending and bucking in this bridge is caused by torsional waves}
\end{figure}

\end{document}

Torbjørn scooped me in adding the alternative, so his answer or the following code yields the same output.
\documentclass[test]{report}
\usepackage[T1]{fontenc}
\usepackage[latin9]{luainputenc}
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}

\makeatletter
\usepackage{bohr}
\usepackage{carbohydrates}
\usepackage{chemfig}
\usepackage{tikz}
 \usepackage{pgfplots}

\pgfplotsset{compat=1.12}

\@ifundefined{showcaptionsetup}{}{%
 \PassOptionsToPackage{caption=false}{subfig}}
\usepackage{subfig}
\makeatother

\usepackage{babel}
\begin{document}
\begin{figure}
\subfloat[]{\begin{tikzpicture}[
declare function={squarex(\t) =
    (\t < 0.25) ? 1 : (
        (\t < 0.5) ? (1 - (\t-0.25) * 8) : (
            (\t < 0.75) ? -1 : (-1 + (\t - 0.75) * 8)
    )
;},
declare function={squarey(\t) =
    (\t < 0.25) ? (-1 + \t*8) : (
        (\t < 0.5) ? 1 : (
            (\t < 0.75) ? (1 - (\t - 0.5) * 8) : -1
    )
;}
]
\begin{axis}[
axis equal image,
z buffer=sort,
hide axis,
domain=0:1, y domain = 0:10, samples y = 25,
ylabel =y, xlabel=x,     clip=false
]
\addplot3 [
z buffer=none, domain=0:330, samples y=1,
ultra thick, black, -latex] (
-0.5,
{sin(x)*1.5},     {cos(x)*1.5}
);
\addplot3 [surf, shader=flat, fill=black!10, draw=black] (
y,
{squarex(x) * cos(y*9) - squarey(x) * sin(y*9)},
{squarex(x) * sin(y*9) + squarey(x) * cos(y*9)}
);
\addplot3 [z buffer=auto, fill=black!30, draw=black] table[row sep=crcr] {
x y z \\
10 -1 -1\\
10 1 -1 \\
10 1 1 \\
10 -1 1 \\
10 -1 -1 \\
};
\addplot3 [
z buffer=auto, domain=-60:270, samples y=1,
ultra thick, black, latex-] (
10.5,
{sin(x)*1.5},
{cos(x)*1.5} );
\draw [ultra thick,-latex] (3.5,0,2) -- (6.5,0,2);
\node[rotate=-12] (label) at (5,0,2.7) {wave motion};
\end{axis}
\end{tikzpicture}

}\hfill{}\subfloat[]{Other figure goes here

}

\caption{Torsional wave. a) a cuboid figure undergoing torsional         distortion
b) the bending and bucking in this bridge is caused by torsional waves}
\end{figure}

\end{document}

A: With table[row sep=\\] and a \\ at the end of each line it works (at least for me).
\documentclass[test]{report}
\usepackage[T1]{fontenc}
\usepackage[latin9]{luainputenc}
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}

\makeatletter
\usepackage{bohr}
\usepackage{carbohydrates}
\usepackage{chemfig}
\usepackage{tikz}
 \usepackage{pgfplots}

\pgfplotsset{compat=1.12}

\@ifundefined{showcaptionsetup}{}{%
 \PassOptionsToPackage{caption=false}{subfig}}
\usepackage{subfig}
\makeatother

\usepackage{babel}
\begin{document}
\begin{figure}
\subfloat[]{\begin{tikzpicture}[
declare function={squarex(\t) =
    (\t < 0.25) ? 1 : (
        (\t < 0.5) ? (1 - (\t-0.25) * 8) : (
            (\t < 0.75) ? -1 : (-1 + (\t - 0.75) * 8)
    )
;},
declare function={squarey(\t) =
    (\t < 0.25) ? (-1 + \t*8) : (
        (\t < 0.5) ? 1 : (
            (\t < 0.75) ? (1 - (\t - 0.5) * 8) : -1
    )
;}
]
\begin{axis}[
axis equal image,
z buffer=sort,
hide axis,
domain=0:1, y domain = 0:10, samples y = 25,
ylabel =y, xlabel=x,     clip=false
]
\addplot3 [
z buffer=none, domain=0:330, samples y=1,
ultra thick, black, -latex] (
-0.5,
{sin(x)*1.5},     {cos(x)*1.5}
);
\addplot3 [surf, shader=flat, fill=black!10, draw=black] (
y,
{squarex(x) * cos(y*9) - squarey(x) * sin(y*9)},
{squarex(x) * sin(y*9) + squarey(x) * cos(y*9)}
);
\addplot3 [z buffer=auto, fill=black!30, draw=black] table[row sep=\\] {%
x y z \\
10 -1 -1\\
10 1 -1 \\
10 1 1 \\
10 -1 1 \\
10 -1 -1 \\
};
\addplot3 [
z buffer=auto, domain=-60:270, samples y=1,
ultra thick, black, latex-] (
10.5,
{sin(x)*1.5},
{cos(x)*1.5} );
\draw [ultra thick,-latex] (3.5,0,2) -- (6.5,0,2);
\node[rotate=-12] (label) at (5,0,2.7) {wave motion};
\end{axis}
\end{tikzpicture}

}\hfill{}\subfloat[]{Other figure goes here

}

\caption{Torsional wave. a) a cuboid figure undergoing torsional         distortion
b) the bending and bucking in this bridge is caused by torsional waves}
\end{figure}

\end{document}


text:
Q: Cross reference table laravel 5 Lets say there are three tables:
categories
id

image_categories
image_id
category_id

images
id

My idea was that an image has multiple categories so I made a cross reference table to attach a category to an image. In my cross table (image_categories) i create a reference with image_id to the image table and category_id to the category table
Now I need to find all images that belong to a category so in my class Category I add.
public function images(){
    return $this->hasManyThrough('App\Image', 'App\ImageCategory');
}

But I get an error that the column is not found.
 Unknown column 'image_categories.id' in 'on clause' (SQL: select `images`.*,
`image_categories`.`subcategory_id` from `images` inner join `image_categories`
on `image_categories`.`id` = `images`.`image_category_id` where
`image_categories`.`subcategory_id` = 29)

if I look at the docs it says:

Has Many Through
The "has many through" relation provides a convenient short-cut for
accessing distant relations via an intermediate relation. For example,
a Country model might have many Post through a User model. The tables
for this relationship would look like this:

It sounds ideal for situations like this but what am I doing wrong?

A: If the category has multiple images and image has multiple categories, here you have a many to many relationship, the name of your pivot table will be category_image (Eloquent will join the two related model names in alphabetical order) and it should contain a both ids of the two tables as foreign key (you can add more argument to the table if you need it).
So just follow instruction in laravel docummentation Many To Many and it will work smoothly.
Note : If you Need to find all images that belong to a category so in your class Category define the images() function like bellow :
public function images(){
     return $this->hasMany('App\Image');
}


text:
Q: D3 grouping bars I'm trying to figure out a way to group 2 bars and then leave some spacing between them. Is there a way to do this in D3? The example I'm following is this http://codepen.io/mbostock/pen/Jaemg.
var data = [4, 8, 15, 16, 23, 42];

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, 420]);

d3.select(".chart")
  .selectAll("div")
    .data(data)
  .enter().append("div")
    .style("width", function(d) { return x(d) + "px"; })
    .text(function(d) { return d; });

Many thanks in advance.

A: Here's the result: https://jsfiddle.net/umeqw2f8/3/
I've changed your style function a bit to achieve this:
.style("width", function(d,i) {
  if(i % 2 == 0 && i != 0){
    d3.select(this).style("margin-top", 5+"px")
  }else if(i == 0){}

  return x(d) + "px"; })

You can change the modulo factor for different sizes of grouping. For example for group of number 3: if(i % 3 == 0 && i != 0){

A: The Idea is to group the bars in DIV and seperate the group div's with some margin or padding.
var data = [4, 8, 15, 16, 23, 42];

var gData=[];
for(var i=0;i<data.length/2;i++){
  gData[i]={
    "before":data[i*2],
    "after":data[i*2+1]
  };
}
console.log(gData);
var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, 420]);

myBarsEnter=d3.select(".chart")
  .selectAll("div.bars")
    .data(gData).enter().append('div').attr('class','bargroup');
  myBarsEnter.append('div')
            .style("width", function(d) { return x(d.before) + "px"; })
            .text(function(d) { return d.before; });
myBarsEnter.append('div')
            .style("width", function(d) { return x(d.after) + "px"; })
            .text(function(d) { return d.after; });

And updated CSS is
.chart .bargroup{
margin-bottom:10px;
}
.chart .bargroup div {
  font: 10px sans-serif;
  background-color: steelblue;
  text-align: right;
  padding: 3px;
  margin: 1px;
  color: white;
}

You can find Updated code on below link.
http://codepen.io/anon/pen/YqJpzK


text:
Q: Akoya Touchpad not working I have Medion Akoya E7226 notebook, with an synaptics touchpad and Kunbuntu installed.
But whatever I try, the touchpad can not be installed because according to the operating system no touchpad is present.
There is no option in the BIOS to switch it on and off.
Anyone have an idea?
cheers

A: Getting Touchpad work on Akoya E7226
I've installed such a notebook and had the same problem. The reason is that this notebook uses a 8042 chip for touchpad communication, which is not supported by the kernel per default.
You have to modify your Grub file

*

*Make a backup of your grub file:
 sudo cp /etc/default/grub /etc/default/grub.backup

*Edit your grub file:
 sudo nano /etc/default/grub

*Now add the following paramters into the line starting with GRUB_CMDLINE_LINUX_DEFAULT:
  i8042.reset i8042.nomux=1 i8042.nopnp i8042.noloop"

In my case this line looks like
 GRUB_CMDLINE_LINUX_DEFAULT="quiet splash logo.nologo i8042.reset i8042.nomux=1 i8042.nopnp i8042.noloop"

Save the changes.

*Now you have to update your grub via
  sudo update-grub

*Reboot your machine


text:
Q: ES6 syntax : what is this an error : .catch(err => throw err); The following code works FINE:
 pool.getConnection()
    .then((conn)=>{
         // something here
       })
      .catch((err) => {
      throw err;
    });

However node throws error when I reformat it as such:
return pool.getConnection()
    .then((conn) => {
     //something here
    })
    .then(results => results[0].insertId)
    .catch(err => throw err);  <-- NODE COMPALINS HERE

$>somefile.js line(190)
.catch(err => throw err);
                  ^^^^^
SyntaxError: Unexpected token throw

What am I missing here ?

A: An arrow function has a behavior where, if you don't put {} after it, it has an implicit return.
So your code is essentially this:
.catch(err => { return throw err; });

You can only return expressions, and cannot return statements like throw.

function test(e) {
  return throw e; // syntax error
}


text:
Q: Wrong code coverage covered by istanbul I have configured tool karma-coverage to measure my code coverage. Hovewer I have noticed that in some cases it does not recognize whether my code was called during testing or not. Here is the sample which I have used in my tests:
This test was not detected by Istanbul correctly:
it('should throw an error if credentials.username is not defined', function() {
   expect(function(){
       currentAuthProvider.authenticate({
           password: '123456'
       }).toThrowError('Parameter credentials.username should be defined.')
   });
});

I have changed the test to this form, which was captured correctly:
it('should throw an error if credentials.username is not defined', function() {
   try{
      currentAuthProvider.authenticate({
         password: '123456'
      })
   } catch(e){
         expect(e.message).toEqual('Parameter credentials.username should be defined.');
   }
});

I would like to write my tests in form as the 1st test is. In 1st case the code coverage was showing that currentAuhProvider.authenticate function was not covered by unit tests, but in 2nd case the correct result was shown in code coverage result. Is there any other way how to influence Istanbul to detect the first test and compute it into code coverage as well?


text:
Q: Create colorbox gallery popup from different div click? This is the JS code that I've been tweaking to try and get the colorbox gallery to popup on click of the $('#sv') element:
$('#sv').click(function(event) {
    event.preventDefault();

    $('.svItem').colorbox({
        width: '80%',
        rel: 'gallery',
        href: function () {
            return $(this).data('href');
        },
        title: function () {
            return $(this).text();
        }
    });
});

and here's what the generated HTML looks like that I need to query:

            Le saviez-vous?

A: Got it working by adding "open: true" with:
$('#sv').on('click', function(event) {
    event.preventDefault();

    $('.svItem').colorbox({
        width: '80%',
        open: true,
        rel: 'gallery',
        href: function () {
            return $(this).data('href');
        }
    });
});


text:
Q: How to loop into nodes with same name I have a part of an XML with the following data :
           <DATA>
              <VALUE>July</VALUE>
              <VALUE>August</VALUE>
           </DATA>

In the following code, "kv.first()" is equal to "DATA"
BOOST_FOREACH(const boost::property_tree::ptree::value_type &kv, children)
{
    std::cout << "kv.first : " << kv.first << std::endl;
    std::cout << "kv.second.data : " << kv.second.data() << std::endl;
}

And what I see with the std::cout is :
kv.first : DATA
kv.second.data : July

What I expect is rather :
kv.first : DATA
kv.second.data : July
kv.first : DATA
kv.second.data : August

Did I write something wrong ? Or something is missing ?
Thank you for your answers.

A: You need to modify your BOOST::FOREACH loop to include the root tag:
BOOST_FOREACH(ptree::value_type &v, pt.get_child("DATA"))

where pt is your ptree
If your root tag has some values before that you need to include them as well for example:
 <ROOT>
   <DATA>
      <VALUE>July</VALUE>
      <VALUE>August</VALUE>
   </DATA>
 </ROOT>

Now foreach loop becomes:
BOOST_FOREACH(ptree::value_type &v, pt.get_child("ROOT.DATA"))


text:
Q: Should I place user image uploads to Amazon S3? Imagine a website like Craigslist.
Users can create a "For Sale" listing and attach images of what they're trying to sell.
Should I upload these images to Amazon S3 or something like Amazon Cloud instead?

A: S3 is the perfect place for storing those.  Users can upload to your app, which does any validation needed, then transfers to an S3 bucket.  Permissions can be managed via IAM roles assigned to your instance(s).
To serve them to your users, you will probably want to use CloudFront - at higher usage it can be cheaper and faster than serving directly from S3


text:
Q: How to validate that a value is one of a set of acceptable values? I want to compare the data of my barcode field with others in backoffice. How can I make this happen? I tried to use @Assert\NotEqualTo, but it did not work.
/**
 * @var string
 *
 * @ORM\Column(name="barcode", type="string", length=38)
 * @Assert\NotBlank(message="La barcode est obligatoire.")
 * @Assert\NotEqualTo('5414975110018','3595890210860','3595890210532',
 * '5414975110001','3595890236426','3595890217197','3595890234613','3595890221552')
 *
 * @Serializer\SerializedName("barcode")
 * @Serializer\Expose()
 */
private $barcode;

Barcode must be one of these values
5414975110018
3595890210860
3595890210532
5414975110001
3595890236426
3595890217197
3595890234613
3595890221552

If the value is one of those, it's okay, but if not it should throw an error.

A: You need to use the Choice constraint for this.
/**
 * @var string
 *
 * @ORM\Column(name="barcode", type="string", length=38)
 * @Assert\NotBlank(message="La barcode est obligatoire.")
 * @Assert\Choice({"5414975110018","3595890210860","3595890210532",
 * "5414975110001","3595890236426","3595890217197","3595890234613","3595890221552"})
 *
 * @Serializer\SerializedName("barcode")
 * @Serializer\Expose()
 */

NotEqualTo asserts that the value of the property is not equal to a certain value, but you want to assert that the value of the property is one of a set of values.


text:
Q: Level sets of a gaussian I would like to plot the level sets of this 2-arguments function :
def xi_gaussian_x(x,y):
        sigma = 0.8
        mu = 1.2
        return (1.0/(sigma*np.sqrt(2*np.pi)))*(np.exp(-(x-mu)**2/(2*sigma**2)))

where x and y are between -pi and pi. My code is the following :
plt.ion()
xInterval = np.linspace(-np.pi,np.pi,num=1000)
yInterval = np.linspace(-np.pi,np.pi,num=1000)
levels_xi_gaussian_x=np.zeros((len(xInterval),len(yInterval)))
for i in range(len(xInterval)):
        for j in range(len(yInterval)):
              levels_xi_gaussian_x[i,j]=xi_gaussian_x(xInterval[i],yInterval[j])
plt.figure()
c = plt.contour(xInterval,yInterval,levels_xi_gaussian_x.T,50)

Even if I increase the resolution of the x and y intervals, I still get regions in the -pi,pi plane which are empty :

How can I make all the plane be filled with vertical lines ?


text:
Q: Separate a file in paragraphs I have a file like this:
cluster number 1

1

2

3

cluster number 2

1

2

3

cluster number x

1

2

3

I want to split this file in paragraph of cluster numbers, like this
cluster number 1

1

2

3

I try to search for an answer but I can't handle it.
Thanks for your help!

A: user regular expression
import re
input_text = "..."
r = re.findall(r"(cluster number (\d+)\n\n(\d+)\n\n(\d+)\n\n(\d+))", input_text)
print r

this code return below list
[('cluster number 1\n\n1\n\n2\n\n3', '1', '1', '2', '3'),
 ('cluster number 2\n\n1\n\n2\n\n3', '2', '1', '2', '3')]

you can also see the detail explanation from here

A: As recommended, you should use regular expressions. Perhaps the re.split function would be suitable here:
>>> l = re.split('cluster number (?:\d+)', x)[1:]
>>> [a.split() for a in l]
[['1', '2', '3'], ['1', '2', '3'], ...]


text:
Q: When I insert a date in Jooq, I get this error: column creation_date is of type timestamp with time zone but expression is of type character varying I'm using Spring boot and postgresql, this is my "pom.xml" file:
<dependencies>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-jpa</artifactId>
   </dependency>
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jooq</artifactId>
   </dependency>
   <dependency>
    <groupId>org.postgresql</groupId>
       <artifactId>postgresql</artifactId>
       <scope>runtime</scope>
   </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>

        <plugin>
           <groupId>org.jooq</groupId>
           <artifactId>jooq-codegen-maven</artifactId>
           <executions>
              <execution>
                 <id>generate-postgre</id>
                 <phase>generate-sources</phase>
                 <goals>
                    <goal>generate</goal>
                 </goals>
                 <configuration>
                     <jdbc>
                        <driver>org.postgresql.Driver</driver>
                        <url>jdbc:postgresql://localhost:5432/DEMO</url>
                        <user>postgres</user>
                        <password>password</password>
                        </jdbc>
                      <generator>
                         <database>
                            <name>org.jooq.meta.postgres.PostgresDatabase</name>
                            <includes>.*</includes>
                            <excludes></excludes>
                            <schemata>
                                <schema> <inputSchema>comun</inputSchema> </schema>
                            </schemata>
                        </database>
                        <generate>
                              <pojos>true</pojos>
                              <pojosEqualsAndHashCode>true</pojosEqualsAndHashCode>
                              <javaTimeTypes>true</javaTimeTypes>
                              <fluentSetters>true</fluentSetters>
                         </generate>
                         <target>
                              <packageName>com.firedragon.erp.comun.entities</packageName>
                              <directory>target/generated-sources/jooq</directory>
                         </target>
                      </generator>
                   </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

I want to insert a User object like this:
User:
  userId --> Long
  name --> String
  password --> String
  creationDate --> ZonedDateTime
  modifitionDate --> ZonedDateTime

In database:
Users:
  user_id --> bigint
  name --> character varying
  password --> character varying
  creation_date --> timestamp with time zone
  modifition_date --> timestamp with time zone

but when I try to insert the user:
@Autowired
DSLContext ctx;
...
Users users=Users.USERS;
ctx.insertInto(users, Arrays.asList(users.NAME, users.PASSWORD, users.CREATION_DATE, users.MODIFICATION_DATE))
   .values(Arrays.asList("user1","password",ZonedDateTime.now(),ZonedDateTime.now()))
   .execute();

I get this error:
column 'creation_date' is of type timestamp with time zone but expression is of type character varying

I realize that the Users class that jooq created has the "creation_date" field as "TableField<UsersRecord, OffsetDateTime>" type instead of "TableField<UsersRecord, ZonedDateTime>"
public final TableField<UsersRecord, OffsetDateTime> CREATION_DATE= createField(DSL.name("creation_date"), SQLDataType.TIMESTAMPWITHTIMEZONE(6).nullable(false), this, "");

I tried to convert the creation_date field from ZonedDateTime to OffsetDateTime before to putting it in the "values" method but it doesn't work either, I get the same error
What should I do to register the user correctly?

A: I think you need to add this parameter to the connection string: stringtype=unspecified
E.g:
jdbc:postgresql://127.0.0.1:5432/testdb?stringtype=unspecified


text:
Q: How to append bunch of tags in existing XML using Python I have a big xml file (2000 kb+) that I want to append using Python. I need to check to see if a tag with some value exists. If not I need to add a bunch of tags to the file at a particular position (before a tag)
Lets take this example, restaurant.xml:
<restaurant>
    <menu>
        <breakfast_menu>
            <food>
                <name>Belgian Waffles</name>
                <price>$5.95</price>
                <description> Two of our famous Belgian Waffles with plenty of real maple syrup</description>
                <calories>650</calories>
            </food>
            <food>
                <name>Strawberry Belgian Waffles</name>
                <price>$7.95</price>
                <description>Light Belgian waffles covered with strawberries and whipped cream</description>
                <calories>900</calories>
            </food>
            <food>
                <name>Berry-Berry Belgian Waffles</name>
                <price>$8.95</price>
                <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
                <calories>900</calories>
            </food>
        </breakfast_menu>
        <lunch_menu>
            blah...blah...blah
    </menu>
</restaurant>

1st step is to check if French Toast exists in xml file. If not, add the following before </breakfast_menu>
<food>
    <name>French Toast</name>
    <price>$4.50</price>
    <description>Thick slices made from our homemade sourdough bread</description>
    <calories>600</calories>
</food>

A: Try the code given below
EDIT:
<restaurant>
    <menu>
        <breakfast_menu>
            <food>
                <name>Belgian Waffles</name>
                <price>$5.95</price>
                <description> Two of our famous Belgian Waffles with plenty of real maple syrup</description>
                <calories>650</calories>
            </food>
            <food>
                <name>Strawberry Belgian Waffles</name>
                <price>$7.95</price>
                <description>Light Belgian waffles covered with strawberries and whipped cream</description>
                <calories>900</calories>
            </food>
            <food>
                <name>Berry-Berry Belgian Waffles</name>
                <price>$8.95</price>
                <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
                <calories>900</calories>
            </food>
         </breakfast_menu>
    </menu>
</restaurant>

Code:
import xml.etree.ElementTree as ET

def SubElementWithText(parent, tag, text):
    attrib = {}
    element = parent.makeelement(tag, attrib)
    parent.append(element)
    element.text = text
    return element

def addXml(file, xpath_to_check, xpath_to_add_element, nodedict):
    tree = ET.parse(file)
    root = tree.getroot()
    if root.findall(xpath_to_check):
        st = False
        for elem in root.findall(xpath_to_check):
            if elem.text == nodedict['name']:
                st = True
        if st == False:
            breakfast_menu = root.find(xpath_to_add_element)
            food = ET.SubElement(breakfast_menu, 'food')
            for element, value  in nodedict.items():
                SubElementWithText(food, element, value)
            tree.write(file)
            print("Elements added successfully")
        else:
            print("ELement already existed")

file = "restaurent.xml"
xpath_to_check = ".//food/name"
xpath_to_add_element = "./menu/breakfast_menu"
nodedict = {"name" : "French Toast", "price" : "$4.50", "description" : "Thick slices made from our homemade sourdough bread" , "calories" : "600" }
addXml(file, xpath_to_check, xpath_to_add_element, nodedict)


text:
Q: Explanation of example 3F.7 in Hatcher The section I am refering to is the following example on page 314 of Hatcher's Algebraic Topology:

I'm a bit confused by his statement about relations and can't quite see what he is trying to say. Could someone help me interpret this example? I understand his approach, it's just a bit terse when he says "the terms after $y_1(1,0,...)$ ... and in particular allow one to reduce an arbitrary sequence $(b_0,b_1,\cdots )$ to a unique sequence"

A: Here's a different way of getting the same result, if it helps...
The maps $\mathbb{Z} \rightarrow \mathbb{Z}/p^j$ give a map of diagrams between $\cdots \rightarrow \mathbb{Z} \stackrel{1}{\rightarrow} \mathbb{Z}\stackrel{1}{\rightarrow} \mathbb{Z}$ and $\cdots \rightarrow \mathbb{Z}/p^3 \rightarrow \mathbb{Z}/p^2 \rightarrow \mathbb{Z}/p$ with kernel given by the diagram $\cdots \rightarrow p^3\mathbb{Z} \rightarrow p^2 \mathbb{Z} \rightarrow p\mathbb{Z}$. Identifying each of these with $\mathbb{Z}$ via multiplication by $p^n$ we get the inverse system in the example. So we have an exact sequence of inverse systems which we'll denote by $0 \rightarrow K \rightarrow A \rightarrow B \rightarrow 0$ which gives rise to an exact sequence (essentially by definition of derived functor...)
$$
0 \rightarrow \text{lim }K \rightarrow \text{lim }A \rightarrow \text{lim }B \rightarrow \text{lim}^1 K \rightarrow \text{lim}^1 A
$$
Now, $\text{lim }B = \mathbb{Z}_p$, by definition, $\text{lim}^1A = 0$ since all the maps are the identity, $\text{lim }K = 0$ as Hatcher says (nothing is infinitely divisible by $p$), and $\text{lim }A = \mathbb{Z}$ by observation, so we have
$$
0 \rightarrow \mathbb{Z} \rightarrow \mathbb{Z}_p \rightarrow \text{lim}^1K \rightarrow 0
$$
which is what we wanted to show.


text:
Q: Error POINTER(IUnknown) when trying to access COM object properties This code in Python is not working:
from comtypes import client
word = client.CreateObject("Word.Application")
word.Documents.Open("C:\\test.docx")

I get this error message:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
doc = word.Documents.Open("test.docx")
AttributeError: 'POINTER(IUnknown)' object has no attribute 'Documents'

Similar code using the class Excel.Appliation also gives the same kind of error. Another test with InternetExplorer.Application worked. So it seems a problem of Office.
I also tested the same code in VBScript and worked.
The code works in Windows7-64bits and Office 2013. The computer where it is not working is Windows10-64bits and Office 365. The Python version in both computers is 3.6-64bits.

A: This is not a good solution but I think I will be able to live with it. I'm using this code now:
from comtypes import client
word = client.CreateObject("Word.Application", dynamic = True)
word.Visible = True
word.Documents.Open("test.docx")
word.Documents[0].SaveAs("test.pdf", 17)
word.Documents[0].Close()

Important is the word.Visible = True row and the dynamic = True parameter. Without them the Documents collection is not found.


text:
Q: The 2 rep disappears a while after I edited a post and received it Sometimes, for example during the night, I edit some post, and I get 2 reputation points. The day after, though, the +2 has disappeared. I check to see if I had a downvote or something, but the log shows nothing. Recently, it happened more than eight times to me. Is it because I should be the last editor of that post to get the score. Am I right?

A: Some suggestions for you about editing:

*

*first, make sure you get everything in a post. Typos and spelling mistakes are great, but there are other things you can clear up in the suggested edits of yours that I checked. Meta talk like "I don't know a lot about this" or "Thanks so much to anyone who helps me" should generally be removed while you're there.

*second, do not try to make answers correct (your objections to the edits on this meta question suggest to me that you think edits are for correctness.) Edits, especially suggested edits that have to be reviewed, are for style issues like spelling, grammar, word order, expanding abbreviations and numerals, capitalization, and so on.

*third, if a question is very bad think twice before investing your time in it. If it is deleted, whether by the asker or the community, you will lose the rep you gained.

*fourth, remember that users with over 2000 rep are considered to have learned the editing rules: their edits are not reviewed and they do not get rep for editing. If you don't like an edit, you can roll it back.

And finally, if you're going to participate in meta, you will have to take the good with the bad. Meta often doesn't agree with people who come here to say something isn't fair.


text:
Q: Using beautifulsoup to extract data from html content - HTML Parsing The contents of my script using beautifulsoup library is as follows:
 <meta content="Free" itemprop="price" />

and

November 4, 2013

I would want to pull the words Free and November 4, 2013 from that output.  Will using a Regex help or does beautifulsoup has any such attributes that will pull out this directly? Here is the code I used below:
   from BeautifulSoup import BeautifulSoup
   import urllib
   import re

   pageFile = urllib.urlopen("https://play.google.com/store/apps/details?id=com.ea.game.fifa14_na")
   pageHtml = pageFile.read()
   pageFile.close()

   soup = BeautifulSoup("".join(pageHtml))
   item = soup.find("meta", {"itemprop":"price"})

   print item
   items = soup.find("div",{"itemprop":"datePublished"})

   print items

A: Ok got it! Just access the values by the following  method(for the above case):
   from BeautifulSoup import BeautifulSoup
   import urllib

   pageFile = urllib.urlopen("https://play.google.com/store/apps/details?id=com.ea.game.fifa14_na")
   pageHtml = pageFile.read()
   pageFile.close()

   soup = BeautifulSoup("".join(pageHtml))
   item = soup.find("meta", {"itemprop":"price"}) # meta content="Free" itemprop="price"
   print item['content']
   items = soup.find("div",{"itemprop":"datePublished"})
   print items.string

No need to add regex. Just a read up through the documentation would help.


text:
Q: Google Cloud Function - Python - Unable to decode gzip I am building a Google Cloud Function that will receive messages from a Google PubSub Topic.
While inserting messages in high volumes I am seeing in the logs of the function the following error:
('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing data: incorrect header check')), retrying in 1 seconds...

This happens for a few times inconsistently:

*

*Does not happen to most of the messages

*Inconsistent number of failures - from a single time to 40 times straight.

My messages are not gzip compressed and there is no "Content-Encoding" attribute in them.
My function code is not executed, this is happening on the gcp function backend before reaching my function code.
The function does work and the messages are executed, but I want to investigate why I am having this issue.
Questions

*

*What could be the cause of this issue?

*How can I fix it?

A: Issue was resolved when I upgraded Python 3.7 to 3.8.
This seems like a bug in the function backend or some library used.


text:
Q: Как пользоваться десятичными числами в mysql? Как пользоваться десятичными числами в mysql? Какой тип в бд нужен для десятичных чисел?
Есть число  1.23, как добавлять в эту строку, например, 0.01?
A: Плохо читали

Требуемая точность данных и масштаб могут задаваться (и обычно задаются)
при объявлении столбца данных одного
из этих типов, например:

salary DECIMAL(5,2)

В этом примере - 5 (точность)
представляет собой общее количество
значащих десятичных знаков, с которыми
будет храниться данная величина, а
цифра 2 (масштаб) задает количество
десятичных знаков после запятой.
Следовательно, в этом случае интервал
величин, которые могут храниться в
столбце salary, составляет от -99,99
до 99,99 (в действительности для
данного столбца MySQL обеспечивает
возможность хранения чисел вплоть до
999,99, поскольку можно не хранить
знак для положительных чисел).

http://sqlfiddle.com/#!2/ffad82


text:
Q: RSS Reader not returning feed So I'm making a very simple RSS reader for the iPhone, but when I launch it none of the items appear with the feed that I'm using. It works with others, but not with feeds.feedburner/ParadiseBeats
Does feedburner use a different system than other feeds? The feed I first used was technobuffalo.com/feeds which display the stories in rows fine.
Here is the relevant code:
 - (void)viewDidAppear:(BOOL)animated
 {
[super viewDidAppear:animated];
if ([stories count] == 0) {
    NSString *path = @"http://feeds.feedburner.com/ParadiseBeats";
    [self parseXMLFileAtURL:path];
}
}

and the element parsing...
 -(void)parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *__strong)qName attributes:(NSDictionary *__strong)attributeDict {

currentElement = [elementName copy];
if([elementName isEqualToString:@"item"]){
    //clear out story item caches...
    item = [[NSMutableDictionary alloc] init];
    currentTitle = [[NSMutableString alloc] init];
    currentDate = [[NSMutableString alloc] init];
    currentSummary = [[NSMutableString alloc] init];
    currentLink = [[NSMutableString alloc] init];

}

}

 -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *__strong)elementName namespaceURI:(NSString *__strong)namespaceURI qualifiedName:(NSString *__strong)qName {

if ([elementName isEqualToString:@"item"]) {
    [item setObject:currentTitle forKey:@"title"];
    [item setObject:currentLink forKey:@"link"];
    [item setObject:currentSummary forKey:@"summary"];
    [item setObject:currentDate forKey:@"date"];

    [stories addObject:[item copy]];
    NSLog(@"adding story: %@", currentTitle);
}

 }

A: The feed you mentioned may have different attributes for it's rss which are eventually not parsed with the mentioned code.
I had the same problem with other feeds as well although some feeds just work fine.


text:
Q: Parse server REST API error I am using  google cloud & database on mLab for deployment of the parse server. i have taken a compute engine instance and a bitnami parse-stack over it , i have configured all variables in server.js file accordingly to example provided by parse in github . Every api works fine like  JAVASCRIPT , i am able make calls from javascript files and get data from database. But the issue is with RESTAPI, my parse server is not able to recognize rest api key.
This is the CURL from my API CONSOLE from dash board
  curl -X POST \ -H "X-Parse-Application-Id: {my app id}" \ -H "X-Parse-REST-API-Key: undefined" \ http://serverURL/parse/functions/Show

this my server.js file during parse initialization
const parseServer = new ParseServer({
  databaseURI: nconf.get('DATABASE_URI') ||
  cloud: nconf.get('CLOUD_PATH') ||
  appId: nconf.get('APP_ID'),
  masterKey: nconf.get('MASTER_KEY'),
serverURL: nconf.get('SERVER_URL'),
   restAPIKey: nconf.get('REST_API_KEY'),
    javascriptKey: nconf.get('JAVASCRIPT_KEY'),
   clientKey: nconf.get('CLIENT_KEY'),
   dotNetKey: nconf.get('.NET_KEY'),
}
As you could see the RESTAPI key is being undefined  in the curl.
 i couldn't understand where was i making a mistake. Please provide me with some advice .
  Thanks in adavance.

A: bitnami developer here.
I have followed your instructions and I'm not able to reproduce your issue.
I've created a machine in google cloud with the bitnami parse instance on the top of it. Then, I went to the url of the application and I created a class called GameScore.See this screenshot.
Then, I've followed the github parse example in order to make a curl to introduce data in the database. This is the curl I made, which it worked for me.
curl -X POST \
  -H "X-Parse-Application-Id: APPID_FORM_SERVER.JS" \
  -H "Content-Type: application/json" \
  -d '{"score":1337,"playerName":"Sean Plott","cheatMode":false}' \
  http://localhost:1337/parse/classes/GameScore

The APPID_FROM_SERVER.JS is the one I get from the server.js file.
Then in the dashboard I'm able to see what I've send to the server.
My server.js file is the default one, which is in  /opt/bitnami/apps/parse/htdocs/server.js
It seems that the configuration of your server.js is wrong. This is how a default server.js file looks like:
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();
// Specify the connection string for your mongodb database
// and the location to your Parse cloud code
var api = new ParseServer({
    databaseURI: "mongodb://root:yCKeC13S@127.0.0.1:27017/bitnami_parse",
    cloud: "./node_modules/parse-server/lib/cloud-code/Parse.Cloud.js",
    appId: "d774b123a533e0ba2169b4926ed99de5676d59ef",
    masterKey: "5cdbe7c6fdb090c97cbf794a701dd697a70716ab",
    fileKey: "80e8cf19d1467992c6559a5826fef0278d489f9a",
    serverURL: 'http://35.187.2.104:80/parse'
});
// Serve the Parse API on the /parse URL prefix
app.use('/parse', api);

var port = 1337;
app.listen(port, function() {
    console.log('parse-server running on port ' + port);
});

//Parse Dashboard
var ParseDashboard = require('parse-dashboard');
var dashboard = new ParseDashboard({
    apps: [
        {
            appName: "My Bitnami Parse API",
            appId: "d774b123a533e0ba2169b4926ed99de5676d59ef",
            masterKey: "5cdbe7c6fdb090c97cbf794a701dd697a70716ab",
            fileKey: "80e8cf19d1467992c6559a5826fef0278d489f9a",
            production: true,
            serverURL: 'http://35.187.2.104:80/parse'
        }
    ]
});

var allowInsecureHTTP = true;

// Serve the Parse Dashboard on the /parsedashboard URL prefix
app.use('/', dashboard);

var portdash = 4040;
app.listen(portdash, function() {
    console.log('parse-dashboard running on port ' + portdash);
});