text:
Q: PHP Sort a complex multi-dimensional array by value I have a multi-dimensional array that generates an HTML table.
Data in array:
Array
(
    [header] => Array
        (
            [1] => Array
                (
                    [0] => Array
                        (
                            [col_pos] => 1
                            [sortable] => 1
                            [content] => Compare
                            [sort_value] =>
                            [ct_help] => Compare help text..
                        )

                    [1] => Array
                        (
                            [col_pos] => 2
                            [sortable] => 1
                            [content] => Product
                            [sort_value] =>
                            [ct_help] => Product help text..
                        )

                    [2] => Array
                        (
                            [col_pos] => 3
                            [sortable] => 1
                            [content] => Type of Cover
                            [sort_value] =>
                            [ct_help] => Type of cover help text..
                        )

                    [3] => Array
                        (
                            [col_pos] => 4
                            [sortable] => 1
                            [content] => Roadside Assistance
                            [sort_value] =>
                            [ct_help] => Roadside assistance help text...
                        )

                    [4] => Array
                        (
                            [col_pos] => 5
                            [sortable] => 1
                            [content] => Nationwhide Recovery
                            [sort_value] =>
                            [ct_help] => Nationwide Recover help text...
                        )

                    [5] => Array
                        (
                            [col_pos] => 9
                            [sortable] => 1
                            [content] => Price
                            [sort_value] =>
                            [ct_help] => Price help text...
                        )

                    [6] => Array
                        (
                            [col_pos] => 10
                            [sortable] => 1
                            [content] =>
                            [sort_value] =>
                            [ct_help] =>
                        )

                )

        )

    [row] => Array
        (
            [2] => Array
                (
                    [0] => Array
                        (
                            [col_pos] => 1
                            [sortable] => 0
                            [content] => Logo
                            [sort_value] =>
                            [ct_help] =>
                        )

                    [1] => Array
                        (
                            [col_pos] => 2
                            [sortable] => 0
                            [content] => Product cover 2
                            [sort_value] => 2
                            [ct_help] =>
                        )

                    [2] => Array
                        (
                            [col_pos] => 3
                            [sortable] => 0
                            [content] => Vehicle & Personal 2
                            [sort_value] => 2
                            [ct_help] =>
                        )

                    [3] => Array
                        (
                            [col_pos] => 4
                            [sortable] => 0
                            [content] => Yes
                            [sort_value] => 1
                            [ct_help] =>
                        )

                    [4] => Array
                        (
                            [col_pos] => 5
                            [sortable] => 0
                            [content] => No
                            [sort_value] => 0
                            [ct_help] =>
                        )

                    [5] => Array
                        (
                            [col_pos] => 9
                            [sortable] => 0
                            [content] => from 75 GBP
                            [sort_value] => 75
                            [ct_help] =>
                        )

                    [6] => Array
                        (
                            [col_pos] => 10
                            [sortable] => 0
                            [content] => Visit site >
                            [sort_value] =>
                            [ct_help] =>
                        )

                )

            [3] => Array
                (
                    [0] => Array
                        (
                            [col_pos] => 1
                            [sortable] => 0
                            [content] => Logo
                            [sort_value] =>
                            [ct_help] =>
                        )

                    [1] => Array
                        (
                            [col_pos] => 2
                            [sortable] => 0
                            [content] => Product cover 3
                            [sort_value] => 3
                            [ct_help] =>
                        )

                    [2] => Array
                        (
                            [col_pos] => 3
                            [sortable] => 0
                            [content] => Vehicle & Personal 3
                            [sort_value] => 3
                            [ct_help] =>
                        )

                    [3] => Array
                        (
                            [col_pos] => 4
                            [sortable] => 0
                            [content] => No
                            [sort_value] => 0
                            [ct_help] =>
                        )

                    [4] => Array
                        (
                            [col_pos] => 5
                            [sortable] => 0
                            [content] => Yes
                            [sort_value] => 1
                            [ct_help] =>
                        )

                    [5] => Array
                        (
                            [col_pos] => 9
                            [sortable] => 0
                            [content] => from 73 GBP
                            [sort_value] => 73
                            [ct_help] =>
                        )

                    [6] => Array
                        (
                            [col_pos] => 10
                            [sortable] => 0
                            [content] => Visit site >
                            [sort_value] =>
                            [ct_help] =>
                        )

                )

            [4] => Array
                (
                    [0] => Array
                        (
                            [col_pos] => 1
                            [sortable] => 0
                            [content] => Logo
                            [sort_value] =>
                            [ct_help] =>
                        )

                    [1] => Array
                        (
                            [col_pos] => 2
                            [sortable] => 0
                            [content] => Product cover 4
                            [sort_value] => 4
                            [ct_help] =>
                        )

                    [2] => Array
                        (
                            [col_pos] => 3
                            [sortable] => 0
                            [content] => Vehicle & Personal 4
                            [sort_value] => 4
                            [ct_help] =>
                        )

                    [3] => Array
                        (
                            [col_pos] => 4
                            [sortable] => 0
                            [content] => Yes
                            [sort_value] => 1
                            [ct_help] =>
                        )

                    [4] => Array
                        (
                            [col_pos] => 5
                            [sortable] => 0
                            [content] => Yes
                            [sort_value] => 1
                            [ct_help] =>
                        )

                    [5] => Array
                        (
                            [col_pos] => 9
                            [sortable] => 0
                            [content] => from 84 GBP
                            [sort_value] => 84
                            [ct_help] =>
                        )

                    [6] => Array
                        (
                            [col_pos] => 10
                            [sortable] => 0
                            [content] => Visit site >
                            [sort_value] =>
                            [ct_help] =>
                        )

                )

            [5] => Array
                (
                    [0] => Array
                        (
                            [col_pos] => 1
                            [sortable] => 0
                            [content] => Logo
                            [sort_value] =>
                            [ct_help] =>
                        )

                    [1] => Array
                        (
                            [col_pos] => 2
                            [sortable] => 0
                            [content] => Product cover 5
                            [sort_value] => 5
                            [ct_help] =>
                        )

                    [2] => Array
                        (
                            [col_pos] => 3
                            [sortable] => 0
                            [content] => Vehicle & Personal 5
                            [sort_value] => 5
                            [ct_help] =>
                        )

                    [3] => Array
                        (
                            [col_pos] => 4
                            [sortable] => 0
                            [content] => No
                            [sort_value] => 0
                            [ct_help] =>
                        )

                    [4] => Array
                        (
                            [col_pos] => 5
                            [sortable] => 0
                            [content] => Yes
                            [sort_value] => 1
                            [ct_help] =>
                        )

                    [5] => Array
                        (
                            [col_pos] => 9
                            [sortable] => 0
                            [content] => from 96 GBP
                            [sort_value] => 96
                            [ct_help] =>
                        )

                    [6] => Array
                        (
                            [col_pos] => 10
                            [sortable] => 0
                            [content] => Visit site >
                            [sort_value] =>
                            [ct_help] =>
                        )

                )

        )

)

HTML Table renders like so:
+---------+-----------------+----------------------+----------+------------+--------------+--------------+
| Compare |     Product     |    Type of Cover     | Roadside | Nationwide |    Price     |              |
+---------+-----------------+----------------------+----------+------------+--------------+--------------+
| Logo    | Product Cover 2 | Vehicle & Personal 2 | Yes      | No         | from £75 GBP | Visit site > |
| Logo    | Product Cover 3 | Vehicle & Personal 3 | No       | Yes        | from £73 GBP | Visit site > |
| Logo    | Product Cover 4 | Vehicle & Personal 4 | Yes      | Yes        | from £84 GBP | Visit site > |
| Logo    | Product Cover 5 | Vehicle & Personal 5 | No       | No         | from £96 GBP | Visit site > |
+---------+-----------------+----------------------+----------+------------+--------------+--------------+

Now I want to be able to sort by "price" but as you can see in the array the 'content' key for the price cell is a string and we need to sort it by the 'sort_value' key. Other sortable columns like 'Roadside' or 'Nationwide' should be sortable too by their 'sort_value' key.
I have tried different combinations of array_multisort or usort but was not successful.
Any help on this would be much appreciated. If you have questions, please feel free to ask.
Thanks in advance.

A: Here's a function that will sort your list the way you want it to. It first searches for the key of the field to sort on in the headers part of the array, then sorts the row part based on the sortable values for that key:
function sort_list($list, $field, $ascending = true) {
    $headers = array_values($list['header'])[0];
    if (($key = array_search($field, array_column($headers, 'content'))) === false || $headers[$key]['sortable'] == 0) {
        // can't find field or field is not sortable, do nothing
        return $list;
    }
    usort($list['row'], function ($a, $b) use ($key, $ascending) {
        return $ascending ? $a[$key]['sort_value'] <=> $b[$key]['sort_value'] : $b[$key]['sort_value'] <=> $a[$key]['sort_value'];
    });
    return $list;
}

Sample usage:
sort_list($data, 'Price');

Demo on 3v4l.org


text:
Q: PHP using preg_replace to create a BB code help please So I'm currently creating a project and in this project it requires a user to add information about their server/game.
I'm making the information field a little unique by adding some BB codes, and so far I've added nearly all but I need one small help.
I want add to add
[img w=100 h=100]IMG link here[/img]
the "100" means the amount, that was just a random number. Here is my PHP code that used:
preg_replace('/\[img w=(.*?) h=(.*?)](.*?)\[\/img\]/i', '', $str);
'
but the code returns this:

if anyone could help me I'd appreciate it, thank you.

A: Your code works correctly (PHP 5.2.8):
$str = "[img w=100 h=200]IMG link here[/img]";

echo preg_replace('/\[img w=(.*?) h=(.*?)](.*?)\[\/img\]/i', '', $str);

Outputs

If you are getting different results, share your PHP version and example similar to mine above.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which theorem is used here? If $A$ is not invertible, then since the polynomial $\det(A+xI_n)$ has finitely many zeros, $A + xI_n$ is invertible for any sufficiently small $x > 0$.

A: A (squared) matrix $B$ is invertible if and only if $\det(B)\ne 0$.
Indeed, $\det(A+xI_n)=0$ only for finitely many values of $x$, namely, $\{x_1,\cdots,x_p\}$ with $p\le n$.
Let $x_0:= \min\{x_j:\, x_j\ne0\}$ (if $x_j\le0$ for all $j$, then take $x_0$ to be any positive real number). Then it is clear that for any $0<x<x_0$, $\det(A+xI_n)\ne0$ and your matrix is invertible.


