text:
Q: libgdx - iOS landscape not working right with scene2d I'm having an issue with libGDX's otherwise great scene2d ui library when running my app in landscape mode. My program works as expected in both the android simulator and the desktop environment, but when I run it on the iOS simulator or a real device, the main menu is drawn as if the phone were still in the portrait orientation, and the just cropped to fit in a landscape view. At first, I assumed I had just screwed up, as I'm still learning the api, but the app works just as expected on android. I have configured my game to run in landscape mode on both iOS and android.
On the android simulator, the menu works as expected. The simulator is in landscape orientation, and properly displays the menu.
On iOS, the menu is off center and unclickable.
I pretty sure that the problem has to do with landscape mode, because everything works fine in portrait orientation. Here's my code for the MainMenuScreen, which extends a ScreenAdapter.
package bakpakin.techgame;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;

/**
 * Created by Calvin on 9/25/14.
 */
public class MainMenuScreen extends ScreenAdapter {

private TechGame game;
private Stage stage;
private Skin skin;
private Table table;

public MainMenuScreen(TechGame game) {
    this.game = game;
}

@Override
public void show() {
    this.stage = new Stage();
    this.skin = new Skin();

    skin.add("default", Assets.superScript48);
    skin.add("title", Assets.superScript128);

    TextButtonStyle textButtonStyle = new TextButtonStyle();
    textButtonStyle.font = skin.getFont("default");
    textButtonStyle.pressedOffsetY = 4;
    skin.add("default", textButtonStyle);

    Label.LabelStyle labelStyle = new Label.LabelStyle();
    labelStyle.font = skin.getFont("title");
    labelStyle.fontColor = Color.CYAN;
    skin.add("default", labelStyle);

    // Create a table that fills the screen. Everything else will go inside this table.
    table = new Table();
    table.setFillParent(true);
    stage.addActor(table);

    final TextButton play = new TextButton("Play", skin);
    final TextButton about = new TextButton("About", skin);
    final TextButton quit = new TextButton("Quit", skin);

    play.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            Assets.button1Sound.play(1, 1, 0);
        }
    });

    about.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            Assets.button1Sound.play(1, 1, 0);
        }
    });

    quit.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            Assets.button1Sound.play(1, 1, 0);
            Gdx.app.exit();
        }
    });

    final Label title = new Label("My Game", skin);

    VerticalGroup vg = new VerticalGroup();

    vg.pad(60);

    table.add(title);
    table.row();
    table.add(vg);

    vg.addActor(play);
    vg.addActor(about);
    vg.addActor(quit);

    Gdx.input.setInputProcessor(stage);
}

@Override
public void render(float delta) {

    GL20 gl = Gdx.gl;
    gl.glClearColor(0, 0, 0, 1);
    gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    stage.act(delta);
    stage.draw();
}

@Override
public void dispose() {
    stage.dispose();
    skin.dispose();
}
}

A: IOS 7 or 8? I heard there are some iOS 8 rendering issues
Apparently this is fixed in the latest snapshot (see github.com/libgdx/libgdx/issues/2386). With a new stable release promised real-soon-now, I'm sure the fix will be folded in if you're not brave enough to run snapshot builds


text:
Q: Attempting to save a snapshot complains Application not found I'm trying to save an App snapshot on OpenShift, however it complains that my application isn't found. When I type rhc apps my application is correctly listed, not sure what I could be doing wrong.
For example:
appname @ http://appname-domain.rhcloud.com

when I run rhc snapshot save -a appname, I get:
Application 'appname' not found.

A: If the application is not in your default namespace, then you will need to add the -n option to your rhc snapshot save command.  That could be your issue.

redpajama_set_name: RedPajamaStackExchange


text: Q: GCP Image Import For the GCP Image Import can I Import the images with ISO format or VDI format from on premise and use it in compute engine after converting into images or using gcloud compute images import.


text:
Q: Select rows based on total percentage of records present MySQL I am not sure if I have put the right title, will be happy for the moderator to change it. Here is what i want:
Lets say i have a table with 3 columns
Id |   Name      |    campaignid
-----------------------------
1. |    John.    |     1
----------------------------
2  |    Peter.   |     2
---------------------------
3. |    Martin.  |     3
----------------------------
4. |    Sarah.   |     2
----------------------------
5. |    Jessica. |     3
----------------------------
6. |    Parker.  |     3

Now in reality i will have a million of records with approximately 1000 different campaignid, at a time i can only process 3000 records, so i want to select 3000 records and process them, then get another 3000 records and process them, so on and so forth.
When i select 3000 records from the database I want to get the rows based on the percentage of campaignids present in total records. For ex in the above example, campaignid 3 is present 50%, 2 is 33.33% and 1 is 17.77%. Now if this was also the compisition of a million of records and i had to select 3000 records out of it, then campaignid 3 should be 1500 times, campaign id 2 should be 999 times and remaining should be campaign id 1, i.e. 50%, 33.3% and 17% respectively.
Please could anyone help me out with an efficient query for this. I am using Mysql database.

A: You might try MySQL's FOUND_ROWS() function. For example:
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
    -> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();

The second SELECT returns a number indicating how many rows the first SELECT would have returned had it been written without the LIMIT clause.


text:
Q: Java loop object declaration best practice I've read some other questions about declaring objects inside loops, like:
Is it Better practice to Declare individual objects or loop Anonymous objects into ArrayList?
Java : declaring objects in a loop
but neither really address my question.
I'm scanning for user input repeatedly and creating a class to parse that string every iteration:
    public static void main(String[] args) {
        while (true) {
            System.out.print("Enter a string of brackets to test: ");
            String exp = new Scanner(System.in).nextLine().trim();
            if (exp.equals("q")) break; // q is the 'quit' flag
            System.out.println(new BracketMatcher(exp.length()).parse(exp));
        }
    }

Is there any difference - in performance, not scope - to this block?:
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    BracketMatcher matcher;
    while (true) {
        System.out.print("Enter a string of brackets to test: ");
        String exp = input.nextLine().trim();
        if (exp.equals("q")) break; // q is the 'quit' flag
        matcher = new BracketMatcher(exp.length());
        System.out.println(matcher.parse(exp));
    }

Would I be better off making parse() a static method in BracketMatcher since I only use that method?
Thanks.

A: The performance difference in your code comes from creating a new Scanner in every iteration (which is silly, maybe not even work reliably, depending how a Scanner buffers).
Where you declare the variable has no performance impact in itself.
Personally I would create the Scanner once (because it is supposed to read all lines, not just a single one), but the BracketMatcher inside of the loop (because it is tied to the current line).
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    while (true) {
        System.out.print("Enter a string of brackets to test: ");
        String exp = input.nextLine().trim();
        if (exp.equals("q")) break; // q is the 'quit' flag
        System.out.println(new BracketMatcher(exp.length()).parse(exp));
    }
}

Would I be better off making parse() a static method in BracketMatcher since I only use that method?

I don't know what your BracketMatcher does, and if anything can be prepared regardless of input. For example regular expression matchers can be compiled once for a fixed expression and then re-used for many strings to match.  In that case, you may keep the BracketMatcher a stateful object,  and create it once outside the loop.

A: Doing an allocation new Scanner(...) is generally going to be less performer than re-using the object.  Especially if there is no internal state involved in the object itself - then allocating a new one each time does nothing for you.
So yes, I'd say make one of each and re-use them.

Would I be better off making parse() a static method in BracketMatcher
  since I only use that method?

If BracketMatcher contains no state then yes you could make it a static method.

A: If you create the scanner multiple times you lose performance(because of garbage collection and constructing it) and you gain a slightly buggier system because of spammed input scanners


text:
Q: How to select records without duplicate column in mysql My Query:
SELECT * FROM `opd`;

OPD No | Name
---------------
1      | Ravi
2      | Ravi
3      | Ravi
1      | Ravi
4      | Ravi
5      | Ravi
2      | Ravi

I want the result using mysql query or any other method to the following:
OPD No | Name
---------------

3      | Ravi
4      | Ravi
5      | Ravi

Kindly note I dont want distinct column I want to remove all duplicates.

A: SELECT OPD_No, Name
FROM opd
GROUP BY OPD_No, Name
HAVING COUNT(*) = 1


text:
Q: Google Developer Console. В настоящий момент через это приложение контент не продается. я хочу добавить Внутренние Платежи (in app billing) в приложение. В документации google написано что нужно добавить permission <uses-permission android:name="com.android.venging.BILLING"/> в manifest файл. Я добавил это разрешение  и IInAppBillingService.aidl в проект, настроил работу с сервисом. Но в консоли разработчика написано
"В настоящий момент через это приложение контент не продается.
Чтобы загружать контент для продажи через приложения, добавьте в APK-файл разрешение BILLING.".
 У кого нибудь была такая проблема? Нужно ли ждать пока google обновит информацию?

A: Решение: У меня ошибка в самом permission. Вместо vending я написал venging по невнимательности.


text:
Q: Create Linked Server at MS SQL to Oracle I was wondering how to create synonym at MS SQL Server that will link my Oracle database? My tables all are at Oracle database. Thanks in advance.

A: Here is a few more links on linked server from SQL Server to Oracle which enables developers on SQL Server to query data in an Oracle database
http://sqlmag.com/sql-server/sql-server-and-oracle-making-connection
http://www.kodyaz.com/articles/create-oracle-linked-server-query-data-from-oracle-to-sql-server.aspx

A: I think, you are looking for the feature called 'Linked Server'.
If so, start reading here: http://technet.microsoft.com/en-us/library/ms188279.aspx

A: You'll need to create a linked server then use synonym on top of that if you need the level of abstraction.
http://www.pressthered.com/sql_server_synonyms_and_linked_servers/


text:
Q: OpenVPN with Smartcard 2FA I have a working OpenVPN setup, which uses X.509 certificates for authentication. In order to implement two-factor authentication I want to enroll new keys/certificates on smartcards. Aventra MyEID was the card that worked smoothest with OpenSC and the CA enrollment process, so I started with this card.
On Linux the OpenVPN client (OpenVPN 2.4.0, opensc-pkcs11 0.16.0-3, libpkcs11-helper1 1.21-1 / Debian Stretch) freezes at the point where it should prompt for the PIN of the card. First I suspected a pinentry/askpass problem but when I played around with the pkcs11-id it already froze during the PKCS11 provider initialization (didn't respond to signals except kill -9).
On Windows the test client reached the point, where it contacts the card, but then displayed an error that sounds like this bug: https://bugzilla.redhat.com/show_bug.cgi?id=1516474
I got the Windows setup working, when I used the 2.3 version of the OpenVPN client, which gave me a working PKCS11 URI:
/usr/sbin/openvpn --show-pkcs11-ids (path-to-provider)

The 2.4 Version gives me different ID, which is not working. However when I use the pkcs11-id that the 2.3 version told me, it works as well.
My colleges have been evaluating other cards (Yubi and Nitrokey), but they also felt that the PCS11 interface of OpenVPN 2.4 wasn't working particularly well with these cards.
If anyone is running a reliable OpenVPN 2.4 setup with Smartards, could you share which cards you are using?
Best regards,
Dirk


text:
Q: How to create a reference table in MS Excel? I would like to create a reference table in Excel like this:

So everywhere in my workbook or worksheet I type X111, Excel shows the value of 2400.
How could I do that?

A: You can create a second sheet and use VLOOKUP to do this.
For example, to get the value alone you can use the formula:
=VLOOKUP("X111", Sheetname!A1:B16, 2)

If you're performing a calculation somewhere, insert this formula as needed.
This isn't as concise or "clean" as specifying variables as you might using VBScript, but hopefully this works for you.


text:
Q: matlab2tikz - problem with german letters - ä, ö, ü, \cdot and r_N I'm using matlab2tikz the first time and get some problems with the first graph. I could seperate the problem. In the moment, I insert german letters like ä, ö, ü or special code like \cdot and r_N in MatLab, using matlab2tikz and compile my Latex document, I got an error.
The figure has to look like the picture attacht
An image of the Error is attached:

The Latex packages I use are:
\documentclass[a4paper,12pt,twoside]{report}
\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}
\usepackage[width=150mm,top=25mm,bottom=25mm,bindingoffset=6mm]{geometry}
\usepackage[T1]{fontenc}
\usepackage{amsmath,amssymb,amsmath}
\usepackage{graphicx, subfig}
\graphicspath{{Bilder/}}

