text:
Q: How to teach the division algorithm? What is the best way to introduce the division algorithm? Are there real life examples of an application of this algorithm. At present I state and prove the division algorithm and then do some numerical examples but most of the students find this approach pretty dry and boring. I would like to bring this topic to live but how?

A:
[Cue sci-fi sequence.]
A number of clones in an underground cloning lab escape from their enclosure. Most of the clones are from the same batch, and they all weigh 150 pounds. There is also a clone from a later batch--not as fully developed, only weighing 50 pounds. They manage to reach the elevator out of the facility, and through [plot contrivance] are able to make it operational for one trip up, only. The elevator has a 2000 pound carrying capacity. How many of the grown clones will escape the facility (assuming that the volume of the elevator is not a restriction)? Will the elevator be able to carry the youngster?
Tune in next time, for Division Algorithm!
[Cut to black.]

Okay, that isn't a real life example, but it certainly isn't dull.

You have a pocket full of quarters (39 in all) and a serious gumball craving. The supermarket gumball machine charges a dollar per gumball. (The money-grubbers!) How many gumballs can you get, and how many quarters will you have left?

That isn't quite as exciting, but it's more "real."

A: I found Cameron Blue's answer confusing so I wrote my own answer. How do you compute a quotient and a remainder of a division problem? It's by computing the quotient and remainder on division of the original dividend by the divisor, in terms of the quotient and remainder of the division of a new divison problem with the original divisor without the last digit as a divisor and the same dividend, and recognizing that you can iterate this process of changing the division problem. Now the quetion is "How do you do a single iteration of that process?" Let's say you have a really large number and you want to find its quotient and remainder on division by 257. Once you find the quotient and remainder of the original dividend without the last digit on division by 257, you can find the quotient and remainder of the original division problem as follows. What does it mean to say the quotient and remainder on the original dividend without the last digit are? It means it can be expressed as 257 $\times$ a natural number + a natural number from 0 to 256. So if you multiply that by 10 than add a number between 0 and 9, then this new number can be expressed as 257 $\times$ 10 times the quotient + 10 times the remainder plus that number from 0 to 9. Now this number is small enough that we can find its quotient and remainder on division by 257 in our head. Its remainder will now become the remainder of the original problem and once you add this quotient onto the number that was used in the sentence "So if you multiply that by 10 than add a number between 0 and 9, then this new number can be expressed as 257 $\times$ 10 times the quotient + 10 times the remainder plus that number from 0 to 9," you get the quotient of the original division problem.


text:
Q: Automatically create class in Eclipse with Pydev I am developing a python system with Eclipse and Pydev using TDD. When I write the code for the tests, the IDE shows erros in classes in methods since I have not writen the code. Can I do the IDE creates the classes with the methods automatically while I write the code?

A: Yes, that's possible...
When the error is highlighted use Ctrl+1 and choose the option to create the class. The following video shows how this is done: http://www.pydev.org/video_pydev_20.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Collect both matching and non-matching in one stream processing? Is there a way to collect both matching and not matching elements of stream in one processing?
Take this example:
final List<Integer> numbers = Arrays.asList( 1, 2, 3, 4, 5 );
final List<Integer> even = numbers.stream().filter( n -> n % 2 == 0 ).collect( Collectors.toList() );
final List<Integer> odd = numbers.stream().filter( n -> n % 2 != 0 ).collect( Collectors.toList() );

Is there a way to avoid running through the list of numbers twice? Something like "collector for matches and collector for no-matches"?

A: You may do it like so,
final Map<Boolean, List<Integer>> parityMap = numbers.stream()
        .collect(Collectors.partitioningBy(n -> n % 2 == 0));
final List<Integer> even = parityMap.get(true);
final List<Integer> odd = parityMap.get(false);

A: If you have more than 2 groups (instead of odd and even here using %2) for example to group ints in remainder classes %3 you can use a Function:
Function<Integer, Integer> fun =  i -> i%3;
List<Integer> a = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Map<Integer, List<Integer>> collect = a.stream().collect(Collectors.groupingBy(fun));

System.out.println(collect);
//{0=[3, 6, 9], 1=[1, 4, 7, 10], 2=[2, 5, 8]}

Or imagine you have a list of strings which you want to group by starting char
instead of grouping matching and non-matching (for e.g. starts with a or not)
you could do something like :
Function<String, Character> fun =  s -> s.charAt(0);
List<String> a = Arrays.asList("baz","buzz","azz","ayy","foo","doo");
Map<Character, List<String>> collect = a.stream().collect(Collectors.groupingBy(fun));

System.out.println(collect);
//{a=[azz, ayy], b=[baz, buzz], d=[doo], f=[foo]}


text:
Q: Native javascript date format in cookie value? I have some code I'm refactoring where PHP sets the current date/time in a cookie. There is some javascript that parses the date from this string, and creates a javascript Date object from it.
However, the code is laborious. Since I have the opporuntity to re-write this, I would like to store the current date time in a format more amenable to javascript creating a Date object out of it.
What is the most efficient way to store the date as a string in a cookie for javascript to ingest, later on?
An important factor is that I need to include the timezone in this reckoning.

A: You can just set the cookie with the date as follows:
var today = new Date();
document.cookie = 'yourCookieName' + '=' + today

And then when you want to get the value and use it as a date object again just grab the cookie value:
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)yourCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1");

Once you have the string value of the date you set, just use it as follows:
var anotherDate = new Date(cookieValue);

anotherDate will be a date object from the cookie date string.

A: I found out I can use Date.parse() to get a unix timestamp from the string version of a Date object.
Since I'm using JQuery's cookie library, here's what I've done:
$.cookie('arrival',
  new Date(),
  { expires : 30,
    path    : '/',
    domain  : 'my domain.com' }
);

And to read it:
var cookieDate = new Date(Date.parse($.cookie('arrival')));


text:
Q: Entity Framework add first row to database from a List? foreach (StockItem item in StockList)
{
    Master master = new Master();
    master.VoucherNo = BillNo;
    master.Voucher = "Sales";
    master.StockName = StockList[0].StockName;
    master.Quantity = StockList[0].Quantity;
    master.Unit = StockList[0].Unit;
    master.Price = StockList[0].UnitPrice;
    master.Amount = StockList[0].Amount;
    dbContext.AddToMasters(master);
    dbContext.SaveChanges();
}
Sale sale = new Sale();
sale.InvoiceNo = BillNo;
sale.Date = BillDate;
sale.Party = Customer;
sale.Amount = (decimal)TotalAmount;
dbContext.AddToSales(sale);
dbContext.SaveChanges();

This code add only the first row from StockList for all n times if there are n rows.
What wrongs with the code?

A: You are iterating over StockList, but you aren't actually using the iteration variable.
Everywhere that you use StockList[0], you should be using item.
Edit: Here is what your loop should look like:
foreach (StockItem item in StockList)
{
    Master master = new Master();
    master.VoucherNo = BillNo;
    master.Voucher = "Sales";
    master.StockName = item.StockName;
    master.Quantity = item.Quantity;
    master.Unit = item.Unit;
    master.Price = item.UnitPrice;
    master.Amount = item.Amount;
    dbContext.AddToMasters(master);
    dbContext.SaveChanges();
}


text:
Q: Get a timestamp from a day,year, and month I have the following string: 2013-03-22
I need to convert that to a UNIX Timestamp.
How do I do this using PHP?

A: Use the strtotime function of PHP.
Like
$unixstamp = strtotime("2013-03-22");

A: With DateTime class
$dateTime = DateTime::createFromFormat('Y-m-d', '2013-03-22');
$dateTime->setTime(0, 0, 0);
echo $dateTime->getTimestamp();

A: Simple:
echo $time = strtotime("2013-03-22");

A: Using
strtotime("2013-03-22")
It will convert the date sting into timestamp value.


text:
Q: Unable to copy dataframe in pyspark to csv file in Databricks I am working in Pyspark environment in Databricks and have a pyspark data frame which I will call as df.
I need to push this spark dataframe into csv file, I am unable to do so. Though there is no error popping up but the dataframe doesn't get copied into the csv. Below is the generic code

path = " " #CSV File Location
header = "This is the header of the file"
With open(path,"a") as f:
    f.write(header+"\n")
    df.write.csv(path=path,format="csv",mode="append")
    f.close

Only the header gets reflected in the file and not the dataframe

A: You can write your dataframe as csv using this:
df.coalesce(1).write.format("com.databricks.spark.csv").option("header", "true").save("dbfs:/FileStore/df.csv")

Coalesce avoids saving it in multiple partitions. You can put in your own path as parameter in save().


text:
Q: Golang TCP server: how to write HTTP2 data I'm new to HTTP/2.0, and I'm trying to set up a TCP server, written in Golang, which receives and writes HTTP/2.0 frames. I'm having trouble writing any data back to the client.
The following code snippet shows how the request is handled.
conn, err := l.Accept()
if err != nil {
    log.Fatal("could not accept connection:", err)
}
defer conn.Close()

// Every connection starts with a connection preface send first, which has to be read prior
// to reading any frames (RFC 7540, section 3.5)
const preface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
b := make([]byte, len(preface))
if _, err := io.ReadFull(conn, b); err != nil {
    log.Fatal("could not read from connection:", err)
}
if string(b) != preface {
    log.Fatal("invalid preface")
}

framer := http2.NewFramer(conn, conn)

// Read client request (SETTINGS and HEADERS)
readFrames(framer)

// Send empty SETTINGS frame to the client
framer.WriteRawFrame(http2.FrameSettings, 0, 0, []byte{})

// Read clients response (contains empty SETTINGS with END_STREAM flag)
readFrames(framer)

// Prepare HEADERS
hbuf := bytes.NewBuffer([]byte{})
encoder := hpack.NewEncoder(hbuf)
encoder.WriteField(hpack.HeaderField{Name: ":status:", Value: "200"})
encoder.WriteField(hpack.HeaderField{Name: "date", Value: time.Now().UTC().Format(http.TimeFormat)})
encoder.WriteField(hpack.HeaderField{Name: "content-length", Value: strconv.Itoa(len("ok"))})
encoder.WriteField(hpack.HeaderField{Name: "content-type", Value: "text/html"})

// Write HEADERS frame
err = framer.WriteHeaders(http2.HeadersFrameParam{StreamID: 2, BlockFragment: hbuf.Bytes(), EndHeaders: true})
if err != nil {
    log.Fatal("could not write headers: ", err)
}

// Clients response contains GOAWAY
readFrames(framer)

framer.WriteData(2, true, []byte("ok"))
conn.Close()

The full server can be found here: https://play.golang.org/p/ONA_OoyAMg-
It is called by doing a curl:
curl -kv https://127.0.0.1:8080 --http2

As far as I know, after the SETTINGS frames, the connection should be ready for traffic. A stream should be opened by sending a HEADERS frame, after which a DATA frame can be send on the open stream. However, after sending the HEADERS frame I get the following error message:
curl: (16) Error in the HTTP2 framing layer

The clients responds with a GOAWAY.

A: I found the issue myself, if fact there were two. I found both issues in this article: http://undertow.io/blog/2015/04/27/An-in-depth-overview-of-HTTP2.html
First of all the required response header containing the status code should be :status instead of :status:.
And finally I didn't respond on the same stream ID from which the request was made and instead tried opening a new stream.
So I should loop over the request frames, look for the stream ID, and use it for writing out the response headers.
// Read client request (SETTINGS and HEADERS)
readFrames(framer)
var streamID uint32
for _, frame := range frames {
    if headersframe, ok := frame.(*http2.HeadersFrame); ok {
        streamID = headersframe.StreamID
    }
}