text:
Q: Android Logcat not showing logs when I switch devices I am trying to use Logcat to help diagnose my android issues. I frequently have a phone plugged in AND an emulator running. Sometimes I debug on the emulator, sometimes I debug on the phone, or maybe even a third device.
Logcat does not continue to show messages after a device is switched. How can I specify what Logcat does or force it to resume logging without restarting eclipse?
Insight appreciated

A: If you are using Eclipse, switch to the DDMS perspective.
There, logcat will be showing the log of the selected device in the devices View
(Window -> Open perspective -> Other -> DDMS)

A: I've noticed this at times. Usually one of two things does the trick. First, open the Devices view, verify that the new device is showing, and then switch back to Logcat. That seems to kick Logcat into action again.
If that doesn't work, then in the Devices view menu, select "Restart ADB" (I think that's what it's called; I don't have it open at the moment).
If even that doesn't work, then kill and restart the ADB server from the command line and repeat the above.

A: You coupld use the CLI for ADB and reattach the debug process to your switched device. Then Logcat will pick the debug msgs from that connected device. Whatever device is actively connected to ADB will output through Logcat


text:
Q: Getting "Server Error 500" when using logger.debug in production I'm trying to find a little bug and need the logger inside one of my models for it. Whenever I use
logger.debug "something"

inside a model, the message is put in the log but I get a 500 Server Error page. Everything is normal without the logger.debug line.
I set
config.log_level = :debug

inside the environments/production.rb file and set the correct file permissions for the log but can't seem to find the problem.

A: Inside the model the logger object is not available by default. Use
Rails.logger.debug "something"

instead...


text:
Q: Application with LARGEADDRESSAWARE flag set getting less virtual memory I have a 32-bit application consisting one EXE and multiple DLLs. The EXE has been built with /LARGEADDRESSAWARE flag set. So I expect on a 64-bit OS I should get 4 GB of user address space. But on some 64-bit Win 7 systems I am getting only 2 GB of user address space.
The physical memory is 8 GB if that matters. What could be reason for this behavior?

A: After browsing through MSDN, I found the following:
On http://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx (the page for MEMORYSTATUSEX which is used by GlobalMemoryStatusEx (http://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx) ) the description for ullTotalVirtual is:

this value is approximately 2 GB for most 32-bit processes on an x86 processor and approximately 3 GB for 32-bit processes that are large address aware running on a system with 4-gigabyte tuning enabled.

The 4GB tuning page is: http://msdn.microsoft.com/en-us/library/windows/desktop/bb613473(v=vs.85).aspx and it says something like:

On 64-bit editions of Windows, 32-bit applications marked with the IMAGE_FILE_LARGE_ADDRESS_AWARE flag have 4 GB of address space available.
Itanium editions of Windows Server 2003:  Prior to SP1, 32-bit processes have only 2 GB of address space available.

Also, the memory limits page (http://msdn.microsoft.com/en-us/library/aa366778.aspx#memory_limits) can come handy if you want to determine the total memory your system supports.
However the real useful information comes from Mark Russinowich's blog: http://blogs.technet.com/b/markrussinovich/archive/2008/07/21/3092070.aspx

While 4GB is the licensed limit for 32-bit client SKUs, the effective limit is actually lower and dependent on the system's chipset and connected devices. The reason is that the physical address map includes not only RAM, but device memory as well, and x86 and x64 systems map all device memory below the 4GB address boundary to remain compatible with 32-bit operating systems that don't know how to handle addresses larger than 4GB.

So the conclusion is that yes, this might depend on the configuration of the system. Maybe you can complete your question with a table, with the amount of the memory you get on each system and some important system configuration settings, and we might discover a pattern in this case.

A: The problem is that an Application has a whole has to be large Adress aware - so that pointers are to be treated as unsigned.
If however on "some" system some of your used DLL is not large adressaware this renders your whole program not large address aware.
http://blogs.msdn.com/b/oldnewthing/archive/2010/09/22/10065933.aspx


text:
Q: Fastest Way To std::vector to std::vector Here is the test code:
class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(b);//Compiler Error
    return 0;
}

Since std::vector<A> and std::vector<B> is different type, we can't make conversion from one to another.
An optional way can be:
class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(std::vector<A>(b.begin(), b.end()));
    return 0;
}

It acts, but it takes extra copying from B to A. If A or B is a large object, it can be very slow. A better choice is:
class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(std::vector<A>(std::make_move_iterator(b.begin()), std::make_move_iterator(b.end())));
    return 0;
}

Since it just move the iter instead of the whole B class, it take a better performance. But there are some extra cost - If b is a very large vector with huge number of items, iteration also can slow down my code.
So I wonder if there is a way to directly convert std::vector<B> to std::vector<A> without any extra cost?

A: One approach is to make the vector a template parameter of the Test function. The calling code will remain the same, there is no copying required.
#include <vector>
#include <iostream>

class A{
public:
    virtual void print() const {
        std::cout << "A" << std::endl;
    }
};
class B : public A{
    virtual void print() const {
        std::cout << "B" << std::endl;
    }
};

template <typename ContainerA>
void Test(const ContainerA& aas)
{
    for(const A& a:aas) {
        a.print();
    }
}

int main()
{
    std::vector<A> a;
    a.push_back(A());
    std::vector<B> b;
    b.push_back(B());
    Test(a);
    Test(b);
    return 0;
}

A: I don't know if it's useful for you but the best I can think is pass std::vector<Derived> to the function and iterate the element as Base elements.
Something like
template <typename D>
void Test (std::vector<D> const & v)
 {
   for ( A const & elem : v )
    {
      // use elem
    }
 }

Using SFINAE you can enable Test() only for vectors of Base or derived from Base elements as follows
template <typename D>
typename std::enable_if<std::is_base_of<A, D>::value>::type
     Test (std::vector<D> const & v)
 {
   for ( A const & elem : v )
    {
      // use elem
    }
 }

So you have
int main ()
 {
   std::vector<A>   a;
   std::vector<B>   b;
   std::vector<int> c;

   Test(a);    // compile
   Test(b);    // compile
   // Test(c); // compiler error
 }


text:
Q: Char[] array help needed I have a collection of objects from a database that holds the titles of companies.
I need to get the first letters (char[]) of all the titles distincted (.Distinct()).
Currently I have something like:
public char[] GetBrandsAlphabet()
    {
        using (var dc = ReturnContext())
        {
            var resultBrands =
                from brands in dc.Brands
                orderby brands.Title ascending
                select brands.Title.ToCharArray()[0];

            char[] ret = new char[resultBrands.Distinct().Count()];

        }
    }

A: Replace the last line with this:
char[] ret = resultBrands.Distinct().ToArray();

Or, hey, how about this one liner to replace everything else?
char[] ret = (from brands in dc.Brands
              select brands.Title.ToUpper[0]).Distinct().OrderBy(c => c).ToArray();

The ToUpper guarantees that you won't have both 'A' and 'a' in your final array.

A: return resultBrands.Distinct().ToArray();

However, this might not work exactly the way that you want, since Distinct could, in principle, change the ordering of the elements. I would remove the orderby statement from the sql statement and use:
return resultBrands.Distinct().OrderBy(c => c).ToArray();

A: OK What others already said. You can improve this part though:
  var resultBrands =
                from brands in dc.Brands
                orderby brands.Title ascending
                select brands.Title[0];

A string is already addressable by index like a char array, you don't need to convert it.


text:
Q: Advanced Custom Fields - Set Post Object of another post I've been trying to solve this issue for a few days now. I hope somebody can help me out here!
Basically, what I'm trying to do is:

*

*When a post is created (an offer)

*Create another post (a review)

*When the review is created

*Update the post object relationship of the offer to the review

The code I currently have is:
add_action( 'transition_post_status', 'create_review', 10, 3 );
function create_review( $new, $old, $post ) {

    if ( ( $new == 'publish' ) && ( $old == 'draft' ) && ( $post->post_type == 'ebs_offer' ) ) {

        //when new offer is created
        //create a review post
        $review_post = array(
        'post_type' => 'ebs_review',
        'post_title'    => get_field('ebs_brand_name', $post->ID),
        'post_content'  => 'Content Goes Here',
        'post_status'   => 'publish',
        'post_author'   => 1,
        );

        // Insert the post into the database
        wp_insert_post( $review_post );

    } else {
        return;
    }

        if ( ( $new == 'publish' ) && ( $old == 'draft' ) && ( $post->post_type == 'ebs_review' ) ) {

        //when new review is created
        //update the offer post object relationship

    } else {
        return;
    }

}

This works fine, I just cannot figure out how to update the post object relationship of the offer. I've tried tonnes of different hooks and functions before anyone says that my code doesn't show that I've tried to solve this myself - I have!
I've stripped my code down so that someone might just be able to point me in the right direction.
Thanks guys!

A: Solved!
For anyone with the same issue, you can use:
update_field($field_name, $post, $post-you-want-to-update-id);
To update.
Pass the entire $post array to update the post object.
Hope this helps someone.
add_action( 'transition_post_status', 'create_review', 10, 3 );
function create_review( $new, $old, $post ) {

    if ( ( $new == 'publish' ) && ( $old == 'draft' ) && ( $post->post_type == 'ebs_offer' ) ) {

        //when new offer is created
        //create a review post

        global $offer_post_id;
        $offer_post_id = $post->ID;

        // Create post object
        $review_post = array(
        'post_type' => 'ebs_review',
        'post_title'    => get_field('ebs_brand_name', $post->ID),
        'post_content'  => 'Content Goes Here',
        'post_status'   => 'publish',
        'post_author'   => 1,
        );

        // Insert the post into the database
        wp_insert_post( $review_post );

    }

    if ( ( $new == 'publish' ) && ( $old == 'new' ) && ( $post->post_type == 'ebs_review' ) ) {

        //when new offer is created
        //link the review page to the offer
        global $offer_post_id;
        update_field('ebs_review_link', $post, $offer_post_id);

    } else {
        return;
    }

}


text:
Q: My Android app cannot connect to localhost after setting APN I have setup a local server running on 127.0.0.1/3000 on my MacBook. My Android app sends requests to 10.0.2.2/3000 to make connection with the server. This works pretty well until I configured the APN in the Android emulator settings. In the APN settings, I set the Proxy to be 192.168.x.xxx and the port number to be 8001. With these settings, the local server is not able to accept any messages sent from my app now. Closing the APN proxy is not an option because my app also needs to connect to some remote services. So how to connect to the local server with APN proxy on?

A: I find the answer. Instead of listening on 127.0.0.1/3000, I configured my local server to listen on 0.0.0.0/3000. Instead of making request to 10.0.2.2/3000 in my Android app, I now make request to 192.168.x.xxx/3000. The local server now can accept messages sent from my Android app.


