text:
Q: Sum values from column in table I've created a website using Google Apps Script.
In this website, I have a table with 4 columns (Item, Price, Quantity & Total)
Once you enter the quantity for the item, column 4 will automatically compute the total.
What I need is to have the sum of all the values from column 4. Which will be displayed to "Total" below the table.
How can I do it? thank you.
This is my code:

   function sumAll() {
  jQuery.each( $('.total'), function( index, textFeild) {
     var value = parseInt($(textFeild).val());
     if(isNaN(value) == false) {
        total = total+ value;
      }
    });
 }

calc_total();

$(".qty").on('input', function(){
  var parent = $(this).closest('tr');
  var price  = parseFloat($('.totals',parent).text());
  var choose = parseFloat($('.qty',parent).val());

  $('.sum',parent).text(choose+price);

  calc_total();
});

function calc_total(){
  var sum = 0;
  $(".totals").each(function(){
    sum += parseFloat($(this).text());
  });

  $('#sum').text(sum);
}

const myTable = document.querySelector('#myTableID')

myTable.oninput = e =>
{
  let rowIndex = e.target.parentNode.parentNode.rowIndex
    , Qte      = getInput_N_RowCell(rowIndex,0)
    , Rate     = getInput_N_RowCell(rowIndex,1)

  setInput_RowCell(rowIndex,2, (Qte * Rate) )

  console.log('sum=',  Sum_RowInputValues(rowIndex) )
}

function getInput_N_RowCell(xRow, xCell) {
  return Number(myTable.rows[xRow].cells[xCell].querySelector('input').value) || 0
}

function setInput_RowCell(xRow, xCell, value) {
  myTable.rows[xRow].cells[xCell].querySelector('input').value = value
}

