text:
Q: jQuery .toggle() equivalent in Google Closure I am rewriting some of my javascript files to get rid of the jQuery and use Google Closure instead. I have got a date picker which a user can toggle to show or to hide. At the moment the following code is being used:
if (this.open == open)
    return false;

$(this.elDatePicker).toggle(open);
this.open = open;
return true;

Where el.DatePicker is the element with the date picker inside, in this case a div.
I am looking for a way to rewrite this piece of code to change the jQuery to Google Closure. Any idea's how this should be possible?

A: You should be able to do
goog.style.showElement(this.elDatePicker, !goog.style.isElementShown(this.elDatePicker));

Source:
Google Closure Style.js Doc

A: For reference
With no parameters, the .toggle() method simply toggles the visibility of elements:
Source : http://api.jquery.com/toggle/
if so then setting either display none or visibility : hidden/visible. should be sufficient.
you can use goog.style.setStyle(element, style, opt_value)
here is a jsbin link : http://jsbin.com/ENOX/3/

A: If you want to toggle a specific CSS clas, you can use:
goog.dom.classlist.toggle(element, 'className');

A: You could use the Zippy class without a header element,
this.zippy = new goog.ui.AnimatedZippy(null, this.elDatePicker);

(...)
this.zippy.setExpanded(open)


text:
Q: Android OpenGL 2 Scrolling Texture Loses Quality Over Time I'm trying to create a simple game for Android, using OpenGL 2 ES, that utilizes a repeating scrolling texture for the background.  I managed to draw the texture, scroll it, and repeat.  It works really well for the first few seconds, then the quality of the image starts to degrade - gets very pixelated.  After about 10 seconds, the scrolling image is just about unrecognizable.
The texture scrolls automatically/infinitely using a float value passed to u_Scroll.
Fragment Shader:
precision mediump float;

uniform float u_Scroll;
uniform sampler2D u_TextureUnit;
varying vec2 v_TextureCoordinates;

void main()
{
    gl_FragColor = texture2D(u_TextureUnit, vec2(v_TextureCoordinates.x, v_TextureCoordinates.y + u_Scroll));
}

Load Texture Method
public static int loadBackgroundTexture(Context context, int resourceId) {
    final int [] textureObjectIds = new int[1];
    glGenTextures(1, textureObjectIds, 0);

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;

    final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);

    glBindTexture(GL_TEXTURE_2D, textureObjectIds[0]);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);
    bitmap.recycle();

    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);

    return textureObjectIds[0];
}

onDraw from Renderer:
public void onDrawFrame(GL10 gl) {

    glClear(GL_COLOR_BUFFER_BIT);

    multiplyMM(viewProjectionMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
    invertM(invertedViewProjectionMatrix, 0, viewProjectionMatrix, 0);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    positionBackgroundInScene();
    backgroundProgram.useProgram();
    backgroundProgram.setUniforms(modelViewProjectionMatrix, texture[1]);
    background.bindData(backgroundProgram);
    background.draw();

    positionAngelInScene(angelPosition.x, angelPosition.y, angelPosition.z);
    textureProgram.useProgram();
    textureProgram.setUniforms(modelViewProjectionMatrix, texture[0]);
    angel.bindData(textureProgram);
    angel.draw();

}

I'm very new to this, so I'm not sure what other code to post.  Why would my background texture be good at first and degrade over time?  Unfortunately, I don't have a high enough rep to post a screenshot.

A: It looks like you're simply incrementing/decrementing the u_Scroll value while you scroll, and count on the texture GL_REPEAT behavior to give you endless scrolling.
The problem here is most likely floating point precision. A medium float value, which is what you're using for the texture coordinate math, has only about 0.1% (10 bits) relative precision in a typical implementation.
To illustrate the implications of this, say you have scrolled through 10 times, and your range of texture coordinates is now between 10.0 and 11.0. At 0.1% relative precision, the increment between floating point values you can represent in this range is about 0.01. Or in other words, you can represent about 100 values between 10.0 and 11.0. If your texture is e.g. 512x512, you can only address every 5th pixel with your texture coordinates.
One option to use this is to change the float precision to highp. But that's not guaranteed to be supported on all ES 2.0 implementation.
Unless I misunderstand what you're doing, there should be a very easy solution: Keep the range of the value you use to set u_Scroll between 0.0 and 1.0 in your app code.
You probably have code that logically looks something like this in your app code to translate user input to scrolling:
if (scrollRight) {
    scrollValue += scrollIncrement;
} else if (scrollLeft) {
    scrollValue -= scrollIncrement;
}
...
glUniform1f(scrollLoc, scrollValue);

Change this to:
if (scrollRight) {
    scrollValue += scrollIncrement;
    if (scrollValue > 1.0f) {
        scrollValue -= 1.0f;
    }
} else if (scrollLeft) {
    scrollValue -= scrollIncrement;
    if (scrollValue < 0.0f) {
        scrollValue += 1.0f;
    }
}
...
glUniform1f(scrollLoc, scrollValue);

This will keep scrollValue between 0.0 and 1.0, which allows you to use the full relative precision of the medium texture coordinates in your fragment shader.

redpajama_set_name: RedPajamaStackExchange


text:
Q: More Columns or more tables in sql/mysql I'm working with many datasets, for example i have a main table with id, and 30 more tables They are relating to main with id, but I have just given me that I have columns specific for each type of event in main table, then for example
the main table
id  event_type  data1     data2   data3     data4   data5   ……..    data15
1   primary     x          x      null      null    x               null
2   primary     x          x      null      null    x               null
3   secundary   x         null     x        x       null            null
4   secundary   x         null     x        x       null            null
5   primary-1   x          x       x        x       x               null

Then for example, data2 is exclusive to secundary, data3 no have info in primary...etc.
so my question is, what would be the best way of working, create a table, for each type of event, and then link it to event_type, or put all the columns in a single primary table,

** note

if i do the first option, i need to work with leftjoin, becouse i have other 30 tables linked to id, and i working with leftjoin, and anyway there will be null for any columns.
my question is for the best optimization, I want faster processing in less time


text:
Q: CSS line-height renders differently on safari The following code renders as expected in Firefox and Chrome browsers, but on Safari it renders with an unwanted white line between the borders.
HTML:
Text here

CSS:
span {
  border-top: 3.3em solid #ff9933;
  border-right: 3.3em solid #ff9933;
  border-bottom: 3.3em solid #ff9933;
  border-left: 3.3em solid transparent;
  color: white;
  display: inline-block;
  font-size: 1em;
  line-height: 0;
}

Firefox and Chrome:

Safari:

Does anybody know why this is happening?
JSFiddle

A: It seems like a problem of proportion, the border 3.3em can't cover totally the text with font-size 1em; you can change the border for 3.5em or you can change the font-size for 0.8em.

span {
border-top: 3.3em solid #ff9933;
border-right: 3.3em solid #ff9933;
border-bottom: 3.3em solid #ff9933;
border-left: 3.3em solid transparent;
color: white;
display: inline-block;
font-size: 0.8em;
line-height: 0;
}
Text here

A: Looks like Safari finds your line height (if zero line height can be called height :)) unsatisfactory for such a small border. Does work fine with 3.5em.

span {
border-top: 3.5em solid #ff9933;
border-right: 3.5em solid #ff9933;
border-bottom: 3.5em solid #ff9933;
border-left: 3.5em solid transparent;
color: white;
display: inline-block;
font-size: 1em;
line-height: 0;
}
Text here


text:
Q: Maven Java error compiling on build: maven-compiler-plugin When I try to run as maven build it always give BUILD FAILURE.
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project testJPA: Fatal error compiling: invalid target release: 11 -> [Help 1]

I already tried the following things:

*

*remove .m2 folder

*reinstall eclipse

*set executable on pom.xml

*set build option to clean

> java -version
java version "1.8.0_261"

> echo %JAVA_HOME%
C:\Program Files\Java\jdk1.8.0_211

pom.xml
<plugin>
    <inherited>true</inherited>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <source>11</source>
        <target>11</target>
        <encoding>UTF-8</encoding>
        <showWarnings>true</showWarnings>
        <showDeprecation>true</showDeprecation>
    </configuration>
</plugin>

None of them worked. Any guesses?

A: I managed to find a solution.
I installed JDK 11 and set it at Window > Preferences > Java > Installed JREs > Add > jdk-11.0.9
Downloaded at: https://www.oracle.com/java/technologies/javase-jdk11-downloads.html


text:
Q: What kernel module to compile for getting QOS service on Linux We are developing on Linux system whose kernel had been compiled without QOS service years ago. Currently we want the QOS service back and plan to compile only the QOS-related kernel modules and install them into the system kernel.
But we don't know what kernel modules represent the QOS service. What modules should we build? And what additional steps should we take including those we usually do for a custom user kernel module? Does anyone know about this?

A: On a 3.2 kernel the modules are:
$ ls /lib/modules/3.2.0-local/kernel/net/sched

act_csum.ko     cls_flow.ko     em_u32.ko       sch_multiq.ko
act_gact.ko     cls_fw.ko       sch_atm.ko      sch_netem.ko
act_ipt.ko      cls_route.ko    sch_cbq.ko      sch_prio.ko
act_mirred.ko   cls_rsvp6.ko    sch_choke.ko    sch_qfq.ko
act_nat.ko      cls_rsvp.ko     sch_drr.ko      sch_red.ko
act_pedit.ko    cls_tcindex.ko  sch_dsmark.ko   sch_sfb.ko
act_police.ko   cls_u32.ko      sch_gred.ko     sch_sfq.ko
act_simple.ko   em_cmp.ko       sch_hfsc.ko     sch_tbf.ko
act_skbedit.ko  em_meta.ko      sch_htb.ko      sch_teql.ko
cls_basic.ko    em_nbyte.ko     sch_ingress.ko
cls_cgroup.ko   em_text.ko      sch_mqprio.ko

Under make menuconfig see

*

*Networking Support

*

*Networking Options

*

*QoS and/or fair queueing

Or in your .config
--- .config_noqos
+++ .config_qos
@@ -1044,7 +1044,66 @@
 CONFIG_PHONET=m
 CONFIG_IEEE802154=m
 CONFIG_IEEE802154_6LOWPAN=m