text:
Q: How to get a bytearray converted into a image in angular 8 I have created a database to hold images that can when sending a post request match the form input and map it to a specific Qrcode and send that as a byte array to the angular frontend. Right now I am using a onSubmit function to run the the post. How do you get turn the incoming byte array response to a image in ur using  I have looked all over stack overflow and see that most of the answers are out dated.
onSubmit(structure: Structure, san: DomSanitizer) {
this.isSubmitted = true;
if (!this.registrationForm.valid) {
  return false;
} else {
  return this.http.post(this.serverURL, structure).toPromise().then((data: any) => {
    this.image = data;
  });
}

}

A: A quick follow up to this. I have added a few things in that seem to work hope this helps anyone along the way:
public onSubmit(structure: Structure) {
this.isSubmitted = true;
if (!this.registrationForm.valid) {
  return false;
} else {
  return this.http.post(this.serverURL, structure, {responseType: 'blob'}).subscribe(blob => {
    const urlCreator = window.URL;
    this.image = this.san.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
  });
}

}
Quick side note** If someone can explain to me why this works and what is going on that is behind the scenes I would be greatful.


text:
Q: columnSimilarities() of RowMatrix returns ERROR Schema: Failed initialising database under spark 2.2.0, I've experienced error using columnSimilarities().
Here is code to reproduce.
from pyspark.mllib.linalg.distributed import RowMatrix
rdd = sc.parallelize([[1.0,2.0,1.0],[1.0,5.0,1.0],[1.0,2.0,1.0],[4.0,2.0,4.0]])
mat = RowMatrix(rdd)
sim = mat.columnSimilarities(0.1)
sim.entries.collect()

Error is like that(trancated. too long. Full log is here).
17/08/13 10:15:19 ERROR Schema: Failed initialising database.
Unable to open a test connection to the given database. JDBC url = jdbc:derby:;databaseName=metastore_db;create=true, username = APP. Terminating connection pool (set lazyInit to true if you expect to start your database after your app). Original Exception: ------
java.sql.SQLException: Failed to start database 'metastore_db' with class loader org.apache.spark.sql.hive.client.IsolatedClientLoader$$anon$1@3234df5e, see the next exception for details.
    at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.Util.seeNextException(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedConnection.bootDatabase(Unknown Source)

This code works well.
from pyspark.mllib.linalg.distributed import IndexedRow, IndexedRowMatrix
rdd = sc.parallelize([IndexedRow(0, [1.0,2.0,1.0]),
                      IndexedRow(1, [1.0,5.0,1.0]),
                      IndexedRow(2, [1.0,2.0,1.0]),
                      IndexedRow(3, [4.0,2.0,4.0])])
mat = IndexedRowMatrix(rdd).toRowMatrix()
sim = mat.columnSimilarities(0.1)
sim.entries.collect()

Is this bug of Spark ?

A: This is a problem of jdbc connectivity - and not about columnSimilarities - or MLlib in general.
You might have some work to do to get the derby connection running. Here is one starting point : https://stackoverflow.com/a/40547664/1056563


text:
Q: Unhandled rejection CastError: Cast to string failed for value "{ email: 'test@g mail.com' }" at path "email" for model "User" what does this error meant for I was trying to make resetPasswordRequest , but whenever i try to submit email to get reset link on mailtrap.io spinner keeps on loading and this error appears at the terminal.
Unhandled rejection CastError: Cast to string failed for value "{ email: 'test@g
mail.com' }" at path "email" for model "User"
    at new CastError (C:\projects\bookworm\bookworm-api\node_modules\mongoose\li
b\error\cast.js:27:11)
    at SchemaString.cast (C:\projects\bookworm\bookworm-api\node_modules\mongoos
e\lib\schema\string.js:476:9)
    at SchemaString.SchemaType._castForQuery (C:\projects\bookworm\bookworm-api\
node_modules\mongoose\lib\schematype.js:1088:15)
    at SchemaString.castForQuery (C:\projects\bookworm\bookworm-api\node_modules
\mongoose\lib\schema\string.js:531:15)
    at SchemaString.SchemaType.castForQueryWrapper (C:\projects\bookworm\bookwor
m-api\node_modules\mongoose\lib\schematype.js:1045:15)
    at cast (C:\projects\bookworm\bookworm-api\node_modules\mongoose\lib\cast.js
:214:34)
    at model.Query.Query.cast (C:\projects\bookworm\bookworm-api\node_modules\mo
ngoose\lib\query.js:3305:12)
    at model.Query.Query._castConditions (C:\projects\bookworm\bookworm-api\node
_modules\mongoose\lib\query.js:1295:10)
    at model.Query.Query._findOne (C:\projects\bookworm\bookworm-api\node_module
s\mongoose\lib\query.js:1507:8)
    at C:\projects\bookworm\bookworm-api\node_modules\kareem\index.js:250:8
    at C:\projects\bookworm\bookworm-api\node_modules\kareem\index.js:23:7
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickDomainCallback (internal/process/next_tick.js:218:9)

these are my files

router/auth.js

router.post('/reset_password_request', (req, res) => {
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      sendResetPasswordEmail(user);
      res.json({});
    } else {
      res.status(400).json({ errors: { global: 'There user with such email' } })
    }
  });
});

model/User.js

schema.methods.generateResetPasswordToken = function generateResetPasswordToken() {
  return jwt.sign({
    _id: this._id
  }, process.env.KEY,
  { expiresIn: '1s' });
}

schema.methods.generateResetPasswordLink = function generateResetPasswordLink() {
  return `${process.env.HOST}/reset_password/${this.generateResetPasswordToken()}`
}


text:
Q: Uses of a C++ Arithmetic Promotion Header I've been playing around with a set of templates for determining the correct promotion type given two primitive types in C++.  The idea is that if you define a custom numeric template, you could use these to determine the return type of, say, the operator+ function based on the class passed to the templates.  For example:
// Custom numeric class
template <class T>
struct Complex {
    Complex(T real, T imag) : r(real), i(imag) {}
    T r, i;
// Other implementation stuff
};

// Generic arithmetic promotion template
template <class T, class U>
struct ArithmeticPromotion {
    typedef typename X type;  // I realize this is incorrect, but the point is it would
                              // figure out what X would be via trait testing, etc
};

// Specialization of arithmetic promotion template
template <>
class ArithmeticPromotion<long long, unsigned long> {
    typedef typename unsigned long long type;
}

// Arithmetic promotion template actually being used
template <class T, class U>
Complex<typename ArithmeticPromotion<T, U>::type>
operator+ (Complex<T>& lhs, Complex<U>& rhs) {
    return Complex<typename ArithmeticPromotion<T, U>::type>(lhs.r + rhs.r, lhs.i + rhs.i);
}

If you use these promotion templates, you can more or less treat your user defined types as if they're primitives with the same promotion rules being applied to them.  So, I guess the question I have is would this be something that could be useful?  And if so, what sorts of common tasks would you want templated out for ease of use?  I'm working on the assumption that just having the promotion templates alone would be insufficient for practical adoption.
Incidentally, Boost has something similar in its math/tools/promotion header, but it's really more for getting values ready to be passed to the standard C math functions (that expect either 2 ints or 2 doubles) and bypasses all of the integral types.  Is something that simple preferable to having complete control over how your objects are being converted?
TL;DR: What sorts of helper templates would you expect to find in an arithmetic promotion header beyond the machinery that does the promotion itself?

A: This is definitely useful -- we use these sorts of things in the math library that I work on for correctly typing intermediate values in expressions.  For example, you might have a templated addition operator:
template<typename Atype, typename Btype>
type_promote<Atype, Btype>::type operator+(Atype A, Btype B);

This way, you can write a generic operator that will handle different argument types, and it will return a value of the appropriate type to avoid precision loss in the expression that it appears in.  It's also useful (in things like vector sums) for properly declaring internal variables within these operators.
As for the question of what ought to go with these: I just checked in our source code where we define them, and all we have there are just the simple ArithmeticPromotion declaration you describe -- three generic versions to resolve the complex-complex, complex-real, and real-complex variants using the specific real-real ones, and then a list of real-real ones -- about 50 lines of code in all.  We don't have any other helper templates with them, and it doesn't (from our usage) look like there are any natural ones that we'd use.
(FWIW, if you don't want to write this yourself, download our source from http://www.codesourcery.com/vsiplplusplus/2.2/download.html, and pull out src/vsip/core/promote.hpp.  That's even in the part of our library that's BSD-licensed, though it doesn't actually say so in the file itself.)

A: For this, what you can use is the ?: operator. It will give you the common type between two types. First, if the two types are the same, you are fine. Then, if the types differ, you invoke the ?: and see what type you get back.
You need to special case the non-promoted types char, short and their unsigned/signed versions thereof since applied to two of such operands of differing types, the result will be neither of them. You need also take care of the case where two classes can be converted to promoted arithmetic types. To get these right, we check whether the result of ?: is a promoted arithmetic type (in the spirit of clause 13.6), and use that type then.
// typedef eiher to A or B, depending on what integer is passed
template<int, typename A, typename B>
struct cond;

#define CCASE(N, typed) \
  template<typename A, typename B> \
  struct cond<N, A, B> { \
    typedef typed type; \
  }

CCASE(1, A); CCASE(2, B);
CCASE(3, int); CCASE(4, unsigned int);
CCASE(5, long); CCASE(6, unsigned long);
CCASE(7, float); CCASE(8, double);
CCASE(9, long double);

#undef CCASE

// for a better syntax...
template<typename T> struct identity { typedef T type; };

// different type => figure out common type
template<typename A, typename B>
struct promote {
private:
  static A a;
  static B b;

  // in case A or B is a promoted arithmetic type, the template
  // will make it less preferred than the nontemplates below
  template<typename T>
  static identity<char[1]>::type &check(A, T);
  template<typename T>
  static identity<char[2]>::type &check(B, T);

  // "promoted arithmetic types"
  static identity<char[3]>::type &check(int, int);
  static identity<char[4]>::type &check(unsigned int, int);
  static identity<char[5]>::type &check(long, int);
  static identity<char[6]>::type &check(unsigned long, int);
  static identity<char[7]>::type &check(float, int);
  static identity<char[8]>::type &check(double, int);
  static identity<char[9]>::type &check(long double, int);

public:
  typedef typename cond<sizeof check(0 ? a : b, 0), A, B>::type
    type;
};

// same type => finished
template<typename A>
struct promote<A, A> {
  typedef A type;
};

If your Complex<T> types can be converted into each other, ?: won't find a common type. You could specialize promote to tell it how to figure out a common type of two Complex<T>:
template<typename T, typename U>
struct promote<Complex<T>, Complex<U>> {
  typedef Complex<typename promote<T, U>::type> type;
};

