text:
Q: Find the domain and the correspondence rule of $F$ $F=f ∘ f∘ f$, $f(x)=\frac{1}{1-x} ⇒ Dom f(x)=\mathbb{R}-\{1\} \land Ran f(x)=\mathbb{R}-\{0\}$, then:
\begin{align*}
 Dom(f∘ f)&=\{ x ∈ Dom(f) \land f(x) ∈ Dom(f)\} \\
           &=\{ x ∈ \mathbb{R}-\{1\} \land \frac{1}{1-x} ∈ \mathbb{R}-\{1\} \} \\
           &=\{ x ∈ \mathbb{R}-\{1\} \land x ∈ \mathbb{R}-\{0\}-\{1\}  \} \\
                &=\{ x ∈ \mathbb{R}-\{1\}  \} \\
  Dom(f∘ f∘ f)&=\{ x ∈ Dom(f∘ f) \land f(f(x)) ∈ Dom(f∘ f)\} \\
          &=\{ x ∈  x ∈ \mathbb{R}-\{1\} \land \frac{1}{1-\dfrac{1}{1-x}} x ∈ \mathbb{R}-\{1\}\} \\
            &=\{ x ∈ \mathbb{R}-\{1\} \land 1-x ∈
              \mathbb{R}-\{1\}\} \\
  &=\{ x ∈ \mathbb{R}-\{1\} \} \\
F&=x
\end{align*}
It's wrong?

From: Lumbreras Editors

A: Since $f(\cdot)$ only takes values $\neq 1$, $f(f(x))$ is defined for $x \neq 1$ (because we need that the inner $f(x)$ is defined) and all the values of $x$ for which $f(x) \neq 1$, that is, $f(f(x))$ is defined for $x \neq 0,1$. Similarly, $f(f(f(x)))$ is defined for $x \neq 0,1$ (because we need that $f(f(x))$ is defined) and all the values of $x$ for which $f(f(x)) \neq 1$, that is, $f(f(f(x)))$ is defined for $x \neq 0,1$ since $f(f(x))$ is always $\neq 1$.
Thus $\operatorname{dom}(F) = \mathbb R \setminus \{0,1\}$.


text:
Q: Fire and forget worker inside controller I need to create a simple solution to receive input from an user, query our database and return the result in any way, but the queries can take as long as half an hour to run (and our cloud is configured to timeout after 2 minutes, I'm not allowed to change that).
I made the following solution that works locally, and want to include code to send the query's result via email to the user (in a fire and forget manner), but am unsure as how to do that while returning HTTP 200 to the user.
index.js:
const express = require('express')
const bodyParser = require('body-parser')
const db = require('./queries')
const app = express()
const port = 3000

app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
)

app.get('/', (request, response) => {
  response.json({ info: 'Node.js, Express, and Postgres API' })
})

app.post('/report', db.getReport)

app.get('/test', db.getTest)

app.listen(port, () => {
  console.log(`App running on port ${port}.`)
})

queries.js:
const Pool = require('pg').Pool
const pool = new Pool({
  user: 'xxx',
  host: 'xx.xxx.xx.xxx',
  database: 'xxxxxxxx',
  password: 'xxxxxxxx',
  port: xxxx,
})

const getReport = (request, response) => {
  const { business_group_id, initial_date, final_date } = request.body

  pool.query(` SELECT GIANT QUERY`, [business_group_id, initial_date, final_date], (error, results) => {
    if (error) {
      throw error
    }
    response.status(200).json(results.rows)
  })
  // I want to change that to something like:
  // FireNForgetWorker(params)
  // response.status(200)
}

module.exports = {
  getReport
}

A: Through the use of callbacks, and based on the design of express, you can send a response and continue to perform actions in that same function. You can, therefore, restructure it to look something like this:
const Pool = require('pg').Pool
const pool = new Pool({
  user: 'xxx',
  host: 'xx.xxx.xx.xxx',
  database: 'xxxxxxxx',
  password: 'xxxxxxxx',
  port: xxxx,
})

const getReport = (request, response) => {
  const { business_group_id, initial_date, final_date } = request.body

  pool.query(` SELECT GIANT QUERY`, [business_group_id, initial_date, final_date], (error, results) => {
    if (error) {
      // TODO: Do something to handle error, or send an email that the query was unsucessfull
      throw error
    }
    // Send the email here.
  })

  response.status(200).json({message: 'Process Began'});
}

module.exports = {
  getReport
}

=============================================================================
Another approach could be to implement a queuing system that would push these requests to a queue, and have another process listening and sending the emails. That would be a bit more complicated though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Printing all text from a class in HTML using python I'm trying to print all the text from a certain class on a page but can't find how,
dmenuhtml = BeautifulSoup(dmenu, 'html.parser')

#print(dmenuhtml)

#using find function to parse through the html
allday_breakfast = dmenuhtml.find()
#converting to text
allday_breakfast2 = allday_breakfast.text.strip()

print ("The All Day Breakfast today features...\n")
print(allday_breakfast)

I'm not familiar with HTML so I'm not sure what toput in the find brackets?

A: a = [i.text for i in dmenuhtml.findAll('div',{'class':'/class_name/'})]

try something like this. you need to know where your text is located in the html.


text:
Q: auto-escape hint is not working in liferay models To prevent XSS attacks in liferay I followed the auto-escape hint concept for domain model attributes.
I added the below configuration in portlet-model-hints.xml
<field name="lastName" type="String" localized="true">
    <hint name="auto-escape">false</hint>
</field>

And from the data entry screens I added the data
UNTRUSTED DATA

for lastname field. But from the view pages of public which doesn't use the  tags are displaying the disigned output and with the alerts. And designed output is not displayed when we use  related tags.
So my doubt here is, what is the exact use of "auto-escape" here?
and will this auto-escape works only with  tags?
Can someone please make my understanding clear about the auto-escape hint.

A: the auto-escape attribute by default is true and make an escape of html using the liferay class HtmlUtil.escape replacing the html tag with the html entity. There is comment in the source of HtmlUtil
    // Escape using XSS recommendations from
    // http://www.owasp.org/index.php/Cross_Site_Scripting
    // #How_to_Protect_Yourself


text:
Q: Session downloading from webclient or webbrowser(.NET) I am having an issue regarding downloading of pdf file from this page for example:
https://publicaccess.solihull.gov.uk/online-applications/applicationDetails.do?activeTab=documents&keyVal=OPQ691OEKGD00
You could see in that page there is an "Application Form" which the last column of it has a pdf link. I can already parse the link for pdf using HtmlAgilityPack but the problem is when I do this for the pdf link

            WebBrowser1.Navigate(docUrl)
            While (WebBrowser1.ReadyState <> WebBrowserReadyState.Complete)
                System.Windows.Forms.Application.DoEvents()
            End While
                Dim client As New WebClient
                client.Headers.Add(HttpRequestHeader.Cookie, WebBrowser1.Document.Cookie)
                client.DownloadFile(New Uri(pdfLink), "appForm.pdf")

It just return 404. This could be possibly a session based page though the pdf link is not changing. As for the headers, I see that WebBrowser1.Document.Cookie returns null even the page just finished loading. Is there any alternative that I can do for this?
Here is the pdf link by the way. You may try to directly open it without clicking the page to see the problem
https://publicaccess.solihull.gov.uk/online-applications/files/B30089CDFBE1BBCC3D0E7A598DEFEA61/pdf/PL_2017_01205_PPRM-APPLICATION_FORM_NO_PERSONAL_DATA-711302.pdf

A: This a cookie aware WebCLient. Credit goes to Pavel Savara.
public class WebClientEx : WebClient
{

    public WebClientEx() // Added to original code
    {
        this.container = new CookieContainer();
    }

    public WebClientEx(CookieContainer container)
    {
        this.container = container;
    }

    public CookieContainer CookieContainer
        {
            get { return container; }
            set { container= value; }
        }

    private CookieContainer container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest r = base.GetWebRequest(address);
        var request = r as HttpWebRequest;
        if (request != null)
        {
            request.CookieContainer = container;
        }
        return r;
    }

    protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
    {
        WebResponse response = base.GetWebResponse(request, result);
        ReadCookies(response);
        return response;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
        ReadCookies(response);
        return response;
    }

    private void ReadCookies(WebResponse r)
    {
        var response = r as HttpWebResponse;
        if (response != null)
        {
            CookieCollection cookies = response.Cookies;
            container.Add(cookies);
        }
    }
}


text:
Q: Getting Pyspark error of 'split' is not in list while calling split() function I have created a dataframe as following
spark= SparkSession.builder.appName("test").getOrCreate()
categories=spark.read.text("resources/textFile/categories")
categories.show(n=2)
+------------+
|       value|
+------------+
|1,2,Football|
|  2,2,Soccer|
+------------+
only showing top 2 rows

Now when I convert this data frame to RDD and try to split each line of RDD on the basis of "," (comma)
crdd=categories.rdd.map(lambda line: line.split(',')[1])
crdd.foreach(lambda lin : print(lin))

While addding the element at position 1 to the crdd RDD, I get following error
Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 13.0 failed 1 times, most recent failure: Lost task 0.0 in stage 13.0 (TID 13, localhost, executor driver): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "C:\Users\Downloads\bigdataSetup\spark-2.2.1-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\sql\types.py", line 1504, in __getattr__
    idx = self.__fields__.index(item)
ValueError: 'split' is not in list

Note : Data in CSV format here is just so that it can be easily reproduced.

A: since your data is in CSV format, you can use read.csv API:
categories=spark.read.csv("resources/textFile/categories")

modify your code as below:
crdd = categories.rdd.map(lambda line: line.value.split(',')[1])

for i in crdd.take(10): print (i)


text:
Q: Delete product from database(don't display in listview) using button placed in listview My problem is in title(I've been looking for an answer on stackoverflow, but no solution in my case). I've been trying to do it using setOnItemClickListener, but clicking on row in ListView does nothing. Also I've tried using myClick() - which is action when button is clicked, but here I don't know how to connect clicked button with row in database.
My activity with layout:
http://pastebin.com/6KLBm80Q
Database class + adapter + layout of listview row
http://pastebin.com/G2HufNgS

A: You must override getView() in your Adapter and set setOnClickListener() (and/or setOnLongClickListener()) for an item within your list item. That item will receive the clicks.


