text:
Q: reactjs es6 calling function inside other function throws function not defined Here is my code
In App.js file there is a button component. I am calling hi function onclick event. In this event, I want to use redux saga to call sayHello();
if I am using sayHello directly on button click event, code works fine. But my requirement is call it in an other function. Below is the entire file for reference.Appreciate your help.

A: When calling some function in another function, you have to specify the scope.
Use it as below:
const hi = () => {
 console.log("hiiiiiiiiiiiiii");
 this.sayHello();
};

Hope this helps!

A: You should defined ur function in your component scope.
Because the function SayHello is defined in props.
Just like this:
class App extends Component {

  hi = () => {
    onsole.log("hiiiiiiiiiiiiii");
    this.props.sayHello();
  }

  render() {
    const { hello, exampleTask } = this.props;
    return (

Hello {hello}

Redux-saga demo. Start editing to see some magic happen!

        <button onClick={this.hi}>Say Hello!</button>
        <button onClick={exampleTask}>Example Task</button>

    );
  }
}


text:
Q: On convergence $f*\phi_c$ to $f$ in $L^\infty$ Let $\phi \in L^1(\mathbb{R})$ be such that $\int_{-\infty}^\infty \phi(x)dx=1$ and let, for $c>0$, $\phi_c(x)=\frac{1}{\varepsilon} \phi(\frac{x}{c})$.
In the book Introduction to Fourier analysis on Euclidean spaces, by Elías M. Stein,Guido L. Weiss,  is the following theorem (Th.1.18):
If $f \in L^p(\mathbb{R})$, where $p\in [1, \infty)$ or in $C_0$ then $\|f*\phi_c-f\|_p \rightarrow 0$ as $c\rightarrow 0^+$.
Proof of this theorem is given there only in the case $p\in [1, \infty)$. How to proof it in the case $f \in C_0 $ ?
($C_0$ is the Banach space, with supremum norm,  of all continuous functions $g: \mathbb{R} \rightarrow \mathbb{R}$ such that $\lim_{x \rightarrow +\infty}g(x)=\lim_{x \rightarrow -\infty}g(x)=0$.)
Thanks.
Edit. The mentioned proof in $L^p$ goes in the following way:
$$(f* \phi_c)(x)-f(x)=\int_R [f(x-t)-f(x)]\phi_c(t)dt$$
Next by generalized Minkowski inequality and substitution:
$$\|f* \phi_c-f\|_p \leq \int( \int|f(x-t)-f(x)|^p dx)^\frac{1}{p} \frac{1}{c} |\phi(\frac{t}{c})|dt=\int( \int|f(x-ct)-f(x)|^p dx)^\frac{1}{p}  |\phi(t)|dt.$$
Next $\|f(x+h)-f(x)\|_p \rightarrow 0$ when $h \rightarrow 0$ is used and is applied majorized convergence in last integral.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Project building in NetBeans8.1 is too slow Note: I did some research, and I found nothing on this type of problem.
When I try to clean and build or run a program, it varies between 20 and 30 seconds to do that. (I'm coding in C and C++)
The last time I tried to clean and build, it took 23 seconds to do it. Building is faster, it takes 10 seconds. Running a program takes 25 seconds.
This started happening a few days ago out of nowhere, I had 3 plugins but they were all just changing my NetBeans skin. What can I do to make my IDE work faster?
It spends most of the time at this part:
cd 'E:\projekti\helloworld'
C:\cygwin642\bin\make.exe -f Makefile CONF=Debug clean
and this:
cd 'E:\projekti\helloworld'
C:\cygwin642\bin\make.exe -f Makefile CONF=Debug
What can I do to make this go away?

A: If you use Malwarebytes Antimalware turn it off. Deactivating its functions doesn't help. You need it to quit it completely. You will gain 12x to 20x build speed increase. It doesn't affect speed of netbeans startup but it drastically speeds up netbeans cleaning iand building. I also reccomend quiting netbeans and deleting entrie cache folder (in windows inside: C:\Users\\AppData\Local\NetBeans). Restart windows. Projects will scan for looong time. Don't quit netbeans, do not write any code or reconfigure your projects. Just wait till scan finishes. Restart netbeans. Scanning should be faster now. Remember, do not run malwarebytes antimalware when you use netbeans. Make sure Antimalware icon is not on your tray.


text:
Q: Auto-Renewable subscription renewal and cancellation detection and receipt refresh I've implemented a local receipt validation routine to extract the expiration date of subscriptions and it is working correctly. But I'm having hard time finding out when exactly the receipt gets updated automatically and when should I force a refresh.
I have a couple of question regarding the matter
1) Does SKPaymentQueue.default() ever gets updated externally by Apple? Or it only gets updated when a transaction is triggered on the device locally?
2) Can we be certain that after a purchase of an auto-renewable subscription product, receipt gets updated automatically? Should I update the receipt with a SKReceiptRefreshRequest() after the purchase has been verified within

    paymentQueue(_ queue: SKPaymentQueue, updated Transactions transactions: [SKPaymentTransaction])
Or after a purchase completes can I directly go and read from the receipt the new expiration date without calling SKReceiptRefreshRequest()?
Please note that I am asking about refreshing the receipt from Apple's servers and not validating or reading expiration date from it.
3) If user cancels the subscription or the payment method fails at the renewal date, does Apple automatically updates the apps receipt or should I refresh the receipt with a SKReceiptRefreshRequest() request each time app starts in order to detect subscription cancellations?
4) When an auto-renewable subscription gets renewed successfully, does Apple automatically updates the apps receipt or should I refresh the receipt with a SKReceiptRefreshRequest() request each time app starts to get the new receipt in order to get the new expiration date when an renewal occurs?
5) Does refreshing the receipt with a SKReceiptRefreshRequest() request asks the user for their App Store credentials every time?
As you can see my main confusion is around when it is needed to force a ReceiptRefresh and when can I rely on the SKPaymentQueue or StoreKit to update it automatically.
Any insight would be welcome.


text:
Q: list & sort subfolders by number of items I'm trying to write a bash script to list & sort subfolders by number of items.
Here's what I have:
find * | wc -l works to return count of items.
And for f in *; do echo "$f"; find "$f" | wc -l ; done works, but the list is hard to parse.
So I tried to use printf:
for f in *; do
   c=`echo find "$f" | wc -l` ;
   printf "$c $f\n";
done

But it returns 1 for every subfolder.
And I would like to sort the final list by the number of items in each subfolder.

A: This intrigued me, so I had a go at it, here's my code:
#!/bin/bash

startIFS=$IFS
IFS=$'\n'

function echocount {
dirs=$(find -type d)
for f in $dirs; do
   c=$(find "$f" -maxdepth 1 -type f | wc -l) ;
   echo "$c $f";
done
}

echocount | sort -n

IFS=$startIFS

I find this very stupid and annoying in shell scripting, but I need to change the IFS so that only newlines and not spaces will signify another directory and the loop will run correctly.
BTW, in your code, the reason it always had a count of 1 is because in echo find "$f" | wc -l, you are actually counting the lines in echo find "$f", which will always be a single line (it's just echoing literally "find whatever", not actually running the find command). If you take the echo out, it will do what you expect.
Also, pedants will tell you that backtick notation is deprecated. I find $() notation more readable anyway.

A: With guidance from localhost, my solution is:
for f in */; do
  c=$(find "$f" | wc -l) ;
  printf "$c $f\n";
done | sort -n


text:
Q: Angular ngFor - load more - how to handle when the same item is loaded? We have a simple list of items (search results), and a "load 10 more" button under the list. With user click, we load the i.e. second page of items and add those at the end of the first list and so on.
The problem is, the data set can be changed in every second. So in the meantime when the user wants to load more items, an item which was already inside the first page, can be loaded again from backend with some updated info within the second page. Since we do not want to show the same item multiple times, at the moment we write our own logic where we iterate the list and manually compare the id's, everytime a new list part is loaded.. and if the same id appears again, we either ignore it or update the value of the original item.
Is there any Angular out-of-the-box solution for this problem?
I have actually thought sth. like "track by", which intelligently realizes which items are already rendered on UI, and just renders the changed  part of a list in DOM.
Thanks in advance.

A: I think the answer for this depends on the db you are using and the queries.
however if you can mirror this solution which works for firestore db. then it should work well for you.
you pull your first 20. and take note of the last item Ref in that array. your next db call would use the item Ref as a starting point and get the next 20 items.
however, if you are subscribed to the 1st 20 items changes in real time. and new items are added. you must change that Ref you were saving each time. so you don't skip any items.
hope this helps

A: it seems you are using the lastUpd date field to decide which "first 10" items to retrieve? that may be a bad idea. instead maybe the server should be sorting them by name or some other field that is not going to change the order when you re-query.
or better yet, do a complete re-query every time the button is pressed, rather than returning next 10 items and appending them to the current list. so after pressing the button one time, it returns 20 items instead of 10, etc.
or if you don't like either of those, continue doing what you are doing which requires a loop through your display data each time you add 10 new items to ensure no duplicates. seems like a pretty simple data loop.

A: For this answer I am making the following assumptions:

*

*You need to get your data ordered by some last-updated field.

*You have access to modify the backend data services or can ask for modifications.

That said... let's start:
When loading the next 10...

*

*Collect the list of ids from records you already have in client side, if any.

*Get the most recent last-updated value from the records.

*Send the list of ids as a parameter, along with the last-updated value, in the request for the next 10 records.

In the backend service.

*

*Get all updated records from the id list with and 'last-updated' date greater than the value sent from client. (I am using TSQL syntax here, but you might be using other flavor of SQL or a NoSQL db, but if you can read SQL syntax you can get the idea. You can also put both queries together with UNION clause)

/* Getting the updated records... */
SELECT * FROM MyTable WHERE id IN (list-of-ids-from-client) AND lastUpdated > @lastupdated
order by lastUpdated;

*Get the next batch of 10...

/* Getting the next batch of 10... */
SELECT TOP 10 * FROM MyTable WHERE id NOT IN (list-of-ids-from-client) order by lastUpdated;

*Return the data to client. (Remember to identify the updated records to make the updates on client side data efficiently).

In the client side

*

*Update existing records with updates, if any.

*Add new records to the list.


text:
Q: Smooth transitions with the new "Pressable" component? I've been using TouchableOpacity for ease of use in my react native project, but I'm interested in trying the new Pressable component instead - given how flexible its API is.
However, while the new Pressable API gives me the ability to change things like style props based on a pressed state easily, there is no smooth/animated transition like there is with the opacity in TouchableOpacity! Instead, the transition happens instantly when pressed/unpressed.
What is the best way to use Pressable but also make a nice, smooth transition between the pressed/unpressed style changes? I assume I'll have to use the Animated API in some way? Does anyone have an example of this?

A: You can use Animated Api
Here is a example of Animated Api:
import React from "react";
import { Pressable, Animated } from "react-native";

const Component = () => {
const animated = new Animated.Value(1);
  const fadeIn = () => {
    Animated.timing(animated, {
      toValue: 0.4,
      duration: 100,
      useNativeDriver: true,
    }).start();
  };
  const fadeOut = () => {
    Animated.timing(animated, {
      toValue: 1,
      duration: 200,
      useNativeDriver: true,
    }).start();
  };

  return (
    <View
          style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
        >
          <Pressable onPressIn={fadeIn} onPressOut={fadeOut}>
            <Animated.View
              style={{
                opacity: animated,
                backgroundColor: "red",
                padding: 50,
                borderRadius: 20,
              }}
            >
              <Text>Text</Text>
            </Animated.View>
          </Pressable>
        </View>
  );
};

Animated Api docs:
https://reactnative.dev/docs/animated
Also i recommend to check out reanimated library to create animation with native performance
https://docs.swmansion.com/react-native-reanimated/


text:
Q: Real time timer task on Android is it possible to create under Android a real time (timer) task?
I need a high performance timer which runs every 20 ms (without pause).
My Use-Case: Create an audio handler which puts every 20 ms an audio packet into the audio buffer. The audio data will be received in an UDP socket.
I used and testet different timer implemenations.
For example: ScheduledExecutorService, Timer/TimerTask, Handler, pure Loop (with Thread.Sleep), CountDownTimer.
No of this solutions works well for me :(
Example dummy implementations with ScheduledExecutorService and Timer/TimerTask (totally easy, see this code):
Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(new Runnable()
{
     @Override
     public void run()
     {
            // TODO here is my timer code
     }
}, 0, 20, TimeUnit.MILLISECONDS);

new Timer().schedule(new TimerTask()
{
     @Override
     public void run()
     {
           // TODO own Code here
     }
}, 0, 20);

My problem is:
Number1: No real time guarantee, my timer will be paused sometimes for 100-200 ms (IMHO the garbage collection or other OS services ...)
Number2: If my timer is in foreground, it works very well (except problem #1), but if my App is in background, the timer interval will be increased to 60 ms (not 20ms)
I've tested it on different android versions (5.x, 6.x, 7.x), on Marshmallow it sometimes works (maybe it depend on vendor driver?)
Some ideas? Or is that not possible under Android?


text:
Q: How can I found all secure and third party cookies on any website using python selenium I was tried different approach to get secure and third party cookies. Pasting approach I was tried.
With cookiesjar:
import urllib
import http.cookiejar

url = "https://www.google.com"

cookie_jar = http.cookiejar.CookieJar()
url_opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie_jar))
url_opener.open(url)

for cookie in cookie_jar:
    print(cookie)

with Requests module:
import requests

r = requests.get('http://www.google.com')

for cookie in r.cookies:
  print(cookie.__dict__)
  print(cookie.secure)

with PhantomJS:
from selenium import webdriver

cookie_file_path = 'cookie.txt'

args = ['--cookies-file={}'.format(cookie_file_path)]
driver = webdriver.PhantomJS(service_args=args)
driver.get('http://google.com')
driver.get('http://facebook.com')
with open(cookie_file_path) as f:
   print(f.read())

with Selenium:
driver = webdriver.Chrome(driver_exe, options=options,  desired_capabilities=capabilities)
driver.get('https://google.com')
cookies = driver.get_cookies()
for cookie in cookies:
   print(cookie)

Any help or docs related to this would be appriacted.
Thanks :)