Usage is simple:
int main() {
  promote<char, short>::type a;
  int *p0 = &a;

  promote<float, double>::type b;
  double *p1 = &b;

  promote<char*, string>::type c;
  string *p2 = &c;
}

Note that for real-world uses, you should best catch a few cases I left out for simplicity, for example <const int, int> should be handled similar to <T, T> (you best first strip const and volatile and convert T[N] to T* and T& to T and afterwards  delegate to the actual promote template - i.e do boost::remove_cv<boost::decay<T>>::type for both A and B before delegating them). If you don't do this, the call to check will end up in an ambiguity for these cases.


text:
Q: How to parse a List inside a Json String In java? Input Json String: "{"predicted_route": [1, 351, 371, 372, 373, 0]}" that has been received after making a Post Request call to a backend server.
I would like to extract the List from the JSON String into an ArrayList.
I haven't found anything online that shows how one would go about this?
If I can use org.json that would be the best.
Thanks

A: import org.json.*;

String jsonString = inputJsonString; //assign your JSON String here
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("predicted_route");
ArrayList<String> arrayList = new ArrayList<String>();
if (jsonArray != null) {
    for (int i = 0; i < jsonArray.length(); i++) {
        arrayList.add(jsonArray.getString(i));
    }
}

More examples to parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json

A: Include Jackson dependency so you're able to deserialize the JSON without parsing it manually
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.4</version>
</dependency>

Create a POJO representation of your object. To have predicted_route mapped to the correct field you can annotate it with @JsonProperty.
class Route {

    @JsonProperty("predicted_route")
    private List<Integer> predictedRoute;

    public List<Integer> getPredictedRoute(){
        return predictedRoute;
    }

    public void setPlannedRoute(List<Integer> route){
        this.plannedRoute = route;
    }
}

Map the JSON string to your object
String yourJson = "{\\"predicted_route\\": [1, 351, 371, 372, 373, 0]}";
Route myRoute = new ObjectMapper().readValue(yourJson, Route.class);

System.out.println(myRoute.getPredictedRoute());


text:
Q: Does timestamp of a file in /proc filesystem indicate the time at which parameter sample is taken? Does timestamp of a file in /proc filesystem indicate the time at which parameter sample is taken ? if not, how to get timestamp at which a parameter is updated in a file under /proc ?

A: In general, you should not trust that much the result of stat(2) on /proc/ pseudo-files, and that includes both the apparent file size and its modification or access times. It is well known that many /proc/ files have a zero-size (as returned by stat) but a non-empty content (so should be read sequentially, like you would read a pipe), e.g. /proc/self/maps
Read more about proc(5), and also Documentation/filesystems/proc.txt in your kernel source tree.
Indeed, some files appear to have a timestamp related to the (current) time of open-ing or stat-ing (e.g. /proc/self/maps or /proc/$$/mounts or /proc/sys/kernel/randomize_va_space) but other files have a timestamp related to boot time, e.g /proc/interrupts
The /proc/ file system is really arcane, the ultimate reference about it is the kernel source code. But I won't rely on the fact that parameter-like files (I guess that you speak of files like /proc/sys/kernel/randomize_va_space ...) have a meaningful mtime.
Of course, the kernel does not keep track about modification times of many of its parameters.