//... Prepare headers

// Write HEADERS frame
err = framer.WriteHeaders(http2.HeadersFrameParam{StreamID: streamID, BlockFragment: hbuf.Bytes(), EndHeaders: true})
if err != nil {
    log.Fatal("could not write headers: ", err)
}

framer.WriteData(streamID, true, []byte("ok"))
conn.Close()


text:
Q: Use responsive images (sizes + srcset) with TinyMCE I want to change the img-tags generated by TinyMCE to responsive ditto when uploading an image, something like this (using lazysizes):
<img
    data-sizes="auto"
    data-src="image2.jpg"
    data-srcset="image1.jpg 300w,
                 image2.jpg 600w,
                 image3.jpg 900w"
    class="lazyload" />

In the deprecated (and not useful, to me) MCImageManager you could do this:
imagemanager_insert_template : '<img src="{$url}" />'

Is there something similar in TinyMCE? Either in the core or some of the (free) plugins? I have full control over the back end where I upload the images and I am already doing the resizing there (using ImageSharp).

A: *

*Edit: This answer works for Wordpress TinyMCE only. I didn't see that the question was not related with Wordpress.

Very old question, but I got the same problem recently.
You can hook image_send_to_editor filter, that is only apply to TinyMCE.
On this hook, you can apply to the output, the wp_filter_content_tags function that is responsible for change some markup.
Currently it adds srcset, sizes, and loading attributes to img HTML tags.
So you can use it like this:
/**
 * Change the image markup to include srcset and sizes
 * when using tinyMCE editor
 *
 * @param $html
 * @param $id
 * @param $alt
 * @param $title
 * @param $align
 * @param $url
 * @param $size
 * @return string
 * @throws Exception
 */
function storms_img_markup( $html, $id, $caption, $title, $align, $url, $size, $alt, $rel ) {
    return wp_filter_content_tags( $html );
}
add_filter( 'image_send_to_editor', 'storms_img_markup', 10, 9 );

This code may require some additional validation, but it works on Wordpress 5.6


text:
Q: Magento 2.3.1 Merge products from one database to another? I have a staging and a production server for my Magento 2.3.1 project. The two databases have different data and configurations, so I can not just dump the mysql db and restore it.
Is there a way to merge only products data from one database to another?

A: You can use Magento's default export and import option to merge products from one magento setup to another magento:

Admin->System->Data Transfer->Import/Export


text:
Q: How to use EVGA GTX 970 to output to 2 Dell P2715Q monitors at 4K resolution at 60hz My EVGA GTX970 has 1 DisplayPort, 1 HDMI 2.0 and 2x DVI ports.
Unfortunately, the HDMI port on Dell P2715Q is only HDMI 1.4. Therefore, I can output 4K resolution at 30Hz.
Is there a way to get 4k@60hz for both of these Dell P2715Q monitors?
Is there a DisplayPort hub which split the signal to dual monitors at 4K resolution at 60hz?

A: When did you buy your monitors? According to this support page from Dell's website displays sold after February 2016 support HDMI 2.0 but it's not enabled from the factory.
You can enable HDMI 2.0 in your P2415Q or P2715Q flat panel displays purchased after February 2016 using the following steps:

*

*Unplug all video cables from the display. (Leave only the power connected to the display.)

*Power on the display.

*Select the HDMI (MHL) input option. (A floating dialogue box will appear.)

*Press and hold the button associated with the Green check mark for 6 to 8 seconds.

*A dialogue box appear that states HDMI 1.4 Enable/Disable
Select the option to Disable HDMI 1.4 support and press the button next to the green check mark to confirm the selection.

*Re-connect the video cables to the display


text:
Q: Proguard generating wrong string resource id When creating a build with Proguard it changes the string resource id with another.
For example, I have two buttons (button1, button2) with label "Create", "Update" respectively. After the Proguard build, the button2 contains label "Create" but it suppose to have label "Update"
This happens only for few string resource id.

A: The problem was related to another build script. We are using crashlytics for error reporting. This crashlytics build file messing up the resource id somehow.


text:
Q: Optimize runtime of calling 'in' many times on same string In finding substrings, the in operator is the best in terms of performance for a single call. It looks like it is also O(n) average runtime.
If i want to find whether or not several substrings exist in a string, something like this:
if 'dog' in str:
    # ....
if 'cat' in str:
    # ....
if 'frog' in str:
    # ....

This would be 3n runtime, which is a lot of repeated work.
Is there a way to optimize in or another library that is available that would be a faster alternative?

A: #EDIT
==============================================================
a_list  = re.sub("[^a-zA-Z ]","",s).split()#4957 words (lorum ipsum generated)
search_space = set("dog cat fish bear walrus".split())

def joranbeasley():
    return search_space.intersection(a_list)

def stephenPochmann():
    for needle in search_space:
        if needle in s: print needle

import timeit
print "Stephen Timeit:",timeit.timeit(stephenPochmann,number=1000)
print "joran Timeit:",timeit.timeit(joranbeasley,number=1000)

results
Stephen Timeit: 0.126952238343
joran Timeit: 0.148540107751

===============================================================
set(["dog","cat","frog"]).intersection(my_str.split())

might give you what you need its hard to tell and should be plenty fast ...
if your string uses delimiters other than spaces you might need to pass an argument to split with your delimiter(";" or something)
you also might have to clean your input to remove stuff like punctuation
my_cleaned_string = re.sub("[^a-zA-Z]","",my_str)

compared to @StephenPochmans if I change it a bit (ie I dont need to keep splitting every time)
import re
a_list  = re.sub("[^a-zA-Z ]","",s).split()#4957 words (lorum ipsum generated)
search_space = set("dog cat fish bear walrus".split())
def stephenPochmann():
    for needle in search_space:
        if needle in a_list: print needle

def joranbeasley():
    return search_space.intersection(a_list)

import timeit
print "Stephen Timeit:",timeit.timeit(stephenPochmann,number=1000)
print "joran Timeit:",timeit.timeit(joranbeasley,number=1000)

and the results
c:\py_exp>python test_benchmark.py
Stephen Timeit: 0.356363602542
joran Timeit: 0.166205366392

after changeing @StephenPochmans to use the string instead of the list, he is right and it is indeed faster ... I will clarify this at the top of my answer soon
def stephenPochmann():
    for needle in search_space:
        if needle in s: print needle

here is the results
Stephen Timeit: 0.126952238343
joran Timeit: 0.148540107751

A: If you have a lot of words you should consider moving to an algorithm build for searching multiple words inside a text.
The most popular is Aho–Corasick algorithm (https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm) and you can find many implementation for it in Python.
This is a just one of many tutorial explaining about the algorithm with implementing it: http://carshen.github.io/data-structures/algorithms/2014/04/07/aho-corasick-implementation-in-python.html


text:
Q: What happens in between planets? I was wondering in an area of space where there arent enough planets around it to suck an object in with gravity, does the object just float there? And if it does just float there will other objects eventually gravitate to it or pick it up eventually? This is a question I've asked a few of my physics and science teachers a few times, but none of them have really answered it very clearly in my opinion. Tell me if my question is unclear.

A: If an object is not close enough to a planet to orbit a planet, it will orbit the Sun.
If an object is not close enough to the Sun (or another star) to orbit it, it will orbit the centre of the Galaxy.
If an object is somewhere in intergalactic space, it will take a very long time before it goes anywhere.
The proper word for "close enough" is the Hill sphere or the Sphere of influence.


text:
Q: reading CSV file in C and creating an matrix I have tried to write a code for reading my CSV file and put the data in a 2D array. but when I run this code I see that all element of array are zero, kindly please help me to know what should I change?
int main(void){
    int rowID = 0;  //declare row index
    int columnID = 0;  //declare column index
    int data_new[10000][5] = {{0, 0}};  //create the matrix that we want to put the data
    char line[50000];                  //size of array line
    char token = NULL;
    FILE *data_csv = fopen("data.csv", "r");
    if (data_csv == NULL){
        perror("unable to open the file");
        exit(1);
    }
    while (fgets(line, 50000, data_csv))
    {
        columnID = 0;
        rowID++;

        if (rowID == 1)
        {
            continue;
        }  //to remove the headers
        char *each_line = strtok(line, ", "); //this split the data by ,

         each_line = strtok(NULL, ", ");
         columnID++;
    }
    fclose(data_csv); // Close the file
    for (int i = 0; i < rowID; ++i)
    {
        for (int j = 0; j < 5; ++j)
        printf("%10.4lf", data_new[i][j]);
        putchar('\n');
    }
}


text:
Q: Exchange 2010 - Disable Address Rewrite per Account Is it possible to disable for only one account the address rewrite in Exchange 2010 ?
I have 1 emails :
helpdesk@mycompany.org
With 2 aliases :
Helpdesk.international@mycompany.org
Helpdesk.local@mycompany.org
I want to fetch all emails that are received with "To=Helpdesk.international@mycompany.org" but not the other one. So far the "To" field is always set to helpdesk@mycompany.org.
PS : It cannot be disable for all users.
TIA,

A: I don't exactly understand what you're asking but it sounds to me like you want to set a specific email address as the primary SMTP address for this user other than the one being set by your email address policy. If so, then go into EMC>Recipient Configuration>Mailbox and bring up the properties of the user in question, then go to the E-mail Addresses tab, then unselect the check box "Automatically update e-mail addresses based on e-mail address policy", then select the email address that you want to be the primary SMTP address and click the "Set as Reply" button.


text:
Q: MySql Sql MAX and SUM error select sum(value) as 'Value',max(value)
from table_name where sum(value)=max(sum(value)) group by id_name;

The error is: Invalid use of group function (ErrorNr. 1111)
Any idea?
Thanks.

A: Can you maybe try
SELECT Value, MXValue
FROM (
       select sum(value) as 'Value',max(value)  MXValue
       from table_name
       group by id_name
     ) as t1
order by value desc
LIMIT 0,1

From MySQL Forums :: General :: selecting MAX(SUM())
Or you could try something like
SELECT  id_name,
        Value
FROM    (
            select id_name,sum(value) as 'Value'
            from table_name
            group by id_name
        ) t
WHERE   Value = (
                    SELECT TOP 1 SUM(Value) Mx
                    FROM table_name
                    GROUP BY id_name
                    ORDER BY SUM(Value) DESC
                )

Or even with an Inner join
SELECT  id_name,
        Value
FROM    (
            select id_name,sum(value) as Value
            from table_name
            group by id_name
        ) t INNER JOIN
        (
            SELECT TOP 1 SUM(Value) Mx
            FROM table_name
            GROUP BY id_name
            ORDER BY SUM(Value) DESC
        ) m ON Value = Mx

A: The =max(sum(value)) part requires comparing the results of two grouped selects, not just one. (The max of the sum.)
Let's step back, though: What information are you actually trying to get? Because the sum of the values in the table is unique; there is no minimum or maximum (or, depending on your viewpoint, there is -- the value is its own minimum and maximum). You'd need to apply some further criteria in there for the results to be meaningful, and in doing so you'd probably need to be doing a join or a subselect with some criteria.