function myFunction() {
var val = Math.floor(1000 + Math.random() * 9000);
document.getElementById("demo").innerHTML =  "Order # " + val;
}
h1{
  background: -webkit-linear-gradient(#FFC0CB, #FF1493);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
h3{
  text-transform: uppercase;

  background: -webkit-linear-gradient(#FFC0CB, #FF1493);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
* {
  box-sizing: border-box;
}

.column {
  margin-left:5%;
  float: left;
  width: 20%;
}
.row:after {
  content: "";
  display: table;
  clear: both;
}

h4{
 margin-left: 2%;
 color: #008B8B;
 font-weight: 900;
 text-transform: uppercase;

}
h5{
 color: red;
 text-transform: uppercase;
 font-weight: 900;
}

h1{
 color: #FFC0CB;
 text-transform: uppercase;
 font-weight: 900;
}

.button {
  background-color: #FF69B4; /* Green */
  border: none;
  color: white;
  padding: 8px 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 10px;
  margin: 4px 2px;
  cursor: pointer;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 4px #999;
}
.button1:hover {background-color: #FFC0CB}

.button:active {
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

.button1 {
  margin-left: 3%;
  border-radius: 12px;
  background-color: white;
  color: black;
  border: 2px solid #FF69B4;
}

th {
  text-align: center;
}

td {
  text-align: right;
}

th, td {
  border-bottom: 1px solid #ddd;
}

tr:hover {background-color: #f5f5f5;}
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

THE MILK TEA CLUB

      Item

      Classic

      Wintermelon

      Chocolate

      Classic with Pearl

      Wintermelon with Pearl

      Chocolate with Pearl

      Classic with Crystal

      Wintermelon with Crystal

      Chocolate with Crystal

      Rate
      Quantity
      Total

      <input id="rate" value='75' size='5' style='text-align:center; font-size: 14px;' disabled>
      <input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'>
      <input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

      <input id="rate" value='75' size='5' style='text-align:center; font-size: 14px;' disabled>
      <input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'>
      <input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

      <input id="rate" value='75' size='5' style='text-align:center; font-size: 14px;' disabled>
      <input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'>
     <input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

      <input id="rate" value='85' size='5' style='text-align:center; font-size: 14px;' disabled>
      <input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'>
      <input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

      <input id="rate" value='85' size='5' style='text-align:center; font-size: 14px;' disabled>
      <input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'>
      <input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

      <input id="rate" value='85' size='5' style='text-align:center; font-size: 14px;' disabled>
      <input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'>
      <input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

      <input id="rate" value='85' size='5' style='text-align:center; font-size: 14px;' disabled>
      <input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'>
      <input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

      <input id="rate"value='85' size='5' style='text-align:center; font-size: 14px;' disabled>
      <input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'>
      <input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

      <input id="rate" value='85' size='5' style='text-align:center; font-size: 14px;' disabled>
      <input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'>
      <input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

    Total:

Order Logs

    <button class="button button1" onclick="myFunction()"> Get Order </button><button class="button button1" onlick="sumAll()"> Record Order </button>

A: Always avoid assigning same id to multiple elements.
You can assign a placeholder class to each totals input.
For eg.
<input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

Then you can loop through those inputs with class total using jQuery class selector and  each function inside your sumAll() function.
Updated code
jQuery.each( $('.total'), function( index, textFeild) {
   var value = parseInt($(textFeild).val());
   if(isNaN(value) == false) {
      total = total+ value;
    }
});

Always check if the value is number.


text:
Q: Who thought applying real value definite integral to contour integral firstly? Who thought applying real value definite integral to contour integral firstly?
Example
$$
\int_{0}^{\infty} \frac{\sin{(x)}}{x} dx
$$
$$
\int_{0}^{2\pi} \log{(\sin{(x)})} dx
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to receive the return value in Python through the OUT parameter in C++? I have a C++ dll, one of the export function is defined as follows:
OPERATEMYSQLSTDCALL_API  int __stdcall CheckMac(char * pcMac, OUT  LPSTR errorInfo);

I use it in python, use the ctypes  library,i read some of the information and call it as follws:
from ctypes import *
lib = WinDLL('OperateMysqlStdcall.dll')
CheckMac = lib.CheckMac
CheckMac.argtypes = [c_char_p, POINTER(c_wchar_p)]
CheckMac.restype = c_int
p1=c_wchar_p()
value = CheckMac('88888888',byref(p1));
print  p1.value

but when i execute it,it return None,i'm sure the value "OUT  LPSTR errorInfo" in C++ is not NULL,i print it in console and it shows Correctly.could anyone tells me why it can't work in python.Thank U very much!

A: The type of LPSTR is char* so you should use c_char_p for its type as well.  As an output parameter, though, you need a writable string buffer.  Ideally, the API should indicate the size of the buffer passed so a buffer overrun could be checked.
Here's some test DLL code:
#include <windows.h>

extern "C" __declspec(dllexport)
int __stdcall CheckMac(char* pcMac, LPSTR errorInfo)
{
    strcpy(errorInfo, pcMac);
    return 1;
}

And Python:
from ctypes import *
lib = WinDLL('test.dll')
CheckMac = lib.CheckMac
CheckMac.argtypes = [c_char_p, c_char_p]
CheckMac.restype = c_int
errorInfo = create_string_buffer(1024)
value = CheckMac('88888888',errorInfo);
print errorInfo.value

Output:
88888888


text:
Q: firefox opera custom search engine and mod_rewrite sites In firefox and opera one can create a custom search engine but it passes along the search as a standard get or post variable. Is there anyway to embed that search term in the url for sites that use pretty urls.
Example
I search github 1411 and it sends me to github.com/myusername/myproject/ticket-1411
or even better two parameters
I search github compare 1411 sends me to github.com/myusername/myproject/compare/ticket-1411

A: Use the github domain as the search URL and %s to substitute the number at the end:
http://www.github.com/myusername/myproject/ticket-%s

Search for 1411 to test the custom search.


text:
Q: Rails: authentication website and mobile app I want develop an authentication system from website and mobile app.
For the sign up i have follow this tutorial: http://railscasts.com/episodes/250-authentication-from-scratch
Now i want also that a mobile app can sign up through json.
How can handle the remember me function for client website and mobile app? The website can use the cookie and rails can use a before_filter to check if the user exists. But how can use a before_filter to differentiate the request incoming from website or mobile app? (i suppose that the mobile app doesn't use cookie but a token maybe)
Thanks u all


text:
Q: Addings functions to an array in swift I was wondering is it possible to add functions to an array in swift?, And if so how would I go about doing that, an example would be helpful.
thankyou in advance
    enum MyFunc{
    case Arity0 (Void ->Void)

}

var cycle = Array<MyFunc>()

to add to the array:
    func addToArray(){

    cycle.append(MyFunc.Arity0(ani1))
    cycle.append(MyFunc.Arity0(ani2))
    cycle.append(MyFunc.Arity0(ani3))
    cycle.append(MyFunc.Arity0(ani4))
    cycle.append(MyFunc.Arity0(ani5))

}

A: If you want to create an array of functions, and each function does not take parameters and returns noting you can do:
var cycle = [()->()]()
cycle.append(nameOfYourFunctionNoBrackets)


text:
Q: Containerized Angular build recompiling every time Context
Recently I have been trying to containerize my Angular build, because I am deploying the frontend together with the backend in a single image. The Dockerfile is as follows:
# Build frontend
FROM node:16 AS node-build
WORKDIR /app

COPY frontend/package.json frontend/package-lock.json ./
RUN npm install

COPY frontend .
RUN npm run build

# Build backend
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS dotnet-build
WORKDIR /app

COPY backend ./
RUN dotnet restore Api
RUN dotnet publish Api -c Release -o out

# Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=dotnet-build /app/out .
COPY --from=node-build /app/dist/film-portal wwwroot/

ENTRYPOINT ["dotnet", "Api.dll"]

Problem
The Dockerfile above perfectly builds the image in question, and it works like a charm after deployed. However, the build takes more time than I'd like. Let me explain:

*

*npm install is only run if either package.json or package-lock.json have changed. This is great and saves time.

*npm run build is run whenever the frontend code is touched. This is of course intended behavior, but it will recompile the Angular library code every time instead of caching the compiled result (as is the case when you do npm run build from your local shell).

I am looking for a way to cache the results of compiling the angular library code, so npm run build only has to build my own code (taking less time to complete). In imaginary syntax, I need something like the following in my Dockerfile for the frontend stage:
FROM node:16 AS node-build
WORKDIR /app

COPY frontend/package.json frontend/package-lock.json ./
RUN npm install
RUN npm compile-angular

COPY frontend .
RUN npm run build

Here npm compile-angular would compile the angular bits only when package.json or package-lock.json change, instead of every time I touch some file in the frontend code.
Unfortunately, as far as I know, there is no command in the Angular CLI to specifically compile the Angular library code, leaving aside the user code. Also, all tutorials I read fail to mention the problem of recompilation, so maybe I am missing something here. Still, I can hardly imagine I am the first one to come across this problem and I assume there must be at least a workaround. So, to summarize:

*

*Is there a way to avoid recompiling the Angular library code in a dockerized setup like mine?

*If not, is there at least a workaround, maybe by performing the build step outside of Docker?

A: After long searching I found about Issue 17017 in the angular-cli repository. One of the comments to that issue mentions that there is a hack to trigger ESM compilation: ./node_modules/.bin/ngcc --properties es2015. With that knowledge, I modified my Dockerfile and it works like a charm, no longer recompiling the Angular library code upon every change to my own code:
# Build frontend
FROM node:16 AS node-build
WORKDIR /app

COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci

# Hack to make sure the angular modules are compiled at this stage
RUN ./node_modules/.bin/ngcc --properties es2015

COPY frontend .
RUN npm run build

# Build backend
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS dotnet-build
WORKDIR /app

COPY backend ./
RUN dotnet restore Api
RUN dotnet publish Api -c Release -o out

# Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=dotnet-build /app/out .
COPY --from=node-build /app/dist/film-portal wwwroot/

ENTRYPOINT ["dotnet", "Api.dll"]


text:
Q: Arduino 4-20ma Accuracy I am connecting a pressure transmitter Dwyer MS-121(Have a Range of -100 Pa to +100Pa) to Arduino using 2 Wires Current Loop. For the shunt resistor, I am using 220Ohm. So to calculate from voltage to pressure, this is what I do:
reading is what I read from the shunt resistor
(((((float)reading * 0.0049) - 0.88) / 3.52) * 200) - 100)

0.0049 is used to know the real voltage, then 0.88 from the bottom range of 4-20mA(4mA * 220Ohm), 3.52 from the top range of 4-20ma(20mA & 220Ohm) and substracted by 0.88 to get a range from 0 to 3.52(So I can calculate it by percentage). Then 200 because the range of my pressure transmitter ( -100 to +100Pa). And the last is substracting it by 100 so I can get a nice range of -100Pa to +100Pa.
Now, My pressure transmitter has display too. The value I got from display is -19.4Pa and I got the value from Arduino is -21.1Pa. It has a difference by 1,7Pa or 0,85%. I am curious why the value from arduino is inaccurate, is it my calculation, or my circuit?

A: Your 220 ohm resistor is probably only specified as accurate to 5%.  And all of your analog readings are relative to the Arduino's 5V power supply, which itself is probably only accurate to 5%.  So your 8.8% result (not sure how you got 0.85%) is within the expected range, just considering these two possible sources of error.
You are making at least one calculation error: that 0.0049 is just an approximation, the actual voltage conversion factor is 5/1024.  That's 3.5% off right there.


text:
Q: when back button is pressed, cursor loader should restart I have a listFragment and when an item of the list is clicked it starts a new activity. When back button is pressed, the list is shown again. Im using cursor Loaders so, I want to know if is there an easy way to refresh the cursor loader when back button is pressed. This is because the new activity changes the contents of the list.
Edit:
public class ListWordFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private static String TAG = ListWordFragment.class.getSimpleName();
    private CursorLoader cursorLoader;

    // Loader
    private static final int URL_LOADER = 0;
    private SimpleCursorAdapter adapter;
    public static LoaderManager mLoaderManager;

    // ActionBar
    private AutoCompleteTextView autoCompView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_list_words, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        ListView list = getListView();

        String[] from = new String[] { Word.NAME, Word.TYPE, Word.TRANSLATE };
        int[] to = new int[] { R.id.textView_word, R.id.textView_type,
                R.id.textView_translate };

        adapter = new ListWordAdapter(getSherlockActivity(),
                R.layout.row_list_words, null, from, to, 0);
        setListAdapter(adapter);

        mLoaderManager = getLoaderManager();
        mLoaderManager.initLoader(URL_LOADER, null, this);

    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        fillRow(l, id, position, false);

    }

    private void fillRow(ListView l, long ide, int position, boolean firstCall) {

        Cursor cursor = getActivity().getContentResolver().query(
                Uri.withAppendedPath(WordListProvider.WORDS_CONTENT_URI,
                        String.valueOf(ide)), null, null, null, null);

        if(cursor.moveToFirst()){

        String id = cursor.getString(cursor.getColumnIndex(Word.ID));
        String name = cursor.getString(cursor.getColumnIndex(Word.NAME));
        String type = cursor.getString(cursor.getColumnIndex(Word.TYPE));
        String translate = cursor.getString(cursor
                .getColumnIndex(Word.TRANSLATE));
        String example = cursor.getString(cursor.getColumnIndex(Word.EXAMPLE));
        String note = cursor.getString(cursor.getColumnIndex(Word.NOTE));

        // Master/Detail
        if ((getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
                && (getResources().getString(R.string.selected_configuration)
                        .equals(Constants.CONFIGURATION_LARGE))) {

            WordDetailFragment frag = (WordDetailFragment) getFragmentManager()
                    .findFragmentById(R.id.word_detail_fragment);

            if (frag != null) {
                frag.setId(id);
                frag.setName(name);
                frag.setType(type);
                frag.setTranslate(translate);
                frag.setExample(example);
                frag.setNote(note);
            }

        } else if (firstCall) {
            // Do nothing

        } else {

            Intent i = new Intent(getActivity().getApplicationContext(),
                    WordDetailActivity.class);

            i.putExtra(Word.ID, id);
            i.putExtra(Word.NAME, name);
            i.putExtra(Word.TYPE, type);
            i.putExtra(Word.TRANSLATE, translate);
            i.putExtra(Word.EXAMPLE, example);
            i.putExtra(Word.NOTE, note);

            startActivity(i);
        }
        cursor.close();
        }

    }

    public void onWordSaved() {
        getLoaderManager().restartLoader(URL_LOADER, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle) {
        String[] projection = { Word.ID, Word.NAME, Word.TYPE, Word.TRANSLATE,
                Word.EXAMPLE, Word.NOTE };

        /* Takes action based on the ID of the Loader that's being created */

        switch (loaderID) {
        case URL_LOADER:

            // Returns a new CursorLoader
            cursorLoader = new CursorLoader(getSherlockActivity(), // Parent
                                                                    // activity
                    // context
                    WordListProvider.WORDS_CONTENT_URI, // Table to query
                    projection, // Projection to return
                    null, // No selection clause
                    null, // No selection arguments
                    null // Default sort order
            );
            return cursorLoader;
        default:
            // An invalid id was passed in
            return null;
        }
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        adapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        adapter.swapCursor(null);
    }

}

A: Try adding to your Fragment class:
@Override
protected void onResume()
{
    super.onResume();
    getLoaderManager().restartLoader(URL_LOADER, null, this);
}

public void onLoaderReset(Loader<Cursor> loader) {
    adapter.swapCursor(null);
}

To clear up your efficiency concern: When you call the initial init, it will start, but restartLoader on the same ID will automatically cancel that previous request and start a new one. So it won't get executed fully twice on activity start up.
More info in Google Loader Dev Doco.


text:
Q: Get dependencies from resolve configuration on Gradle 4.1 On previous versions of android plugin for Gradle I could, with my own task, take the path of the jar dependencies using this:
android.libraryVariants.all { variant ->
    task "copyDependencies${variant.name.capitalize()}"(type: Copy) {
        configurations.compile.files().each { dependency ->
            from dependency.path
        }
        into project.projectDir.path + "/build/libs/${variant.name}"
    }
}

But in the latest version of this plugin, compile pass to deprecated and they introduced api and implementation configurations, so when I try to use the previous code, gradle said that:

Resolving configuration 'api' directly is not allowed

Any suggestion for this new change introduced?

UPDATE
I have got a dependencies list and filter for configurations doing this:
android.libraryVariants.all { variant ->

    task "copyDependencies${variant.name.capitalize()}"(type: Copy) {
        from {
            variant.getCompileConfiguration().files().each { dependency ->
                configurations.api.getDependencies().each { configDep ->
                    if (dependency.name.contains(configDep.name)) {
                        from dependency.path
                    }
                }
            }
        }
        into project.projectDir.path + "/build/libs/${variant.name}"
    }
}

But this solution still has problems, in addiction when project B is dependent on project A. Both with this task defined, Gradle doesn't build.

A: Finally, I found a solution for copy dependencies from a configuration:
android.libraryVariants.all { variant ->
    task "copyDependencies${variant.name.capitalize()}"() {
        outputs.upToDateWhen { false }
        doLast {
            println "Executing from in copyDependencies${variant.name.capitalize()}"
            variant.getCompileConfiguration().getAllDependencies().each { dependency ->
                configurations.api.getDependencies().each { configDep ->
                    if (dependency.name.contains(configDep.name)) {
                        println "Dependency detected: " + dependency.name
                        variant.getCompileClasspath().each { fileDependency ->
                            if (fileDependency.absolutePath.contains(dependency.name)) {
                                println fileDependency.absolutePath
                                copy {
                                    from fileDependency.absolutePath
                                    into project.projectDir.path + "/build/intermediates/bundles/${variant.name}/libs"
                                    exclude '**/classes.jar'
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

A: Please see chapter 48.4 of the userguide to find all available configurations and which are to be consumed and / or resolved.


text:
Q: Let L be a language over {a,b} that contains the same number of occurrences of a and b. Which of the following language is regular? (https://i.stack.imgur.com/lU278.png)
Why option C is also not correct?

A: Let's evaluate each one in turn. Let L be the language over {a, b} with #a = #b.
(a) L intersect ab. This is the language of strings of the form a^n b^n. This is not regular by the Myhill-Nerode theorem since each string a^k has a unique shortest string b^k which can be appended to get a string in the language, and there are clearly infinitely many such cases, so there can be no finite automaton for the language.
(b) (L intersect ab) union ab. This is regular because (L intersect ab) is clearly a subset of ab, but the union of a subset with any of its supersets is the superset; thus, (L intersect ab) union ab = ab which is regular since it has just three unique equivalence classes: those strings which can be followed by ab to get a string in the language; those that can only be followed by b* to get a string in the language; and those strings which cannot be followed by anything to get a string in the language.
(c) L union ab. This is not regular because strings of the form b^(k+1)a have unique shortest strings a^k which can be appended to get a string in the language, and there are clearly infinitely many such cases, so there can be no finite automaton to cover them all.
(d) (L intersect ab) union ba. This is not regular because strings of the form a^(k+1)b have unique shortest strings b^k which can be appended to get strings in the language, and there are infinitely many such cases, so no finite automaton can cover them all.


text:
Q: Delphi 2010 RTTI : Use TValue to store data I would like to be able to use TValue to store Data in a TList<>. Like in :
type
  TXmlBuilder = class
  type
    TXmlAttribute = class
      Name: String;
      Value: TValue; // TValue comes from Rtti
    end;

    TXmlNode = class
      Name: String;
      Parent: TXmlNode;
      Value: TXmlNode;
      Attributes: TList<TXmlAttribute>;
      Nodes: TList<TXmlNode>;
      function AsString(Indent: Integer): String;
    end;
  ...
  public
    ...
    function N(const Name: String): TXmlBuilder;
    function V(const Value: String): TXmlBuilder;
    function A(const Name: String; Value: TValue): TXmlBuilder; overload;
    function A<T>(const Name: String; Value: T): TXmlBuilder; overload;
    ...
 end;

implementation

function TXmlBuilder.A(const Name: String; Value: TValue): TXmlBuilder;
var
  A: TXmlAttribute;
begin
  A := TXmlAttribute.Create;
  A.Name := Name;
  A.Value := Value;
  FCurrent.Attributes.Add(A);
  Result := Self;
end;

function TXmlBuilder.A<T>(const Name: String; Value: T): TXmlBuilder;
var
  V: TValue;
begin
  V := TValue.From<T>(Value);
  A(Name, V);
end;

And a bit later, in the main program, I use my "fluent" xml builder like this :
b := TXmlBuilder.Create('root');
b.A('attribute', 1).A('other_attribute', 2).A<TDateTime>('third_attribute', Now);

On the second call, the program raises an access violation exception.
It looks like the first TValue has been "freed". Is it really possible to use TValue to store "Variant" data a runtime ?
I know that Variants exists in Delphi. My XML builder will be used to (de)serialize native delphi objects to XML using RTTI so I will be using TValue everywhere.
regards,
--
Pierre Yager

A: I found the answer. My mistake.
function TXmlBuilder.A<T>(const Name: String; Value: T): TXmlBuilder;
var
  V: TValue;
begin
  V := TValue.From<T>(Value);
  Result := A(Name, V); // I missed the return value
end;

Sorry ;-)


text:
Q: Drupalchat causing unlimited number of guest users? After launching my site, I noticed that the guest users jump from 0 to 45 in seconds. It seems to increase without ever stopping. It worked fine locally, but it seems that the "Sessions" aren't sticking and it's thinking each user is a new user.
I'm using Centos, with Drupal 7 and the DrupalChat module. I did add some custom code, but nothing that should cause this. And like I said, it works locally.
I suppose there is a chance that even though the site is hidden from prying eyes, that it could still be something creating 45 viewers. But I dont know what. Any ideas?
UPDATE
It's probably only getting to 45 users, because it is picking up SOMETHING as a new user, and then losing track of it. 45 seconds later it expires and that user is shown as offline.
UPDATE
Every time cron runs, it seems to think a new user is accessing the site. I.e. Every time I open cron.php, it shows the user as active. Why would it be doing that and how do I fix it?

A: I fixed this by setting a session variable when cron runs and then where the module asks on which pages to display it, I return false if the session variable is set.
It's definitely a hack, but the real solution is to propose quite a few changes to the module.


text:
Q: Centering title of toolbar while working with BottomNavigationView and jetpack
*

*Home screen (first time loading)

*Navigating to 2nd option from the bottom navigation

To center the title on the ActionBar for each selected screen/fragment (as working with BottomNavigationView) I created the custom toolbar to hide the default title and display it at the center of the toolbar, code given below.
XML part
<?xml version="1.0" encoding="utf-8"?>
   <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".bkk_revamp.home_screen.HomeScreenActivity">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:titleTextColor="@color/white"
            android:paddingBottom="15dp">

            <TextView
                android:id="@+id/title_toolbar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:textSize="20sp"
                android:textColor="@color/white"
                android:layout_gravity="center_horizontal"/>

        </androidx.appcompat.widget.Toolbar>

        <androidx.appcompat.widget.SearchView
            android:id="@+id/search"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginStart="30dp"
            android:layout_marginEnd="30dp"
            android:background="@drawable/search_box"
            android:iconifiedByDefault="false"
            app:layout_constraintBottom_toBottomOf="@+id/toolbar"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/toolbar">

            <requestFocus />
        </androidx.appcompat.widget.SearchView>

        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_gravity="bottom"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/search"
            app:navGraph="@navigation/app_navigation" />
        <!--android:layout_height="wrap_content"-->

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="#F5F5F5"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/bottom_navigation_menu" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/drawer_navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:itemIconTint="@color/colorPrimary"
        app:menu="@menu/drawer_navigation_menu" />

</androidx.drawerlayout.widget.DrawerLayout>

Activity code:
toolbar = findViewById(R.id.toolbar);
titleToolbar = toolbar.findViewById(R.id.title_toolbar);
setSupportActionBar(toolbar);
NavigationUI.setupActionBarWithNavController(this, navController);
NavigationUI.setupWithNavController(toolbar, navController, drawerLayout);

navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {

        @Override
        public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
            if(destination.getId()== R.id.profileFragment || destination.getId()== R.id.settingsFragment){
                bottomNavigationView.setVisibility(View.GONE);
            }
            else{
                bottomNavigationView.setVisibility(View.VISIBLE);
            }

            titleToolbar.setText(toolbar.getTitle());
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
    });

it works well on app loading but as another option is clicked from the bottom navigation the default screen label also starts appearing, how can display only one title and at the center of the toolbar.

A: I assume you tried this?
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");


text:
Q: How to show categories total in labels using highcharts I'm trying to show the total in xAxis labels (categories) in the following JSFIDDLE:
    ...
    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas'],
        labels: {
            formatter: function() {
                return this.value + ' (' + 'total?' + ')';
            }
        }
    },
    ...

Someone knows how could I get the total there?

A: The main problem here is that total and all other points are not yet generated, so you need to calculate total on your own, for example:
    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas'],
        labels: {
            formatter: function() {
                var index = this.axis.categories.indexOf(this.value),
                    sum = 0;

                $.each(this.axis.series, function(i, s) {
                   sum += s.options.data[index];
                });

                return this.value + ' (' + sum + ')';
            }
        }
    },

Demo: http://jsfiddle.net/jnkpvreL/


text:
Q: WebGL Uniform Argument Type I am attempting to write a WebGL image filter using the PixiJS library.  My filter should take an array of arrays, where each inner array represents a possible pixel color.  The function will then decide which element in the outer array to use.
I have managed to write a simple GLSL function which takes a single color array as a "uniform" argument, however I can't figure out how to pass the nested array.  Could you point me to the proper type declaration to accept a nested array of floats from this snippet?

var fragmentSrc = [
  "uniform vec4 colorList;", // WHAT TYPE DO I NEED HERE TO PASS THE ARRY IN THE COMMENT BELOW?
  "void main() {",
  "  float GrayScale =  (gl_FragCoord.r * 299.0 / 1000.0) + (gl_FragCoord.g * 587.0 / 1000.0) + (gl_FragCoord.b * 114.0 / 1000.0);",
  "  float sigmoidThreshold = 1.0 / (1.0 + pow(2.7182818284590452353602874713527, (-((GrayScale - 128.0) /32.0))));",
  "  gl_FragColor = colorList;",
  "}",
];

var renderer = PIXI.autoDetectRenderer(750, 750);
document.body.appendChild(renderer.view);
var stage = new PIXI.Container();

function CustomFilter(fragmentSource) {

  PIXI.Filter.call(this,
    null,
    fragmentSource
  );
}

CustomFilter.prototype = Object.create(PIXI.Filter.prototype);
CustomFilter.prototype.constructor = CustomFilter;

var bg = new PIXI.Graphics();
bg.drawRect(0, 0, 375, 375);
bg.endFill();
stage.addChild(bg);

var filter = new CustomFilter(fragmentSrc.join('\r\n'));
filter.uniforms.colorList = [1.0, 1.0, 0.0, 1.0] // WANT TO PASS AN ARRAY OF ARRAYS LIKE:
// [[1.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]]
bg.filters = [filter];

renderer.render(stage);
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.5.1/pixi.min.js"></script>

var fragmentSrc = [
  "uniform vec4 colorList;", // WHAT TYPE DO I NEED HERE TO PASS THE ARRY IN THE COMMENT BELOW?
  "void main() {",
  "  float GrayScale =  (gl_FragCoord.r * 299.0 / 1000.0) + (gl_FragCoord.g * 587.0 / 1000.0) + (gl_FragCoord.b * 114.0 / 1000.0);",
  "  float sigmoidThreshold = 1.0 / (1.0 + pow(2.7182818284590452353602874713527, (-((GrayScale - 128.0) /32.0))));",
  "  gl_FragColor = colorList;",
  "}",
];

A: I changed the code to this
var fragmentSrc = `
  uniform vec4 colorList[10];
  void main() {
    float GrayScale =  (gl_FragCoord.r * 299.0 / 1000.0) + (gl_FragCoord.g * 587.0 / 1000.0) + (gl_FragCoord.b * 114.0 / 1000.0);
    float sigmoidThreshold = 1.0 / (1.0 + pow(2.7182818284590452353602874713527, (-((GrayScale - 128.0) /32.0))));
    gl_FragColor = colorList[9];
  }
`;

var filter = new CustomFilter(fragmentSrc);
console.log(filter.uniforms);

And it prints

so this works
filter.uniforms.colorList = [
   1, 0, 0, 0,     // 0
   1, 1, 0, 0,     // 1
   0, 1, 0, 0,     // 2
   0, 1, 1, 0,     // 3
   0, 0, 1, 0,     // 4
   1, 0, 1, 0,     // 5
   .5, 0, 0, 0,    // 6
   0, .5, 0, 0,    // 7
   1, 1, 0, 1,     // 8
   .5, .5, .7, 1., // 9
];

and this
filter.uniforms.colorList = new Float32Array([
   1, 0, 0, 0,     // 0
   1, 1, 0, 0,     // 1
   0, 1, 0, 0,     // 2
   0, 1, 1, 0,     // 3
   0, 0, 1, 0,     // 4
   1, 0, 1, 0,     // 5
   .5, 0, 0, 0,    // 6
   0, .5, 0, 0,    // 7
   1, 1, 0, 1,     // 8
   .5, .5, .7, 1., // 9
]);

etc...
If you really want an array of arrays in JavaScript you can do this to make ArrayBufferViews into the larger array
const colorValues = [];
for (let i = 0; i < filter.uniforms.colorList.length; i += 4) {
  const buffer = filter.uniforms.colorList.buffer;
  const byteOffset = i * Float32Array.BYTES_PER_ELEMENT;
  const length = 4;
  colorValues.push(new Float32Array(buffer, byteOffset, length));
}

now you can set an array element like this
colorValues[9].set([1, 1, 0, 1]);

var fragmentSrc = `
  uniform vec4 colorList[10]; // WHAT TYPE DO I NEED HERE TO PASS THE ARRY IN THE COMMENT BELOW?
  void main() {
    float GrayScale =  (gl_FragCoord.r * 299.0 / 1000.0) + (gl_FragCoord.g * 587.0 / 1000.0) + (gl_FragCoord.b * 114.0 / 1000.0);
    float sigmoidThreshold = 1.0 / (1.0 + pow(2.7182818284590452353602874713527, (-((GrayScale - 128.0) /32.0))));
    gl_FragColor = colorList[9];
  }
`;

var renderer = PIXI.autoDetectRenderer(750, 750);
document.body.appendChild(renderer.view);
var stage = new PIXI.Container();

function CustomFilter(fragmentSource) {

  PIXI.Filter.call(this,
    null,
    fragmentSource
  );
}

CustomFilter.prototype = Object.create(PIXI.Filter.prototype);
CustomFilter.prototype.constructor = CustomFilter;

var bg = new PIXI.Graphics();
bg.drawRect(0, 0, 375, 375);
bg.endFill();
stage.addChild(bg);

var filter = new CustomFilter(fragmentSrc);
const colorValues = [];
for (let i = 0; i < filter.uniforms.colorList.length; i += 4) {
  const buffer = filter.uniforms.colorList.buffer;
  const byteOffset = i * Float32Array.BYTES_PER_ELEMENT;
  const length = 4;
  colorValues.push(new Float32Array(buffer, byteOffset, length));
}

colorValues[9].set([1, 1, 0, 1]);

bg.filters = [filter];

renderer.render(stage);
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.5.1/pixi.min.js"></script>


text:
Q: Ice Cream Sandwich(Api14) android users keeps reporting StackOverflowError error Certain 4.0.1-4.0.2 users keep reporting this StackOverflowError error in my application in my Google Play developer account, how can I decide which Fragment/layout is causing the problem?? I have been trying to fix it for a week now but still no luck
at android.graphics.Paint.getTextRunAdvances(Paint.java:1691)
at android.text.TextLine.handleText(TextLine.java:745)
at android.text.TextLine.handleRun(TextLine.java:972)
at android.text.TextLine.drawRun(TextLine.java:397)
at android.text.TextLine.draw(TextLine.java:199)
at android.text.Layout.draw(Layout.java:425)
at android.widget.TextView.onDraw(TextView.java:5241)
at android.view.View.draw(View.java:11118)
at android.view.View.getDisplayList(View.java:10557)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.draw(View.java:11121)
at android.view.View.getDisplayList(View.java:10557)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.draw(View.java:11121)
at android.view.View.getDisplayList(View.java:10557)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.draw(View.java:11121)
at android.view.View.getDisplayList(View.java:10557)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.draw(View.java:11121)
at android.view.View.getDisplayList(View.java:10557)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.support.v7.widget.RecyclerView.drawChild(Unknown Source)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.draw(View.java:11121)
at android.support.v7.widget.RecyclerView.draw(Unknown Source)
at android.view.View.getDisplayList(View.java:10557)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2502)
at android.view.View.draw(View.java:11121)
at android.view.View.getDisplayList(View.java:10557)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.draw(View.java:11121)
at android.support.v4.view.ViewPager.draw(Unknown Source)
at android.view.View.getDisplayList(View.java:10557)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.draw(View.java:11121)
at android.widget.FrameLayout.draw(FrameLayout.java:450)
at android.view.View.getDisplayList(View.java:10557)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.support.v4.widget.DrawerLayout.drawChild(Unknown Source)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.draw(View.java:11121)
at android.widget.FrameLayout.draw(FrameLayout.java:450)
at android.view.View.getDisplayList(View.java:10557)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.getDisplayList(View.java:10555)
at android.view.ViewGroup.drawChild(ViewGroup.java:2856)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
at android.view.View.draw(View.java:11121)
at android.widget.FrameLayout.draw(FrameLayout.java:450)
at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2290)
at android.view.View.getDisplayList(View.java:10557)
at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:840)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2049)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1773)
at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2585)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4507)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)


text:
Q: Extracting information from an attribute using goquery package main

import (
    "fmt"
    "github.com/PuerkitoBio/goquery"
    "net/http"
)

func main() {

    url := "https://books.toscrape.com"

    resp, err := http.Get(url)

    if err != nil {
        fmt.Println(err)
    }

    defer resp.Body.Close()

    doc, err := goquery.NewDocumentFromReader(resp.Body)

    if err != nil {
        fmt.Println(err)
    }

    doc.Find(".product_pod").Each(func(i int, selection *goquery.Selection) {
        title := selection.Find(".image_container").Find("img")
        price := selection.Find(".price_color").Text()
        fmt.Printf("Title: %s, Price: %s\n", title, price)
    })
}

I am trying to use goquery to extract the Title from https://books.toscrape.com, I already extracted the prices, but I am having trouble extracting the title since it has multiple attributes.
This is how you print it with the colly library
Except, I'm not trying to do it with the colly, I'm trying to do it with goquery.
Here is the website: https://books.toscrape.com
   title := e.ChildAttr(".image_container img", "alt")
})```

A: You can use Selection.Attr("alt") to select alt attribute of the current element:
doc.Find(".product_pod").Each(func(i int, selection *goquery.Selection) {
    title, _ := selection.Find(".image_container img").Attr("alt")
    price := selection.Find(".price_color").Text()
    fmt.Printf("Title: %s, Price: %s\n", title, price)
})

Note that Attr() returns 2 values: the attribute value and boolean wether the value exists (for some weird reason), so you need to unpack the values as in the example above (the title, _ =  part)


text:
Q: Counting data categories on excel For the last part of my genome analysis I have to make a pie chart related to gene function. I have an excel spreadsheet with the gene function and the corresponding letter category (COG letter column D in screenshot), to make the pie chart I need to filter by column C so I can adjust the number of genomes depending on which ones I am looking at in certain parts of the analysis and then count how many times this letter appears in the list of ~4000 genes. After filtering by Column C, I would like to make a table that looks like the second screenshot. The issue is some letters appear more than once e.g. EGP (row 40 - would need to be counted as one E and one G and one P separately in the table for the pie chart). Any advice/formulas greatly appreciated.

A: You can use COUNTIF with wildcards.  For example:
=COUNTIF(D:D,"*E*")

will count both a standalone "E" as well as the E in "EGP".


text:
Q: Export raster with its min max range from GEE I'm trying to export a raster as GeoTIFF from GEE and keep it's min max range (pixel value) so I can import the raster into ArcGIS and check it's min, max, mean and std.dev. in Symbology. My attempt so far can only manage to export the raster layer with a green color but when imported into ArcGIS all min, max, mean and std. dev. is 0.
Here is the code I have tried:
var Blueskin =ee.Image('COPERNICUS/S2/20160721T223713_20160722T000334_T59GMK');
var Red=Blueskin.select('B4');
var NIR=Blueskin.select('B8');
var ndvi = NIR.subtract(Red).divide(NIR.add(Red)).rename('NDVI');
var mean = ee.Number(stats.get('NDVI_mean'));
var std = ee.Number(stats.get('NDVI_stdDev'));
//find regions (Ulva) in ndvi has value higher than mean +1SD
var maskImage = ndvi.updateMask(ndvi.gt(mean.add(std)));
Map.addLayer(maskImage, {palette: 'green'}, 'mask image');
//get Ulva region max min
var stats = maskImage.reduceRegion({
  reducer: ee.Reducer.minMax(),
  bestEffort: true,
});

// Display min and max
print(stats);
//it's a bit confusing here but NDVI_min =maskImage_min according to print I just don't know how to change the name
var NDVI_min = ee.Number(stats.get('NDVI_min'));
var NDVI_max = ee.Number(stats.get('NDVI_max'));
print(NDVI_min);
print(NDVI_max);
var visualization_params =  {min: NDVI_min, max: NDVI_max, palette:'green'};
// Export a cloud-optimized GeoTIFF.
Export.image.toDrive({
  image: maskImage.visualize(visualization_params),
  description: '21072016UNDVI',
  scale: 10,
  region: table,
  fileFormat: 'GeoTIFF',
  formatOptions: {
    cloudOptimized: true
  }
});

The min and max I set in the visualization_params doesn't seem to work and I can't use ee.Reducer.minMax() as an argument in visualization_params..


text:
Q: PSD specifications help I'm writing a program (in Python for now) for reading PSD files. I'm using this specification: http://www.fileformat.info/format/psd/egff.htm
Here it says

BYTE Name[];   /* Even-length Pascal-format string, 2 bytes or longer
  */

Um, 2 bytes or longer? How am I supposed to find out how ling it is? I don't know what "Pascal-format string" means either.
Thanks in advance.
EDIT: Heres a direct link to the official PSD specification (pdf): http://forums.adobe.com/servlet/JiveServlet/download/2923119-45984/Photoshop%20File%20Formats.pdf;jsessionid=21F2DBA32AB9E56882065663C10A1EBF.node0
Look in page 9, under "Image Resource Blocks"
Please help.

A: "Pascal-format string" could mean string that have length encoded on first position IIRC.


text:
Q: Surveymonkey API: per_page defaults and max We are calling the /contacts API for SurveyMonkey.  Docs are here.  We need to get all active contacts, and I'm wondering about the paging feature.  If we don't specify a per_page parameter, will we truly get all active contacts?  Or will we get the first page only?  There is no default listed for per_page, unfortunately, so I don't know how it will act.
A quick follow-up to this is wondering if there is a max for this field.  If there is a default per_page, and I need to mess with paging, what is the max I can set per_page to?
We currently don't have a ton of contacts so it's tough to test the defaults/max.

A: By default, all list endpoints unless specified otherwise can accept a max page size of 1000 resources as specified under Request and Response Limits. Perhaps that should (also?) be under Pagination. Some bulk endpoints for example, have a max page size of 100.
I don't see in the docs what the page size is by default, but it is 50. So if you don't specify the number of resources to return, you will get up to 50 back.


text:
Q: Do I need to release the object in php? Previously I've used Objective-C in iPhone Development.  It seems I need to do some work in the back-end site, I chose PHP for this.  In Objective-C, I need to release objects after I use them.  Do I need to do this in PHP also? Thank you.

A: 99.9% of the time, no you do not need to delete the object. PHP has a garbage collector that will handle that for you. The garbage collector will free a given instance of memory once it is no longer needed in your code.
To read more:
http://php.net/manual/en/features.gc.php

A: Not for memory, PHP uses garbage collection. Objects are released at some point after they become unreachable (not instantly as some simplified introductions claim) to your code. This includes reference cycles since a few versions (a references b, b references a) - previously, it used reference counting only and thus failed in the face of such cycles.
Resources (files, database connections, etc.) might happen to be closed when they are collected, but since the time of collection is non-deterministic and whether that closes them depends on the resource in question, it's propably a very bad idea to just leave them when you're done with them.

A: You don't except for persistent database connections.
http://php.net/manual/en/language.types.resource.php

A: No. You don't! Php has a garbage collector that take care of memory handling for you.


text:
Q: When Trying to Import Old Visual FoxPro Database into SQL receiving "Cannot find column -1" I have a ton Visual FoxPro db files that I am trying to import into an empty SQL 2008 Express database.  When I run through the SQL Import and Export Wizard everything seems to communicate fine.  When I get to the mappings section I can click on preview and see the data in the selected FP table.  When I click on Edit Mappings or Next I get:
===================================
Column information for the source and destination data could not be retrieved.

"eqr_sellers" -> [dbo].[eqr_sellers]:

           - Cannot find column -1.
 (SQL Server Import and Export Wizard)
===================================

Cannot find column -1. (System.Data)

------------------------------
Program Location:

   at System.Data.DataColumnCollection.get_Item(Int32 index)
   at Microsoft.DataTransformationServices.Controls.ProviderInfos.MetadataLoader.LoadColumnsFromTable(IDbConnection myConnection, String[] strRestrictions)
   at Microsoft.SqlServer.Dts.DtsWizard.OLEDBHelpers.LoadColumnsFromTable(MetadataLoader metadataLoader, IDbConnection myConnection, String[] strRestrictions, DataSourceInfo dsi)
   at Microsoft.SqlServer.Dts.DtsWizard.TransformInfo.PopulateDbSourceColumnInfoFromDB(IDbConnection mySourceConnection)
   at Microsoft.SqlServer.Dts.DtsWizard.TransformInfo.PopulateDbSourceColumnInfo(IDbConnection mySourceConnection, ColumnInfoCollection& sourceColInfos)

Any insight would be appreciated.

A: What are the data types?  Auto-Increment Integer fields are not supported by the ODBC connectors I have used in the past.


text:
Q: MongoDB slow aggregate time I'm facing an issue where the aggregate function is performing very slowly where it takes about 30 seconds to gather all my data. Assume 1 of the record in this structure:
{
    "_id":{
        "$oid":"5909a5cefece40f172895a6b"
    },
    "Record":1,
    "Link":"https://www.google.com",
    "Location":["loc1", "loc2", "loc3"],
    "Organization":["org1", "org2", "org3"],
    "Date":2017,
    "PeoplePPL":["ppl1", "ppl2", "ppl3"]
}

And the aggregate query as follows:
db.testdata_4.aggregate([{
    "$unwind": "$PeoplePPL"
},{
    "$unwind": "$Location"
},{
    "$match": {
        Date: {
            $gte: lowerBoundYear,
            $lte: upperBoundYear
        }
    }
},{
    "$group": {
        "_id": {
            "People": "$PeoplePPL",
            "Date": "$Date"
        },
        Links: {
            $addToSet: "$Link"
        },
        Locations: {
            $addToSet: "$Location"
        }
    }
},{
    "$group": {
        "_id": "$_id.People",
        Record: {
            $push: {
                "Country": "$Locations",
                "Year": "$_id.Date",
                "Links": "$Links"
            }
        }
    }
}]).toArray()

There are a total of 154 records in the "testdata_4" collection, and upon aggregation, there will be 5571 records returned with the query time of 28 seconds. I have performed the ensureIndex() on "Locations" and "Date". Is this supposed to be normal as the number of records returned increases?
If it isn't normal, may I know if there's a workaround to decrease my query time to 5 seconds at max instead of having it at 28 seconds or more?

A: It's very likely that the index on Date isn't being used.
The $match and $sort operators can take advantage of indexes when they are being used at the beginning of the pipeline. In this case, the filters are applied after several $unwind stages, which mean it likely isn't be used.
Suggestions:

*

*Move the $match stage to the beginning of the pipeline

*The "Location", "Date" and "Link" fields aren't arrays, so it isn't immediately clear why there are $unwind aggregation stages on these fields. You may want to remove these.


text:
Q: Correct NodeJS server for Vue.js application I'm using Vue.js and the vue-router and would like to server the static files via Node.JS.
So I've create server.js with the following code:
// server.js
var express = require('express');

var path = require('path');

var serveStatic = require('serve-static');

app = express();
app.use(serveStatic(__dirname + "/dist"));

var port = process.env.PORT || 5000;

app.listen(port);

console.log('server started '+ port);

It seems to work, but only when I click around.
If I visit ex. my-url.com/some-path/another-path it fails.
Am I missing something?
Ex. I'm getting:
Cannot GET /cars with I type www.my-domain.com/cars into the address bar in the browser, but visiting www.my-domain.com and clicking on cars does work.

A: You need to setup your server to redirect users to the appropriate server location.  Please read the Vue Router - HTML5 History Mode docs.

When using history mode, the URL will look "normal," e.g.
  http://oursite.com/user/id. Beautiful!
Here comes a problem, though: Since our app is a single page client
  side app, without a proper server configuration, the users will get a
  404 error if they access http://oursite.com/user/id directly in
  their browser. Now that's ugly.
Not to worry: To fix the issue, all you need to do is add a simple
  catch-all fallback route to your server. If the URL doesn't match any
  static assets, it should serve the same index.html page that your
  app lives in. Beautiful, again!

The main thing that you need to do is have all routes lead to the root route.  Alternatively, since you are using Express, you can leverage the connect-history-api-fallback which the Vue Router docs recommend.


text:
Q: Plotting fewer wind barbs in NorthPolarStereo projection in python I want to plot maps for sea level pressure and wind using the NorthPolarStereo projection. I managed to plot the pressure in contours and the windbarbs, but I can't adjust the wind barbs in any way. When plotting it in PlateCaree projection, I can plot every second lat/lon for u and v, which thinned out the wind barb field. However, the same method does not work for this projection and I don't know why.
Below is the part of my code that I use to plot the sea level + wind map and that won't let me alter the wind barbs:
vcs=np.arange(-3,3.2,0.2)
slplevels=[980,985,990,995,1000, 1005, 1010, 1015,1020, 1025,1030,1035]

ax3 = plt.subplot(4,2,3, projection=ccrs.NorthPolarStereo())
ax3.set_extent([coord_east, coord_west, coord_south, coord_north], crs.PlateCarree())
ax3.coastlines(linewidth=1.5)

data, lon = add_cyclic_point(slp_2, slp_2['lon'])

slp2=ax3.contourf(lon,slp_2["lat"][:], data/100, levels=vcs,
            transform = data_crs, extend='both', cmap=plt.get_cmap('coolwarm'))

ax3.barbs(u10_2['lon'][::2].values, u10_2['lat'][::2].values, u10_2[::2,::2].values,
      v10_2[::2,::2].values, transform=ccrs.PlateCarree(), pivot='middle',
         sizes=dict(emptybarb=0.0000001, height=0.5),
         length=4, color='black', regrid_shape=35,
      linewidth=1, alpha=0.8, barb_increments=dict(half=.5, full=1, flag=5))

stipples=ax3.contourf(slp_std_2['lon'][:], slp_std_2['lat'][:],
                 slp_std_2[:,:]/100, colors='none', levels= np.arange(0.1,6,0.1), transform = data_crs,
                 hatches=['..'])

sclim=ax3.contour(sc['lon'], sc['lat'], sc[:,:]/100, levels=slplevels,
          transform = data_crs, extend='both', colors='black', alpha=0.7)

plt.clabel(sclim, inline=1, fontsize=18, fmt='%1.0f',
                  colors='black')

cbar_slp = plt.colorbar(slp2, ax=ax3, ticks=[-3.0,-2.0,-1.0,0,1.0,2.0,3.0], extend='both', orientation='horizontal', fraction=0.046, pad=0.04)
cbar_slp.ax.tick_params(labelsize=18)
cbar_slp.ax.set_xlabel('hPa', fontsize=18)


text:
Q: Custom Drawn Component Not Drawing Inside JScrollPane I was using Java JRE 1.6.7 and had a JComponent and a JScrollPane.  I couldn't get double buffering to work on this which always resulted in a flicker.  I had the buffering taken care of if I used a Canvas, but this resulted in problems when used in conjunction with a JScrollPane.
So I downloaded JRE 1.6.18 in hopes that one of these problems would be fixed.  Well now the JComponent inside the JScrollPane is not drawing properly at all.  It draws only the outside region of the JComponent, as if the JScrollPane is drawing on top of it except for the borders.
Here is an example of code that is not drawing..this results in a 1-pixel-wide white outline of the area where drawing should occur:
public void paint(Graphics arg0) {

Graphics2D graphics = (Graphics2D) arg0;

  graphics.setColor(Color.WHITE);
  graphics.fillRect(0, 0, (int) getWidth(), (int) getHeight());

Any help is greatly appreciated!
-Craig

A: try to make an override from paintComponent(Graphics g) instead of paint(Graphics g).
paintComponent is the method you have to override for costum drawing.
Are you sure you can see the white rectangle, try to use red or something else you can see good.

A: It looks like you're making progress, but you might like to see the tutorial examples, too.
Martijn Courteaux's analysis is correct: you should override paintComponent(). Also, it's a bad idea to mix AWT and Swing components. Both ideas are discussed in Painting in AWT and Swing.
Scrolling shouldn't cause flickering. Here's an example that scrolls a grid of components and paints a checkerboard on the background.
import java.awt.*;
import javax.swing.*;

public class Scrolling extends JFrame {

    private static final int MAX = 8;
    private static final int SIZE = 480;
    private static final Color light = new Color(0x40C040);
    private static final Color dark  = new Color(0x408040);

    private static class MyPanel extends JPanel {

        public MyPanel() {
            super(true);
            this.setLayout(new GridLayout(MAX, MAX, MAX, MAX));
            this.setPreferredSize(new Dimension(SIZE, SIZE));
            for (int i = 0; i < MAX * MAX; i++) {
                this.add(new JLabel(String.valueOf(i), JLabel.HORIZONTAL));
            }
        }

        @Override
        public void paintComponent(final Graphics g) {
            int w = this.getWidth()/MAX;
            int h = this.getHeight()/MAX;
            for (int row = 0; row < MAX; row++) {
                for (int col = 0; col < MAX; col++) {
                    g.setColor((row + col) % 2 == 0 ? light : dark);
                    g.fillRect(col * w, row * h, w, h);
                }
            }
        }
    }

    public Scrolling() {

        this.setLayout(new BorderLayout());
        final MyPanel panel = new MyPanel();
        final JScrollPane scrollPane = new JScrollPane(panel);
        scrollPane.getHorizontalScrollBar().setUnitIncrement(16);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        this.add(scrollPane, BorderLayout.CENTER);
        this.pack();
        this.setSize(SIZE - SIZE / 3, SIZE - SIZE / 3);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
    }

    public static void main(final String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Scrolling().setVisible(true);
            }
        });
    }
}

A: Ok, I've come up with a slight answer.
Instead of calling
scrollPane.add(containerCanvas);

I'm calling
new JScrollPane(containerCanvas);

This works in a sense.  However, it now is disallowing the JScrollPane bars from showing up.  I have no idea why this is, but am currently looking into it.  But at least the component is drawing again.


text:
Q: Part of view with storyboard So I'm working on a Google Maps-app, and I want a certain behavior. When tapping a marker I want the "Detail View", displayed below to popup. If swiping that detail view up I want it to cover the whole screen and make "MORE DETAIL" appear. If swiping down, it will close it.

I just can't figure out how to implement this behavior. Container View? Just a regular UIView wit gesture recognizer? Modal segue?
I'm not asking for code, just some words to get me on the right track.
Edit: For anyone else looking for this kind of behavior, every answer below is perfectly fine. I went with the container view, since the detail view is doing some network requests and UITableView work.

A: go with UIView and UIGestureRecognizer, it would be faster and simpler. Modal segue does not cover the whole page as you want, and container view is too much work to put on just a simple thing

A: Can be done with Pan gesture and I would say by having Parent ViewController (Container) and Child ViewController instead UIView. Let me know if you would need more help :)


text:
Q: Characterization of the geometric distribution $X,Y$ are i.i.d. random variables with mean $\mu$ , and taking values in {$0,1,2,...$}.Suppose for all $m \ge 0$, $P(X=k|X+Y=m)=\frac{1}{m+1}$ , $k=0,1,...m$. Find the distribution of $X$ in terms of $\mu$.
I have a feeling that $X$ is a geometric random variable. I wrote $P(X=k)=p_k$ and tried to equate the coefficient of $p_k$ on both sides but it was futile. My teacher gave me a hint to try with probability generating functions. But I really can't implement it. Please help.

A: We have
$$
P(X = k | X+Y = m) = \frac{P(X = k \,\&\, Y = m-k)}{P(X+Y = m)} = \frac{p_{k}p_{m-k}}{\sum_{j=0}^{m}p_{j}p_{m-j}} = \frac{1}{m+1}
$$
for all $0\leq k \leq m+1$. In particular, we have
$$
p_{0}p_{m} = p_{1}p_{m-1} = p_{2}p_{m-2} = \cdots = p_{m}p_{0}.
$$
This gives
$$
\frac{p_{1}}{p_{0}} = \frac{p_{m}}{p_{m-1}}
$$
for all $m\geq 1$, so that $p_{m}/p_{m-1}$ is a constant for all $m\geq 1$ and this characterizes $X$ as a geometric distribution.

It seems like we may use generating function as well. If we put
$$
f(x)= \sum_{k\geq 0} p_{k} x^{k},
$$
then the identity actually gives a differential equation
$$
f(x)^{2} = p_{0}(f(x) + xf'(x)) = p_{0}(xf(x))'
$$
with $f(1) = 1$ and $f'(1) = \mu$. I think this will also show that $X, Y$ follows geometric distribution.


text:
Q: Problems with comboBox value and textBox value on C# Im beginner on c#, and i really need some clue how to solve this problem.
I created one project in c#, and in one form i have comboBox with value is numbers between 9-20 and a textBox.
all i want is whenever ComboBox is selected, then TextBox will be set to ComboBox value plus 1.
for example: If ComboBox1 is selected and the value is 11, then TextBox1.Text will be set to 12.
here's my code i've been working on.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e
{
    textBox1.Text = comboBox1.SelectedIndex.ToString() +1;
}

There's nothing's wrong with the code, but i didnt get the value i want, because the result was like if comboBox is selected with value =11, and textBox1.Text is 21, not 12.
thx before :)

A: you have to first convert ComboBox.SelectedValue to int
then add 1 and
then convert it to String
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
   textBox1.Text = Convert.ToString(Convert.ToInt16(comboBox1.SelectedValue) + 1);
}

Edit :
If you are developing Windows Form Application then try this :
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    textBox1.Text = Convert.ToString(Convert.ToInt16(comboBox1.SelectedItem) + 1);
}

A: .ToString() converts the selected index to a string type. The addition operator (+) converts the integer 1 to a string "1", simply appending the digit 1 to your text. Instead you should preserve the SelectedIndex as an integer, perform the addition, then convert to string.
Try the following:
textBox1.Text = (comboBox1.SelectedIndex + 1).ToString();

A: You probably need to use SelectedValue rather than SelectedIndex because the former gets the actual value of the Combo Box item while the latter gets the index of the item in the Combo Box.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e
{
    textBox1.Text = ((int)comboBox1.SelectedValue + 1).ToString();
}


text:
Q: Replace multiple column values in Power Query / Power BI / M code using `List.Zip` I have a Power Query table with a column of values between 1 and 12.
I want to replace the number with a fixed set of values as shown in table below.
Period Number   Period Text
1               Jan
2               Feb
3               Mar
4               Apr
5               May
6               Jun
7               Jul
8               Aug
9               Sep
10              Oct
11              Nov
12              Dec

I have seen a solution using List.Zip that "zips" these values as below:
periodNumber = Table.Column(#"Prev Step", "Period Number"),
periodText = Table.Column(#"Prev Step", "Period Text"),
#"periodRename" = List.Zip({periodNumber, periodText}),

The List.Zip looks like this. Inside each record are two elements.

and then uses them to rename columns by replacing with zipped values as follows:
= Table.RenameColumns(#"Another Prev Step", #"periodRename")

What other function than Table.RenameColumns can make use of this structure? Perhaps some form of Table.ReplaceValue?
My table has a column has 1000's of rows and is in a sequence like below.
Period Number
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
1
2
etc

I want to replace all of these period numbers with their period text.
I like the idea of using List.Zip as it provides a dynamic list of periods, because sometimes the data will not have the entire 12 periods eg only 3 periods. Also the periods could also be quarters eg periodNumber = [1, 2, 3, 4] and periodText = [Q1, Q2, Q3, Q4] or years.
Is there some other way of using List.Zip to replace table values down a column instead of across table columns?
Note: The Period Numbers do not correspond to specific months. The start could be any month, for a 12 month period. So they Period Text will change. Hence need to get them dynamically.

A: Try:
monthName = Table.TransformColumns(#"Previous Step",{"Period Number", each Date.MonthName(#date(2020, _,1))})

Before Transform

After Transform

Edit: Other ways to use transform
months = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"},
...
translate = Table.TransformColumns(#"Previous Table Step",{"Period Number", each months{_-1}})

to use your List.Zip
useful if the mapping is random
 translationList = List.Zip({{1,2,3,4,5,6,7,8,9,10,11,12},{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}}),
...
translate = Table.TransformColumns(typeIt,{"Period Number", each
                    List.Range(List.Combine(translationList),
                        List.PositionOf(List.Combine(translationList),_)+1,1){0}})


text:
Q: During validation, using AJAX request to check DB. Form does not submit when true I have a form for an internal app where I am using client side validation. It's a whole nested javascript thing, with the last call being an AJAX request which checks to make sure there are two or less appointment books at the same time.
If it returns false (there are already 2 appointments booked), it triggers the error correctly. However, when it passes, the form doesn't submit, it just sits there. Does nothing. Well, at this point it pisses me off, but it doesn't do anything else.
$('#save-button').click(function(event){
    var firstAppointmentStartHour = 9;//No appointments before 9 am
    var lastAppointmentEndHour = 16;//No appointments after 4 pm
    if ($('#name').val() != ''){
        if ($('#address').val() != ''){
            if ($('#claim_number').val() != ''){
                if($('#vin').val() != ''){
                    if($('#plate').val() != ''){
                        if($('#appt_start').val() != ''){
                            var startDateTime = Date.parse($('#appt_start').val());
                            var startYear = startDateTime.getFullYear();
                            var startMonth = startDateTime.getMonth() + 1;
                            startMonth = (startMonth.toString().length == 1) ? '0' + startMonth : startMonth; //append a 0 if it is a single digit month
                            var startHour = startDateTime.getHours();
                            var stringStartHour = (startHour.toString().length == 1)? '0' + startHour : startHour; //append a 0 if it is a single digit hour
                            var startDay = startDateTime.getDate();
                            var startMinutes = startDateTime.getMinutes();
                            startMinutes = (startMinutes == '0') ? '00' : startMinutes;
                            var startTime = startHour + startMinutes/60;
                            var stringStartDate = startYear+'-'+startMonth+'-'+startDay+' '+stringStartHour+':'+startMinutes+':00';
                            if (startHour >= firstAppointmentStartHour){
                                if($('#appt_end').val() != ''){
                                    var endDateTime = Date.parse($('#appt_end').val());
                                    var endYear = endDateTime.getFullYear();
                                    var endMonth = endDateTime.getMonth() + 1;
                                    endMonth = (endMonth.toString().length == 1) ? '0' + endMonth : endMonth; //append a 0 if it is a single digit month
                                    var endHour = endDateTime.getHours();
                                    var stringEndHour = (endHour.toString().length == 1)? '0' + endHour : endHour; //append a 0 if it is a single digit hour (ie 9am)
                                    var endDay = endDateTime.getDate();
                                    var endMinutes = endDateTime.getMinutes();
                                    endMinutes = (endMinutes == '0') ? '00' : endMinutes;
                                    var endTime = endHour + endMinutes/60;
                                    var stringEndDate = endYear+'-'+endMonth+'-'+endDay+' '+stringEndHour+':'+endMinutes+':00';
                                    if(endHour <= lastAppointmentEndHour){
                                        if(startDay == endDay){
                                            if(endTime > startTime){
                                                if ( $('#email').val() != ''  || $('#phone').val() != '' ){
                                                    event.preventDefault();
                                                    $.ajax({
                                                        url: "/widgets/collision_center_appointment_calendar/check_overlap/" + stringStartDate + "/" + stringEndDate,
                                                        type: "get",
                                                        success: function(data){
                                                            if (data){
                                                                return true;
                                                            } else {
                                                                showError('**Only two bookings allowed at any time. Please adjust your start and end times**');
                                                                return false;
                                                            }
                                                        },
                                                        error:function(){
                                                            $('#current_appointments').html('There was an error submitting your information... Please contact Team Systems.');
                                                        }
                                                    });
                                                } else {
                                                  showError('**Please enter either a valid phone number or valid email address**');
                                                  return false;
                                                }
                                            } else {
                                                showError('**The appointment start time must be before the appointment end time!**');
                                                return false;
                                            }
                                        } else {
                                            showError('**Start date and end date must be the same day**');
                                            return false;
                                        }
                                    } else {
                                        showError('**The last appointment of the day cant\'t end after 4 pm**');
                                        return false;
                                    }
                                } else {
                                    showError('**Please enter an end date and time**');
                                    return false;
                                }
                            } else {
                                showError('**The first appointment of the day can\'t be prior to 9 am**');
                                return false;
                            }
                        } else {
                            showError('**Please enter a start date and time**');
                            return false;
                        }
                    } else {
                        showError('**Please enter a plate number**');
                        return false;
                    }
                } else {
                    showError('**Please enter a VIN**');
                    return false;
                }
            } else {
                showError('**Please enter a claim number**');
                return false;
            }
        } else {
            showError('**Please enter an address**');
            return false;
        }
    } else {
        showError('**Please enter a name**');
        return false;
    }
});

I don't do a lot of this sort of thing, and am very sure I've screwed up something simple.
Could any one of you fine folks help a brother out?
Thanks in advance.

A: Instead of returning true to cause the form to submit after calling event.preventDefault() you need to call form.submit();
I'd suggest this (http://css-tricks.com/return-false-and-prevent-default/) for further reading on the difference between return false and even.preventDefault(), but basically once you call preventDefault, calling return true will not cause the form to submit.
Also, I'd recommend looking into some validation libaries, like parsleyjs, it may save you some time / clean up your code a bit.


text:
Q: in my webpages some characters changed when uploaded on host but fine in local Asp.net MVC I have implemented a webpage with ASP.net MVC. the problem is that when I type foreign languages special characters like Spätes Frühstück in German language it does not show it and it changed to something else Spätes Frühstück .
I am not sure why this happened and I do not know I should put which codes of the project. and the amazing part is that it works fine when I check it offline in local host, but it show like this when it goes on domain. may it be the server provider problem?
I really appreciate any help. thank you


text:
Q: Angular Observable error handling with async I have a service that collects data and a component to show it the code is as follows:
books.service:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Book} from '../model/book';

@Injectable()
export class BooksService {

  constructor(private http: HttpClient) {
  }

  findAllBooks(): Observable<Book[]> {
    return this.http.get<Book[]>('api/books');
  }

}

list-books.component.ts:
import {Component, OnInit} from '@angular/core';
import {BooksService} from '../../services/books.service';
import {Observable} from 'rxjs/Observable';
import {Book} from '../../model/book';

@Component({
  selector: 'app-list-books',
  templateUrl: './list-books.component.html',
  styleUrls: ['./list-books.component.css']
})
export class ListBooksComponent implements OnInit {

  books: Observable<Book[]>;

  constructor(private booksService: BooksService) {
  }

  ngOnInit() {
    this.books = this.booksService.findAllBooks();
  }
}

list-books.component.html:

      {{book.title}}

Now I would like to handle HTTP Errors (e.g. 404). But I don't know how to properly add error handler without adding subscribe function.

A: use the catchError to handle the errors.
import { catchError } from 'rxjs/operators';

findAllBooks(): Observable<Book[]> {
    return this.http.get<Book[]>('api/books').pipe(
      catchError(error =>  // handle the errore)
    )
  }


text:
Q: Are there English equivalents to "Samurai uses (show off) a toothpick, even he hasn't eaten anything (for a day)"? There is a Japanese proverb, 武士は食わねど高楊子、of which literal translation is "Samurai uses (show off) a toothpick, even he hasn't eaten meal," meaning a Samurai glories in his honorable poverty. Samurais were esteemed as a warrior class, but many of them lived on meager salary. I'm curious to know if there is a similar saying in English.
Yahoo Japan Glossary lists "Better go to bed supper-less than rise in debt" as the equivalent expression, but I don't think it well conveys the notion of Samurai's self-esteem and honorable endurance of poverty.
By the way, "have eaten" meant "to fare well," in the Oriental world, as I heard that Chinese people used to exchange "你, 吃了飯么?" – "Did you eat (finished) meal (breakfast)?" each other as a day-to-day salute up until early 20 century. I wonder this concept and expression – having had a meal implies to fare well – applies to western culture and English language or not.

A: In addition to the phrase suggested by Elian, I feel that keeping a stiff upper lip, is close to the meaning of the Japanese proverb you quote.

Someone who has a stiff upper lip does not show their feelings when they are upset (Cambridge Dictionary)
To be courageous or stoic in the face of adversity. (The Free Dictionary by Farlex)
A steady and determined attitude or manner in the face of trouble (Merriam-Webster)
One who has a stiff upper lip displays fortitude in the face of adversity, or exercises great self-restraint in the expression of emotion. (Wikipedia)

The Phrase Dictionary further expands on its meaning, saying

That 'do your duty and show no emotion' attitude was expressed in Alfred, Lord Tennyson's The Charge of the Light Brigade:
  Theirs not to make reply,
  Theirs not to reason why,
  Theirs but to do and die:
  Into the valley of Death
  Rode the six hundred.

Which makes me think the phrase may in some ways reflect the martial (?) philosophy of the samurai, although maybe not which as much weight on honour or wealth as the question implies the Japanese phrase has.
Related phrases suggested by the Phrases Dictionary, which have more to do with keeping a sunny disposition, are "keep your chin up" or "keep your pecker up".

A: Consider, put on a brave (or bold) face/brave front

To react to or face difficulties, setbacks, or adversity with high spirits or good cheer. Farlex Dictionary of Idioms
To behave in a way that makes people think you are happy when you are not Cambridge Dictionary

A: I agree, partially, w/ @Josh61's assessment of the proverb's meaning: Not to appear downtrodden in the face of adversity. "Keeping a stiff upper lip," (as provided by @eirikdaude) is close, but in keeping with the legendary stoicism of the Samurai, I think that the meaning also implies keeping "cool" (in the "Fonzie" sense). May I suggest:
"Playing your cards close to the vest."
and
"Don't show your ass."


text:
Q: Unsplash.com: How can I get the username from a preselected photo ID via the Unsplash API I have a list of manually selected Unsplash photo IDs that I want to display on a website. Now I want to make sure to print out proper attribution via the Unsplash API.
The .get_attribution function in PyUnsplash is perfect for my use case. However, it requires a username or search query to return the attribution.
I was hoping to simply query the API with the photo ID, but sadly, that does not work.
So if there's any suggestions how to get from photo-ID to username via the API, I would love to hear them.
_
Alternative question titles:
Get Unsplash user's profile by photo id

A: github.com/salvoventura/ released a new version of PyUnsplash. Now this is possible.

PyUnsplash v1.0.0rc1 (release candidate, v1)
This is the first release candidate for production ready 1.0.0 of
  PyUnsplash. Thanks to all the early adopters, there have been a number
  of improvements and bugfixes and now should be a good time to start
  the rc process.
This release brings one useful addition:
Introduction of SinglePhoto which allows instantiating a Photo object
  using a photo_id Deprecated format value 'str' in favor of 'txt' in
  get_attribution()

A: I just did some troubleshooting for unsplash queries with Paw to a photos/:id endpoint. Using the requests library I was able to pull the username out of the returned json object:
import requests

def send_request():
    # Request
    # GET https://api.unsplash.com/photos/4Fjjyhg1YFc

    try:
        response = requests.get(
            url="https://api.unsplash.com/photos/4Fjjyhg1YFc",
            params={
                "client_id": "YOUR_API_KEY",
            },
            headers={
                "Cookie": "",
            },
        )

        data = response.json()
        print('Response HTTP Status Code: {status_code}'.format(
            status_code=response.status_code))
        print('Unsplash API Username: {uname}'.format(
            uname=data['user']['username']))
        print('Unsplash API Full Name: {fname}'.format(
            fname=data['user']['name']))
        print('Unsplash API Location: {location}'.format(
            location=data['user']['location']))
        print('Unsplash API Portfolio: {portfolio}'.format(
            portfolio=data['user']['portfolio_url']))
        print('Unsplash API Instagram: {ig}'.format(
            ig=data['user']['instagram_username']))
    except requests.exceptions.RequestException:
        print('HTTP Request failed')

send_request()

For more info, checkout the 'Response' section under Get A Photo in the docs. It shows all the fields returned, you may find more you'd like to use.


text:
Q: [List / Vector]: Need some foundation advice I would like some advice on how I can solve an interesting problem I have.
The problem is to have two storage containers, of which the user selects which one to use for the remainder of the program (edit: at runtime). The two containers are Vector and List and store an object type we are to define. These two containers can be accessed using any means you desire (pop/[i]/...) How would you go about solving this problem?
Below is my best (almost working) solution, but I would really like to see what solutions more skilled C++ professionals have. As previously stated, I am really interested if I am taking the right approach. I have more than typical free time this semester and I intend to use it to really improve my c++ abilities. Thanks for your feedback.
Version 1
To start, I have a boolean flag,
bool using_vector = true;   // what storage container was selected?

Second comes my two containers,
list<Question> q_llist;
vector<Question> q_vec;

Third my implementations for accessing the containers,
(still haven't figured out how make get_question() work in a graceful way, and I am not fond of the current route I am taking at the moment)
const Question& get_question(){
    Question q = (using_vector) ?
            q_vec.back() : q_llist.back();

    (using_vector) ?
            q_vec.pop_back() : q_llist.pop_back();

    return q;
}

int questions_size(){
    return (using_vector) ?
            q_vec.size() : q_llist.size();
}

void push_back_question(Question& q){
    if(using_vector){
        q_vec.push_back(q);
    }else{
        q_llist.push_back(q);
    }
}

Version 2
Note: Please use the tag "#v2" when referencing.
I decided to attempt the polymorphism approach. How does this implementation look?
/**
 * using polymorphism to implement a parent class "Container"
 * depending on user selection, reference C_Vec or C_List
 */
class Container {
protected:
    list<Question> qlist;
    vector<Question> qvec;

public:
    void push_back(Question& q){/** do nothing */}
    void pop_back(){/** do nothing */}
    int size(){/** do nothing */}
    Question& back(){/** do nothing */}
};

class C_Vec: public Container{
public:
    void push_back(Question& q){qvec.push_back(q);}
    void pop_back(){qvec.pop_back();}
    int size(){return qvec.size();}
    Question& back(){return qvec.back();}
};

class C_List: public Container{
public:
    void push_back(Question& q){qlist.push_back(q);}
    void pop_back(){qlist.pop_back();}
    int size(){return qlist.size();}
    Question& back(){return qlist.back();}
};

int main(){

    Container *store;
    char user_in;

    cout << "Before we begin please select a storage container:" << endl
         << "a) Linked List" << endl
         << "b) Vector" << endl << ':';

    cin >> user_in;

    if(tolower(user_in) == 'a'){
        C_List l;
        store = &l;
    }else{
        C_Vec v;
        store = &v;
    }
}

A: You have several options. If you need to decide at runtime which container to use, polymorphism (inheritance) might work well.
#include <vector>
#include <list>
#include <memory>

struct Question {};

// runtime
struct Question_container {
  virtual const Question& get_question() = 0;
  virtual int questions_size() = 0;
  virtual void push_back(const Question&) = 0;
  virtual ~Question_container() = default;
};

struct Vector_question_container : Question_container {
  const Question& get_question() override { return qv.back(); }
  int questions_size() override { return qv.size(); }
  void push_back(const Question& q) override { qv.push_back(q); }
private:
  std::vector<Question> qv;
};

struct List_question_container : Question_container {
  const Question& get_question() override { return qv.back(); }
  int questions_size() override { return qv.size(); }
  void push_back(const Question& q) override { qv.push_back(q); }
private:
  std::list<Question> qv;
};

int main()
{
  // some how figure out which container to use
  std::unique_ptr<Question_container> qc{new Vector_question_container()};
}

If you can make the choice at compile-time, you could make the underlying sequence a template (or even template template) argument.
// CompileTime
template<typename Sequence>
struct Question_container_c {
  const Question& get_question() { return s.back(); }
  int questions_size() { return s.size(); }
  void push_back(const Question& q) { s.push_back(q); }
private:
  Sequence s;
};

int main()
{
  Question_container_c<std::list<Question>> qlc;
  Question_container_c<std::vector<Question>> qvc;

  return 0;
}

Although you could also just make your algorithm work on iterators and leave the choice of the container to the user. This might be hard for some methods such as your push_back, but it doesn't actually do anything else then the normal push_back already provided.

A: To complement @pmr's answer, if you want to do it in an idiomatic way, you can create an adapter interface:
class IContainer {
public:
    virtual ~IContainer() {}
    virtual void push_back(const Question & q) = 0;
    virtual void pop_back() = 0;
    virtual const Question & back() const = 0;
    virtual unsigned int size() const = 0;
};

And a generic implementation:
template <class T>
class Container: public IContainer {
private:
    T m_container;

public:
    virtual void push_back(const Question & q) {
        m_container.push_back(q);
    }

    virtual void pop_back() {
        m_container.pop_back();
    }

    virtual const Question & back() const {
        return m_container.back();
    }

    virtual unsigned int size() const {
        return m_container.size();
    }
};

So you can do this:
std::unique_ptr<IContainer> pctr;
if (choice) {
    pctr.reset(new Container<std::vector<Question>>);
}
else {
    pctr.reset(new Container<std::list<Question>>);
}
std::cout << pctr->size();

A: I suppose the best way for your approach is to use iterators instead. Iterators are invented as a container abstraction in mind (sure thing, you can't abstract by 100% due different behavior of containers but anyway you have a solution better than nothing).