\usepackage{color}
\usepackage{transparent}

\usepackage{pgfplots}
\usepackage{tikz}

\usepackage[printonlyused]{acronym}
\begin{document}

\begin{figure}
\centering
\input{img/KOSTRA_S24_Z78_r_N.tikz}
\caption{Kostra 2010R Spalte 24 Zeile 78 für die Niederschlagspende}
\label{kostra_2010R}
\end{figure}
\end{document}

The graph looks after compiling in Latax without the letters and special code like this:
The compiled code of matlab2tikz:
% This file was created by matlab2tikz.
%
%The latest updates can be retrieved from
%  http://www.mathworks.com/matlabcentral/fileexchange/22022-matlab2tikz-matlab2tikz
%where you can also make suggestions and rate matlab2tikz.
%
\definecolor{mycolor1}{rgb}{0.00000,0.44700,0.74100}%
\definecolor{mycolor2}{rgb}{0.85000,0.32500,0.09800}%
\definecolor{mycolor3}{rgb}{0.92900,0.69400,0.12500}%
\definecolor{mycolor4}{rgb}{0.49400,0.18400,0.55600}%
\definecolor{mycolor5}{rgb}{0.46600,0.67400,0.18800}%
\definecolor{mycolor6}{rgb}{0.30100,0.74500,0.93300}%
\definecolor{mycolor7}{rgb}{0.63500,0.07800,0.18400}%
%
\begin{tikzpicture}

\begin{axis}[%
width=15.5in,
height=8.175in,
at={(2.6in,1.103in)},
scale only axis,
xmin=0,
xmax=100,
xlabel style={font=\color{white!15!black}},
xlabel={Jährlichkeit [a]},
ymin=0,
ymax=1200,
ylabel style={font=\color{white!15!black}},
ylabel={$\text{Niederschlagspenden r}_\text{N}\text{  [l/(s}\cdot\text{ha)]}$},
axis background/.style={fill=white},
title style={font=\bfseries},
title={KOSTRA S24 Z78},
legend style={at={(0.139,0.692)}, anchor=south west, legend cell align=left, align=left, draw=white!15!black}
]
\addplot [color=mycolor1]
  table[row sep=crcr]{%
1   55\\
2   73\\
3   84\\
5   97\\
10  115\\
20  133\\
30  143\\
50  157\\
100 175\\
};
\addlegendentry{5 min}

\addplot [color=mycolor2]
  table[row sep=crcr]{%
1   87\\
2   112\\
3   126\\
5   145\\
10  170\\
20  196\\
30  210\\
50  229\\
100 254\\
};
\addlegendentry{10 min}

\addplot [color=mycolor3]
  table[row sep=crcr]{%
1   107\\
2   138\\
3   156\\
5   178\\
10  209\\
20  240\\
30  258\\
50  280\\
100 311\\
};
\addlegendentry{15 min}

\addplot [color=mycolor4]
  table[row sep=crcr]{%
1   121\\
2   157\\
3   177\\
5   203\\
10  239\\
20  274\\
30  295\\
50  321\\
100 356\\
};
\addlegendentry{20 min}

\addplot [color=mycolor5]
  table[row sep=crcr]{%
1   140\\
2   183\\
3   208\\
5   240\\
10  283\\
20  326\\
30  351\\
50  383\\
100 426\\
};
\addlegendentry{30 min}

\addplot [color=mycolor6]
  table[row sep=crcr]{%
1   156\\
2   209\\
3   239\\
5   278\\
10  330\\
20  382\\
30  413\\
50  451\\
100 504\\
};
\addlegendentry{45 min}

\addplot [color=mycolor7]
  table[row sep=crcr]{%
1   166\\
2   226\\
3   261\\
5   305\\
10  366\\
20  426\\
30  461\\
50  505\\
100 565\\
};
\addlegendentry{60 min}

\addplot [color=mycolor1]
  table[row sep=crcr]{%
1   182\\
2   246\\
3   283\\
5   330\\
10  394\\
20  458\\
30  495\\
50  542\\
100 606\\
};
\addlegendentry{90 min}

\addplot [color=mycolor2]
  table[row sep=crcr]{%
1   195\\
2   261\\
3   300\\
5   349\\
10  416\\
20  482\\
30  521\\
50  570\\
100 637\\
};
\addlegendentry{2 h}

\addplot [color=mycolor3]
  table[row sep=crcr]{%
1   214\\
2   285\\
3   326\\
5   378\\
10  449\\
20  519\\
30  561\\
50  613\\
100 684\\
};
\addlegendentry{3 h}

\addplot [color=mycolor4]
  table[row sep=crcr]{%
1   229\\
2   302\\
3   346\\
5   400\\
10  474\\
20  547\\
30  591\\
50  645\\
100 719\\
};
\addlegendentry{4 h}

\addplot [color=mycolor5]
  table[row sep=crcr]{%
1   251\\
2   329\\
3   375\\
5   433\\
10  511\\
20  590\\
30  635\\
50  693\\
100 771\\
};
\addlegendentry{6 h}

\addplot [color=mycolor6]
  table[row sep=crcr]{%
1   276\\
2   359\\
3   408\\
5   469\\
10  552\\
20  635\\
30  684\\
50  745\\
100 828\\
};
\addlegendentry{9 h}

\addplot [color=mycolor7]
  table[row sep=crcr]{%
1   295\\
2   382\\
3   432\\
5   496\\
10  583\\
20  670\\
30  721\\
50  785\\
100 871\\
};
\addlegendentry{12 h}

\addplot [color=mycolor1]
  table[row sep=crcr]{%
1   324\\
2   416\\
3   470\\
5   538\\
10  630\\
20  722\\
30  776\\
50  844\\
100 936\\
};
\addlegendentry{18 h}

\addplot [color=mycolor2]
  table[row sep=crcr]{%
1   346\\
2   442\\
3   498\\
5   569\\
10  666\\
20  762\\
30  818\\
50  889\\
100 985\\
};
\addlegendentry{24 h}

\addplot [color=mycolor3]
  table[row sep=crcr]{%
1   426\\
2   524\\
3   581\\
5   653\\
10  750\\
20  848\\
30  905\\
50  977\\
100 1075\\
};
\addlegendentry{48 h}

\addplot [color=mycolor4]
  table[row sep=crcr]{%
1   481\\
2   580\\
3   637\\
5   710\\
10  809\\
20  907\\
30  965\\
50  1037\\
100 1136\\
};
\addlegendentry{72 h}

\end{axis}

\begin{axis}[%
width=20in,
height=10.031in,
at={(0in,0in)},
scale only axis,
xmin=0,
xmax=1,
ymin=0,
ymax=1,
axis line style={draw=none},
ticks=none,
axis x line*=bottom,
axis y line*=left
]
\end{axis}
\end{tikzpicture}%

I have an Win10 system and use MikTex 2.9. Did every Update I could ....
Is it a problem to run the system with an English language? Cann't change it at the moment. A simulation is running for the next 24 hours.
I like to use vector graphics. I can use png but it looks bad.
Thanks for the help
Kopi
I did the update over the MikTeX Console. At some point the admin mode was necessary.  5 minutes ago, I did a new update .  You are rigth, the image of a compile without the problematic letters and code. If I change the \documentclass to \documentclass[tikz]{standalone} I get the full error report. This time I uncomment some of my latex document code. That's why is the error message shorter.

A: The problem was created by the compiling of matlab2tikz. If I delete the command \text{} in the x- ans y-label, then I donnt' get the error. Has someone an answer, why this happend? There is only one problem left. The legend.
See picture attached:

I use at the moment the following code:
\documentclass[a4paper,12pt,twoside]{report}

\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage{graphicx, subfig}
\graphicspath{{img/}}
%\usepackage{fancyhdr}
\usepackage{lmodern}
\usepackage{amsfonts}

%Für Vektorgrafiken
\usepackage{color}
%\graphicspath{img/}
\usepackage{transparent}
%Für TikZ

\usepackage{pgfplots}
\usepackage{tikz}
\pgfplotsset{compat=1.17}
\usepackage{textcomp}

\begin{document}

%\begin{figure}
%\centering
%\input{img/KOSTRA_S24_Z78_r_N.tikz}
%
%\caption{Kostra 2010R Spalte 24 Zeile 78 für die Niederschlagspende}
%\label{kostra_2010R}
%\end{figure}

% This file was created by matlab2tikz.
%
%The latest updates can be retrieved from
%  http://www.mathworks.com/matlabcentral/fileexchange/22022-matlab2tikz-matlab2tikz
%where you can also make suggestions and rate matlab2tikz.
%
\definecolor{mycolor1}{rgb}{0.00000,0.44700,0.74100}%
\definecolor{mycolor2}{rgb}{0.85000,0.32500,0.09800}%
\definecolor{mycolor3}{rgb}{0.92900,0.69400,0.12500}%
\definecolor{mycolor4}{rgb}{0.49400,0.18400,0.55600}%
\definecolor{mycolor5}{rgb}{0.46600,0.67400,0.18800}%
\definecolor{mycolor6}{rgb}{0.30100,0.74500,0.93300}%
\definecolor{mycolor7}{rgb}{0.63500,0.07800,0.18400}%
%
\begin{tikzpicture}

\begin{axis}[%
width=3.5in,
height=3.175in,
at={(2.6in,1.103in)},
scale only axis,
xmin=0,
xmax=100,
xlabel style={font=\color{white!15!black}},
xlabel={Jährlichkeit [a]},
ymin=0,
ymax=1200,
ylabel style={font=\color{white!15!black}},
ylabel={Niederschlagspenden $r_N$ $[l/(s\cdot ha)]$},
axis background/.style={fill=white},
title style={font=\bfseries},
title={KOSTRA S24 Z78},
legend style={at={(0.139,0.692)}, anchor=south west, legend cell align=left, align=left, draw=white!15!black}
]
\addplot [color=mycolor1]
  table[row sep=crcr]{%
1   55\\
2   73\\
3   84\\
5   97\\
10  115\\
20  133\\
30  143\\
50  157\\
100 175\\
};
\addlegendentry{5 min}

\addplot [color=mycolor2]
  table[row sep=crcr]{%
1   87\\
2   112\\
3   126\\
5   145\\
10  170\\
20  196\\
30  210\\
50  229\\
100 254\\
};
\addlegendentry{10 min}

\addplot [color=mycolor3]
  table[row sep=crcr]{%
1   107\\
2   138\\
3   156\\
5   178\\
10  209\\
20  240\\
30  258\\
50  280\\
100 311\\
};
\addlegendentry{15 min}