text:
Q: Why is this measure concentrated on a cyclic subset of $\mathbb{R}$? Say $\mu$ is a Borel probability measure on $\mathbb{R}$ such that for some $t\neq 0$, we have $\hat{\mu}(t)=1$. That means
$$1 = \int\limits_{-\infty}^{\infty} e^{-itx}d\mu(x).
$$
Does it then follow that $\mu$ must be concentrated on $\left\lbrace \frac{2\pi n}{t} : n \in \mathbb{Z} \right\rbrace$?
Sorry if you find this question offensive; I failed trigonometry.

A: Taking  real parts we get $1=\int \cos (tx) d\mu (x)$ which can  be written as $\int [1-\cos (tx)] d\mu(x)=0$. Since the integrand is non-negative this implies $1-\cos (tx)=0$ for almost all $x$. Can you complete the argument ?


text:
Q: How can I make setInterval increase each time when user clicks? This is from JavaScript for kids, and I am stuck. How can I make setInterval increase each time the user clicks on the header? I have tried several solutions such as setInterval(moveheading,counter) or creating multiple setIntervals but it always seems to choose the fastest one and then proceeds to lose the second slowest (creating the opposite desired effect).
I have read that maybe setTimeOut would be a better solution to this, but I am having a hard time figuring out how. The book 'JavaScript for kids' can be found online as a PDF if you need further reference. The page where this challenge is at is 166.
<!DOCTYPE html>

    <title>MouseMove</title>

 Try and click me 10 times.

A: Why you can make settimeout as setinterval,

function function1(time) {
    console.log("Time is :" + time); // run this it is actually funny
}
let x;
function runner(time) {
    function1(time);
    x = setTimeout(function() {
        runner(1000);
    }, time);
    clearTimeout(x); // Comment out this clear timeout and see the output
}

runner(100);

try this type of solution

A: To set different (dynamic) duration, we need to stop the current timer, using clearInterval(), then re-run the timer with the new counter.


text:
Q: Are coordinate systems just rank 1 covariant tensor fields?
Question: Given, the Euclidean plane $\mathcal{P}$, with the point $O \in \mathcal{P}$ (called "the origin").
1. Is a Cartesian coordinate system for this plane centered at $O$ just an orthonormal basis for the cotangent space of the Euclidean point at $O$, i.e. an orthonormal basis for $(T_O \mathcal{P})^*$?
2. Are vectors with tail at $O$ in the Euclidean plane $\mathcal{P}$ just elements of the tangent space at $O$, i.e. $v \in T_O \mathcal{P}$? And is a vector $w$ with tail at point $A \in \mathcal{P}$ just an element $w \in T_A \mathcal{P}$?
3. That any point can be given a unique coordinate is just a reflection of the fact that $$\mathcal{P} \simeq (T_O\mathcal{P})^* $$ as vector spaces, and the fact that every point can be associated with a position vector is just a way of expressing the fact that $$\mathcal{P} \simeq T_O\mathcal{P} $$ as vector spaces? And the fact that position vectors can be associated with coordinates is just a reflection of the fact that, being finite-dimensional vector spaces, $$T_O\mathcal{P} \simeq (T_O\mathcal{P})^*?$$

Incredibly long-winded context:
I was thinking recently that coordinate systems and "physical vectors" are naturally dual -- the coordinates of a space don't change under a linear transformation, whereas "physical vectors" do change under linear transformations. In contrast, coordinates change under (aptly named) changes of coordinates, whereas "physical vectors" do not change under changes of coordinates.
In other words, it seems like it makes the most sense to define coordinate systems to be covariant tensor fields of order 1, i.e. one-forms. Then the purpose of always having and considering cotangent and tangent spaces makes sense, because the former is the coordinate system with origin at a given point, and the latter is the space of "physical vectors" anchored at the point.
Moreover, the notions of coordinate system for a vector space only starts to get messy exactly when the notion of dual space gets messy -- in infinite dimensions. The inner product at a point on a Riemannian manifold, which generates associated notions of length and angle, is defined on the tangent space, whose objects probably not coincidentally are "physical vectors", the objects for which notions of length and angle make the most sense (compared to points in a coordinate space). Likewise, notions of integration and differentiation seem to correspond most naturally to cotangent spaces, which seems to correspond to how calculus is defined in the simplest possible setting -- from a space of points to another space of points. And vector fields live in tangent spaces, and vector fields are most easily thought of in terms of "physical vectors", again suggesting that tangent spaces are "physical vectors" and that cotangent systems are just coordinate systems.
At least one other person seems to have come to this conclusion independently (or maybe I read that answer before and my subconscious just understood it now). This seems to be how physicists think of everything, and implicitly the viewpoint behind much of differential geometry, or at least this mental model seems to make what these experts say seem much clearer now. For instance, these youtube videos about tensor calculus suddenly make much more sense when one thinks of "the covariant basis" and the "coordinate system" as literally the exact same thing. Watching this video again, it also makes a lot more sense if one thinks "coordinates = covectors".
The only reason why one might not want to identify coordinate systems with cotangent spaces, is that one is often taught, when first introduced to "physical vectors", to identify them with the coordinates of the heads of their arrows. But that shouldn't discourage us, because obviously any finite-dimensional vector space is isomorphic to its dual vector space (as vector spaces). The isomorphism is so simple that we can completely ignore that it exists in elementary situations, but then suddenly one moves to differential geometry and gets confused because the distinction was pushed under the rug previously.
This answer also seems to suggest the same thing -- a vector space has no "intrinsic coordinate system" -- because one needs to specify a basis for the dual space in order to do so, i.e. a vector space has no "intrinsic coordinate system" for the exact same reason that it doesn't have an "intrinsic basis" -- one needs to specify both a basis for the vector space, and one for the dual vector space, the latter which we call a "coordinate system". And the manner in which coordinates for points are found -- via orthogonal projections, i.e. inner products -- is just application of covectors to vectors, or at least so it would seem to me.
Related questions:
Computationnal geometry: vector, basis, point and coordinate system?
How can vector functions define coordinate systems?
What is (fundamentally) a coordinate system ?
Linear algebra revisited: What do we do when we set a coordinate system?

A: Not entirely, but you can find a direct connection.  A covector field inhabits the cotangent space, a vector field inhabits the tangent space and a coordinate system is a set of $n$ scalar fields, where $n$ is the dimension of the manifold.  This statement is valid for any differentiable manifold, without the need to identify an origin.
If one has specifically a flat manifold and designates an origin, one can canonically identify (points of) the manifold with (vectors of) the tangent space at the origin.  A covector assigns to each vector a scalar value.  Through the mentioned identification, $n$ linearly independent covectors become equivalent to assigning to each point a set of $n$ coordinates, and transformations necessarily behave equivalently.  This picture only holds for "straight" coordinate systems though: it cannot produce curvilinear coordinate systems, but it applies regardless of the angles involved.  To keep one's implicit presumptions to a minimum, it is best to avoid assuming metric concepts such as angle and distance ("Euclidean").
It may be noted that all this depends on a list of restrictions: the manifold must be flat, an origin must be selected, the (co)tangent space at only the origin is considered, not a general (co)vector field; the coordinates must be linear, parallel and uniformly spaced.  But if one thinks in terms of differential behaviour, all of these are valid "locally", and the insight is a useful one.  So I'd say 'no' to all your questions, but in the limit of the tangent space at any given point, they become 'yes'.


text:
Q: Which cosmological dark matter theory is most compatible with current particle physics? This occurred to me while I was writing Why hasn't warm dark matter replaced cold dark matter as the standard model of cosmology? but I think this deserves a question of its own. The background info for this question is covered in that link, so I'll just cut straight to the point.
Is one of the current cosmological dark matter models of interest (cold dark matter, warm dark matter, self-interacting cold/warm dark matter) easier to reconcile with our current understanding of particle physics and the current measured limits on possible undiscovered particles?

A: Each model of dark matter has its strengths and weaknesses in different regimes. Sterile neutrinos are compelling since they can explain neutrino oscillation and dark matter. Warm dark matter closes some of the gaps between simulated and observed galaxy dynamics and properties. Cold dark matter doesn't require an emission line from annihilation since it has not been observed yet (except for 3.5 keV line). The evidence is not overwhelming for either case as of now.

A:
easier to reconcile with our current understanding of particle physics and the current measured limits on possible undiscovered particles?

Dark matter whether cold or hot or lukewarm needs frontier particle physics research, i.e. beyond the standard model, which is our current understanding. All theories can be accommodated within present limits,  as long as the LHC does not produce a supersymmetric candidate (the next level of sought after standard physics) to nail down a WIMP, necessary as a candidate for dark matter.


text:
Q: Select last row and sum of column in MySQL query My table:
date        Id  name    amount  payment
01/05/2017  01  Maxi    50000   Dec'16
01/10/2017  02  Shirly  50000   Jan'17
01/28/2017  01  Maxi    100000  Jan'17
02/12/2017  02  Shirly  50000   Feb'17

What query do I need to get this in MySQL?
Id  name    SUM(amount)  LAST(payment)
01  Maxi    1,50,000      Jan'17
02  Shirly  100,000       Feb'17