-# CONFIG_NET_SCHED is not set
+CONFIG_NET_SCHED=y
+
+#
+# Queueing/Scheduling
+#
+CONFIG_NET_SCH_CBQ=m
+CONFIG_NET_SCH_HTB=m
+CONFIG_NET_SCH_HFSC=m
+CONFIG_NET_SCH_ATM=m
+CONFIG_NET_SCH_PRIO=m
+CONFIG_NET_SCH_MULTIQ=m
+CONFIG_NET_SCH_RED=m
+CONFIG_NET_SCH_SFB=m
+CONFIG_NET_SCH_SFQ=m
+CONFIG_NET_SCH_TEQL=m
+CONFIG_NET_SCH_TBF=m
+CONFIG_NET_SCH_GRED=m
+CONFIG_NET_SCH_DSMARK=m
+CONFIG_NET_SCH_NETEM=m
+CONFIG_NET_SCH_DRR=m
+CONFIG_NET_SCH_MQPRIO=m
+CONFIG_NET_SCH_CHOKE=m
+CONFIG_NET_SCH_QFQ=m
+CONFIG_NET_SCH_INGRESS=m
+
+#
+# Classification
+#
+CONFIG_NET_CLS=y
+CONFIG_NET_CLS_BASIC=m
+CONFIG_NET_CLS_TCINDEX=m
+CONFIG_NET_CLS_ROUTE4=m
+CONFIG_NET_CLS_FW=m
+CONFIG_NET_CLS_U32=m
+# CONFIG_CLS_U32_PERF is not set
+CONFIG_CLS_U32_MARK=y
+CONFIG_NET_CLS_RSVP=m
+CONFIG_NET_CLS_RSVP6=m
+CONFIG_NET_CLS_FLOW=m
+CONFIG_NET_CLS_CGROUP=m
+CONFIG_NET_EMATCH=y
+CONFIG_NET_EMATCH_STACK=32
+CONFIG_NET_EMATCH_CMP=m
+CONFIG_NET_EMATCH_NBYTE=m
+CONFIG_NET_EMATCH_U32=m
+CONFIG_NET_EMATCH_META=m
+CONFIG_NET_EMATCH_TEXT=m
+CONFIG_NET_CLS_ACT=y
+CONFIG_NET_ACT_POLICE=m
+CONFIG_NET_ACT_GACT=m
+CONFIG_GACT_PROB=y
+CONFIG_NET_ACT_MIRRED=m
+CONFIG_NET_ACT_IPT=m
+CONFIG_NET_ACT_NAT=m
+CONFIG_NET_ACT_PEDIT=m
+CONFIG_NET_ACT_SIMP=m
+CONFIG_NET_ACT_SKBEDIT=m
+CONFIG_NET_ACT_CSUM=m
+# CONFIG_NET_CLS_IND is not set
+CONFIG_NET_SCH_FIFO=y
 CONFIG_DCB=y
 CONFIG_DNS_RESOLVER=y
 CONFIG_BATMAN_ADV=m
@@ -1899,6 +1958,7 @@
 CONFIG_MII=y
 CONFIG_IEEE802154_DRIVERS=m
 # CONFIG_IEEE802154_FAKEHARD is not set
+CONFIG_IFB=m
 CONFIG_MACVLAN=m
 CONFIG_MACVTAP=m
 CONFIG_NETCONSOLE=m


text:
Q: How to set needle type in std::binary_search I have the following simple program that will binary_search for an item:
#include <vector>
#include <algorithm>
#include <string>
#include <iostream>

class Record
{
public:
    Record() = default;
    Record(std::string name, int data) : mName(name), mData(data) { }
    std::string mName;
    int mData = 0;
};

int main(int, char**)
{
    std::vector<Record> recs;

    recs.emplace_back(Record("1", 1));
    recs.emplace_back(Record("55555", 2));
    recs.emplace_back(Record("333", 3));
    recs.emplace_back(Record("qwertyuiop", 4));
    recs.emplace_back(Record("22", 5));
    recs.emplace_back(Record("4444", 6));

    std::cout << "Unsorted:" << std::endl;
    for (auto& rec : recs)
    {
        std::cout << "Name: "  << rec.mName << " Data: " << rec.mData << std::endl;
    }
    std::cout << std::endl;

    std::stable_sort(recs.begin(), recs.end(), [](const Record& lhs, const Record& rhs) -> bool
    {
        return lhs.mName.length() < rhs.mName.length();
    });

    std::cout << "Sorted:" << std::endl;
    for (auto& rec : recs)
    {
        std::cout << "Name: " << rec.mName << " Data: " << rec.mData << std::endl;
    }
    std::cout << std::endl;

    if (std::binary_search(
        recs.begin(),
        recs.end(),
        Record("qwertyuiop", 4),
        [](const Record& lhs, const Record& rhs) -> bool
    {
        return lhs.mName < rhs.mName;
    }))
    {
        std::cout << "Found" << std::endl;
    }
    else
    {
        std::cout << "Not found" << std::endl;
    }

    return 0;
}

How can I search the vector of Records based on another type of T? For example std::string instead of Record?
Something like:
 if (std::binary_search(
            recs.begin(),
            recs.end(),
            "qwertyuiop",
            [](const Record& lhs, const std::string& rhs) -> bool
        {
            return lhs.mName < rhs.mName;
        }))
        {
            std::cout << "Found" << std::endl;
        }
        else
        {
            std::cout << "Not found" << std::endl;
        }

Is what I want - basically I don't want to construct a Record to search for it as this presents a performance issue for me.

A: You can create a function object type that handles heterogeneous comparisons:
struct comp_t
{
    bool operator()(Record const& lhs, std::string const& rhs) const {
        return lhs.mName < rhs;
    }

    bool operator()(std::string const& lhs, Record const& rhs) const {
        return lhs < rhs.mName;
    }
};

Then you can call binary_search like this:
std::binary_search(recs.begin(), recs.end(),
                   std::string("qwertyuiop"),
                   comp_t{})

A: You can do this by adding an implicit constructor to convert std::string to Record and an operator to convert Record to std::string.
operator std::string() const {
    return mName;
}

Record(std::string name) : mName(name), mData(int()) {}

or you can convert your existing constructor to this
Record(std::string name, int data = int()) : mName(name), mData(data) {}

But anyways you'll need to create a std::string object to search.
/// create std::string object from "qwertyuiop"
if (std::binary_search(recs.begin(), recs.end(), std::string("qwertyuiop"),
    [](const Record & lhs, const std::string & rhs) -> bool
        {
            return lhs.mName < rhs;    /// rhs is a std::string type
        })) {
    std::cout << "Found" << std::endl;
}
else {
    std::cout << "Not found" << std::endl;
}

See http://ideone.com/0f16GE demo.


text:
Q: Why an inline function defined in a Kotlin file cannot be used in Java code? I'm trying to understand why I cannot use my inline function defined in a Kotlin file in my Java code?
Project details
Kotlin: 1.5.20 - Java: 15.0.1
Mixed code (Java + Kotlin). I have same package structure both in Java & Kotlin as below:
com.app.company.util.Util.java
com.app.company.util.Util.kt
In Util.kt I have an inline function as below:
val commonMapper = jacksonObjectMapper()

inline fun <reified T> parseJson(content: String): T {
   return commonMapper.readValue(content)
}

I noticed that since I have the same name Util for both Java class and Kotlin file, If I want to refer to the Kotlin file I have to use UtilKt. I found this by decompiling the Kotlin file.
Interestingly, only commonMapper is exposed by getCommonMapper() method not parseJson.
Could someone please help me understand why parseJson is not visible from Java?


text:
Q: Help needed Using C File In Project, iPhone I am new to all this, but here goes:
There is an apple file that I would like to use parts of for my app. It is called BatteryTimeRemaining.c.
http://www.opensource.apple.com/source/PowerManagement/PowerManagement-211/pmconfigd/BatteryTimeRemaining.c
I want to be able to use some of the calculations in it, the problem being I don't to know how to add and use it properly. I get countless errors e.g. undeclared: first use of this function.
Do I need to add all the header files which are included in the .c file? Do I compile it and then add?
Many thanks,
Stuart

A: Yeh you would need to include all the header files mentioned in BatteryTimeRemaining.c.  So all of these files...
#include <syslog.h>
#include <unistd.h>
#include <stdlib.h>
#include <notify.h>
#include <mach/mach.h>
#include <mach/mach_port.h>
#include <servers/bootstrap.h>
#include <asl.h>

#include "powermanagementServer.h" // mig generated
#include "BatteryTimeRemaining.h"
#include "SetActive.h"
#include "PrivateLib.h"

All the triangle bracket includes should be system include files and so should be on your system already.  The quoted include files though are likely part of that project you are retrieving BatteryTimeRemaining.c from.  You would need to copy them out of that project to your own project.
Likely its easier to copy out the functions you want and paste them into your own code base.  No doubt you'll have some dependency issues but its probably easier to get one or two functions building on your system then the whole file.  It's pretty long.
What function did you want to use exactly out of BatteryTimeRemaining.c?

A: Try adding just
#import "BatteryTimeRemaining.h"

to the file you want to use these functions in. It might be enough..

A: Unfortunately, most of the functions contained in this file are mac-specific, hence my problems using some of it's contents.


text:
Q: Is there C++ project manager like NPM? I used to have NPM to manage my javascript project like npm init command or etc. but I'm curious about there's a C/C++ open source project manager that manage like NPM. If there is, what's name of C++ project manager?

A: CMake is a good project build management tool, but it does not have the dependency management capabilityies NPM or Maven have. You can check out CPM, but it is not actively maintained anymore.
The Maven Nar Plugin for C/C++ projects is another option, but sadly its not very active either. See also the suggestions in the answer to a similar question regarding Maven.


text:
Q: Will Python open a file before it's finished writing? I am writing a script that will be polling a directory looking for new files.
In this scenario, is it necessary to do some sort of error checking to make sure the files are completely written prior to accessing them?
I don't want to work with a file before it has been written completely to disk, but because the info I want from the file is near the beginning, it seems like it could be possible to pull the data I need without realizing the file isn't done being written.
Is that something I should worry about, or will the file be locked because the OS is writing to the hard drive?
This is on a Linux system.

A: Typically on Linux, unless you're using locking of some kind, two processes can quite happily have the same file open at once, even for writing. There are three ways of avoiding problems with this:

*