\addplot [color=mycolor4]
  table[row sep=crcr]{%
1   121\\
2   157\\
3   177\\
5   203\\
10  239\\
20  274\\
30  295\\
50  321\\
100 356\\
};
\addlegendentry{20 min}

\addplot [color=mycolor5]
  table[row sep=crcr]{%
1   140\\
2   183\\
3   208\\
5   240\\
10  283\\
20  326\\
30  351\\
50  383\\
100 426\\
};
\addlegendentry{30 min}

\addplot [color=mycolor6]
  table[row sep=crcr]{%
1   156\\
2   209\\
3   239\\
5   278\\
10  330\\
20  382\\
30  413\\
50  451\\
100 504\\
};
\addlegendentry{45 min}

\addplot [color=mycolor7]
  table[row sep=crcr]{%
1   166\\
2   226\\
3   261\\
5   305\\
10  366\\
20  426\\
30  461\\
50  505\\
100 565\\
};
\addlegendentry{60 min}

\addplot [color=mycolor1]
  table[row sep=crcr]{%
1   182\\
2   246\\
3   283\\
5   330\\
10  394\\
20  458\\
30  495\\
50  542\\
100 606\\
};
\addlegendentry{90 min}

\addplot [color=mycolor2]
  table[row sep=crcr]{%
1   195\\
2   261\\
3   300\\
5   349\\
10  416\\
20  482\\
30  521\\
50  570\\
100 637\\
};
\addlegendentry{2 h}

\addplot [color=mycolor3]
  table[row sep=crcr]{%
1   214\\
2   285\\
3   326\\
5   378\\
10  449\\
20  519\\
30  561\\
50  613\\
100 684\\
};
\addlegendentry{3 h}

\addplot [color=mycolor4]
  table[row sep=crcr]{%
1   229\\
2   302\\
3   346\\
5   400\\
10  474\\
20  547\\
30  591\\
50  645\\
100 719\\
};
\addlegendentry{4 h}

\addplot [color=mycolor5]
  table[row sep=crcr]{%
1   251\\
2   329\\
3   375\\
5   433\\
10  511\\
20  590\\
30  635\\
50  693\\
100 771\\
};
\addlegendentry{6 h}

\addplot [color=mycolor6]
  table[row sep=crcr]{%
1   276\\
2   359\\
3   408\\
5   469\\
10  552\\
20  635\\
30  684\\
50  745\\
100 828\\
};
\addlegendentry{9 h}

\addplot [color=mycolor7]
  table[row sep=crcr]{%
1   295\\
2   382\\
3   432\\
5   496\\
10  583\\
20  670\\
30  721\\
50  785\\
100 871\\
};
\addlegendentry{12 h}

\addplot [color=mycolor1]
  table[row sep=crcr]{%
1   324\\
2   416\\
3   470\\
5   538\\
10  630\\
20  722\\
30  776\\
50  844\\
100 936\\
};
\addlegendentry{18 h}

\addplot [color=mycolor2]
  table[row sep=crcr]{%
1   346\\
2   442\\
3   498\\
5   569\\
10  666\\
20  762\\
30  818\\
50  889\\
100 985\\
};
\addlegendentry{24 h}

\addplot [color=mycolor3]
  table[row sep=crcr]{%
1   426\\
2   524\\
3   581\\
5   653\\
10  750\\
20  848\\
30  905\\
50  977\\
100 1075\\
};
\addlegendentry{48 h}

\addplot [color=mycolor4]
  table[row sep=crcr]{%
1   481\\
2   580\\
3   637\\
5   710\\
10  809\\
20  907\\
30  965\\
50  1037\\
100 1136\\
};
\addlegendentry{72 h}

\end{axis}

\begin{axis}[%
width=10in,
height=1.031in,
at={(0in,0in)},
scale only axis,
xmin=0,
xmax=1,
ymin=0,
ymax=1,
axis line style={draw=none},
ticks=none,
axis x line*=bottom,
axis y line*=left
]
\end{axis}
\end{tikzpicture}%

\end{document}

After changing the matlab Code to UTF-8 and using matlab2tikz again I got this error message.


text:
Q: External Style is not detected by javascript (if conditon used) I am relative new to web development so while developing a project site responsive design I ran into a problem that when ever hamburger menu is pressed even though lines for expending exists in external css file but it is not detected but new inine styles are created by javascript and then it works as expected.
HTML:

Home

Astronomy

Telescopes

About

CSS:
#mobileMenu {
 font-family: light, sans-serif;
 max-height: 0px;
 z-index: 99;
 transform: translateY(-100%);
 overflow: hidden;
 padding: 0px;
 transition: transform 0.5s;
}

Javascript:
function show() {
if (document.getElementById("mobileMenu").style.maxHeight == "0px") {
    setTimeout(function(){
        document.getElementById("mobileMenu").style.maxHeight = "100%";
        document.getElementById("mobileMenu").style.position = "fixed";
        document.getElementById("mobileMenu").style.padding = "1%";
    }, 1)
    document.getElementById("mobileMenu").style.transform = "translateY(0px)";
} else {
    setTimeout(function(){
        document.getElementById("mobileMenu").style.maxHeight = "0px";
        document.getElementById("mobileMenu").style.padding = "0px";
        document.getElementById("mobileMenu").style.position = "relative";
    }, 500)
    document.getElementById("mobileMenu").style.transform = "translateY(-100%)";
}}

Working Example:
Astromuneeb (Require Portrait Orientation)
Any help will be appreciated.

A: There are better approaches of what you are trying to accomplish. For instance, you could use css classes for styling and use javascript only for switching classes.

A: I agree with Eugene, but .mobileNav class seems to be overriding your portrait media query.

I added important to your .mobileNav portrait media query but even that won't override it, guess its something to do with hierarchy. It's weird you get display:none; as an inline style on your nav when opening and closing currently, that will not help.
Definitely just set a .open class as Eugene suggested. And use css transforms to do the animation. And just simply add/remove class on the nav.
And when using media queries in css for mobile etc prob best to use screen size etc, and start mobile first...
.mobileNav { display: block; }

@media (min-width: 992px) {
  .mobileNav { display: none; }

}


text:
Q: How do I check in python if an element of a list is empty? I have a list like
l = []

How do I check if l[i] is empty?
l[i] = ''

and
l[i] = ""

dont't work.

A: Just check if  that element is equal to None type or make use of NOT operator ,which is equivalent to the NULL type you observe in other languages.
if not A[i]:
    ## do whatever

Anyway if you know the size of your list then you don't need to do all this.

A: Suppose
letter= ['a','','b','c']

for i in range(len(letter)):
    if letter[i] =='':
        print(str(i) + ' is empty')

output- 1 is emtpy
So we can see index 1 is empty.

A: If you want to know if list element at index i is set or not, you can simply check the following:
if len(l)<=i:
    print ("empty")

If you are looking for something like what is a NULL-Pointer or a NULL-Reference in other languages, Python offers you None. That is you can write:
l[0] = None # here, list element at index 0 has to be set already
l.append(None) # here the list can be empty before
# checking
if l[i] == None:
    print ("list has actually an element at position i, which is None")

A: Try:
if l[i]:
    print 'Found element!'
else:
    print 'Empty element.'

A: Unlike in some laguages, empty is not a keyword in Python. Python lists are constructed form the ground up, so if element i has a value, then element i-1 has a value, for all i > 0.
To do an equality check, you usually use either the == comparison operator.
>>> my_list = ["asdf", 0, 42, '', None, True, "LOLOL"]
>>> my_list[0] == "asdf"
True
>>> my_list[4] is None
True
>>> my_list[2] == "the universe"
False
>>> my_list[3]
""
>>> my_list[3] == ""
True

Here's a link to the strip method: your comment indicates to me that you may have some strange file parsing error going on, so make sure you're stripping off newlines and extraneous whitespace before you expect an empty line.

A: I got around this with len() and a simple if/else statement.
List elements will come back as an integer when wrapped in len() (1 for present, 0 for absent)
l = []

print(len(l)) # Prints 0

if len(l) == 0:
    print("Element is empty")
else:
    print("Element is NOT empty")

Output:

Element is empty

A: List = []

for item in List:
    if len(item.rstrip()) != 0:
        # Do whatever you want

This will be useful if you have long string list with some whitespace and you're not considering those list values.

A: Having a similar issue where a location string needed some pre-testing:
loc_string = "site/building/room//ru" # missing rack
is_ok = True
for i in loc_string.split('/'):
  if not i:
    is_ok = False

if is_ok:
  #perform any action
  print(is_ok)

This will return True if all values have data.


text:
Q: UTF8 Encoding and Network Streams A client and server communicate with each other via TCP. The server and client send each other UTF-8 encoded messages.
When encoding UTF-8, the amount of bytes per character is variable. It could take one or more bytes to represent a single character.
Lets say that I am reading a UTF-8 encoded message on the network stream and it is a huge message. In my case it was about 145k bytes. To create a buffer of this size to read from the network stream could lead to an OutMemoryException since the byte array needs that amount of sequential memory.
It would be best then to read from the network stream in a while loop until the entire message is read, reading the pieces in to a smaller buffer (probably 4kb) and then decoding the string and concatenating.
What I am wondering is what happens when the very last byte of the read buffer is actually one of the bytes of a character which is represented by multiple bytes. When I decode the read buffer, that last byte and the beginning bytes of the next read would either be invalid or the wrong character. The quickest way to solve this in my mind would be to encode using a non variable encoding (like UTF-16), and then make your buffer a multiple of the amount of bytes in each character (with UTF-16 being a buffer using the power 2, UTF-32 the power of 4).
But UTF-8 seems to be a common encoding, which would leave me to believe this is a solved problem. Is there another way to solve my concern other than changing the encoding? Perhaps using a linked-list type object to store the bytes would be the way to handle this since it  would not use sequential memory.

A: It is a solved problem. Woot woot!
http://mikehadlow.blogspot.com/2012/07/reading-utf-8-characters-from-infinite.html


text:
Q: Return correct number of citations from Microsoft Academic API I'm trying to get citation count for several authors using Microsoft Academic API. However, I'm finding that my manual searches retrieve different results than the API call. For example, the author Laurens van der Maaten appears to have 40,747 citations (see here). However, when I I try using the API call as shown below (using Python), I get fewer results.
import requests

def get_author_CC(subscription_key, author_name):
    url = 'https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate'
    params = {
        "expr": f"Composite(AA.AuN=='{author_name}')",
        "attributes": "CC"
    }
    headers = {'Ocp-Apim-Subscription-Key': subscription_key}

    r = requests.get(url, params=params, headers=headers).json().get('entities')

    return sum([ld.get('CC') for ld in r])