A: SELECT Id,name,SUM(amount),MAX(STR_TO_DATE(payment,'%b'%y')) AS LAST(payment) FROM TABLENAME GROUP BY Id

Try above code. Hope this will help you.

A: You can use group_concat to accumulate the payment values in a certain order, and then use substring_index to extract the first from that:
select   id,
         name,
         sum(amount),
         substring_index(group_concat(payment order by date desc), ',', 1)
from     mytable
group by id

This assumes you want to take the last payment in the order by the date column. The payment column seems to be a non-date value, which will be useless to sort by.
If you need to take the last value of payment in the order of payment date, you should define that column as a date. Then you can do a simple max:
select   id,
         name,
         sum(amount),
         max(payment)
from     mytable
group by id


text:
Q: Нету класса у блока span из за того что на некоторых отелях нету оценки, выдает ошибку что у блока нету атрибута текст. Как можно обойти это
код:
import requests
import lxml
from bs4 import BeautifulSoup
import csv

def get_data(url):
    headers = {
        'User Agent': 'Mozilla / 5.0(WindowsNT10.0; Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 110.0.0.0 Safari / 537.36'
    }

    req = requests.get(url=url)

    #with open('index.html', 'w', encoding='utf8') as file:
        #file.write(req.text)

    soup = BeautifulSoup(req.text, 'lxml')

    hotel_cards = soup.find_all('li', class_='item')
    #print(hotel_cards)
    for hotel_url in hotel_cards:
        hotel_url = 'https://101hotels.com' + hotel_url.find('a').get('href')
        #print(hotel_url)

    for title_hotels in hotel_cards:
        title_hotels = title_hotels.find('a').text
        #print(title_hotels)

    for hotel_price_result in hotel_cards:
        hotel_price = hotel_price_result.find('span', class_='price-highlight').text.strip()
        hotel_price2 = hotel_price_result.find('span', class_='currency').text.strip()
        price_with_currency = f'{hotel_price} {hotel_price2}'
        #print(price_with_currency)

    for hotel_rating in hotel_cards:
        hotel_rating = hotel_rating.find('span', {"itemprop": "ratingValue"}).text.strip()
        print(hotel_rating)

def main():
    get_data('https://101hotels.com/main/cities/yuzhno-sakhalinsk')

if __name__ == '__main__':
    main()

A: Можно исправить следующим образом:
import requests
import lxml
from bs4 import BeautifulSoup
import csv

def get_data(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
    }

    req = requests.get(url=url, headers=headers)

    soup = BeautifulSoup(req.text, 'lxml')

    hotel_cards = soup.find_all('li', class_='item')

    hotels = []

    for hotel_card in hotel_cards:
        hotel_url = 'https://101hotels.com' + hotel_card.find('a').get('href')
        title_hotel = hotel_card.find('a').text
        hotel_price_result = hotel_card.find('span', class_='price-highlight')
        hotel_price = hotel_price_result.text.strip() if hotel_price_result else ''
        hotel_price_currency = hotel_card.find('span', class_='currency')
        hotel_price_currency = hotel_price_currency.text.strip() if hotel_price_currency else ''
        hotel_price_with_currency = f'{hotel_price} {hotel_price_currency}'
        hotel_rating_result = hotel_card.find('span', {'itemprop': 'ratingValue'})
        hotel_rating = hotel_rating_result.text.strip() if hotel_rating_result else ''

        hotels.append({
            'url': hotel_url,
            'title': title_hotel,
            'price': hotel_price_with_currency,
            'rating': hotel_rating
        })

    return hotels

def main():
    hotels = get_data('https://101hotels.com/main/cities/yuzhno-sakhalinsk')
    with open('hotels.csv', 'w', encoding='utf8', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['Title', 'URL', 'Price', 'Rating'])
        for hotel in hotels:
            writer.writerow([hotel['title'], hotel['url'], hotel['price'], hotel['rating']])

if __name__ == '__main__':
    main()


text:
Q: Passing multiple file names to shell script from java I want to pass multiple filenames (7 to 10) to a shell script from java code.The filenames are fetched from Database depending on conditions, so the number of files is not fixed. The max will be 10 file names.
In the shell script i want to copy all these files to a different directory.
What i am doing is
cp -p "$@" /dir/temp/
But this dosent seem to work.
I am a newbie in unix and shell scripting.
Thanks.

A: You can use a loop where the contents of $@ is copied one by one


text:
Q: How to populate a DBComboBox control from a table in Delphi 7? The programming environment is Delphi 7, the DBMS is MySQL.
I have this table definition:
DROP TABLE IF EXISTS language;
CREATE TABLE IF NOT EXISTS language (
    language_id   TINYINT       NOT NULL   AUTO_INCREMENT,
    language      VARCHAR(16)   NOT NULL,
    PRIMARY KEY  (language_id),
    UNIQUE       (language)
) ENGINE=InnoDB;

Now, how do I go about populating a DBComboBox with data from the language table in such a way that the user can't see the language_id column but it's there and I can use it? But it may as well be just a ComboBox.

A: You need to fill it via its Items property. The chosen item is used as a field value.
What you probably want is a lookup combobox. It's called TDBLookupComboBox. You should be able to get it working once you find that one.

A: I agree with the answer above, some simple example code is as per :
with MyDataSource1.DataSet
do begin
   Open;
   DBComboBox1.Properties.Items.clear;
   while not EOF do begin
       DBComboBox1.Properties.Items.Add(fieldbyname('language').asstring);
       next;
   end;
end;


text:
Q: Enter full screen mode in wpf browser .xbap hosted in asp.net I has searched a lot but failed to success.
I wrote media player in Wpf Browser, then I deploy my .xbap file inside asp.net aspx file.
now I need my media player will be able to switch into full screen mode, Someone have any idea?
I tried many ways, first I don't want to play with my height\width of my controller (This is not a full screen mode), second I tried the following code:
App.Current.MainWindow.WindowState = WindowState.Maximized;

But I got the following message:
Cannot perform this operation when hosted in browser.

Anyone can help me???

A: Regular basic fullscreen not exist in WPF Browser, there are some solutions to create bypass to this problem.

*

*Use Window instead of Page (This will require full trust application) and then the following line will work fine:
App.Current.MainWindow.WindowState = WindowState.Maximized;

*Use IE kiosk mode, but then your application will open in a new proccess,

*Use PopUp window but then you can only cover 75% from browser size.

*Use silverlight!!


text:
Q: How to navigate page number in word 2016? I know I can go to "Navigation" - "Pages" and scroll down the side panel to certain pages. But can I directly go to a particular page by typing the page number?

A: Navigate to the search box (e.g. Ctrl + F), then in the "Find and Replace" box, find "Go To" and "Page". Type the page number there.


text:
Q: Hashicorp Vault fetch secrets in browser with certificate authentication in javascript I have a Hashicorp Vault server deployed with tls enabled to be able to login with a certificate. My certificate is stored in my browser certificate store.
I want to request data from the vault in my frontend react app.
Now to be able to request data from the vault with the certificate, I have to call :
POST "https://{vault_domain}/v1/auth/cert/login"

The first time I call the endpoint I get prompted to select the certificate in my browser certificate personal store. And then I get the response with the client_token.
Then I use the client_token in the header of all my vault calls to be authorized to call the vault endpoints. For example getting the public key key_name :
fetch("https://{vault_domain}/v1/transit/keys/key_name", {headers: { "X-Vault-Token": {client_token}}}

I find it very annoying to have to call the login endpoint to get the token and use token to make the other calls. Am I doing it right ? Is there an other way to do it ?  To be automatically authorized if the certificate is in the store ?
And also is there a way to automatically check if a valid certificate is available and use it without prompting the user ?


text:
Q: Why my jquery don't take that classes of this iframe? I'm trying to get all classes whose name is "titular_portada".
There are a lot, but for some reason is not working:
<!DOCTYPE html>
<html lang="es">
<head>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    <iframe src="https://vandal.elespanol.com" id="iframe" width="100%" height="100%"></iframe>
    <script src="js/jquery-3.6.0.js"></script>
</body>
</html>

$(window).on("load", function() {
    $("#iframe > .titulo_portada").each((i, el) => {
        console.log(el);
    });
});

A: $(window).on("load", function() {
    var iframe = document.getElementById("iframe");
    var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
    $(".titulo_portada",$(iframeDocument)).each((i, el) => {
        console.log(el);
    });
});

It should work, but jsfiddle at https://jsfiddle.net/NickU/65dxzg3s/9/
shows errors "Uncaught SecurityError: Blocked a frame with origin "https://fiddle.jshell.net" from accessing a cross-origin frame."


text:
Q: Pythonic and compact way to compare the key in dict Just want to know a good way how to do this:
a = {'key':'value'}
if 'key' in a:
    if a['key'] == 'value':
        # do something ...

The problem is sometimes I need to handle cases whe "key" is actually "@key", So I don't want to duplicate the same code with if '@key' in a: ....
So the question is how to handle both cases in most Pythonic and more compact way?

A: Here's how I would go about doing this:
a = {'key':'value'}
if any(a.get(key, None) == 'value' for key in ('key','@key')):
    # do something ...

A: What about this:
if a.get('key', a.get('@key', None)) == 'value':

This combines both keys (and gets rid of the slightly non-Pythonic use of if... in... followed by a['key']).

A: Another idea is to create a function which will act as a holder for the code (well, that's more or less what functions are for):
a = {'key':'value'}

def handle(key):
    if key in a:
        if a[key] == 'value':
            # do something...

handle('key')
handle('@key')

This will be a good solution if you actually have to do something with key (like for example update existing entry).

A: What you are looking for is a function like a.get('key') that checks more than one key. Therefore, I would write that general function. That's the most pythonic way, in my opinion, and leads to the most compact and readable code when you use it.
1) Here's one way:
def dget(d, keys, default=None):
    for key in keys:
        try: return d[key]
        except KeyError: pass
    return default

...

a = {'key':'value'}
if dget(a, ['key', '@key']) == 'value':
    #do something

2) You could be less general if you always want to look for exactly 'key' and '@key'.
def dget(d, key, default=None):
    return d.get(key,d.get('@' + key, default))

...

a = {'key':'value'}
if dget(a, 'key') == 'value':
    #do something

3) Finally, you could extend the dict class. You would rewrite the get method, so that you could just
a = mydict()
a['key'] = 'value'
if a.get(['key', '@key']) == 'value':
   #do something

A: If you have more potential patterns than just 'key' and '@key', you could use a regex on each key and test the value:
import re

a = {'key':'value', '@key':'value', '#key':'value', 'k':'value', 'key2':'val'}
print [k for k,v in a.items() if re.search(r'.?key',k) and v=='value']
# ['@key', '#key', 'key']


text:
Q: Программы для верстки! Я увлекся веб версткой сайтов из psd шаблонов.Хочу спросить какие приложения помогут мне в этом.Пока у меня есть atom[с кучей плагинов] , avocode , gimp , opera[для просмотра результата].

A: *

*Visual Studio Code - лучшая альтернатива для Atom

*$ Dreamweaver - редактор от Adobe, с возможностью визуальной компоновки, может открывать/импортировать PSD

*Brackets - от Adobe, (может открывать/импортировать PSD, но по моему сейчас поддержка этой опции прекращена)

*$ WebStorm - "самый лучший" редактор для веб-разработчика

Альтернативы Chrome/Opera при разработке есть, например Firefox  Quantum. Но думаю пока Chrome самый подходящий.
Для обучения хорошо походят сервисы типа CodePen.
VsCode/Atom, Chrome - вполне достаточно для работы.

A: Sublime Text 3 - Редактор
И еще скачай несколько браузеров, чтобы делать кроссбраузерную верстку


text:
Q: Use group price in shopping cart price rule conditions Is there a properly way to use the product "group price" in the "shopping cart price rules" conditions, like the special_price attribute?
For some of my "shopping cart rules", I need to exclude from products that have special_price AND products that have group_price defined.
For the special_price, it is working out of the box.
Someone has probably already had the same requirement?
Thanks in advance for the feedback.

A: NO there is no way.
Group price is not a simple attribute. It's value is saved as a serialized array that cannot be used in promo rules.


text:
Q: Im getting property value does not exist on type 'eventtarget' im trying to do a filter of a table but i get an error un my event,target.value
I am getting error "Property 'value' does not exist on type 'EventTarget'" what is the solution
Table Filtering

<ng-template pTemplate="header">

        First Name
        Last Name
        Age

            <input pInputText type="text" (input)=
            "myTab.filter($event.target.value, col.field, col.filterMatchMode)" />

</ng-template>

<ng-template pTemplate="body" let-people>

            {{ people.firstname }}

            {{ people.lastname }}

            {{ people.age }}

</ng-template>


text:
Q: How can I obtain programatically the location prefix of an App Engine project ID? I am using Google App Engine standard in python 3.7 and need to obtain the legacy safe url for an Entity in the Datastore using its Key.
In order to achieve this I need to know the location_prefix.
https://googleapis.dev/python/datastore/latest/_modules/google/cloud/datastore/key.html#Key.to_legacy_urlsafe
How can I obtain that value programatically in Python for a given project id?

A: Is this what you are looking for?: Retrieving Entities from Keys
appengine/standard/ndb/entities/snippets.pyView on GitHub

You can also use an entity's key to obtain an encoded string suitable
  for embedding in a URL:

url_string = sandy_key.urlsafe()

This produces a result like 'agVoZWxsb3IPCxIHQWNjb3VudBiZiwIM' which can later be used to reconstruct the key and retrieve the original entity:
sandy_key = ndb.Key(urlsafe=url_string)
sandy = sandy_key.get()


text:
Q: If a surface $S$ admits two differentiable orthogonal families of geodesics $\Rightarrow$ The Gaussian curvature of $S$ is zero. This question was previously posted in Orthogonal differentiable family of curves . But I'm facing unsolved issues.
I'm still interested in solve the following exercise:

QUESTION: We say that a set of regular curves on a surface $S$ is a differentiable family of curves on $S$ if the tangent lines to the curves of the set make up a differentiable field of directions. Assume that a surface $S$ admits two differentiable orthogonal families of geodesics. Prove that the Gaussian curvature of $S$ is zero.

where a differentiable field of directions is:

Definition: A field of direction $r$ in a open $U \cap S$ is a correspondence which assigns to each $p$ $\in$ $U\cap S$ a line $r(p)$ in $T_pS$ passing through $p$. $r$ is said to be diferentiable at $p$ $\in$ $U \cap S$ if there exists a nonzero differentiable vector field $w$, defined in a neighborhood $V\cap S$ $\subset$ $U \cap S$ of $p$, such that for each $q$ $\in$ $V\cap S$, $w(q) \neq 0$ is a basis of $r(q)$; $r$ is diferentiable in $U\cap S$ if it is differentiable for every $p$ $\in$ $U$.

At the end of the book, Manfredo give us the following hint

Manfredo's Hint: Parametrize a neighborhood of $p\in S$ in such a way that the two families of geodesics are coordinate curves (Corollary 1, Sec. 3-4). Show that this implies that $F=0$, $E_v=0, $ $G_u = 0$. Make a change of parameters to obtain that $\bar{F} = 0$, $\bar{E} = \bar{G} =1$.

where Corollary 1, Sec.3-4 is:

Corollary 1. (Sec.3-4): Given two fields of directions $r$ and $r'$ in an open set $U \subset S$ such that at $p$ $\in$ $U$, $r(p) \neq r'(p)$, there exists a parametrization $x$ in a neighborhood of $p$ such that the coordinate curves of $x$ are the integral curves of $r$ and $r'$.

And now my problem appears.
Let $\tau_1$ be the field of directions associated to the first family, and $\tau_2$ be the field of directions associated to the second family (note that $\tau_1$ and $\tau_2$ are orthogonal).
I really don't understand why when we apply the Corollary 1 (Sec. 3-4), on the fields of directions $\tau_1$ and $\tau_2$, we end up getting a chart $x: U \subset \mathbb{R}^2 \rightarrow W \cap S$, in such a way that the coordinate curves, $x(u, c^{te})$ and  $x(c^{te},v)$, are the two families of geodesics.
From what I know, when the coordinate curves are the integral curves of
 fields of directions $\tau_1$ and $\tau_2$, we can only conclude that $x_u(u, c^{te})$ is l.d with the direction  $\tau_1(x(u, c^{te}))$ and  $x_v(c^{te},v)$ is l.d. with the direction $\tau_2(x(c^{te}, v))$.
GI can't see any reason for these coordinate curves to solve the geodesic's differential equation. In the best case scenario I was only able to conclude that the coordinate curves have the same path of a geodesic (which implies nothing).
Does anyone know how I outline this problem and solve the exercise?


text:
Q: How to change the default scope of attributes from Private to Public in Enterprise Architect? Does anybody know how to change the default scope for attributes of UML classes in Enterprise Architect (I am using version 9.2)? When adding a new attribute, it is by default set to Private. I am mainly using Enterprise Architect for data modelling, and all the attributes should be public.
Currently I have to manually change the scope from Private to Public for every single attribute I add, so I would save me quite some time if I could someway set the default scope for new attributes to Public.

A: You can use the following script to change all private attributes to public in a package.
!INC Local Scripts.EAConstants-JScript

function main()
{
    Repository.EnsureOutputVisible( "Script" );
    Repository.ClearOutput( "Script" );

    // Get the type of element selected in the Project Browser
    var treeSelectedType = Repository.GetTreeSelectedItemType();

    switch ( treeSelectedType )
    {
        case otPackage :
        {
            // Code for when a package is selected
            var pkg as EA.Package;
            pkg = Repository.GetTreeSelectedObject();

            Session.Output("----------------------------------------");
            Session.Output("Processing... " + pkg.Name);

            for (var i = 0 ; i < pkg.Elements.Count; i++)
            {
                var element as EA.Element;
                element = pkg.Elements.GetAt(i);

                Session.Output("Analyzing : " + element.Name);

                for (var j = 0; j < element.Attributes.Count; j++)
                {
                    var attrib as EA.Attribute;
                    attrib = element.Attributes.GetAt(j);

                    if (attrib.Visibility == "Private")
                    {
                        attrib.Visibility = "Public";
                        attrib.Update();
                        Session.Output("- Changed attribute :" + attrib.Name);
                    }
                }
                element.Update();
                element.Refresh();
            }

            Session.Output("----------------------------------------");
            break;
        }

        default:
        {
            // Error message
            Session.Prompt( "This script does not support items of this type.", promptOK );
        }
    }
}

main();

TIPS: If you still need some private attributes, you can add additional flag/character in the attribute name, then modify the above script to parse attribute name and only change it to public when you find the flag and remove the flag from the attribute name.


text:
Q: Detect 220Vac signal on Microcontroller I'm developing a module and the control switch may be at long distances.
Considering I have the 127 or 220Vac input, I want to use that for switch signal. I believe is better, instead of making a pull up and send 5V through a long wire where can have a lot of interference.
My idea is to make as the schematic bellow:

For the optocoupler, I'm considering use TCMT1109 - CTR > 200%
R1 - to discharge the capacitor when the device gets unplugged.
R2 - to protect against inrush current.
D1 - to ensure C1 can (dis)charge every half cycle and to protect LED D2 against being reverse biased.
Can anybody help me to dimension R1, R2, C1 and D1? Or perhaps indicates a good reference?

A: Consider using an industry-standard interface isolation module such as...

http://www.opto22.com/site/pr_details.aspx?cid=4&item=IAC5A
It has the advantage of regulatory approvals to avoid any problems with "home-made" DIY solutions in a commercial or industrial system.

A: Normally constant current switches are used for long distances with suitable low voltage DC filter. e.g. 4-20mA for sending 0 or 1.  Then disconnect faults can be detected. For sensing line voltage decide on brown out threshold and decide how critical tolerance is, as the opto-tranny has a wide range in hFE.
For current mode, twisted pair immunity is ok with V+ based on conductor losses on both wires.  This is an old std. method for PLC sensors.
Another method would divide AC to 12 or 24 Vdc unfiltered down to send low voltage DC e.g. then drive 10 to 20mA LED opto as a current switch with a suitable RC decay cap on the collector so that switch out is detected below 80V.. Opto-PD's are more accurate than transistors. With opto-diodes gain is often guaranteed to 50% min. so pullup value and threshold can be computed.


text:
Q: Flutter RichText ellipsis is shown separately I'm trying to use the RichText widget with ellipsis on text overflow, but the dots are shown separated by a space of the last word, like this:
"Lorem Ipsum is simply dummy text of the printing and ..."
When the correct form should be like this:
"Lorem Ipsum is simply dummy text of the printing and..."
This is the code:
Expanded(
  child: RichText(
    overflow: TextOverflow.ellipsis,
    text: TextSpan(
        style: DefaultTextStyle.of(context).style,
        children: <TextSpan>[
          TextSpan(text: "Lorem Ipsum is simply dummy text "),
          TextSpan(
            text: "of the printing and typesetting industry",
            style: TextStyle(
                fontStyle: FontStyle.italic
                ),
          ),
        ]),
  ),
)

Is there a solution for this?

A: not fully sure but remove the space from last
change "Lorem Ipsum is simply dummy text " to "Lorem Ipsum is simply dummy text"
 Expanded(
  child: RichText(
    overflow: TextOverflow.ellipsis,
    text: TextSpan(
        style: DefaultTextStyle.of(context).style,
        children: <TextSpan>[
          TextSpan(text: "Lorem Ipsum is simply dummy text"),
          TextSpan(
            text: "of the printing and typesetting industry",
            style: TextStyle(
                fontStyle: FontStyle.italic
                ),
          ),
        ]),
  ),
)

i hope it helps..

A: This space is actually space of the text. When I try your code, my result is here,

If I remove g char into typesetting, result is

So, I think its not about ellipsis or richtext. Maybe not the exact answer but maybe you can think something else.


text:
Q: Problems starting Postgresql with sudo Running Ubuntu 17.10 and I am having an issue running Postgres. It was working a couple weeks ago, but now I have this problem.
sudo su postgres psql

/usr/bin/psql: line 19: use: command not found
/usr/bin/psql: line 20: use: command not found
/usr/bin/psql: line 21: use: command not found
/usr/bin/psql: line 22: use: command not found
/usr/bin/psql: psql: line 24: syntax error near unexpected token `$version,'
/usr/bin/psql: psql: line 24: `my ($version, $cluster);'

I have no idea what to do, the syntax looks normal.

A: Try
sudo -u postgres psql

instead.
I actually do not know what your command does. A quick look to man su does not really clarify what su will do with extra arguments but obviously it is not starting psql, it is probably feeding the file contents to the shell.


text:
Q: 17.10 gnome-terminal resize info with CompizConfig Settings Manager From a time even far before Ubuntu 13.04, there was always a method, when one resized Gnome Terminal, to see an immediate visual tooltip which showed what length and width you were resizing Gnome terminal to.
This used to be the default with Ubuntu, then it was made optional.  When it became optional, the way to launch it would be to launch  CompizConfig Settings Manager (ccsm) and have "resize info" enabled.
I just upgraded to 17.10 today (I waited several weeks to upgrade since I was burned by bug #1674838 crashing my machine every day earlier this year, and had to wait several weeks for a fix, and figured this time I would wait a few weeks for things to settle down).  I waited several weeks because I was hit with bug #1674838 earlier this year, and dreaded what bugs and pulled features I would encounter this time around.
I enabled resize info for all windows in ccsm, but don't see the tool tip for Gnome Terminal any more.  Has the method of doing this changed?  Or has this useful feature which Ubuntu had since before 13.04 just been tossed into the dustbin?  My laptop runs Ubuntu and still has this tooltip running, and now I dread the idea of upgrading it to 17.10.
Is there a way to turn this on, or has the feature been discarded after existing for years?
Also, I don't really have the time to do it, but I have had patches applied to Gnome and fd.o projects before...if this feature has been tossed, what should I target to program it back in, just for myself if need be?

A: This seems to be a Wayland specific issue (see this bug report for Fedora).
As a workaround you may switch back to an Xorg session for now.

A: This has bothered me for several versions of Ubuntu, currently on 17.10. I got motivated to find a workaround because I'm now switching between 80-column and 100-column formatted code.
I don't want to switch to Xorg. So my solution is to run this command inside the Gnome Terminal when I want to resize:
$ watch stty size

then use the mouse to resize. The size information updates instantly as the mouse moves, not delayed by 2 seconds. (It looks like the 'watch' command traps the SIGWCH signal generated by the mouse resize and reruns the 'stty' command.)


text:
Q: SpringMVC Annotation Validation - DataBinding data type When using custom validation under this scenario:
if(officer.getBadgeId() == 0){

        errors.rejectValue("badgeId", "badgeId.required");
}

if the POJO/Model officer has a datatype of int for the badgeId can a string be set as the error message for the attribute? Or the datatype of the attribute does not matter when doing validation and returning error messages to the view.
If it is an issue how do you handle this scenario in terms or returning an error message to the user from custom validation

A: Error message will be of type String only.

void     rejectValue(String field, String errorCode, String
  defaultMessage)
            Reject the given field of the current object, using the given error description.

Spring doc link.

A: This is an example from: http://alasdoo.com/2011/07/data-validation-conversion-basics-custom-error-messages-in-spring-mvc/
if (user.getBirthYear()!=null)
            if ( user.getBirthYear() <MINI_YEAR || user.getBirthYear() >MAX_YEAR)
                e.rejectValue( "birthYear", "user.birthYear.outOfInterval");
    }

Here you can see birthYear being a date type is returning an error message that is of type String stored in a message.properties file.


text:
Q: Countif function (excel) in R I have a dataset "a" with a column "id" with about 23,000 rows, which are unique in this dataframe. I want to count the appearance frequency of these unique values in another two datasets "b" and "c".
To do this, I tried the code:
count1 <- as.data.frame(apply(a,1,function(x)sum(b$id==x[45])))
a <- cbind(a,count1)

, since "id" is the 45th column in the dataframe "b".
The code works for counting in b, but when I tried the same code for counting the frequency of "id" in dataframe "c":
count2 <- as.data.frame(apply(a,1,function(x)sum(c$id==x[17])))

"id" in dataframe "c" is in the 17th column. The frequencies of all "id"s are counted as 0, which is not the case it should be. Could anyone suggest where the problem is or how to fix this problem?

A: We can actually do this in a way that might at first seem a little weird, but is relatively straight forward. Let's start by working with just data frames a and b and let's simplify things a bit. Let's assume that the id variable in both a and b are the following:
a_id <- 1:5
b_id <- 1:5

In this simple example, a_id and b_id are exactly identical. What we want to know is how many times each of the values in a_id shows up in b_id. We obviously know the answer is one time each, but how do we get R to tell us that? That's where the table function can come in handy:
table(a_id, b_id)
#     b_id
# a_id 1 2 3 4 5
#    1 1 0 0 0 0
#    2 0 1 0 0 0
#    3 0 0 1 0 0
#    4 0 0 0 1 0
#    5 0 0 0 0 1

That might look a little ugly, but you can see that we have our b_ids on the top (1-5) and our a_ids on the left-hand side. Down the diagonal, we see the counts for how many times each value of a_id shows up in b_id, and it's 1 each just like we already knew. So how do we get just that information? R has a nice function called diag that gets the main diagonal for us:
diag(table(a_id, b_id))
# 1 2 3 4 5
# 1 1 1 1 1

And there we have it. A vector with our "countif" values. But what if b_id doesn't have all of the values that are in a_id? If we try to do what we just did, we'll get an error because table doesn't like it when two vectors have different lengths. So we modify it a bit:
a_id <- 1:10
b_id <- 4:8
table(b_id[b_id %in% a_id])
# 4 5 6 7 8
# 1 1 1 1 1

A couple new things here. The use of %in% just asks R to tell us if a value exists in a vector. For example, 1 %in% 1:3 would return TRUE, but 4 %in% 1:3 would return FALSE. Next, you'll notice that we indexed b_id by using [. This only returns of the values of b_id where b_id %in% a_id is TRUE, which in this case is all of b_id.
So what does this look like if we expect more than one value of each a_id in b_id, but not every a_id value to be in b_id? Let's look at a more real example:
a_id <- 1:10
b_id <- sample(3:7, 1000, replace=TRUE)
table(b_id[b_id %in% a_id])
#   3   4   5   6   7
# 210 182 216 177 215

Like I said, it might seem a little weird at first, but it's relatively straight forward. Hopefully this helps you more than it confuses you.


text:
Q: UIMA, extraction semi-structured (tabular) data out of the text I am working on application using Apache UIMA for NLP task about domain specific entity extraction.
The use case is following:
There is Office document or PDF (both scanned, non-scanned) as the input, the application needs to get domain specific data out of it. The document could have free text or/and key-values,  tables,  pictures
What are the challenges:
Sometimes the original document can contain tables (w/ metadata or w/o). There is no problem to annotate specific standalone token. However, I am looking for some example of building relationships between annotated tokens inside the table (say, it has headers with some business attributes and rows underneath contains the attributes values so I need to create proper relationships as well as to define groups so I can later extract instances of information, say, each row of the table is a one business entity instance compiled of some primitive entities and bounded by relationships).
So there are questions:

*

*I am looking for something that is more flexible and human readable in terms of the annotation rules i.e. can I use Ruta in such scenarios when table-form data needs to be annotated? Any rule examples would be very help. The research over this topic did not give much yet.

*I am looking for approach how to extract the data if no metadata exist (see below. Would Ruta suites here or anything else? Any examples would be appreciated

*I am looking for the tools which will simplify work with annotated text i.e. for profiling, testings purposes. Again, would Ruta solve it?

Examples:

*

*OCR w/ metadata, data after extract stage:

      Name
      Favorite Color

      Bob
      Yellow

      Michelle
      Purple

*OCR w/o metadata, data after extract stage:

Name    Favorite Color
Bob Yellow
Michelle    Purple

A: Question 1:
In my very subjective opinion, Ruta is very well suited for those tasks, especially if the text processing should be implemented in UIMA. There are countless options to specify this extraction task in Ruta depending on the available annotation and the structure of the tables. Here is an exemplary set of rules building upon the output of the HtmlAnnotator (actually, it's only a single rule):
PACKAGE uima.example;

TYPESYSTEM utils.HtmlTypeSystem;

ENGINE utils.HtmlAnnotator;

EXEC(HtmlAnnotator, {TAG});

ADDRETAINTYPE(WS);
TAG{->TRIM(WS)};
REMOVERETAINTYPE(WS);

DECLARE Relation (Annotation attribute, Annotation value);

BLOCK(tables) TABLE{} {
    TR{-CONTAINS(TH)-> CREATE(Relation, "attribute" = a, "value" = v)}
        <-{# a:TD v:TD;};
}

Question 2:
You can of course recreate the table structure of question 1 using rules and then apply the same rules. Identifying the table structure strongly depends on the information you have about the tables and what output the text converter produces, e.g., do you know what kind of attributes/values will occur or uses the converter tabs for separating cells. Here's again an exemplary set of rules building upon the output of the PlainTextAnnotator:
PACKAGE uima.example;

TYPESYSTEM utils.PlainTextTypeSystem;

ENGINE utils.PlainTextAnnotator;

EXEC(PlainTextAnnotator, {Line});

ADDRETAINTYPE(WS);
Line{->TRIM(WS)};
Paragraph{->TRIM(WS)};
REMOVERETAINTYPE(WS);

DECLARE Relation (Annotation attribute, Annotation value);
DECLARE Attribute, Value;

DECLARE TextTable, Row;
DECLARE HeaderInd, HeaderLine;

// mock some annotations
"Name" -> HeaderInd;
"Color" -> HeaderInd;

Line{CONTAINS(HeaderInd, 50, 100, true)-> HeaderLine};

Paragraph{STARTSWITH(HeaderLine)-> TextTable};
TextTable->{Line{-PARTOF(HeaderLine)-> Row};};

FOREACH(row) Row{}{

    row{CONTAINS(W,2,2)} ->{W{-> Attribute} W{-> Value};};
    row{-> CREATE(Relation, "attribute" = Attribute, "value" = Value)};
}

Question 3:
The UIMA Ruta Workbench provides several useful tools of an IDE, which include amongst others profiling and testing.
DISCLAIMER: I am a developer of UIMA Ruta


text:
Q: Birthday surprise I'm an absolute beginner in coding. In fact, I'll probably never do it again ;)
I'm trying to create this very simple website for my boyfriend as a surprise (he's a developer). And now I'm just encountering one problem after the other :(
I've decided on html (although I'm so desperate by now that I'd be willing to go with anything).
<!DOCTYPE html>

Hello, world (especially Mitchell)

I want to show you something…

Remember that time when I was losing so many rounds of Quizduell that even you noticed? Well, turns out I was doing that on purpose. I was trying to spell something out for you. But as I found out the hard way, it is actually really hard to lose specific games on purpose in the exact order you need. It seemed like I needed to change my plans…

This is all I have so far. And it's just going to be a bit more text, a couple more images and maybe a little bit of colour and layout (if I can manage that).
Right now my biggest problem is inserting the images.
It just doesn't work :(
Can someone please help me?

A: You have to close all of your tags. You see the  and  tags, etc.? All of those tags with /'s before them are the end of a section. First of all, you need that for your  and  tags. You also need it on your image tag, but there is a special way to do so for such tags as images. Simply add a space followed by a slash at the end of the angled brackets of the image tag:

This basically allows the tag to be on one line, making code simpler.
Good job on your project so far, and good luck!
Fixed version of your code:
<!DOCTYPE html>

Hello, world (especially Mitchell)

I want to show you something…

Remember that time when I was losing so many rounds of Quizduell that even you noticed? Well, turns out I was doing that on purpose. I was trying to spell something out for you. But as I found out the hard way, it is actually really hard to lose specific games on purpose in the exact order you need. It seemed like I needed to change my plans…

`
In case this doesn't work, make sure 7.JPG is in the directory of the .html file. The filename is case-sensitive.

A: First of all, I thought that it was very sweet of you to do that!
Here is a sample html that might help you out.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

The body and the html is wrapped here, and the image src is using relative path to find the image.

A: How sweet!
I would suggest you to use a WYSIWYG (What You See Is What You Get) editor to design like Microsoft Word. After you are done with the design, go to tools > source code. There you can get the html code for your design. Simply copy the code from there and paste it within the  tag. And done! You have designed the webpage!
Link to a WYSIWYG Editor: click here
For image issues, make sure that they are placed in the same directory where the .html file is kept. It should work properly.


text:
Q: Contact form reply to sender So I've completed a contact form made in PHP. After testing it sends emails, but in the email header it is not capturing the sender's name or email address. It shows up as sh-908129268@eu.hosting-webspace.io
Is there a way to correct that? I need to be able to respond to emails.
The inputs are as follows:
<form id="contact" action="<?= $_SERVER['PHP_SELF']; ?>" method="post">

<input class="input is-small" type="text" name="name" placeholder="Text input" value="<?= $name ?>" >

<?= $name_error ?>

<input class="input" type="email" name="email" placeholder="Email Address" value="<?= $email?>">

<?= $email_error?>

// back-end file

$sendTo = 'test@email.com';
        $subject = 'Business Enquiry';
        $headers = "";

        $headers .= "Sent From: ".$name. "\r\n";
        $headers .= "Reply To: ".$email. "\r\n";
        $headers .= "Message: ".$message. "\r\n";

        if (mail($sendTo, $subject, $message, $headers)) {

            $success = "Thank you for your message, I will reply as soon as I can.";
            $name = $email = $message = ''; // resets all fields
        }

A: You cannot pick the names of the headers freely, you have to adhere to the standard (RFC 5322 Internet Message Format).
Your header "Sent From" should be just From, your header "Reply To" should be Reply-To and your header "Message" shouldn't be in the headers at all - you already pass the message as such into the mail function.

A: All fixed now, thanks. All I needed was to specify one header ,
$headers = "From: ".$email;
So it's just $subject and $headers


text:
Q: How to print a function in the main function import math

return def is_valid(filing_status, income):
  """Function determines whether the input is valid. If valid, it returns 'True'. The filing status must come from the list of options given and the income must be an integer greater than 0. If these qualifications are not met, the function will return 'False'."""

   x = filing_status
   y = income
   def setup(x, y):
   if x in ('single', 'married filing jointly', 'married filing separately', 'widow', 'head of household') and y >= 0:
    print "True"
   else:
    print "False"
   setup(x, y)

return def tax(filing_status, income):

"""Fuction displays the value of taxes that different groups of people are required to pay based on their income."""

  f = filing_status
  i = income
  def calculation(f, i):
  if f in ('single') and int(0 < i <= 9275):
     print int(i*0.100)
  elif 9276 <= i <= 37650:
     print int((i-9276.00)*0.15 + 9275.*0.1)
  elif 37651 <= i <= 91150:
     print int((i-37651)*0.25 + 28375*0.15 + 9275*0.1)
  elif 91151 <= i <= 190150:
     print int((i-91151)*0.28 + 53500*0.25 + 28375*0.15 + 9275*0.1)
  elif 190151 <= i <= 413350:
     print int((i-190151)*0.33 + 99000*0.28 + 53500*0.25 + 28375*0.15 + 9275*0.1)
  elif 413351 <= i <= 415050:
     print int((i-413351)*0.35 + 223200*0.33 + 99000*0.28 + 53500*0.25 + 28375*0.15 + 9275*0.1)
  elif i >= 415051:
     print int((i-415051)*0.396 + 1700*0.35 + 223200*0.33 + 99000*0.28 + 53500*0.25 + 28375*0.15 + 9275*0.1)
  calculation(f,i)

 return def tax(filing_status,income):
 c = filing_status
 d = income
   def calculation(c,d):
   if c in ('widow','married filing jointly') and 0 < d <= 18550:
     print int(d*0.1)
   elif 18551 <= d <= 75300:
     print int((d-18551)*0.15 + 18550*0.1)
   elif 75301 <= d <= 151900:
     print int((d-75301)*0.25 + 56750*0.15 + 18550*0.1)
   elif 151901 <= d <= 231450:
     print int((d-151901)*0.28 + 76600*0.25 + 56750*0.15 + 18550*0.1)
   elif 231451 <= d <= 413350:
     print int((d-231451)*0.33 + 79550*0.28 +76600*0.25 + 56750*0.15 + 18550*0.1)
   elif 413351 <= d <= 466950:
     print int((d-413351)*0.35 + 181900*0.33 + 79550*0.28 +76600*0.25 + 56750*0.15 + 18550*0.1)
   elif d >= 466951:
     print int((d-466951)*0.396 + 53600*0.35 + 181900*0.33 + 79550*0.28 +76600*0.25 + 56750*0.15 + 18550*0.1)
  calculation(c,d)

return def tax(filing_status,income):
  g = filing_status
  h = income
  def calculation(g,h):
    if g in ('married filing separately') and 0 < h <= 9275:
       print int(h*0.1)
    elif 9276 <= h <= 37650:
       print int((h-9276)*0.15 + 9275*0.1)
    elif 37651 <= h <= 75950:
       print int((h-37651)*0.25 + 28375*0.15 + 9275*0.1)
    elif 75951 <= h <= 115725:
       print int((h-75951)*0.28 + 38300*0.25 + 28375*0.15 + 9275*0.1)
    elif 115726 <= h <= 206675:
       print int((h-115726)*0.33 + 39775*0.28 +38300*0.25 + 28375*0.15 + 9275*0.1)
    elif 206676 <= h <= 233475:
       print int((h-206676)*0.35 + 90950*0.33 + 39775*0.28 +38300*0.25 + 28375*0.15 + 9275*0.1)
    elif h >= 233476:
       print int((h-233476)*0.396 + 26800*0.35 + 90950*0.33 + 39775*0.28 +38300*0.25 + 28375*0.15 + 9275*0.1)

    calculation(g,h)

return def tax(filing_status,income):
    m = filing_status
    n = income
    def calculation(m,n):
       if m in ('head of household') and 0 < n <= 13250:
          print int(n*0.1)
       elif 13251 <= n <= 50400:
          print int((n-13251)*0.15 + 13250*0.1)
       elif 50401 <= n <= 130150:
          print int((n-50401)*0.25 + 37150*0.15 + 13250*0.1)
       elif 130151 <= n <= 210800:
          print int((n-130151)*0.28 + 79750*0.25 + 37150*0.15 + 13250*0.1)
       elif 210801 <= n <= 413350:
          print int((n-210801)*0.33 + 80649*0.28 +79750*0.25 + 37150*0.15 + 13250*0.1)
       elif 413351 <= n <= 441000:
          print int((n-413351)*0.35 + 202550*0.33 + 80649*0.28 +79750*0.25 + 37150*0.15 + 13250*0.1)
       elif n >= 441001:
          print int((n-441001)*0.396 + 27649*0.35 + 202550*0.33 + 80649*0.28 +79750*0.25 + 37150*0.15 + 13250*0.1)

      calculation(m,n)

return def percent_of_income(tax, income):
   """Function calculates the percent of income that goes to taxes."""

    t = tax
    s = income
    def calc_percent (t, s):
       print (t/s)*100
    calc_percent(t, s)

return def main(filing_status,income):
  """Function brings the previous functions together to describe taxes and the percent of income of individuals based on their filing statuses"""

  w = filing_status
  o = income
  v = tax(filing_status, income)
  if w not in ('single', 'married filing jointly', 'married filing separately', 'widow', 'head of household'):
     print "Invalid input. Filing status must be 'single', 'married filing jointly', 'married filing separately', 'widow', or 'head of household'. Income must be greater than or equal to zero."
  if o < 0:
     print "Income must be greater than or equal to zero."
  else:
     return ('Tax: $', str(v))
     return ('Tax as % of income: $', str(percent_of_income(tax, income)) + '%')

Trying to print the tax and percent of income functions in the main. How do I reference this? I am not sure if the variables in the percent of income are  documented correctly, and everytime i try to run the function, it won't print the tax value inside of the string "Tax;". I also tried concatenating that.

A: I think I need a little more info to help you out, but I'll try.
It looks like with this function that you are only printing if the first or second ifs are executed. If they are not, you are executing the else, which only returns a tuple without printing. Also, the second return will not be executed. Once a return is executed, the function ends.


text:
Q: Proving any two elements in recursive sequence are coprime. A sequence $x_0, x_1, x_2, \ldots$ is defined recursively as follows:
$$x_0 = 3 \\ x_n = 2 + (x_0 \cdot x_1\cdot x_2\cdots x_{n-1})$$
I'm stuck at trying to prove that for any two different elements of the sequence, $x_i$ and $x_j$, it always holds that $x_i$ and $x_j$ are coprime.

A: Suppose $i < j$
and
$d|x_i$ and $d|x_j$.
Since
$0 \le i \le j-1$,
$x_j
=2+\prod_{k=0}^{j-1}x_k
=2+x_i\prod_{k=0, k\ne i}^{j-1}x_k
$,
$d | (x_j-x_i\prod_{k=0, k\ne i}^{j-1}x_k)
=2$
so
$d = 2$ or $d = 1$.
Since,
as
John Omielan
observed,
all the $x_n$ are odd,
$d=1$
so $x_i$ and $x_j$
are relatively prime.

A: Hint: apply the Euclidean algorithm to $x_i$ and $x_j$.

A: Since $x_n = 2 + \prod_{k=0}^{n-1} x_k$,
$$\gcd(x_i, x_n) = \gcd\left(x_i, 2 + \prod_{k=0}^{n-1} x_k\right) = \gcd\left(x_i, 2 + x_i \prod_{k=0,k\neq i}^{n-1} x_k\right)$$
Now, if m is any integer, then $\gcd(a, b + m\cdot a) = \gcd(a, b)$.
$$\gcd(x_i, x_n) = \gcd\left(x_i, 2 + x_i \prod_{k=0,k\neq i}^{n-1} x_k\right)= \gcd\left(x_i, 2\right) = 1$$
The last equation is true because it should be obvious that all $x_i$ are odd(only because the first is though).


text:
Q: SQLite pragma (journal_mode) statement persistence Let's say that I have a script called schema.sql which is used to allocate a new SQLite db with my desired schema.
If this script contains PRAGMA journal_mode = 'wal'; before any DML, is the database continually set to WAL mode? Or is journal mode something that needs to be configured on each connection/command?

A: The journal mode is only persisted for WAL mode. From the docs:

Unlike the other journaling modes, PRAGMA journal_mode=WAL is persistent. If a process sets WAL mode, then closes and reopens the database, the database will come back in WAL mode. In contrast, if a process sets (for example) PRAGMA journal_mode=TRUNCATE and then closes and reopens the database will come back up in the default rollback mode of DELETE rather than the previous TRUNCATE setting.

A: After some experimentation it turns out the journal mode is persisted.
To demonstrate:
PS C:\> sqlite3 TestDb.db

sqlite> PRAGMA journal_mode;
delete
sqlite> PRAGMA journal_mode = 'wal';
wal
// terminate session (ctrl+c)
PS C:\> sqlite3 TestDb.db
sqlite> PRAGMA journal_mode;
wal


text:
Q: Add link to image I need to add a hyperlink to an image. Here is my code. how do I add link to the image?
success: function(data, textStatus, jqXHR){
  $.each( data, function( idx, obj ) {
  //   $( "<img>" ).attr( "src", '/images/' + obj.Icon ).attr("title", obj.DisplayName).appendTo( "#images" );
});

A: Assuming that obj also contains the link address, and pretending that obj.Href is where it lives:
$.each( data, function( idx, obj ) {
  var i = $( "<img>" ).
    attr( "src", '/images/' + obj.Icon );

  $('a').
    attr('href', obj.Href).
    attr("title", obj.DisplayName).
    append(i).
    appendTo( "#images" );
});

A: You can do it like this:
$.each(data, function (idx, obj) {
    $("<img>").attr({
        src: '/images/' + obj.Icon,
        title: obj.DisplayName,
    }).appendTo("#images").wrap('<a href="url">');
});

http://jsfiddle.net/py25pL3c/


text:
Q: How to properly mock and unit test I'm basically trying to teach myself how to code and I want to follow good practices. There are obvious benefits to unit testing. There is also much zealotry when it comes to unit-testing and I prefer a much more pragmatic approach to coding and life in general. As context, I'm currently writing my first "real" application which is the ubiquitous blog engine using asp.net MVC. I'm loosely following the MVC Storefront architecture with my own adjustments. As such, this is my first real foray into mocking objects. I'll put the code example at the end of the question.
I'd appreciate any insight or outside resources that I could use to increase my understanding of the fundamentals of testing and mocking. The resources I've found on the net are typically geared towards the "how" of mocking and I need more understanding of the where, why and when of mocking. If this isn't the best place to ask this question, please point me to a better place.
I'm trying to understand the value that I'm getting from the following tests. The UserService is dependent upon the IUserRepository. The value of the service layer is to separate your logic from your data storage, but in this case most of the UserService calls are just passed straight to IUserRepository. The fact that there isn't much actual logic to test could be the source of my concerns as well. I have the following concerns.

*

*It feels like the code is just testing that the mocking framework is working.

*In order to mock out the dependencies, it makes my tests have too much knowledge of the IUserRepository implementation. Is this a necessary evil?

*What value am I actually gaining from these tests? Is the simplicity of the service under test causing me to doubt the value of these tests.

I'm using NUnit and Rhino.Mocks, but it should be fairly obvious what I'm trying to accomplish.
    [SetUp]
    public void Setup()
    {
        userRepo = MockRepository.GenerateMock<IUserRepository>();
        userSvc = new UserService(userRepo);
        theUser = new User
        {
            ID = null,
            UserName = "http://joe.myopenid.com",
            EmailAddress = "joe@joeblow.com",
            DisplayName = "Joe Blow",
            Website = "http://joeblow.com"
        };
    }

    [Test]
    public void UserService_can_create_a_new_user()
    {
        // Arrange
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(true);

        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.True,
          "UserService.CreateUser(user) failed when it should have succeeded");
    }

    [Test]
    public void UserService_can_not_create_an_existing_user()
    {
        // Arrange
        userRepo.Stub(repo => repo.IsExistingUser(theUser)).Return(true);
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.False,
            "UserService.CreateUser() allowed multiple copies of same user to be created");
    }

A: You are right: the simplicity of the service makes these tests uninteresting. It is not until you get more business logic in the service, that you will gain value from the tests.
You might consider some tests like these:
CreateUser_fails_if_email_is_invalid()
CreateUser_fails_if_username_is_empty()

Another comment: it looks like a code-smell, that your methods return booleans to indicate success or failure. You might have a good reason to do it, but usually you should let the exceptions propagate out. It also makes it harder to write good tests, since you will have problems detecting whether your method failed for the "right reason", f.x. you might write the CreateUser_fails_if_email_is_invalid()-test like this:
[Test]
public void CreateUser_fails_if_email_is_invalid()
{
    bool result = userSvc.CreateUser(userWithInvalidEmailAddress);
    Assert.That(result, Is.False);
}

and it would probably work with your existing code. Using the TDD Red-Green-Refactor-cycle would mitigate this problem, but it would be even better to be able to actually detect that the method failed because of the invalid email, and not because of another problem.

A: If you write your tests before you write your code, you'll gain much more from your unit tests.  One of the reasons that it feels like your tests aren't worth much is that you're not deriving the value of having your tests drive the design.  Writing your tests afterwards is mostly just an exercise in seeing if you can remember everything that can go wrong.  Writing your tests first causes you to think about how you would actually implement the functionality.
These tests aren't all that interesting because the functionality that is being implemented is pretty basic.  The way you are going about mocking seems pretty standard -- mock the things the class under test depends on, not the class under test.  Testability (or good design sense) has already led you to implement interfaces and use dependency injection to reduce coupling.  You might want to think about changing the error handling, as other have suggested.  It would be nice to know why, if only to improve the quality of your tests, CreateUser has failed, for instance.  You could do this with exceptions or with an out parameter (which is how MembershipProvider works, if I remember correctly).

A: Essentially what you are testing here is that the methods are getting called, not whether or not they actually work.  Which is what mocks are supposed to do.  Instead of calling the method, they just check to see if the method got called, and return whatever is in the Return() statement. So in your assertion here:
Assert.That(result, Is.False, "error message here");

This assertion will ALWAYS succeed because your expectation will ALWAYS return false, because of the Return statement:
userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);

I'm guessing this isn't that useful in this case.
Where mocking is useful is when you want to, for example, make a database call somewhere in your code, but you don't want to actually call to the database.  You want to pretend that the database got called, but you want to set up some fake data for it to return, and then (here's the important part) test the logic that does something with the fake data your mock returned.  In the above examples you are omitting the last step. Imagine you had a method that displayed a message to the user that said whether the new user was created:
public string displayMessage(bool userWasCreated) {
    if (userWasCreated)
        return "User created successfully!";
    return "User already exists";
}

then your test would be
userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
Assert.AreEqual("User already exists", displayMessage(userSvc.CreateUser(theUser)))

Now this has some value, because you are testing some actual behavior.  Of course, you could also just test this directly by passing in "true" or "false."  You don't even need a mock for that test.  Testing expectations is fine, but I've written plenty of tests like that, and have come to the same conclusion that you are reaching - it just isn't that useful.
So in short, mocking is useful when you want to abstract away externalities, like databases, or webservice calls, etc, and inject known values at that point.  But it's not often useful to test mocks directly.

A: You are facing the question of "classical" vs. "mockist" approaches to testing. Or "state-verification" vs. "behaviour-verification" as described by Martin Fowler: http://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting
Another most excellent resource is Gerard Meszaros' book "xUnit Test Patterns: Refactoring Test Code"


text:
Q: Subquery returned more than 1 value error for getting specific value within columns i got stuck with a Msg 512, Level 16, State 1, Line 2
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. What I'm trying to do is pull the specific quantity available per Size which is UserField1 column. Hoping to get some clarity over what I'm doing wrong. TIA!
 SELECT DISTINCT(InvMaster.AlternateKey1) AS 'Item Group', InvWarehouse.Warehouse,
        (SELECT (QtyOnHand - QtyAllocated) AS 'S' FROM InvMaster WHERE UserField1 = 'SMALL'),
        (SELECT (QtyOnHand - QtyAllocated) AS 'M' FROM InvMaster WHERE UserField1 = 'M'),
        (SELECT (QtyOnHand - QtyAllocated) AS 'L' FROM InvMaster WHERE UserField1 = 'L'),
        (SELECT (QtyOnHand - QtyAllocated) AS 'XL' FROM InvMaster WHERE UserField1 = 'XL'),
        (SELECT (QtyOnHand - QtyAllocated) AS '2XL' FROM InvMaster WHERE UserField1 = '2XL')
    FROM InvMaster INNER JOIN InvWarehouse ON InvMaster.StockCode = InvWarehouse.StockCode
    WHERE InvMaster.ProductClass = 'FGUND'
    GROUP BY InvMaster.AlternateKey1, InvWarehouse.Warehouse

A: It's seem your InvMaster table has multiple rows with the same Size, try to add sum(QtyOnHand - QtyAllocated) on subquery

A: @TerSiy you can use subquery as table and using left join to query data, your sql should like this:
SELECT DISTINCT(InvMaster.AlternateKey1) AS 'Item Group', InvWarehouse.Warehouse , S.S, M.M, L.L

FROM InvMaster INNER JOIN InvWarehouse ON InvMaster.StockCode = InvWarehouse.StockCode
left join (SELECT (QtyOnHand - QtyAllocated) AS 'S', AlternateKey1 FROM InvMaster WHERE UserField1 = 'SMALL') S
            ON InvMaster.AlternateKey1 = S.AlternateKey1
left join (SELECT (QtyOnHand - QtyAllocated) AS 'M',AlternateKey1 FROM InvMaster WHERE UserField1 = 'M') M
            ON InvMaster.AlternateKey1 = M.AlternateKey1
left join (SELECT (QtyOnHand - QtyAllocated) AS 'L',AlternateKey1 FROM InvMaster WHERE UserField1 = 'L') L
            ON InvMaster.AlternateKey1 = L.AlternateKey1
WHERE InvMaster.ProductClass = 'FGUND'
GROUP BY InvMaster.AlternateKey1, InvWarehouse.Warehouse

A: If you want to output rows as column in this case the UserField1, try to use pivot. Hope this helps. SQL does not allow column name starting with a number, you may want to comment out the 2XL column.

    SELECT InvMaster.AlternateKey1 AS 'Item Group',
            InvWarehouse.Warehouse,
            S AS 'SMALL',
            M,
            L,
            XL,
            2XL
    FROM (
        SELECT InvMaster.AlternateKey1,
                InvWarehouse.Warehouse,
                UserField1
        FROM InvMaster im
        INNER JOIN InvWarehouse  iw
            ON im.StockCode = iw.StockCode
        WHERE im.ProductClass = 'FGUND') up
        PIVOT (SUM(QtyOnHand - QtyAllocated) FOR UserField1 IN (S, M, L, XL, 2XL)) AS pvt
    ORDER BY InvMaster.AlternateKey1, InvWarehouse.Warehouse

A: Use SUM In your Query Like below :
 SELECT DISTINCT(InvMaster.AlternateKey1) AS 'Item Group', InvWarehouse.Warehouse,
        (SELECT sum(QtyOnHand) - sum(QtyAllocated) AS 'S' FROM InvMaster WHERE UserField1 = 'SMALL'),
        (SELECT sum(QtyOnHand) - sum(QtyAllocated) AS 'M' FROM InvMaster WHERE UserField1 = 'M'),
        (SELECT sum(QtyOnHand) - sum(QtyAllocated) AS 'L' FROM InvMaster WHERE UserField1 = 'L'),
        (SELECT sum(QtyOnHand) - sum(QtyAllocated) AS 'XL' FROM InvMaster WHERE UserField1 = 'XL'),
        (SELECT sum(QtyOnHand) - sum(QtyAllocated) AS '2XL' FROM InvMaster WHERE UserField1 = '2XL')
    FROM InvMaster INNER JOIN InvWarehouse ON InvMaster.StockCode = InvWarehouse.StockCode
    WHERE InvMaster.ProductClass = 'FGUND'
    GROUP BY InvMaster.AlternateKey1, InvWarehouse.Warehouse


text:
Q: bash sort is not sorting numerically on field as desired I've been trying to do a numeric sort on a list of file names.
They're all named as

something.txt~NUM~

I've tried sorting them by

sort -t "~" -k1 -k2n

But the sort comes out wrong.  If I do

sort -n

Then they're numerically sorted as desired but the file handles aren't sorted.
Here's a test file
explanation.txt.~1~
explanation.txt.~2~
explanation.txt.~3~
explanation.txt.~4~
explanation.txt.~5~
explanation.txt.~6~
explanation.txt.~7~
explanation.txt.~8~
explanation.txt.~9~
explanation.txt.~11~
explanation.txt.~12~
explanation.txt.~13~
explanation.txt.~14~
explanation.txt.~15~
explanation.txt.~16~
explanation.txt.~17~
explanation.txt.~18~
explanation.txt.~19~
explanation.txt.~20~
presentation.txt.~10~
presentation.txt.~11~
presentation.txt.~12~
presentation.txt.~13~
presentation.txt.~14~
presentation.txt.~15~
presentation.txt.~16~
presentation.txt.~17~
presentation.txt.~18~
presentation.txt.~19~
presentation.txt.~1~
presentation.txt.~20~
presentation.txt.~21~
presentation.txt.~22~
presentation.txt.~2~
presentation.txt.~3~
presentation.txt.~4~
presentation.txt.~5~
presentation.txt.~6~
presentation.txt.~7~
presentation.txt.~8~
presentation.txt.~9~

which gets sorted as
explanation.txt.~11~
explanation.txt.~12~
explanation.txt.~13~
explanation.txt.~14~
explanation.txt.~15~
explanation.txt.~16~
explanation.txt.~17~
explanation.txt.~18~
explanation.txt.~19~
explanation.txt.~1~
explanation.txt.~20~
explanation.txt.~2~
explanation.txt.~3~
explanation.txt.~4~
explanation.txt.~5~
explanation.txt.~6~
explanation.txt.~7~
explanation.txt.~8~
explanation.txt.~9~
presentation.txt.~10~
presentation.txt.~11~
presentation.txt.~12~
presentation.txt.~13~
presentation.txt.~14~
presentation.txt.~15~
presentation.txt.~16~
presentation.txt.~17~
presentation.txt.~18~
presentation.txt.~19~
presentation.txt.~1~
presentation.txt.~20~
presentation.txt.~21~
presentation.txt.~22~
presentation.txt.~2~
presentation.txt.~3~
presentation.txt.~4~
presentation.txt.~5~
presentation.txt.~6~
presentation.txt.~7~
presentation.txt.~8~
presentation.txt.~9~

I'm running Sierra OSX.  So, in particular, sort -V is not available to me.  I also know how to get the desired result using a perl script.  So, it's not a matter of how to get the desired result, but how to do this using 'sort'.

A: You first want to sort only by field 1, and then in case of ties look at field 2:
sort -t'~' -k1,1 -k2,2n

When you use -k1, you are sorting by field 1 up to the end of line. When you do that, there are no ties, so the sorting by field 2 never kicks in.