text:
Q: Multiple colored line of text on canvas This is more of a solution than a question. I figured this out and thought others like me might want to know.
I did find "Can I do by character text color in HTML5 Canvas?" when searching but I didn't want to use a "round about way" function.
That led me to gradients e.g. createLinearGradient. And I figured out how to hard block the colors so there was no gradient just two blocks of color. This is what I did:
var gradient = ctx.createLinearGradient(0, 0, 300, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(0.5, "red");
gradient.addColorStop(0.5, "blue");
gradient.addColorStop(1, "blue");
ctx.fillStyle = gradient;

This code allows text to look like this and also allows for multiple colors of text on one line of text. Check out this example: w3school example. Hope this helps.
Also, sorry if I'm not supposed to post solutions as questions.


text:
Q: Delete a matching pattern with sed I try to delete all occcurence of a word from my xml file. The pattern I would like to delete is something like below:
& lt;foo_bar>300</foo_bar& gt;

I am not familiar with sed, but I know it's feasible using it. I tried something like :
sed 's^&lt[foo_bar]>$g' myfile.xml

or
sed 's/^&lt[foo_bar]>$//' myfile.xml

both failed with an error message. So could you please help me how to figure out this? OS is Solaris 10 so most likely standart version is sed installed not GNU one. Please ignore space after & sign in the expression. There is no space in actual expression.
Thanks

A: At least, the way you are using character classes [foo_bar] is wrong. [foo_bar] can match one of f,o,b,a,r,_ only once. And you seem to have no attempt at matching /. The first expression you have lacks regex delimiters. sed will assume you are using ^ as the delimiter but then it lacks the corresponding delimiters as in s^find^replace^g.
This seems to work:
sed 's!<foo_bar>[^&]*</foo_bar>!!g' input

A: This might work for you (GNU sed):
sed -r 's/&\s*lt;(foo_bar&)gt;[0-9]+<\/\1\s*gt;//g' file


text:
Q: Why is removeClass not working properly? I'm trying to make some effects to work but I can't. I have a list of divs and I want 4 buttons.
1) Load more
2) Show less
3) Change max
4) Change min
I made a JSFiddle. I don't know why on JSFiddle the removeClass and addClass don't work because on my computer they work.
$(document).ready(function () {
    $('#changeMax').on('click', function(){
        $('li.col-md-3').addClass('fullwidth');
    });
    $('#changeMin').on('click', function(){
        $('li.col-md-3').removeClass('fullwidth');
    });
});

$(document).ready(function () {
    size_li = $(".row li").size();
    x=3;
    $('.row li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+4 : size_li;
        $('.row li:lt('+x+')').show("fast");
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 4 : x-4;
        $('.row li').not(':lt('+x+')').hide("fast");
    });
});

I will explain my problem from my computer. The first 3 buttons work with animation. The removeClass works but not with animation. I tried but it doesn't work.
Thanks