A: Does this give you cookies?
import requests
r = requests.get('http://www.google.com')
print(r.cookies.get_dict())

A: we can use selenium devtool to extract all the cookies present on the website.
Ref:
[1]: https://www.selenium.dev/documentation/webdriver/bidirectional/chrome_devtools/


text:
Q: How to optimize F# programs generally I have an interpreter for a lisp-style language in F#, and have just gotten into the optimization phase. Simple tests of the evaluator reveal that I need to optimize it in an extreme manner. However, I don't have a general background in F# performance or optimization.
Are there any good general knowledge resources for F# program optimization? Particularly useful are tips of keeping cache coherency and surprising primitive performance issues. A cursory search hasn't revealed much on the internet.
Thank you!

A: Performance optimization tricks are all myths. As @svick said, it's no better way than profiling your program, identifying hot spots and optimizing them using concrete benchmarks.
Since you asked, here is some information floating around:

*

*A bunch of good answers about F# performance: C# / F# Performance comparison

*Using inline for performance optimization: Use of `inline` in F#

*Using structs instead of records for better performance: http://theburningmonk.com/2011/10/fsharp-performance-test-structs-vs-records/

*Array-oriented programming for performance-critical code: http://sharp-gamedev.blogspot.com/2010/03/thoughts-about-f-and-xbox-games.html

*Concrete case studies of performance optimization:
FSharp runs my algorithm slower than Python
F# seems slower than other languages... what can I do to speed it up?


text:
Q: Having trouble understanding how calculation_function works [Python 100 Days of Code] def add(n1, n2):
    return n1 + n2
def subtract(n1, n2):
    return n1 - n2
def multiply(n1, n2):
    return n1 * n2
def divide(n1, n2):
    return n1 / n2

operations = {
    "+" : add,
    "-" : subtract,
    "*" : multiply,
    "/" : divide
}

num1 = int(input("What's the first number? "))
for symbol in operations:
    print(symbol)
operation_symbol = input("Pick an operation from the line above: ")
num2 = int(input("What's the second number? "))
calculation_function = operations[operation_symbol]
answer = calculation_function(num1, num2)

print(f"{num1} {operation_symbol} {num2} = {answer}")

Third to the last line in the code, calculation_function as variable gets assigned with the value of whatever the user entered as operation symbol (which I assume the words: add, subtract, multiply & divide) that is from the dictionary.
Then the next line suddenly it will get the value of num1 and num2 to do the operation (now as a call to a function). I really don't get it, I see the value of the answer variable as (for example:) 1 add 1
Please help..
For reference, I'm on 10th Day of Python 100 Days of Code , final project being the Calculator.


text:
Q: How do I add 2 players and give them cards ? [Python] i'm new to OOP and I've been stuck in writing this for the past hour. I just don't understand how to assign the deck I created to 2 players !
Classes
class Card:
    def __init__(self, faceNum, suitNum):
        self.faceNum = faceNum
        self.suitNum = suitNum

    def getCardName(self):
          nameSuit = ['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King']
          nameFace = ['Coeur','Pique','Carreau','Trèfle']
          return "%s of %s" % (nameFace[self.faceNum], nameSuit[self.suitNum])

    def __str__(self):
        carte_print1 = str(self.faceNum)
        carte_print2 = str(self.suitNum)
        return carte_print1 +('-')+ carte_print2

class Player:
    def __init__(self,ID,Card):
        self.PlayerID = ID
        self.CardForPlayer = Card

Main code
import random

playerA = list()
playerB = list()
deck = list()

def deck():
    deck = []
    for suitNum in range(13):
    for faceNum in range(4):
        deck.append(Card(faceNum, suitNum))
    return deck

deck = deck()
random.shuffle(deck)
for card in deck:
    print(card.getCardName())

Now I just need to give 2 player an equal amount of cards how do I do this ?!

A: So there should be an attribute in the Player class with the name like deck. Modify your Player class like this.
class Player:
    def __init__(self,ID,deck):
        self.PlayerID = ID
        self.deck = deck # this will hold a list of Card objects

Now in your main code, at the end of what you've written, add the following lines.
player1 = Player(1, deck())
player2 = Player(2, deck())


