text:
Q: C++ Open File Dialog doesn't show up with OpenCv library I build windows form C++ which it contains one button to open the file then show the file text that I choose on the text box but the issue is the file dialog box not shown no idea why and am sure nothing wrong on my code.
Is something wrong in my setting?
private: System::Void btnOpenImage_Click(System::Object^  sender, System::EventArgs^  e)
{
    //Stream;
    IO::Stream^ myStream;

    OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;

    openFileDialog1->InitialDirectory = Directory::GetCurrentDirectory();
    openFileDialog1->Filter = "Image Files (JPEG,GIF,BMP,PNG,ICO)|*.jpg;*.jpeg;*.gif;*.bmp;*.png;*ico";
    openFileDialog1->FilterIndex = 2;
    openFileDialog1->RestoreDirectory = true;

    if ( openFileDialog1->ShowDialog() ==System::Windows::Forms::DialogResult::OK)
    {
        file_path_temp = "image_0003.jpg";
        txtImgUrl->Text = file_path_temp;

        IntPtr pointer_temp = Marshal::StringToHGlobalAnsi(file_path_temp);
        const char* input_location = static_cast<const char*>(pointer_temp.ToPointer());
        cv::Mat imgOriginalScene = cv::imread(input_location, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR);
        Marshal::FreeHGlobal(pointer_temp);
    }
}


text:
Q: fieldset hide/show when choose dropdown I have a form with 5 different products and attributes for it, i want only show a single product field-set(1 product) when user choose from dropdown menu and increment
$scope.choices = [{id:'choice1'},{id:'choice1'},];

//New element adding function
$scope.addNewChoice = function(){
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo})
}

//Remove an evidence item from the form
$scope.removeChoice = function(){
    var lastItem = $scope.choices.length-1;
    $scope.choices.splice(lastItem);
}

this is how i make dynamic form field but inside a each row there is my fieldset but i want only show particular product fieldset when user choose that product

A: inside HTML formfield set
<fieldset ng-if='showField($index,"item")'>
...........
</fieldset>

$scope.showField = function(index,item){

       if($scope.choices[index]['item'] == item){

           return true;
       }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery How to write text to ID selector - multiple ID My div has two ID and I'm trying to add text to these div with use one id selector. How to do?
jQuery
function fn(k) {
    $('#' + k).text('test')
};

html

A: Quote from MDN:

The id global attribute defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).

You can never have more than one id for the element.

A: ID should be unique across the HTML page. You can have multiple classes though.
So,

 is wrong.

 is right.
Hope its clear.
To select the classes using JQuery do something like -
$( ".myClass" ).css( "border", "3px solid red" );


text:
Q: Form items selection order in .NET I have a Form with 5 textbox. When I press tab I want each of them to be selected in a particular order like tbox1, tbox5, tbox2,...
How do I do it?

A: You'll want to set the .TabIndex property on the controls.
This will allow you to set the order in which they are focused when tabbing through the UI.  Keep in mind, however, that there is no unique constraint on this property among the controls.  You can set multiple controls to have the same TabIndex and the ordering of those particular controls would revert back to whatever it would be by default with no explicit tab ordering.

A: You need to set the tab index of each element. You can set this in the Visual Studio designer.

A: Set the TabIndex property of the text box control.
 <asp:TextBox ID="txtFirstName" runat="server" CssClass="txtRegForm" MaxLength="50" TabIndex="1"></asp:TextBox>

 <asp:TextBox ID="txtLastName" runat="server" CssClass="txtRegForm" MaxLength="50" TabIndex="2"></asp:TextBox>

 <asp:TextBox ID="txtStreetName" runat="server" CssClass="txtRegForm" MaxLength="50" TabIndex="3"></asp:TextBox>

The value in tab index decides the orde to switch from one text box to another


text:
Q: Firefox event.target issue Generally speaking, and if I recall correctly I've used this at least a dozen times before, but for some god-forsaken reason it doesn't work since this morning... Somebody have a clue?
JSFiddle Example
HTML:
<button id="testID" onclick="foo()">
test me
</button>

<button id="testID2" onclick="foo(this)">
test me 2
</button>

JS:
function foo(event){
alert(event.target.id);
}

A: In the first example, you pass undefined to event. In the second example, you pass the button to event.
If you want the event object, then you have to pass the event object. That's called event, but I don't know how standard it is for it to be created for intrinsic event attributes.
In general, you are better off binding your event handlers with JavaScript.

function foo(event){
    alert(event.target.id);
}

var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", foo);
}
<button id="testID">
test me
</button>

<button id="testID2">
test me 2
</button>


text:
Q: How to delete and shift values in a pandas df column I have a pandas df that I want to manipulate so it's ordered. So for the df below, I'd like ['I'] to be ordered. So values would read 10-50. I have 2 options to do this;
1) Try to delete values in Column ['G'] or ['H']. So if values are == X then delete.
2) Try to merge values in the same Columns when they are  == X
import pandas as pd

d = pd.DataFrame({
        'J' : [10,'B','C','C',50],
        'I' : ['B',20,30,40,'C'],
        'H' : ['X','A','C','B','X'],
        'G' : ['X', 'B', 'A','B','X'],
        })

Output:
   G  H   I   J
0  X  X   B  10
1  B  A  20   B
2  A  C  30   C
3  B  B  40   C
4  X  X   C  50

Option 1 is we delete X from Column H and the intended output would be:
   G  H   I   J
0  X  B  10
1  B  A  20   B
2  A  C  30   C
3  B  B  40   C
4  X  C  50

Option 2 is we merge on X in Column G-H and the intended output would be:
   G   H   I   J
0  XX  B  10
1  B   A  20   B
2  A   C  30   C
3  B   B  40   C
4  XX  C  50

I have played around with df = df.drop(df.H == 'X') but this deletes the whole row.

A: Option 1:
You can use shift the values to the left for rows that meet the criteria df.H == 'X':
With the following variable definitions:
hij = ['H', 'I', 'J']
x = df.H=='X'

We can write the shift assignment concisely.
df.loc[x, hij] = df.loc[x, hij].apply(lambda x: x.shift(-1), axis=1)
outputs:
    G   H   I   J
0   X   B   10  NaN
1   B   A   20  B
2   A   C   30  C
3   B   B   40  C
4   X   C   50  NaN

Option 2:
Same principle, but two statements are needed.
we can concat H to G
df.loc[x, 'G'] = df.loc[x, 'G'] + df.loc[x, 'H']
# df.loc[x, 'G'] = df.loc[x, ['G, 'H']].sum(axis=1)
# or df.loc[x, ['G', 'H']].apply(np.sum, axis=1)
# or df.loc[x, 'G'] = df.loc[x, ['G', 'H']].apply(lambda x: (x + x.shift(-1))[0], axis=1)

and shift as in option 1
df.loc[x, hij] = df.loc[x, hij].apply(lambda x: x.shift(-1), axis=1)
final output:
    G   H   I   J
0   XX  B   10  NaN
1   B   A   20  B
2   A   C   30  C
3   B   B   40  C
4   XX  C   50  NaN

A: More general solution should be change condition if in G or H columns is X, then merge together and shift by condition:
d = pd.DataFrame({
        'J' : [10,'B','C','C',50, 60],
        'I' : ['B',20,30,40,'C', 'D'],
        'H' : ['X','A','C','B','X', 'Y'],
        'G' : ['Y', 'B', 'A','B','X', 'X'],
        }, columns=list('GHIJ'))
print (d)
   G  H   I   J
0  Y  X   B  10
1  B  A  20   B
2  A  C  30   C
3  B  B  40   C
4  X  X   C  50
5  X  Y   D  60

m = d[['G','H']].eq('X').any(axis=1)
print (m)

0     True
1    False
2    False
3    False
4     True
5     True
dtype: bool

d['H'] = d['G'] + d['H']
d[m] = d[m].shift(-1, axis=1)
print (d)
    G   H   I    J
0  YX   B  10  NaN
1   B  BA  20    B
2   A  AC  30    C
3   B  BB  40    C
4  XX   C  50  NaN
5  XY   D  60  NaN

A: For you question one , replace the 'X' as np.nan , then sorted the data frame (shift the value)
d.replace({'H':{'X':np.nan}}).apply(lambda x: sorted(x, key=pd.isnull),1).fillna('')
Out[234]:
   G  H   I  J
0  X  B  10
1  B  A  20  B
2  A  C  30  C
3  B  B  40  C
4  X  C  50

For question two: using np.where create the d.G firstly , then we do the same as above
d.G=np.where((d.G=='X')&(d.H=='X'),'XX',d.G)

d.replace({'H':{'X':np.nan}}).apply(lambda x: sorted(x, key=pd.isnull),1).fillna('')

Out[242]:
    G  H   I  J
0  XX  B  10
1   B  A  20  B
2   A  C  30  C
3   B  B  40  C
4  XX  C  50

A: You can go for np.where and shift i.e
ndf = pd.DataFrame(np.where((d['H']=='X')[:,None],
                       d.assign(H=d.H+d.G).shift(-1,axis=1), #only d.shift(...) in case you dont want to add
                       d), columns=d.columns)

    G  H   I    J
0  XX  B  10  NaN
1   B  A  20    B
2   A  C  30    C
3   B  B  40    C
4  XX  C  50  NaN


text:
Q: Calculated Column Formula Syntax Error I am trying to setup a list that I can use to calculate deadlines for an approval process. I was asked to set the deadline to 5 working days, and exclude the 2 weekend days. I found a really helpful article, and was attempting to adjust their formula to work with my needs.
However when I made the adjustments, SharePoint threw a syntax error. Here are the formulas:
Original:
=IF(OR(WEEKDAY(CurrentDate)=1,WEEKDAY(CurrentDate)=7),CurrentDate+3,IF(OR(WEEKDAY(CurrentDate)=5,WEEKDAY(CurrentDate)=6),CurrentDate+4,IF(OR(WEEKDAY(CurrentDate)>1,WEEKDAY(CurrentDate)<4),CurrentDate+2)))

Adjusted:
=IF(WEEKDAY(CurrentDate)=1),CurrentDate+5,IF(WEEKDAY(CurrentDate)=7),CurrentDate+6,IF(OR(WEEKDAY(CurrentDate)>1,WEEKDAY(CurrentDate)<6,CurrentDate+7))

I am assuming I am making a simple mistake (fledgling SP Admin), but could use some expert advice.

A: Missing parens...
Try this:
=IF(WEEKDAY(CurrentDate)=1,CurrentDate+5,IF(WEEKDAY(CurrentDate)=7,CurrentDate+6,IF(OR(WEEKDAY(CurrentDate)>1,WEEKDAY(CurrentDate)<6),CurrentDate+7)))

Here's a shorter version that will probably do what you need:
= CurrentDate+5 + IF(WEEKDAY(CurrentDate+5)=1,1,0) + IF(WEEKDAY(CurrentDate+5)=7,2,0)

(No nested IFs!!!)

A: You have several small problems:

*

*Extra close parenthesis after condition in first two IF's

*The last IF has several issues:

*

*a close parenthesis for the OR

*now you have three nested if so you need a close parenthesis more at the end

*What should happen if WEEKDAY(CurrentDate) = 6?

The best way to play with a formular like this is to use Excel:

*

*Create a new notebook

*Enter a date in A1

*Label A1 to be CurrendDate

*Now you can play with the formular in A2 (or any other cell)

My suggestion:
=IF(WEEKDAY(CurrentDate)=1,CurrentDate+5,IF(WEEKDAY(CurrentDate)=7,CurrentDate+6,CurrentDate+7))
or if you can assume that items are only created on working days
=CurrentDate+7