text:
Q: How to access and manipulate strings in Stata variable labels? I have a Stata dataset with variable labels describing the year of measurement. I need to access the year of measurement from the variables to later rename each variable using a suffix showing the year. For example V95 has a label GNP/CAPITA,75, and I want to rename it to gnp_capita_75. Some variables have labels like GNP/C:GROWTH RTS,60-75, and I want to add the midpoint of the interval after the comma to the variable name.
So far my code for accessing the variable labels looks like this:
local varlist  V1 V2 V3 V28 V29 V30 V85 V86 V87 V88 V89 V90 V91 V92 V93 V94
foreach variable in `varlist' {
    //get the label of the variable
    local label : var label `variable'

    //find the position of the comma
    local commapos : strpos(`label', ",")

    //find the stub before the comma
    local namestub : substr(`label', 1, `commapos' - 1)

    //find year after the comma
    local year : substr(`label', `commapos' + 1, `commapos' + 2)

    //replace any illegal character (%,/,:," ") with underscores:
    local namestub : subinstr(`namestub', "%", "_")
    local namestub : subinstr(`namestub', "/", "_")
    local namestub : subinstr(`namestub', ":", "_")
    local namestub : subinstr(`namestub', " ", "_")

    //rename variable with the new stub and the year
    rename `variable' `namestub'`year'
}

I get an error saying that strpos() is not allowed. Is it because I'm trying to make that a local macro? The examples I saw use it to generate a variable in the dataset, but I'm dealing with the variable labels.
Am I in the right direction here? How do I fix this error?

A: The syntax you need is
local commapos = strpos("`label'", ",")`

and similarly for substr().
Note the extra bug that you need to enclose the label text in " ". That is needed elsewhere too.
The colon syntax is for extended macro functions, not functions in general.
(Learning how to automate this is a good ambition, but if the problem is this size, using varm interactively would have been quicker.)


text:
Q: Меню позиционируется неправильно Если ставлю text-align: center; позиционируется справа. Я вообще не понимаю почему так, возможно был такой вопрос, но я не нашел.

.header {
 width: 300px;
 background: #ccc;
 height: 500px;
 text-align: center;
}
.menu {
 margin: 5px;

}
li {

 display: inline-block;
}

<title>Mr. Robot</title>

1 сезон

2 сезон

3 сезон

A: Такой эффект создает отступ у ul по-умолчанию padding-left: 40px;:

.header {
 width: 300px;
 background: #ccc;
 height: 500px;
 text-align: center;
}
.menu {
 margin: 5px;

}
li {

 display: inline-block;
}

ul {padding: 0;}

<title>Mr. Robot</title>

1 сезон

2 сезон

3 сезон

A: При просмотре кода-элемента, для ul задано padding-left:40px
Попробуй для ul задать padding:0 , лично у меня сработало.
CSS :
ul {
    padding:0;
}


text:
Q: Is updating app.config manually a good idea? I'm updating a C# application to .NET 4.0. The older application uses several third party DLLs which are needed to be upgraded from version 2509.0.0.0 to 3396.0.0.0.
In the older application, the app.config file contains several of the following kind of nodes:
<configSections>
    <section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" />
</configSections>
.
.
.
<cachingConfiguration defaultCacheManager="Users">
<cacheManagers>
  <add expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="100000" numberToRemoveWhenScavenging="0" backingStoreName="Isolated Storage" name="SendQueues" />
  <add expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000" numberToRemoveWhenScavenging="10" backingStoreName="Null Storage" name="ServiceUrls" />
  <add expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="10" numberToRemoveWhenScavenging="1" backingStoreName="Null Storage" name="MonitorData" />
  <add expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="10" numberToRemoveWhenScavenging="1" backingStoreName="Null Storage" name="Shipments" />
  <add expirationPollFrequencyInSeconds="5" maximumElementsInCacheBeforeScavenging="1000" numberToRemoveWhenScavenging="10" backingStoreName="Tag Collection Storage" name="TagCollections" />
  <add expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000" numberToRemoveWhenScavenging="10" backingStoreName="UserIsolatedStorage" name="Users" />
  <add expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000" numberToRemoveWhenScavenging="10" backingStoreName="WebProxyIsolatedStorage" name="WebProxy" />
  <add expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000" numberToRemoveWhenScavenging="0" backingStoreName="InterfaceMapIsolatedStorage" name="InterfaceMap"/>
  <add expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000" numberToRemoveWhenScavenging="10" backingStoreName="RememberMeIsolatedStorage" name="RememberMe" />
</cacheManagers>
<backingStores>
  <add partitionName="WebProxy" encryptionProviderName="WebProxyEncryption" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.IsolatedStorageBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="WebProxyIsolatedStorage" />
  <add partitionName="SendQueues" encryptionProviderName="SendQueues Encryption" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.IsolatedStorageBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="Isolated Storage" />
  <add partitionName="TagCollections" encryptionProviderName="Tags Cache Encryption" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.IsolatedStorageBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="Tag Collection Storage" />
  <add partitionName="User" encryptionProviderName="Symmetric Storage Encryption" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.IsolatedStorageBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="UserIsolatedStorage" />
  <add encryptionProviderName="" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="Null Storage" />
  <add partitionName="RememberMe" encryptionProviderName="Remember me Storage Encryption" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.IsolatedStorageBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="RememberMeIsolatedStorage" />
  <add partitionName="InterfaceMap" encryptionProviderName="InterfaceMap Encryption" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.IsolatedStorageBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="InterfaceMapIsolatedStorage"/>
</backingStores>
<encryptionProviders>
  <add symmetricInstance="DPAPI Symmetric Cryptography Provider" type="Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography.SymmetricStorageEncryptionProvider, Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="WebProxyEncryption" />
  <add symmetricInstance="DPAPI Symmetric Cryptography Provider" type="Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography.SymmetricStorageEncryptionProvider, Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="SendQueues Encryption" />
  <add symmetricInstance="DPAPI Symmetric Cryptography Provider" type="Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography.SymmetricStorageEncryptionProvider, Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="Tags Cache Encryption" />
  <add symmetricInstance="DPAPI Symmetric Cryptography Provider" type="Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography.SymmetricStorageEncryptionProvider, Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="Symmetric Storage Encryption" />
  <add symmetricInstance="DPAPI Symmetric Cryptography Provider" type="Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography.SymmetricStorageEncryptionProvider, Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="Remember me Storage Encryption" />
  <add symmetricInstance="DPAPI Symmetric Cryptography Provider" type="Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography.SymmetricStorageEncryptionProvider, Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography, Version=2509.0.0.0, Culture=neutral, PublicKeyToken=ecdd5b3dfcfef3bb" name="InterfaceMap Encryption"/>
</encryptionProviders>

Notice that there are references to numerous DLLs with version number 2509.0.0.0. I have the version 3396.0.0.0 of each of those DLLs. It is tempting to modify all version numbers from 2509.0.0.0 to 3396.0.0.0 in the app.config file, but I believe that's not the proper way to do it.
The older version of the application was developed by someone else. How did they generate such an app.config file? How can I generate necessary nodes in the app.config file for version 3396.0.0.0 of all those DLLs?

A: I've not been working with .NET for almost 2yrs, but as I still remember, there can be 2 ways to make your wish come true :)

*

*You can re-generate your app.config file by updating your project settings, should check the pre-build option.

*Manually replace in app.config file, it won't be that harmful :)

Good luck!


text:
Q: Tier Pricing Issue - Please Help I need to apply a Tier Pricing by 10 Units. But not for unit number 11. Just by group of 10 units or 20 o 30. This is because we offer discount by closed package.
And the package contained 10 units. We don't want to discount the other units that doesn't fits in a closed package.


text:
Q: SSAS 2008 Account provision During SSAS 2008 installation the Account provisioning tool comes up and you can select the current Windows user (or other windows user).  However that account was deleted prior to adding another user as the administrator.  In 2005 the tool existed on the server and could be run manually, however I'm not seeing it in 2008.
I assume I can uninstall and reinstall to do this, however is there another way how I can add an admin account?
Thanks,

A: By default accounts that have local administrator rights on the server will also be SSAS admins, so such an account should be able to access the server in Management Studio and add other users as SSAS administrators.
If this option is turned off a server admin can always navigate to ..\Program Files\Microsoft SQL Server\MSSQL.X\OLAP\Config\ and change the BuiltinAdminsAreServerAdmins setting from 0 to 1 in the msmdsrv.ini file and restart the SSAS service and then add other admins in Management Studio.


text:
Q: ASP.net Gridview not sorting I have a gridview that I'd like to sort. I've read a few tutorials and copied most of my code directly from the MSDN page, but I can't get it to work. It compiles, but nothing happens when I click the grid column headers.
My HTML:
<asp:DataGrid runat="server" id="dgrMainGrid" CssClass="c_mainGrid"
AutoGenerateColumns="true" AllowSorting="true"
OnSorting="TaskGridView_Sorting" />

My Codebehind:
protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
    //Retrieve the table from the session object.
    DataTable dt = Session["Grid"] as DataTable;

    if (dt != null)
    {
        dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
        dgrMainGrid.DataSource = dt;
        dgrMainGrid.DataBind();
    }
}

private string GetSortDirection(string column)
{
    // By default, set the sort direction to ascending.
    string sortDirection = "ASC";

    // Retrieve the last column that was sorted.
    string sortExpression = ViewState["SortExpression"] as string;

    if (sortExpression != null)
    {
        // Check if the same column is being sorted.
        // Otherwise, the default value can be returned.
        if (sortExpression == column)
        {
            string lastDirection = ViewState["SortDirection"] as string;
            if ((lastDirection != null) && (lastDirection == "ASC"))
            {
                sortDirection = "DESC";
            }
        }
    }
    return sortDirection;
}

I know the data table in my session variable works, because it's the source for my grid on page load, which works fine. One other thing, if it's important, this gridview resides in an update panel.
As I said, most of this is copied from the MSDN page, and I've been through it until I'm going code-blind. Can someone see my mistake? Thanks.

A: You are using a DataGrid, not a GridView. According to Microsoft, DataGrid does not have a OnSorting event, but an OnSortCommand. Either use that or switch to GridView (recommended)
<asp:DataGrid runat="server" OnSortCommand="dgrMainGrid_SortCommand" id="dgrMainGrid" CssClass="c_mainGrid" AutoGenerateColumns="true" AllowSorting="true" />

And in code behind
protected void dgrMainGrid_SortCommand(object source, DataGridSortCommandEventArgs e)
{
    DataTable dt = Session["Grid"] as DataTable;

    if (dt != null)
    {
        dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
        dgrMainGrid.DataSource = dt;
        dgrMainGrid.DataBind();
    }
}

And your GetSortDirection does not work as it should. See this example.


text:
Q: Importing content of local file data into another Angular Component I have some mock data in Customers.mock.ts file. I am trying to access this data in 2 other files Customers.component.spec.ts and Customers.stories.ts files.
Here is my code for Customers.mock.ts file

export const Customer = {
  Customer: []
};

Here is my code for Customers.component.spec.ts file

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, '/i18n/', '.json');
}

describe('Data', () => {
  let component: Data;
  let fixture: ComponentFixture<Data>;

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Here is my code for Customer.ts
export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, './i18n/', '.json');
}

@NgModule()
export class CustomerStoriesComponent {
  constructor(private translate: TranslateService, private localeService: LocaleService) {
    localeService.nameObservable().subscribe((name) => {
      translate.use(name);
    });
    localeService.locale = locale;
  }
}

  };
}

How can I get mock data in both spec and stories file so that I do not need to manually keep this data in both the files?

A: you need export your const at empiricial-percentiles.mock.ts
export const empiricalPercentiles = {...}

and import in where you want.
import {empiricalPercentiles} from 'empiricial-percentiles.mock.ts';


text:
Q: Toggle data-value after Ajax success without element ID I have multiple buttons to toggle status of different projects:

  <button class="btn btn-default active">ACTIVE</button>
  <button class="btn btn-primary">CLOSED</button>

  <button class="btn btn-default active">ACTIVE</button>
  <button class="btn btn-primary">CLOSED</button>

I need to toggle the data-value between 1 and 2 when ajax post success.
I have tried this so far but without any luck:
$('.project_status').click(function(){
    var project_id = $(this).attr('data-project-id');
    var project_status_val = $(this).attr('data-value');
    var toggle_status = function(){
        $(this).find('.btn').toggleClass('active').toggleClass('btn-primary');
        if (project_status_val == '1'){
            alert(project_status_val);
            $(this).attr('data-value','2');
        } else {
            alert(project_status_val);
            $(this).attr('data-value','1');
        }
        return false;
    };
    var dataString = 'project_id=' + project_id + '&project_status=' + project_status_val;
    $.ajax({
        type: "POST",
        url: "post.php",
        data: dataString,
        success: toggle_status
    });
    $('#sidebar-wrapper').load('sidebar.php');
    return false;
});

I have got the alert data value correct. I have got the sidebar reload with updated value (only the first click). But I am not able to change the attribute value so that the next click will send the toggled value.
Please help! Thx

A: $(this) inside the toggle_status method is not your btn. Inside the method the this keyword refers to the object the method belongs to. In this case Window. As a workaround, I have made a self property before the method to store a reference to the selected $('.project_status') object. I have updated the code so it will work.
https://jsfiddle.net/05akxvx3/1/
$('.project_status').click(function(){
  var self = $(this);
  var project_id = self.attr('data-project-id');
  var project_status_val = self.attr('data-value');
  var toggle_status = function(){
    self.find('.btn').toggleClass('active').toggleClass('btn-primary');
    if (project_status_val == '1'){
        self.attr('data-value','2');
    } else {
        self.attr('data-value','1');
    }
    alert(self.attr('data-value'));
    return false;
  };
  var dataString = 'project_id=' + project_id + '&project_status=' + project_status_val;
  $.ajax({
    type: "POST",
    url: "post.php",
    data: dataString,
    success: toggle_status
  });
  $('#sidebar-wrapper').load('sidebar.php');
  return false;
});

A: You have an extra dash in your $(this).attr() statement.
$(this).attr('data--value','2'); ought to be:
$(this).attr('data-value','2');


text:
Q: Swift : Cast wrapped value I am trying to cast a wrapped value from a String to a float and I can't manage to do it. I think I'm missing a little knowledge about the whole wrapped/unwrapped (?/!) thing in swift.
I'm trying to get the text from a label.
Here's my label:
@IBOutlet weak var maxDistance: UILabel!

Here's what I tried:
var max = Float(maxDistance.text)!
--> Could not find an overload for 'init' that accepts the supplied arguments

var max = Float(maxDistance.text!)
--> Cannot invoke 'init' with an argument of type '@lvalue String'

var max = Float(maxDistance!.text)
--> Cannot invoke 'init' with an argument of type '@lvalue String?'

var max = Float(maxDistance?.text)
--> Cannot invoke 'init' with an argument of type '$T4??'

A: This has nothing to do with "wrapped value". What you're saying is simply not Swift. There is no Swift-native provision for turning a string to a Float. You can turn it to an Int (with toInt). Otherwise, you'll have to fall into Cocoa and call floatValue. So:
 let s = "1.3"
 let f = (s as NSString).floatValue

However, the real answer is that you should not be doing this. If there is a Float underlying this text value, you should be preserving that Float as part of your data model. Pulling a number out of a view text representation totally violates MVC (model-view-controller).

A: You could use the original Obj-C method floatValue like so:
var max = (maxDistance.text as NSString).floatValue


text:
Q: ItemCommand event not firing for DataList I've inherited a VB.Net application that I'm testing and the ItemCommand event is not firing... It is a VB.Net 4.0 application.
I've searched the web for this error and doubhle checked the code in the application.
I know this event is supposed to fire on a postback after the page_load event. However, when I click on the ImageButton (to force a postback and hopefully execute the ItemCommand event), the Page.IsPostBack property is still set to FALSE, thereby never being able to execute the ItemCommand event. I don't know why this property would still be set to FALSE. Evidently, I need a way to signify to the page that a postback is occurring. The ImageButton should take care of this since it has the runat="server" tag.
Below are the code snippets. Can someone please inform me what I would need to do in order to fire the Item command? What I said above is true, I believe. I don't know why after the page loads and I press the ImageButton that the property would still be set to FALSE.
HTML
<asp:DataList ID="lstReferrals" runat="server" DataKeyField="ReferringAffiliateID"
    OnItemCommand="lstReferrals_ItemCommand" CellPadding="4" Summary="Referral Design Table"
    Width="800"><ItemTemplate>

                <asp:ImageButton ID="btnSelect" AlternateText="Select" ImageUrl='<%# NodeImage(1) %>'
                    CommandName="select" runat="server" />CODE BEHINDPrivate Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Put user code to initialize the page here
        If Not (Request.Params("ItemIndex") Is Nothing) Then
            itemIndex = Int32.Parse(Request.Params("ItemIndex"))
        Else
            itemIndex = Convert.ToInt32(Null.SetNull(itemIndex))
        End If

        If Not Page.IsPostBack Then
            LoadReferrals()

            If Not Null.IsNull(itemIndex) Then
                lstReferrals.SelectedIndex = itemIndex
                LoadReferrals()
            End If
        End If

    End Sub

Protected Sub lstReferrals_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles lstReferrals.ItemCommand

        Try
            errormessage.Visible = False
            ' Determine the command of the button (either "select" or "collapse")
            Dim command As String = CType(e.CommandSource, ImageButton).CommandName

            ' Update asp:datalist selection index depending upon the type of command
            ' and then rebind the asp:datalist with content
            Select Case command
                Case "collapse"
                    lstReferrals.SelectedIndex = -1
                    LoadReferrals()
                Case "select"
                    lstReferrals.SelectedIndex = e.Item.ItemIndex
                    LoadReferrals()

A: I needed to add an event handler in the page_load method which would set the OnItemCommand event to fire:
lstProducts.ItemCommand += new DataListCommandEventHandler(lstProducts_ItemCommand);

In C#, I've noticed sometimes that the aspx file doesn't always trigger an event firing. For instance, if you have OnItemCommand="abc", it doesn't neccessarily fire (for whatever reason). If this is the case, you should force asp.net to add the event handler in the code behind as stated above.


text:
Q: Allowing users to install fonts in Windows 7 (through GPO) This is somewhat related to my previous question, Why do installed fonts disappear after reboot?.
Having got the font install issue sorted out under XP just fine, recently we've got a Windows 7 workstation and I've created a special GPO for it. Initially it was UAC that was demanding administrative access to C:\windows\fonts despite the fact the policy dictates that directory is writable (as is the relevant registry entries, on XP anyway). The issue now though is that when I try to copy a font or hit install it claims that the font "does not appear to be a valid font". This happens with every type of font as well.
Is there some new and special consideration when allowing these changes on Windows 7?
Any input would be appreciated.
Many thanks,
Doug

A: So I figured it out.
Having looked at the Resultant Set Of Policy and seeing nothing untoward there, I checked C:\windows\security\logs\winlogon.txt
The Windows 7 client GPO is a copy of the standard XP one that I created, and therefore had entries in it to allow domain users to edit the content of C:\windows\fonts.
However, Windows 7 shows this in winlogon.txt:

----Configure File Security...
Configure c:\windows\fonts.
Warning 5: Access is denied.
Error setting security on c:\windows\fonts.

I checked the GPO and removed the settings for this directory and re-added it, which upon a GPO update and restart gave me this:

----Configure File Security...
Configure c:\windows\fonts.
Configure c:\windows\system32\fntcache.dat.
File Security configuration was completed successfully.

I tried adding a font and voila! Worked as intended.
Hope this helps anyone else who may come across the same issue. No idea why re-adding the same security setting made it work but it did.

A: Well I can only suggest you have the UAC turned off because I have taken ownership and set the Windows 7 font directory and registry key permissions to allow users change access but the UAC keeps prompting for administrator credentials.

A: This error occurs because the file attribute System is checked. Checked directorys at System cannot have their permissions changed. In my case I try these following command:
attrib -r -s %systemroot%\fonts

To correct these error below:
Warning 5: Access is denied.

Error setting security on c:\windows\fonts

A: You could try to use the Silent Install Builder from Apreltech at https://www.silentinstall.org/. This program builds MSI or EXE packages containing a font registry scripts. You could deploy Silent Install Builder's  MSI through GPO.

A: Login with Admin account first

*

*Go to Run Command

*Type "regedit" click Enter

*Now you can see " HKEY_LOCAL_MACHINE" click and explore it

*next go to "SOFTWARE" then "MICROSOFT" after then "WINDOWS NT"

*Now you can see "Current Version" and go to "Fonts"

*Now you right Click on fonts

*go to change permissions

*make your local user permission for allow access..


text:
Q: How do I merge two different object lists with a unique field into a separate list? I have two different object models(SellerOrder and BuyerOrders) with different properties except one(OrderId). I am getting list of data of both models from different files and I want to get both list to be merged in another object Model(OrderDetails) list. Here are the details.
I have models as below:
Public class SellerOrder
    {
        public string OrderId { get; set; }
        public string MerchantOrderId { get; set; }
        public DateTime PurchaseDate { get; set; }
        public DateTime Amount{ get; set; }
    }

Public class UserOrder
    {
        public string OrderId { get; set; }
        public string BuyerId { get; set; }
        public string BuyerName { get; set; }
        public string BuyerAddress{ get; set; }
    }

Public class OrderDetails
    {
        public string OrderId { get; set; }
        public string MerchantOrderId { get; set; }
        public DateTime PurchaseDate { get; set; }
        public DateTime Amount{ get; set; }
        public string BuyerId { get; set; }
        public string BuyerName { get; set; }
        public string BuyerAddress{ get; set; }
    }

My data is coming like below:
 //getting data from two different places
 List<SellerOrder> sellerOrderList = place1.GetSellerData();
 List<BuyerOrder>  buyerOrderList = place2.GetBuyerData();

I want to get the result like below:
 SellerOderList:
{ OrderId = "1", MerchantOrderId = "1s1", PurchaseDate = "2020/12/04", Amount = "10.00" }
{ OrderId = "2", MerchantOrderId = "1s2", PurchaseDate = "2020/12/04", Amount = "10.00" }
{ OrderId = "3", MerchantOrderId = "1s3", PurchaseDate = "2020/12/04", Amount = "10.00" }
{ OrderId = "4", MerchantOrderId = "1s4", PurchaseDate = "2020/12/04", Amount = "10.00" }
{ OrderId = "5", MerchantOrderId = "1s5", PurchaseDate = "2020/12/04", Amount = "10.00" }

 BuyerOderList:
{ OrderId = "1", BuyerId = "1b1", BuyerName = "Abc", BuyerAddress = "Toronto" }
{ OrderId = "2", BuyerId = "1b2", BuyerName = "Efg", BuyerAddress = "Toronto" }
{ OrderId = "3", BuyerId = "1b3", BuyerName = "Hij", BuyerAddress = "Toronto" }
{ OrderId = "4", BuyerId = "1b4", BuyerName = "Lmn", BuyerAddress = "Toronto" }
{ OrderId = "5", BuyerId = "1b5", BuyerName = "Opq", BuyerAddress = "Toronto" }

OrderDetailsList:

{ OrderId = "1", MerchantOrderId = "1s1", PurchaseDate = "2020/12/04", Amount = "10.00", BuyerId = "1b1", BuyerName = "Abc", BuyerAddress = "Toronto" }
{ OrderId = "2", MerchantOrderId = "1s2", PurchaseDate = "2020/12/04", Amount = "10.00", BuyerId = "1b2", BuyerName = "Efg", BuyerAddress = "Toronto" }
{ OrderId = "3", MerchantOrderId = "1s3", PurchaseDate = "2020/12/04", Amount = "10.00" , BuyerId = "1b3", BuyerName = "Hij", BuyerAddress = "Toronto" }
{ OrderId = "4", MerchantOrderId = "1s4", PurchaseDate = "2020/12/04", Amount = "10.00" , BuyerId = "1b4", BuyerName = "Lmn", BuyerAddress = "Toronto" }
{ OrderId = "5", MerchantOrderId = "1s5", PurchaseDate = "2020/12/04", Amount = "10.00", BuyerId = "1b5", BuyerName = "Opq", BuyerAddress = "Toronto" }

I want to get Seller Order details and Buy Order details to be merged in Order Details List.

A: Try Enumerable.Join:
var orderDetailsList: = sellerOrderList.Join(buyerOrderList, arg => arg.OrderId, arg => arg.OrderId,
    (first, second) => new OrderDetails {
        OrderId = first.OrderId,
        MerchantOrderId = first.MerchantOrderId,
        PurchaseDate = first.PurchaseDate,
        Amount = first.Amount,
        BuyerId = second.BuyerId,
        BuyerName = second.BuyerName,
        BuyerAddress = second.BuyerAddress
        });


text:
Q: Getting All Folders in the given http address I want to know all directories in the given http address. How can I get all directory names in the web application?
I am using C# in Visual Studio 2010.
Thank you for your attention.

A: You can't, unless that information is exposed by something like a sitemap and you read this in some manner.
It is not possible to 'query' a webserver, GET and POST are standard operations and for those you will need the address (uri) to GET/POST from/to.


text:
Q: How to remove the comma using the replace in angular here's the code: https://stackblitz.com/edit/angular-w5ecbw?file=src/app/app.component.ts
item.component.ts
ngOnInit() {
    const data = ['.23.2 ms','.23.001 ms', '.23.81 ms', '192,101.02 ms', '1291,291.02 ms'];
    for (let x = 0; x <= data.length; x++) {
      console.log(this.formatData(data[x].replace(/ .+/, '')))
    }
  }
  formatData(num: any) {
    const [num1, num2] = String(num).split('.');
    if (!num2) {
      return num1;
    } else {
      return `${num1}.${num2}`;
    }
  }

expected output should be:
.23.2
.23.001
    .23.81
    192101.02
    1291291.02

What I want to do here is to remove the comma.

A: Try this.

const data = ['.23.2 ms','.23.001 ms', '.23.81 ms', '192,101.02 ms', '1291,291.02 ms'];

const result = data.map( item => item.replace(/,|[^0-9\.]|/g, ""));

console.log(result.join(", "));

A: You can just remove it like this:
string.replace(',', '');

A: User map, split, replace and join methods.

const data = [
  ".23.2 ms",
  ".23.001 ms",
  ".23.81 ms",
  "192,101.02 ms",
  "1291,291.02 ms"
];

updated = data.map(x => x.split(" ms")[0].replace(",", "")).join('');

console.log(updated);


text:
Q: Ordering based on another model attribute - Ruby I have two models.  Category and Photo.  There are many photos for each category.
I want to order a category object array in such a way that it is ordered by an attribute in the Photo model. Specifically how many times a photo is downloaded.
I am trying to initiate the instance variable with something like
@category = Category.active.order('photos.qty_download DESC)

I would then use that instance variable to list the categories and how many photos have been downloaded for each category
Chicago   45
San Fran   32
Boston    23
etc

What expression will work in Rails?
Thanks

A: Let's assume that your models look something like this:
class Category < ActiveRecord::Base
  has_many :photos
end

class Photo < ActiveRecord::Base
  belongs_to :category
end

Let's also assume:

*

*each photo has a qty_download field as you describe in your
question

*each category has a name field

*the goal is to order the display of categories according to
the sum of all the qty_download for all of the photos in each
category

*it's okay to exclude entirely categories that have no associated photos

With those assumptions, you should be able to write
Category.
  joins(:photos).
  group("categories.id, categories.name").
  select("categories.id, categories.name, sum(photos.qty_download) as total_downloads").
  order("total_downloads desc")

Note that what will be returned will be "partial" category objects that contain only id, name, and total_downloads. If you want additional category fields, add them to both the group and the select clauses.
Update
Newer versions of Postgres allow a simplification of the query:
Category.
  joins(:photos).
  group("categories.id").
  select("categories.*, sum(photos.qty_download) as total_downloads").
  order("total_downloads desc")

Note that in recent versions of Postgres, you can simply group by a unique id -- you no longer must group by all attributes that you which to include in your select. So you can now include all the attributes of categories as categories.*. I'll leave the original in place as it is (marginally) more efficient and backwards-compatible with older versions of Postgres.

A: Category.includes(:photos).order(qty_download: :desc).reference(:photos)


text:
Q: State of in-app purchases in ios I have a bunch of non-consumable and auto-renewable in-app purchases in my app. I want to know if the user has already purchased the app when I visit the in-app purchases. Is there a way to know this?

A: You might want to implement a solution for this problem by storing the purchases of a user and their purchase receipts  on your server.
So before showing products to a user, you can ask your server about which products user has purchased. And accordingly handle the interaction from there on.
P.S. :- Ideally you would not want to hide the already purchased products from a user as he might upgrade and then if he would want to downgrade back to same product then that won't be visible or vice versa.


text:
Q: I can't repeat the texture using GL_TEXTURE_CUBE_MAP and GL_REPEAT After two days of reading and trying, I was able to texture a cube with GL_TEXTURE_CUBE_MAP:
Textured Cube
Then I decided to make a parallelepiped from the cube, in which the corresponding texture is repeated on the long side. I get similar or worse results:
Poorly stretched texture
And I want to get such a result:
Repeated texture
Is it even possible?
Here is the essential part of the code:
void Create( void ) {
    glGenTextures( 1, &id );
    glBindTexture( GL_TEXTURE_CUBE_MAP, id );
    glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );

    const RGB bk_cols[ ] = { {207,193,0}, {133,96,169}, {0,166,81}, {0,84,166}, {158,11,15}, {137,137,137} };
    const char letters[ ] = { 'x', 'y', 'z' };
    RGB* rgb = new RGB[ 16 * 16 + 16 ];
    for( unsigned int i = 0; i < 6; i++ ) {
        glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, 16, 16, 0, GL_RGB, GL_UNSIGNED_BYTE,
            CreateLetter16x16( rgb, {0,250,0}, bk_cols[i], {0,0,0}, letters[ i >> 1 ], (i & 1 ? false : true) ) );
    }
    delete [ ] rgb;

    glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT/*GL_CLAMP_TO_EDGE*/ );
    glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT/*GL_CLAMP_TO_EDGE*/ );
    glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
}

void DrawTexturedCube( void ) {
    float v = 2.0;
    float p = 6.0;
    // All the faces that are not front-faces are discarded.
    // This is a good test of vertex sequence.
    glEnable( GL_CULL_FACE );
    // Of course a depth test is needed here.
    glEnable( GL_DEPTH_TEST );

    // Must be enabled, else textures doesn't work
    glEnable( GL_TEXTURE_CUBE_MAP );
    // If you want your image to be unaffected by the current color,
    // you must change the texture environment parameter to decal
    glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL );

    // Select texture
    glBindTexture( GL_TEXTURE_CUBE_MAP, sq_txt.id );

    glBegin( GL_QUADS );
    // Right
    glTexCoord3f( 1,-1,-1); glVertex3f( p,-v,-v);
    glTexCoord3f( 1, 1,-1); glVertex3f( p, v,-v);
    glTexCoord3f( 1, 1, 1); glVertex3f( p, v, v);
    glTexCoord3f( 1,-1, 1); glVertex3f( p,-v, v);
    // Left
    glTexCoord3f(-1,-1,-1); glVertex3f(-p,-v,-v);
    glTexCoord3f(-1,-1, 1); glVertex3f(-p,-v, v);
    glTexCoord3f(-1, 1, 1); glVertex3f(-p, v, v);
    glTexCoord3f(-1, 1,-1); glVertex3f(-p, v,-v);
    // Top
    glTexCoord3f(-1, 1, 1); glVertex3f(-p, v, v);
    glTexCoord3f( 1, 1, 1); glVertex3f( p, v, v);
    glTexCoord3f( 1, 1,-1); glVertex3f( p, v,-v);
    glTexCoord3f(-1, 1,-1); glVertex3f(-p, v,-v);
    // Bottom
    glTexCoord3f(-1,-1,-1); glVertex3f(-p,-v,-v);
    glTexCoord3f( 1,-1,-1); glVertex3f( p,-v,-v);
    glTexCoord3f( 1,-1, 1); glVertex3f( p,-v, v);
    glTexCoord3f(-1,-1, 1); glVertex3f(-p,-v, v);
    // Front
    float xn = -3.0;
    float xp =  3.0;
    float yn = -1.0;
    float yp =  1.0;
    float zz =  1.0;
    glTexCoord3f(xn,yn,zz); glVertex3f(-p,-v, v);
    glTexCoord3f(xp,yn,zz); glVertex3f( p,-v, v);
    glTexCoord3f(xp,yp,zz); glVertex3f( p, v, v);
    glTexCoord3f(xn,yp,zz); glVertex3f(-p, v, v);
    // Back
    glTexCoord3f( 1,-1,-1); glVertex3f( p,-v,-v);
    glTexCoord3f(-1,-1,-1); glVertex3f(-p,-v,-v);
    glTexCoord3f(-1, 1,-1); glVertex3f(-p, v,-v);
    glTexCoord3f( 1, 1,-1); glVertex3f( p, v,-v);

    glEnd();

    // Restore default parameters
    glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
    // Must be disabled, else colors doesn't work ( Everything will be textured ).
    glDisable( GL_TEXTURE_CUBE_MAP );

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

    float k = v+.01f;
    // Disable fill
    glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
    // Set line width
    glLineWidth( 3 );
    glBegin( GL_QUADS );
    glColor3f( .9f, 0, 0 );
    glVertex3f( k,-k,-k); glVertex3f( k, k,-k); glVertex3f( k, k, k); glVertex3f( k,-k, k); // Right
    glVertex3f(-k,-k,-k); glVertex3f(-k,-k, k); glVertex3f(-k, k, k); glVertex3f(-k, k,-k); // Left
    glVertex3f(-k, k, k); glVertex3f( k, k, k); glVertex3f( k, k,-k); glVertex3f(-k, k,-k); // Top
    glVertex3f(-k,-k,-k); glVertex3f( k,-k,-k); glVertex3f( k,-k, k); glVertex3f(-k,-k, k); // Bottom
    glVertex3f(-k,-k, k); glVertex3f( k,-k, k); glVertex3f( k, k, k); glVertex3f(-k, k, k); // Front
    glVertex3f( k,-k,-k); glVertex3f(-k,-k,-k); glVertex3f(-k, k,-k); glVertex3f( k, k,-k); // Back
    glEnd();
    // Restore fill
    glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
    // Restore default line width
    glLineWidth( 1 );

    // Restore default state
    glDisable( GL_DEPTH_TEST );

    // Restore default state
    glDisable( GL_CULL_FACE );
}

A: Repeat filtering is a texture sampling wrap mode. And wrap modes explain how texture coordinates outside of the space of the texture work.
But the way cubemap texture coordinates are defined (they are vectors from the center of a cube pointing to a location inside that cube), they basically never fall outside of the size of a face of the cubemap. So repeat filtering is a no-op, functionally identical to clamp-to-edge.


text:
Q: Prove $E|Y_n^2 - n|$ is finite Suppose $Y_n$ is a simple random walk on $\mathbb{Z}$. That is $Y_n = X_1 + X_2+...+X_n$, where $\mathbb{P}(X_i=1)=\mathbb{P}(X_i=-1)=\frac{1}{2}$, and $(X_i)$ are i.i.d. I try to show that $E|Y_n^2 - n|$ is finite for any $n\geq 1$.
Here is my proof:
$$E|Y_n^2 - n| =E|(X_1 + X_2+...+X_n)^2- n| = E|X_1^2+...+X_n^2 +2\sum_{1\leq i<j\leq n}(X_iX_j)- n|$$
since $X_i^2 = 1$, the equality becomes $E|2\sum_{1\leq i<j\leq n}(X_iX_j)|$
I stuck here, hope some one can help me.
Thank you

Actually I tried to show $Y_n^2 -n$ is a martingale. Being a Martingale has to satisfy $E|M_n| < \infty$.

A: You will need that

*

*$\mathbb E[X_i^2]=1$

*$\mathbb E[X_iX_j]=\mathbb E[X_i]\mathbb E[X_j]=0$ by independence, and

So, you have: \begin{align}\mathbb E\left[|M_n|\right]&= \mathbb E\left[|Y_n^2-n|\right]\le \mathbb E[Y_n^2]+n\\[0.2cm]&=\mathbb E\left[\left(\sum_{i=1}^n X_i\right)^2\right]+n=\mathbb E\left[\sum_{i=1}^n{X_i^2}+\sum_{i\neq j}X_iX_j\right]+n\\[0.2cm]&=
\sum_{i=1}^n\mathbb E[X_i^2]+\sum_{i\neq j}\mathbb E[X_iX_j]+n=n\mathbb E[X_1^2]+0+n=2n<\infty\end{align}
Note, that you are not asked to show that the bound $(2n)$ does not grow to $\infty$ as $n\to\infty$. You are only asked to show that $\mathbb E[|M_n|]<\infty$, so the above bound of $(2n)$ does it.


text:
Q: Navigation button based on several PowerApps dropdown values I am trying to set mandatory dropdowns to be selected in order to go to the next screen.

*

*Next screen is called End

*First dropdown is called type_4

*Second dropdown is called type_3

*Third dropdown is called type_2
Please note that the default value of the dropdowns is Select your answer (first choice of the dropdown).
This is the code that I used but it doesn't seem to go through:
If(
    IsBlank(type_4.Selected.Value),
    IsBlank(type_3.Selected.Value),
    IsBlank(type_2.Selected.Value),
    Notify("Fill all the fields to continue", NotificationType.Error),
    Navigate(End,ScreenTransition.Cover) )

A: If the default option for your dropdowns is 'Select your answer', then you can use the Or function (or the Or operator) to combine the conditions, in an expression similar to the one below:
If(
    Or(
        type_4.Selected.Value = "Select your answer",
        type_3.Selected.Value = "Select your answer",
        type_2.Selected.Value = "Select your answer"),
    Notify("Fill all the fields to continue", NotificationType.Error),
    Navigate(End,ScreenTransition.Cover) )


text:
Q: Removing Carriage Return (Control-M) in Groovy My file is having unwanted Control-M characters at the end of the records and because of this file is not getting processed.
Sample file (CSV)

Please suggest how can I use ReplaceAll function in Groovy to remove it .

A: This depends on your shell/OS; try "^M" (in the ReplaceAll function), but this is entered by first pressing the "v" key while holding the "control" key down, then pressing the "return" key.

A: Something like this should work....
csvFileContent.replaceAll("\r\n", "\n");


text:
Q: Is self-energy $\mathrm{Im}\Sigma^r<0$ always true? Consider a one-particle retarded Green's function $$G^r(\alpha)=[\omega+i\eta-\varepsilon(\alpha)-\Sigma^r(\alpha)]^{-1}$$ with self-energy $\Sigma^r(\alpha)$ for some quantum number $\alpha$. It is argued that $-\mathrm{Im}\Sigma^r>0$ always holds as it signifies the quasiparticle lifetime. Is this true always?

A: Let us consider the following:

*

*$\Sigma^r$ is a retarded self-energy, i.e., it is given by expressions like
$$\Sigma^r(\omega)=\sum_k |V_k|^2G^r(\omega).$$
Here $V_k$ might be replace by vortex parts with more complex structure, but the rpesence of the retarged Green's function, $\Im \left[G^r\right]<0$ suggests that $\Im [\Sigma^r]<0$.

*$G^r$ is a retarded Green's function - it would not be the case, if we had $\Im \left[\Sigma^r\right]>0$.

I cannot say, if there is a rigorous mathematical proof that $\Im[\Sigma^r]\leq 0$, for any type of dispersions laws and interactions. However, if this relation breaks, we are facing the breakdown of the causality in our calculations, which means that some of the premises of our derivations are wrong - the initial Hamiltonian requires revision (keeping in mind that sometimes the breakdowns of theory are meaningful - e.g., many quantities diverge near phase transitions).


text:
Q: error cp: cannot overwrite directory '/usr/bin/dpkg' with non-directory Go to this url http://security.ubuntu.com/ubuntu/pool/main/d/dpkg/
and you will see a list of dpkg packages. You need to find the dpkg version you need than open new terminal.
Anywhere your machine I select Desktop.
mkdir dpkg
cd dpkg

Run:
wget http://security.ubuntu.com/ubuntu/pool/main/d/dpkg/

(Add the version of dpkg you need after the last /)
For example I needed dpkg_1.17.5ubuntu5.2_amd64.deb but this does not exist any more so I chose the closest one which is
dpkg_1.17.5ubuntu5.8_amd64.deb

So:
wget http://security.ubuntu.com/ubuntu/pool/main/d/dpkg/dpkg_1.17.5ubuntu5.8_amd64.deb

Run
ar x dpkg_1.17.5ubuntu5.8_amd64.deb

Now you can see the contents:
~/dpkg $ ls
control.tar.gz  data.tar.gz  debian-binary  dpkg_1.17.5ubuntu5.8_amd64.deb

Run
~/dpkg $ tar xfvz data.tar.gz ./usr/bin/dpkg
./usr/bin/dpkg
~/dpkg $ ls
control.tar.gz  data.tar.gz  debian-binary  dpkg_1.17.5ubuntu5.8_amd64.deb  usr
~/dpkg $ cd usr/bin/
~/dpkg/usr/bin $ ls
dpkg

~/dpkg/usr/bin $ sudo cp dpkg /usr/bin/

Hi after performing all the above steps it is giving me an error
cp: cannot overwrite directory '/usr/bin/dpkg' with non-directory
Got this error after last step
What can be this error?


text:
Q: Getting XSLT Current Node, formatted as XPath Query? I have the following block of code that gets the name of the nodes down the tree, like this:
section/page/subPage
But I would like to be able to get it down to the following (just making it up):
section[@id='someId']/page/subPage[@user='UserA']/@title
I found the following code from one of these StackOverflow posts:

<xsl:attribute name="path">
  <xsl:for-each select="ancestor-or-self::*">
    <xsl:if test="name() != 'root'">
      <xsl:value-of select="name()">
        <xsl:if test="not(position()=last())">
          <xsl:text>/</xsl:text>
        </xsl:if>
      </xsl:value-of>
    </xsl:if>
  </xsl:for-each>
</xsl:attribute>

Which gives me the straight path, but I would like to run more logic on it to make it so it included the @id (or relevant attribute), and maybe some more stuff I can't think of at the moment.
What is the best way to do this?
I've checked into EXSLT functions, which may work, but maybe you guys have already solved this problem a better way.
Any ideas?
I'm using ruby's nokogiri to parse the xml/xslt if that helps.
Thanks a lot,
Lance

A: This solution does what you want:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" encoding="utf-8" omit-xml-declaration="yes" />

  <xsl:template match="/">
    <root>
      <xsl:attribute name="path">
        <xsl:apply-templates select="(//@title)[1]" mode="make-path" />
      </xsl:attribute>
    </root>
  </xsl:template>

  <xsl:template match="*|@*" mode="make-path">
    <xsl:apply-templates select="parent::*" mode="make-path" />
    <xsl:text>/</xsl:text>
    <xsl:apply-templates select="." mode="make-name" />
    <xsl:choose>
      <xsl:when test="self::section">
        <xsl:apply-templates select="@id" mode="make-predicate" />
      </xsl:when>
      <xsl:when test="self::subPage">
        <xsl:apply-templates select="@user" mode="make-predicate" />
      </xsl:when>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="*|@*" mode="make-predicate">
    <xsl:text>[</xsl:text>
    <xsl:apply-templates select="." mode="make-name" />
    <xsl:text> = '</xsl:text>
    <xsl:value-of select="." />
    <xsl:text>']</xsl:text>
  </xsl:template>

  <xsl:template match="*" mode="make-name">
    <xsl:value-of select="name()" />
  </xsl:template>

  <xsl:template match="@*" mode="make-name">
    <xsl:text>@</xsl:text>
    <xsl:value-of select="name()" />
  </xsl:template>

</xsl:stylesheet>

When applied to
<section id="someId">
  <page>
    <subPage user="UserA" title="test" />
    <subPage user="UserB" title="blah" />
  </page>
  <page>
    <subPage user="UserC" title="fooh" />
  </page>
</section>

you get:
<root path="/section[@id = 'someId']/page/subPage[@user = 'UserA']/@title" />

The <xsl:choose> is the configurable spot (add as many <xsl:when>s as you like):
<!-- test for element name -->
<xsl:when test="self::section">
  <!-- make predicates out of selected attributes -->
  <xsl:apply-templates select="@id" mode="make-predicate" />
</xsl:when>

also possible:
<xsl:when test="self::section">
  <xsl:apply-templates select="@name|@category|subElement" mode="make-predicate" />
</xsl:when>

which would lead to
<root path="/section[@name = 'someName'][@category = 'somecat'][subElement = 'xyz']/..." />

The only issue I see is with predicate values that contain single quotes. They would break the XPath.

A: For each ancestor node you can loop over all attributes with simple xsl:for-each
<xsl:for-each select="@*">

You could then use the attributes to build up the XPath string
<xsl:for-each select="ancestor-or-self::*">
   <xsl:if test="name() != 'root'">
      <xsl:value-of select="name()"/>
      <xsl:if test="@*">
         <xsl:text>[</xsl:text>
         <xsl:for-each select="@*">
            <xsl:text>@</xsl:text>
            <xsl:value-of select="name()"/>
            <xsl:text>='</xsl:text>
            <xsl:value-of select="."/>
            <xsl:text>'</xsl:text>
            <xsl:if test="not(position()=last())">
               <xsl:text> and </xsl:text>
            </xsl:if>
         </xsl:for-each>
         <xsl:text>]</xsl:text>
      </xsl:if>
      <xsl:if test="not(position()=last())">
         <xsl:text>/</xsl:text>
      </xsl:if>
   </xsl:if>
</xsl:for-each>


text:
Q: copy from one database to another using oracle sql developer - connection failed I am trying to copy a table from one database to another using oracle sql developer. I have the username, password and SIDs.
copy from uname1/password1@SID1 to uname2/pwd2@SID2 insert table1 (*) using (select * from message_table);

However I am getting the connection failed error.
The two databases are present in different host hosts (the hostname is different in connection properties).
The table has 5 million records and is too cumbersome to export/import

A: The copy command is a SQL*Plus command (not a SQL Developer command).  If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2).  Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

*

*On the tool bar, select Tools>Database copy.

*Identify source and destination connections with the copy options you would like.

*For object type, select table(s).

*Specify the specific table(s) (e.g. table1).

The copy command approach is old and its features are not being updated with the release of new data types.  There are a number of more current approaches to this like Oracle's data pump (even for tables).


text:
Q: Spivak: How do we know $\arctan{x}$ and $\log{(1+x)}$ for all $x$ if we know these functions for $|x|<1$? In Ch. 20 of Spivak's Calculus, he shows that the remainder terms for $\arctan$ and $\log{(1+x)}$ become large with the order of the Taylor polynomial used to approximate these functions. Thus these approximations

are of no use whatsoever in computing $\arctan{x}$ and $\log{(1+x)}$.
This is no tragedy, because the values of these functions can be
found for any $x$ once they are known for all $x$ with $|x|<1$.

How do we find the values of these functions for any $x$ if we know the functions for $|x|<1$?

A: With base ten logarithms, we have $\log_{10}(1234)=4+\log_{10}(0.1234)$, and in general,
$$\log_{10} x=n+\log_{10} (x/10^n),$$
where $n$ is the number of digits of $x$ before the decimal point. Natural logarithms are just this multiplied by a constant: $\log_e(x)=\log_{10}(x) / \log_{10}(e)$.
For tangents,
$$
\begin{align}
\tan(90^\circ-x)&={\sin (90^\circ-x)\over\cos (90^\circ-x)}\\
&={\cos x\over \sin x}\\
&={1\over \tan x}
\end{align}
$$
All the values of $\tan$ from $0$ to $90^\circ$ are known once the values are known up to $45^\circ$, so $$\arctan (1/x)=90^\circ-\arctan(x).$$ Thus you only need to compute values from $0$ to $1$.

A: It is easy to show, using differentiation the formula
$arctanx+arctan(\dfrac{1}{x})=\dfrac{\pi}{2}$. Hence, knowing the value
for $0<x<1$ we obtain the value of $arctanx$ for $x\geq1$. For negative $x$
we have $arctanx+arctan(\dfrac{1}{x})=-\dfrac{\pi}{2}$ and we follow the same method.
Now, for $log(1+x)$. We assume that $x\in\,[1,2)$ then $x=1+y$ where $0\leq\,y\,<1$.
So $log(1+x)=log(2+y)=log2(1+\dfrac{y}{2})$=$log2+log(1+\dfrac{y}{2})$ where $\dfrac{y}{2}<1$.
If $x\in[2,3)$ then $x=1+z$ where $1\leq z<2$, hence
$log(1+x)=log(2+z)=log2(1+\dfrac{z}{2})=log2+log(1+\dfrac{z}{2})$ where
$\dfrac{z}{2}<1$.
Continuing this process on $[3,4)$ e.t.c. we get the value of $log(1+x)$ for all $x>1$.