text:
Q: PHP Alphanumeric Regular Expression I am new to PHP, and very new to Regular Expressions. I am currently trying to write a Regular Expression that makes sure the characters are all Alpha Numeric, and that accepts other characters a well. I would like to accept áéíñóúüÁÉÍÑÓÚÜ and @.+-. To accept all alphanumeric characters, and the symbols @.+-. I use the expression:
if (!preg_match("!^[\w@.-]*$!")

Also, before I continue I would like to add. These are values being grabbed from a form input, and they should all be one word phrases (as in no spaces). Ok now lets continue! :D Now I want to grab the characters áéíñóúüÁÉÍÑÓÚÜ as well. When I use the expression:
if (!preg_match("/[\wáéíñóúüÁÉÍÑÓÚÜ@.\+-].*/")

It does not seem to work, could anyone please help? If you are confused, or it is worded bad just ask and I will rewrite it :)
UPDATE
My expression:
if (!preg_match("!^[\w@.-]*$!")

does work, it is the other one that is not working. Thank You! :)
UPDATE 2
Now when I try the expression:
if (!preg_match("~^[\p{L}\p{N}@+._-]+$~", $email)) {

with the input of michael.jonesáéí@gmail.com it raises a error. There error it raises is "Email contains restricted characters." because I made it say that. Here is the specific code I am using:
<?php
if (!preg_match("~^[\p{L}\p{N}@+._-]+$~", $email)) {
?>

 Email contains restricted characters.

<?php } ?>
                                                }

and here is all of the code I am using:
<?php
                                if ($_POST) {
                                    $emailtest1 = False;
                                    $emailtest2 = False;
                                    $emailtest3 = False;
                                    $emailtest4 = False;
                                    $emailtest5 = False;

                                    // Test #1 - Makes sure there is a input

                                    if(empty($_POST['email'])) {
?>

 Please enter your email.

<?php
                                    }

                                    else {
                                        $emailtest1 = True;

                                        // Test #2 - Makes sure it does not already exist

                                        $usernamequery = "SELECT 1 FROM users WHERE email = :email";

                                        $usernameparams = array(':email' => $_POST['email']);

                                        try{
                                            $emailstmt = $connection->prepare($usernamequery);
                                            $emailresult = $emailstmt->execute($usernameparams);
                                        }

                                        catch(PDOException $ex){
                                            echo ("Failed to run query: " . $ex->getMessage());
                                        }

                                        $emailcolumns = $emailstmt->fetch();

                                        if($emailcolumns){
?>

 This email already exists.

<?php
                                        }

                                        else {
                                            $emailtest2 = True;

                                            // Test #3 - Makes sure it fits the length requirements

                                            if(strlen($email) < 5 ) {
?>

 Email is to short.

<?php
                                            }

                                            elseif(strlen($email) > 75 ) {
?>

 Email is to long.

<?php
                                            }

                                            else {
                                                $emailtest3 = True;

                                                // Test #4 - Makes sure it does not have any restricted characters

                                                if (!preg_match("~^[\p{L}\p{N}@+._-]+$~", $email)) {
?>

 Email contains restricted characters.

<?php
                                                }

                                                else {
                                                    $emailtest4 = True;

                                                    // Test #5 - Makes sure the email is valid

                                                    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
?>

 Not a valid email.

<?php
                                                    }

                                                    else {
                                                        $emailtest5 = True;

                                                        // Final Check

                                                        if (($emailtest1 = True) and ($emailtest2 = True) and ($emailtest3 = True) and ($emailtest4 = True) and ($emailtest5 = True)) {
                                                            // Email is valid! :D
                                                        }

                                                        else {
?>

 There is a error.

<?php
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
?>

A:
Regex to accept all alphanumeric characters, and the symbols @.+-.

^[\p{L}\p{N}@+.-]+$

Your regex ^[\w@.-]*$ won't match the accented characters. That is \w would match only the English alphabets,  digits 0-9 plus the underscore symbol.

*

*\p{L} matches any kind of letter from any language

*\p{N} matches any kind of numeric character in any script.

*+ after the char class would repeat the previous token one or more times. I suggest you to use + instead of * because * repeats the previous token zero or more times. So it matches empty strings also.
DEMO
Update:
You ust need to include the unicode modifier u, so that it would make \p{L} to match accented characters.
if (!preg_match("~^[\p{L}\p{N}@+._-]+$~u", $email)) {


text:
Q: How to redirect port 8080 with apache? I'm running a tomcat webserver on port 8080 behind a apache2, and want to redirect some ports.
For testing, I'm trying to redirect to an invalid location, as follows:
<VirtualHost *:80>
        ProxyPreserveHost On
        RequestHeader set X-Forwarded-Proto "http"

        ProxyPass / http://127.0.0.1/test80
        ProxyPassReverse / http://127.0.0.1/test80
</VirtualHost>

<VirtualHost *:8080>
        ProxyPreserveHost On
        RequestHeader set X-Forwarded-Proto "http"

       ProxyPass / http://127.0.0.1/test8080
        ProxyPassReverse / http://127.0.0.1/test8080
</VirtualHost>

Result:
The :80 redirect works as expected.
BUT accessing :8080 shows the tomcat manager starting page, instead of the redirect. Why?
Somehow it seems as if the apache2 could not take control of that port?

A: I guess there is no Listen 8080 option in your apache config files. Just adding the port to a VirtualHost is not enough.
check one of these files (based on your distribution) for Listen options and add one for port 8080:
# /etc/apache2/ports.conf     [On Debian/Ubuntu]
# /etc/httpd/conf/httpd.conf  [On RHEL/CentOS]

more info here: https://www.tecmint.com/change-apache-port-in-linux/
But as mentioned in the comments, you cannot have two services listening on the same port. You have to change the tomcat listening port for this to work.


text:
Q: Flutter WEB: Detect when app is killed (window/tab is closed) Is there a way to detect when a Flutter WEB app is killed ?
I found that it's possible to use 'onBeforeUnload':
html.window.onBeforeUnload.listen((event) async{
  // do something
});

But I can't figure out how to use it.
I'm in need of obtain the session time duration of a user and send data with a ws when window is closed.
If someone could help me with an example of how to use onBeforeUnload(), it'll be really helpful.

A: It should be casted into the BeforeUnloadEvent before setting the returnValue
import 'dart:html' as html;

...

html.window.onBeforeUnload.listen((event) {
  if (event is html.BeforeUnloadEvent) {
    event.returnValue = 'Some return value here';
  }
});


text:
Q: TSQL Insert Into Table From * delimited field I have a table with one column containing millions of rows of asterisk delimited values.
I have been trying a straightforward insert statement that would be fast. Below is a pseudo code of what I tried
Test Table contents of the [cds] field:
bobo11*bobo12*bobo13
bobo21*bobo22*bobo23
bobo31*bobo32*bobo33

SQL:
INSERT INTO TestTable2
(boboA,boboB,boboC)
SELECT '''' + REPLACE(cds,'*','''' + ',' + '''') + '''' FROM Test Table

The trouble is that even though I do have the correct number of columns,
the statement above is not recognized and comes back with the error message:

The select list for the INSERT statement contains fewer items than the
  insert list. The number of SELECT values must match the number of
  INSERT columns.

A: You need to actually parse out the values.  With the values that you have, you can just do:
INSERT INTO TestTable2(boboA, boboB, boboC)
    select left(cds, 6), substring(cds, 8, 6), right(cds, 6)
    from TestTable;

A: You cannot build dynamic columns list in the static query. You have to split the column values and insert them. You can try the following query instead
INSERT INTO TestTable2
(boboA,boboB,boboC)
SELECT PARSENAME(REPLACE(cds,'*','.'),3)
      ,PARSENAME(REPLACE(cds,'*','.'),2)
      ,PARSENAME(REPLACE(cds,'*','.'),1)
FROM TestTable

A: Small example to create dynamic sql with XML PATH
DECLARE
    @sql nvarchar(max) ;

SET @sql = 'INSERT INTO TestTable2(boboA,boboB,boboC)VALUES' + (
select
'('''+REPLACE(A,'*',''',''')+'''),'
from Test
FOR XML PATH(''));

SET @sql = SUBSTRING(@sql,1,LEN(@sql)-1);

print @sql


text:
Q: create bind volumes with docker compose v2 I want to create volumes using docker compose.
I've listed all volumes in a yaml file volumes.yaml:
version: '3'

volumes:
  a_volume:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: "/opt/volumes/a_volume"
    name: "a_volume"

  b_volume:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: "/opt/volumes/b_volume"
    name: "b_volume"

Then using docker-compose v1 (1.29.0) I can create all volumes this way:
docker-compose -f volumes.yaml up
Creating volume "a_volume" with local driver
Creating volume "b_volume" with local driver
Attaching to

Using docker-compose v2 (2.5.0) I don't know how to do it, the command has no effect:
docker compose -f volumes.yaml up
no service selected

UPDATE:
Define a dummy service like this:
version: '3.8'

services:

  dummy:
    image: rwgrim/docker-noop
    volumes:
      - a_volume:/tmp
      - b_volume:/tmp

volumes:
  a_volume:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: "/opt/volumes/a_volume"
    name: "a_volume"

  b_volume:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: "/opt/volumes/b_volume"
    name: "b_volume"

docker-noop simply doesn't do anything (no operation).
Volumes will be created using docker compose up command.


text:
Q: Expand textarea (and bring it to front) while it has the focus I want to expand a textarea (increase the height) as long as it has the focus. When expanded, the textarea should not move the content down, instead it should be displayed above the other content.
This is the code I'm using so far (see here for an example):
$(document).ready(function () {
    $('#txt1').focus(function () {
        $(this).height(90).css('zIndex', 30000);
        $('#txt2').val('focus');
    });
    $('#txt1').blur(function () {
        $(this).css('height', 'auto');
    });
});

The expanding of the textarea works fine, but I can't get it to display above the other elements on the page (it is displayed behind the elements which follow).
Are there any tricks to show the expanded textarea above/in front of all other elements?
Update: this is the (minmal) HTML code used to reproduce the problem:

first:

   <textarea id="txt1" rows="1" cols="20"
     style="width: 400px; height: 12px; font-size: 10px;">
   </textarea>

second:

<input type="text" id="txt2"/>

A: Setting position on the textarea works. You can also get rid of the z-index.
Working demo

A: Adding a z-index does nothing without the element having a position other than static. Personally, I would add a class with all of the css changes and include an overlay, like this (demo):
CSS
.focused {
    position: relative;
    height: 90px !important;
    z-index: 1000;
}
.overlay {
    display: block;
    position: absolute;
    height: auto;
    bottom: 0;
    top: 0;
    left: 0;
    right: 0;
    margin: 0;
    background: #000;
    opacity: .75;
    filter: alpha(opacity=75);
    z-index: 999;
}

Script
$(document).ready(function () {
    $('#txt1').focus(function () {
        $('
').appendTo('body');
        $(this).addClass('focused');
        $('#txt2').val('focus');
    });
    $('#txt1').blur(function () {
        $(this).removeClass('focused');
        $('.overlay').remove();
        $('#txt2').val('blur');
    });
});

A: Try setting the style 'position:absolute;' on the first textarea (txt1) and that should do the trick.

A: Try this plug-in.  Should be quick and simple: http://unwrongest.com/projects/elastic/

A: working fiddle with input and textarea, mostly css with a little jquery for positioning
http://jsfiddle.net/Ap5Xc/


text:
Q: How to pass a function into a map of another object I'm trying to create a table with a row for each object in an array, but I also want each row to contain a Button with a custom onClick function that is inherited from the row creator:
var React = require('react');
import {Button} from 'react-bootstrap';
...

export class ObjectTable extends React.Component {
  render() {
    return (

          ...

            {
              this.props.objects.map(
                function(object) {
                  return <TableRowWrapper key={object.id} object={object} action={this.props.action} />;
                  }
                )
            }

    )
  }
};

var TableRowWrapper = React.createClass({
  ...
  render() {
    return (

        <Button onClick={this.props.action}>Object 1</Button>

    )
  }
});

Both objects and action are passed to <ObjectTable /> as props, and in any other element within the ObjectTable class I'd be able to call {this.props.action} to get it.
However, it doesn't work when I try to call from within the objects map (presumably because this no longer refers to ObjectTable). I've read the examples in map Method (Array) (JavaScript), but I can't do this.props.objects.map(function(object, this) {..., or any other permutation of this.props, this.props.action, etc. either.
What's the correct way to do this?

A: Use arrow functions
export class ObjectTable extends React.Component {
  render() {
    return (

          ...

            {
              this.props.objects.map(
                (object) => {
                  return <TableRowWrapper key={object.id} object={object} action={this.props.action} />;
                  }
                )
            }

    )
  }
};

A: You need to store a reference to the original this and use it in the map callback function:
export class ObjectTable extends React.Component {
  render() {
    var self = this;
    return (

          ...

            {
              this.props.objects.map(
                function(obj) {
                  return <TableRowWrapper key={obj.id} object={obj} action={self.props.action} />;
                  }
                )
            }

    )
  }
};


text:
Q: How to access local files other than JSON with react-native I need to parse a local .csv file that I include somewhere between all the js files (like some kind of local ressource).
I found a library that does the job > Papaparse. But it seems like it can't "download" my local file due to incompatibilities with the Javascript-Environment.
I guess it would work if I can somehow just pass the content of my local csv file to papaparse as a string. But I can't figure out how to get the content of local csv-file inside a variable with react-native.
Any Suggestions?
EDIT:
I've tried it with react-native-fs. I put my csv-file under android/src/main/assets/ and try to access it with
RNFS.readDirAssets('/');
-> Output is this:
08-11 14:53:14.524 17058 17202 I ReactNativeJS: [ { ctime: null,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     mtime: Invalid Date,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     name: 'AndroidManifest.xml',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     path: '//AndroidManifest.xml',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     size: 0,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isFile: [Function: isFile],
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isDirectory: [Function: isDirectory] },
08-11 14:53:14.524 17058 17202 I ReactNativeJS:   { ctime: null,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     mtime: Invalid Date,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     name: 'META-INF',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     path: '//META-INF',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     size: 0,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isFile: [Function: isFile],
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isDirectory: [Function: isDirectory] },
08-11 14:53:14.524 17058 17202 I ReactNativeJS:   { ctime: null,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     mtime: Invalid Date,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     name: 'assets',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     path: '//assets',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     size: 0,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isFile: [Function: isFile],
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isDirectory: [Function: isDirectory] },
08-11 14:53:14.524 17058 17202 I ReactNativeJS:   { ctime: null,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     mtime: Invalid Date,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     name: 'classes.dex',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     path: '//classes.dex',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     size: 0,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isFile: [Function: isFile],
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isDirectory: [Function: isDirectory] },
08-11 14:53:14.524 17058 17202 I ReactNativeJS:   { ctime: null,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     mtime: Invalid Date,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     name: 'lib',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     path: '//lib',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     size: 0,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isFile: [Function: isFile],
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isDirectory: [Function: isDirectory] },
08-11 14:53:14.524 17058 17202 I ReactNativeJS:   { ctime: null,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     mtime: Invalid Date,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     name: 'res',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     path: '//res',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     size: 0,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isFile: [Function: isFile],
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isDirectory: [Function: isDirectory] },
08-11 14:53:14.524 17058 17202 I ReactNativeJS:   { ctime: null,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     mtime: Invalid Date,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     name: 'resources.arsc',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     path: '//resources.arsc',
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     size: 0,
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isFile: [Function: isFile],
08-11 14:53:14.524 17058 17202 I ReactNativeJS:     isDirectory: [Function: isDirectory] } ]
It seems like my assets folder is always empty.

A: I've managed to access my csv file:
Placed it inside:
android/app/src/main/assets/myFile.csv

(I've created the assets folder myself)
I was able to get the csv-data as string with the following code:
const csvFile = RNFS.readFileAssets('myFile.csv', 'ascii').then(file => {
            return file;
        });

In my case, the file was ascii-encoded, so I've put the encoding 'ascii' as second argument, otherwise I would get some error saying "invalid continuation byte".


text:
Q: Array with dynamic field names I am passing this function different field names on each call.  I would like it to post the interpolated string value of the variable field as the name of the posted var.  Eg one post might have
data: { 'shoppingCartContents' : cartrow, 'number' : number, 'foo' : value }

but every post just has
data: { 'shoppingCartContents' : cartrow, 'number' : number, 'field' : value }

even though field is not in quotes.
function update_personalization(cartrow, number, field, value) {
  $.ajax({
    type: 'POST',
    url: 'updatePersonalization.php',
    data: { 'shoppingCartContents' : cartrow, 'number' : number, field : value }
  });
}

What am I doing wrong?

A: You'll have to build the object differently:
   data: (function() {
     var rv = {shoppingCartContents: cartrow, number: number};
     rv[field] = value;
     return rv;
   })()

What that does is build up the object you want to pass as "data" in a little anonymous function. The function initializes a simple object with the static field names, then adds the dynamically-named field in a separate statement.
That's not really an "array", for what it's worth.


text:
Q: If change element in DOM with JS not working event I have a function that changes a table in a list, so far so good, but when the function changes in js it stops working, if I reload the page it works but if I change the DOM nothing. Can you help me?
$(document).ready(function() {
    $('#table-list tbody tr').click(function(event) {
        if(event.target.type == 'checkbox'){
        }else{
            $(':checkbox', this).trigger('click');
        }
    });

    $('#ul-list li').click(function(event) {
        var checkbox_type = $(event.target).find("input[type='checkbox']").attr('name');
        if(checkbox_type){
            $(':checkbox', this).trigger('click');
        }
    });

});

These are the two events that should always be active. But if I change the table to ul not it works
So let me explain better, I have a table like this:

      <input type="checkbox" name="1" />

      <input type="checkbox" name="3" />

Then by clicking on a button I convert it to a list by removing the table from the DOM and inserting this:

      <input type="checkbox" name="1" />

      <input type="checkbox" name="3" />

Now I want if I try to click on the list this function should start:
$('#ul-list li').click(function(event) {
        var checkbox_type = $(event.target).find("input[type='checkbox']").attr('name');
        if(checkbox_type){
            $(':checkbox', this).trigger('click');
        }
    });

instead no.

A: If you rewrite the DOM, you need to DELEGATE
$('#ul-list').on("click","li",function(event) {

I though you might need this - see the stopPropagation when the target is one of the checkboxes itself:

function findCheck(e) {
  const tgt = e.target;
  if (tgt.type && tgt.type === "checkbox") {
    e.stopPropagation()
  } else {
    const $row = $(e.currentTarget);
    $row.find("[type=checkbox]").each(function() {
      $(this).click();
      //$(this).attr("checked", !$(this).attr("checked"))
    });
  }
}

$(function() {
  let $ul = $("
", {
    id: "ul-list"
  });
  const $tbl = $("#table-list");
  $tbl.find("tr").each(function() {
    let $li = $("
")
    $("td",this).each(function() {
      $li.append($(this).html())
    })
    $ul.append($li);
  })
  $tbl.replaceWith($ul)
  $('#ul-list').on("click", "li", findCheck)
})
tr {
  background-color: red
}

li {
  background-color: red
}

      1
      <input type="checkbox" name="1" />
      <input type="checkbox" name="2" />

      2
      <input type="checkbox" name="3" />


text:
Q: Convert.ToDateTime runs slow when culture changed I changed culture to Persian in my PC, after that my app load database slower about five times because of this line:

Convert.ToDateTime(someString)

what is problem? and what I should do to fix it?
UPD1: example of string 2010-08-03 00:00:00.000
UPD2: I measure with this following code:
        string s = "2010-08-03 00:00:00.000";
        DateTime start = DateTime.Now;
        int n = (int)5e6;
        for (int i = 0; i < n; i++)
        {
            DateTime date = Convert.ToDateTime(s);
        }
        DateTime finish = DateTime.Now;
        Console.WriteLine(finish - start);
        Console.ReadKey();

in default(AD) calendar:(~5 seconds)

00:05:48

and when I change calendar to Persian in windows 10:(~4 minutes)

03:51:73

A: It is not documented, so this can be wrong at anytime, but I am guessing that DateTime.Parse (or Convert.ToDateTime) will try all available formats(in current culture) to parse the string. And it just happens that it starts from the format that does not match with your string. Therefore, several failures before getting to the right one. Which results to longer time to complete the process.
To get exact (well approximately) same performance I would recommend using DateTime.ParseExact or DateTime.TryParseExact and specify the Culture Invariant format. For ex:
string s = "2010-08-03 00:00:00.000";
string format = "yyyy-MM-dd HH:mm:ss.fff";
DateTime date = DateTime.ParseExact(s, format, CultureInfo.InvariantCulture);

Reference: Is DateTime.ParseExact() faster than DateTime.Parse() . But note that the accepted answer is not correct.


text:
Q: How to install SGP4 V 1.4 package in Python 3.6 First post hear and relatively new coder. Trying to get this package: https://pypi.python.org/pypi/sgp4/ to work, only I have no idea what I'm doing. I'm not familiar with the file extension (.tar.gz) and I don't know if this is a module or what and how to install it and get it to work. I am using python 3.6.4 currently. Apologies that this is a pretty dumb question, but I'm trying to learn towards the goal of adding to this script so that I can build a tracking capable ground station.
Any and all help appreciated.
Thank you for your time,
Lorcan.

A: The SGP4 MATLAB version returns the satellite's state vector in four coordinate systems i.e. TEME, ITRS, GCRS, and TOD. The SGP4 Python version returns the satellite's state vector in three coordinate systems i.e. TEME, ITRS, and GCRS. You can use my Python version of SGP4 from the following link: https://www.researchgate.net/publication/358351066_SGP4_Python_code or you can use my MATLAB version of SGP4 from the following link: https://www.researchgate.net/publication/346217793_SGP4_MATLAB_code In the SGP4 Python version, it is mentioned which packages you need to install and how to install them.

A: Did you try using
pip install sgp4

from a terminal window? That should handle the actual download and installation for you as well as resolving any dependencies.


text:
Q: User Standard Controller populate output fields with logged in user details Thanks anyone for listening. I have added a section to our User page layout consisting of 14 custom fields that are used to track sales performance (most use the DLRS app to roll up data from opportunities).  I want to create a Visualforce tab that users can click on to easily view this data.  I have zero experience with Apex but went about it two ways:
(1) using the $User fields which is perfect as it retrieves the logged in user details but doesn't follow the field format (i.e. % values displayed as decimal)
(2) using StandardController="User".  This looks much nicer from a formatting standpoint but I can't figure out how to get it to display logged in user data without manually updating the URL.
Assuming I have to write an apex class to query this data, would someone be able to help me get started?  I really want to learn and feel like if I knew how to start I could build off of that for future development. Thanks
Sample (1)
<apex:pageBlockSection title="Sales Performance" columns="4">
        <apex:pageBlockSectionItem >
         <p> Sales Target </p>
         <p> Open Pipeline </p>
         <p> Won Opps Year to Date </p>
         <p> Lost Opps Year to Date </p>
         <p> Shortfall </p>
         <p> Nbr of Closed Opps </p>
         <p> Nbr of Open Opps </p>
      </apex:pageBlockSectionItem>
       <apex:pageBlockSectionItem >
         <p> ${!$User.Sales_Target__c} </p>
         <p> ${!$User.Open_Pipeline__c} </p>
         <p> ${!$User.WonOpps_CY__c} </p>
         <p> ${!$User.LostOpps_CY__c} </p>
         <p> ${!$User.Shortfall__c} </p>
         <p> {!$User.Nbr_Closed_Opps__c} </p>
         <p> {!$User.Nbr_Open_Opps__c} </p>
</apex:pageBlockSection>

Sample (2)
<apex:page standardController="User">
 <apex:pageBlock title="Sales Target Tracking">
   <apex:pageBlockSection title="Sales Performance">
     <apex:pageBlockSectionItem >
       <apex:outputField value="{! User.Sales_Target__c }"/>
       <apex:outputField value="{! User.Win_Rate__c }"/>
       <apex:outputField value="{! User.Open_Pipeline__c }"/>
       <apex:outputField value="{! User.Loss_Rate__c }"/>
       <apex:outputField value="{! User.WonOpps_CY__c }"/>
     </apex:pageBlockSectionItem>
    </apex:pageBlock>
 </apex:page>

A: Typically, in order to avoid writing a controller, you'd add a button or link on the user detail page. If you want it as at tab, you can, but you'll have to do a bit of trickery. The following code should work:
<apex:page standardController="User"
    action="{!IF(ISBLANK($CurrentPage.parameters.id), URLFOR($Page.theSamePage,
        $User.Id, [id=$User.Id]), null)}">

This basically says "If the current page's Id parameter is blank, redirect to the same page but with the id parameter set to the current user Id." Make sure to replace theSamePage with the page's name.


text:
Q: Динамические псевдонимы полей в mysql Возможно ли в MySQL добавлять динамически псевдонимы полей?
Пример:
3 таблички, из 1 вытаскиваем определенные поля, а 2 другие по join-у. В одной значения, в другой коды полей:
SELECT ...
       table_1.value,
       table_2.code,
FROM table
LEFT JOIN `table_1` ON `table_1`.table_id = `table`.id
LEFT JOIN `table_2` ON `table_2`.ID = `table1`.table_2_id
WHERE ...

На выходе 6 одинаковых с позиции table записей с разными полями table_1.value и table_2.code.
Можно ли сделать, чтобы на выходе была одна строка c дополнительными 6 полями:
table_field_1 table_field_2 ... table_1_value_as_field_name * 6

То есть, одна строка на выходе и 6 полей из сджоиных таблиц, который имеют псевдонимы в виде table_2.code и значения table_1.value.


text:
Q: Intersection of meaning between Lebesgue Measure and Natural Density FYI: the articles linked and their content within are well-known in number theory, so number theory is a tag (correct if need be).
$\textbf{Background}$: This article by Maier states that a given statement is true "for almost all values of $x$" (see page 1 paragraph 2). The article then continues with "By 'for almost all values of $x$' is meant that $x \to \infty$ through any sequence lying outside a certain exceptional set $\mathcal{E}$ of $x$-values, for which the Lebesgue measure of $\mathcal{E} \cap (0, u]$ is $o(u)$ for $u \to \infty$." A different article by Richards comments on the same statement in a sightly different manner: "[the statement] is true for most values of $x$, that is the set of values of $x$ for which [the statement] holds has asymptotic density one as $x \to \infty$." Richards then follows up by stating that asymptotic density one for a set $S$ of positive real numbers means "measure$(S \cap [0, x])/x \to 1$ as $x \to \infty$." I understand both of these renditions of the same claim to be also given using natural density: [the statement] is true for $x \in S$ where $t(x)/x \to 1$ as $x \to \infty$ and $t(x)$ is the number of elements in $S$ no greater than $x$.
$\textbf{Question}$:

*

*Are all three of these renditions equivalent? Is there any difference between them?

*The Lebesgue measure of a countable set of real numbers is $0$, so how is the Lebesgue measure of $\mathcal{E} \cap (0, u]$ not equal to zero? I understand that $\mathcal{E}$ may indeed be uncountable, but this is not given as a fact.

*When considering sets of real numbers, how do Lebesgue measure and measure differ, and how do these two concepts related to the natural density of the sets that they are involved in? My understanding is that Lebesgue measure has a vastly different meaning than natural density, so I am confused on how they provide similar meanings in this context.

Any help would be nice, thanks.

A: Suppose $P(x)$ is a property which may hold for $x\in[0,\infty)$. Here are two different properties that $P$ may satisfy, though they are by no means exhaustive. (Throughout, "measure" refers to Lebesgue measure.)

*

*$\mathrm{measure}(\{x:P(x)\ \text{fails}\}) = 0$. In this case, we say that $P(x)$ holds for (Lebesgue-)almost every $x$.

*For some "exceptional" set $\mathcal E\subset[0,\infty)$, we have
$$
\lim_{u\to\infty}\frac{\mathrm{measure}(\mathcal E\cap[0,u))}{u} = 0,
$$
and $P(x)$ fails for all $x\in \mathcal E$. In this case we say that $P(x)$ holds for a set with asymptotic density $1$.  The limit condition means that the exceptional set has "asymptotic density zero," but it is certainly possible that $\mathcal E$ can have positive Lebesgue measure, so the set of $x$ where $P(x)$ fails in this case can be larger than the set of exceptional $x$ in the first case. There is nowhere specified that $\mathcal E$ needs to be countable in this case. For example, $\mathcal E$ could be the interval $[0,500)$, which has measure $500$. Check that for this example, the limit above still holds.
Briefly, Lebesgue measure and "measure" often mean the same thing in the context of the real number line, but there are other "measures" besides the Lebesgue measure. Asymptotic density refers to quantities such as the limit appearing in 2., and it has little to do with the Lebesgue measure in spite of "measure" appearing in the definition of the limit. If a property $P(x)$ holds for Lebesgue-almost every $x$, this is much stronger than $P(x)$ holding on a set of asymptotic density $1$.


text:
Q: Find variable in json php loop I need to find a phone number in a json array with php. i was trying foreach but the issue is if the phone number is not found I get multiple records. Is there anyway to write the else so I only get 1 response. I need to post back if the phone is not found but it creates a record for each not found record.
My response looks like this
Not found
Not found
found
Not found
Not found
I need 1 Not found not multuple.
$curl = curl_init();
$usertype='x-cw-usertype: integrator';

   curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
   curl_setopt($curl, CURLOPT_URL, "/apis/3.0/company/contacts");
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
   curl_setopt($curl, CURLOPT_HTTPHEADER, array(

             'Authorization: basic ' . base64_encode($username . ':' . $password),
             'clientId: ',

             $usertype,

 'Content-type: application/json'

       ));

$response = curl_exec($curl);
curl_close($curl);
$json_contacts = json_decode($response, true);
//var_dump($json_contacts);

}

// Loop through Array
foreach ( $json_contacts  as $item ) {

// If a phone number is found
if ( $item['defaultPhoneNbr'] == '5551212' ) {

   echo 'found
';
}

// If phone is not found
else if  ( $item['defaultPhoneNbr'] != '5551212' ){

   echo 'Not found
';

}
}

A: Create variable for storing result. Like:
foreach ( $json_contacts  as $item ) {

// Check item and the return value of
// reset() function is equal then it
// will be the first iteration
if ( $item['defaultPhoneNbr'] == '6102070035' ) {

    // Desplay the array element

    $result = "found";
    break;
 }

// Check if item and return value of
// end() function is equal then it
// will be last iteration
else if  ( $item['defaultPhoneNbr'] != '6102070035' ){

       $result = "not found";
}
}

Then just echo it.
  echo $result;


text:
Q: Immutable state - state change not working I am trying to change the state of an array upon a click event. I have read up on immutability so have created a copy of the array in the method and mutated the copy rather than directly mutating the original. However the state still doesn't update on first click. Is there something I'm doing wrong?
const [details, setDetails] = useState([]);

  const getMovieDetails = () =>{
    fetch("url")
    .then((res)=> {
      return res.json();
    })
    .then((data)=>{
      const newDetails =[...details];
      newDetails.push(data)
      setDetails(newDetails)
console.log(details)
    })
  }


text:
Q: Implementing simpleadapter using HashMap I am retrieving data from sqlite and showing it in a listview using simpleadapter.I don't have any issues regarding Layouts.Still just for your reference :
list_item.xml
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >

    <!-- Name Label -->

    <TextView
        android:id="@+id/subject"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#421fc4"
        android:textSize="16sp"
        android:textStyle="bold" />

        <TextView
            android:id="@+id/day"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:textStyle="bold" />

    <TextView
        android:id="@+id/slot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textColorHighlight="#782086"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/instructor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textColor="#782086"
        android:textStyle="bold" />

</LinearLayout>

I am having problem somewhere in the following code snippet.I tried to retrieve the data from sqlite using normal listview and it worked perfect.But when i used this code snippet for custom listview using SimpleAdapter i get only the last row of the result of the query.That last row's data gets repeated 8 times in the listview as there are 8 rows in the result of the query.
 HashMap<String, String> hashMap = new HashMap<String, String>();
 ArrayList<HashMap<String, String>> Timetablelist;

//c being the cursor
    if  (c.moveToFirst()) {
           do {
                String subject = c.getString(c.getColumnIndex(dba.KEY_SUBJECT));
                String day = c.getString(c.getColumnIndex(dba.KEY_DAY));
                String slot = c.getString(c.getColumnIndex(dba.KEY_SLOT));
                String instructor = c.getString(c.getColumnIndex(dba.KEY_INSTRUCTOR_NAME));
                // adding each child node to HashMap key => value
                hashMap.put("Subject", subject);
                hashMap.put("Day", day);
                hashMap.put("Slot", slot);
                hashMap.put("Instructor", instructor);
                Timetablelist.add(hashMap);
                ListAdapter adapter = new SimpleAdapter(
                                this, Timetablelist,R.layout.list_item, new String[] { "Subject", "Day",
                                "Slot","Instructor" }, new int[] { R.id.subject,
                                R.id.day, R.id.slot,R.id.instructor });
                setListAdapter(adapter);

              }while (c.moveToNext());

                       }

P.S : I was able to retrieve data using normal listview.So database and other layouts are working fine.

A: Move the below out of do While
 ListAdapter adapter = new SimpleAdapter(
                            this, Timetablelist,R.layout.list_item, new String[] { "Subject", "Day",
                            "Slot","Instructor" }, new int[] { R.id.subject,
                            R.id.day, R.id.slot,R.id.instructor });
setListAdapter(adapter);

You get the data from database and you can populate Timetablelist in the do while. But there is no need to initialize adapter everytime and setListAdapter.
Edit:
HashMap<String, String> hashMap ;
ArrayList<HashMap<String, String>> Timetablelist = new ArrayList<HashMap<String,String>>();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
    String subject = c.getString(c.getColumnIndex(dba.KEY_SUBJECT));
    String day = c.getString(c.getColumnIndex(dba.KEY_DAY));
    String slot = c.getString(c.getColumnIndex(dba.KEY_SLOT));
    String instructor = c.getString(c.getColumnIndex(dba.KEY_INSTRUCTOR_NAME));
    // adding each child node to HashMap key => value
    hashMap = new HashMap<String, String>();
    hashMap.put("Subject", subject);
    hashMap.put("Day", day);
    hashMap.put("Slot", slot);
    hashMap.put("Instructor", instructor);
    Timetablelist.add(hashMap);
}
 ListAdapter adapter = new SimpleAdapter(
                            this, Timetablelist,R.layout.list_item, new String[] { "Subject", "Day",
                            "Slot","Instructor" }, new int[] { R.id.subject,
                            R.id.day, R.id.slot,R.id.instructor });
 setListAdapter(adapter);


text:
Q: Executing msp430x instruction but mcu is not a msp430x I am using sky motes in cooja. The simulation for the same code worked fine for first few times but now suddenly the following Contiki error
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) - Executing MSP430X instruction but MCU is not a MSP430X
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) - Stack Trace: number of calls: 3 PC: $02076
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   process_thread_ctimer_process (local in ctimer.c) called from PC: $0674e (elapsed: 23678)
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   call_process (local in process.c) called from PC: $068f2 (elapsed: 23713)
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   process_run (memset.c) called from PC: $04228 (elapsed: 24975)

Java Stack Trace:
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) - org.contikios.cooja.ContikiError
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   at org.contikios.cooja.mspmote.MspMote.execute(MspMote.java:341)
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   at org.contikios.cooja.mspmote.MspMote.execute(MspMote.java:298)
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   at org.contikios.cooja.motes.AbstractWakeupMote$1.execute(AbstractWakeupMote.java:47)
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   at org.contikios.cooja.Simulation.run(Simulation.java:280)
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   at java.lang.Thread.run(Thread.java:745)
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) - Caused by: se.sics.mspsim.core.EmulationException: Executing MSP430X instruction but MCU is not a MSP430X
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   at se.sics.mspsim.core.MSP430Core.emulateOP(MSP430Core.java:1079)
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   at se.sics.mspsim.core.MSP430.stepMicros(MSP430.java:253)
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   at org.contikios.cooja.mspmote.MspMote.execute(MspMote.java:337)
     [java]  INFO [AWT-EventQueue-0] (MessageList.java:261) -   ... 4 more

I am working with latest version of contiki and gcc. I have tried restarting cooja after ant clean. Any idea on how do I solve the problem?

A: As unexpected, the issue was not with the environment. I posted the issue here which helped me.
If the MAX_PAYLOAD_LEN is either too small or too long to fit in the array then this issue occurs. I had set the MAX_PAYLOAD_LEN to 19.


text:
Q: Non-linear regression with simulation as forward model (MATLAB) I am trying to use the build-in non-linear regression function from MATLAB to perform inverse problem solving and find the parameter that will lead to the best fit of the real data.
I already wrote a function: forwardModel(kGuess) that will take a guess as the input, and run the simulation. This function will generate a vector of data.
So I used the function as my forward model and put it into the lsqcurvefit function in MATLAB. However, it won't run and generate the error saying there is not enough input. How can I fix this problem? Or is there other better way to perform non-linear regression with simulation as forward model?
Below is part my code that performs non-linear regression, please take a look!
kGuess = 300;   %initial guess
options = optimoptions('lsqcurvefit', 'Algorithm', 'levenberg-marquardt');
lb = 10;
ub = 1000;
[k,resnorm,~,exitflag,output] = lsqcurvefit(forwardModel, kGuess, time, potentialMeasured, lb, ub, options)
hold on;
plot(time, forwardModel(k));
xlabel('time(days)'); ylabel('potential between electrodes(V)');
hold off;


text:
Q: how to exctract extension in php I am trying to extract extension from string using php and then look inside array. It seems that i do get the extension but when i look inside array it does not work and I cant see a problem. Maybe you could suggest or point me. Thank you.
Here is the code:
$file = '/folder/subfolder/file.mp4' //It can be also a url with domain etc. basically anything

$extension = pathinfo($file);
$final_extension = strtolower($extension['extension']);

$fileArray = array("mp4","mp3");

if (in_array($final_extension, $fileArray)) {
    echo "Found!";
}

A: You can use regex.
This would be pattern: "/.(\w+)$/"
This would be implementation:
if (preg_match('/.(\w+)\/?$/', $file, $matches) { $extension = $matches[1]; }

A: You have a missing ";"
Corrected line below. It should work fine. Tested.
$file = '/folder/subfolder/file.mp4';


text:
Q: total calculation not showing i was trying to compile the sample codes of google and find out the total distance, i believe the scripting isnt wrong..if it was. map of google wont be displayed... there is something missing.. can any one please help..

      Start:
      <select id="start" onchange="calcRoute();">
       <option value="san bernardino, ca">San Bernardino</option>
        <option value="los angeles, ca">Los Angeles</option>
      </select>
      End:
      <select id="end" onchange="calcRoute();">
        <option value="san bernardino, ca">San Bernardino</option>
        <option value="los angeles, ca">Los Angeles</option>
      </select>

A: Try
computeTotalDistance(response)

Instead of
computeTotalDistance(result)`

A: You never call your computeTotalDistance function.  You need to call it in the DirectionsService.route callback function.
     directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        computeTotalDistance(response);
      }

Working example


text:
Q: Automated Bug logging support in Test API I am using SimpleTest API and PHPUnit Test API. Does any of them support automated bug logging support . And if not then how can I will provide this feature ?

A: PHPUnit can, for example, interact with issues in

*

*Trac ( https://github.com/sebastianbergmann/phpunit-ticketlistener-trac )

*GitHub ( https://github.com/sebastianbergmann/phpunit-ticketlistener-github )

*and a couple others: http://pear.phpunit.de/
Buiding one that fits your propose sure is possible.
Also there are other ways to make PHPUnit tell you what is happening like

*

*Test listeners. Where you can really act on everything PHPUnit does.

*The xml or json output. That you can parse and act on it accordingly


text:
Q: couldn't get a good image quality when used DOM to Image I'm working on a meme editor web app using DOM to image library and FileSaver.JS to save the image.
Saving the image using the PC screen is somewhat good, but when it's saved using the phone screen the image that shows up is a pixelated image.
Here is the div that I need to save:

                        People struggles with making memes for free

                        Instant Memes:

Also, here is my code for the function that saves the image:
function generateMeme(){

var options = {
    quality: 1,
};

var alertMsg = "*********** Please Read *********** \n";
alertMsg += "Image must be saved in your device \n";
alertMsg += "If you didn't get the image that you want try again, otherwise, feel free to get in touch with us \n";
alertMsg += "*********** Thanks for reading ***********";

domtoimage.toBlob(document.getElementById('theUserMeme'), options)
.then(function (blob) {

    alert(alertMsg);
    window.saveAs(blob, 'instant meme.jpeg');
});

}

Also, here is my CSS code for the parts of the meme:
    #memeWords{

    font-size: 25px;
}

#theUserMeme{

    background-color: white;
}

What the issue could be? Why it is happening? How to fix it?


text:
Q: Any compliant way to connect a USB C dongle to a computer with legacy (USB A) ports only? The simplest solution would be to use an adapter with USB A male on one end and USB C female on the other. These are readily available, and would even work fine for the purpose, but are unfortunately against USB spec. I've done a lot of reading on this and understand why now (it makes it possible to connect it to another C to legacy adapter and lose the assurance that only one end believes it's the host, so USB-IF prevent this by only certifying C to legacy adapters where the C end is male).
But for someone who just wants to plug in a USB-C dongle to a USB 3 type A port it seems the non-spec way is the only real option, short of buying a new USB-C host (e.g., in the form of a PCIe card, or hub - if even that is to spec).
Is that true? If so, it seems dongles with a non-removable male USB C connection are fairly limited in use at least in a world where "legacy" type A sockets are still common.


text:
Q: "A car is in the garage" versus "There's a car in the garage" We say

"There is a car in the garage."  and
  "There are three cars in the
  garage."

Is it also correct to say

"A car is in the garage."  and
   "Three cars are in the garage."

If yes, is there any difference between them, or do they exactly mean the same?

A: The Original Poster's four examples are all grammatical. However, the sentences with there are preferable in most situations. The reason is that the phrases a car and three cars are indefinite. A car uses the indefinite article a, not the. The phrase three cars doesn't use the word the, as in the three cars. It's also therefore indefinite. This means that we haven't been speaking about the car or the three cars before.
In English we don't like to use indefinite noun phrases as Subjects. We like to put old information, stuff that we have already talked about, at the beginning of the sentence. If we put indefinite noun phrases at the beginning of the sentence, the sentence is more difficult for listeners to process.
If a sentence uses the verb BE, we can avoid this problem by using an existential sentence. We can use there is or there are. This moves the new information to later in the sentence where it is easier for the listener to process. Look at the following groups of sentences:

*

*A cafe is on the corner.

*A riot was in the West End.

*An accident was on the motorway.

*A meeting is at 2 o'clock in the main hall.

*A God is in heaven.

The sentences above are all grammatical, but they are strange and awkward. There may be some special time when want to say these sentences like this, but usually they are not a natural way of phrasing the sentence. If you generally speak like this, people will find it difficult to understand you, and they will know that your English is not very good.
If we use an existential construction instead (there is or there are), the sentences become completely natural:

*

*There's a cafe on the corner.

*There was a riot in the West End.

*There was an accident on the motorway.

*There is a meeting at 2 o'clock in the main hall.

*There's a God in heaven.

Notice that the problem in the first group of sentences is that we used indefinite noun phrases. If we use definite noun phrases, the sentences become completely natural. Look at these versions of the sentences:

*

*The cafe is on the corner.

*The riot was in the West End.

*The accident was on the motorway.

*The meeting is at 2 o'clock in the main hall.

*God is in heaven.

Those sentences sound like native-speaker sentences.
Conclusion
All four sentences are grammatically well-formed. However, the sentences with there are more natural, and will make you sound like a better English speaker. They will also make it easier for the person listening to you.

A: All four of your sentences are valid. "There is a car ..." and "A car is ..." mean the same thing.
In context, the "there is an X" form can be used to emphasize that the thing really exists, while "X is" simply assumes it. Like if someone said, "What? You have a car now?", you might reply, "Yes, there is a car in my garage". You're emphasizing that it's really there. The "X is" form tends to put the emphasis more on what follows, with the existence of X taken for granted.
Maybe this would make more sense with an example where the claim of existence is more controversial. For example, if someone said, "God is in Heaven", that would normally be understood to mean that the question of God's existence is accepted, and what we are debating is where he is. But, "There is a God in Heaven" is an assertion that God exists, with the claim that he is in Heaven a secondary issue.


text:
Q: How to create a link to a markdown header in databricks? I would like to reference a markdown cell inside a databricks workspace from another markdown cell.
The reference cell is the following:
%md
[business questions](#buisiness-questions)

The referenced cell look like this:
%md
# Buisiness Questions

If I click on the link then it will navigate me to the home page because it can not find the  link.
I have managed to reference the cell according to documentation using HTML hyperlink tag. However, the workspace and notebook, and cell IDs are hard-coded so anytime it is changed, adaptation is necessary.
%md
business questions

How to link a markdown header without hardcoding any IDs?

A: As @Saideep Arikontham mentioned there is no way to retrieve the cell's URL programmatically. Fortunately, the cell's URL is not changed if the cell's order or content changes. It will also not change if the workspace is detached from the cluster or restarted.
Therefore it is safe to use the hyperlink tag for referencing the cell.
%md
business questions

NOTE: Be aware that if the cell is deleted then the cell URL is also removed. So cell URL adaptation would be necessary. More information about identifiers.


text:
Q: What does scrap mean here? https://www.oxfordlearnersdictionaries.com/definition/english/scrap_2

Carriers face the potential of taking drastic action — including permanent cuts in capacity and increased scrapping — if there is a prolonged downturn in demand caused by successive outbreaks of the coronavirus disease 2019 (COVID-19), maritime consultancy Drewry said Tuesday.

Source: https://www.joc.com/maritime-news/container-lines/carriers-could-make-permanent-capacity-cuts-prolonged-downturn-drewry_20200714.html

A: The source is behind a subscription wall.
Occurring in the same sentence as "permanent cuts in capacity", "scrapping" may mean the destruction of a ship that is no longer used. A search for the phrase "What is scrapping in the shipping industry" brings up an article in Wikipedia called "ship breaking", which is about destruction of excess shipping vessels.
Wikipedia "ship breaking"

Ship-breaking or ship demolition is a type of ship disposal involving the breaking up of ships for either a source of parts, which can be sold for re-use, or for the extraction of raw materials, chiefly scrap.

... all ships will be eventually scrapped, sunk, or preserved for museums

The article mentions the word "scrap", "scrapping", "scrapped" multiple times.
The sense of that word is this:
American Heritage Dictionary "scrap"
v. tr. 1. To break down into parts for disposal or salvage: scrap an old stove.


text:
Q: What is a hollow world? I have heard the phrase hollow world several times, but seeing the question "Does the Song of Ice and Fire take place in a hollow world?," inspired me to finally Google the topic. This led to a TV Trope page about hollow worlds explaining:

When science started to switch over to the modern view of Earth's
  composition the idea of the hollow earth became a Discredited Trope,
  but later generations of Speculative Fiction writers took up the
  concept and revitalized it.

Adding various world types: ring worlds, dyson spheres, artificially constructed worlds, etc. Which confused the matter further. Unfortunately, I guess I don't truly understand the concept of a hollow world. Is it as simple as the world is hollow? Or is there something more conceptual at play?

A: To add more color to cjm's excellent answer, the "Hollow Earth" Wiki has a whole big list of historical theories, from ancient world and primitive tribes, to 17-18th century, up through 21st.
It also mentions "megastructures that have some similarities to a hollow Earth – Dyson sphere and Globus Cassus" which your question mentioned.
Among the most interesting ideas are "Concave hollow Earths" as well as "Multiple concentric shells", both of which actually contradict cjm's statement that the fundamental quality of a hollow world is that it is a large, hollow, more-or-less spherical object, and creatures live on the inside surface of it:

As far as concentric spheres, Edmond Halley (the astronomer of the Halley's Coment fame):

... in 1692 put forth the idea of Earth consisting of a hollow shell about 800 km (500 mi) thick, two inner concentric shells and an innermost core, about the diameters of the planets Venus, Mars, and Mercury. Atmospheres separate these shells, and each shell has its own magnetic poles. The spheres rotate at different speeds. Halley proposed this scheme in order to explain anomalous compass readings.

Also, another curious theory had us living on the inside of the sphere:

Instead of saying that humans live on the outside surface of a hollow planet, sometimes called a "convex" hollow-Earth hypothesis, some have claimed that our universe itself lies in the interior of a hollow world, calling this a "concave" hollow-Earth hypothesis. The surface of the Earth, according to such a view, might resemble the interior shell of a sphere.

Aside from its weirdness/elegance, this latter theory is notable for this website since it was the basis of the worldview of an alien world in one of the most famous Soviet SciFi novels, "Inhabited Island"

A: Yes, the fundamental quality of a hollow world is that it is a large, hollow, more-or-less spherical object, and creatures live on the inside surface of it.
What's on the outside of the object (or even if it has an outside) may vary.  There could be creatures living on the outside, or it could be bare, or the object could fill the entire universe (and thus have no outside).
Of course the science problem is that gravity as we know it can't hold objects to the inside of a sphere, which is why this is now mostly a fantasy concept.  If the world is cylindrical, though, centrifugal force could be used to press the inhabitants to the surface.


text:
Q: Various interfaces for a single "data-carrying" class I am trying to implement a series of classes that provide a (common) interface to triangular or symmetric matrices, but I want to avoid copying memory (i.e. make a lot of in-place operations).
The way I was thinking to do this in C++ is to implement a class or struct that is simply a vector containing the matrix data (since I am only concerned on triangular matrices, I only have to store half of the matrix approx.). Let's call this "data-carrying" class SquareTriangularMatrix. Now the data inside this matrix could be accessed differently depending wether the data should be treated as upper triangular, lower triangular or even symmetric.
I do not think that polymorphism can be applied in my case because I want that the same object of SquareTriangularMatrix have different interfaces depending on the context. Some times SquareTriangularMatrix could be treated as a lower triangular matrix, but some others might be its transpose: an upper triangular matrix, and so on.
Is there any design pattern that addresses this problem? Any hint or guideline in this context would be much appreciated.
Many thanks

A: You can create adapter classes for your storage class, like that:
struct SquareTriangularMatrix {
    // constructor, maybe operator[], etc
    int* values;
    int nrows;
    int ncolumns;
};

struct UpperTriangleMatrix {
    UpperTriangleMatrix (SquareTriangularMatrix& data): data(data) {}
    int at (unsigned row, unsigned column) const {
        if (row > column) return 0;
        return data.values [row * data.ncolumns + column];
    }
private:
    SquareTriangularMatrix& data;
};

Then you can make that class UpperTriangleMatrix nested in the SquareTriangularMatrix and add a function like SquareTriangularMatrix::as_upper() which will return that adapter constructed with this matrix.
Another way you can go is to create a function as in the SquareTriangularMatrix that will allow to add custom adapters later, like this:
struct SquareTriangularMatrix {
    //...
    template <class T> T
    as () { return T(*this); }
};

//usage:
SquareTriangularMatrix m;
auto upper = m.as <UpperTriangleMatrix>();

Using this approach, you can convert your matrix at any moment to any adapter you wish that satisfies the as template (which is pretty simple and broad), and extend the list of adapters in any file locally.
You can also follow the way STL allows to convert time (std::duration_cast):
template <typename T> T& matrix_cast (SquareTriangularMatrix& m) { return T(m); }

SquareTriangularMatrix m;
auto upper = matrix_cast <UpperTriangleMatrix>(m);

It works just the same way as the function as<> from the previous sample, it's only a matter of taste.


text:
Q: Fetching the param value form the url From a web application, a url is called to the jasper server; the url has the user_id as one of the parameter. As soon as the Jasper server is logged in, I need to fetch the value of the user id to filter one another input parameter of the report.
Can anyone help me out to resolve this?

A: If your report has an input control with a name of user_id then it should get set with the value from the URL. If you want to use this param in another input control (e.g. a single select query control) then $P{user_id} will work.


text:
Q: Background image only works in Chrome I managed to put a background image -only with css- which covers the whole page and if you zoom in or zoom out it stays covering the full screen. I started with html+css coding but ended up with this more simple solution.
The problem is it only works on Chrome and the picture doesn't even appear when oppening with Firefox or IE.
Here is my css:
body {
    background-image: url(/img/18A_0159.JPG);
    background-size: cover;
}

I tried different solutions as for exemple to put it directly in the css's html part but still only works in Chrome, also checked different forums but maybe too old and not been updated?
I'm pretty new into coding so any help is welcome! Maybe better html+css??

A: Your url needs to be in quotes.
body {
    background-image: url("/img/18A_0159.JPG");
    background-size: cover;
}

A: Try this
body{margin: auto;
padding: 0px;
background: url(images/bg.jpg) no-repeat center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;}

A:

    body{
         background: url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQvRaBo6ZZdUBrwsgfzubKwSf-E6Bsqm1RkfmGh8X40uiSVV-fSNw);
         background-size: cover;
        }

Note:

*

*To change the Image, modify the https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQvRaBo6ZZdUBrwsgfzubKwSf-E6Bsqm1RkfmGh8X40uiSVV-fSNw


text:
Q: Facebook post- open graph I am developing a fan page which requires the open graph meta tags of facebook. Everything works fine. posting on timeline, tagging of friends and places etc. but the post which gets posted has the main heading like
"{User} visted a {action} on {App name} - with {Tagged Friend} at {Tagged Place}"
but i want "in" instead of "at" before {Tagged Place}
Can someone help me out. Sorry for the weak explanation

A: Not sure if you can use actions from fan page unless you are running an app.
If you have custom action you can select which term to use. I think the correct syntax is
(user) (action) (object) on (app name). Maybe you should revisit the facebook action API and make sure your app is setup correctly.
https://developers.facebook.com/docs/opengraph/actions/


text:
Q: Where to find tempdb logs in SQL Server? I'm currently using SQL Server 2014. In a stored procedure, I'm inserting data into a local temporary table (#TestTemporaryTable). I want to see the logs of data insertion into temp table, how can I fetch it from tempdb? And also, I want to know for how long these logs will exist?

A: You can examine the log records with the undocumented fn_dblog
eg
SELECT * FROM tempdb.sys.fn_dblog(NULL, NULL)


text:
Q: Node.js Promise without returning it I have a use case to resolve a Promise without returning it. Catching for errors internally, but don't want the caller to wait for the promise to resolve.
doSomething()
{
    Promise.resolve()
        .then(() => {
            // do something.
        })
        .catch(reason => {
            this.logger.error(reason);
        });
}

Getting this error:
(node:2072) Warning: a promise was created in a handler at internal/timers.js:439:21 but was not returned from it, see http://. goo.gl/rRqMUw
    at Function.Promise.cast (.../node_modules/bluebird/js/release/promise.js:225:13)

A: Just return something from the Promise callback where you are creating the fire and forget promise.
I'm guessing that handler is doSomething
doSomething()
{
    Promise.resolve()
    .then(() => {
        // do something.
    })
    .catch(reason => {
        this.logger.error(reason);
    });

    return null //or anything else that's sensible
}

Note: We usually ignore the error message, but sometimes they contain valuable information. In your error there's a link http://. goo.gl/rRqMUw that explains exactly this problem:d


text:
Q: How do I use a DLL function in C# without adding the DLL as reference? I'm trying to use functions from a DLL that can't be added as Reference through Visual Studio (a message saying "reference cannot be added" appears). However, I've gotten instructions from the creator of the DLL and they suggested I use them like this in VB.Net:
Private Declare Function Prn_Init Lib "VAx_VPOS396_APPAPI.dll" () As Integer

That works, but now I want to write a program in C#. How do I "translate" that declaration to C#?
Additional: In C++ the declaration comes in a *.h file with these lines:
#ifndef  _VPOS396DLL_API_H
#define  _VPOS396DLL_API_H
VPOS396_DLL_API     int Prn_Init(void);

A: You should create the method(s) you want to use in C#, make them extern and add a [DllImport] attribute. For example:
[DllImport("kernel32.dll")]
static extern bool Beep(uint dwFreq, uint dwDuration);

See https://msdn.microsoft.com/en-us/library/aa984739%28v=vs.71%29.aspx

A: [System.Runtime.InteropServices.DllImport("VAx_VPOS396_APPAPI.dll")]
public static extern unsafe Int32 Prn_Init(void);
("unsafe" is optional)


text:
Q: How to take the inner text of id and assign it to a specific variable only for a specific inner text I have different pages which populate a div tag with a specific id based on the id inner text:
here are some different example of pages with this div:

text page1

text page2

text page3

I want to take only the inner text of second and fill a variable.
I try to use something like this:
if($("#id_name").length > 0 && $("#id_name").text() === "text page2") {
    site.text = $("#id_name").text();
}

A: Try this:
if($("#id_name:eq(1)").length > 0 && $("#id_name:eq(1)").text() === "text page2") {
    site.text = $("#id_name:eq(1)").text();
}

Hint use class instead of ID.

A: *

*Do not use the same id for multiple elements. See Why is it a bad thing to have multiple HTML elements with the same id attribute?

*Use classes instead

*You can use :contains()

if ($(".class_name:contains(text page2)").length > 0) {
  $('body').text("text page2");
}

text page1

text page2

text page3

A: Try this:
$("[id*='id_name']").each(function(){
    if ($(this).html() == "text page2"){
    site.text($(this).html());
}
});


text:
Q: How can I change between different color schemes in vi? How can I change between different color schemes in vi?

A: As far as I know, plain ol' vi doesn't provide different colorschemes. If you are using vim however, you can type :colorscheme <newcolorscheme>. You can use tab to cycle through the installed colorschemes.
See http://vim.wikia.com/wiki/Switch_color_schemes for more information

A: you could try different color schemes like this:
https://kb.mediatemple.net/questions/1565/Enabling+vi+syntax+colors#gs
My problem was only deep blue comment color in default color scheme, so I changed just that:
cd ~
vi .vimrc
highlight comment ctermfg=lightblue

or change lightblue to cyan or whatever


text:
Q: Classifying Multinomial Naive Bayes Classifier with Python Example I am looking for a simple example on how to run a Multinomial Naive Bayes Classifier. I came across this example from StackOverflow:
Implementing Bag-of-Words Naive-Bayes classifier in NLTK
import numpy as np
from nltk.probability import FreqDist
from nltk.classify import SklearnClassifier
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline

pipeline = Pipeline([('tfidf', TfidfTransformer()),
                     ('chi2', SelectKBest(chi2, k=1000)),
                     ('nb', MultinomialNB())])
classif = SklearnClassifier(pipeline)

from nltk.corpus import movie_reviews
pos = [FreqDist(movie_reviews.words(i)) for i in movie_reviews.fileids('pos')]
neg = [FreqDist(movie_reviews.words(i)) for i in movie_reviews.fileids('neg')]
add_label = lambda lst, lab: [(x, lab) for x in lst]
#Original code from thread:
#classif.train(add_label(pos[:100], 'pos') + add_label(neg[:100], 'neg'))
classif.train(add_label(pos, 'pos') + add_label(neg, 'neg'))#Made changes here

#Original code from thread:
#l_pos = np.array(classif.batch_classify(pos[100:]))
#l_neg = np.array(classif.batch_classify(neg[100:]))
l_pos = np.array(classif.batch_classify(pos))#Made changes here
l_neg = np.array(classif.batch_classify(neg))#Made changes here
print "Confusion matrix:\n%d\t%d\n%d\t%d" % (
          (l_pos == 'pos').sum(), (l_pos == 'neg').sum(),
          (l_neg == 'pos').sum(), (l_neg == 'neg').sum())

I received a warning after running this example.
C:\Python27\lib\site-packages\scikit_learn-0.13.1-py2.7-win32.egg\sklearn\feature_selection\univariate_selection.py:327:
UserWarning: Duplicate scores. Result may depend on feature ordering.There are probably duplicate features,
or you used a classification score for a regression task.
warn("Duplicate scores. Result may depend on feature ordering."

Confusion matrix:
876 124
63  937

So, my questions are..

*

*Can anyone tell me what does this error message means?

*I made some changes to the original code but why is the confusion matrix results so much higher than the one in the original thread?

*How can I test the accuracy of this of this classifier?

A: The original code trains on the first 100 examples of positive and negative and then classifies the remainder.  You have removed the boundary and used each example in both the training and classification phase, in other words, you have duplicated features.  To fix this, split the data set into two sets, train and test.
The confusion matrix is higher (or different) because you are training on different data.
The confusion matrix is a measure of accuracy and shows the number of false positives etc.  Read more here: http://en.wikipedia.org/wiki/Confusion_matrix

A: I used the original code with only the first 100 entries for the training set and still had that warning.   My output was:
In [6]: %run testclassifier.py
C:\Users\..\AppData\Local\Enthought\Canopy\User\lib\site-packages\sklearn\feature_selection\univariate_selecti
on.py:319: UserWarning: Duplicate scores. Result may depend on feature ordering.There are probably duplicate features, o
r you used a classification score for a regression task.
  warn("Duplicate scores. Result may depend on feature ordering."
Confusion matrix:
427     473
132     768


text:
Q: "$MAKEOPTS" ignored, why? I have defined
export MAKEOPTS="-j4"

in my ~/.profile file.
But when I do a compilation with make, this option is ignored.
I've consulted the GNU Make manual but it says nothing about this variable. Is it standard or only it works in certain distros?

A: export MAKE="make -j4"

This will help invoking child make processes, but I'm afraid this wouldn't help with direct invocations, like just make all. Though a shell alias may help with the direct ones, so:
MAKEFLAGS="-j4"
export MAKE="make $MAKEFLAGS"
alias make="make $MAKEFLAGS"

A: I'll be honest, before today I'd never seen MAKEOPTS.
MAKEFLAGS I know of but after some research, MAKEOPTS appears to be Gentoo- (and its children) specific.
And if it's not in the manual, it can hardly be considered standard by any stretch of the imagination.

A: Add
MAKEOPTS="-j4"

to /etc/make.conf (create it if it doesn't already exist).


text:
Q: How to move cells to the top of a JPanel using GridBagLayout I'm creating a GUI interface which uses several JPanels all formatted using BorderLayout. My east and west panels utilize a GridBagLayout. I want my west panel to align towards the top of the JPanel to line up with my east panel, but for whatever reason it's stuck in the center, making the interface look kind of silly. I'm brand new to GridBagLayout and it seems far more complicated than any of the other layouts i've used in the past, so i'm having trouble getting this to work.
I've read tons on the Layout both here and on other sites, so I can't figure out why it won't behave like I want it to. From what I understand, using the anchor() method allows you to align your widgets within the layout. My west panel uses a JLabel with some JRadioButtons, which I have anchored at NORTHWEST so the RadioButtons line up correctly and aren't scattered unevenly throughout.
Anyways, here is my code for both the east and west panels:
EAST(which i'm trying to align my west panel with):
//east panel
        GridBagConstraints gbc1 = new GridBagConstraints();
        gbc1.fill = GridBagConstraints.VERTICAL;

        eastLbl = new JLabel("Click to Complete", SwingConstants.CENTER);
        eastLbl.setFont(f3);
        eastLbl.setOpaque(true);
        eastLbl.setBackground(newOrange);
        eastLbl.setPreferredSize(new Dimension(130,100));
        eastLbl.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        gbc1.weightx = 1;
        gbc1.gridx = 0;
        gbc1.gridy = 0;
        eastPanel.add(eastLbl, gbc1);

        cartBtn = new JButton("Add to Cart");
        cartBtn.setFont(f3);
        cartBtn.setToolTipText("Add to cart");
        cartBtn.setMnemonic(KeyEvent.VK_A);
        cartBtn.setPreferredSize(new Dimension(130,100));
        gbc1.weightx = 1;
        gbc1.gridx = 0;
        gbc1.gridy = 1;
        eastPanel.add(cartBtn, gbc1);

        clearBtn = new JButton("Clear Order");
        clearBtn.setFont(f3);
        clearBtn.setToolTipText("Clear Order");
        clearBtn.setMnemonic(KeyEvent.VK_C);
        clearBtn.setPreferredSize(new Dimension(130,100));
        gbc1.weightx = 1;
        gbc1.gridx = 0;
        gbc1.gridy = 2;
        eastPanel.add(clearBtn, gbc1);

        exitBtn = new JButton("Exit");
        exitBtn.setFont(f3);
        exitBtn.setToolTipText("Exit");
        exitBtn.setMnemonic(KeyEvent.VK_E);
        exitBtn.setPreferredSize(new Dimension(130,100));
        gbc1.weightx = 1;
        gbc1.gridx = 0;
        gbc1.gridy = 3;
        eastPanel.add(exitBtn, gbc1);

        c.add(eastPanel, BorderLayout.EAST);

WEST(which is stuck in the center of my JPanel, and is unevenly matched with my east panel):
//west panel
        GridBagConstraints gbc2 = new GridBagConstraints();
        gbc2.fill = GridBagConstraints.VERTICAL;
        gbc2.anchor = GridBagConstraints.NORTHWEST;

        westLbl = new JLabel("Click Seat Selection", SwingConstants.CENTER);
        westLbl.setFont(f3);
        westLbl.setOpaque(true);
        westLbl.setBackground(newOrange);
        westLbl.setPreferredSize(new Dimension(140,100));
        westLbl.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        gbc2.weightx = 1;
        gbc2.gridx = 0;
        gbc2.gridy = 0;
        westPanel.add(westLbl, gbc2);

        lowerDeck = new JRadioButton("Lower Deck");
        gbc2.weightx = 2;
        gbc2.gridx = 0;
        gbc2.gridy = 1;
        westPanel.add(lowerDeck, gbc2);

        upperDeck = new JRadioButton("Upper Deck");
        gbc2.weightx = 2;
        gbc2.gridx = 0;
        gbc2.gridy = 2;
        westPanel.add(upperDeck, gbc2);

        obstructed = new JRadioButton("Obstructed View");
        gbc2.weightx = 2;
        gbc2.gridx = 0;
        gbc2.gridy = 3;
        westPanel.add(obstructed, gbc2);

        luxury = new JRadioButton("Luxury");
        gbc2.weightx = 2;
        gbc2.gridx = 0;
        gbc2.gridy = 4;
        westPanel.add(luxury, gbc2);

        bGroup = new ButtonGroup();
        bGroup.add(lowerDeck);
        bGroup.add(upperDeck);
        bGroup.add(obstructed);
        bGroup.add(luxury);

        c.add(westPanel, BorderLayout.WEST);

To reiterate, my east panel flows from the top of the panel to the bottom, while my west panel sits in the center. Both use GridBagLayout. I want them to align properly from the top of each JPanel. I'm sure i'm making a silly mistake, but i'm at wits end with it and hopefully someone can point me in the right direction. Thanks again folks :)