text:
Q: Book layout Contents, Chapter, Section, my goal is to get new style of Table of Contents, new style of Chapter and new style of section. I there is one more: how to change itemize native symbol for a black square?
Table of Contents: text on the left side in the middle of two lines. And there is a big white space non normal one.

Chapter: number of chapter in a roman in a black box on the line above the chapter name, Name of chapter on right side, another line under name of Chapter

Section: I want to add a black square at the begining of each section name.

I appreciate that
thank You

A: You can use the packages titlesec for the titles of the sectional units, and titletoc for the entries in the ToC; a little example producing the layout for chapters and sections, and the redefinition of the label for itemize to use a square (feel free to adjust the settings according to your needs):
\documentclass{book}
\usepackage{xcolor}
\usepackage[explicit]{titlesec}
\usepackage[dotinlabels]{titletoc}

% chapter tiltes formatting
\titleformat{\chapter}[display]
  {\normalfont\sffamily\bfseries\LARGE}
  {\renewcommand{\thechapter}{\Roman{chapter}}\hspace*{0.5em}\colorbox{black}{%
    \parbox[c][1.2cm][c]{1cm}{%
      \centering\textcolor{white}  {\Huge\thechapter}}}}
  {-1ex}
  {\titlerule\vspace{.7ex}\filleft\MakeUppercase{#1}}
  [\vspace{.2ex}\titlerule]
% chapter tiltes spacing
\titlespacing*{\chapter}{0pt}{50pt}{80pt}

% section tiltes formatting
\titleformat{\section}
  {\normalfont\Large\bfseries}{\MySecSquare\ \thesection}{1em}{#1}
\titleformat{name=\section,numberless}
  {\normalfont\Large\bfseries}{\MySecSquare}{1em}{#1}

% formatting for chapter entries in ToC
\titlecontents{chapter}
  [1.5em]{}
  {\sffamily\bfseries\contentslabel{1.5em}}
  {\hspace*{-1.5em}}
  {\hfill\sffamily\bfseries\contentspage}
% formatting for section entries in ToC
\titlecontents{section}
  [3.8em]{}
  {\sffamily\contentslabel{2.3em}}
  {\hspace*{-2.3em}}
  {\titlerule*[1pc]{.}\sffamily\contentspage}

% Square to be used in itemize
\newcommand\MySquare{%
  \leavevmode\hbox to 1.2ex{\hss\vrule height .9ex width .7ex depth -.2ex\hss}}
% Square to be used in section titles
\newcommand\MySecSquare{%
  \leavevmode\hbox to 1.2ex{\hss\vrule height 1.3ex width 1.1ex depth -.2ex\hss}}

% First level of itemize uses a square
\renewcommand\labelitemi{\MySquare}

\begin{document}

\tableofcontents

\chapter{Test Chapter One}
\section{Test Section One One}
\begin{itemize}
\item First item.
\item Second item.
\item Third item.
\end{itemize}
\section{Test Section One Two}
\chapter{Test Chapter Two}
\chapter{Test Chapter Three}

\end{document}

An image of the ToC showing the requested formatting for the entries, and an image of the first numbered chapter, showing the desired chapter titles formatting, the use of a black square in itemize and the section titles formatting:

There's a little detail that deserves some thought: the black box used to typeset the chapter number; in the code above I used a \parbox of fixed width (I chose 1cm) and this will be insufficient for "large" roman numerals (such as VIII), One option is to increase the width of the \parbox, but then small numerals (such as I) might not look good inside a too wide box. Another option is to have a default width of, say 1cm, and let the widht of the \parbox increase just for those numbers requiring more spacing; here's now the code implementing this idea:
\documentclass{book}
\usepackage{xcolor}
\usepackage[explicit]{titlesec}
\usepackage[dotinlabels]{titletoc}

\newlength\BoxWd
\setlength\BoxWd{1cm}
\newlength\Aux

% chapter tiltes formatting
\titleformat{\chapter}[display]
  {\normalfont\sffamily\bfseries\LARGE}
  {\renewcommand{\thechapter}{\Roman{chapter}}%
    \settowidth\Aux{\textcolor{white}{\Huge\thechapter}}
    \ifnum\Aux>\BoxWd
      \setlength\BoxWd{\Aux}
    \else\fi
    \hspace*{0.5em}\colorbox{black}{%
    \parbox[c][1.2cm][c]{\BoxWd}{%
      \centering\textcolor{white}{\Huge\thechapter}}}}
  {-1ex}
  {\titlerule\vspace{.7ex}\filleft\MakeUppercase{#1}}
  [\vspace{.2ex}\titlerule]
% chapter tiltes spacing
\titlespacing*{\chapter}{0pt}{50pt}{80pt}

% section tiltes formatting
\titleformat{\section}
  {\normalfont\Large\bfseries}{\MySecSquare\ \thesection}{1em}{#1}

% formatting for chapter entries in ToC
\titlecontents{chapter}
  [1.5em]{}
  {\sffamily\bfseries\contentslabel{1.5em}}
  {\hspace*{-1.5em}}
  {\hfill\sffamily\bfseries\contentspage}
% formatting for section entries in ToC
\titlecontents{section}
  [3.8em]{}
  {\sffamily\contentslabel{2.3em}}
  {\hspace*{-2.3em}}
  {\titlerule*[1pc]{.}\sffamily\contentspage}

% Square to be used in itemize
\newcommand\MySquare{%
  \leavevmode\hbox to 1.2ex{\hss\vrule height .9ex width .7ex depth -.2ex\hss}}
% Square to be used in section titles
\newcommand\MySecSquare{%
  \leavevmode\hbox to 1.2ex{\hss\vrule height 1.3ex width 1.1ex depth -.2ex\hss}}

% First level of itemize uses a square
\renewcommand\labelitemi{\MySquare}

\begin{document}

\tableofcontents

\chapter{Test Chapter One}
\setcounter{chapter}{17}% just for the example
\chapter{Test Chapter Eighteen}

\end{document}

An image of the titles for chapters I and XVIII:


text:
Q: Notice: Undefined variable With error_reporting(E_ALL); removed, my script works fine, however when I uncomment it, the following notice appears:

Notice: Undefined variable: messages in /home/www/test/register/html/form_1.html.php on line 11

form_1.html.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">

    <meta name="generator" content=
          "HTML Tidy for Linux/x86 (vers 7 December 2008), see www.w3.org">
    <title>Sign in or Register</title>

<?php displayMessages($messages) ?>

On line 11 there is a function call, which basically iterates over an array argument:
function displayMessages($array)

{
    if (!empty($array) && isset($array))
    {
        foreach ($array as $number => $error)
        {
            echo '' . "* $error" . "
";
        }
    }
    elseif (empty($array) || !isset($array) )
    {
        echo "";
    }

    elseif (empty($array) || !isset($array))
    {
        $array = array();
        $array = null;
    }

}

I've added the if condition to check if its empty, because sometimes I will pass an empty array.
This is a small part of these three files, it's supposed to be a registration form:

*

*index.php

*output.php

*form_1.html.php

All found here ( http://pastie.org/1062886 )
The index file checks if the user has filled in out the values and validates them, however if they haven't it'll place an error in the respective error array, the display error function is supposed to display them if there are values in the array passed to it.
I bet the solution is pretty basic, but I am a noob and its making me pull my hair out.

A:
<?php displayMessages($messages) ?>

That variable does not exist at that point in time.

<?php if(isset($messages)) displayMessages($messages); ?>

Calling isset later on in your function won't fix that: your argument has already been set to null (as $messages did not exist), and $array surely exists as a function argument.

A: For the displayMessages($messages) function call, make sure $messages exist:
if (isset($messages)) {
  displayMessages($messages);
}

empty() already checks if the variable is set, so the && !isset($array) checks are unnecessary in your code.
The condition for the second elseif branch is equivalent to the first elseif condition, so the second elseif block will never be entered.


text:
Q: Find Value "age" with class name bs4 and Python 2.7 HTML:
<div class="person" age="52"

I want to get the value of age with bs4
I have tried:
from bs4 import BeautifulSoup

soup = BeautifulSoup(source, "lxml") #source is the page.text
age = soup.find("div", { "class": "person" })["age"]

But every time I run this, I end up with a None value as if the element doesn't exist.


text:
Q: Create React App Excluding mapbox-gl explicitly from transpilation Only in production using vercel my Mapbox map doesn't work.
This is the error message I get, which links to the mapbox documentation:

An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling

On the official documentation it says we should select a set of compatible transforms.

0.2%, not dead, not ie 11, not chrome < 51, not safari < 10

Which I did, but this did not work:
package.json
"production": [
      ">0.2%",
      "not dead",
      "not ie 11",
      "not chrome < 51",
      "not safari < 10",
      "not op_mini all"
],

We can as well use import mapboxgl from '!mapbox-gl'; to exclude GL JS explicitly from transpilation. Which also gives me an error message.
Or we can configure this centrally in webpack.config.js which is not accessible using react-create-app.
Since I do not want to use react-scripts eject I installed react-app-rewired following this StackOverflow post
My configuration looks like this:
module.exports = {
    use: {
        loader: 'babel-loader',
        options: {
            ignore: ['./node_modules/mapbox-gl/dist/mapbox-gl.js']
        }
    }
}

But that doesn't work either.
Does someone know a sure way to fix this mapbox error? Or is what I have already tried wrong somehow?
GitHub issue

A: I've found an answer searching deeper on the GitHub issue which worked.
zacharyliu commented on 23 Dec 2020

One workaround for Create React App, where the bundler config is not
configurable, is to use Webpack's inline loader syntax.
First, install the worker-loader package (yarn add worker-loader).
Then add the following snippet somewhere in your app, ideally right
below your imports:
// eslint-disable-next-line import/no-webpack-loader-syntax
mapboxgl.workerClass =
require('worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker').default;
You probably need the eslint-disable line so Create React App doesn't
error out the build.

Since I do not use yarn I did
npm install worker-loader --save-dev

Then on my js file
import mapboxgl from 'mapbox-gl';
mapboxgl.workerClass = require('worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker').default; // eslint-disable-line

The // eslint-disable-line comment disables the linter rule for just that line.


text:
Q: Alternatives to Curl in CentOS is there any other efficient alternative clients to CURL in Centos by which I can send a PUT request to Upload a file to the webserver that is installed in the host?
Thank you

A: Curl is the de-facto command line tool for that sort of malarkey over http
to transfer files you can also use:
ftp
sftp
scp
smbclient
I could go on, you will need to be more specific


text:
Q: May I get a SQLite View on JSON format? I am using Firefox SQLIte plugin and I have an option to export as CSV. Is it possible to do it on JSON?
Thank you

A: SQLite is a relational database and CSV is a natural textual representation of tabular data, as seen in the relational model. JSON is a textual represenation of an object. As such, it's not really suited for the representation of tabular data.
That said, you can use the CSV file produced from the SQLite database to generate JSON output.

A: I used sqlite studio to convert result to json. It is open source it does a good job! Although you might need to massage the json data a bit because it contains things like DDL, etc.


text:
Q: How can I produce the same/similar layout with the fonts in (La)TeX? The below document is from 1965 (scanned PDF) and I really like it. Any idea about producing this layout with the included fonts. I'm sorry for not being able to provide my own work about this as I'm very new to LaTeX.
Document

A: Welcome to StackExchange!
The typeface for the title (INSTRUMENT NOTES) is Warren Chappell's Lydian, first designed in 1938. The sans serif type is Futura designed (at least to start) by Paul Renner. For some strange reason, the two typefaces are found together rather more than one would expect.
Cheers.

A: *

*In the title of your question you mention "typeface" (font).

*If you look at the document properties of the PDF then you see the following (also see here). But I am not sure if these are the actual fonts since you mention that it is a scanned PDF.

*

*Or consider Fran's comment: https://tug.org/FontCatalogue/

*But if you are looking to re-create the layout etc., then I repeat my comments: (1) If you are very new to LaTeX then maybe don't start with a huge project like mimicking a special template, start small instead. (2) Maybe have a look at learners' material like this.


text:
Q: Invalid Endblock tag in django I am receiving an error message when I go to one of my pages in my Django project, as it is saying that the End-block tag is invalid (asks whether I remembered to register or load). The error looks like this:

My code for this template - (login.html) - is below:
{% extends "learning_logs/base.html" %}

{% block content %}

    {% if form.errors %}

Your username and password didn't match. Please try again.'

    {% endif %}

    <form method="post" action="{% url 'users:login' %}">
    {% csrf_token %}
    {{ form.as_p }}

    <button name="sumbit">log in</button>
    <input type="hidden" name="next" value="{% extends 'learning_logs/index.html' %}" />
    </form>

{% endblock content %}

I am very confused, and I am wondering whether anyone knows what the problem is?
Thanks
Milo

A: <input type="hidden" name="next" value="{% extends 'learning_logs/index.html' %}" />

Above line contains {% extends .... %}. To prevent being interpreted as a extends tag, use templatetag tag:
<input type="hidden" name="next" value="{% templatetag openblock %} extends 'learning_logs/index.html' {% templatetag closeblock %}" />

A: use {% endblock %} instead o f {% endblock content %}

A: for me it was wrongly auto-formatted html file. Check auto-formatting for html files.


text:
Q: Query Folder tree for Size and export to a log on a server Im looking to query the my documents folder for size, but also list the subfolders for size and export to a directory. I found some of this online and am trying to tweak to my needs but having issues with the export part, any help is GREATLY appreciated! :
$startFolder = "C:\Users"

$colItems = (Get-ChildItem $startFolder | Measure-Object -property length -sum)
"$startFolder -- " + "{0:N2}" -f ($colItems.sum / 1MB) + " MB"

add-content \\server\logs$\DirSize\log.log "$(gc env:computername)"

$colItems = (Get-ChildItem $startFolder -recurse | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object)
foreach ($i in $colItems){
    {
        $subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum)
        $i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB" | add-content \\server\logs$\DirSize\log.log}}

Right now it is opening all folders under the C:\User\"User", can I limit to just one subdirectory under C:\Users\"User"? Thanks again!

A: Give this go:
$log = "C:\logfile.log"
$startFolder = "C:\Users"
$colItems = Get-ChildItem $startFolder  | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object
foreach ($i in $colItems){
   $itemSum = Get-ChildItem ("$startFolder\" + $i.Name) -recurse | Measure-Object -property length -sum
   "$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1MB) + " MB" >> $log
   }

This will output all the folders sizes within the given $startFolder and output the result to a log file ($log) that will look like this:
Start file: 'C:\test'
C:\test\config -- 0.00 MB
C:\test\docs -- 0.38 MB
C:\test\files -- 0.03 MB
C:\test\Help -- 7.28 MB
C:\test\inbox -- 0.00 MB
C:\test\install -- 0.00 MB
C:\test\jobs -- 0.00 MB

Stepping down 2 levels:
$log = "C:\logfile.log"
$startFolder = "C:\Users"
$colItems = Get-ChildItem $startFolder  | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object
foreach ($i in $colItems){
   $itemSum = Get-ChildItem ("$startFolder\" + $i.Name) -recurse | Measure-Object -property length -sum
   "$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1MB) + " MB" >> $log
   $colItems2 = Get-ChildItem ("$startFolder\" + $i.Name)  | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object
   foreach ($j in $colItems2){
        If($j -ne $null){
            $itemSum2 = Get-ChildItem ("$startFolder\" + $i.Name +"\"+ $j.Name) -recurse | Measure-Object -property length -sum
            "-->$startFolder\$i\$j -- " + "{0:N2}" -f ($itemSum2.sum / 1MB) + " MB" >> $log
        }
   }
}

A: This will recurse all subdirectories of the tree and get their respective sizes:
Param($Path = $(throw "Missing directory")
,$CSVFile = $(throw "Missing logfile")
)

Function GerDirSize($PathDir)
{
    #Gets subdirectories
    $dirs = Get-ChildItem $PathDir | Where-Object {$_.PsIsContainer}

    #Check if the list is empty
    if($dirs -ne $null)
    {
        foreach($dir in $dirs)
        {
            #Gets size of current directory
            $itemSum = Get-ChildItem $dir.FullName -recurse | Where-Object {!$_.PsIsContainer} | Measure-Object -Property length -Sum
            $itemSum = "{0:N2}" -F ($itemSum.sum / 1MB)
            $result = $dir.FullName + ";" + $itemSum
            Add-Content $CSVFile -Value $result

            #Gets size of subdirectories
            GerDirSize($dir.FullName)
        }
    }
}

GerDirSize $Path

Name it GetDirSize.ps1 and use it as follows:
GetDirSize.ps1 "c:\temp" "c:\temp\logfile.log"

The result will be:
C:\temp\directory1;10.34
C:\temp\directory1\subdirectory1;2.07
C:\temp\directory1\subdirectory1\subsub1;0.00
C:\temp\directory1\subdirectory2;6.21
C:\temp\directory1\subdirectory3;0.00
C:\temp\directory2;4.14
C:\temp\directory3;10.34
C:\temp\directory3\subdirectory1;4.14
C:\temp\directory3\subdirectory1\subdirectory1;2.07
C:\temp\directory4;0.00


text:
Q: Can I see which of the legendary swords I picked when I completed the quest with Shaxx? I have 3 characters in Destiny and I've just completed the mission step for the exotic sword where I had to do 500 kills with arc abilities and gather 10 rare materials from Spinmetal on earth, on my Warlock.
On my 2nd character I picked up a legendary sword as well but this character is now at the PvP step. After picking up the sword on that character, at some point I purchased the 3rd sword from Shaxx, a feature that became available with Taken King I think.
The question now is. On my 3rd character I have turned in the materials with Shaxx and I'm ready to pick the legendary sword. In order to get exotic versions of all swords I need to pick the type I purchased, so that on each character I've picked a different kind.
I can't remember which one I picked on my 2nd character and which one I bought, however.
Is my only option to complete the PvP step on my 2nd character so that I can see which kind of ability I need to use, or is there some information somewhere that shows me what I picked?
Summary:

*

*My warlock picked the arc sword when he turned in materials with Shaxx

*My titan picked either void or solar when he got to that point

*I later then purchased either void or solar to complete the two I already had

*Can I see somewhere now which one I picked on my 2nd character, or do I need to wait for the ability-step to see which ability I need to use?

To clarify for comment

*

*I have all 3 legendary swords, none exotic yet

*On my Warlock (1st character) I just now completed the step where I had to gather 10 rare spinmetal items and kill 500 mobs with Arc abilities, this is clearly for the Arc exotic sword.

*On my Titan I am on a previous step, where I now have to kill 25 people with Sword in PvP, this is before the ability-step

*I purchased the 3rd sword to complement the two I then had but I cannot remember which one I picked from Shaxx on my titan and which one I subsequently purchased. Either I picked Void on my titan and then purchased the solar sword, or vice versa.

*Can I see which one I picked on my titan, or do I just have to wait until the ability-kill step to see which ability to use?

A: Luckily for you, any sword kills count towards that step in the quest line. So simply go into the world and into Crucible with any sword currently owned and get the kills.
Following that, it is very easy to determine because of the type of element required to get kills with.

*

*Dark Drinker (void): void kills paired with relic iron, Mars

*Bolt Caster (arc): arc kills paired with spin metal, Earth

*Raze-Lighter (fire): fire kills paired with helium filaments, Moon

I currently have all 3 of these.

A: A Sword Reforged Part 1 applies to all of your swords, and can in fact trigger A Sword Reforged Part 2 (the ability kills/material gathering quest) for all swords separately once turned in, so long as all the swords you have are above 280 Light and completely upgraded.  So, you should be able to give both swords to one character and complete ASR P1, then trigger ASR P2 for both swords.
As an aside, don't do the void sword on your titan, neither kills while inside the bubble nor kills while buffed by the bubble count as void ability kills for the quest.


text:
Q: Get user follower count with 1.1 - 410 Gone I'm trying to build a 'Follow' button with a vertical followers count above it.  I had a solution working until Twitter retired the 1.0 API today and now require an Oauth solution.  My question, what is the best, easiest solution for this (preferably JS).
Here is the old solution
$.getJSON("https://api.twitter.com/1/users/show.json?callback=?&screen_name=twitter",

function(data) {
    $('.here').text(data);
});

And the error I'm getting now
GET https://api.twitter.com/1/users/show.json?callback=jQuery20205200183007400483_1371012819892&screen_name=twitter&_=1371012819893 410 (Gone)

A: Firstly, according to official sources:

You are discouraged from performing OAuth operations via client-side Javascript. You should perform these requests server-side. If you want the user interaction to be more client-side, the AJAX call should probably be a secure one to your own backend to initiate the tweeting process.

There isn't any easy way to perform client side requests to the new 1.1 API via AJAX. You should use some server-side language to perform this transaction, like php.

You're getting 410 (Gone) response code from their API. Let's see what this actually means:

Indicates that the resource requested is no longer available and will not be available again. This should be used when a resource has been intentionally removed and the resource should be purged. Upon receiving a 410 status code, the client should not request the resource again in the future. [Emphasis my own]

Now let's take a look at the latest twitter API news:

As of yesterday, (June 11th 2013), the previously deprecated v1.0 API was retired. This means that the resource will not be available again, and you need to progress onto the v1.1 API.
The v1.1 API requires authenticated requests, usually using OAuth or 'application-specific'.
Not sure why, but you already posted the most helpful answer as a comment, but yes that's a simple library I wrote to help you guys out transitioning to v1.1 of the twitter API.
Your response: GET https://api.twitter.com/1/[Emphasis my own] contains the API version in the URL.
In closing, any twitter url's with /1/ instead of /1.1/ will no longer take on any requests whatsoever, and you will always get a 410 (Gone) response. Time to move to 1.1!

A: Since Twitter stopped providing an API that doesn't require authentication for simple read-only operations like getting the follower count, they deserve to be scrapped.
We'll use YQL to get the Twitter page of the user, then parse out the follower count. This also works on the client alone, without same-origin restrictions:

function getFollowerCount(username, callback) {
  $.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'http%3A%2F%2Ftwitter.com%2F" + username + "'%20and%20xpath%3D'%2F%2Finput%5B%40id%3D%22init-data%22%5D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys", function (data) {
    callback(data.query.results.input.value.match(/followers_count":(\d+)/)[1]);
  });
}

getFollowerCount('dandv', function (count) {
  $('#follower-count').text(count)
});

Of course, this is somewhat brittle and depends on Twitter keeping the same markup - a hidden input element after the closing .

A: i follow this step.and to get twitter follower count
use this code
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=Android';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$follow_count=$twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();
            $testCount = json_decode($follow_count, true);
echo "
";
echo $testCount[0]['user']['followers_count'];
echo "
";

you can change the "screen_name" and get the follower count.
cheers.


text:
Q: Make Jquery Capty effect on data came from ajax request How can make capty effect on data load from ajax request?
I have some dive in main page and have a load more request from ajax, the capty work fine for main data but not work on data loaded from ajax request and i try to add capty function in ajax result but older div display black screen.
how can i use capty for data came from ajax request?
index:
<!doctype html>

<meta charset="utf-8">
<title>Capty</title>
<link rel="stylesheet" href="css/jquery.capty.css">

detail 1

info 1

more

css:
@CHARSET "UTF-8";

#holder{
    padding: 0px 0px;
    margin: 20px auto;
    width: 800px;
    background:#CC9;
}
#more {
    padding:10px 10px;
    background:#CCF;
    width: 30px;
    margin: 50px auto;
    cursor:pointer;
    float: left;
}
.box {
    float:right;
    margin:5px 7px;
    height:163px;
    width:198px;
    background: #F2F2F2;
    border: 1px solid #2A5F86;
}

.detail {
    width:198px;
    height:163px;
    background: none;
}
.info {
    margin: 0px auto;
    width: 178px;
    height: 148px;
    background: none;
    border: 0px solid #DDDDDD;
    padding: 0px 0px;

    overflow-x: hidden;
    overflow-y: hidden;
    position: relative;
}
div.capty-caption {
    background-color: #000;
    color: #FFF;
    font-size: 11px;
    text-shadow: 1px 1px 0 #222;
    border-radius: 0px 0px 3px 3px;
    width: 198px;
    max-width: 198px;
    min-width: 198px;
    height: 163px;
    min-height:163px;
    max-height:163px;
}

div.capty-caption a {
    color: #318DAD;
    font-size: 11px;
    text-decoration: none;
    text-shadow: none;
}

.capty-wrapper {
    height: 150px;
    overflow-x: hidden;
    overflow-y: hidden;
    position: relative;
    width:198px;
    min-width:198px;
    max-width:198px;
    height: 163px;
    min-height:163px;
    max-height:163px;
    background:none;
}

ajax:

detail 1

info 1

jQuery Capty - A Caption Plugin - http://wbotelhos.com/capty
plugin also available on github.

A: When you load data from ajax, its elements are not automatically updated with triggers.
When you load your ajax, you need to call .capty() on them as well.
Here is an example:
function(data){
    $(".box:last").after(data);
    $(".detail",".box:last").capty({
       height:     163,
       width:      200,
       opacity:    .8,
       animation: 'fade',
       speed:      400
    }) ;
});

Pay attention to the sequence in the $() selector. The first is really the last.
So selector will find ".box:last" first, and only then will do find() in it searching for class "detail"
=== Edit start ===
The code after your change will work except that the data returned by ajax must contain unique ids while your ajax/more.html is a copy of what you have in the main body.
Please consider changing ids.
When I changed them myself it worked:

        detail 2
        info 2

Please see fiddle: http://jsfiddle.net/5K3nq/ where I copied your source into.
Instead of calling $.post() I have called function greg() which returns what your ajax was supposed to return (except it contains my changes.) Scroll the Result window to the right to see your squares.
=== Edit end ===
Hope it will help.
PS. In jQuery, use one function that would initialize all elements when whole page is already loaded:
$(document).ready(function(){
    // Now, I know the page has completely loded.
    // All initialization comes here.
});


text:
Q: Search filter in Netsuite for specified months In netsuite we have months (Not in serial order).
months values are say :
list_month = [182,183,186,187,188,190,191,192,194,195,196,199,200,201];

I want to apply search filter to get records within certain months say from 183 to 194.
var period = 183;
var period1 = 194;

I used the "between" and "within" but it did not work'
Here is my filter:
filters.push(new nlobjSearchFilter("postingperiod","transaction","within",period,period1));

this returns only the values of 183. I want all of them : 183,186,187,188,190,191,192,194.
*Note this are not dates but months (starting from 1 to last date of that month)
How can i get this.
Thanks

A: You would need to specify each period as a separate filter and use .setParens(1) and .setOr(true) to build out the logic of your search like this:
var results = nlapiSearchRecord('invoice', null, [
    new nlobjSearchFilter('mainline', null, 'is', 'T'),
    new nlobjSearchFilter('postingperiod', null, 'within', 122).setLeftParens(1).setOr(true),
    new nlobjSearchFilter('postingperiod', null, 'within', 123).setRightParens(1)
], [
    new nlobjSearchColumn('internalid', null, 'count')
]);

If you don't always know which periods you'll need, you can generate these filters dynamically with a function like this:
function buildPeriodFilters(periodIds) {
    // Return empty array if nothing is passed in so our search doesn't break
    if (!periodIds) {
        return [];
    }

    // convert to array if only a single period id is passed in.
    periodIds = [].concat(periodIds);

    return periodIds.map(function(periodId, index, periodIds) {
        var filter = new nlobjSearchFilter('postingperiod', null, 'within', periodId);

        // if this is the first periodid, add a left parenthesis
        if (index === 0) {
            filter = filter.setLeftParens(1);
        }

        // if this is the last period id, add a right parenthesis, otherwise add an 'or' condition
        if (index !== periodIds.length - 1) {
            filter = filter.setOr(true);
        } else {
            filter = filter.setRightParens(1);
        }

        return filter;
    });
}

var dynamicPeriodFilter = buildPeriodFilters([122,123,124]);

var results = nlapiSearchRecord('invoice', null, [
    new nlobjSearchFilter('mainline', null, 'is', 'T'),
].concat(dynamicPeriodFilter), [
    new nlobjSearchColumn('internalid', null, 'count')
]);


text:
Q: yield and WWWForm error I have been trying to convert the code at (the 2nd sample on the page): http://unity3d.com/support/documentation/ScriptReference/WWWForm.html
..to C# in Unity3D:
void Start ()
{
    string dataUrl = "http://www.my-site.com/game/test.php";
    string playName = "Player 1";
    int score = -1;

    // Create a form object for sending high score data to the server
    var form = new WWWForm();
    // Assuming the perl script manages high scores for different games
    form.AddField( "game", "MyGameName" );
     // The name of the player submitting the scores
    form.AddField( "playerName", playName );
     // The score
    form.AddField( "score", score );

    // Create a download object
    WWW downloadW = new WWW( dataUrl, form );

    // Wait until the download is done
    yield return downloadW;

    if(downloadW.error == null) {
        print( "Error downloading: " + downloadW.error );
        return false;
    } else {
        // show the highscores
        Debug.Log(downloadW.text);
    }
}

I get the following error:

error CS1624: The body of rr2game.Start()' cannot be an iterator block becausevoid' is not an iterator interface type

After doing some reading I have tried changing void Start() to IEnumerator Start()
..but it says IEnumerator is is not declared..?
If I comment out the yield command the errors go away, but of course the data doesn't load.
Please can someone help?
Thank you.

A: You need to change the return type of Start(), the Start callback supports both void and IEnumerator as it's return types.
IEnumerator Start ()
{
    string dataUrl = "http://www.my-site.com/game/test.php";
    string playName = "Player 1";
    int score = -1;

    // Create a form object for sending high score data to the server
    var form = new WWWForm();
    // Assuming the perl script manages high scores for different games
    form.AddField( "game", "MyGameName" );
     // The name of the player submitting the scores
    form.AddField( "playerName", playName );
     // The score
    form.AddField( "score", score );

    // Create a download object
    WWW downloadW = new WWW( dataUrl, form );

    // Wait until the download is done
    yield return downloadW;

    if(downloadW.error == null) {
        print( "Error downloading: " + downloadW.error );
        return false;
    } else {
        // show the highscores
        Debug.Log(downloadW.text);
    }
}

Once the return type is IEnumerator you are allowed to use the yield keyword.
Most callbacks let you return IEnumerator, some that can't are: Awake, Update, LateUpdate, FixedUpdate, OnGUI, OnEnable, OnDisable, OnDestroy. You will need to check the documentation of the event callback to see if it does not support being a co-routine.

A: yield can not be used in the Start() function, it needs to be called within its own thread, instead try this:
void Start()
{
    StartCoroutine(SaveScore());
}

IEnumerator SaveScore()
{
    string dataUrl = "http://www.my-site.com/game/test.php";
    string playName = "Player 1";
    int score = -1;

    // Create a form object for sending high score data to the server
    var form = new WWWForm();
    // Assuming the perl script manages high scores for different games
    form.AddField( "game", "MyGameName" );
     // The name of the player submitting the scores
    form.AddField( "playerName", playName );
     // The score
    form.AddField( "score", score );

    // Create a download object
    WWW downloadW = new WWW( dataUrl, form );

    // Wait until the download is done
    yield return downloadW;

    if(!string.IsNullOrEmpty(downloadW.error)) {
        print( "Error downloading: " + downloadW.error );
    } else {
        // show the highscores
        Debug.Log(downloadW.text);
    }
}


text:
Q: Adding a header file for all files in a directory I have a directory with lots of C files. For each of these C files, I need to add the line #include config.h. Is there a way to avoid doing this manually?
I'm thinking that maybe there is a neat way to tell the preprocessor to do that, or maybe pass a well-constructed flag to the linker. How can I get all files in a directory to "include" the same header file?

A: Either use -include switch
$ cat foo.c
int main(void) {
    printf("%s\n", "ohai there o/");
    return 0;
}
$ gcc -include stdio.h foo.c

or write a script that will insert that include for you automatically
in these examples editing .c files, and adding the include in the very 1st line of the file.
assuming bash shell, GNU sed :
while read -r; do
    sed -i '1i #include "config.h"' "$REPLY"
done < <(find /path/to/project/dir -type f -name "*.c")

or with something POSIX
find /path/to/project/dir -type f -name "*.c" | while read -r file; do
    ed "$file" <<EOF
0a
#include "config.h"
.
wq
EOF
done


text:
Q: Is it possible to use Predicate when creating queries for Jinq? My question is about Jinq , and I am using version 1.8.9 which currently is the latest release.
I am trying to use Jinq  for implementing a general reusable JPA (Java Persistence API) typesafe query method with the Java 8 lambda (functional interface) Predicate as method parameter.
Unfortunately, I can not make it work with the Java 8 Predicate but instead I can use a similar predicate type (provided by Jinq) as method parameter, but would like to avoid dependencies to Jinq in method signatures, and therefore would prefer the Java 8 Predicate if possible?
Jinq provides the functional interface "Where":
package org.jinq.orm.stream;
public interface JinqStream<T> extends Stream<T> {
    @FunctionalInterface
    public static interface Where<U, E extends Exception> extends Serializable {
      public boolean where(U obj) throws E;
    }

I can implement the query method I want (but with the undesirable coupling) by using the above interface in the method signature like this:
public List<T> select(JinqStream.Where<T, Exception> wherePredicate)

Instead of the above coupling to Jinq in the method signature I would like to use the standard Predicate as below:
public List<T> select(java.util.function.Predicate<T> wherePredicate) {

The standard Predicate is defined like this:
@FunctionalInterface
public interface Predicate<T> {
  public boolean test(T t);
}

Therefore I thought it might have been possible to implement my desired select method using the following code for creating a lambda implementation of  the Jinq interface:
public List<T> select(java.util.function.Predicate<T> predicate) {
    org.jinq.orm.stream.JinqStream.Where<T, Exception> wherePredicate = u -> predicate.test(u);
    ...

However, it does not work but results in an IllegalArgumentException (see stacktrace pasted further down below)
Below is some more code illustrating what I am trying to do.
The problem I am trying to illustrate is that I want to use the Predicate parameter in the below method "DataMapperBase.select2" instead of the Jinq specific Where parameter as in below method "DataMapperBase.select".
public abstract class DataMapperBase<T> {
    ...
    private EntityManagerFactory entityManagerFactory;
    private EntityManager entityManager;
    private final Class clazz;// initialized using below method getClazz()

    private Class getClazz() throws ClassNotFoundException {
        Type genericSuperclass = getClass().getGenericSuperclass();
        Type actualTypeArgument = ((ParameterizedType)genericSuperclass).getActualTypeArguments()[0];
        return Class.forName(actualTypeArgument.getTypeName());
    }

    // This method works but has an undesirable dependency to Jinq in method signature.
    public List<T> select(org.jinq.orm.stream.JinqStream.Where<T, RuntimeException> wherePredicate) {
        JinqJPAStreamProvider streams = new JinqJPAStreamProvider(entityManagerFactory);
        List<T> result = streams
          .streamAll(entityManager, clazz)
          .where( wherePredicate )
          .toList();
        return result;
    }

    // Instead of the above select method I want to use the below method (currently named "select2")

    // The code below compiles but does not work in runtime.This is the method signature I would like to use.
    public List<T> select2(java.util.function.Predicate<T> predicate) {
        org.jinq.orm.stream.JinqStream.Where<T, RuntimeException> wherePredicate = u -> predicate.test(u);
        JinqJPAStreamProvider streams = new JinqJPAStreamProvider(entityManagerFactory);
        List<T> result = streams
          .streamAll(entityManager, clazz)
          .where( wherePredicate )
          .toList();
        return result;
    }
...
public class PersonDataMapper extends DataMapperBase<Person> { ...
...
@Entity
@Access(AccessType.PROPERTY)
@Table(name="person")
public class Person implements Serializable {
    ...
    private int age;
    @Column(name = "Age")
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    ...

...
// The invocations below can be used e.g. from a test class
List<Person> persons  = personDataMapper.select( p -> p.getAge() > 20 );
List<Person> persons2 = personDataMapper.select2( p -> p.getAge() > 20 );

Both above methods (select and select2) compiles but the second fails in runtime with the following exception;
java.lang.IllegalArgumentException: Could not extract code from lambda. This error sometimes occurs because your lambda references objects that aren't Serializable.
    at org.jinq.jpa.transform.LambdaInfo.analyze(LambdaInfo.java:33)
    at org.jinq.jpa.transform.LambdaAnalysisFactory.extractSurfaceInfo(LambdaAnalysisFactory.java:7)
    at org.jinq.jpa.JPAQueryComposer.applyTransformWithLambda(JPAQueryComposer.java:269)
    at org.jinq.jpa.JPAQueryComposer.where(JPAQueryComposer.java:365)
    at org.jinq.jpa.JPAQueryComposer.where(JPAQueryComposer.java:1)
    at org.jinq.orm.stream.QueryJinqStream.where(QueryJinqStream.java:45)
    at org.jinq.jpa.QueryJPAJinqStream.where(QueryJPAJinqStream.java:86)

The error message indicates it might be a problem with java.util.function.Predicate not implementing Serializable.
(since the Person in my example implements Serializable)
Though, then I experimented with another interface like this:
public interface Predicate2<T> extends java.util.function.Predicate<T> , Serializable {}

When I used it instead, I got the following exception:
java.lang.IllegalArgumentException: Could not analyze lambda code
    at org.jinq.jpa.transform.LambdaAnalysis.fullyAnalyzeLambda(LambdaAnalysis.java:197)
    at org.jinq.jpa.transform.LambdaInfo.fullyAnalyze(LambdaInfo.java:116)
    at org.jinq.jpa.JPAQueryComposer.applyTransformWithLambda(JPAQueryComposer.java:278)
    at org.jinq.jpa.JPAQueryComposer.where(JPAQueryComposer.java:365)
    at org.jinq.jpa.JPAQueryComposer.where(JPAQueryComposer.java:1)
    at org.jinq.orm.stream.QueryJinqStream.where(QueryJinqStream.java:45)
    at org.jinq.jpa.QueryJPAJinqStream.where(QueryJPAJinqStream.java:86)

So, my question is if someone can provide a working implementation of the above method "DataMapperBase.select2" i.e. the method using parameter java.util.function.Predicate ?

A: Due to limitations of Java 8's implementation of lambdas, Jinq requires the use of Serializable lambdas. Unfortunately, the default Predicate in Java 8 is not Serializable, so it cannot be analyzed by Jinq.
I gave a talk at the JVM Language Summit last year on how Jinq works. The section on why the default Java 8 Predicate couldn't be used by Jinq is discussed at around the 17:16 mark:
https://youtu.be/JqCnZFzTR2I?t=17m16s
The current Jinq bytecode analysis is currently designed to work mainly with the Jinq query style, so if you try to stuff in arbitrary lambdas, Jinq's analysis will likely fail. That's also discussed elsewhere in the video.


text:
Q: Visualforce Remote Objects - Context incomplete - authorization not provided I am using Visualforce Remote objects for a simple query to get a value from a custom object in Guest-user context inside the community and also same thing happens if run the vf page using "/apex/[vfpagename]".
Error

Visualforce Remoting: Context incomplete - authorization not provided

Code
<!-- Remote Objects definition of jobs to get Job term -->
    <apex:remoteObjects >
        <apex:remoteObjectModel name="Job__c" jsShorthand="jobs" fields="Id, JobTerm__c" />
    </apex:remoteObjects>
    <!-- JavaScript to make Remote Objects calls -->
    <script>
        var fetchJobTerm = function(){
            // Create a new Remote Object
            var job = new SObjectModel.jobs();
            // Use the Remote Object to query for jobterm
            job.retrieve({where: {Id: {eq: '{!$CurrentPage.parameters.jobId}' }}}, function(err, records, event){
                if(err) {
                    alert(err.message);
                }
                else {
                    var clsJobTerm = document.getElementById("jobTerm");
                    records.forEach(function(record) {
                        var jobTerm = record.get("JobTerm__c");
                        alert("JobTerm is:" + jobTerm);
                        //clsJobTerm = jobTerm;
                    });
                }
            });
        };

        window.onload = function() {
            fetchJobTerm();
        };
    </script>

Spring'21 - Security Update)
Has already been applied to the sandbox and I honestly don't see a way around it.


text:
Q: Norm closure of convex hull of its set of extreme points How to prove that the set of extreme points of $B_{\ell^1} = \{v \in \ell^1 : \| v \| \le 1\}$ is $\{ +e^N, -e^N : N=1,2,3,\ldots \}$, where $e^N$ denotes the Nth standard basis element in $\ell_1$: $e_n^N=0$ if $n\neq N$ and $e_N^N =1$.
Also, is $B_{\ell^1}$ the norm closure of the convex hull of its set of extreme points? How to prove this? I don't know how to do it. Please help.

A: First, if $e^N = \frac 12(x+y)$ with $x,y \in B_{\ell^1}$, then $1 = e^N_N = \frac 12(x_N + y_N)$ with $|x_N|, |y_N| \le 1$. Therefore $x_N = y_N = 1$ and since $\|x\|_1, \|y\|_1 \le 1$ we have $x=y= e^N$. So all $e^N$ are extreme points of $B_{\ell^1}$, so are $-e^N$.
Otherwise, if $x \in S_{\ell^1}$ with $x \ne \pm e^N$ for all $N$, there are $n \ne m$ with $x_n, x_m \ne 0$ and therefore $0 &lt |x_n|, |x_m| &lt 1$, let $\eta := \min\{|x_n|, |x_m|, 1 - |x_n|, 1-|x_m|\}$ and set $y = x + \eta e^n - \eta e^m$ and $z = x - \eta e^n + \eta e^m$. Then $y,z \in B_{\ell^1}$, $x = \frac 12(y+z)$ and $y\ne z$. So $x$ is not extreme.
No let $x \in B_{\ell^1}$. We have
\[
  \sum_{i=1}^n x_i e^i = \sum_{i=1}^n |x_i|\cdot \mathrm{sgn} x_i\cdot e_i + \frac 12\left(1 - \sum_{i=1}^n |x_i|\right)e^{1} + \frac 12 \left(1 - \sum_{i=1}^n |x_i|\right)(-e^{1})
\]
so $\sum_{i=1}^n x_i e^i \in\mathrm{conv}\mathrm{ext} B_{\ell^1}$ for each $n$. But $\sum_{i=1}^n x_ie^i \to x$ in norm, so we are done.


text:
Q: How can i handle DZRPlayer finished playing current track? I tried to use (void)player:(DZRPlayer *)player didBuffer:(long long)bufferedBytes outOf:(long long)totalBytes to handle end of the track,  but it never has been called with buffered Bytes being the same as totalBytes.
Is it possible to handle track ends?

A: Maybe the progress property of DZRPlayer can come in handy.
/*!
The progress in the playback of the current playing DZRTrack.

This is the percentage of the track aldready played. You can assign to this
property to seek inside the track.
*/
@property (nonatomic, assign) double progress;


text:
Q: Vimeo video in Landscape Mode In one app i am displaying videos from Vimeo and Youtube. All videos should be open in Landscape Mode by default. Whole App is on Portrait orientation based only. Youtube Video is opening in Landscape mode automatically and also supporting orientation without any effort which i want but problem is with Vimeo Video. Vimeo Video is not playing in Landscape Mode and also not supporting orientation. I m in big trouble, if any one know please help me.
for Youtube i have loaded following Html String:
 NSString *embedHTML =  @"\
\
\
\
<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
";
NSString *html = [NSString stringWithFormat:embedHTML, urlString, frame.size.width, frame.size.height];
return html;

And for Vimeo i have written following Html String:
@""


text:
Q: Stateful Angular's services I created a directive, that needs a data to be loaded from the server. The data depends on id, and for each instance of directive it will be different.
I think it will be better to write the logic of downloading the data in a service, that than will be injected in directive. But with plain Angular's services, that are singletons, i will have one and the same data for all instances of directive.
In the internet i found that in the service i can write a method, that will return a new instance of object, and than use it.
My questions are:

*

*Is it normal to write such a logic in services?

*What should i do with service for my purposes?

A: I think you are confused by the definition of "singleton" in this context. It's what other languages call "shared" or "static" function; as opposed to "member" function. So you will call the same function - but you won't get the same data back. You can have service definition with $http or $resource or whatever; but then if you invoke this service from the controller (or from the directive - I just never had a need to do that), you pass id as parameter, and get the result that you want.
The bottom line, service returns a function (and this function is a singleton, that is, same function application-wide); but then you call this function with parameters and get the result that you want


text:
Q: How to use parameters/variables in a function outside of the function in a different block of code I am trying to assign value to the variables winsP1 and winsP2 by playing a random number game in my function 'determineWinner'.  The values of winsP1 and winsP2 will be the number of times that each player wins the random number game.
The trouble I am running into is I am not able to pull the values from my function and use them outside of the function in my next block of code that tells me which player ultimately won the most rounds.
import random
answer = input("Play the game?")

winsP1 = 0
winsP2 = 0

def determineWinner(winsP1, winsP2):
    from random import randint
    player1 = randint(1,10)
    player2 = randint(1,10)
    #time.sleep(1)
    print("Player 1:", player1)
    #time.sleep(1)
    print("Player 2:", player2)
    #time.sleep(1)
    if player1==player2:
        print("This round is a tie!")
        winsP1 + 1
        winsP2 + 1
    elif player1>player2:
        winsP1 + 1
        print("Player 1 wins this round!")
    elif player2>player1:
        print("Player 2 wins this round!")
        winsP2 + 1
    #time.sleep(1)

for i in range(10):
    determineWinner(winsP1, winsP2)

if answer == "y" or answer == "Y" or answer == "yes" or answer ==  "Yes":
    if winsP1>winsP2:
        print()
        print("The score totals are:")
        print("Player one: " + str(winsP1))
        print("Player two: " + str(winsP2))
        print()
        print("Player 1 wins with a score of", str(winsP1) +  "!")
        print()
    elif winsP2>winsP1:
        print()
        print("The score totals are:")
        print("Player One: " + str(winsP1))
        print("Player two: " + str(winsP2))
        print()
        print("Player 2 wins with a score of", str(winsP2) +  "!")
        print()
    elif winsP1==winsP2:
        print()
        print("The score totals are:")
        print("Player one: " + str(winsP1))
        print("Player two: " + str(winsP2))
        print()
        print("It's a tie!")
        print()

A: Rather than iterating variables in place, consider using lists to collect results from determineWinner then subset to count by players:
from random import randint
answer = input("Play the game?")

def determineWinner():
    player1 = randint(1,10)
    player2 = randint(1,10)

    print("Player 1:", player1)
    print("Player 2:", player2)

    if player1 == player2:
        print("This round is a tie!")
        result = 'T'
    elif player1 > player2:
        print("Player 1 wins this round!")
        result = 'P1'
    elif player2 > player1:
        print("Player 2 wins this round!")
        result = 'P2'

    return result

# BUILD LIST OF RESULTS VIA LIST COMPREHENSION
results = [determineWinner() for i in range(10)]

# COUNT NUMBER OF ELEMENTS ACCORDING TO PLAYER
winsP1 = len([r for r in results if r in ("P1", "T")])
winsP2 = len([r for r in results if r in ("P2", "T")])

...

A: winsP1 = 0
winsP2 = 0

def determineWinner(anyName1, anyName2):
    ...
    do stuff with anyName1 and anyName 2
    ...
    return anyName1, anyName2

winsP1, winsP2 = determineWinner(anyName1=winsP1, anyName2=winsP2)

The return keyword gives you back any variables you want from the function. Notice that I have returned more than one value in this case. The function can give back multiple values which are stored in a tuple. You can then unpack them like I have using variables seperated by a comma. Note that the function is using a copy of the variables you gave it, and when you get the values back, you have to overwrite the variables outside of the function with the returned copies. You can also simply write
winsValues = determineWinner(winsP1, winsP2)

and then access them by writing
accessP1 = winValues[0]
accessP2 = winValues[1]


text:
Q: C check if fd is open using write(2) Is possible to know with system call write(2) if the fd that I'm  sending data to is open or close?
My problem is that I'm writing to a fd that is sometimes closed and sometimes open. I think there must be a way to know with write this kind of situation but I can't find that.

A: You could use a system function that doesn't affect the file (if opened), instead of write, use fstat (man page)
int fstat(int fd, struct stat *buf);

Example
struct stat buf;
if (fstat(fd, &buf) == -1) {
    // fd is either closed or not accessible
}

fstat() returns -1 if it couldn't use the file descriptor (0 otherwise).

A: From the manual page

On success, the number of bytes written is returned (zero indicates
  nothing was written). On error, -1 is returned, and errno is set
  appropriately.

So just check the return value for -1


text:
Q: Need to make a something like a tool tip with a literal inside I'm tring to basically make a box appear when ever someone hovers over a button like a tool tip. But i want to be able to put html inside the box. I have been able to do this with a div and some javascript to hide and unhide the div but I cant seem to make the div appear where the mouse is when it is over the button. Is there a way to do this?

A: You could get help using a library like jquery.
Or you can try with something like:
http://sixrevisions.com/tutorials/javascript_tutorial/create_lightweight_javascript_tooltip/
Here is a working demo:
http://sandbox.scriptiny.com/tooltip/
You need to replace the logic to work with your button, but it should be easy.


text:
Q: mongod Failed to obtain address information for hostname OS X Having an issue starting mongo using mongod --dbpath.  I get the following error:
NETWORK  [HostnameCanonicalizationWorker] Failed to obtain address information for hostname ##########: nodename nor servname provided, or not known

Host name only has latin characters.  I've tried multiple networks, deleted all DNS entries, confirmed my /etc/hosts looks fine and now I'm at a standstill.
Here is my /etc/hosts:
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
#::1             localhost

A: Try enabling the ipv6 and restart the mongod server
::1             localhost

A: I followed the answer in this JIRA ticket.
And here is my /etc/hosts file.
  1 ##
  2 # Host Database
  3 #
  4 # localhost is used to configure the loopback interface
  5 # when the system is booting.  Do not change this entry.
  6 ##
  7 # 127.0.0.1 localhost
  8 127.0.0.1 localhost localhost.localdomain
  9 255.255.255.255 broadcasthost
 10 # ::1             localhost

A: change your HOSTNAME in /etc/sysconfig/network likes:
HOSTNAME=Steven

Then change your hostname in /etc/hosts:
127.0.0.1 localhost localhost.localdomain ...............

to
127.0.0.1 localhost Steven  ...............


text:
Q: Threading not using all cores in python I have recently faced a problem of running something on multiple threads/cores.    My setup:   (Cpython with GIL) python 3.6.3 (anaconda)   OS: windows 10   CPU: i7 8700 (6 cores/12 threads)   GPU: 1080, 1070    tensorflow==1.8.0 tensorflow-gpu==1.8.0   keras==2.1.5
And there is no bottleneck for sure. RAM usage 6/24 GB Disk usage: 0%
The problem is that threading module seems to use only half of my cores/threads according to task manager, which shows CPU load of only 50% instead of 100.
Here is my code
class Environment(Thread):
    stop_signal = False

    def __init__(self, testing=False, eps_start=EPS_START, eps_end=EPS_STOP, eps_steps=EPS_STEPS):
        Thread.__init__(self)
        self.testing = testing
        self.env = Market(1000, train_data, testing=testing)

        self.agent = Agent(eps_start, eps_end, eps_steps)

    def runEpisode(self):
        s = self.env.reset()

        R = 0
        done = False

        while not done:
            time.sleep(THREAD_DELAY) # yield

            a = self.agent.act(s)
            s_, r, done, info = self.env.step(a)

            if done: # terminal state
                s_ = None

            self.agent.train(s, a, r, s_)

            s = s_
            R += r

        print("Total reward:", R)

    def run(self):
        while not self.stop_signal:
            self.runEpisode()
            if self.testing: break

    def stop(self):
        self.stop_signal = True

class Optimizer(Thread):
    stop_signal = False

    def __init__(self):
        Thread.__init__(self)

    def run(self):
        while not self.stop_signal:
            brain.optimize()

    def stop(self):
        self.stop_signal = True

if __name__ == '__main__':

    #-- main
    env_test = Environment(testing=True, eps_start=0., eps_end=0.)
    NUM_STATE = env_test.env.observation_space.shape[0]
    NUM_ACTIONS = env_test.env.action_space.n
    NONE_STATE = np.zeros(NUM_STATE)

    brain = Brain() # brain is global in A3C

    envs = [Environment() for i in range(THREADS)]
    opts = [Optimizer() for i in range(OPTIMIZERS)]

    start_time = time.time()

    for o in opts:
        o.start()

    for e in envs:
        e.start()

    time.sleep(RUN_TIME)

    for e in envs:
        e.stop()

    for e in envs:
        e.join()

    for o in opts:
        o.stop()

    for o in opts:
        o.join()

    print("Training finished in ", time.time() - start_time)

    brain.model.save('dense.h5')

A: Turns out the solution is using multiprocessing module. But I'am having problem integrating it. I am getting BrokenPipeError: [Errno 32] Broken pipe. I think it is in someway related to this line brain = Brain(), since brain is a global variable
class Environment():
    stop_signal = False

    def __init__(self, testing=False, data=train_data, eps_start=EPS_START, eps_end=EPS_STOP, eps_steps=EPS_STEPS):
        self.testing = testing
        self.env = Market(1000, data, testing=testing)
        self.agent = Agent(eps_start, eps_end, eps_steps)

    def runEpisode(self):
        s = self.env.reset()
        done = False

        while True:
            time.sleep(THREAD_DELAY) # yield

            a = self.agent.act(s)
            s_, r, done, info = self.env.step(a)

            if done: # terminal state
                s_ = None

            self.agent.train(s, a, r, s_)

            s = s_

            if done or self.stop_signal:
                break

        print("Total reward:", self.env.total)

    def run(self):
        while not self.stop_signal:
            self.runEpisode()
            if self.testing: break

    def stop(self):
        self.stop_signal = True

class Optimizer():
    stop_signal = False

    def run(self):
        while not self.stop_signal:
            brain.optimize()

    def stop(self):
        self.stop_signal = True

np.seterr(all='raise')

env_test = Environment(testing=True, data=test_data, eps_start=0., eps_end=0.)
NUM_STATE = env_test.env.observation_space.shape[0]
NUM_ACTIONS = env_test.env.action_space.n
NONE_STATE = np.zeros(NUM_STATE)

brain = Brain(True) # brain is global in A3C

envs = [Environment() for i in range(THREADS)]
opts = [Optimizer() for i in range(OPTIMIZERS)]

if __name__ == '__main__':
    start = time.time()
    env_threads, opt_threads = [], []

    for env in envs:
        p = Process(target=env.run)
        p.start()
        env_threads.append(p)

    for opt in opts:
        p = Process(target=env.run)
        p.start()
        opt_threads.append(p)

    time.sleep(RUN_TIME)

    for p in env_threads:
        p.stop()

    for p in env_threads:
        p.join()

    for p in opt_threads:
        p.stop()

    for p in opt_threads:
        p.join()

    print('finished in ', time.time() - start)

brain.model.save('dense.h5')


text:
Q: Spring @Value annotation not working Properties annotated with @Value are not being set on my beans.
My context and classes are inside a jar that is on the classpath of another project. Its spring context imports my spring context and my spring context loads a config file from the classpath and contains various bean definitions.
Lazy loading is not being used anywhere, my jar is using Spring 3.1.4 and the project using my jar is using Spring 3.2.3.
Logger showing properties file is loaded when the external project loads it's context (which imports mine)
[main] INFO  Loading properties file from class path resource [connector-config.properties] - (PropertyPlaceholderConfigurer.java:172:)

Excerpt from my Spring context:
<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    lazy-init="false">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:connector-config.properties</value>
        </list>
    </property>
</bean>
...
    <!-- The actual beans referenced are not foo bar and com but should not be relevant to this issue -->
<bean id="requestGenerator" class="com.connector.RequestGenerator">
    <constructor-arg name="foo" ref="foo" />
    <constructor-arg name="bar" ref="bar" />
    <constructor-arg name="com" ref="com" />
</bean>

config file that is on classpath of project using my jar
ruleType=PAUL
response.poolSize=10
ack.poolSize=10
#This needs to be in minutes
max.run.time=100
base.dir=\\

Class from external project loading a bean from my context:
By inspecting the requestGen object in Eclipse debug mode I can see the property ruleType is null. Given the above properties file, ruleType should be "PAUL" but it is null.
public class App
{
public static void main(Straing[] args)
{
    @SuppressWarnings("resource")
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
    RequestGenerator requestGen = context.getBean("requestGenerator", RequestGenerator.class);

A: The @Value annotation is processed by AutowiredAnnotationBeanPostProcessor which is typically registered if you have a <component-scan> or <annotation-config> configuration in XML (or directly with a bean definition). You need to add either of those, probably <annotation-config> since you've said you don't have any @Component classes.

A: Since Spring 3.1 it isn't recommended to use PropertyPlaceholderConfigurer for such task. For more info see its JavaDoc
From other side, show, please, your connector-config.properties and the code of RequestGenerator to have more info about an issue.


text:
Q: Laravel 403 Forbidden Error As title said, I got error 403 (title of page) on Laravel project. Locally, it's working, but when I'm trying to put it live, on a web-host/my domain it gives me:

Forbidden
  You don't have permission to access / on this server.
  Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

I deleted .htaccess file from public folder, and nothing happened.
Any solutions?

A: Your .htaccess is not parsed by apache because AllowOverride All directive is missing inside virtualhost configuration. .htaccess file is required for Laravel. Put back it. Then change apache virtual host configuration on server to allow .htaccess.
<VirtualHost *:80>
    ServerName www.example.net
    DocumentRoot "/var/www/html/example3"
    <Directory /var/www/html/example3>
         DirectoryIndex index.php
         AllowOverride All
         Require all granted
    </Directory>
</VirtualHost>

Change your virtualhost like this and restart apache by sudo service apache2 restart.
Replace www.example.net and  /var/www/html/example3 with correct details.

A: If you are using your own Request, change the authorize function to return true:
public function authorize()
{
    return true;
}

As simple as that!

A: You can try these commands.
sudo chmod -R gu+w project_folder
sudo chmod -R guo+w project_folder

chmod -R 775 storage/
chmod -R 775 bootstrap/cache


text:
Q: Doubt in proof of Euclidean Algorithm I got this text from https://www.math.fsu.edu/~pkirby/mad2104/SlideShow/s5_2.pdf

Is it necessary for the proof to suppose:
"Now suppose $d$ is a common divisor of $b$ and $r$..."
By showing that if $d|a$ and $d|b$ then $d|(a-bq)$ aren't we already showing that the set of common dividers for $a$ and $b$ are the same $r$ and $b$?

A: No. By showing that if $d\mid a$ and $d\mid b$ then $d\mid r$, we are showing that$$\{\text{common dividers of $a$ and $b$}\}\subset\{\text{common dividers of $b$ and $r$}\}.$$Now, we must prove that the reverse inclusion also holds.

A: Yes. Let $\,{\rm CD}(x,y)\,$ be the set of Common Divisors of $x,y$. The proof works as follows.
Note $\ \ {\rm CD}(a,b) \,\subseteq\, {\rm CD}(b,r)\ $ by paragraph $2$ in the proof,
and $\ \ \  \ {\rm CD}(a,b)\, \supseteq\, {\rm CD}(b,r)\ $ by paragraph $3$ in the proof.
Thus  $\,\ {\rm CD}(a,b)\, =\, {\rm CD}(b,r)\ $ so they have the same greatest element (= common divisor)
i.e. $\ \ {\rm GCD}(a,b)\! =\! {\rm GCD}(b,r)$
Note that the proof requires both containment directions (paragraph $2$ and $3$) to deduce the equality of the common divisor sets (hence equality of their greatest elements).

A: Indeed, the proof shows that any common divisor of $a,b$ is a common divisor of $b,r$ and vice versa.
Thus $a,b$ and $b,r$ have the same greatest common divisor, where greatest is taken according to the divisibility relation.


text:
Q: Reading binary data (.tec) into C++ program variable matrices So I am expected a data file usually with ending .tec but also seen as .dat with an ASCII version that looks like such:
Title="UPSCALE DATA"
Variables="X","Y","Z","U","V","W","rho"

Zone I=  3,  J=  3,  K=  3,  U=POINT,  V=POINT,  W=POINT,  rho=POINT
         0         0         0              1              2              3              4
         0         0         1              1              2              3              4
         0         0         2              1              2              3              4
         0         1         0              1              2              3              4
         0         1         1              1              2              3              4

Here the first 3 columns and the numbers following "I=", "J=" and "K=" are to be read as integers in the program. And the other columns are to be read as float data types in C++.
This is the code I used on how to write the above file in ASCII with the following function:
#ifndef Tecplotter_H
#define Tecplotter_H

#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>

static void Tecplot(int counter, std::string prefix, float* xvel, float* yvel, float* zvel, float* rho, int xRes, int yRes, int zRes) {

    char buffer[80];
    sprintf(buffer, "%04i", counter);
    std::string number = std::string(buffer);
    std::string filenameTec = prefix + number + std::string(".tec");
    printf("Writing 3D Tec file %s\n", filenameTec.c_str());

    std::cout << "Printing to Tecplot files" << std::endl;

    std::ofstream myfile;
    myfile.open(filenameTec.c_str(), std::ofstream::trunc);

    myfile << "Title=\"UPSCALE DATA\"" << '\n';
    myfile << "Variables=\"X\"," << "\"Y\"," << "\"Z\",";
    myfile << "\"U\"," << "\"V\"," << "\"W\",";
    myfile << "\"rho\"";
    myfile << "\n\n";

    myfile << "Zone I=  " << xRes << ",  J=  " << yRes << ",  K=  " << zRes << ",  ";
    myfile << "U=POINT,  " << "V=POINT,  " << "W=POINT,  " << "rho=POINT" << '\n';

    // register matrices in style X, Y, Z, U, V, W, rho
    int index = 0;
    for (int i = 0; i < xRes; i++)
        for (int j = 0; j < yRes; j++)
            for (int k = 0; k < zRes; k++)
            {
                myfile << std::setw(10) << i << std::setw(10) << j << std::setw(10) << k;
                myfile << std::setw(15) << xvel[index] << std::setw(15) << yvel[index] << std::setw(15) << zvel[index] << std::setw(15) << rho[index];
                myfile << '\n';
                index++;
            }

    myfile.close();

}
#endif

My question is two fold:

*

*How would I rewrite the above printing code to do the same thing but in binary (without the code breaking, as I tried adding an '| ios::binary" tag to the ofstream and that didn't work?

*What code would then read that code back into the program into the same array variables?

Essentially I want to create a middle man where the data gets printing into binary and then read back into the program from binary.
Disclaimer: I am an Aeronautical Engineer not a Software engineer so treat me like a first year. Secondly the broader code I am using (not included) is not my own and was written a while back so if the data types or something seem outdated I am not really in the capacity to rewrite someone else's code into the 2021 efficiency.


text:
Q: How do I correctly pass CMake list (semicolon-sep) of flags to set_target_properties? CMake lists are essentially just semicolon-separated strings, but if you pass such a variable to a command, it does get expanded into multiple arguments - for example,
set(FLAGS f1 f2 f3)
# now FLAGS == 'f1;f2;f3'
add_custom_command(
  ...
  COMMAND my_cmd ${FLAGS}
  ...
)

will correctly call my_cmd f1 f2 f3.
Now if I do this with
set_target_properties(
  myTarget PROPERTIES
  LINK_FLAGS  "${LD_FLAGS}"
)

the expansion does not occur, and I end up with a single LD_FLAG that contains semicolons -- useless, instead of expanding it into a space-separated string.
Is there any way to make it so that when I pass a list to the LINK_FLAGS property (or any property that is), it gets expanded into multiple arguments rather than just one?

A: The set_property command is designed for this
http://www.cmake.org/cmake/help/v3.0/command/set_property.html
set_property(TARGET tgt PROPERTY LINK_FLAGS foo bar)

A: I don't think set_target_properties can do the expansion automatically, but you can use string (REPLACE ...) to expand a list into a space separated string:
string (REPLACE ";" " " LD_FLAGS_STR "${LD_FLAGS}")
set_target_properties(
  myTarget PROPERTIES
  LINK_FLAGS  "${LD_FLAGS_STR}"
)

A: I use it like strings
set(FLAGS " f1 f2 f3")
Note the space in the front, it allows you to concatenate other sets of flags.
For more complex projects, instead of if-elses you may also do a double expansion trick:
set(GCC_FLAGS " -Wl,--relax")
set(DIAB_FLAGS " -tPPCE500ES:cross")
set(MSVC_FLAGS " /RAINBOW_CRAP)
# ...
# ...LINUX_FLAGS, WINDOWS_FLAGS, etc...

set_target_properties(
  myTarget PROPERTIES
  LINK_FLAGS  "${${COMPILER}_FLAGS} ${${SYSTEM}_FLAGS}"
)

# COMPILER and SYSTEM is set somewhere else, in toolchain files for example

A: For using a cmake List as list, use
${LD_FLAG}

For using a cmake list as string, (i.e. list items are separated with ';'), use
"${LD_FLAG}"

So in your case, just remove "" should be sufficient.

A: separate_arguments(LD_FLAGS_AS_LIST  NATIVE_COMMAND  LD_FLAGS)

set_target_properties(
  myTarget PROPERTIES
  LINK_FLAGS  "${LD_FLAGS_AS_LIST}"
)

A: As of CMake 3.12, you can use the list(JOIN <list> <glue> <output variable>) command described here:
set(FLAGS f1 f2 f3)
# now FLAGS == 'f1;f2;f3'
list(JOIN FLAGS " " FLAGS) # Note: Overwrites FLAGS variable
# now FLAGS == 'f1 f2 f3'
add_custom_command(
  ...
  COMMAND my_cmd ${FLAGS}
  ...
)

This is a little more direct than using string(REPLACE ...).

A: In cmake 3.x there are a few approaches
The top level CMakeLists.txt file then looks something like this:
# The name of the included file could be anything,
# it doesn't have to be called CMakeLists.txt
include(foo/CMakeLists.txt)
include(bar/CMakeLists.txt)

add_executable(myApp ${myApp_SOURCES})

with the subdirectory files structured something like this:
list(APPEND myApp_SOURCES
    ${CMAKE_CURRENT_LIST_DIR}/foo.cpp
    ${CMAKE_CURRENT_LIST_DIR}/foo_p.cpp
)

Enhanced source file handling with target_sources()


text:
Q: Hide ActionBar MenuItems when Navigation Drawer slides for any amount I'm trying to implement a Navigation Drawer that hides the menu items in the ActionBar whenever the drawer is opened.
I am following google's documentation, however their code does not produce the expected behavior.
http://developer.android.com/training/implementing-navigation/nav-drawer.html
Using this code, the menu items are hidden when the drawer becomes completely opened , and shown when the drawer becomes completely closed.
However, the Gmail app behaves differently.  The menu items are hidden as soon as the drawer opens by any amount.  This is the behavior I want.  Does anyone know how to achieve this?
Thanks!

A: If you want to override action bar as soon as drawer enters screen and restore action bar the moment drawer is no longer visible (exactly how Gmail behaves as of March 20, 2014) you can use the following code:
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
    R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {

  @Override
  public void onDrawerStateChanged(int newState) {
    super.onDrawerStateChanged(newState);

    boolean isOpened = mDrawerLayout.isDrawerOpen(mDrawerList);
    boolean isVisible = mDrawerLayout.isDrawerVisible(mDrawerList);

    if (!isOpened && !isVisible) {
      if (newState == DrawerLayout.STATE_IDLE) {
        // drawer just hid completely
        restoreActionBar();
      } else {
        // } else if (newState == DrawerLayout.STATE_SETTLING) {
        // drawer just entered screen
        overrideActionBar();
      }
    }
  }

  private void restoreActionBar() {
    getSupportActionBar().setTitle(mTitle);
    supportInvalidateOptionsMenu();
  }

  private void overrideActionBar() {
    getSupportActionBar().setTitle(mDrawerTitle);
    supportInvalidateOptionsMenu();
  }
};

// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);

Modify restoreActionBar() and overrideActionBar() methods acording to your needs.
There is no need to distinguish between swipes and home button and no need to measure swipe lengths.
Variation
If you don't want to reference the drawer list view use the following code instead:
    boolean isOpened = mDrawerLayout.isDrawerOpen(GravityCompat.START);
    boolean isVisible = mDrawerLayout.isDrawerVisible(GravityCompat.START);

You may want to use GravityCompat.END instead depending on what you specified in XML layout.
Edit - concerning actions
The above example does not hide action bar items relevant to content below the navigation drawer. To do so or show different set of icons when drawer is visible you have to keep track of whether the drawer is opened or closed manually.
In addition to the above code declare private boolean mDrawerVisible = false with proper save/restore state handling.
Then modify mDrawerToggle inner methods as follows:
  private void restoreActionBar() {
    getSupportActionBar().setTitle(mTitle);
    mDrawerVisible = false;
    supportInvalidateOptionsMenu();
  }

  private void overrideActionBar() {
    getSupportActionBar().setTitle(mDrawerTitle);
    mDrawerVisible = true;
    supportInvalidateOptionsMenu();
  }

Finally in onCreateOptionsMenu inflate different menu resource or in onPrepareOptionsMenu show/hide different actions based on the value of mDrawerVisible.

A: Have you tried this:

*

*Use invalidateOptionsMenu() whenever you toggle the nav drawer, by measuring the sliding offset.

*Iterate over each menu item in onPrepareOptionsMenu(Menu menu) and hide it.
@Override

public boolean onPrepareOptionsMenu(Menu menu) {

    // If the nav drawer is open, hide action items related to the content view
    boolean drawerOpen = shouldGoInvisible;
    hideMenuItems(menu, !drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

private void hideMenuItems(Menu menu, boolean visible)
{

    for(int i = 0; i < menu.size(); i++){

        menu.getItem(i).setVisible(visible);

    }
}

Detecting how much the nav drawer has slided:
     mDrawerLayout.setDrawerListener(new DrawerListener(){
                    float mPreviousOffset = 0f;

        @Override
        public void onDrawerClosed(View arg0) {
                         super.onDrawerClosed(arg0);
                         shouldGoInvisible = false;
                         invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View arg0) {
                         super.onDrawerOpened(arg0);
                         shouldGoInvisible = true;
                         invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerSlide(View arg0, float slideOffset) {
             super.onDrawerSlide(arg0, slideOffset);
             if(slideOffset > mPreviousOffset && !shouldGoInvisible){
                shouldGoInvisible = true;
                invalidateOptionsMenu();
            }else if(mPreviousOffset > slideOffset && slideOffset < 0.5f && shouldGoInvisible){
                shouldGoInvisible = false;
                invalidateOptionsMenu();
            }
            mPreviousOffset = slideOffset;

        }

        @Override
        public void onDrawerStateChanged(int arg0) {
            // or use states of the drawer to hide/show the items

        }});

Note: shouldGoInvisible is class field.

A: I'd half agree with Nikola but it's sufficient just to update the icons when the drawer state has
Create a global variable to keep track of the drawer state:
private int mDrawerState;

Set a new DrawerListener:
mDrawerLayout.setDrawerListener(new DrawerListener() {

  @Override
  public void onDrawerStateChanged(int state) {
    mDrawerState = state;
    invalidateOptionsMenu();
  }

  @Override
  public void onDrawerSlide(View view, float slide) {
    // TODO Auto-generated method stub
  }

  @Override
  public void onDrawerOpened(View view) {
    // TODO Auto-generated method stub
  }

  @Override
  public void onDrawerClosed(View view) {
    // TODO Auto-generated method stub
  }
});

Update the menu visibility:
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawer);
for(int i=0;i<menu.size();i++){
  // If the drawer is moving / settling or open do not draw the icons
  menu.getItem(i).setVisible(mDrawerState!=DrawerLayout.STATE_DRAGGING &&
      mDrawerState!=DrawerLayout.STATE_SETTLING && !drawerOpen);
}

A: I have a better solution for this question:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    if (navigationDrawerFragment.isDrawerOpen()) {
        menu.clear();
    }
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!navigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        showLocalContextActionBar();
        return false;
    }
    return super.onCreateOptionsMenu(menu);
}

A: If you want to hide all menu items, simply use:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

    return showActionBarMenu; // boolean value, set it in drawer listeners as class variable
}

Then you do not need to visible of each menu item.

A: I took the answer by @Laurence Dawson and simplified it a bit. This solution does not require any class members to be used.
Execute this code during onCreate():
    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {

        @Override
        public void onDrawerSlide(View view, float v) {
            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerClosed(View view) {
            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerOpened(View view) {}

        @Override
        public void onDrawerStateChanged(int state) {}
    });

And override this method:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    boolean actionsVisibility = !drawerLayout.isDrawerVisible(Gravity.START);

    for(int i=0;i<menu.size();i++){
        menu.getItem(i).setVisible(actionsVisibility);
    }

    return super.onPrepareOptionsMenu(menu);
}

Few notes:

*

*The above implementation assumes that the view associated with NavigationDrawer has its layout_gravity set to start in XML.

*Unrelated to OP's question, but annoying: there seems to be some kind of a bug which causes the drawer to stuck along the way. If you do observe this behavior, here is the solution: Android Navigation Drawer bug using the sample

A: I have different code but the same solution:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    hideMenuItems(menu, !mShouldGoInvisible);
    return super.onCreateOptionsMenu(menu);
}
private void hideMenuItems(Menu menu, boolean visible){
    for(int i = 0; i < menu.size(); i++){

        menu.getItem(i).setVisible(visible);
    }
}

and
 @Override
public void onNavigationDrawerListener(boolean opened, int position) {

    if (opened){
        mShouldGoInvisible = true;
        invalidateOptionsMenu();

    } else {
        mShouldGoInvisible = false;
        invalidateOptionsMenu();
    }
}


text:
Q: Wordpress MySQL join _usermeta on _users I'm a total mysql dumby doing my first paid wordpress gig and I cant seem to figure out how to join the users and usermeta tables to get a friendly result that I can use in my MYSQL-> Frontend Table plugin.
The users table layout is:
id | user_id | user     | password
------------------------------------
1  | 1       | x        | yyyyyy
2  | 2       | xx       | yyyyyy
3  | 3       | xxx      | yyyyyy
4  | 4       | xxxx     | yyyyyy
5  | 5       | xxxxx    | yyyyyy
6  | 6       | xxxxxx   | yyyyyy

And the usermeta table layout is:
id | user_id | meta_key | meta_value
------------------------------------
1  | 1       | firstname| bob
2  | 1       | lastname | smith
3  | 1       | email    | bob@smith.com
4  | 1       | phone    | 123-456-7890
5  | 1       | Street   | first street
6  | 1       | City     | New York
.
.
.
25 | 2       |firstname | jane

The result I'm looking for would look like:
id | user_id     | name     | email   | phone  | street  |  city  |
-----------------------------------------------------------------
1  | 1           | x        |
2  | 2           | xx       |

Any help here would be much appreciated.
EDIT-----------
Ive gotten to here, where I cant seem to get past error
"MySQL said: Unknown column 'u.ID' in 'on clause'"
select u.ID as name,
um.*
from wp_xxxxxx_users as u, wp_xxxxxx_usermeta as um
join (
   select um.umeta_id,
   max(case when meta_key='nickname' then meta_value end)as nickname,
   max(case when meta_key='first_name' then meta_value end)as first_name
from wp_xxxxxx_usermeta as um
group by um.umeta_id)
um on u.ID=um.umeta_id

A: This is called Pivot. Provided that the required meta_keys are known in advance, you can achieve this using condition aggregation.
Something like this:
select u.user as name,
    um.*
from users u
join (
    select user_id,
        max(case when meta_key = 'email' then meta_value end) as email,
        max(case when meta_key = 'phone' then meta_value end) as phone,
        ...
    from usermeta
    group by user_id
    ) um on u.user_id = um.user_id;


text:
Q: C Array behaves different with different number of digits, why? I have a code that gets a number from input and then puts it into array, and then prints said array. But there is very strange side-effect, when I enter 13 digit number, my last digit is wrong. If I enter 15 or 16 digit number everything is fine. I can't understand what's happening! Here is the code:
numberDigits is either 12, 14 or 15, based on the number of digits in number.
int myNumber[numberDigits];
    for (int i = 0; i <= numberDigits; i++)
    {
        myNumber[numberDigits - i] = number % 10;
        number = number / 10;
    }
    printf("\n");

    for (int i = 0; i <= numberDigits; i++)

    {
        printf("%i",myNumber[i]);
    }

EDIT:
My number is initialized as long long int. Here is a check to verify number of digits:
    if (number / 1000000000000 >= 1 && number / 1000000000000 < 10)
    {
        numberDigits = 12;
    }
if (number / 100000000000000 >= 1 && number / 100000000000000 < 10)
    {
        numberDigits = 14;
    }
if (number / 1000000000000000 >= 1 && number / 1000000000000000 < 10)
    {
        numberDigits = 15;
    }

EDIT: Last update, Yes, I have updated my code and it works as expected with your suggestions, but I need to understand why my code doesn't work. I think that maybe array[12] actually holds 12 elements and not 13, and when I access element array[12] with it, I get some random value from memory, but why this doesn't happen with array[14] or array[15] with 15 and 16 digit numbers respectively. And why program does not crash as it should when you access array at wrong position. Original question below with old code that doesn't work.
EDIT: Here is whole listing for those interested.
#include <stdio.h>
#include <cs50.h>

int verify (long long int number);

int main(void)

{
    printf("Please enter card number: \n");
    long long int number = GetLongLong();
    // AMEX uses 15 digits
    if (number > 100000000000000 && ((number / 10000000000000 == 34) || (number / 10000000000000 == 37)))
    {

        printf("AMEX");

    }

    if (number > 1000000000000 && number < 10000000000000 && (number / 1000000000000 == 4))
    {
        printf("VISA");
    }

    if (number > 1000000000000000 && number < 9999999999999999 && (number / 1000000000000000 == 4))
    {
        printf("VISA");
    }

        if (number > 1000000000000000 && number < 9999999999999999 && (number / 100000000000000 == 51 || number / 100000000000000 == 52 || number / 100000000000000 == 53 || number / 100000000000000 == 54 || number / 100000000000000 == 55))
    {
        printf("MASTERCARD");
    }

    return verify(number);
}

int verify (long long int number)
{
    int numberDigits;
    if (number / 1000000000000 >= 1 && number / 1000000000000 < 10)
        {
            numberDigits = 12;
        }
    if (number / 100000000000000 >= 1 && number / 100000000000000 < 10)
        {
            numberDigits = 14;
        }
    if (number / 1000000000000000 >= 1 && number / 1000000000000000 < 10)
        {
            numberDigits = 15;
        }

    int myNumber[numberDigits];
    for (int i = 0; i <= numberDigits; i++)
    {
        myNumber[numberDigits - i] = number % 10;
        number = number / 10;
    }
    printf("\n");

    for (int i = 0; i <= numberDigits; i++)

    {
        printf("%i",myNumber[i]);
    }

    return 0;
}

A: Your for loop should look like this:
for (int i = 0; i < numberDigits; i++)

Since indexes are zero-based, the last one will be numberDigits - 1. And so <= would go past the end.

A: I think it should be something like this:
for(int i = 0; i < numberDigits; ++i) printf("%d",myNumber[i]);

instead of:
for(int i = 0; i <= numberDigits; ++i) printf("%i",myNumber[i]);

And in the first loop:
myNumber[numberDigits - (i + 1)] = number % 10;

Also, you could use something like this to know the number of digits:
int digits(long long num) {
  if(!num) return 1;
  return log10(num) + 1;
}