*Locking
By having the writer apply a lock to the file, it is possible to prevent the reader from reading the file partially. However, most locks are advisory so it is still entirely possible to see partial results anyway. (Mandatory locks exist, but a strongly not recommended on the grounds that they're far too fragile.) It's relatively difficult to write correct locking code, and it is normal to delegate such tasks to a specialist library (i.e., to a database engine!) In particular, you don't want to use locking on networked filesystems; it's a source of colossal trouble when it works and can often go thoroughly wrong.

*Convention
A file can instead be created in the same directory with another name that you don't automatically look for on the reading side (e.g., .foobar.txt.tmp) and then renamed atomically to the right name (e.g., foobar.txt) once the writing is done. This can work quite well, so long as you take care to deal with the possibility of previous runs failing to correctly write the file. If there should only ever be one writer at a time, this is fairly simple to implement.

*Not Worrying About It
The most common type of file that is frequently written is a log file. These can be easily written in such a way that information is strictly only ever appended to the file, so any reader can safely look at the beginning of the file without having to worry about anything changing under its feet. This works very well in practice.
There's nothing special about Python in any of this. All programs running on Linux have the same issues.

A: On Unix, unless the writing application goes out of its way, the file won't be locked and you'll be able to read from it.
The reader will, of course, have to be prepared to deal with an incomplete file (bearing in mind that there may be I/O buffering happening on the writer's side).
If that's a non-starter, you'll have to think of some scheme to synchronize the writer and the reader, for example:

*

*explicitly lock the file;

*write the data to a temporary location and only move it into its final place when the file is complete (the move operation can be done atomically, provided both the source and the destination reside on the same file system).

A: If you have some control over the writing program, have it write the file somewhere else (like the /tmp directory) and then when it's done move it to the directory being watched.
If you don't have control of the program doing the writing (and by 'control' I mean 'edit the source code'), you probably won't be able to make it do file locking either, so that's probably out. In which case you'll likely need to know something about the file format to know when the writer is done. For instance, if the writer always writes "DONE" as the last four characters in the file, you could open the file, seek to the end, and read the last four characters.

A: Yes it will.
I prefer the "file naming convention" and renaming solution described by Donal.


text:
Q: Deleting an Auth Firebase User When an Activity Is Destroyed I have an activity called ValidadorActivity, in this activity I do a sms validation, right after the user signs up.
The registration is done by the Firebase Auth but it is done before this validation, so I look for a way to delete the auth firebase registry when the user exits the validation screen without putting the Token that was sent by sms correctly.
@Override
    protected void onDestroy() {
        super.onDestroy();

        //Ao fechar completamente a tela de validação com o campo textValidacao nulo ou incorreto, o cadastro no autenticacao e no banco de dados sao apagados, para evitar o cadastro de usuarios não validados.

        String codigoDigitado = codigoValidacao.getText().toString(); //Pega o texto da caixa de texto

        if (! codigoDigitado.equals(tokenGerado)) {//Verifica se esse texto e igual

            user.delete().addOnCompleteListener(new OnCompleteListener<Void>() { //deleta o usuario no Auth
                @Override
                public void onComplete(@NonNull Task<Void> task) {

                    if (task.isSuccessful()) {//Testa para ver se funcionou

                        Log.i("Usuario deletado(auth)","Sim");

                    }else{

                        Log.i("Usuario deletado(auth)","Não");

                    }

                }
            });
}

This code is not running, I think the code is right. Any ideas or suggestions?

A: The onDestroy method only runs when the activity is destroyed by the system, which is seldom the same as when the user exits the activity.
You might want to look at onPause or onStop, and in general have a look at the Android activity lifecycle for when precisely you want the code to run.


text:
Q: How to get all values inside a div as a string using HtmlAgilityPack I have an html that i need to extract just a div and the elements inside this div but as a string.
 <div id=01>
    <div id-02>
      <label></labell>
      <input></input>
       //etc
     </div>
 </div>

How do i get all inside the div 01 as a single string?
The only way i found is to get using the nodes, but it returns me a collection of HtmlNodes.
document.DocumentNode.SelectNodes("//*[contains(@class,'container')]").Descendants("div").Select(p => p.OuterHtml);

A: var Node = document.DocumentNode.SelectNodes("//div[@id='01']").SingleOrDefault();
var target = Node.InnerHtml;

becouse id is single I used SingleOrDefault for this id


text:
Q: Rss feeds for asp.net webforms I followed this tutorial http://net.tutsplus.com/tutorials/asp-net/how-to-build-an-rss-feed-with-asp-net/
This tutorial is working fine, but I am using it with my existing project, It is giving me the following error
error at line 26 at column 30:opening and ending tag mismatch: img line 0 and a
Here is my code:
1-
2-

    <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="http://www.gsmarena.com/rss-news-reviews.php3" XPath="rss/channel/item"></asp:XmlDataSource>

    <asp:ListView ID="ListView1" runat="server" DataSourceID="XmlDataSource1">
        <ItemTemplate>
           <a href="<%#XPath("link") %>"><%#XPath("Title") %>
            <%#XPath("title") %>

&nbsp

            <%#XPath("description") %>
        </ItemTemplate>
    </asp:ListView>


text:
Q: Using Stokes theorem twice
Let $\partial S$ be the closed, piece wise smooth curve that travels from $(0,0,0)$, $(2,0,4)$, $(3,2,6)$, $(1,2,2)$ and then back to $(0,0,0)$ in precisely that order. Let $S$ be the planar region with boundary $\partial S$ (this region is necessarily contained in the plane $z = 2x$). Use Stokes' theorem to calculate the line integral
  $$  \oint_{\partial S} \mathbf{F} \cdot \mathrm{d}r$$
  where $\mathbf{F}$ is the vectorfield $\mathbf{F}(x,y,z) = z (\cos x) \cdot \mathbf{i} + x^2 y z \cdot \mathbf{j} + yz \cdot \mathbf{k}$.

Simply using Stokes we can parameterize the surface as
$$
\mathbf{r}(u,v) = (2u + v, 2v, 4u + 2v) \ , \qquad (u,v) \in [0,1]^2
$$
Some very tedious calculations give then
$$
  \oint_{\partial S} \mathbf{F} \cdot \mathrm{d}r
\stackrel{\text{Stokes'}}{=} \iint_{S} \mathrm{curl}\,\mathbf{F} \,\mathrm{d}S = \iint_{[0,1]^2} \mathrm{curl}\,\mathbf{F}(\mathbf{r}(u,v)) \cdot \left( \frac{\partial \mathrm{r}}{\partial u}\times\frac{\partial \mathrm{r}}{\partial v}\right) \mathrm{d}(u,v) = 52
$$
I was hoping there was a quicker way to do this. Plotting the function in the $xz$-plane it looks like this.

Is there any reason why I can not use Stokes backwards and instead calculate the line integral over this simpler curve? I should be able to take the projection of S, down into the $xz$-plane as is still a piecewise-smooth boundary to $S$. Any other simpler way would also be appreciated.


text:
Q: Subsetting a Data Frame Based on Character Ending I'm a newbie to R. I've a data.frame. The beginning and end, respectively, look like:

What I'd like to do is to subset this data frame based on the last digit(s) of the "barcode" column. The digits go from 1 to 16, so there are 16 groups. I'd like to group these 16 into 5 groups. For example, all barcodes ending in "1" and "2" would be one subset of the data frame, all barcodes ending in "3", "4" and "5" would go into another subset, and so on.
I tried this using the which() and endsWith() functions:
my_frame = data.frame()
character_one = as.character(1)
subset_by_group_one <- my_frame[which(endsWith(my_frame, character_one)),]

However, I get the following error:
Error in endsWith(barcode_subset, character_one) :
  non-character object(s)
It seems that based on the R documentation, the endsWith() function must take in a character, and not a data frame. Yet I'd like to use it -- or something like it -- on my data frame to subset it. What's the best way to do this? Is there a way to coerce a data frame to a character? Will I need to use a loop to iterate through the data frame?

A: You want to subset the rows according to a regular expression pattern (ends with "16", which is "16$".  I think the most direct way to do this is with a logical vector that is true for those rows that end in 16.  Produce the logical vector with grepl(pattern, x),  where x is the column with the values you're interested in.  Then subset according to rows by using that logical index vector in the row position of the subset expression my_frame[<index vector>,]. See how the data was simulated below. drop is set to FALSE in case the rownames are actually row names and not another column (and you don't have another column).
my_frame[grepl("16$", my_frame$barcode),, drop = FALSE]
#                               barcode other
# GACCTAAATGCCTGT-16 GACCTAAATGCCTGT-16  blah
# GAAATTGACATGACT-16 GAAATTGACATGACT-16  blah

Data:
barcode <- replicate(32, {
  paste(sample(c("T", "A", "C", "G"), 15, replace = TRUE), collapse = "")
})
barcode <- paste0(barcode, "-", 1:16)
my_frame <- data.frame(row.names = barcode, barcode = barcode, other = rep("blah", 32), stringsAsFactors = FALSE)
head(my_frame)
#                             barcode other
# GTCCGGTGATGATAA-1 GTCCGGTGATGATAA-1  blah
# CTGCTACATATAGAA-2 CTGCTACATATAGAA-2  blah
# GTGACCGTGGTCGAA-3 GTGACCGTGGTCGAA-3  blah
# TCTAGGACGATTACT-4 TCTAGGACGATTACT-4  blah
# GAGGGAGGCGTCCAT-5 GAGGGAGGCGTCCAT-5  blah
# CAGCAGCCTCCACCG-6 CAGCAGCCTCCACCG-6  blah

A: I'm using Dan Hall's example. This builds a 'splitting/grouping vector" by removing all the material up to and including the dash, converts it to numeric and then groups it with findInterval. The grouping was somewhat unclear but you can modify the second argument to findInterval to adjust::
 grp <- findInterval( as.numeric( gsub("^.+[-]", "", my_frame$barcode)),
                       c(.5, 2.5, 5.5, 8.5, 12.5, 16.5)) #split boundaries
> split( my_frame, grp)
$`1`
                            barcode other
TCGCGCGTTACATGT-1 TCGCGCGTTACATGT-1  blah
GCGTGTTATCCGCCT-2 GCGTGTTATCCGCCT-2  blah
CTCCCTCTTCTGTGC-1 CTCCCTCTTCTGTGC-1  blah
TTCTTGTGCGACAAA-2 TTCTTGTGCGACAAA-2  blah

$`2`
                            barcode other
CTTACGTCGTCAGCA-3 CTTACGTCGTCAGCA-3  blah
CCCATGTGTGACTAC-4 CCCATGTGTGACTAC-4  blah
GAGCCCAGAACTGTG-5 GAGCCCAGAACTGTG-5  blah
GTTGGCGAGCAGCAT-3 GTTGGCGAGCAGCAT-3  blah
ATTTAGGGGACCCAA-4 ATTTAGGGGACCCAA-4  blah
TGGCCAATGCGTTGA-5 TGGCCAATGCGTTGA-5  blah

$`3`
                            barcode other
TCCGTCCGGGGAGGA-6 TCCGTCCGGGGAGGA-6  blah
TTCAAATCGTCTACT-7 TTCAAATCGTCTACT-7  blah
AGGTACAATCTCGCA-8 AGGTACAATCTCGCA-8  blah
CGTGACTCCAATGGT-6 CGTGACTCCAATGGT-6  blah
CCGGGGGGTTGCCCC-7 CCGGGGGGTTGCCCC-7  blah
CTTTAAGTGTGTCAG-8 CTTTAAGTGTGTCAG-8  blah

$`4`
                              barcode other
TGCTGACAGTTAGAG-9   TGCTGACAGTTAGAG-9  blah
GGAAGGTGCAGAGGC-10 GGAAGGTGCAGAGGC-10  blah
AATTTAGGGCGGCCT-11 AATTTAGGGCGGCCT-11  blah
CCATCATGCGGGACG-12 CCATCATGCGGGACG-12  blah
TCCGAATCTGAGCAA-9   TCCGAATCTGAGCAA-9  blah
TCCCACCCTTTCTCG-10 TCCCACCCTTTCTCG-10  blah
CTCCTGGTCGCCACA-11 CTCCTGGTCGCCACA-11  blah
TCCCGCAACATGTAC-12 TCCCGCAACATGTAC-12  blah

$`5`
                              barcode other
TAAGAGTGCCAGTCC-13 TAAGAGTGCCAGTCC-13  blah
ACTCCACTGCCCAAC-14 ACTCCACTGCCCAAC-14  blah
CACCGTGGGTGCACA-15 CACCGTGGGTGCACA-15  blah
TGGGTGTCTGTCATG-16 TGGGTGTCTGTCATG-16  blah
CTGACATTGGTACAC-13 CTGACATTGGTACAC-13  blah
GCGCAGGTTCGAACC-14 GCGCAGGTTCGAACC-14  blah
TTTTTTCCCCCGACC-15 TTTTTTCCCCCGACC-15  blah
CCCAGCTGCCATTGA-16 CCCAGCTGCCATTGA-16  blah

A: Actually the function you werelooking for is base::endsWith. It returns a vector of booleans and has the variable as the first argument.
df2 <- df1[endsWith(df1$z,"2"),]
#    z whatev
# 1 x2   blah
# 3 l2   blah
# 4 y2   blah
# 5 o2   blah
# 8 v2   blah

dplyr::ends_with was essentially made to be used inside dplyr calls, especially select, though we could make it work as well by being careful about argument order. It returns numeric values though in this case it doesn't make a difference.
library(dplyr)
df2 <- df1[ends_with("2",vars=df1$z),]
#     z whatev
# 1  v2   blah
# 3  s2   blah
# 8  j2   blah
# 9  n2   blah
# 10 z2   blah

data
set.seed(1)
df1 <- data.frame(z = paste0(sample(letters,10),sample(1:3,10,T)),whatev="blah",stringsAsFactors=F)
#     z whatev
# 1  v2   blah
# 2  q3   blah
# 3  s2   blah
# 4  m1   blah
# 5  l1   blah
# 6  y1   blah
# 7  a1   blah
# 8  j2   blah
# 9  n2   blah
# 10 z2   blah

Ironically  base::endsWith is much better suited for dplyr::filter calls than dplyr::ends_with.

A: I'd use a regular expression to extract the endings, then join with a data frame containing the group information.
Some example data:
library(tidyverse)
df1 <- data.frame(x = paste0("AAA-", 1:16))

Some example groups: 1-2 = 1; 3-5 = 2; 6-9 = 3; 10-14 = 4; 15-16 = 5.
Join with df1:
df1 %>%
  mutate(suffix = str_match(x, "-(\\d+)$")[, 2] %>% as.numeric()) %>%
  left_join(data.frame(suffix = 1:16,
                       group = c(1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5)))

        x suffix group
1   AAA-1      1     1
2   AAA-2      2     1
3   AAA-3      3     2
4   AAA-4      4     2
5   AAA-5      5     2
6   AAA-6      6     3
7   AAA-7      7     3
8   AAA-8      8     3
9   AAA-9      9     3
10 AAA-10     10     4
11 AAA-11     11     4
12 AAA-12     12     4
13 AAA-13     13     4
14 AAA-14     14     4
15 AAA-15     15     5
16 AAA-16     16     5


text:
Q: multi threading on asp.net I have not used multi threading much for asp.net. I have a web application that uploads a large temp file to folder. I would like to take that temp file and do some other things with it after it is uploaded. Can I do this work on another thread without the user being on the website any more? Thanks for any help or suggestions.
1.User post large file
2.uploading temp to server
3.After upload completes. I would like to run another thread/worker that can run without any user iteration but is trigger by the user.
void uploading(){
//Uploading file To server
}
void Submitclick(){
Start a Thread
Thread thread = new Thread(DoThreadWork);// does the user still need to be logged in?
Send to another page
}
void DoThreadWork(){Do this in background}

A: It's definitely possible, I've used background threads quite a bit in ASP.NET to do some funky stuff. If you have complete control over the server it might be more elegant to run the background code in a separate application or a windows service.
It's a better separation of concerns to have your IIS app dealing with just responding to web requests, and it's not geared up for that.
Also a warning, if you have a background thread in ASP.NET 2.0 and it has an unhandled exception, the default is to reset the application pool.
More information here: http://blogs.msdn.com/b/tess/archive/2006/04/27/584927.aspx
// 3 downvotes?
Listen, it's not alway possible to avoid running something in a background thread. I've hit this in several situations:

*

*I've worked in a company with an unreasonable attitude to software
where we were not allowed to deploy a separate app to handle the
background processing. I argued for a windows service, but was
overruled and told to implement it in a background thread. Obviously
I moved on from that company to a healthier environment, but that is
the reality is this you have to deal with unreasonable situations
sometimes.

*if you're in a hosted environment you don't always have the option to offload onto a seperate process.

The question was if it is possible. I'm answering that question.

A: If you want to separate the uploading of file from website user interaction you can make a windows service that will contineously check that if file is ready for upload and upload the file.

A: You can use the thread pool for that. The sample code relies on the article in the following lik: http://msdn.microsoft.com/en-us/library/3dasc8as(v=vs.80).aspx
First write your method that does the work. The method must get 1 argument of type object:
 public void DoWork(object threadContext)
 {
 }

than, in the place of the code that you want to call the method do:
 ...
 var threadParam = ... // Put any value you want to be used by the DoWork method
 ThreadPool.QueueUserWorkItem(DoWork, threadParam );

The method will be queued until the system will hav free thread to handle the work and execute the method regardless if the request has been ended or not.


text:
Q: Am I applying the Dominated Convergence Test correctly in this example? If $f_n:\mathbb{R}^n\to\mathbb{R}$, with  $f_n=\frac{(1-|x|)(n^{-2}+|x|^2)}{|x|^2}$, find
$$\lim_{n\to\infty}\int_{B_1(0)}f_n\,dx.$$
Clearly, I would need to use the $\textit{Dominated Convergence Theorem}$. To find my dominating function $G(x)$, note that
\begin{align}\left|\frac{(1-|x|)(n^{-2}+|x|^2)}{|x|^2}\right|&=\frac{|1-|x||\cdot\left( n^{-2}+|x|^2\right)}{|x|^2}=|1-|x||\left(1+\frac{1}{\left(n|x|\right)^2}\right)\\&\leq|1-|x||=G(x).\end{align}
$G(x)$ is integrable because $1-|x|$ is continuous and integrable by $(1)$ (Can I state this?).
Also,
$$\lim_{n\to\infty}f_n=\lim_{n\to\infty}\frac{(1-|x|)(n^{-2}+|x|^2)}{|x|^2}=1-|x| \\ \therefore f_n\to 1-|x|\quad a.e.$$
So by the DCT the answer is $(1)$. I did not really talk about measurability of $f_n$, $G(x)$ is clearly measurable, how can I show that each $f_n$ is too?

$(1)\,$ The level set $S_f(t):=\{x\in\Omega:f(x)>t\}$.  Using Lebesgue,
$$\int_{B_1(0)}\left(1-|x|\right)\,dx=\int_0^\infty\mathcal{L}^n\left(S_f(t)\right)\,dt=\int_0^{\infty}\mathcal{L}^n\left(B_{1-t}(0)\right)\,dt=\frac{2\pi^{n/2}}{(n+1)\Gamma\left(n+\frac12\right)}.$$

A: Note that the inequality
$$
|1-|x||\left(1+\frac{1}{\left(n|x|\right)^2}\right)\leq|1-|x||\tag1
$$
is not correct because $\tfrac{1}{|x|}$ is not bounded near zero. A possible way to proceed is study the sequence of integrals using spherical coordinates, then we have
$$
\int_{B_1(0)}\frac{(1-|x|)(\tfrac{1}{n^2}+|x|^2)}{|x|^2}\,\mathrm d x=\int_{0}^1n\lambda (B_1(0)) r^{n-3}(1-r)(\tfrac{1}{n^2}+r^2)\,\mathrm d r\tag2
$$
where $\lambda (B_1(0))=\frac{\pi^{n/2}}{\Gamma (1+\tfrac{n}{2})}$. Then using the Stirling approximation for the $\Gamma $ function we can know if the sequence of integrands of the RHS on $\rm (2)$ is dominated for some function or not (anyway it doesn't seems the case because the LHS on $\rm (1)$ is unbounded). Or we can just evaluate the integral and after calculate the limit.

A: It seems that your $f_{n}$ is not integrable over $B_{1}(0)$. For
example, consider the case that $n=2$. For $x\in B_{\frac{1}{2}}(0),$
$f_{n}(x)\geq C\cdot\frac{1}{|x|^{2}}$, where $C$ is a constant
(which is not important). However $\int_{B_{\frac{1}{2}}(0)}\frac{1}{|x|^{2}}dm_{2}=\int_{0}^{\frac{1}{2}}\int_{0}^{2\pi}\frac{1}{r^{2}}\cdot rd\theta dr=\infty$.


text:
Q: Building older NetBeans project in bash leads to error I am opening an older NetBeans project and I want to build it using ant in bash with debian. However, when I try to run ant, I get this error

BUILD FAILED
  /home/karelbilek/NetBeansProjects/oldProject/nbproject/build-impl.xml:528:
  The following error occurred while executing this line:
  /home/karelbilek/NetBeansProjects/oldProject/nbproject/build-impl.xml:261:
  Unable to find a javac compiler; com.sun.tools.javac.Main is not on
  the classpath. Perhaps JAVA_HOME does not point to the JDK. It is
  currently set to "/usr/lib/jvm/java-7-openjdk-i386/jre"

What does that mean? What should I do? In "/usr/lib/jvm/java-7-openjdk-i386/jre" there seems to be an actual JRE when I look there, so what is the problem?

A: You're pointing to a JRE (Java runtime environment) but not a JDK (Java development kit).
Only the JDK contains the compiler (javac). The JRE is used for running Java programs but doesn't carry the extra components of the JDK (compiler etc.)

A: it happened for me and i got through it by installing the jdk
sudo apt-get install openjdk-7-jdk

After installing jdk, the classpath executed right


text:
Q: SQL count(*) statement returning 0 whilst table contains several hundred rows I am running queries on an Intersystems Cache database via an ODBC connection. It had been working perfectly up until a couple of hours ago when sending a statement like SELECT COUNT(*) FROM cmr_table started to return 0. The statement SELECT * FROM cmr_table returns plenty of rows and seems to work as normal.
Any help is greatly appreciated!

A: Looks like, you added new index. Try to rebuild all indices in your class.
do ##class(your.class).%BuildIndices()


text:
Q: Como formatar um campo de um Datatable Jquery para formato Money usando o Jquery Mask Plugin? Preciso formatar os campos de um DataTable jQuery para formato de moeda, enquanto é feito o carregamento do Datatable, mas não estou conseguindo. Estou usando o Jquery Mask Plugin:
{
    data: 'ValorParcela',
    title: 'ValorParcela',
    autoWidth: true,
    render: function (data, type, item) {
        //return item.valorParcela;
        return item.valorParcela.mask("#.##0, 00", { reverse: true });
    },
},

Como resolver?
DATATABLE:
function load_dtFinanceiroParcela() {

    //$('#dtFinanceiroParcela').DataTable();

    //$.fn.dataTable.moment('D/M/YYYY');

    //moment.locale("pt-br");
    //alert(moment('2020/09/23', 'YYYY/MM/DD', true).format('DD/MM/YYYY'));

    var financeiroId = $('#hid-financeiro-id').val();

    $('.dataTables_filter input').attr('placeholder', 'Search...').hide();
    var table = $("#dtFinanceiroParcela").DataTable({
        "processing": false, // for show progress bar
        "serverSide": true, // for process server side
        "filter": false, // this is for disable filter (search box)
        "orderMulti": false, // for disable multiple column at once
        "ordering": true, //Ativar/Desativar Ordenação de colunas
        "order": [[1, "asc"]], //Ordenar da segunda coluna em diante para não atrapalhar a coluna [0] da seleção
        "autoWidth": false,
        "ajax": {
            "url": '/financeiro-parcela-gerenciar/get-financeiro-parcelas',
            "data": { financeiroId: financeiroId },
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [
            //Estilos Das Colunas
            { className: "align-center", "targets": [0] },
            { className: "align-center", "targets": [1] },
            { className: "align-center", "targets": [2] },
            { className: "align-center", "targets": [3] },
            { className: "align-center", "targets": [4] },
            { className: "align-center", "targets": [5] },

            //Largura das Colunas
            { width: 10, targets: 0 },
            { width: 50, targets: 1 },
            { width: 150, targets: 2 },

            //{
            //    "targets": [1, 2],
            //    "render": function (data, type, full) {
            //        moment.locale("pt-br");
            //        return moment(data).format('DD/MM/YYYY');
            //    }
            //},

            { "orderable": false, "targets": 0 },

        ],
        "columns": [

            {
                data: 'Parcela',
                title: 'Parcela',
                autoWidth: true,
                render: function (data, type, item) {
                    return item.parcela;
                },
            },
            {
                data: 'DataEmissao',
                title: 'DataEmissao',
                autoWidth: true,
                render: function (data, type, item) {
                    moment.locale("pt-br");
                    return moment(item.dataEmissao).format('DD/MM/YYYY');
                },
            },
            {
                data: 'DataVencimento',
                title: 'DataVencimento',
                autoWidth: true,
                render: function (data, type, item) {
                    moment.locale("pt-br");
                    return moment(item.dataVencimento).format('DD/MM/YYYY');
                },
            },
            {
                data: 'ValorParcela',
                title: 'ValorParcela',
                autoWidth: true,
                Render: $.fn.dataTable.render.number(",", ".", 2),

                ////render: $.fn.dataTable.render.number(",", ".", 2)
                //render: function (data, type, item) {
                //    //return item.valorParcela;
                //    //return item.valorParcela.mask("#.##0, 00", { reverse: true });
                //    render: item.valorParcela.number(",", ".", 2)

                //},
            },
            {
                data: 'FinanceiroParcelaSituacaoDescricao',
                title: 'Situação',
                autoWidth: true,
                render: function (data, type, item) {
                    return item.financeiroParcelaSituacaoDescricao;
                },
            },
            {
                "render": function (data, type, full, meta) {
                    return '

Histórico

';
                }
            }
        ],
        "language": {
            "sEmptyTable": "Nenhum registro encontrado",
            "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
            "sInfoFiltered": "(Filtrados de _MAX_ registros)",
            "sInfoPostFix": "",
            "sInfoThousands": ".",
            "sLengthMenu": "_MENU_ resultados por página",
            "sLoadingRecords": "Carregando...",
            "sProcessing": startLoadDataTable(),
            "sZeroRecords": "Nenhum registro encontrado",
            "sSearch": "Pesquisar",
            "searchPlaceholder": "Digite algo...",
            "oPaginate": {
                "sNext": "Próximo",
                "sPrevious": "Anterior",
                "sFirst": "Primeiro",
                "sLast": "Último"
            },
            "oAria": {
                "sSortAscending": ": Ordenar colunas de forma ascendente",
                "sSortDescending": ": Ordenar colunas de forma descendente"
            }
        }
    });

    ////Evento disparado depois que a table for desenhada
    table.on('draw', function () {
        stopLoadDataTable();
    });

    $('.search-input').on('keyup change', function () {
        var index = $(this).attr('data-column'),
            val = $(this).val();
        table.columns(index).search(val.trim()).draw();
    });
}

A: Seguindo essa resposta do stackoverflow pt-BR Formatar moeda brasileira em JavaScript no método render adicione a função como no exemplo:
{
    data: 'ValorParcela',
    title: 'ValorParcela',
    autoWidth: true,
    render: function (data, type, item) {
       const value = parseFloat(item.valorParcela);
       if (!value) return 0;
       return value.toLocaleString('pt-br', { minimumFractionDigits: 2 });
    },
},

Referencia: Formatar moeda brasileira em JavaScript


text:
Q: How can I smartly redirect users who click on an email link, to my app or my mobile site? I have an app and a mobile site. I also send emails to my users. I would like the following to happen if my users open these emails on their mobile phones and click on a link:
If a user has installed my app, then launch the app and open the relevant page inside it.
If a user has NOT installed my app, then launch the browser and take him to the relevant page on my mobile site.
I want this to happen seamlessly and automatically. I DON'T want to use the inbuilt android prompt as users end up choosing chrome (since it is the first option shown). How can I do this? Would ideally want solutions for both android & ios.

A: You can do this with a landing page. Send user to landing page, check platform, then check if they have app installed(if they have registered custom url scheme) if they have then they go to app. Otherwise they go to mobilesite.
See this answer by https://stackoverflow.com/a/29019660/1165581 by Adam

A: You can NOT prevent the Android prompt which lets the user choose an option. What you can do is, create a link to your mobile site and have your App react to urls containing your domain. So what will happen is:

*

*if a user clicks the link and does NOT have your App installed, he/she will be prompted with the default url handler prompt (only the first time) and then open the mobile site in the prefered browser

*if a user clicks the link and DOES have your App installed, he/she will get the same prompt, only your App will be listed there as well next to browser Apps.

Here is an explanation on how to this: Android Respond To URL in Intent

A: You can use URL Schemes in iOS for your requirement to be full filled. By Using URL Scheme you can do exactly same. Clicking on link will launch your app. Please go through the concept of URL Schemes.
Follow the below referral link:
http://code.tutsplus.com/tutorials/ios-sdk-working-with-url-schemes--mobile-6629

Hope this helps!!


text:
Q: Getting Error: connect ECONNREFUSED 127.0.0.1:80 node.js : odoo-xmlrpc I am trying to connect to odoo via odoo-xmlrpc
var odoo = new Odoo({
  url: 'x.y.z.com',
  port: 80,
  db: 'Data_Base',
  username: 'username',
  password: 'password'
});

my debugger shows "client normal" for the second line (console.log(err)) of the code below
odoo.connect(function (err) {
  if (err) { return console.log(err); }
  console.log('Connected to Odoo server.');
});

and this Error for the 3rd line :
{ Error: connect ECONNREFUSED 127.0.0.1:80
    at Object.exports._errnoException (util.js:1020:11)
    at exports._exceptionWithHostPort (util.js:1043:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80 }

I am using meanjs 0.5.0, this is the development configuration
  port: process.env.PORT || 3000,
  host: process.env.HOST || 'localhost',

I tried to use the same code on loopbackjs and it worked, but i need to deploy my app on meanjs why am I getting this error ?

A: I was using odoo-xmlrpc 1.0.5 on loopbackjs and 1.0.6 on meanjs ... When I downgraded to to 1.0.5 it worked on meanjs and to be sure about that i upgraded the package on loopback and i had the same error ...
so it is a version issue at the moment.
thank you for passing by.
EDIT :
Must use http://url or https://url


text:
Q: Regex to extract numbers from a String in VBA How can I extract the numbers from col A and print in into col B.
I am using the below regex function, it print all the numbers with a space between them.
How can I get the initial set of numbers and skip the remaining ones.
Docetaxel Injection 160MG/16ML prints  160 16. I need to print only 160.
Private Sub splitUpRegexPattern()
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim Myrange As Range

    Set Myrange = ActiveSheet.Range("A1:A10")

    For Each C In Myrange
        strPattern = "\D+"

        If strPattern <> "" Then
            strInput = C.Value
            strReplace = "$1"

            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
            End With

            If regEx.test(strInput) Then
                C.Offset(0, 1) = regEx.Replace(strInput, " ")
            Else
                C.Offset(0, 1) = "(Not matched)"
            End If
        End If
    Next
End Sub

A: This should work (pattern allows for decimals but not very robustly so):
Sub splitUpRegexPattern()

    Dim re As Object, c As Range
    Dim allMatches

    Set re = CreateObject("VBScript.RegExp")
    re.Pattern = "([\d+\.]+)"
    re.IgnoreCase = True
    re.Global = True

    For Each c In ActiveSheet.Range("A1:A10").Cells
        Set allMatches = re.Execute(c.Value)
        If allMatches.Count > 0 Then
            c.Offset(0, 1).Value = allMatches(0)
        Else
            c.Offset(0, 1).Value = "(Not matched)"
        End If
    Next c

End Sub

A: If its always 3 digits then use \s\d{3} https://regex101.com/r/lEc4mN/1

Option Explicit
Private Sub splitUpRegexPattern()
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim Myrange As Range
    Dim C As Range
    Dim Matches As Variant

    Set Myrange = ActiveSheet.Range("A1:A10")

    For Each C In Myrange
        strPattern = "\s\d{3}"

        If strPattern <> "" Then
            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
                 Set Matches = .Execute(C.Value)
            End With

            If Matches.Count > 0 Then
                Debug.Print Matches(0)
                C.Offset(0, 1) = Matches(0)
            Else
                C.Offset(0, 1) = "(Not matched)"
                Debug.Print "Not Found "
            End If

        End If
    Next
End Sub


text:
Q: After Explode() geting result: %C4%84 My problem is that after exploding a string I get this: %C4%84 value
but I should get Ą. I can convert it using preg_replace, but is there simple way to convert ?
$band_song = explode('/',$url,6);
echo $band5=$band_song[3].' '.$band_song[4]);

A: You can simply urlencode your variables.
$var = urlencode($original_var);

EDIT
You'd want decode, not encode sorry
$var = urldecode($original_var);


text:
Q: Update html image via javascript functions I'm fairly new to javascript, and getting quite frustrated by the following code

<!DOCTYPE html>

URL Output:

Forecast Hour:

 00
 01
 02

 Region Selection:

 Northeast
 Southeast

I have 18 different "hours" of images for different regions across the US. The goal is to change the hour of the image when the hour links are moused over, and update the region when the region links are clicked.
The function update_time() works as expected, changing the image as I mouse over the links. However, the function update_area() fails with the following error:
"Uncaught ReferenceError: neast is not defined"
I'm not sure why this is happening, because the update_time and update_area functions are built in exactly the same way, and I globally defined the time and area variables at the start of the script.
Any help would be appreciated!

A: You have to put the arguments in quotes .
onclick="update_area('neast');"
onclick="update_area('seast');"

<!DOCTYPE html>

URL Output:

Forecast Hour:

 00
 01
 02

 Region Selection:

 Northeast
 Southeast

In JavaScript variables are not restricted to a single 'type', but a String will always be contained in quotes and a number will not. Also a variable cannot be, or start with, a number. This is why when you use a string as an argument it must be contained within quotes, otherwise it thinks you are sending a variable.

A: You're starting your document with <!doctype html> so you're saying you're writing HTML5, but there is a whole bunch of things that are incredibly wrong here due to use HTML3.2 and obsolete ways to invoke javascript.
Under modern HTML5 rules, there are no self-closing elements. It's not a hard error, but don't add that /> at the end of an <img.... Also  hasn't existed as element for 20 years now. It was removed in HTML4.1 in 1998. Then some semantics: if you need button functionality (i.e. clickable, but NOT navigating to some (part of a) page), use <button>. That's what it's for. Do not use , and definitely not with href="#", because that's an active instruction for the browser to scroll to the top of the page. Finally, on...=... handlers are an ancient attribute that is unfortunately still supported, but you should never use. Use addEventListener in your Javascript, after you've declared all your HTML.
So let's just fix everything at the same time:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Always just fill this in, it's good practice</title>

URL Output:

Forecast Hour:

        <button class="forecast update" data-value="0">0h</button>
        <button class="forecast update" data-value="1">1h</button>
        <button class="forecast update" data-value="2">2h</button>

Region Selection

        <button class="area update" data-value="neast">Northeast</buton>
        <button class="area update" data-value="seast">Southeast<button>

And then we make a second file for the javascript called updates.js:
// this goes last, so that the DOM is done by the time you invoke your script.
var currentTime = 0;
var currentArea = `NorthEast`;

// this function doesn't need parameters: we already know what they are
function load_updated_image() {
  var url = `http://personal.psu.edu/kps5442/modelimages/hrrr_${currentArea}_wetbulb${currentTime}.png`;
  let figure = document.getElementById(`forecast-image`);
  // update the image
  let img = figure.querySelector(`img`);
  img.src = url;
  // update the image caption with a link
  let caption = figure.querySelector(`figcaption`);
  caption.innerHTML = ``;
  let link = document.createElement(`a`);
  link.href = url;
  caption.appendChild(link);
}

// update the area, and called image update
function update_area(area) {
  currentArea = area;
  load_updated_image();
};

// update the time, and called image update
function update_time(time) {
  currentTime = timel
  load_updated_image();
};

// add the initial page load handling
document.addEventListener(`ready`, evt => load_updated_image());

// add the click handling for forecast time buttons
let forecastButtons = document.querySelectorAll(`button.forecastupdate`);
forecastButtons.forEach(button => {
  // get the button's data-value
  value = button.dataset.value;

  // and then set up a click listener to update the forecast time
  button.addEventListener(`click`, evt => update_time(value));
});

// add the click handling for forecast area buttons
let areaButtons = document.querySelectorAll(`button.area.update`);
forecastButtons.forEach(button => {
  // get the button's data-value
  value = button.dataset.value;

  // and then set up a click listener to update the forecast area
  button.addEventListener(`click`, evt => update_area(value));
});

And then to be even more proper, don't use  but make a new file called "forecast.css" and then link to that in your page using <link href="forecast.css" rel="stylresheet"> (note: this is still HTML5, you don't put /> at the end. Link elements simply don't have a closing tag)


text:
Q: Populate AngularJS model with existing values I'm adding a mild amount of angularjs to my existing application.  I'm starting with utilizing controllers to manage my forms which are all submitted by ajax.  The forms are currently pulled into the page using jQuery's $.load() function and the form elements already have values.
I'd like my models I've assigned into $scope to have these values available.  For example:
<form>
  <input type="text" ng-model="user.firstName" value="Gregg" />
  <input type="text" ng-model="user.lastName" value="Bolinger" />
  <button ng-click="update(user)">Save</button>
</form>

And then in my main.js file I would have something like the following:
function UserCtrl($scope) {
  $scope.update = function(user) {
    // update the user
  };
}

As is, my form input elements are blank because the ng-model is empty.  Is there a way to initialize my ng-model with the existing values in the form?
BTW, I did read this SO Question which is the same as mine, however, I'm hoping for a better answer than some window scoped global variable.

A: The big issue here really is that in your current setup, jQuery is operating outside of the angular world. It has no concept of angular scopes, or any real way of accessing them without being a little bit hacky and going against how angular works, BUT you can do this if you want.
After you've loaded your data from jQuery, rather than setting the values of your form, you can just set the values directly within the angular models. If for example you had your page something like
<div class="wrapper" ng-controller="UserCtrl">
    <form>
        ... inputs as in your post ...
    </form>
</div>

Then inside your controller, put
$scope.user = {
    firstName: "",
    lastName: ""
}

Then you're actually able to get the angular scope from jQuery at any point. In this example, you would simply do
$(".wrapper").scope();

So, in your jQuery, you could fetch your data as you're doing, and then just assign the values within the scope. So for example, you could do something such as
var user = ... load data with jquery here ...;
var scope = $(".wrapper").scope();
var $user = scope.user;
scope.$apply(function() {
    $user.firstName = user.firstName;
    $user.lastName = user.lastName;
});

In theory this should do what you're after.
I would however highly recommend you move your data loading to angular as well, as this makes life a lot easier and less confusing. Angular makes data loading just as easy as jQuery does as well which is nice, and if you were to use ngResource (which personally I love) you could fetch a user by simply doing
User.get({ id: user_id_here })

And that's it. Then in your controller, you'd just have
$scope.user = User.get({ id: user_id_here })

And the form would be set to go :)
But as I say, you can have it run inline with your current structure if you wish


text:
Q: Running stanford NER classifier in server mode To make the NER classification faster I am trying to execute it in server mode listerning on port xxxx, so that it can give faster result when request is send.
Here is the original execution command without server that I am using.
java -mx1500m -cp $1/stanford-ner.jar edu.stanford.nlp.ie.crf.CRFClassifier -loadClassifier $1/classifiers/ner-eng-ie.crf-3-all2008-distsim.ser.gz -textFile $2

(this command is in .sh file and executed by python script. $1 is input file name)
This documentation explain how it can be run in server mode - Link
Here how the server get started:
java -mx400m -cp stanford-ner.jar edu.stanford.nlp.ie.NERServer -loadClassifier classifiers/ner-eng-ie.crf-3-all2008.ser.gz 1234

Now server is in listerning mode on port 1234.
How can I make call using input text file for this server?
I followed this tut : Link and executed this command:
java -cp stanford-ner.jar edu.stanford.nlp.ie.NERServer -port 1234 -client

But it just print this message:
Usage: NERServer [-loadFile file|-loadJarFile resource] portNumber

I am working on linux system.

A: To run the NER in server mode, you have to use the following command line :
java -mx400m -cp stanford-ner.jar edu.stanford.nlp.ie.NERServer -loadClassifier classifiers/ner-eng-ie.crf-3-all2008.ser.gz -port 1234

(-port is missing  in the README file, it works well for me)


text:
Q: StreamBuilder flutter I added two item in list, then add the list to sink.
var list = new List<String>();
AbcBloc _abcBloc = AbcBloc(repository: null);

 @override
  void didChangeDependencies() {
    _abcBloc = Provider.of<AbcBloc>(context);
    super.didChangeDependencies();
  }

@override
  void initState() {
    super.initState();

    list.add('Electrical');
    list.add('Inspection');

    _abcBloc.listSink.add(list);
  }

But when I try to print the list in TextField, it prints empty?
  StreamBuilder(
                      stream: _abcBloc.listStream,
                      builder: (context, snapshot) {
                        return TextField(
                          decoration: InputDecoration(
                              labelText: snapshot.data,
                             ....
                        );
                      },
                    ),

AbcBloc.dart
  final _list = BehaviorSubject<List<String>>();
  get listSink => _list.sink;
  get listStream => _list.stream;

Edit
After use the suggestion answers, it print null value. Why would this happened?

A: Firstly, snapshot.data is a list of String items so to display the list as a single String you need to add a toString(); Secondly, you need to be more specific with types - you need to specify what data your StreamBuilder expects, i.e.
    StreamBuilder<List<String>>(
      stream: _abcBloc.listStream,
      builder: (context, snapshot) {
        return TextField(
            decoration: InputDecoration(
          labelText: snapshot.data.toString(),
        ));
      },
    ),

Taking your example and making those two changes then resulted in [Electrical, Inspection] showing in the text field on my device.

A: Problems I see:

*

*StreamBuilder has no generic type. Make it StreamBuilder<List<String>>

*You're passing List to labelText parameter. You should pass String. (e.g. snapshot.data.toString())

*You don't check whether your stream has data or not inside builder. You can do it using snapshot.hasData condition or set initialData parameter.

A: I was able to fix it.What I did was put the list and the stream in didChangeDependencies.
  @override
  void didChangeDependencies() {
     _abcBloc = Provider.of<AbcBloc>(context);
     list.add('Electrical');
     list.add('Inspection');
     _abcBloc.listSink.add(list);
     super.didChangeDependencies();

  }


text:
Q: Return dictionary + CookieContainer cookies from task I have some code That Runs a Task to return a dictionary ... but sometimes i need it to return both the dictionary and a cookiecontainer with cookies ... here's the code
        static public async Task<Dictionary<String,String>> login(string server, string id, string pw)
    {

        CookieContainer cookies = new CookieContainer();
        HttpWebRequest newRequest = GetNewRequest(server, cookies);
        Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
        dictionary2.Add("name", id);
        dictionary2.Add("password", pw);
        dictionary2.Add("uni_url", server);
        Dictionary<string, string> parameters = dictionary2;
        HttpWebResponse response = await MakeRequest(newRequest, cookies, "login", server, parameters);
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            if (!reader.EndOfStream)
            {
                Dictionary<String, String> answer = new Dictionary<string, string>();
                answer.Add("HTML", reader.ReadToEnd());
                return answer;// here i need it to return CookieContainer .
            }
        }
        Dictionary<String, String> answerFailed = new Dictionary<string, string>();
        answerFailed.Add("LoginFailed", "LoginFailed! No Internet Connection!");
        return answerFailed;
    }

my question : How do I return two different things from the same method?

A: If you can change method you can use Tuple<T1,T2> To return two values from task:
 static public async Task<Tuple<Dictionary<String,String>,CookieContainer>> login(string server, string id, string pw)
    {
     CookieContainer cookies = new CookieContainer();
      Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
// create result tuple
     var result = Touple.create(dictionary2,cookies);
     return result;
    }

A: The overload capabilities can't help you because only parameters should be different.
In these case i normally create a new class with all properties you need as output and return an instance of these classe from task.
The overhead is minimal and is a good pattern for future espansion.


text:
Q: Articles in menu items I found articles are omitted in menu items(Open File, Create Folder). Is there a rule that I should follow?
I'm wondering do I need to add articles to these items?

Create a Box
  Delete the Selected Objects
  Close the Window.

A: I see it as a form of headlinese (Wikipedia). Headlinese is a rough guideline of abbreviated language used in newspaper headlines to save space. However, the usage extends beyond headlines. I would say it applies here too, since menu items use limited space. Specifically,

*

*Forms of the verb "to be" and articles (a, an, the) are usually omitted.

*Most verbs are in the simple present tense, e.g. "Governor signs bill", while the future is expressed by an infinitive, with to followed by a verb, as in "Governor to sign bill".

In this style, your examples with the articles omitted sound fine to me as menu items.


text:
Q: How overload optional parameter in typescript? I have interface like this:
export interface Actions {
      [ActionEnum.FOO](someParam: {}, payload: string): void
      [ActionEnum.BAR](someParam: {}, payload: PayloadType): void
      [ActionEnum.BAZ](someParam: {}): void
    }

As u can see second parameter is optional.
I have a function:
type Dispatch = <K extends keyof Actions, P extends Parameters<Actions[K]>[1]>(type: K,  payload?: P) => ReturnType<Actions[K]>

First parameter is ActionEnum. Second is payload from same action.
It is works. TS check type of payload correctly if I pass payload. But I may not pass payload if even necessary. No TS errors for this case.
How say to TS that in specific case second parameter optional or not. For example:
Dispatch(ActionEnum.FOO) // error, because we have second parameter in Action
Dispatch(ActionEnum.BAZ) // no error, because we have not second parameter in Action


text:
Q: QGIS vector edition corrupts SpatiaLite attribute table I have a problem with edit SpatiaLite Layer on QGIS.
When I make a this set of editions: cut line, delete a part, insert a new line and save it, the attribute table is corrupted.
I was thought that the trouble is within PK, but I have made new tests and now think the trouble is about value NULL in the numeric attributes of new features inserted. If I fill the atributes with any value when insert the trouble not occurs.
I tested it with a PK_UID attribute defined as INTEGER PRIMARY KEY AUTOINCREMENT and an spatial index on the geometry (type linestring). I also tested without PK.
I've tested on QGIS 2.2 and 2.4 (Windows 32).


text:
Q: Burnside's Lemma and Necklaces I have the following question that I am stuck on.

A jeweler is making necklaces containing 12 beads of two colors that can be worn on either side (that is, we consider necklaces up to both circular and flip symmetry). How many distinct necklaces can be created?

I know that two necklaces are distinct if one can not be rotated or flipped to form the other. I also know that we need Burnside's Lemma for this question. Burnisde's Lemma tells us that for a finite group $G$ acting on  a set $X$, the number $|\mathcal{O}|$ of orbits is $$|\mathcal{O}|=\frac{1}{|G|}\sum_{g\in G}\mathrm{Fix}(g).$$
So in this case, the set $X$ is the collection of all configurations of necklaces, so $X$ is a set with cardinality $2^{12}$. Because we are considering both circular and flip rotations, the group acting on $X$ should be $D_{24}$, the set of symmetries of the regular 12-gon, right?
From here, I think that all we need to do is examine the elements of $D_{24}$ and find their fixed points. However, I'm not sure how to actually find the set of fixed points for all 24 elements in the group. Thanks in advance for any help!


text:
Q: How can I capture images of people not wearing Face Mask and store images in local desktop? IN PYTHON THIS IS MY PYTHON CODE SO FAR,
This code generates a live stream video from the webcam and detects facemask and no facemask people,
now I want to take pictures of people who are not wearing face mask and store images of those in the local directory.
please help me to find the solution to this issue
I already have a data set of no mask and mask
now I want to take picture of those not wearing face mask and save in the local directory using the webcam live videostram
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
from imutils.video import VideoStream
import numpy as np
import imutils
import time
import cv2
import os
import time

lowConfidence = 0.75

def detectAndPredictMask(frame, faceNet, maskNet):

    (h, w) = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224),
        (104.0, 177.0, 123.0))

    faceNet.setInput(blob)
    detections = faceNet.forward()

    faces = []
    locs = []
    preds = []

    for i in range(0, detections.shape[2]):

        confidence = detections[0, 0, i, 2]

        if confidence > lowConfidence:

            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            (startX, startY) = (max(0, startX), max(0, startY))
            (endX, endY) = (min(w - 1, endX), min(h - 1, endY))

            face = frame[startY:endY, startX:endX]
            face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
            face = cv2.resize(face, (224, 224))
            face = img_to_array(face)
            face = preprocess_input(face)

            faces.append(face)
            locs.append((startX, startY, endX, endY))

        if len(faces) > 0:
        faces = np.array(faces, dtype="float32")
        preds = maskNet.predict(faces, batch_size=32)

    return (locs, preds)

prototxtPath = r"deploy.prototxt"
weightsPath = r"res10_300x300_ssd_iter_140000.caffemodel"
faceNet = cv2.dnn.readNet(prototxtPath, weightsPath)

maskNet = load_model("mask_detector.model")

vs = VideoStream(src=0).start()

while True:

    frame = vs.read()
    frame = imutils.resize(frame, width=900)

    (locs, preds) = detectAndPredictMask(frame, faceNet, maskNet)

    for (box, pred) in zip(locs, preds):

        (startX, startY, endX, endY) = box
        (mask, withoutMask) = pred

        label = "Mask" if mask > withoutMask else "No Mask"
        color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
        if label =="Mask":
            print("MASK DETECTED")

        else:
            print("MASK NOT DETECETED")

            label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)

        cv2.putText(frame, label, (startX, startY - 10),
            cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
        cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)

    cv2.imshow("PROMENADE FACE MASK DETECTOR", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

cv2.destroyAllWindows()
vs.stop()

A: cv2.imwrite('path_to_desktop/filename.jpg', face)

read more about imwrite() here
Within detectAndPredictMask your code is looping over detections and is extracting a slice of frame and assigning it to face (face = frame[startY:endY, startX:endX]). face contains a OpenCV compatible image. Use imwrite before face = img_to_array(face) as there image is trasformed to a Numpy array.


text:
Q: simple_form and on the fly conversions I'm writing a rails app where there is a model that takes certain measures (height, weight, neck_circumference, etc.)
I want it to work both for metric and imperial measurement system.
My model has a measure_unit attribute that can be both metric or imperial. All the measures will be stored in the database in metric system.
I use the simple_form gem, and I have no clue on how to implement the views so that if a user uses the imperial system his data is converted on the fly.
<% if @customer.measure_unit.eql? "metric" %>
  <%= f.input :height %>

<% else %>
  ...
<% end %>

How do I fill the blanks?
EDIT -- Found a working solution
I ended up using virtual attributes such as "height_in_cm" and "height_in_in" leaving the entries in the database to be stored in mm.
Here is the code for the model:
  def height_in_cm
    height / 10
  end

  def height_in_cm=(height)
    self.height = height.to_f  * 10
  end

  def height_in_in
    height * 0.039370
  end

  def height_in_in=(height)
    self.height = height.to_f / 0.039370
  end

And the code for the view:
  <% if @customer.measure_unit.eql? "imperial" %>
    <%= f.input :height_in_in %>

  <% else %>
    <% if @customer.measure_unit.eql? "metric" %>
      <%= f.input :height_in_cm %>

    <% end %>
  <% end %>

A: One solution would be to pass a hidden field back to the controller indicating that the value passed is imperial and needs to be converted into metric for database storage.
So rather than having a different input for metric and imperial measurements you can simply use a single input which defaults to metric and you have to detect for the non-default (imperial):
<%= f.input :height %>

<%= f.hidden_field :imperial, :value => (@customer.measure_unit.eql? "imperial" ? true : false) %>

Now in your controller action before you have the measurement attribute saved:
if params[:imperial] == true
  #convert imperial measurement to metric (replace @foo with your object)
  @foo.height = convert_to_metric(params[:height])
end


text:
Q: What are the rules for out-of-line definitions of constrained member templates? Consider the following code:
template <typename T>
struct S
{
    template <typename = void>
    static constexpr bool B = true;

    template <std::enable_if_t<S<T>::template B<>, int> = 0>
    void f();
};

template <typename T>
template <std::enable_if_t<S<T>::template B<>, int>>
void S<T>::f() {}

gcc accepts this, but clang rejects it with:
error: out-of-line definition of 'f' does not match any declaration in 'S<T>'

This has been asked about before, but there is no answer there.

On the other hand, if B is not a template, and I write this code:
template <typename T>
struct S
{
    static constexpr bool B = true;

    template <std::enable_if_t<S<T>::B, int> = 0>
    void f();
};

template <typename T>
template <std::enable_if_t<S<T>::B, int>>
void S<T>::f() {}

clang accepts this, but gcc rejects the code with:
error: no declaration matches 'void S<T>::f()'

So are either of these snippets valid?

A: During the definition of S<X> it is an incomplete type. And the class member access operator requires a complete type.
But you could solve the situation with the following code:
#include <type_traits>

template <typename T>
struct S {

    template <typename = void>
    static constexpr bool B = true;

    template <
        typename TX = T,
        std::enable_if_t<S<TX>::template B<>, int> = 0>
    void f();
};

template <typename T>
template <typename TX, std::enable_if_t<S<TX>::template B<>, int>>
void S<T>::f() {}

//-----------

template <typename T>
struct S2 {

    static constexpr bool B = true;

    template <
        typename TX = T,
        std::enable_if_t<S2<TX>::B, int> = 0>
    void f();
};

template <typename T>
template <typename TX, std::enable_if_t<S2<TX>::B, int>>
void S2<T>::f() {}


text:
Q: Display images in order rather than by random using JS? Listed below in the block of code is Math.random. I'm trying to display images every time the page is refreshed or reloaded. Though, the only way I know is to mathmatically load them randomly. The problem is, I don't want them to load randomly, I want them to load in order of the imageArray. Is there a way around the random function that can display each image in order of the array?
var imageArray = [
    [ 'http://example.com/assets/reporter.png', '', '' ],
    [ 'http://example.com/assets/chair.png', '', '' ]

];

function doIt()
{
var rand = Math.floor(Math.random()*imageArray.length);

    var html = "
"+imageArray[rand][1]+"
";

document.getElementById("image").innerHTML = html;
}

A: Put the array index in a cookie or local storage. When the page loads, get the cookie, and increment it (if it's not set this is the first time, so select an image at random). If the increment reaches the size of the array, wrap around to 0. Then display the image with that index. Then save the new cookie value.
var imageArray = [
    [ 'http://example.com/assets/reporter.png', '', '' ],
    [ 'http://example.com/assets/chair.png', '', '' ]

];

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function doIt()
{
    var rand = getCookie('rand');
    if (rand == null) {
        rand = Math.floor(Math.random()*imageArray.length);
    } else {
        rand++;
        if (rand >= imageArray.length) {
            rand = 0;
        }
    }
    setCookie('rand', rand);
    var html = "
"+imageArray[rand][1]+"
";

    document.getElementById("image").innerHTML = html;
}


text:
Q: Wired ethernet on a Mac mini 2012 with Ubuntu 12.10 problem I have a issue with a late mac mini 6.1 2012
Ubuntu: 12.10 Kernel: 3.5.0-25 generic
lspci -nnk | grep -i net -a3:
00:1f.3 SMBus [0c05]: Intel Corporation 7 Series/C210 Series Chipset Family SMBus Controller [8086:1e22] (rev 04)
        Subsystem: Intel Corporation Device [8086:7270]
        Kernel modules: i2c-i801
01:00.0 Ethernet controller [0200]: Broadcom Corporation NetXtreme BCM57766 Gigabit Ethernet PCIe [14e4:1686] (rev 01)
        Subsystem: Broadcom Corporation NetXtreme BCM57766 Gigabit Ethernet PCIe [14e4:1686]
01:00.1 SD Host controller [0805]: Broadcom Corporation NetXtreme BCM57765 Memory Card Reader [14e4:16bc] (rev 01)
        Subsystem: Broadcom Corporation Device [14e4:0000]
        Kernel driver in use: sdhci-pci
        Kernel modules: sdhci-pci
02:00.0 Network controller [0280]: Broadcom Corporation BCM4331 802.11a/b/g/n [14e4:4331] (rev 02)
        Subsystem: Apple Inc. Device [106b:010e]
        Kernel driver in use: bcma-pci-bridge
        Kernel modules: bcma

I cant get wired to work but my wifi works after a install of this package packages.ubuntu.com/quantal/all/linux-firmware-nonfree/downloadU. ,
Now i need to figure out how to get the wired to work.
but i will come and ask about that if i cant find any post about it.

A: Based on these instructions I found a link to installing the driver with DKMS. I tested this on 12.04 LTS (not 12.10) and it worked with this hardware:
01:00.0 0200: 14e4:1686 (rev 01)
Subsystem: 14e4:1686
01:00.0 Ethernet controller: Broadcom Corporation Device 1686 (rev 01)
Subsystem: Broadcom Corporation Device 1686
Flags: bus master, fast devsel, latency 0, IRQ 16
Memory at a0400000 (64-bit, prefetchable) [size=64K]
Memory at a0410000 (64-bit, prefetchable) [size=64K]
Capabilities: <access denied>
Kernel driver in use: tg3
Kernel modules: tg3

I've copied the relevant instructions here as requested.
Install any pending kernel updates, and the dkms package. Check that you are running a Linux kernel version 3.5 or later. If you upgraded the kernel, you must reboot with the new kernel before you will be able to load the driver.
Accept the Broadcom license and download and install the latest drivers for 3.5 and higher kernels. Extract the ZIP file and move its contents to /usr/src/tg3-3.124c/src:
unzip linux-3.124c_3.5_KERNELS.zip
sudo mkdir /usr/src/tg3-3.124c
sudo mv tg3-3.124c /usr/src/tg3-3.124c/src

Create a file called /usr/src/tg3-3.124c/dkms.conf with the following contents:
PACKAGE_NAME=tg3
PACKAGE_VERSION=3.124c
CLEAN="make -C src/ clean"
MAKE="cd src/ && make BUILD_KERNEL=${kernelver} KVER=${kernelver}"
BUILT_MODULE_NAME[0]="tg3"
BUILT_MODULE_LOCATION[0]="src/"
DEST_MODULE_LOCATION[0]=/updates
AUTOINSTALL=yes

Run the following commands to compile and install the driver:
sudo dkms add -m tg3 -v 3.124c
sudo dkms build -m tg3 -v 3.124c
sudo dkms install -m tg3 -v 3.124c

And load the driver:
sudo modprobe tg3


text:
Q: How to find near polygons I have some polygons with attributes (in my case, some polygons have health establishments) and others without attributes (without health establishments). Is there a function that I can use in order to attribute health establishments to the polygons without it (using a distance approach)?

A: I think you can using the following steps:

*

*Split your polygon layer to two:

*

*One polygon layer with health establishments

*One polygon layer without health establishments

*Then make sure you have the refFunctions plugin installed and enabled by going to the menubar:
Plugins > Manage and Install Plugins...

*Highlight your polygon layer without health establishments, access the Field Calculator and enter the following expression (replace with the layer name of the layer with health establishments and the field of which you want to copy the attributes from):
geomnearest('layer_name_with_health_establishments', 'Field_Name')

Your layer now should contain the nearest health establishment.

*(Optional). You can then join or merge the two polygon layers into one using tools such as from the menubar:
Vector > Data Management Tools > Merge Shapefiles to One

or from the Processing Toolbox:
QGIS geoalgorithms > Vector general tools > Join attributes table


text:
Q: NIFI: limit number of concurrent tasks of a NIFI processor in a NIFI-Cluster The question says it all. How can I do one of the following things:

*

*How can I limit the number of concurrent tasks running for one processor cluster-wide?

*Is there any unique and short ID for the Node, I run on? I could use these ID to append to the database-table-name to load (see details below) and have an exclusive table per connection.

I have a NIFI cluster and a self-written, specialized Processor, that loads heavy amounts of data into a database via JDBC (up to 20Mio rows per Second). It uses some of the database-vendor specific tuning tricks to be really fast in my particular case. One of these tricks needs an exclusive, empty table to load into for each connection.
At the moment, my processor opens one connection per Node in the NIFI-Cluster (it takes a connection from the DBCPConnectionPool). With about 90-100 nodes in the cluster, I'd get 90-100 connections - all of them bulk loading data at the same time.
I'm using NIFI 1.3.0.0
Any help or comment is highly appreciated. Sorry for not showing any code. It's about 700 lines not really helping with the question. But I plan to put it on Git and as part of the open-source project Kylo.

A: A common way of breaking up tasks in NiFi is to split the flow file into multiple files on the primary node. Then other nodes would pull one of the flow files and process it.
In your case, each file would contain a range of values to pull from the table. Let's say you had a hundred rows and wanted only 3 nodes to pull data. So you'd create 3 flow files each having separate attribute values:

*

*start-row-id=1, end-row-id=33

*start-row-id=34, end-row-id=66

*start-row-id=67, end-row-id=100

Then a node would pick up a flow file from a remote process group or a queue (such as JMS or SQS). There's only 3 flow files so no more than 3 nodes would being loading data from a connection.


text:
Q: How do we express a straight line of $R^2$ in set notation? How do we express a straight line of $R^2$, with equation $y=x$, in set notation?  Is this okay?
$ \{y \ | \ y=x, x \in R \} $

A: You want to have a set of points in the plane. A point in the plane is usually written as $(x, y)$. We start with that:
$$
\{(x, y)\in \Bbb R^2\mid{}
$$
(The $\in \Bbb R^2$ is to make it clear to anyone reading this line that we are actually talking about points in the plane, and implicitly that $x$ and $y$ are real numbers.)
Now, which $x$ and $y$ pairs are we after? It's all the pairs where $x = y$ and no other pairs. So we add that, and we're done:
$$
\{(x, y)\in \Bbb R^2\mid x = y\}
$$

A: The appropriate notation would be $\{(x,y)\in\Bbb R^2\,:\,y=x\}$. An alternative could be $\{(t,t)\,:\,t\in\Bbb R\}$, though it would not be too nice to use when it is not clear from context that it is suppesed to be a subset of $\Bbb R^2$.


text:
Q: Asp.NET Web API throwing 404 instead of 400 I have built a service in .NET 4.5 and Entity Framework 6, using the ASP.NET Web API template. When I make a GET request to the service and omit a required parameter, it is returning a 404 - Not Found, instead of a 400 - Bad Request. I tried checking to see if the required parameters are null, but it's not even reaching the code inside the method (see code below). My question is how do I change the default response or make it return 400 for missing required parameters.
[Route("item")]
[HttpGet]
public IHttpActionResult GetItem(string reqParam1, string reqParam2)
{
    if (reqParam1 == null || reqParam2 == null)
        throw new HttpResponseException(HttpStatusCode.BadRequest);

    //remainder of code here
}

Here is the webAPI.config file. I don't think that I have modified it from the default.
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Just a note: the API isn't accessing information such as item/electronics/tvs but more like items where item is green and is square, where those descriptions are mandatory to pass in - so the query is like /item?color=green&shape=square.

A: The server returns a 404 because it cannot find the route you are trying to access. Actually the arguments should be a part of your route, as optionals or not: Route("items/{reqParam1}/{reqParam2}")
If you defined them as optionals the route should still be called if you use just items and you can throw the BadRequest. If not optionals then probably the NotFound will still be thrown.
You should also post the webApi config, so that we can see the base route mapping.
EDIT
take the following route example:
config.Routes.MapHttpRoute(
            name: "RunsWithParams",
            routeTemplate: "api/{controller}/{project}/{skip}/{take}",
            defaults: new { take = RouteParameter.Optional, skip = RouteParameter.Optional }
        );

the project param is mandatory, the remaining are optional. you can call with just the project, or the remaining, and if you use just one of the Optionals then 404 is thrown, because the route is not defined.
This is the same as using the decorators, so it does not exactly solve your issue, but explains a bit better the routing. Still, I don't see why you need a BadRequest in particular.
Yet another edit:
To use the request url parameters as you mention at the end of the post, you just need to use the [FromUri] decorator, see this page for more details, and a breef example follows:
// POST api/files/{project}?target={target}
public HttpResponseMessage Post(string project, string target, [FromUri]string fname){...}


text:
Q: Are there X11 XInput2 raw events for joysticks and controllers? I am using the XInput2 interface in C++ to get raw input events for keyboard and mouse on my X11 application to linux. That works fine.
I have a joystick and a bluetooth connected game controller (xbox controller like)
I don't see any events from either of those using XInput2
Should I expect to be able to get events from those as well as keyboard & mouse or is there a different method I should use for them?
A brief look seems to indicate that I can use read events from /dev/input/event* for them. Is this the correct way to interface with them in low level linux. That seems a pity as I'll need two entirely different input event systems, one for keyboard & mouse, and one for controller and joystick so wanted to make sure before going that way.


text:
Q: How can I stream all audio from my imac into a PC on the same network? I would like all iMac sounds to go through my network into my PC speakers. Is there an available solution for this?

A: Should be possible with AirFoil, but I've only personally used it to send audio between two Macs. They have a Windows version as well, though.


text:
Q: Public CNAME to private internal domain doesn't work Public name server (controlled by me, I own example.com):

private.example.com. 300 IN CNAME myserver.home.

Private name server (some auto-config voodoo, can't modify this record):

myserver.home. 300 IN A 192.168.6.66

But private.example.com only works intermittently: It did use to work in Chrome, but currently doesn't. dig without further options returns the cname, but dig with +norecurse fails, each tested with the local dns server and several public ones.
What is the easiest way to fix this? Something that doesn't involve setting up a local nameserver, preferably?
Background: In my home network there is a server "myserver.home" which is accessible as "myserver.home", but this is obviously no valid public dns name. It does work fine in the home network, though. Because I want HTTPS, I added a CNAME from private.example.com to myserver.home so I can get a certificate for private.example.com (using certbot, dns-01, works just fine).

A: It is not clear setup, but I suppose dig is asking public DNS server which obviously have no idea what 'myserver.home' is. dig (and any other resolving software) have to go through actual DNS-records to resolve 'example.com'. If you refer to 'myserver.home' - this name should exist in DNS realm of resolver, no any other realms will work (like /etc/hosts or autoconfig).
There are two ways to prove you own the domain-name - through web-page or through DNS TXT record.
If you need a certificate issued to example.com and you are the one managing public example.com DNS - you need to create TXT records for example.com proving it belong to you. This depends on the software you are using (certbot, acme.sh or else). Look the manpage for 'DNS challenge'.