A: Because of specificity, other rules have a higher value
The rule .row li.col-md-3{ has a greater value than .fullwidth so the new width will not apply.
Change
.fullwidth{

to
.row li.fullwidth{

and it will start to work.

A: Just some css issues.
A quick fix is to use !important, but that is not always recommended.
.fullwidth{
    width: 100% !important;
    -webkit-transition: all 1s ease-in-out;
    -moz-transition: all 1s ease-in-out;
    -o-transition: all 1s ease-in-out;
    transition: all 1s ease-in-out;
}

A: This is showing that the fullwidth class is added:
$('#changeMax').on('click', function(){
        $('.row li.col-md-3').addClass('fullwidth');
        alert($('.row li.col-md-3')[0].className);
});


text:
Q: At what point during a typical request does the $wpdb object become available? I've wrote some custom SQL queries inside a class method and noticed they seem to work if I hook the method to the wp action. If I hook to the plugins_loaded action, they don't seem to work.
My question:
At what point during a typical request does the $wpdb object become available?
Refs:

*

*http://codex.wordpress.org/Plugin_API/Action_Reference

*http://codex.wordpress.org/Class_Reference/wpdb

A: Please, post your code because the problem is not the one you guessed.
Actually, $wpdb is available very early: it is inited by the function require_wp_db() located in the file wp_settings.php at line #79.
The hook 'plugins_loaded' is fired in the same wp_settings.php file, but at line #237, so pretty after $wpdb is available.


text:
Q: Find and delete subString in a String with delimiters (start: 55555, end: \n) I have this String:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim adminim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat 55555 Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.

In this string, there are three paragraphs, I need to find this subString: "55555" and delete from there to the next newline (end of the line). How could you do this?

A: You may choose the needed part of the whole string and split it by \n. Then change the paragraph that needs to be corrected.
String[] strings = string.split("\n");
strings[1] = strings[1].substring(0, strings[1].indexOf("55555"));

A: This is my solution:
String strings = string.substring(string.indexOf("55555"), string.indexOf("\n"));

A: I made a program that will hopefully solve your problem. Note that the program takes multi-line input, so you have to enter a comma (,) to end the input. It'll first take the main string as input and then ask for the word to remove from it. It's a simple program: doesn't use the substring() function or other techniques as you are not acquainted with.
class ProgramTest{

    public static void main(String[] args){

        java.util.Scanner sc=new java.util.Scanner(System.in);
        String str1="", str2="", a="", w="", mystr="";

        System.out.println("Enter your string. Enter ',' to terminate input.");

        while(!(a=sc.nextLine()).equals(","))
            str1 += a+"\n";

        System.out.println("Enter word to remove");

        str2 = sc.nextLine();

        for(int i=0;i<str1.length();i++){
            if(str1.charAt(i)!=' '){
                w+=str1.charAt(i);
            }
            else{
                if(!(w.equals(str2)))
                mystr += w+" ";
                w="";
            }
        }
        System.out.println("String after removing "+str2+" is \n"+mystr);
    }
}


text:
Q: How to select the closest descendant using jquery or selector? I want to get the descendant of a node that match class="foo".
The problem is : I don't know how deep this descendant will be.
I know I could get the immediate child using >
Or if I knew how deep it is, I could use multiple > > > >
I could just use class="foo" but then I'll get descendant of my target that also match class="foo".
Is div.class="foo":first-child the solution ?
div id="im_here"
  div id="child"
    ......
         div class="foo"              <= I want this
           ......
                div class="foo"       <= not that
                ......
                      div class="foo" <= not that
                      ......

A: You can use jQuery's :first selector in conjunction with .find():
$('#im_here').find('.foo:first')


text:
Q: Wrong Mixed Character Encoding in XML I have an automatically-generated XML file that is supposed to be encoded with UTF-8.  For the most part, the encoding is correct.  However, there are some few characters that are not encoded properly.  When viewing the file in Emacs, I get \370, \351.
Is there a way to detect their characters programatically?  I prefer solutions using PHP, but solutions in Perl or Java would be very helpful as well.

A: You can check for UTF-8-ness of a string with this regular expression:
(^(?:
[\x00-\x7f] |
[\xc0-\xdf][\x80-\xff] |
[\xe0-\xef][\x80-\xff]{2} |
[\xf0-\xf7][\x80-\xff]{3}
)*$)x

A: Are you absolutely certain that the encoding is incorrect? Rather than use emacs, I'd use a binary file viewer. What are the actual bytes at the problematic position?
With Java it would be reasonably easy to detect invalid UTF-8 byte patterns. I'm not sure whether the default Charset support would handle it, but UTF-8 is pretty simple. I usually use the UTF-8 table here as a reference for valid byte sequences.

A: You can use libxml_use_internal_errors and libxml_get_errors to loop through the errors that occurred when the document was loaded. The error code you're looking for is XML_ERR_INVALID_CHAR = 9.
<?php
$xml = '<?xml version="1.0" encoding="utf-8"?>

    ' . chr(0xfd) . chr(0xff) . '
';
libxml_use_internal_errors(true);

$doc = new DOMDocument;
$doc->loadxml($xml);

foreach (libxml_get_errors() as $error) {
    print_r($error);
}
libxml_clear_errors();

prints
LibXMLError Object
(
    [level] => 3
    [code] => 9
    [column] => 5
    [message] => Input is not proper UTF-8, indicate encoding !
Bytes: 0xFD 0xFF 0x3C 0x2F

    [file] =>
    [line] => 3
)


text:
Q: Is it possible to (conditionally) lookup from two different collections Let's suppose I have 3 schemas:
1. User:
const User = mongoose.model('users', {
    name: {
        type: String,
        required: true,
        trim: true
    }
}

*SuperUser:

const SuperUser= mongoose.model('superusers', {
    name: {
        type: String,
        required: true,
        trim: true
    }
}

*Messages:

const Message = mongoose.model('Message', {
    content: {
        type: String,
        required: true,
        trim: true
    },
    sender: {
        type: {
            type: mongoose.Schema.Types.String,
            required: true,
            enum : ['USER,'SUPER_USER'],
        },
        id: {
            type: mongoose.Types.ObjectId,
            required: true
        }
    }
})

I want to use the aggregation framework, to fetch (all) messages, and at the same time populate the nested sender object, inside the message with the data from the tables 'superusers' or 'users' (The columns of superusers and users are just an example).
Is it possible to 'conditionally lookup', meaning to lookup either the superusers or users, based on the type? I'm very new to the aggregate framework, so this may be an obvious solution.

A: Yes it is quite possible with mongoose what you are trying to achieve. You can use  refPath while defining the schema. And your enum should be the collection names i.e. User, SuperUser, and not the capital case.
const Message = mongoose.model('Message', {
    content: {
        type: String,
        required: true,
        trim: true
    },
    sender: {
        type: {
            type: mongoose.Schema.Types.String,
            required: true,
            enum : ['User','SuperUser'],
        },
        id: {
            type: mongoose.Types.ObjectId,
            required: true,
            refPath : "sender.type"
        }
    }
})

and then you can populate the documents like this:
Message.find({}).populate("sender.id");

Your sender will be available in sender.id
To simplify, you can simply store sender id in sender field, and store senderType separately, so that you don't have to use sender.id for the sender document, and its much cleaner.
const Message = mongoose.model('Message', {
    content: {
        type: String,
        required: true,
        trim: true
    },
    sender: {
        type: mongoose.Types.ObjectId,
        required: true,
        refPath : "senderType"
    },
    senderType: {
        type: mongoose.Schema.Types.String,
        required: true,
        enum : ['User,'SuperUser'],
    }
})

And now you can populate the documents like this:
Message.find({}).populate("sender");

Your sender document/object will be available in sender field
For detailed information, read Mongoose documentation on dynamic-ref


text:
Q: Building capybara-webkit on Windows 7 I'm trying to use capybara-webkit on Windows 7 and am having problems.  I'm trying to follow the instructions here but am having problems.  Specifically I'm having issues building from source.  The following is a small extract of the very large output from building.
This first output is from where the error is happening.
g++ -c -pipe -g -frtti -fexceptions -mthreads -Wall -Wextra -DUNICODE -DQT_LARGEFILE_SUPPORT -DQT_DLL -DQT_WEBKIT_LIB -DQT_GUI_LIB -DQT_NETWORK_LIB -D QT_CORE_LIB -DQT_HAVE_MMX -DQT_HAVE_3DNOW -DQT_HAVE_SSE -DQT_HAVE_MMXEXT -DQT_HAVE_SSE2 -DQT_THREAD_SUPPORT -I'c:/Qt/4.8.4/include/QtCore' -I'c:/Qt/4.8.4/include/QtNetwork' -I'c:/Qt/4.8.4/include/QtGui' -I'c:/Qt/4.8.4/include/QtWebKit' -I'c:/Qt/4.8.4/include' -I'c:/Qt/4.8.4/include/ActiveQt' -I'debug' -I'c:/Qt/4.8.4/mkspecs/win32-g++' -o debug/qrc_webkit_server.o debug/qrc_webkit_server.cpp
g++ -Wl,-subsystem,console -mthreads -o debug/webkit_server.exe object_script.webkit_server.Debug  -L'c:/Qt/4.8.4/lib' -lQtWebKitd4 -lQtGuid4 -lQtNetworkd4 -lQtCored4
./debug/Version.o: In function `ZN7Version5startEv':
c:\MyRailsProject\capybara-webkit\src/Version.cpp:11: undefined reference to `_imp___Z14qWebKitVersionv'
./debug/Version.o: In function `ZN7QStringpLERKS_':
c:/Qt/4.8.4/include/QtCore/../../src/corelib/tools/qstring.h:274: undefined reference to `_imp___ZN7QString6appendERKS_'
./debug/Version.o: In function `QString':
c:/Qt/4.8.4/include/QtCore/../../src/corelib/tools/qstring.h:419: undefined reference to `_imp___ZN7QString16fromAscii_helperEPKci'

This is from the very end of the very long output chain
collect2: ld returned 1 exit status
make[2]: *** [debug/webkit_server.exe] Error 1
make[2]: Leaving directory `/c/MyRailsProject/capybara-webkit/src'
make[1]: *** [debug] Error 2
make[1]: Leaving directory `/c/MyRailsProject/capybara-webkit/src'
make: *** [sub-src-webkit_server-pro-make_default-ordered] Error 2
Command 'make' failed

Does anyone know what I'm doing wrong and how to correctly compile capybara-webkit?

A: I actually solved this by getting the correct version of QT.  I had originally downloaded the Visual Studios 2008 version, but after changing to the MingGW version everything works as expected.


text:
Q: How to add a context menu to an empty tableview's header row? I have a TableView. If it has columns, I can add context menus to the columns, and the menu will appear when I right click on the column header.
How do I add a context menu to the blank bar that appears for an empty table? Screenshot:

A: This can be done by accessing the internal structure of the TableView directly, I'm unaware of any official API to do this.
The official TableView CSS names a class of column-header-background which we can then access via the Node#lookup() method.
An example
public class ContextMenuOnTableHeader extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        TableView<String> table = new TableView<>();
        Scene scene = new Scene(table);
        primaryStage.setScene(scene);
        primaryStage.setWidth(200);
        primaryStage.setHeight(200);

        primaryStage.show();

        Node header = table.lookup(".column-header-background");
        header.setOnContextMenuRequested(event -> {
            ContextMenu menu = new ContextMenu();
            menu.getItems().add(new MenuItem("Mr Horse"));
            menu.show(header, event.getScreenX(), event.getScreenY());
        });
    }

}


text:
Q: Cloud point shader with assigned colors map from model I'm working on a project using threejs to make a 3D environment to navigate in space.I integrated my environment as GLTF object and instanced a sphere on its surface of it.Now I would use the texture to assign colors to each instance. I think using a shader would be the most performant method!
Does someone have a clue on how to make it?
here is an image of the concept i would recreate
enter image description here
here is the basic point were I'm stuck
// create the model that the points will be placed on
const model = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshBasicMaterial({
        color: 0x00ff00
    })
);
scene.add(model);

// create the instanced geometry to hold the points

const geometry = new THREE.InstancedBufferGeometry();

// set the attributes for the points (such as position, color, etc.)
const positions = [];
const colors = [];
const modelViewMatrices = [];
const projectionMatrices = [];
for (let i = 0; i < 100; i++) {
    positions.push(Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1);
    colors.push(Math.random(), Math.random(), Math.random());
    modelViewMatrices.push(camera.matrixWorldInverse.elements);
    projectionMatrices.push(camera.projectionMatrix.elements);
}
const positionAttribute = new THREE.Float32BufferAttribute(positions, 3);
geometry.setAttribute('position', positionAttribute);
const colorAttribute = new THREE.Float32BufferAttribute(colors, 3);
geometry.setAttribute('color', colorAttribute);
const modelViewMatrixAttribute = new THREE.InstancedBufferAttribute(new Float32Array(modelViewMatrices.flat()), 4);
geometry.setAttribute('modelViewMatrix', modelViewMatrixAttribute);
const projectionMatrixAttribute = new THREE.InstancedBufferAttribute(new Float32Array(projectionMatrices.flat()), 4);
geometry.setAttribute('projectionMatrix', projectionMatrixAttribute);

// create the material for the points,using the modelViewMatrix and projectionMatrix attributes in the shader
const material = new THREE.ShaderMaterial({
    uniforms: {},
    attributes: {
        modelViewMatrix: { value: null },
        projectionMatrix: { value: null }
    },
    vertexShader: `
        attribute vec3 pointPosition;
        attribute vec3 color;
        attribute mat4 modelViewMatrix;
        attribute mat4 projectionMatrix;
        varying vec3 vColor;
        void main() {
            vColor = color;
            gl_Position = projectionMatrix * modelViewMatrix * vec4(pointPosition, 1.0);
        }
    `,
    fragmentShader: `
        varying vec3 vColor;
        void main() {
            gl_FragColor = vec4(vColor, 1.0);
        }
    `
});

// create the mesh to hold the points and add it to the scene
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

// set the number of instances (points) to render
geometry.setDrawRange(positions.length / 3);

// animate the scene
const animate = function () {
    requestAnimationFrame(animate);

    // update the modelViewMatrix and projectionMatrix uniforms
    material.uniforms.modelViewMatrix.value = camera.matrixWorldInverse;
    material.uniforms.projectionMatrix.value = camera.projectionMatrix;

    renderer.render(scene, camera);
};
animate();


text:
Q: How to read wire wrap labels? This image is an example of a wire wrap label that lists multiple AWG numbers.
What does it mean? How could it be anything but a single specific gauge?

A: The part number (P/N B-30-1000) indicates it is AWG30 (and black and 305m = 1000').
The part number is printed onto a pre-printed 2-color label which contains the UL specification numbers and well as the brand. UL is "a global safety consulting and certification company headquartered in Northbrook, Illinois. It maintains offices in 46 countries."
The relevant UL specification number in this case is UL1423 since it's AWG30. The standard is "Appliance Wiring Material UL 758".
That tells you (follow the link) that it's 105°C Polyvinylidene Fluoride (PVDF) Resin Insulated Wire, and provides some test parameters.


text:
Q: Form not submitting on ENTER when no type="submit" element present We're using custom buttons to submit forms. A click event is assigned to .btn-submit's to submit the respective form. However, without some type of <button type="submit"> or <input type="submit"> element located within the <form>, pressing ENTER in either the username or password text field does not submit the form.
How do I still allow users to submit a form when pressing ENTER in an input field without a type="submit" element present in the <form>?
HTML
<form action="post.php" method="post">

Username <input type="text" name="username" style="width: 300px; font-size: 18px">

Password <input type="password" name="password" style="width: 300px; font-size: 18px">

<input type="hidden" name="user_login" value="1">

Log In

</form>

JS
$(document).ready(function()
{
    $('.btn-submit').on('click', function(e)
    {
        $(this).parents('form:first').submit();
    });
});

A: you could do something like this to make it so when the enter key is pressed within the input it activates the submit button
$('form').keypress(function(e){
    var code = e.keyCode || e.which;

    if( code === 13 ) {
        e.preventDefault();
        $( ".btn-submit" ).click();
    };
});

EDIT
This wont cause the submit button to be clicked if return is pressed in the textarea it will only do that for inputs of the type text now.
$('input:text').keypress(function(e){
    var code = e.keyCode || e.which;

    if( code === 13 ) {
        e.preventDefault();
        $( ".btn-submit" ).click();
    };
});

A: You need to capture the enter key press, preferably using jQuery delegates on the form.   Just target your delegate at the form and looking at input elements, or body looking at form, I suppose. Essentially it's saying "look at this top element, trigger X action on the inner element".   Your parent would be form, inner input, action is keydown or keyup
See this :
jQuery delegate method not working for keydown and keypress
Then in the function test for what keypress was hit.   If enter, submit.  If not, return false.
PS:  when I'm not on mobile, I can do a code snippet for you.

A: And here is why:

The submit event is sent to an element when the user is attempting to
  submit a form. It can only be attached to <form> elements. Forms can
  be submitted either by clicking an explicit <input type="submit">,
  <input type="image">, or <button type="submit">, or by pressing Enter
  when certain form elements have focus.
Depending on the browser, the Enter key may only cause a form
  submission if the form has exactly one text field, or only when there
  is a submit button present. The interface should not rely on a
  particular behavior for this key unless the issue is forced by
  observing the keypress event for presses of the Enter key.

Source: http://api.jquery.com/submit/


text:
Q: How to check if an entered value is 10 javascript? I want to check if an entered value is 10 or not(and if the value is 10, I want the result to be sent to "send.php"). What am I doing wrong?
<?php  $cod1=rand(0, 10);
    $cod2=10-$cod1; ?>
    <form action='send.php'  method='post' onsubmit='f1(this)'>
    Please enter the value of <br> <?php echo $cod1 ?> + <?php echo $cod2 ?> in the following box
    <input type="text" name="xrezultat" id="xrezultat" class="box" size="32"/>

    <input name="Submit1" type="submit" class="butt" value="Trimiteti">
    <input name="Submit2" type="reset" class="butt" value="Stergeti ">

    </form>

    <Script>
    function f1(input)
    {
    if(document.getElementById("xrezultat").value!=10)
    aux==false;

     if (aux == true)
    {
       return true;
    }

       else
    {
        alert ( "Please enter the correct value" );
        return false;
                 }

    }
    </script>

A: aux==false; checks to see if aux is equal to false, it does not assign to it.
It should read aux=false;.

A: Try using parseInt.
var numberValue = parseInt(document.getElementById("xrezultat").value, 10);


text:
Q: PHP user permission check Just wondering for user permission check,
Should you keep the permission in the session
eg. select out the user info and store the permission id in the session
or doing a permission check against the database everything time before you doing a query?

A: I fetch the data from the database every time, so when I change permissions, the user gets updated instantly instead of the next login.
Many people would assume there may be a performance penalty. But if you use MySQL like most PHP users, results will be held in a query cache in RAM and will be available in almost no time.

A: It depends on the security level of your website. If you think security is really important for your website and you want security changes to be made on user as soon as they're changed, you have to use database calls. However, if your permission system is designed this way, it can become quite slow and inefficient.
If security can "wait" for the next session then I think it's better to save permissions in the session to avoid a loss of performance.

A: This is a great use case for memcache. You could store user permissions in a database, pull them down once and cache them. Subsequent page loads would fetch from memcache.
When an administrator changes a user's permission, that action can simply invalidate (delete) the cache key. Then, the next time you fetch from cache it won't be there and you'll know to hit the database again.

A: In an application, data that is not available, should not be available. How you establish this simple procedure is up to you and depends a lot how you structure your application.
For example, you allow data-access with the database credentials you share across your whole application probably within it's configuration values.
Assuming you do this: If you have not a problem with that, why are you concerned about a much more detailed case that much?


text:
Q: Match a string which doesn't start with string I'm trying to usa a regex which only matches string which doesn't start with some other string. As far as I know and from some other questions here on Stack Overflow I should use a negative look-ahead assertion. But for some reason it doesn't seem to work. Consider the following three strings:
/match.jpg
match.png
excludedpath/no-match.gif

I want my regex pattern to only match the first two strings, because the last string starts with excludepath/. What I have tried is the following:
(?!excludedpath\/)(.*)\.(gif|jpg|png)$

I want to use this regex pattern in a rewrite rule for Apache. Basically I want to simply load all images (with those three extensions) unless they are in the format of http://example.com/excludedpath/some-image.jpg:
RewriteCond %{REQUEST_FILENAME} (?!excludedpath\/)(.*)\.(gif|jpg|png)$
RewriteRule ^(.*)$ $1 [L]

RewriteCond "/my/path/to/application/%{REQUEST_URI}" !-f
RewriteRule ^(.*)$ /index.php/$1 [L]

Anybody can tell me why it still matches all three strings: This Link and how to fix it?

A: It's because you don't require the lookahead to look at the beginning of your string. Just add another anchor:
^(?!excludedpath\/)(.*)\.(gif|jpg|png)$

Otherwise, the engine will of course fail to match at the first character (because the lookahead kicks in), but then it will gladly try to match from the second character. And of course xcludedpath... does not set off the negative lookahead.
Since your rubular example has the last string start with a slash, you could add an optional slash to the lookahead, if you want to exclude both variants:
^(?!\/?excludedpath\/)(.*)\.(gif|jpg|png)$


text:
Q: Prepare an activity before show The problem is only when my activity already shown it begins updates and it look no good. How it works: in onStart of activity I send cmd to service to get update data, also I register brodcast listener there. I want to prepare received data from service to show before activity appears. How to do that? Thanks.
How it works now: when I back from another activity first I see old data and then it changes (very fast but you can see it) to new.

A: if you want to setup things before your activity is shown you need to do things in the onCreate method instead of onStart method.
further informations in android documentation

A: When you send the command to the service to update your data, you should change the views in your Activity to show loading indicators, or a blank view, or whatever you want the user to see until the Broadcast comes in that your new data is ready. Then you shouldn't need to worry about old data being visible.


text:
Q: Split String by Upper Case Consisting of Both Latin and Unicode Building on the Splitting String based on letters case answer;
lang <- "DeutschEsperantoItalianoNederlandsNedersaksiesNorskРусский"
strsplit(lang, "(?!^)(?=[[:upper:]])", perl = T)

results in
"Deutsch"      "Esperanto"    "Italiano"     "Nederlands"   "Nedersaksies" "NorskРусский"

The problem is the last pair is not separated as Russian is converted to UTF-8 (there will be more variation in the strings; e.g. more or less all other languages in Wikipedia). I checked online Regex testers and other SO answers but they are not much help with R. Tried iconv and Encoding workarounds in base R as well (can't seem to convert to UTF-16; conversion to bytes doesn't help). Thoughts?

A: Use unicode property \p{Lu} that means an uppercase (u) letter (L) in any alphabet. See http://www.regular-expressions.info/unicode.html
lang <- "DeutschEsperantoItalianoNederlandsNedersaksiesNorskРусский"
strsplit(lang, "(?!^)(?=\p{Lu})", perl = TRUE)


text:
Q: How to Pass Different Build Arguments to Projects of one Solution Background: We've got a single .NET solution which contains multiple projects, some of them are compiled against the .NET Framework, some against .NET Core (UWP). We use Visual Studio Team Services (was Visual Studio Online) to build our solution continuously.
Challenge: The UWP projects require different MSBuild arguments and platform settings. We created a build definition as per screenshot below: the solution is built first using the .NET arguments. Then, for every UWP project, we have an MSBuild step.
Problem: Every time we add, remove, or rename a UWP project we have to update the build definition. We would like to somehow select the UWP projects automatically, ideally using a Visual Studio Build Step and no custom scripting. Any ideas?

Working alternative: Originally, we split the solution into two (one solution per platform) and had two different Visual Studio Build events running against each solution. We prefer to work in one single solution though.

A: There isn't any easy way to achieve this without custom script.
You may trying creating a MSBuild project file and add your projects in it with separate arguments like following:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Build">
    <MSBuild Projects="Project1.csproj" Properties=Arguments1/>
    <MSBuild Projects="Project2.csproj" Properties=Arguments2/>
</Target>
</Project>

Then you just need to build the project file in your build definition. But this will require you to update the MSProject file when you have project added/changed.

A: The Msbuild step supports wildcards, so you could set it to build **/*.uwp.csproj if your projects follow this naming pattern.


text:
Q: Linux : Disabling File cache for a process? Is there a way to disable file cache for a particular process ?
I have two process running A and B.
I want file opened by A to remain in cache.
and
I don't want to enable file cache for B so It doesn't replace the file cached by process in the memory.
Is there a way to disable file cache for a particular process?

A: None that I know of... the only option are global/device-specific:

*

*using -sync option with mount

*using drop_caches
Another point:
Even IF you could do what you ask for there is no guarantee that any other processes (C, D, E etc.) behaves in a way that "the file cached by process A in the memory" gets replaced...
UPDATE - after comments from OP ragarding performance:
Linux offers (as most modern OS) something called "memory-mapped file" - basically this is a way to access the file's contents in-memory... the OS assigns the file (depending on the given params) part of the address space and loads the content of the file into that address space (again: exact behaviour depends on the given params).
You would do this in Process A to achieve what you want...
Checkout the mmap API calls for details.

A: Process B could use fadvise() to direct the kernel to not cache data read from a given file descriptor.


text:
Q: How To Output CountryName Appropriately? I am trying to display the Username, LastName, JoinDate and CountryName for all the users who joined after the 13th January 2017 in ascending order.
I'm struggling to understand what type of join I should use and how to connect the two tables together, If you have any ideas or more knowledge than I do, please let me know.
An attempt of my code is below:

SELECT DISTINCT
"Username",
"LastName",
"JoinDate",
"CountryId"
FROM BR_USER, BR_COUNTRY
WHERE "JoinDate" > '01-JAN-17'
LEFT JOIN BR_USER ON BR_USER."CountryId" = BR_COUNTRY."CountryId"
GROUP BY BR_USER."CountryId"
ORDER BY "JoinDate" ASC;

How the two tables are created below:

A: JOIN is an operator in the FROM clause.  The WHERE clause follows the FROM clause:
SELECT u."Username", u."LastName", u."JoinDate", u."CountryId"
FROM BR_USER u JOIN
     BR_COUNTRY c
     ON u."CountryId" = c."CountryId"
WHERE u."JoinDate" > DATE '2017-01-01'
ORDER BY u."JoinDate" ASC;

When I write SQL statements, you will note that the clauses are aligned on the left and operators tend to be at the end of a row.  This format is consistent in the SELECT, FROM and WHERE clause.
Notes:

*

*Aggregation does not seem necessary.  I don't see why users would be duplicated in a table called BR_USERS.

*The JOIN seems utterly superfluous, given that you are not using any columns from BR_COUNTRY.

*I assume that all CountryIds are correct in BR_USER.  If not, use a LEFT JOIN.

*Learn to use the DATE keyword followed by YYYY-MM-DD.  This is a safer way to provide date constants.

*Table aliases make the query easier to write and read, particularly with escaped column and table names.

*Qualify all column references.

A: You can simply use:
 SELECT bru.username,
               bru.lastname,
               bru.joindate,
               bru.countryid
 from br_user bru join br_country brc
 on bru.countryid = brc.countryid
where bru.joindate > DATE '2017-01-01'
order by bru.joindate asc;

As always, try to make a english statement of the problem.
For example: i need all the users even if they dont have countryid and who joined after 1st Jan 2017.
Also, please take care of boundary conditions whether or not to include 1st Jan 217.


text:
Q: static field initialization using AST I need to create a static String variable with a default value (e.g. public static final String COUNTRY="INDIA";) using Eclipse AST. I'm able to create such a varibale using SingleVariableDecleration or FieldDecleration. But I'm not sure how to initialize the same using AST.
This is what I could implement==>
public static final String COUNTRY;
This is what I could not implement==>
public static final String COUNTRY*="INDIA";*
Please help me to know how can I do this. Thanks in advance,
Shyam

A: First create a VariableDeclarationFragment in which you can specify the initializer. Then use this fragment to set FieldDeclaration.FRAGMENTS_PROPERTY.
You should use the AST View plugin to visualize the AST of Java source, this helps in creating the AST nodes for given source by hand which is what you are trying to do.


text:
Q: Unexpected memcmp return value I made a INI file parser, it works well on Windows but not with Linux, the problem comes from the memcmp function, it doesn't return 0 when it should, I already checked with printf and strlen, (I also tried to use strncmp instead, it returned different value but still different than 0) but couldn't find where the problem comes from.
Here is the code :

#define INI_KEY_LENGTH   128
#define BEGIN        '['
#define SEP          '='
#define COMMENT      ';'

static char configfilename[255];

static char * str_dup (const char * str){
    char * dup = NULL;

    if (str != NULL){
        size_t size = strlen (str) + 1;
        dup = malloc (size);
        if (dup != NULL){
            memcpy (dup, str, size);
        }
    }
    return dup;
}

static void str_finalize (char * str){
    char * p = strchr (str, '\n');

    if (p != NULL){
        *p = '\0';
    }
}

static char * get (const char * filename, const char * section, const char * key){
    char *   ret         = NULL;
    char     buff        [INI_KEY_LENGTH];
    FILE *   file        = NULL;
    int      opened      = 0;

    file = fopen (filename, "r");
    if (file != NULL){
        while ((fgets (buff, INI_KEY_LENGTH, file)) != NULL){
            str_finalize (buff);
            if (! opened && buff [0] == BEGIN){
                char * p = buff;
                // Don't work here
                if (memcmp (p + 1, section, strlen (buff) - 2) == 0){
                    opened = 1;
                    continue;
                }
            }
            else if (opened){
                if (buff [0] == BEGIN){
                    opened = 0;
                    break;
                }
                if(buff [0] != COMMENT){
                    if (strstr (buff, key) != NULL){
                        char * p = strchr (buff, SEP);

                        if (p != NULL){
                            p++;
                            ret = str_dup (p);

                            break;
                        }
                    }
                }
            }
        }
        fclose (file);
    }
    return ret;
}

int init_iniFile (const char * filename){
    int ret = 0;
    FILE * file;

    if ((file = fopen(filename, "r")) != NULL){
        fclose(file);
        strcpy(configfilename, filename);
        ret = 1;
    }
    return ret;
}

char * get_string (const char * section, const char * key){
    return get (configfilename, section, key);
}

I suspect the error to be stupid, but I'm a noob in C, sorry for the inconvenience.

A: Seeing this hack:
... strlen(buff) - 2)

along with reading "works on windows and doesn't on Linux" my senses tell me the code stumbles over the fact that windows new-lines are \r\n and Linux new-lines are \n , that is on windows they are 2 chars and one char long on Linux.
My advise to get around this is to add some (perhaps platform specific) code to get rid of any new-lines before working with "the rest" of the line read.
Some code showing how the might be done is here: https://stackoverflow.com/a/16000784/694576
Adding a general advise: If you trap yourself writing strlen(..) - x with x possibly being a positive value always think twice if this is really what you need, as this is a way into desaster if the result of this substraction ever becomes negativ, especially if you are using (as you ought to) size_t as the result type. It will underflow then. And as such construct typically is used to later index another string, this will happend with a BIG number ... - the rest is "bleeding" history.

A: IMHO There is too much operation for one line, try to split it and check
if (memcmp (p + 1, section, strlen (buff) - 2) == 0)

to
char *lefthand = p + 1;
size_t comaprecnt = strlen (buff) - 2;
if ( memcmp(lefthand, section, comparecnt) == 0) {...


text:
Q: Generating excel clears viewbag/tempdata I am trying to generate excel with following code
        public void GenerateExcel(string reportName, DataTable dt)
        {

            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.Buffer = true;
            Response.ContentType = "application/ms-excel";
            Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
            Response.AddHeader("Content-Disposition", "attachment;filename= " + reportName + ".xls");
            Response.Charset = "utf-8";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");

            StringWriter ws = new StringWriter();

            ws.Write("");
            //       ws.Write("

");
            //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
            ws.Write("
");

            string strBoldCell = "{0}	";
            string strRedCell = "{0}	";
            string strCell = "{0}	";
            string strColSpan = "{1}	";

            int r;
            int c;

            if (dt.Rows.Count > 0)
            {
                try
                {
                    ws.Write("
");
                    for (c = 0; c < dt.Columns.Count; c++)
                    {
                        ws.Write(string.Format(strBoldCell, dt.Columns[c].ColumnName).Replace("_", ""));
                    }
                    ws.Write("
");
                    ws.Write("\n");

                    for (r = 0; r < dt.Rows.Count; r++)
                    {

                        ws.Write("
");
                        for (c = 0; c < dt.Columns.Count; c++)
                        {
                            if (string.IsNullOrEmpty(dt.Rows[r][dt.Columns[c].ColumnName].ToString()) == false)
                            {

                                if (dt.Rows[r]["Comment"].ToString() != null && dt.Rows[r]["Comment"].ToString() != "")
                                {
                                    ws.Write(string.Format(strRedCell, dt.Rows[r][dt.Columns[c].ColumnName].ToString().Replace('_', ' ')));
                                }
                                else
                                {
                                    ws.Write(string.Format(strCell, dt.Rows[r][dt.Columns[c].ColumnName].ToString().Replace('_', ' ')));
                                }
                            }
                            else
                            {
                                if (dt.Rows[r]["Comment"].ToString() != null && dt.Rows[r]["Comment"].ToString() != "")
                                {
                                    ws.Write(string.Format(strRedCell, " "));
                                }
                                else
                                {
                                    ws.Write(string.Format(strCell, " "));
                                }
                            }

                        }
                        ws.Write("
");
                        ws.Write("\n");
                    }

                }
                catch (Exception ex)
                {

                    throw ex;
                }

            }

            else
            {
                ws.Write("
");
                ws.Write(string.Format(strColSpan, 10, "No records found"));
                ws.Write("
");
            }

            ws.Write("
");
            ws.Write("");

            Response.Write(ws.ToString());
            Response.Flush();
            Response.End();

        }

by calling above method in main method as follows
                if (Cnt != 0)
                {
                    TempData["Error"] = "There were issues with the Excel Import: Total Records: " + result.Rows.Count+" Error Row Count: "+Cnt;
                }
                else
                {
                    TempData["Error"] = "No error found in given excel: Total Records: " + result.Rows.Count;
                }
                GenerateExcel("OutputFile" + DateTime.Now.ToString("MMddyyyyhhmmss"), result);
                return View();

also trying to pass Tempdata to view but the problem is excel is generating successfully but tempdata does not showing anything in view.
if i comment the code of calling GenerateExcel method tempdata is perfectly showing on view..why this is happening?

A: Please Try moving calling function before setting tempdata like:
GenerateExcel("OutputFile" + DateTime.Now.ToString("MMddyyyyhhmmss"), result);
if (Cnt != 0)
            {
                TempData["Error"] = "There were issues with the Excel Import: Total Records: " + result.Rows.Count+" Error Row Count: "+Cnt;
            }
            else
            {
                TempData["Error"] = "No error found in given excel: Total Records: " + result.Rows.Count;
            }
            return View();


text:
Q: Creating an API proxy using HAProxy and getting responses I have an issue where an API vendor requires a static IP to connect to it and I do not have the ability to configure a static IP for the requests, so I am looking at using HAProxy as my gateway/proxy to the API.
It was very easy to configure HAProxy in a basic form and have it proxy my requests, but I'm finding that some requests return no response while others do.
The API requests will use PUT, POST and GET methods. My config is very similar to default. I'm using HAProxy 1.8.
Two questions;
Is HAProxy the right tool for this? Will anything else work? I'm even happy to pay for a commercial tool that does the job.
If it is the right tool, is there any reason why some GET requests return responses and some dont? The response code is still 200 but I have no access to logs on the API vendor side to troubleshoot.
#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    local2.*                       /var/log/haproxy.log
    #
    #log         127.0.0.1 local2
    log         127.0.0.1:514  local0
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000
    log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %CC %CS %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq %hr %hs %{+Q}r"

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
#frontend  main *:5000
#    acl url_static       path_beg       -i /static /images /javascript /stylesheets
#    acl url_static       path_end       -i .jpg .gif .png .css .js
#
#    use_backend static          if url_static
#    default_backend             app

frontend api_proxy
    bind *:6109
    mode http
    # capture response header
    default_backend remote_api_server

backend remote_api_server
    #replace 10.10.10.10 with the actual Ip address
    mode http
    http-request set-header Host myhost.com.au
    server server1 myhost.com.au:443 ssl verify none
#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
#backend static
#    balance     roundrobin
#    server      static 127.0.0.1:4331 check

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
#backend app
#    balance     roundrobin
#    server  app1 127.0.0.1:5001 check
#    server  app2 127.0.0.1:5002 check
#    server  app3 127.0.0.1:5003 check
#    server  app4 127.0.0.1:5004 check

A: So, the use of HAProxy continued to not behave the way I expected so I tried doing what I needed in nginx and it was so easy.
Ultimately, this block does exactly what I need.
server {
    listen      6109;

    location / {
        proxy_redirect          off;
        proxy_pass_header       Server;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Scheme $scheme;
        proxy_set_header        Host myhost.com.au;
        proxy_set_header        X-NginX-Proxy true;
        proxy_connect_timeout   5;
        proxy_read_timeout      240;
        proxy_intercept_errors  on;

        proxy_pass              https://myhost.com.au:443;
    }
}

This is on an EC2 instance so I have a load balancer in front of it handling SSL.


text:
Q: Flutter error: Could not download bundletool.jar (com.android.tools.build:bundletool:0.9.0) pls how can I resolve this flutter error
What went wrong:
A problem occurred configuring project ':flutter_udid'.
Could not resolve all artifacts for configuration ':flutter_udid:classpath'.
   Could not download bundletool.jar (com.android.tools.build:bundletool:0.9.0)
      Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/bundletool/0.9.0/bundletool-0.9.0.jar'.
         Read timed out
   Could not download kotlin-stdlib.jar (org.jetbrains.kotlin:kotlin-stdlib:1.3.50)
      Could not get resource 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-stdlib/1.3.50/kotlin-stdlib-1.3.50.jar'.
         Could not GET 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-stdlib/1.3.50/kotlin-stdlib-1.3.50.jar'.
            Remote host closed connection during handshake
   Could not download gradle-download-task.jar (de.undercouch:gradle-download-task:3.4.3)
      Could not get resource 'https://jcenter.bintray.com/de/undercouch/gradle-download-task/3.4.3/gradle-download-task-3.4.3.jar'.
         Could not GET 'https://jcenter.bintray.com/de/undercouch/gradle-download-task/3.4.3/gradle-download-task-3.4.3.jar'.
            jcenter.bintray.com: Temporary failure in name resolution
   Could not download httpmime.jar (org.apache.httpcomponents:httpmime:4.5.6)
      Could not get resource 'https://jcenter.bintray.com/org/apache/httpcomponents/httpmime/4.5.6/httpmime-4.5.6.jar'.
         Could not GET 'https://jcenter.bintray.com/org/apache/httpcomponents/httpmime/4.5.6/httpmime-4.5.6.jar'.
            jcenter.bintray.com
   Could not download httpclient.jar (org.apache.httpcomponents:httpclient:4.5.6)
      Could not get resource 'https://jcenter.bintray.com/org/apache/httpcomponents/httpclient/4.5.6/httpclient-4.5.6.jar'.
         Could not GET 'https://jcenter.bintray.com/org/apache/httpcomponents/httpclient/4.5.6/httpclient-4.5.6.jar'.
            jcenter.bintray.com
   Could not download httpcore.jar (org.apache.httpcomponents:httpcore:4.4.10)
      Could not get resource 'https://jcenter.bintray.com/org/apache/httpcomponents/httpcore/4.4.10/httpcore-4.4.10.jar'.
         Could not GET 'https://jcenter.bintray.com/org/apache/httpcomponents/httpcore/4.4.10/httpcore-4.4.10.jar'.
            jcenter.bintray.com
   Could not download error_prone_annotations.jar (com.google.errorprone:error_prone_annotations:2.3.1)
      Could not get resource 'https://jcenter.bintray.com/com/google/errorprone/error_prone_annotations/2.3.1/error_prone_annotations-2.3.1.jar'.
         Could not GET 'https://jcenter.bintray.com/com/google/errorprone/error_prone_annotations/2.3.1/error_prone_annotations-2.3.1.jar'.
            jcenter.bintray.com
   Could not download kotlin-script-runtime.jar (org.jetbrains.kotlin:kotlin-script-runtime:1.3.50)
      Could not get resource 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-script-runtime/1.3.50/kotlin-script-runtime-1.3.50.jar'.
         Could not GET 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-script-runtime/1.3.50/kotlin-script-runtime-1.3.50.jar'.
            jcenter.bintray.com
   Could not download kotlin-daemon-embeddable.jar (org.jetbrains.kotlin:kotlin-daemon-embeddable:1.3.50)
      Could not get resource 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-daemon-embeddable/1.3.50/kotlin-daemon-embeddable-1.3.50.jar'.
         Could not GET 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-daemon-embeddable/1.3.50/kotlin-daemon-embeddable-1.3.50.jar'.
            jcenter.bintray.com
   Could not download trove4j.jar (org.jetbrains.intellij.deps:trove4j:1.0.20181211)
      Could not get resource 'https://jcenter.bintray.com/org/jetbrains/intellij/deps/trove4j/1.0.20181211/trove4j-1.0.20181211.jar'.
         Could not GET 'https://jcenter.bintray.com/org/jetbrains/intellij/deps/trove4j/1.0.20181211/trove4j-1.0.20181211.jar'.
            jcenter.bintray.com
   Could not download kotlin-build-common.jar (org.jetbrains.kotlin:kotlin-build-common:1.3.50)
      Could not get resource 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-build-common/1.3.50/kotlin-build-common-1.3.50.jar'.
         Could not GET 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-build-common/1.3.50/kotlin-build-common-1.3.50.jar'.
            jcenter.bintray.com
   Could not download kotlinx-coroutines-core.jar (org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1)
      Could not get resource 'https://jcenter.bintray.com/org/jetbrains/kotlinx/kotlinx-coroutines-core/1.1.1/kotlinx-coroutines-core-1.1.1.jar'.
         Could not GET 'https://jcenter.bintray.com/org/jetbrains/kotlinx/kotlinx-coroutines-core/1.1.1/kotlinx-coroutines-core-1.1.1.jar'.
            jcenter.bintray.com
   Could not download kotlin-stdlib-common.jar (org.jetbrains.kotlin:kotlin-stdlib-common:1.3.50)
      Could not get resource 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-stdlib-common/1.3.50/kotlin-stdlib-common-1.3.50.jar'.
         Could not GET 'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-stdlib-common/1.3.50/kotlin-stdlib-common-1.3.50.jar'.
            jcenter.bintray.com
   Could not download trove4j.jar (org.jetbrains.trove4j:trove4j:20160824)
       Could not get resource 'https://jcenter.bintray.com/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar'.
        Could not GET 'https://jcenter.bintray.com/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar'.
            jcenter.bintray.com
   Could not download commons-codec.jar (commons-codec:commons-codec:1.10)
      Could not get resource 'https://jcenter.bintray.com/commons-codec/commons-codec/1.10/commons-codec-1.10.jar'.
         > Could not GET 'https://jcenter.bintray.com/commons-codec/commons-codec/1.10/commons-codec-1.10.jar'.
            > jcenter.bintray.com

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 6m 2s
  Command: /home/benny/Documents/Afiaanyi/mobile_app_codes/android/gradlew app:properties

pls can someone suggest how I can fix this errors

A: Try to copy the above url address into your browser and see if you can access them
for example  this one https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-daemon-embeddable/1.3.50/
Also try to see if you have proxy or network issue to access the internet.


text:
Q: App on Server 2016 running under Framework Version: v4.0.30319 instead of 4.6? I have a full framework 4.6.2 windows service running on a Server 2016 box.  I recently moved it from using Ninject to the Microsoft extensions DI framework.  Runs fine on my local system, but when I try to run it on the server it's throwing an error, specifically something about a missing method exception.  I traced it down to my GenerateProvider method, but it's about as basic as you can get.  What caught my eye was in the error message it included this:
Framework Version: v4.0.30319

The full error for reference:
Application: MyApp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.MissingMethodException
   at MyApp.Repository.WorkOrderRepository..ctor()
   at MyApp.Repository.ProcessingRepository..ctor()
   at MyApp.Worker..ctor(MyApp.Repository.IJobRepository)
   at MyApp.Program.Main()

If I'm reading that right, is it really trying to run this under the 4.0.30319 framework?  Microsoft extensions needs 4.6.1, so I imagine that'd be part of my error.  But server 2016 comes with 4.6.2, any thoughts as to why it'd try to run an app as 4.0?


text:
Q: MySQL correlated subquery SUM() ORDER BY Is there anyway to optimize the following query:
SELECT
  t1.id,
  (SELECT SUM(col1) FROM table_name_two t2 WHERE t2.name LIKE CONCAT('%',t1.name)) AS col1_count
FROM
  table_name_one t1
ORDER BY
  col1_count DESC

Using ORDER BY col1_count DESC takes a long time.
Thanks.

A: Just make a normal join with your comparison in the join's on clause:
SELECT
  t1.id,
  SUM(t2.col1) AS col1_count
FROM table_name_one t1
LEFT JOIN table_name_two t2 on t2.name LIKE CONCAT('%', t1.name)
GROUP BY 1
ORDER BY 2 DESC

It should be way faster this way - it's basically one query instead of "n" queries, although it won't get any help from indexes using the LIKE operator with a leading %


text:
Q: asp.net navigation custom pages I have an ASP.NET Dynamic Data Web Site. I have created a new Web Form at the top level and access it with NavigateUrl="~/ChangePassword.aspx".
However if I try to add a new Web Form inside the CustomPages folder I can't access it like this...Why is this?

A: You should have a look into the web.config file within the DynamicData folder
<system.web>
    <httpHandlers>
      <add path="*.aspx" verb="*"
           type="System.Web.HttpNotFoundHandler" validate="true" />
    </httpHandlers>
 </system.web>

any access to an .aspx file will be redirected to a HttpNotFoundHandler!
Within CustomPages folder you may place your own - customized - dyanmic data template pages for any kind of entitySet.
Just create a subFolder with the name of an EntitySet and within this folder, create (or copy) your new templates.
Anyways - this new templated customized pages will be accessible only by your defined route(s) (eg: new DynamicDataRoute("{table}/{action}.aspx")  )


text:
Q: Flutter Stripe Payment : StripeSource class missing I am following this and this tutorial to integrate stripe payment into my flutter project. Both of these tutorials/examples reference the class StripeSource by calling its method
StripeSource.setPublishableKey("pk_test");
but this class seems to be missing from the latest stripe package for a flutter. I've added the flutter SDK using stripe_payment: ^1.0.0 in my pubspec.yaml file and other stripe classes are available.
Any help is highly appreciated :-).

A: Those tutorial are outdated. The library changed and now it works in a different way. Instead of using StripeSource, you should use StripePayment.
For example:
StripePayment.setOptions(StripeOptions(
                          publishableKey:
                              'YOUR_TEST_PUBLISH_KEY'));
                      StripePayment.paymentRequestWithCardForm(
                              CardFormPaymentRequest())
                          .catchError((e) {
                        print('ERROR ${e.toString()}');
                      }).then((paymentMethod) {
                        //DO SOMETHING WITH YOUR PAYMENT METHOD
                      });

EDIT
What matters to follow those tutorials, is to optain the 'token'. As it is not very clear and there is not a complete documentation, I want to point out that:
paymentMethod.id is equal to the token returned by StripeSource.addSource() in the old versions.


text:
Q: Find all possible combinations of even or odd numbers and perform mathematical operations on the result I am trying to find all possible combinations from taking one integer from each of three lists. The combinations must contain either all even or all odd integers.
I would then like to find the sum of the squares of the integers in each combination.
Finally I would like to create a dictionary that uses this value as the key and the combination it used as its stored value.
E.g. for the combination (1,3,1): the key would be the integer 11 (from the sum (1^2) + (3^2) + (1^2)) and the value stored would be (1,3,1)
My code so far:
lists = [[0,1,2,3,4,5,6],[0,1,2,3,4,5,6],[0,1,2,3,4,5,6]]

combos = np.array([list(i) for i in np.array(np.meshgrid(*values)).T.reshape(-1,len(values))])

This takes three lists that each contain the integers 0-6
and uses an element from each list to create a combination of three integers
All possible combinations result: [0,0,0], [0,1,0], [0,2,0], [1,0,0] ... [6,6,6]

A: One solution.
Code
from itertools import product

lsts = [[0,1,2,3,4,5,6],[0,1,2,3,4,5,6],[0,1,2,3,4,5,6]]

# Product generates all combinations of taking one from each list
combos = product(*lsts)

# We filter for the combinations with all odd or even
# using generator i.e. () but could have been a list i.e. []
valid = (c for c in combos if all(x%2==0 for x in c) or all(x%2==1 for x in c))

# Dictionary key is sum of the squares of c
d = {sum(map(lambda i : i * i, c)) : c for c in valid}

# Pretty Print result
import pprint
pprint.pprint(d)

Output
{0: (0, 0, 0),
 3: (1, 1, 1),
 4: (2, 0, 0),
 8: (2, 2, 0),
 11: (3, 1, 1),
 12: (2, 2, 2),
 16: (4, 0, 0),
 19: (3, 3, 1),
 20: (4, 2, 0),
 24: (4, 2, 2),
 27: (5, 1, 1),
 32: (4, 4, 0),
 35: (5, 3, 1),
 36: (6, 0, 0),
 40: (6, 2, 0),
 43: (5, 3, 3),
 44: (6, 2, 2),
 48: (4, 4, 4),
 51: (5, 5, 1),
 52: (6, 4, 0),
 56: (6, 4, 2),
 59: (5, 5, 3),
 68: (6, 4, 4),
 72: (6, 6, 0),
 75: (5, 5, 5),
 76: (6, 6, 2),
 88: (6, 6, 4),
 108: (6, 6, 6)}

A: from itertools import combinations_with_replacement as cwr

iter_list = [0,1,2,3,4,5,6]

evens = [
    [t[0], t[1], t[2]]
    for t in list(cwr(iter_list, 3))
    if t[0] % 2 == 0 and t[1] % 2 == 0 and t[2] % 2 == 0
]

odds = [
    [t[0], t[1], t[2]]
    for t in list(cwr(iter_list, 3))
    if t[0] % 2 != 0 and t[1] % 2 != 0 and t[2] % 2 != 0
]

evens_dict = {e[0] ** 2 + e[1] ** 2 + e[2] ** 2 : e for e in evens}

odds_dict = {o[0] ** 2 + o[1] ** 2 + o[2] ** 2 : o for o in odds}

final_dict = {}
final_dict.update(evens_dict)
final_dict.update(odds_dict)

final_dict

# if you need it sorted by keys, add this
#final_dict = {k : v for k, v in sorted(final_dict.items(), key = lambda v : v, reverse = False)}
#final_dict

A: You can use the Law of Quadratic Reciprocity to enumerate the sequence of uniformly odd / even sums of integer squares directly.
from itertools import combinations_with_replacement
{
  sum(x ** 2 for x in xs): xs
  for xs in combinations_with_replacement(range(7), r=3)
  if sum(x ** 2 for x in xs) % 8 in {3, 4, 0}
}

Youtube Channel "Mathologer" demonstrates a proof of the theorem which explains where the modulus and residue are found by breaking down "the sum of 3 even/odd integer squares" into coherent statements in modular arithmetic.


text:
Q: Tableau Auto-refresh local on-premises Database/files on Mac I wonder anyone has succeeded in refreshed publishing workbook from local on-premises database/files on Mac?   I am using Tableau Online and I made Tabcmd working on mac. But seems I need Tableau Data Extract Command-line Utility to do the job.
I do not want to use VMs or Windows machines as it may cause trouble for my database management, which I built with OS X.  I also tried Wine/Crossover to run Tableau.exe on Mac, which did not work.
Any better suggestions?  Please kindly help. Thanks!

A: It's not clear exactly what you are trying to do.
If you want to create a Tableau data extract programmatically, you can write a script or program that calls the Tableau Data Extract API.
If you want to upload something to Tableau server, you can write a script or program that calls the Tableau REST API


text:
Q: Break out of inner loop only in nested loop I'm trying to implement a break so I don't have to continue to loop when I got the result xxxxx times.
$baseFileCsvContents | ForEach-Object {
    # Do stuff
    $fileToBeMergedCsvContents | ForEach-Object {
        If ($_.SamAccountName -eq $baseSameAccountName) {
            # Do something
            break
        }
        # Stop doing stuff in this For Loop
    }
    # Continue doing stuff in this For Loop
}

The problem is, that break is exiting both ForEach-Object loops, and I just want it to exit the inner loop. I have tried reading and setting flags like :outer, however all I get is syntax errors.
Anyone know how to do this?

A: You won't be able to use a named loop with ForEach-Object, but can do it using the ForEach keyword instead like so:
$OuterLoop = 1..10
$InnerLoop = 25..50

$OuterLoop | ForEach-Object {
    Write-Verbose "[OuterLoop] $($_)" -Verbose
    :inner
    ForEach ($Item in $InnerLoop) {
        Write-Verbose "[InnerLoop] $($Item)" -Verbose
        If ($Item -eq 30) {
            Write-Warning 'BREAKING INNER LOOP!'
            BREAK inner
        }
    }
}

Now whenever it gets to 30 on each innerloop, it will break out to the outer loop and continue on.

A: Using the return keyword works, as "ForEach-Object" takes a scriptblock as it's parameter and than invokes that scriptblock for every element in the pipe.
    1..10 | ForEach-Object {
        $a = $_
        1..2 | ForEach-Object {
            if($a -eq 5 -and $_ -eq 1) {return}
            "$a $_"
        }
        "---"
    }

Will skip "5 1"


text:
Q: SQL Join on conditions I'm trying to write a query which will do some calculations on a transaction if that specific transaction meets a certain requirement (in this case that it's total quantity != 0).
IF EXISTS(
   SELECT DISTINCT
        T0.[ItemCode],
        T0.[ItemName],
        T0.[DocDate],
        CAST(CAST(T0.[CreateTime] / 100 AS varchar) + ':' + CAST(T0.[CreateTime] % 100 AS varchar) AS time) AS [CreateTime],
        T0.[DocType],
        T0.[DocEntry],
        T0.[DocNum],
        T0.[LocCode],
        T1.[MdAbsEntry],
        T4.[AbsEntry],
        T4.[DistNumber] AS [BatchNumber],
        T1.[Quantity],
        T5.[CalcPrice] AS [Price],
        T3.[U_ORC_BE_Variance]

    FROM OITL T0
        INNER JOIN ITL1 T1 ON T1.[LogEntry] = T0.[LogEntry]
        INNER JOIN OITM T2 ON T2.[ItemCode] = T0.[ItemCode]
        INNER JOIN IGE1 T3 ON T3.[DocEntry] = T0.[DocEntry]
        INNER JOIN OBTN T4 ON T1.[MdAbsEntry] = T4.[AbsEntry]
        INNER JOIN OINM T5 ON T0.[ItemCode] = T5.[ItemCode]
            AND T0.[LocCode] = T5.[Warehouse]
            AND T0.[AppDocNum] = T5.[BASE_REF]

    WHERE T0.[ItemCode] LIKE 'BB%' -- BBT items only
        AND T3.[U_ORC_BE_Variance] = 'M3'-- Code issued upon BBT empty
        AND CAST(CAST(T0.[CreateTime] / 100 AS varchar) + ':' + CAST(T0.[CreateTime] % 100 AS varchar) AS time)
            BETWEEN CAST(DATEADD(MINUTE,-11,GETDATE())AS TIME) AND CONVERT(varchar(10), GETDATE(), 108) -- Last 10 minutes
        AND T0.[DocDate] = CAST(LEFT(GETDATE(), 11) AS DATETIME) -- Today
   )

BEGIN

SELECT DISTINCT
       'BBT ALERT - ' + convert(varchar(10), GETDATE(), 108) + ' - Check for errors',
        'Difference HL:',
       SUM(T1.[Quantity]),
       'Percentage Difference:',
       ((((SUM(ABS(T1.[Quantity])) - MAX(T1.[Quantity])) / MAX(T1.[Quantity])) * 100) - 100)

FROM OITL T0
    INNER JOIN ITL1 T1 ON T1.[LogEntry] = T0.[LogEntry]
    INNER JOIN OITM T2 ON T2.[ItemCode] = T0.[ItemCode]
    INNER JOIN IGE1 T3 ON T3.[DocEntry] = T0.[DocEntry]
    INNER JOIN OBTN T4 ON T1.[MdAbsEntry] = T4.[AbsEntry]
    INNER JOIN OINM T5 ON T0.[ItemCode] = T5.[ItemCode]
        AND T0.[LocCode] = T5.[Warehouse]
        AND T0.[AppDocNum] = T5.[BASE_REF]

WHERE
        (SELECT SUM([Quantity]) FROM ITL1 WHERE
                (SELECT DISTINCT
                    T4.[AbsEntry]
                 FROM OITL T0
                    INNER JOIN ITL1 T1 ON T1.[LogEntry] = T0.[LogEntry]
                    INNER JOIN OITM T2 ON T2.[ItemCode] = T0.[ItemCode]
                    INNER JOIN IGE1 T3 ON T3.[DocEntry] = T0.[DocEntry]
                    INNER JOIN OBTN T4 ON T1.[MdAbsEntry] = T4.[AbsEntry]
                    INNER JOIN OINM T5 ON T0.[ItemCode] = T5.[ItemCode]
                        AND T0.[LocCode] = T5.[Warehouse]
                        AND T0.[AppDocNum] = T5.[BASE_REF]

                WHERE T0.[ItemCode] LIKE 'BB%' -- BBT items only
                        AND T3.[U_ORC_BE_Variance] = 'M3'-- Code issued upon BBT empty
                        AND CAST(CAST(T0.[CreateTime] / 100 AS varchar) + ':' + CAST(T0.[CreateTime] % 100 AS varchar) AS time)
                            BETWEEN CAST(DATEADD(MINUTE,-11,GETDATE())AS TIME) AND CONVERT(varchar(10), GETDATE(), 108) -- Last 10 minutes
                                AND T0.[DocDate] = CAST(LEFT(GETDATE(), 11) AS DATETIME) -- Today
                ) = [MdAbsEntry]
            ) <> 0

SELECT DISTINCT
       T1.[MdAbsEntry],
       T0.[DocNum],
       T1.[Quantity]

FROM OITL T0
    INNER JOIN ITL1 T1 ON T1.[LogEntry] = T0.[LogEntry]
    INNER JOIN OITM T2 ON T2.[ItemCode] = T0.[ItemCode]
    INNER JOIN IGE1 T3 ON T3.[DocEntry] = T0.[DocEntry]
    INNER JOIN OBTN T4 ON T1.[MdAbsEntry] = T4.[AbsEntry]
    INNER JOIN OINM T5 ON T0.[ItemCode] = T5.[ItemCode] AND T0.[LocCode] = T5.[Warehouse]
        AND T0.[AppDocNum] = T5.[BASE_REF]

WHERE
        (SELECT SUM([Quantity]) FROM ITL1 WHERE
                (SELECT DISTINCT
                    T4.[AbsEntry]
                 FROM OITL T0
                    INNER JOIN ITL1 T1 ON T1.[LogEntry] = T0.[LogEntry]
                    INNER JOIN OITM T2 ON T2.[ItemCode] = T0.[ItemCode]
                    INNER JOIN IGE1 T3 ON T3.[DocEntry] = T0.[DocEntry]
                    INNER JOIN OBTN T4 ON T1.[MdAbsEntry] = T4.[AbsEntry]
                    INNER JOIN OINM T5 ON T0.[ItemCode] = T5.[ItemCode]
                        AND T0.[LocCode] = T5.[Warehouse]
                        AND T0.[AppDocNum] = T5.[BASE_REF]

                  WHERE T0.[ItemCode] LIKE 'BB%' -- BBT items only
                        AND T3.[U_ORC_BE_Variance] = 'M3'-- Code issued upon BBT empty
                        AND CAST(CAST(T0.[CreateTime] / 100 AS varchar) + ':' + CAST(T0.[CreateTime] % 100 AS varchar) AS time)
                            BETWEEN CAST(DATEADD(MINUTE,-11,GETDATE())AS TIME) AND CONVERT(varchar(10), GETDATE(), 108) -- Last 10 minutes
                                AND T0.[DocDate] = CAST(LEFT(GETDATE(), 11) AS DATETIME) -- Today
                ) = [MdAbsEntry]
            ) <> 0

END

If I run the first part in isolation I get the following (which is correct):

However if I run the query in full I get the following:

I would expect it to only list results with one value in MdAbsEntry (in this case 5618).
It looks to me that it's not matching on the MdAbsEntry value like I want it to, and so pulling results for all data instead of just for this one specific transaction.
Can anyone give me any advice on why it might be doing this?


text:
Q: How to extract only the first instance of a number of lines between two strings in bash? My file is:
abc
123
xyz
abc
675
xyz

And I want to extract:
abc
123
xyz

(123 could be anything, the point is I want the first occurrence)
I tried using this:
sed -n '/abc/,/xyz/p' filename

but this is giving me all the instances. How could I get just the first one?

A: Could you please try following, written and tested with shown samples.
awk '/abc/{found=1} found; /xyz/ && found{exit}'  Input_file

OR as per Ed sir's comment for better efficiency try following.
awk '/abc/{found=1} found{print; if (/xyz/) exit}'  Input_file

Explanation: Adding detailed explanation for above.
awk '               ##Starting awk program from here.
/abc/{              ##checking condition if a line has abc in it then do following.
  found=1           ##Setting found here.
}
found;              ##Checking condition if found is SET then print that line.
/xyz/ && found{     ##Checking if xyz found in line and found is SET then do following.
  exit              ##exit program from here.
}
'  Input_file       ##Mentioning Input_file name here.

A: If you don't mind Perl:
perl -ne 'm?abc?..m?xyz? and print' file

will print only the first block that matches. The delimiter for the matches must be the ? character.

A: Using sed you can do:
sed -n '/abc/,/xyz/p; /xyz/q' filename

q will quit after the "xyz" pattern is reached.

A: Match the Terminal Condition Twice
Regardless of the language, the most common technique for line-oriented processing is to print lines within a given range and then use a second command to exit the loop when your terminal condition is reached. This will be true for common patterns in sed, awk, ruby, and perl, although there are certainly other techniques that can be performed using multi-line matches (not supported in sed without using the hold space). For example, you might use a non-greedy, multi-line regular expression pattern such as /^abc\n.*?\nxyz$/m.
To illustrate the line-oriented approach you want a little more verbosely, consider this Ruby one-liner where $_ holds the current input line. From the shell:
$ ruby -ne 'puts $_ if /^abc$/ .. /^xyz$/; exit if /^xyz/' filename
abc
123
xyz

The equivalent in sed is:
$ sed -n '/^abc$/,/^xyz$/p; /^xyz$/q' filename
abc
123
xyz

All you were missing was a quit or exit command attached to the second match against the first instance of xyz.

A: This has already been well and sufficiently answered and hashed out by better minds than me, but

*

*since you explicitly used sed, and

*for some variety of approach that handles the requested conditions...

sed -n '/abc/,/xyz/{ p; /xyz/q; }' filename

*

*This only looks at the range in question, so won't print or quit on xyz with no opening abc ahead of it

*it prints all the records in the range

*it exits on the first xyz it sees AFTER an abc, so will dependably exit

*if the end doesn't have an xyz it will just print to EOF.

You might refine the pattern if you want to make sure of exact matching, such as
sed -n '/^abc$/,/^xyz$/{ p; /^xyz$/q; }' filename

This prevents near-matches from confusing the logic, but is (intentionally) unforgiving of botched sentinel strings.

A: This might work for you (GNU sed):
 sed '/abc/!d;:a;n;/xyz/!ba;q' file

If it is not a line containing abc delete it.
Otherwise, print it and fetch the next.
If that line is not xyz, repeat.
Otherwise, quit.
N.B. The option -n is not set and so the last line will be printed before termination.
This will print until the end of the file or the string xyz is encountered.
If xyz must be present, use:
sed -n '/abc/!d;:a;N;/xyz/!ba;p;q' file


text:
Q: mysql update column value from 3 tables I have 3 Tables Y2018 Y2017 Y2016 with total_revenue field.
I would like to update Y2018.5Y_growth_total_revenue  with the medium value of the 3 tables value of total_revenue.
I tried like this but it does not work:
update Y2018 y8
inner join Y2017 y7
inner join Y2016 y6 on y7.id_azione = y8.id_azione = y6.id_azione
set
    y8.5Y_growth_total_revenue = (
        y8.total_revenue + y7.total_revenue + y6.total_revenue
    ) / 3;

Thank You
Carlo

A: You could try this way
update Y2018 y8
inner join Y2017 y7  on y7.id_azione = y8.id_azione
inner join Y2016 y6  on y8.id_azione = y6.id_azione
set y8.5Y_growth_total_revenue = (y8.total_revenue + y7.total_revenue + y6.total_revenue) / 3;

or using a subquery if the db don't let change the table invoved  in join
update Y2018 y8
INNER JOIN (
    select y8.id_azione  (y8.total_revenue + y7.total_revenue + y6.total_revenue) / 3 the_avg
    from Y2018 y8
    inner join Y2017 y7  on y7.id_azione = y8.id_azione
    inner join Y2016 y6  on  y8.id_azione = y6.id_azione
) t on t.id_azione = y8.id_azione
set y8.5Y_growth_total_revenue = t.the_avg;

anyway  sql have also avg() aggreation function and group by for control the  aggregation


text:
Q: What is the difference between MySQLi and PDO? I have recently started learning PHP. I came to know that there has been many changes and SQL is now being avoided and has been replaced by MySQLi, but then I came to know about PDO. I have gone through many posts about these two topics, but everyone has their own opinion and I am confused. Many posts have said that MySQLi supports procedural and object oriented method whereas PDO supports only an object-oriented method.
What I want to know is that:

*

*Are these two (PDO and MySQLi) just two different ways of doing the same thing or are they different from each other?

*If they are just two different ways to do the same thing then what is the difference between them and which one is a better way to perform the task?

*If learning MySQLi, which one is better method between object-oriented and procedural?
For some it may seem to be a broad question, but I would be highly obliged if anyone can give specific answer for these three questions.

A: When accessing a database in PHP, we have two choices: MySQLi and PDO. So what should you know before choosing one?

*

*PDO has 12 different driver supports while MYSQLI has only one i.e MYSQL.

*PDO uses OOP API while MySqli use both OOP and precedural

*PDO has named parameters but MuSqli does not.

*With PDO one can have prepared statements at client side

A: PDO is an interface for accessing databases:

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server. (source)

MySQLi is an extension for accessing MySQL databases:

The mysqli extension allows you to access the functionality provided by MySQL 4.1 and above. (source)

Which one you should use is primarily opinion-based and not particularly well suited for the Stack Overflow format.


text:
Q: Cannot figure out how to implement a very basic arbitrary tree in F# I found this question from way back when that seemed quite relevant to my needs - Tree Representation in F#
for the sake of learning I tried implementing a super simple test basically exactly as Daniel had written
 type Tree =
     | Branch of string * Tree list
     | Leaf of string

 let t2 = Branch ("a", [Branch ("b", [Leaf "c"; Leaf "d"]); Branch ("e", [Leaf "f"; Leaf "g"])])

 let rec checkstuff tree =
      match tree with
      | Leaf _ -> true
      | Branch(node, children) -> List.fold (||) false (List.map checkstuff children)

And while this compiles and runs, I guess I'm just not sure how to actually use it? With the above example, the only way I could figure out to successfully call the function always yields a value of -true- regardless of the content of the successful input. i.e
  checkstuff (Leaf "z")

But I'm obviously not using it right above. It always returns true regardless of the string value of the leaf passed. That makes sense bc the only tree its been given to check is a tree consisting of the single leaf "z". Ok so maybe I'm supposed to use it like this
 t2 |> checkstuff (Leaf "z")

But that's wrong because it, and every slight variation of it, yields a type mismatch error
  This expression was expected to have type    'Tree -> 'a'    but here has type    'bool'

It seems like I am still not grasping some very fundamental aspects of this language, and recursion/fold techniques in general. I am particularly confounded by the last chunk of that implementation
   List.fold (||) false (List.map checkstuff children)

What exactly is going on here? Through my reading I've found that the (||) is the boolean or operator being used in the style of a function call, so the successive "false" and list.map parts are the 2 parameters of that OR 'function' (correct?). But how exactly does that work as the accumulator for the fold?
My two main questions are

*

*Can I see a functioning example of how one would actually use/call the Tree type and checkstuff function shown above (thank you Daniel), to see if a given string value exists in the tree?

*Can someone show how that implementation might be adapted to, say, concatenate all the string values in this tree? Or maybe find if any values match a pattern? Or really any example that involves a slight modification of the above would be so helpful

====================
EDIT:
after experimenting some more with the answer below a lot of stuff finally "clicked" for me about F#. In retrospect, my "conceptual" understanding wasn't as poor as I thought, its just that my implementation was full of technical errors and syntax misuse. The common theme (besides trying to implement code I didn't fully understand :P ) was the misuse of parentheses. In many places I had annotations grouped together with parentheses when they should not have been. E.g
  let funcles (x:string y:string) : string

Should be
  let funcles (x:string) (y:string) : string

and definitely shouldn't be
  let  funcles (x:string y:string :string)

In other places I had parameters for function calls grouped together when they shouldn't have been - or not properly grouped with the function call itself when they should have been - causing either errors or causing them to be interpreted as a single parameter and leading the compiler to thinking the next function it encountered was actually my final parameter.
And further some of my problems were also coming from me not using type annotations in contexts where the compiler really needs them. Certain types were being interpreted as generic when they should have been specific, so my custom types weren't matching as they should later in the program. This seems especially crucial if you are trying to use partial application on custom functions being used w/ the pipe operator.
All of these different instances combined and my noob-ness meant I was getting a barrage of virtually incomprehensible compiler errors, all of which now make a lot more sense.
I would post my working solution but its nearly identical to the answer below, except instead of a string it uses (string * string), so i'm not sure it would add much value.
TL;DR - PARENTHESES ARE IMPORTANT

A: I'm afraid you've copied some code that isn't very useful: checkstuff will return true for any tree that contains at least one Leaf. It simply recursively OR's together its child results, so a single true value will guarantee that the final result is also true.
To check if a string exists in a tree, I would do this:
let rec exists str = function
    | Leaf s -> s = str
    | Branch (s, children) ->
        if s = str then true
        else children |> List.exists (exists str)

exists "c" t2 |> printfn "%A"   // true
exists "x" t2 |> printfn "%A"   // false

To concatenate the strings in a tree, I would do this:
let rec concat = function
    | Leaf s -> s
    | Branch (s, children) ->
        let childStr =
            children
                |> List.map concat
                |> String.concat ""
        $"{s}{childStr}"

concat t2 |> printfn "%s"   // abcdefg


text:
Q: CSS Rotate and Replace Image at the Same Time Can someone help me understand how, using CSS, I can rotate and change an image at the same time on hover?  When a user hovers over an image I want to start the rotation and change the image during the middle of the rotation.  So far I have the following but I can not figure out how to delay the image change on hover.
.image-swap {
    background: url("image1.jpg") no-repeat;
    border-radius: 50%;
    height: 300px;
    width: 300px;
    -moz-transition: -moz-transform 0.8s ease-in-out;
    -webkit-transition: -webkit-transform 0.8s ease-in-out;
    -o-transition: -o-transform 0.8s ease-in-out;
    -ms-transition: -ms-transform 0.8s ease-in-out;
    transition: transform 0.8s ease-in-out;
}
.image-swap:hover {
    background: url("image2.jpg") no-repeat;
    cursor: pointer;
    -moz-transform: rotateY(360deg);
    -webkit-transform: rotateY(360deg);
    -o-transform: rotateY(360deg);
    -ms-transform: rotateY(360deg);
    transform: rotateY(360deg);
}

A: You really just need to add background-image to the transition rule.
In this example, I also use a container element to trigger the hover (otherwise the interactive area rotates with the image, which causes jerkiness if the cursor gets caught on, say, a moving corner).

.image-swap-container {
  width: 300px;
  height: 300px;
  overflow: hidden;
}

.image-swap {
    background-repeat: no-repeat;
    background-image: url("http://placehold.it/300x300/ff0000");
    border-radius: 50%;
    height: 300px;
    width: 300px;
    transform: none;
    transition: transform 1s, background-image 1s;
}

.image-swap-container:hover {
    cursor: pointer;
}

.image-swap-container:hover .image-swap {
    background: url("http://placehold.it/300x300/00ff00");
    transform: rotateZ(360deg);
}


text:
Q: Use hardware remotely I have a software that runs on my PC.  There is a test setup elsewhere in the network which has  temperature and pressure measuring cards. That setup also has a windows OS.
Both my PC and the setup are connected to the LAN. Now I want to write a temperature measuring test on my PC using my software (written in python)  which would access the remote setup.
How can I achieve this? Previously I was running my software on the setup itself , using windll utitlty to initialize the cards and now I want to separate it out.

A: Since you are already using python you should consider fabric http://www.fabfile.org/ or the new incarnation this project, invoke http://www.pyinvoke.org/
Both of these allow you to run code remotely over an ssh connection.   I'm a mac/unix guy but I think they work with windows.

A: If the set up is proving a LAN interface and exposes a server then it is possible to read the value using socket programming. If not then a web service can be run on the setup to read the value and serve it on the network


text:
Q: Pivot table in Hive I'm new to hadoop and hive. if anyone worked with a concept of pivot in hive then please share with me.
Eg: the data from teradata or oracle is unpivoted, these data should be pivoted in hive. so how to apply the concept of pivot in hive...
Thanks in advance,
Tamil

A: Not sure if you have seen the link below
http://www.flytxt.com/community/general-discussion/pivot-table-in-hive/
It tries to explain the concept in detail


text:
Q: PHP магия с индексом массива Всем добрый вечер, столкнулся с непонятной проблемой.
В скрипте:
var_dump(array_keys($obj->content->photo_self_thinking));
var_dump(array_key_exists("2", $obj->content->photo_self_thinking));
var_dump(array_key_exists(2, $obj->content->photo_self_thinking));

Выводит:
array(3) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "3"
  [2]=>
  string(1) "4"
}
bool(false)bool(false)

Попытка обращения к соответствующему индексу заканчивается ошибкой E_NOTICE Undefined offset.
Что за магия?