get_author_CC(subscription_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", author_name="laurens van der maaten")
>>> 26545

Is there a parameter or something I'm missing? Thanks.

A: After going through the docs, I think you need to use ECC which is the estimated citation count. Also, you need to provide count in the params, since the default is count=10
import requests

def get_author_CC(subscription_key, author_name):
    url = 'https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate'
    params = {
        "expr": f"Composite(AA.AuN=='{author_name}')",
        "attributes": "ECC,CC",
        'count': 10000
    }
    headers = {'Ocp-Apim-Subscription-Key': subscription_key}

    r = requests.get(url, params=params, headers=headers).json().get('entities')

    return sum([ld.get('ECC') for ld in r])

get_author_CC(subscription_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", author_name="laurens van der maaten")


text:
Q: Have I just found a bug in Chrome? I have written simple page with fixed sidebar and footer. Sidebar is child of a div located outside the window, just to the right of it. Sidebar should always be behind footer. Everything works fine on Firefox, Edge and Opera but on Chrome sidebar is sometimes on top and sometimes behind footer. When page is loaded and you scroll to bottom sidebar is on top (incorrectly). Then when action is performed on sidebar (for example mouse hovers over inputbox located on sidebar) sidebar is sent back and Chrome displays page correctly. If you would scroll to top (to make footer invisible) and hover mouse over inputbox again, Chrome goes back to displaying sidebar on top.
Here is codepen demonstrating this: codePen
And here is code:

body {
    position: relative;
    height: 160vh;
    font-size: 5vw;
}
input{font-size:2vw;}
#footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 80px;
    color: white;
    background-color: black;
}
#sideAnchor {
    position: fixed;
    top: 0;
    right: 100%;
    width: 30%;
    height: 100%;
}
#side {
    position: absolute;
    top: 0;
    left: 100%;
    width: 100%;
    height: 100%;
    background-color: green;
}
#side input:hover {
    background-color: yellow;
}

        <input type="number" placeholder="Hover over this" />

        This should always be behind footer

   This should always be on top

I have a workaround this so I'm not asking for solution. In my opinion there is a bug in Chrome, what do you think? I'm using Google Chrome 87.0.4280.66, Windows 10


text:
Q: Generic use of SimpleCursorAdapter I am building a database app which should make use of a generic mechanism to read its data and show it to in listview. I am relatively new to Android programming.
I am using the SimpleCursorAdapter but the problem is that I need to design in XML, the row layout view. But I do not want to do this. The reason is that I want the stuff to work generic against any table, like "SELECT * FROM ". Using the SimpleCursorAdapter I need to create a LinearLayout per table record, and add that id to to the constructor.
What I want is to programmatically create the LinearLayout and pass that id to the constructor, but this is not working. I get the ResourceNotFoundException. When trying to add TextViews to the ContentView, this is not working either, the components do not show.
Is this possible at all?
Thanks,
Coenos
Edit:
this is the stacktrace
09-15 16:43:43.547: ERROR/AndroidRuntime(13273): FATAL EXCEPTION: main
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):       android.content.res.Resources$NotFoundException: Resource ID #0x4
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.content.res.Resources.getValue(Resources.java:892)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.content.res.Resources.loadXmlResourceParser(Resources.java:1869)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.content.res.Resources.getLayout(Resources.java:731)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.view.LayoutInflater.inflate(LayoutInflater.java:318)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.ResourceCursorAdapter.newView(ResourceCursorAdapter.java:79)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.CursorAdapter.getView(CursorAdapter.java:182)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.AbsListView.obtainView(AbsListView.java:1427)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1273)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.ListView.onMeasure(ListView.java:1184)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.view.View.measure(View.java:8226)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.view.View.measure(View.java:8226)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.view.View.measure(View.java:8226)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
09-15 16:43:43.547: ERROR/AndroidRuntime(13273):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)

This is the code
Cursor cur = dbAdapter.findAllRecordsByTableName(tableName);

    List<String> columnList = dbAdapter.findColumnsByTableName(tableName);

    String[] columns = columnList.toArray(new String[0]);

    startManagingCursor(cur);

    LinearLayout layout = new LinearLayout(this);
    layout.setId(4);
    int[] to = new int[columns.length];
    int i = 5;
    for (String column : columns) {
        Log.d("this", "column in list :" + column);
        TextView view = new TextView(this);

        view.setId(i);
        to[i-5] = i;
        i++;
        /*
        this.addContentView(view, new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                */
        layout.addView(view);
    }

    Log.d("buildContent2", "total children "+layout.getChildCount());

    SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
            layout.getId(), cur, columns, to);

    this.setListAdapter(mAdapter);

I understand that the LinearLayout with id=4 is not know to the Context, but how can I make it known? Do I need to add it to the Context, but how? This is where my Android knowledge is lacking....


text:
Q: Meteor google maps javascript api how would one go about calling meteor method from inside GoogleMaps.ready callback? I am using dburles:google-maps package.
On the client
GoogleMaps.ready('eventsmap', function(map) {
   google.maps.event.addListener(map.instance, 'click', function(event) {
      Markers.insert({lat: event.latLng.lat(), lng: event.latLng.lng()});
   });
   ...

I tried following:
GoogleMaps.ready('eventsmap', function(map) {
   google.maps.event.addListener(map.instance, 'click', function(event) {
      var lat = event.latLng.lat();
      var lng = event.latLng.lng();
        Meteor.call("insertMarker", lat, lng, function(error, results) {
           if(error) {
              console.log(error.reason);
           } else {
              console.log(results);
           }
        });
   });
   ...

On the server I have "insertMarker" method which will insert marker into Markers collection.
But got event is not defined exception. Any idea? Thank you.

A: Sorry guys, I just wrapped the method call inside if(event){...} conditional. It needed something to trigger the call. It works now, missed that one xD


text:
Q: Proofs of elementary identities on 2 sets Apologies for not having the proper math notation symbols here, but I am trying to disprove that ((A or B) and B complement) is in the subset of A. This is what I have so far:
1.) (B complement and (A or B)) = (B complement and A) or (B complement and B) - Distributive.
2.) (B complement and B) = empty set - Domination on 1.
3.) (B complement and A) or (empty set) = (B complement and A) - Identity on 1 and 2.
From here, I know that (B complement and A) is equal to the ((Universe - B) and A), which is not in the subset of A, but I am not sure how to formally show this.


text:
Q: Laurent series for $f(z)= \frac{1}{ (z-i)(z+2i)}$ I'm struggling with this question. I tried to break $f(z)$ using partial fractions and modify each equation so it looks like $\dfrac{1}{1-z}$ series but that's where I get stuck. Any help would be greatly appreciated.
Expand $f(z)= \dfrac{1}{ (z-i)(z+2i)}$ as a series throughout each of the domains:

*

*$|z|< 1$

*$1 <|z|< 2$

*$2 <|z|< \infty$
This is the partial fractions that I got. (1i/3)/(z+2i)-(1i/3)/(z-i)

A: Let me only give you the secret to doing this; you can go from there.
No matter what, you can express $\frac1{az+b}$ either as $\frac1 b\cdot\frac1{1+az/b}$ or as $\frac1{az}\cdot\frac1{1+b/(az)}$.
It'll be your choice as to which form you take, to make the part after the "$1+$" smaller than $1$ in absolute value.


text:
Q: Why won't this simple jquery work in rails 4 Why won't this code work in rails 4.  I have changed my gemfile so i use the 2.3.2 version of twitter bootstrap.
ruby '1.9.3'
 gem 'rails', '4.0.0'
 gem 'pg'
gem 'cloudinary'
#gem 'less-rails-bootstrap'
gem 'less-rails-bootstrap', github: 'metaskills/less-rails-bootstrap', ref:     'cbe20d4593e21297f7bc3bc6bc6471a7ad18e890'
gem 'therubyracer'
gem 'rails_12factor', group: :production
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'jquery-turbolinks'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
group :doc do
gem 'sdoc', require: false
end

Here is my simple code. I just want to se a div with my facebook comments. I was working before i run bundle install.

Article headline

Indhold tekst tekst tekst.

    <button class="btn btn-large btn-block btn-primary comments-show-button post-button" type="button">Show comments</button>
    <button class="btn btn-large btn-block btn-primary remove-button post-button" type="button">Remove comments</button>


text:
Q: Jquery autocomplete JSON return result from webservice but it is not showing in dropdownlist I do not know what is wrong with this code. alert shows that data has returned from web service but auto-complete still not showing data. I am using ASP.net 2.0 and google jquery link

  $(document).ready(function() {
         $.ajax({
            type: "POST",
            url: "http://localhost/WebService/Service.asmx/getlist2",
            dataType: "json",
            data: "{}",

            contentType: "application/json; charset=utf-8",
            success: function(data) {
         alert("getlist 2");
             alert(data);

                $('#project1').autocomplete({
                    minLength: 2,
                    source: data,

                    focus: function(event, ui) {
                        $('#project1').val(ui.item.TagName);
                        alert(ui.item.TagName);//no alert is fired here
                        return false;
                    },
                    select: function(event, ui) {
                        $('#project1').val(ui.item.TagName);
                        //$('#selectedValue').text("Selected value:" + ui.item.TagID);
                        return false;
                    }
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
     });

and web service method
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Tag> getlist2()
{
    <Tag> tagscollection = new  EntitiesCollection<Tag>();
    ProcessTagList getlisttags = new ProcessTagList();

    string strtag = "";

    Tag tag = new Tag();
    tag.TagName =   strtag;
    tag.UniqueName =   strtag;
    getlisttags.OTag = tag;
    getlisttags.Invoke();
    tagscollection = getlisttags.OTagsCollection;

    ;
      List<Tag> a = new List<Tag>();
    foreach(Tag tagc in tagscollection)
    {
        a.Add(tagc);
    }

    return a;

}

data shown in firebug is:
[{"__type":"myproject.Common.Tag","TagID":"21abf6b1-6d45-41e5-a39b-006e621eeb22","UniqueName":"dotnet","TagName":"dotnet","CreatedAt":"/Date(1255108286850)/"}]
this jquery code shows dropdown list from the webservice used with first jquery example.
$("#tbAuto").autocomplete({
    source: function(request, response) {
        $.ajax({
            url: "http://localhost/myproject/Service.asmx/getlist2",
            data: "{}",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
          //  dataFilter: function(data) { return data; },

            success: function(data) {
                response($.map(data, function(item) {
                    return {
                        value: item.TagName
                    }
                }))
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(errorTrown);
            }
        });
    },
    minLength: 0
});

A: You need to set the autocomplete source property to a collection\array. I do not think your returned data is one although it may contain one. You also need to rename your server side object to provide a label value pair. e.g
{ "id": "1", "label": "StackOverflow", "value": "SO" }
Check the examples out here and use firebug to see how they return the json data.
From the docs

The local data can be a simple Array
  of Strings, or it contains Objects for
  each item in the array, with either a
  label or value property or both. The
  label property is displayed in the
  suggestion menu. The value will be
  inserted into the input element after
  the user selected something from the
  menu. If just one property is
  specified, it will be used for both,
  eg. if you provide only
  value-properties, the value will also
  be used as the label.

Can you paste the json response.

A: Okay, I know you are using asp.net and my example is based on PHP and MySQL, but since your problem seem to be about the JSON format autocomplete is expecting, I am posting anyway.
Get the latest files from the jQuery UI page. The autocomplete need UI Core, UI Widget and UI Position from the base package. You also need the autocomplete widget itself.
This example works well for me:
The HTML:
<div>
    <input id="cities" />
</div>

The script part:
(It sends the search variable to cities.php as cities.php?term=)
$(function() {
  $("#cities").autocomplete({
    source: "backend/cities.php",
    minLength: 2,
    select: function(event, ui) {
      // perhaps do something with these?
      region = ui.item.id;
      country = ui.item.label;
      city = ui.item.value;
      secret = ui.item.secret;
   }
});
});

The PHP in cities.php:
(The variables id, label and value need to be used. Label is used to populate the drop down list. Value is entered into the input box when the label value is clicked in the list).
// important to set header with charset
header('Content-Type: text/html; charset=utf-8');
$term = $_POST["term"];
// some database stuff removed
// loop it through and build array
$n = 0;
    while ($row = $q->fetch()) {
        $row_array[$n]['id'] = $row['City'];
        $row_array[$n]['label'] = $row['Country'];
        $row_array[$n]['value'] = $row['Region'];
        $row_array[$n]['secret'] = 'blabla';
        $n++;
    }
    // encode it to json format
    echo json_encode($row_array);

The JSON sent back:
(When ?term=new york)
[{"id":"New York","label":"United States","value":"New York","secret":"blabla"},{"id":"Minnesota","label":"United States","value":"New York Mills","secret":"blabla"},{"id":"New York","label":"United States","value":"New York Mills","secret":"blabla"}]

So, to recap:

*

*By default, it sends the variable "term" with the search word to the backend page.

*It needs "id", "value" and the "label" variables to be sent back.

*By default the drop down list is populated with the "label"-values.

*By default, clicking in the list will fill out the input box with "value".

*You can put additional variable names and make something with them, but the three above is needed.

*The JSON syntax need to look as provided above.

I hope it helps.

A: Your data is not showing up because autocomplete expects the data in a certain way (id,label and value). See other answers as well.
Your getlist2 functions gives another structure of data (__type, TagID,UniqueName,TagName and CreatedAt).
Try to modify getlist2 to give back the proper syntax.
Your last change to the topic start (jquery autocomplete + .ajax) looks alright, what is not working on that piece of code?


text:
Q: Do I use appositive clause correctly? Can I use appositive clause (in bold) in the following way:

The merits of technology should never be denied, that they eliminate the inconvenience of attending events in person, be it traffic congestions or clash in schedule.

I want to use a appositive clause to help explain what is the merits of technology, is this the acceptable way to do that?

A: I would think an appositive clause would follow a noun. As for your sentence I would reformulate it in this way:

The merits of technology in eliminating the inconvenience of attending events in person, be it traffic congestions or clash in schedule, should never be denied.


text:
Q: WAR extension strategy in Wildfly In a WildFly-project, I have a big WAR-File (about 100 MB) which contains the whole application in JAR-Files (EJBs, GUI, Web Services etc)
In this WAR, there are some Functions which implement a custom Function interface (there are also other classes like AbstractFunction and so on). Now I would like to extend the application with user-provided functions (they should be on the class path which can then be accessed by the application.
The problem is that I can't deploy the functions before the main WAR because Function, AbstractFunction etc. are the the WAR which is not yet deployed.
Adding a WildFly module with the functions fails for the same reason.
One possibility would be to restructure the WAR file so that Function, AbstractionFunction are in an own jar which is deployed separately. Unfortunately, this would be a major refactoring which is not possible at the time being.
So is the only (simple) possibility to put the user-defined functions in a JAR into the WAR-file?

A: You can deploy user code as independent jar/war with EJB. EJB implements Function. Main module can lookup and find them through JNDI. Also you have to make common classes like Function and DTO available for user modules and for main war. The simplest way is share classes from main war. You can add META-INF/jboss-deployment-structure.xml to client modules:
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
<deployment>
    <dependencies>
        <module name="deployment.main.war"/>
    </dependencies>
  </deployment>
</jboss-deployment-structure>

PS
I have similar project with structure:

*

*core.war contains Plugin interface

*set of plugin*.jar (dependent from core.war)

In my core.war I have code like:
 Plugin srv = (Plugin) new InitialContext().lookup(jndi);

And my plugin looks like:
 @Stateless
 public class UserPlugin implements Plugin

JNDI looks like java:global/user-plugin/UserPlugin


text:
Q: How much memory is allocated for int8, int16 and int32 in Golang? I have a simple piece of code where I allocate memory for int8, int16, int32 and int64 types and print out the addresses of the variables:
package main

import (

"fmt"
"runtime"
)

func main() {

    fmt.Println(runtime.Compiler, runtime.GOARCH, runtime.GOOS)

    var i8 *int8
    var i16 *int16
    var i32 *int32
    var i64 *int64

    fmt.Println(&i8)
    fmt.Println(&i16)
    fmt.Println(&i32)
    fmt.Println(&i64)

}

Here is the output I receive:
gc amd64 darwin
0xc00008a020
0xc00008a028
0xc00008a030
0xc00008a038

From here I may conclude that only int16 is using 4 bytes, the other types are using 8 bytes.
Are both my reasoning and the method of checking the allocated memory size correct?
If yes, what would be the advantages of using int8, int32 on a 64-bit architecture system?

A: You are allocating pointers which are all 8 bytes in your example: gc amd64 darwin.
For your example,
package main

import (
    "fmt"
    "runtime"
    "unsafe"
)

func main() {

    fmt.Println(runtime.Compiler, runtime.GOARCH, runtime.GOOS)

    var i8 *int8
    var i16 *int16
    var i32 *int32
    var i64 *int64

    fmt.Println(&i8, unsafe.Sizeof(i8), unsafe.Sizeof(*i8))
    fmt.Println(&i16, unsafe.Sizeof(i16), unsafe.Sizeof(*i16))
    fmt.Println(&i32, unsafe.Sizeof(i32), unsafe.Sizeof(*i32))
    fmt.Println(&i64, unsafe.Sizeof(i64), unsafe.Sizeof(*i64))

}

Output:
gc amd64 linux
0xc00000e030 8 1
0xc00000e038 8 2
0xc00000e040 8 4
0xc00000e048 8 8

For CPU operations it is often most efficient to use the natural word size of the CPU, for example, int or int64 on amd64.
For memory size, for a large number of integers, it can be most efficient to use the smallest integer size that can hold the range of values.
It's a balancing act. Benchmark real code from real applications.


text:
Q: Keep map values into vector I have a set of objects that, during some initializations, I need to keep in an std::map, but after initialization I only need an std::vector. What efficient way is there to save the map's values into a vector?
I'm looking either for something with move semantics, or maybe there's some implementation of a map in Boost that would make this easier.

A: Shouldn't this do the job:
your_vector.reserve(your_map.size());
for(auto& item : your_map) {
    your_vector.push_back(std::move(item.second));
}


text:
Q: "Cannot contact service to set scan periods" - during ble scan I am scanning ble using background service and also from activity. so when background service and activity both running parallel then scanning is not given any beacon. so i am stopping service when scanning activity is open then it gives "Cannot contact service to set scan periods" error. after that scanning is stop in activity

A: I had same setup first - a foreground Activity and a backgound Service, both communicating with BLE peripheral.
But then I have rewritten my Activity just to communicate with the Service - and only the latter communicates with BLE peripheral:
public class MainActivity extends Activity {
    private Intent mServiceIntent;
    private ScanService mService;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
              ScanBinder sb = (ScanBinder) binder;
              mService = sb.getService();
              mService.setActivity(MainActivity.this);
              Utils.showToast(MainActivity.this, "Connected to service");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
              Utils.showToast(MainActivity.this, "Disconnected from service");
              mService.setActivity(null);
              mService = null;
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mServiceIntent = new Intent(this, ScanService.class);
        startService(mServiceIntent);
......

public class ScanService extends Service {
    private Activity mActivity;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (mActivity != null)
            Utils.showToast(this, "Service (re)started");

        return START_STICKY;
    }

    public void setActivity(Activity activity) {
        mActivity = activity;
    }

This kind of communication is described in 9. Exercise: Define and consume local service tutorial by Lars Vogel.


text:
Q: Centralized vs Distributed Version Control on Oracle Right Now I have been tasked with setting up some type of version control for our development server files location. We current use Oracle's Service Cloud called "Right Now". It holds our dev/staging/prod environments for multiple sites.
Basically I need to VC just the dev files.. and not have to carry a local repo. Is this possible? The reason being for no local is there are just tooo many sites to download all locally. I want to open the files in Sublime from the dev server, make changes, save them, then at some point create a commit regarding the files I changed since the last commit. How can this be done.
I would love to use git, but this requires a local repo as far as I can tell. What about SVN? Could this do it? Your suggestions and resource links are appreciated.
~ WB

A: Unfortunately I'm not familiar with Oracle's "Right Now" product so I may be missing something important here. Putting this "Right Now" aside, I can say that Apache Subversion can be a good match for your requirements.

*

*With Subversion you don't need to download the whole repository as you need with Git. Subversion's working copy which you need to svn checkout is much less in size than the whole repository in Git because is represents a particular snapshot of the repository's state in time (it does not contain the whole repo history as in Git).

*You can checkout only a part of a repository. E.g. if a repository contains multiple projects, you can choose which ones to checkout.

*Using sparse directories / shallow checkouts can help you to minimize the size of the working copy by specifying only those modules you require to operate on.


text:
Q: Making a gameObject push the player I am working on a Unity 3D game for Oculus and I have problems with making my objects to apply physics on a player. So getting rid of a CharacterController and using something like a rag doll is not an option.
I am using OVRPlayerController, that has a Rigidbody with mass 1 and a box collider on it. My gameObject has a Rigidbody of mass 100, and a box collider. But when the object hits the player it just goes through it, whereas I want it to push the player in x direction.
I tried using onColliderHit but it doesn't even recognize the collision between the player and the object, so I checked box collider on the object to be a trigger and I use OnTriggerEnter() to recognize the collision.
I tried to translate the player's position on collision, but player gets positioned to weird places out of my map for some reason. Here is what I use:
info.transform.Translate(new Vector3( -0.5f, 0.0f, 0.0f));
info.transform.rotation = Quaternion.identity;

I also tried to manually set the x position of the player but this doesn't work, and I know I am not supposed to do it.
I searched for answers for a long long time, so please don't answer to this with something like "oh, have you tried googling it, there are a lot of similar questions" etc.

A: It should be detecting the collision just fine, as long as one of the box colliders has a non-kinematic (Is Kinematic = false) rigidbody attached.
Make sure Is Trigger is false, and you specified a material for your collider.
Also try messing with the other properties on the rigidbody, such as Collision Detection and Mass. The unity docs indicate that your mass should be no more or less than 100 times that of other rigidbodies.


text:
Q: Opencart from MAMP to Web hosting I have created an Opencart shop on my locally hosted site on MAMP. Now I have moved the site to a hosting company, I need to know what I need to update for the shop to work. I know that I need to edit the "config.php" files to point to the new links. Then upload the SQL db to the server.
I would be grateful for step by step instructions to get this to work. My opencart config files:
// HTTP
define('HTTP_SERVER', 'http://localhost:8888/shop/');

// HTTPS
define('HTTPS_SERVER', 'http://localhost:8888/shop/');

// DIR
define('DIR_APPLICATION', '/Applications/MAMP/htdocs/shop/catalog/');
define('DIR_SYSTEM', '/Applications/MAMP/htdocs/shop/system/');
define('DIR_IMAGE', '/Applications/MAMP/htdocs/shop/image/');
define('DIR_LANGUAGE', '/Applications/MAMP/htdocs/shop/catalog/language/');
define('DIR_TEMPLATE', '/Applications/MAMP/htdocs/shop/catalog/view/theme/');
define('DIR_CONFIG', '/Applications/MAMP/htdocs/shop/system/config/');
define('DIR_CACHE', '/Applications/MAMP/htdocs/shop/system/storage/cache/');
define('DIR_DOWNLOAD', '/Applications/MAMP/htdocs/shop/system/storage/download/');
define('DIR_LOGS', '/Applications/MAMP/htdocs/shop/system/storage/logs/');
define('DIR_MODIFICATION', '/Applications/MAMP/htdocs/shop/system/storage/modification/');
define('DIR_UPLOAD', '/Applications/MAMP/htdocs/shop/system/storage/upload/');

// DB
define('DB_DRIVER', 'mysqli');
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_DATABASE', 'opencart');
define('DB_PORT', '3306');
define('DB_PREFIX', 'oc_');

I have contacted my hosting company and the address of folder is:
/home/cluster-sites/3/c/MYWEBSITE.co.uk/public_html/shop

What do I need to change?
My SQL db is set up on phpMyAdmin as "opencart". How do I transfer this to my hosting - do i need to keep naming exactly the same?
I have searched for a step by step guide but so far no luck. Any help would be appreciated.

A: I found a great step by step guide here:
https://www.squirrelhosting.co.uk/hosting-blog/hosting-blog-info.php?id=47
Is is now working for me


text:
Q: Showing date on main.gsp I want to show date on main.gsp. Do I just call g:formatDate? Because I did that but date is not rendered:

          <sec:ifLoggedIn>
              You are logged in as:<sec:username/> (<g:link controller='logout'>Logout</g:link>)
          </sec:ifLoggedIn>
          <sec:ifNotLoggedIn>
             <g:link controller='login'>Login</g:link>
          </sec:ifNotLoggedIn>

        Date:<g:formatDate format="yyyy-MM-dd" date="${date}"/>

A: Are you sure that the 'main' controller action returns the 'date' variable containing the actual date? For example:
def main =  {
    [date: new Date()]
}

Another solution would be to instanciate the Date class directly in your gsp code.
<g:formatDate format="yyyy-MM-dd" date="${new Date()}"/>


text:
Q: React Render Array of object in parent-child realationship with checkbox I want to render the object of array in parent and child relationship tree structure with checkbox to select any of the child or parent to do some operation in react

A: I made a sandbox where I built what I thought you meant. You can see the autcome here: https://5dhss.csb.app/
import React, { useState } from "react";
import "./styles.css";

const objectOfArrays = {
  manfred: ["kreuz", 12, "abc"],
  dieter: [1, 2, 3, 4, 5, 6, 7, 7, 8],
  robert: ["bar", "321", "foo"]
};

export default function App() {
  const [{ row, key }, setSelected] = useState({ row: -1, key: null });

  const keys = Object.keys(objectOfArrays);

  const rowNumbers = keys.reduce((acc, key) => {
    for (let j = 0; j < objectOfArrays[key].length; j += 1) {
      if (!acc.includes(j)) acc = [...acc, j];
    }

    return acc;
  }, []);

  return (

        {row < 0 ? (
          <>Click into a field</>
        ) : (
          <>
            You selected [{row}, {key}]
          </>
        )}

            {keys.map(key => {
              return {key}	;
            })}

          {rowNumbers.map(row => (

              {keys.map(key => (
                 {
                    setSelected({ key, row });
                  }}
                >
                  {objectOfArrays[key][row]}

              ))}

          ))}

  );
}


text:
Q: Angular and Router - unexpected page refresh Was struggling until realised that if I bind click event to method that does not exist in my component, Angular refreshes page. I think its because of routerLink, because if I remove it, I get an expected error that method checkUser() does not exist. Why this happens?
<a md-button
    routerLink="articles"
    routerLinkActive="menu-active"
    (click)="checkUser()"
    >Articles</a>

A: The routerLink directive applied to an a element sets an href attribute upon this element.
I guess the same exception is thrown on click but the event still bubbles up and then the default behavior is executed and the page location is changed. As this happens really fast, you don't notice the error.
Try preserving the console logs even after page relaod, the error should be there.


text:
Q: Show that $\frac {\sin x} {\cos 3x} + \frac {\sin 3x} {\cos 9x} + \frac {\sin 9x} {\cos 27x} = \frac 12 (\tan 27x - \tan x)$ The question asks to prove that -
$$\frac {\sin x} {\cos 3x} + \frac {\sin 3x} {\cos 9x} + \frac {\sin 9x} {\cos 27x}  = \frac 12 (\tan 27x - \tan x) $$
I tried combining the first two or the last two fractions on the L.H.S to allow me to use the double angle formula and get $\sin 6x$ or $\sin 18x$ but that did not help at all.
I'm pretty sure that if I express everything in terms of $x$, the answer will ultimately appear but I'm also certain that there must be another simpler way.

A: In general, we have
$$\sum_{k=1}^n \dfrac{\sin\left(3^{k-1}x \right)}{\cos\left(3^kx\right)} = \dfrac{\tan\left(3^nx\right)-\tan(x)}2$$
We can prove this using induction. $n=1$ is trivial. All we need to make use of is that
$$\tan(3t) = \dfrac{3\tan(t)-\tan^3(t)}{1-3\tan^2(t)}$$
For the inductive step, we have
$$\sum_{k=1}^n \dfrac{\sin\left(3^{k-1}x \right)}{\cos\left(3^kx\right)} = \dfrac{\tan\left(3^nx\right)-\tan(x)}2$$
Adding the last term, we obtain
$$\sum_{k=1}^{n+1} \dfrac{\sin\left(3^{k-1}x \right)}{\cos\left(3^kx\right)} = \dfrac{\tan\left(3^nx\right)-\tan(x)}2 + \dfrac{\sin\left(3^{n}x \right)}{\cos\left(3^{n+1}x\right)} = \dfrac{\tan\left(3^{n+1}x\right)-\tan(x)}2$$
where we again rely on $(\spadesuit)$ to express $\tan\left(3^{n+1}x\right)$ in terms of $\tan\left(3^{n}x\right)$.

A: @MayankJain @user,
I don't know that the case for $n=1$ is trivial, especially for someone in a trig class currently. I will offer a proof without induction using substitution instead. Mayank, to see that this is the case for $n=1$, convert the RHS of the equation as follows:
$\dfrac{1}{2} \cdot \big{[}\dfrac{\sin 3x}{\cos 3x} - \dfrac{\sin x}{\cos x}]$ = (1) $\dfrac{1}{2} \cdot \big(\dfrac{\sin 3x \cos x - \cos 3x \sin x}{\cos 3x \cos x}\big{)} $ = (2) $ \dfrac{1}{2} \cdot \dfrac{\sin 2x}{\cos 3x \cos x}$ = (3) $\dfrac{1}{2} \cdot \dfrac{2\sin x \cos x}{\cos 3x \cos x}$ = $\dfrac{\sin x}{\cos 3x}$
This is pretty heavy on trig identities. We get equivalence (1) by multiplying out the fraction, equivalence (2) because $\sin(u - v) = \sin u \cos v - \cos u \sin v$, equivalence (3) because $\sin 2x = 2\sin x \cos x$, and, finally, (4) by cancellation.
Now, if you are unfamiliar with induction, substitution will help here as an alternative method. Since you can now derive the equivalence for the 'trivial' case, set $3x = u$ for the second case, and $9x = v$ for the third. Then you already know $\dfrac{\sin u}{\cos 3u} = \dfrac{1}{2} \cdot (\tan 3u - \tan u)$, and similarly, $\dfrac{\sin v}{\cos 3v} = \dfrac{1}{2} \cdot (\tan 3v - \tan v)$. So now we can re-write the original expression $\dfrac{\sin x}{\cos 3x} + \dfrac{\sin u}{\cos 3u} + \dfrac{\sin v}{\cos 3v}$ as $\dfrac{1}{2} \cdot (\tan(3x) - \tan x + \tan(9x) - \tan(3x) + \tan(27x) - \tan(9x))$ and everything cancels out except the desired expression: $\dfrac{1}{2} \cdot (\tan(27x) - \tan(x))$.

A: For $\cos y\ne0,$ $$\tan3y-\tan y=\dfrac{\sin(3y-y)}{\cos3y\cos y}=\dfrac{2\sin y\cos y}{\cos3y\cos y}$$
$$\implies\tan3y-\tan y=2\dfrac{\sin y}{\cos3y}$$
Set $y=x,3x,9x$  and add to recognize the Telescoping series


text:
Q: Why can we allocate a 1 PB (10^15) array and get access to the last element, but can't free it? As known: http://linux.die.net/man/3/malloc

By default, Linux follows an optimistic memory allocation strategy.
  This means that when malloc() returns non-NULL there is no guarantee
  that the memory really is available. In case it turns out that the
  system is out of memory, one or more processes will be killed by the
  OOM killer.

And we can successfully allocate 1 Petabyte of VMA (virtual memory area) by using malloc(petabyte);: http://ideone.com/1yskmB
#include <stdio.h>
#include <stdlib.h>

int main(void) {

    long long int petabyte = 1024LL * 1024LL * 1024LL * 1024LL * 1024LL;    // 2^50
    printf("petabyte %lld \n", petabyte);

    volatile char *ptr = (volatile char *)malloc(petabyte);
    printf("malloc() - success, ptr = %p \n", ptr);

    ptr[petabyte - 1LL] = 10;
    printf("ptr[petabyte - 1] = 10; - success \n");

    printf("ptr[petabyte - 1] = %d \n", (int)(ptr[petabyte - 1LL]));

    free((void*)ptr);   // why the error is here?
    //printf("free() - success \n");

    return 0;
}

Result:
Error   time: 0 memory: 2292 signal:6
petabyte 1125899906842624
malloc() - success, ptr = 0x823e008
ptr[petabyte - 1] = 10; - success
ptr[petabyte - 1] = 10

And we can successfully get access (store/load) to the last member of petabyte, but why do we get an error on free((void*)ptr);?
Note: https://en.wikipedia.org/wiki/Petabyte

*

*1000^5    PB  petabyte

*1024^5    PiB pebibyte - I use it
So really if we want to allocate more than RAM + swap and to work around overcommit_memory limit, then we can allocate memory by using VirtualAllocEx() on Windows, or mmap() on Linux, for example:

*

*16 TiB (16 * 2^40 bytes) then we can use example from Nominal Animal's answer: https://stackoverflow.com/a/38574719/1558037

*127 TiB (127 * 2^40 bytes) then we can use mmap() with flags MAP_NORESERVE | MAP_PRIVATE | MAP_ANONYMOUS and fd=-1: http://coliru.stacked-crooked.com/a/c69ce8ad7fbe4560

A: (This is not an answer, but an important note on anybody working with large datasets in Linux)
That is not how you use very large -- on the order of terabytes and up -- datasets in Linux.
When you use malloc() or mmap() (the GNU C library will use mmap() internally for large allocations anyway) to allocate private memory, the kernel limits the size to the size of (theoretically) available RAM and SWAP, multiplied by the overcommit factor.
Simply put, we know that larger-than-RAM datasets may have to be swapped out, so the size of the current swap will affect how large allocations are allowed.
To work around that, we create a file to be used as "swap" for the data, and map it using the MAP_NORESERVE flag. This tells the kernel that we don't want to use standard swap for this mapping. (It also means that if, for any reason, the kernel cannot get a new backing page, the application will get a SIGSEGV signal and die.)
Most filesystems in Linux support sparse files. This means that you can have a terabyte-sized file, that only takes a few kilobytes of actual disk space, if most of its contents are not written (and are thus zeroes). (Creating sparse files is easy; you simply skip over long runs of zeroes. Hole-punching is more difficult, as writing zeroes does use normal disk space, other methods need to be used instead.)
Here is an example program that you can use for exploration, mapfile.c:
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    const char    *filename;
    size_t         page, size;
    int            fd, result;
    unsigned char *data;
    char           dummy;

    if (argc != 3 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
        fprintf(stderr, "\n");
        fprintf(stderr, "Usage: %s [ -h | --help ]\n", argv[0]);
        fprintf(stderr, "       %s MAPFILE BYTES\n", argv[0]);
        fprintf(stderr, "\n");
        return EXIT_FAILURE;
    }

    page = sysconf(_SC_PAGESIZE);
    if (page < 1) {
        fprintf(stderr, "Unknown page size.\n");
        return EXIT_FAILURE;
    }

    filename = argv[1];
    if (!filename || !*filename) {
        fprintf(stderr, "No map file name specified.\n");
        return EXIT_FAILURE;
    }

    if (sscanf(argv[2], " %zu %c", &size, &dummy) != 1 || size < 3) {
        fprintf(stderr, "%s: Invalid size in bytes.\n", argv[2]);
        return EXIT_FAILURE;
    }

    if (size % page) {
        /* Round up to next multiple of page */
        size += page - (size % page);
        fprintf(stderr, "Adjusted to %zu pages (%zu bytes)\n", size / page, size);
    }

    do {
        fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
    } while (fd == -1 && errno == EINTR);
    if (fd == -1) {
        fprintf(stderr, "Cannot create %s: %s.\n", filename, strerror(errno));
        return EXIT_FAILURE;
    }

    do {
        result = ftruncate(fd, (off_t)size);
    } while (result == -1 && errno == EINTR);
    if (result == -1) {
        fprintf(stderr, "Cannot resize %s: %s.\n", filename, strerror(errno));
        unlink(filename);
        close(fd);
        return EXIT_FAILURE;
    }

    data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE, fd, 0);
    if ((void *)data == MAP_FAILED) {
        fprintf(stderr, "Mapping failed: %s.\n", strerror(errno));
        unlink(filename);
        close(fd);
        return EXIT_FAILURE;
    }

    fprintf(stderr, "Created file '%s' to back a %zu-byte mapping at %p successfully.\n", filename, size, (void *)data);

    fflush(stdout);
    fflush(stderr);

    data[0] = 1U;
    data[1] = 255U;

    data[size-2] = 254U;
    data[size-1] = 127U;

    fprintf(stderr, "Mapping accessed successfully.\n");

    munmap(data, size);
    unlink(filename);
    close(fd);

    fprintf(stderr, "All done.\n");
    return EXIT_SUCCESS;
}

Compile it using e.g.
gcc -Wall -O2 mapfile.c -o mapfile

and run it without arguments to see the usage.
The program simply sets up a mapping (adjusted to a multiple of the current page size), and accesses the first two and last two bytes of the mapping.
On my machine, running a 4.2.0-42-generic #49~14.04.1-Ubuntu SMP kernel on x86-64, on an ext4 filesystem, I cannot map a full petabyte. The maximum seems to be about 17,592,186,040,320 bytes (244-4096) -- 16 TiB - 4 KiB --, which comes to 4,294,967,296 pages of 4096 bytes (232 pages of 212 bytes each). It looks like the limit is imposed by the ext4 filesystem, as the failure occurs in the ftruncate() call (before the mapping is even tried).
(On a tmpfs I can get up to about 140,187,732,541,440 bytes or 127.5 TiB, but that's just a gimmick, because tmpfs is backed by RAM and swap, not an actual storage device. So it's not an option for real big data work. I seem to recall xfs would work for really large files, but I'm too lazy to format a partition or even look up the specs; I don't think anybody will actually read this post, even though the information herein has been very useful to me over the last decade or so.)
Here's how that example run looks on my machine (using a Bash shell):
$ ./mapfile datafile $[(1<<44)-4096]
Created file 'datafile' to back a 17592186040320-byte mapping at 0x6f3d3e717000 successfully.
Mapping accessed successfully.
All done.

.

A: I believe that your problem is that malloc() does not take a long long int as its argument. It takes a size_t.
After changing your code to define petabyte as a size_t your program no longer returns a pointer from malloc. It fails instead.
I think that your array access setting petabyte-1 to 10 is writing far, far outside of the array malloc returned. That's the crash.
Always use the correct data types when calling functions.
Use this code to see what's going on:
long long int petabyte = 1024LL * 1024LL * 1024LL * 1024LL * 1024LL;
size_t ptest = petabyte;
printf("petabyte %lld %lu\n", petabyte, ptest);

If I compile in 64 bit mode it fails to malloc 1 petabyte. If I compile in 32 bit mode it mallocs 0 bytes, successfully, then attempts to write outside its array and segfaults.


text:
Q: Extracting data from a table in a windows application I'm attempting to extract data from a windows application. The data is displayed like an excel table within the program, but it has no functionality for automatically exporting or parsing the data for real-time automated analysis, which is what I need.
I have seen the thread at Screen-scraping a windows application in c# and going through it got me to a point where I can extract data from notepad perfectly, but doesn't seem to work for the table format that this program is displaying.  My guess is that WM_GETTEXT isn't really designed to get the data this program displays. It could wind up being 10 colums x 1000 rows feasibly, but maybe that doesn't matter.  Anyways, I don't know what might be the correct way to go about getting this data.  Or maybe WM_GETTEXT can do it and I just don't have it set up correctly? I'm not sure, but I've tried it a lot of different ways and none have gotten me anything but the title of the window (yes I did also find the child handles and those returned nothing)
Hypothetically I might be able to get it to work by sending the program keystrokes and copying/pasting the data into a file, saving, and then reading that file, but my thought is that might be cumbersome and weird as I'll need my program to check the data for updates pretty regularly.
I know it can be done, I just don't know where to go to figure it out.  I haven't ever had a need to interact with an external program before so this is all new to me. Most of the material I find online has to do with screen scraping web pages, which this is not. I'm using C#, but I'd use whatever language I need to in order to make it work. Any help would be much appreciated, thank you!


text:
Q: apt-get always installs old version of node.js I want to install 11.x version of Node.js on my Ubuntu sevrer using apt/apt-get, but it always installs version 8.10.x. Is there a way to install the latest 12.x or 11.x version without using nvm?
I've tried apt-get update, purging nodejs, using commands below:
curl -sL https://deb.nodesource.com/setup_11.x | sudo -E bash -
sudo apt-get install -y nodejs

None of above helped. I'm still getting an old verion of Node.js

A: The implementations of languages provided by operating systems tend to lean towards stability within their particular ecosystem (i.e: they play nice with everything else in the repositories). If you wish to use a newer version I recommend asdf which allows you install multiple versions of implementations of various languages including Node.


text:
Q: Push object to array in js or jquery? In my Script.js I am trying to push the object to array=>array of objects.
$("#save_filter").click(function(){
    var filter_saved = new Object();//Create new object to store the filter have been saved.
    var customer_type_selected = $('#id_customer_type :selected').text();
    var list_tag_selected = $("#tag_checked").val();
    var filter_name = $("#put_filter_name").val();

    // Save filter name to the object={tag:[2,3,], customer_type:'TDO', more...}
    filter_saved = {
        customer_type: customer_type_selected,
        tag: list_tag_selected
    };
    var array_obj_filter_saved = []

    //I am trying...
    array_obj_filter_saved.push(filter_saved);//push every objects to array
    alert(array_obj_filter_saved.length);
});

My Array will be like this  assciated array
array_obj_filter_saved = {"time1":filter_saved1,"time2":filter_saved2}

Anybody know how can I push every object to a array or associated array?
*** filter_saved this an object  it will create every time base on options in   form(customer_type_selected(choicefield),list_tag_selected(checkboxs))

A: The line below is not an array, it is an object. You can only have integer indexes in arrays, and you use [] to define an array (like you did in your example).
array_obj_filter_saved = {"time1":filter_saved1,"time2":filter_saved2}

You cannot push objects onto an object, instead you set them, using the specific index:
array_obj_filter_saved["keyName"] = "value";

A: This is very unclear to me. Is array_obj_filter_saved an array or not?
If you want to append all the elements of an Array to another Array, you can use the concat method:
var a1 = ["a", "b", "c"], a2 = ["d", "e"];
var a3 = a1.concat(a2); // a3 is ["a", "b", "c", "d", "e"]

A: Just like this:
var x= { a: 1};
x.b = 2;


text:
Q: why jquery .attr() become case sensitive in this case? i know that jquery .attr() is case insensitive to attribute name, but when i create an element from document created by code, it becomes case sensitive.
here is code sample that explain the problem:
var mydoc = document.implementation.createDocument('a:b','c',null);
var myElement = mydoc.createElement("myelement");
myElement.setAttribute("attr1","val1");

alert($(myElement).attr("attr1"));//val1
alert($(myElement).attr("Attr1"));//undefined! , why?

var myElement2 = document.createElement("myelement2");
myElement2.setAttribute("attr1","val1");

alert($(myElement2).attr("attr1"));//val1
alert($(myElement2).attr("Attr1"));//val1

i have tested it on chrome 22.0 and jquery 1.8.
UPDATE:
it seems that it is not jquery issue.
console.log(myElement.attributes['attr1']); //val1 , OK
console.log(myElement.attributes['Attr1']); //undefined ???

console.log(myElement2.attributes['attr1']); //val1 , OK
console.log(myElement2.attributes['Attr1']); //val1 , OK

A: it's due to the type of documents, just specify the type of document (HTML for example):
var mydoc = document.implementation.createHTMLDocument()

http://jsfiddle.net/ouadie/wwNhw/

A: You need to create a documentType (https://developer.mozilla.org/en-US/docs/DOM/DOMImplementation.createDocumentType) of html and pass it to the createDocument method as the 3rd parameter
var dt = document.implementation.createDocumentType('html', '', '');
var mydoc = document.implementation.createDocument('a:b','c',dt);

var myElement = mydoc.createElement("myelement");
myElement.setAttribute("attr1","val1");

console.log(myElement.attributes['attr1']); //val1 , OK
console.log(myElement.attributes['Attr1']); //val1 , OK !!!


text:
Q: How to avoid null values in a stream We are in the case where we have a corrupted data X in the list, and where the presence of this corrupted data X prevents an operation on Y data of the same type as X. . This isn't normal, and we must shield the code so that the presence of the corrupt data X does not block the use of other valid data.
I used Optional with an operation filter, for filter if the name is null we skip.
     Personne personne = null;
     String name= personne.getName();
     try {
        Optional<Personne> abstractPersonne=
      APIPersonne.getAllPersonne(currentPersonne.getMethod())
                                                            .stream()
                                                            .filter(e -> e.getName() != null && e.getName().equals(name))
                                                            .findAny();
  if (abstractPersonne.isPresent())
    personne= abstractPersonne.get();
}

Is there a way to avoid the test of (e-> e.getName != null) ?

A: Just reverse the condition, if you are sure that the variable "name" is null safe. For example instead of
e.getName().equals(name)

use
name.equals(e.getName())

A: Invert the condition: name.equals(e.getName())
.filter(e -> name.equals(e.getName()))

A: You can check with the Optional.ofNullable(T) like this

*

*check the value is not null

*check with your string (list value and your desired string are equals or not )

Optional<Personne> abstractPersonne = APIPersonne
                    .getAllPersonne(currentPersonne.getMethod())
                    .stream()
                    .filter(e -> Optional.ofNullable(e).isPresent()  && e.getName().equals(name))
                    .findAny();
            if (abstractPersonne.isPresent())
                personne= abstractPersonne.get();


text:
Q: node express + formidable + form with multipart/form-data how to get req.body? I'm using mean stack
and formidable to upload file
the form has a multipart/form-data attribute
exports.create = function(req, res) {
    console.log(req.body);
}

but the rq.body is empty.
How can I get it ?

A: If you are using formidable for multipart upload, you can get req.body fields in
form.parse(req, function(err, fields, files)

fields.item


text:
Q: What is The remote server returned an error: (400) Bad Request? I am trying to add contacts to the constant contact site n there  i am getting following exception
The remote server returned an error: (400) Bad Request.
i am using ASp.net C# application for inserting my records.
can  any one tell me the solution ,or why i am getting the above error?
Thanks in advance

A: This website is useful.

Introduction:
Why I am getting this exception? What is the cause of this error. Developers are always curious to know the root cause of an
  exception, even though they found the solution from elsewhere. So what
  is the reason of this exception (400 Bad Request).The answer is
  security. Security is an important feature for any application.
  ASP.NET try to his best to give you more secure application
  environment as possible. One important security feature is related to
  URLs. Because there are various ways a hacker can try to access server
  resource. Therefore it is important to make your application as secure
  as possible. Fortunately, ASP.NET provides this security by throwing
  an exception of Bad Request whenever he feels. In this Article I am
  try to present when ASP.NET feels to throw this exception. You will
  also see some new ASP.NET 4 features which gives developers some
  control on this situation.


text:
Q: How to create new array based on position in python? I have an array (b) and I want to add new rows according to the position of 1s in the (a) array.
a=np.array([1,1,0,1,0]

b=np.array([1,2,3,4,5])

I'd need to make a new array like this:
Output: array([1,2,3,4,5],[1,0,0,0,0],[0,1,0,0,0],[0,0,0,1,0])

How could this be done? Loop and append? Many thanks in advance

A: One-liner with broadcasting -
In [14]: np.vstack((b,np.arange(len(a)) == np.flatnonzero(a)[:,None]))
Out[14]:
array([[1, 2, 3, 4, 5],
       [1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 0, 1, 0]])

With zeros-initialized array -
In [17]: s = a.sum()

In [18]: c = np.zeros((s,len(a)),dtype=b.dtype)

In [20]: c[np.arange(s),np.flatnonzero(a)] = 1

In [21]: np.vstack((b,c))
Out[21]:
array([[1, 2, 3, 4, 5],
       [1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 0, 1, 0]])

A: def solution(a, b):
    result = [b]
    for i, elem in enumerate(a):
        if elem == 1:
            temp = [0] * len(a)
            temp[i] = 1
            result.append(temp)
    return np.array(result)


text:
Q: margin between books not the size in css 3d book cover I have this book cover design using css and modernizer:
HTML :

CSS:
/* Fallback styles */
.book {
  display: inline-block;
  box-shadow: 5px 5px 20px #333;
  margin: 10px;
}

.book img { vertical-align: middle; }

/*
 *  In order for this to work, you must use Modernizer
 *  to detect 3D transform browser support. This will add
 *  a "csstransforms3d" class to the HTML element.
 *
 *  Visit http://modernizr.com/ for installation instructions
 */

.csstransforms3d  .books {
  -moz-perspective: 100px;
  -moz-transform-style: preserve-3d;
  -webkit-transform-style: preserve-3d;
}

.csstransforms3d  .book {
  position: relative;
  -moz-perspective: 100px;
  -moz-transform: rotateY(-3deg);
  -webkit-transform: perspective(100) rotateY(-3deg);
  outline: 1px solid transparent; /* Helps smooth jagged edges in Firefox */
  box-shadow: none;
  margin: 0;
}

.csstransforms3d  .book img {
  position: relative;
  max-width: 100%;
}

.csstransforms3d  .book:before,
.csstransforms3d  .book:after {
  position: absolute;
  top: 2%;
  height: 96%;
  content: ' ';
  z-index: -1;
}

.csstransforms3d  .book:before {
  width: 100%;
  left: 7.5%;
  background-color: #5a2d18;
  box-shadow: 5px 5px 20px #333;
}

.csstransforms3d  .book:after {
  width: 5%;
  left: 100%;
  background-color: #EFEFEF;
  box-shadow: inset 0px 0px 5px #aaa;
  -moz-transform: rotateY(20deg);
  -webkit-transform: perspective(100) rotateY(20deg);
}
.csstransforms3d  #book2:before { background-color: #333; }
.csstransforms3d  #book3:before { background-color: #254053; }

Now in action width of next+1/last book is elder. i check with more books and see only first book have a normal size. the margin between books is different and not the size
how do can i fix this problem?
demo Fiddle
Picture

A: First of all, you don't really need moz prefixes, here. Right now, only unprefixed and webkit prefixed browsers are in use
Second, as Vinc199789 said, you have a perspective set for FF that don't have for the others
.csstransforms3d  .books {
    -moz-perspective: 100px;
    -moz-transform-style: preserve-3d;
    -webkit-transform-style: preserve-3d;
}

should be
.csstransforms3d  .books {
    -webkit-perspective: 100px;
    perspective: 100px;
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
}

You have the same problem in the book class, you have different styles between different prefixes.
But now, for the real issue: when you are working with this setting, you can choose to give the book series a global perspective or a constant perspective.
Global pespective

.book {
  display: inline-block;
  box-shadow: 5px 5px 20px #333;
  margin: 0px;
}

.book img { vertical-align: middle; }

.books {
  -webkit-perspective: 100px;
  perspective: 100px;
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.book {
  position: relative;
  -webkit-transform: rotateY(-3deg);
  transform: rotateY(-3deg);
}

.book img {
  position: relative;
  max-width: 100%;
}

.csstransforms3d  .book:before,
.csstransforms3d  .book:after {
  position: absolute;
  top: 2%;
  height: 96%;
  content: ' ';
  z-index: -1;
}

.csstransforms3d  .book:before {
  width: 100%;
  left: 7.5%;
  background-color: #5a2d18;
  box-shadow: 5px 5px 20px #333;
}

.csstransforms3d  .book:after {
  width: 5%;
  left: 100%;
  background-color: #EFEFEF;
  box-shadow: inset 0px 0px 5px #aaa;
  -moz-transform: rotateY(20deg);
  -webkit-transform: perspective(100) rotateY(20deg);
}

Constant perspective

.book {
  display: inline-block;
  box-shadow: 5px 5px 20px #333;
  margin: 0px;
}

.book img { vertical-align: middle; }

.books {
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.book {
  position: relative;
  -webkit-transform: perspective(100px) rotateY(-3deg);
  transform: perspective(100px) rotateY(-3deg);
}

.book img {
  position: relative;
  max-width: 100%;
}

.csstransforms3d  .book:before,
.csstransforms3d  .book:after {
  position: absolute;
  top: 2%;
  height: 96%;
  content: ' ';
  z-index: -1;
}

.csstransforms3d  .book:before {
  width: 100%;
  left: 7.5%;
  background-color: #5a2d18;
  box-shadow: 5px 5px 20px #333;
}

.csstransforms3d  .book:after {
  width: 5%;
  left: 100%;
  background-color: #EFEFEF;
  box-shadow: inset 0px 0px 5px #aaa;
  -moz-transform: rotateY(20deg);
  -webkit-transform: perspective(100) rotateY(20deg);
}

Notice the different use of the perspective


text:
Q: How to read Ionic Webview version in Javascript? Is there any way to read the webview version using JS in Ionic during runtime ?
I want to execute some code blocks based on the WKWebview version in iOS .
if (webview version is > 3.x) {

} else {
// older webview versions.

}

A: Try this.platform.userAgent(), where platform is an instance of import { Platform } from '@ionic/angular';, this should return a string containing the browser details of the environment you are running in.
For example my local browser running the app via ionic serve returned - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36.
You should be able to parse this string to find the relevant details you're after when the app is running in WKWebview.


text:
Q: How do I code a simple boolean method? (Can't recall how to to code the one below) I need to create a method largerThan(See below) which takes a Rectangle object as an argument and returns true if the invoking object has a greater area than the object which is the argument and will return false otherwise. I've done this before but simply can't recall how to complete the code in this part of the method. Any help will be truly appreciated! NOTE: Professor doesn't want us to use the "this" operator! :-(
public class Rectangle
{

  private double length;

  private double width;

    public Rectangle()
    {
      length = 0;
      width = 0;
    }
    public Rectangle(double l, double w)
    {
      length = l;
      width = w;
    }
    public void setRectangle(double l, double w)
    {
      length = l;
      width = w;
    }
    public double getLength()
    {
      return length;
    }
    public double getWidth()
    {
      return width;
    }
    public double perimeter()
    {
      return length + width;
    }
    public double Area()
    {
      return length*width;
    }
    **public boolean largerThan(Rectangle r1)
    {
      if()
        return True;
      else
        return False;
    }**
    public String toString()
    {
       return "Length is " + length + " width is " + width;
    }
}

A: public boolean largerThan(Rectangle otherRec){
    return this.Area() > otherRec.Area();
}

A: You can do it like this:
public boolean largerThan(Rectangle r1){
    return this.Area() > r1.Area();
}

A: Your skeleton is basically there, now take the English words of what you want to do:

returns true if the invoking object has a greater area than the object which is the argument and will return false otherwise

And turn it in to code:
public boolean largerThan(Rectangle r1)
{
  if(this.Area() > r1.Area())
    return True;
  else
    return False;
}


text:
Q: Is a data model driven resource Id a facet of the resource or of the database? My examples are going to involve pseudo C# code for discussion purposes, but this is not specific to any single language or database tooling.
Take a simple model
Customer { string Id }
Using RavenDB when I store new Customer() it will generate an id for me at execution time, suppose "Customers/234". In this scenario I'm fine with accepting that id is a facet of RavenDB. Fundamentally this is absolutely no different than Guid.NewGuid().ToString() as it creates an identifier that has no human understandable meaning and merely achieves the goal of global uniqueness (to this database). This is just arguably a nicer version of a guid, and will create better URLs and allow a human to communicate their id if it's ever needed far easier than a string of 16 random hex characters.
In another scenario take:
User { string UserName, string Id }
In this scenario I want to place true semantic meaning into my Id as opposed to just an unique number.
With RavenDB this could be accomplished similar to:
store.Conventions.DocumentKeyGenerator = (entity) =>
{
   User user = entity as User;
   if(user == null)
      return  defaultKeyGeneration (entity);

  return "Users/" + user.UserName;
}

Which then during this store operation you would end up with "Users/dotnetchris"
I could also approach this by instead of having User have a simple property for Id, to use a read-only property:
User {
    string Id { get { return "Users/" + UserName }

I'm having a hard time deciding which of these is the proper place for this construct.
I'm leaning towards it should be included in the class directly, as this gives you information that it will be easy to load this object by id from user input without actually needing to query to the datbase to find Users.Where(user.UserName == "dotnetchris")

A: It seems highly dependent on how the data may or may not be referenced in the database. If the  "full" ID (i.e. Users/name) is required for some kind of constraint in the database design, then keeping it close to the database would be a better option, but if that's not the case, you will benefit more from keeping it as a piece of the domain model to allow for flexibility in the code (as per your final code sample).

A: As a rule I strive for every single identifier to be owned by the application and not the database. The only reason I will pass ownership of a model's identity is performance reasons, e.g. a SQL table that needs replicated and has 500 million rows.