text:
Q: CommonJS imports vs ES6 imports Here are two examples of using a non-default export. The first uses commonjs syntax, and the second uses es6. Why does the first example work, but not the second?
// commonjs --- works!
var ReactRouter = require('react-router')
var Link = ReactRouter.Link

// es6 --- doesn't work!
import ReactRouter from 'react-router'
var Link = ReactRouter.Link

I understand that I can use import { Link } from 'react-router' instead, but I'm just trying to wrap my head around how each import differs.

A: import ReactRouter only imports the default export. It does not import an object of named exports which is what you're attempting to achieve in your ES6 code. If there is no default export in the module, this ReactRouter will be undefined.
As stated, import { Link } from 'react-router' is the dedicated syntax for importing a single named export.
If you want to import all named exports into an object, you can use the import..as syntax:
import * as ReactRouter from 'react-router';
var Link = ReactRouter.Link

MDN has a super-helpful list of all the different types of imports and how they work.


text:
Q: What query am I able to perform with Lambda(Method Syntax) and not with (Query Syntax)? What query am I able to perform with Lambda(Method Syntax) and not with (Query Syntax)?
The questions is simple, this is an example of both:
    int[] numbers = { 5, 10, 8, 3, 6, 12};

    //Query syntax:
    IEnumerable<int> numQuery1 =
        from num in numbers
        where num % 2 == 0
        orderby num
        select num;

    //Method syntax:
    IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);

What would be a query that I can perform Method Syntax and not in the Query Syntax?

A: (This is a shorter answer than I was originally writing, but other answers have already provided some of the details.)
There are two reasons one might wish to use lambda expressions instead of query expressions:

*

*Operations which simply aren't covered by query expressions, whether that's methods which aren't covered at all (e.g. Count) or overloads of operations which are included in query expressions, but not in that form. For example:
var indexedValues = values.Select((value, index) => new { value, index });

There's no query expression form which uses that overload.

*When the lambda form is simpler. For example, if you've only got a single projection or filter, it can be simpler to do it in one call than set up the fluff of a query expression:
 var adults = people.Where(person => person.Age > 18);

Vs:
 var adults = from person in people
              where person.Age > 18
              select person;

Additionally, the lambda expression approach is somewhat tidier when you want to continue the expression after the query. For example, creating a list of the names of adults:
 var names = people.Where(person => person.Age > 18)
                   .Select(person => person.Name)
                   .ToList();

Vs:
 var names = (from person in people
              where person.Age > 18
              select person.Name).ToList();

The brackets end up being a bit irritating.
Where query expressions shine is in the operations which introduce transparent identifiers - joins, SelectMany, let etc. While you obviously can translate such code into lambda form, it can end up really ugly.

A: You can find complete list of methods that have corresponding keywords within query expression syntax here: Query Expression Syntax for Standard Query Operators. List contains information about both C# and VB.NET support. Any method that is not listed there is not available neither in C# nor VB.NET.
Interesting thing is, that there is a bit more available in VB.NET then in C#.

A: You can't do a select top 10 in query syntax. You can use .Take(10) in method syntax.
Aggregate functions are not supported either.

A: LINQ query syntax translates directly to extension method syntax. However, the reverse is not true. There are way more extension methods than supported by the LINQ query syntax keywords.
So, with method syntax you can do exactly the same or more than with LINQ query syntax. Usually LINQ query syntax is nicer to read.
// LINQ query syntax
var query =
    from num in numbers
    where num % 2 == 0
    orderby num
    select num;

// Corresponding method syntax
var query = numbers
    .Where(num => num % 2 == 0)
    .OrderBy(num => num)
    .Select(num => num);

A simple example of what you can do with method syntax and not with query syntax (since there are no keywords for it):
var query = numbers
    .First();

You can combine both if you want:
var query =
    (from num in numbers
    where num % 2 == 0
    orderby num
    select num)
    .First();

Apart from First, there are tons of LINQ extension methods (Sum, Average, Max...) that have no keywords in LINQ query syntax.

By the way, because LINQ query syntax maps to extension methods, you are not restricted to using LINQ extension methods. If you define on your own custom objects a Select and Where method that both accept a delegate, then you can use LINQ query syntax on your own objects! How cool is that? For example, a nonsensical example:
public class MyClass
{
    public MyClass Where(Func<string, bool> function)
    {
        return this;
    }

    public List<string> Select(Func<string, string> function)
    {
        return new List<string>();
    }
}

MyClass myClass = new MyClass();
var x = from m in myClass
        where !String.IsNullOrEmpty(m)
        select m;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do we have a slow `malloc`? As far as I know, custom memory managers are used in several medium and large-scale projects. This recent answer on security.se discusses the fact that a custom memory allocator in OpenSSL was included for performance reasons and ultimately ended up making the Heartbleed exploit worse. This old thread here discusses memory allocators, and in particular one of the answer links to an academic paper that shows that while people write custom memory allocators for performance reasons because malloc is slow, a general-purpose state-of-the-art allocator easily beats them and causes fewer problems than developers reinventing the wheel in every project.
As someone who does not program professionally, I am curious about how we ended up in this state and why we seem to be stuck there --- assuming my view is correct, which is not necessarily true. I imagine there must be subtler issues such as thread safety. Apologies if I am presenting the situation wrongly.
Why is the system malloc not developed and optimized to match the performance of these "general-purpose state-of-the-art allocators"? It seems to me that it should be quite an important feature for OS and standard library writers to focus on. I have heard a lot of talking about the scheduler implementation in Linux kernel in the past, for instance, and naively I would expect to see more or less the same amount of interest for memory allocators. How come standard malloc is so bad that so many people feel the need roll out a custom allocator? If there are alternative implementations that work so much better, why haven't system programmers included them in Linux and Windows, either as default or as a linking-time option?

A: There are two problems:

*

*No single allocation scheme fits all application needs.

*The C library was poorly designed (or not designed). Some non-eunuchs operating systems have configurable memory managers that can allow the application to choose the allocation scheme. In eunuchs-land, the solution is to link in your own malloc/free implementation into your application.
There is no real standard malloc implementation (GNU LIBC's is the probably the closest to standard). The malloc implementations that come with the OS tend to work fine for more applications.


text:
Q: How do I create a multi-column constraint in SQL Server? I know this is very simple, but how do I do this in plain SQL?

A: For a unique constraint during table creation:
CREATE TABLE T1 (
    Col1 int NOT NULL,
    Col2 int NOT NULL,
    UNIQUE (Col1, Col2)
)

After table creation:
ALTER TABLE T1 ADD UNIQUE (Col1, Col2)

A: Are you talking about check constraints?
alter table MyTable add constraint CC_Dates check (FromDate < ToDate)


text:
Q: How to rebase an upstream branch to master while keeping the merge histories? Given that an upstream feature branch was first created and branched off from master, others have been merging their changes to it. Now the master has been updated because of other essential features, which are also needed by this feature branch, how do you rebase this upstream feature branch to the latest master head while keeping all the histories?
e.g.
        ----  changes merged to feature
       /    \
      +------+---- feature
     /
----+---- master

now
        ----  changes merged to feature
       /    \
      +------+---- feature
     /
----+----+------+---- master
          \    /
           ---- other features merged to master

want to rebase so that change histories to the feature branch are not lost
                    ----  changes merged to feature
                   /    \
                  +------+---- feature
                 /
---------+------+---- master
          \    /
           ---- other features merged to master

A: Verify that you have a version of git >= 2.19 (2.22 is better for that) and do:
git checkout feature
git rebase --rebase-merges master

One source: https://www.infoq.com/news/2019/07/git-2-22-rebase-merges/


text:
Q: sql - IN, JOIN or EXISTS for filtering I have the following two entities:
project(identifier, name, ...)
member(identifier, name, ...)

They are joined by the following table:
project-member(project_identifier, member_identifier)

What is the most common way to find out which projects a certain member (by identifier) belongs to? I see three possibilities:
select r1.*
from   project r1
join   project-member r2
       on r2.member_identifier = 3 and r1.identifier = r2.project_identifier;

select *
from   project r1
where  r1.identifier in (select project_identifier from project-member where member_identifier = 3);

select *
from   project r1
where  exists (select * from project-member where member_identifier = 3 and project_identifier = r1.identifier);

I understand that it mostly depends on the data and that the query plan should be analyzed with real-life data, but I want to know what the default choice would be. I expect it is the EXISTS construction, but I would like to have your opinion.

A: As you say it depends on many factors that are not stated in the question, but assuming correct indexes are in place I believe they will produce the same or at least very similar query plans since they all begin by fetching a specific set of rows from project-member and then joins that against project.
I think this variant seems most natural:
select p.*
from project-member pm
inner join project p on p.identifier = pm.project_identifier
where pm.member_identifier = 3

That is, filter rows from a table based on what you have a predicate for, and then join the other table to get the information you actually need.


text:
Q: Linux Shell Script Illegal number I am trying to find out the number of occurrences of pattern in a file with following code:
#!/bin/sh

var='grep -c 'abc' file1'

if [ "$var" -lt 10 ]; then
     echo "less than 10"
fi

I am getting the error: Illegal number: grep -c abc file1
Can someone please help.
Thanks.

A: Use backticks (`) instead of apostrophes ('):
#!/bin/sh

var=`grep -c 'abc' file1`

if [ "$var" -lt 10 ]; then
     echo "less than 10"
fi

A: You probably want backticks (`) rather than single-quotes (').  i.e.:
var=`grep -c 'abc' file1`

A: You've used a single quote rather than a backtick so your var variable is actually set to a string literal rather than the result of that command. You'd see that if you echoed the variable first:
pax$ var='grep -c 'abc' file1'
pax$ echo "[$var]"
[grep -c abc file1]

The backtick version would be:
var=`grep -c 'abc' file1`

But I'd like to suggest using bash where possible for scripting. You'll be hard-pressed finding a mainstream distro that doesn't have it by default and it's considered by some to be more powerful than other shells. In fact, on some systems, /bin/sh is bash.
If you can go that rute, the $() construct is usually a better idea since you can nest them without pain:
var=$(grep -c 'abc' file1)

A: Try posting the followings to get better answer:

*

*grep --version

*bash --version if your shell is Bash or let us know which shell you are using.

*use grep within back-ticks or as shown below

*[[ is more versatile in Bash than [.

Finally, the following works on my machine without any error:
#!/bin/bash
var=$(grep -c "abc" file1)
if [[ "$var" -lt 10 ]]
then
    echo "less than 10"
fi

Execution:
user@machine:~$ cat file1
abc
abcd
abcde
abcdef
user@machine:~$
user@machine:~$ ./t.sh
less than 10
user@machine:~$


text:
Q: Setting UILabel background color causes app to crash I have the following code:
UIImageView *photo = [[[UIImageView alloc] initWithFrame:CGRectMake(title_bar.titleView.frame.origin.x+130, title_bar.titleView.frame.origin.y-12, 22.0, 22.0)] autorelease];
UIImage *theImage = [UIImage imageNamed:@"question mark icon"];
photo.image = theImage;
UIView *new_view = [[UIView alloc] init];
[new_view addSubview:photo];
UILabel *new_label = [[UILabel alloc] initWithFrame:CGRectMake(title_bar.titleView.frame.origin.x-145, title_bar.titleView.frame.origin.y-12, 268.0, 22.0)];
[new_label setText:@"gregrgtg"];
[new_label setBackgroundColor:[UIColor clearColor]]; //COMMENTING THIS LINE OUT MAKES IT WORK
[new_view addSubview:new_label];
title_bar.titleView = new_view;

When the background color is set to clear, the program SIGABRTs. If I comment out that line, it works fine (except that the background for the label is just white). Also, if I just init the label rather than initWithFrame-ing it, the program doesn't crash, but my label can't be seen.

A: UIImageView *photo = [[[UIImageView alloc] initWithFrame:CGRectMake(title_bar.titleView.frame.origin.x+130, title_bar.titleView.frame.origin.y-12, 22.0, 22.0)] autorelease];
UIImage *theImage = [UIImage imageNamed:@"question mark icon"];
photo.image = theImage;
UIView *new_view = [[UIView alloc] init];
[new_view addSubview:photo];

title_bar.titleView = new_view;//this line by madhu

UILabel *new_label = [[UILabel alloc] initWithFrame:CGRectMake(title_bar.titleView.frame.origin.x-145, title_bar.titleView.frame.origin.y-12, 268.0, 22.0)];
[new_label setText:@"gregrgtg"];
[new_label setBackgroundColor:[UIColor clearColor]]; //COMMENTING THIS LINE OUT MAKES IT WORK
[new_view addSubview:new_label];

reason :
u had added ur titlebar's titleview atlast but referred them before .


text:
Q: Setting the value in a matrix after fill() returns incorrect matrix If I initialize the matrix like
x = [["O", "O", "O"], ["O", "O", "O"], ["O", "O", "O"]];

And then set
x[0][1] = "X"
It returns
[ [ 'O', 'X', 'O' ], [ 'O', 'O', 'O' ], [ 'O', 'O', 'O' ] ]

as expected
However, if I initialize the matrix as the following:
x = new Array(3).fill(new Array(3).fill('O'))

And then
x[0][1] = "X"
It gives me back
[ [ 'O', 'X', 'O' ], [ 'O', 'X', 'O' ], [ 'O', 'X', 'O' ] ]

What is going on here?

A: When you do this:
x = [["O", "O", "O"], ["O", "O", "O"], ["O", "O", "O"]];

Javascript is creating 3 different Arrays in memory, so when you access x[0][1] you're accessing just that array.
When you are using the:
x = new Array(3).fill(new Array(3).fill('O'))

You are basically filling the array with same array 3 times, so when you access x[0][1] you're accessing the same Array in memory that's also connected to x[1] and x[2].
As commented by @Shidersz, a possible iterative solution would be:
// one liner:
Array.from({length: 3}, x => new Array(3).fill("0"));

This is creates an array and populates it with the values returned from the inputed function. Here's a breakdown:
// same as previous only longer with comments
// Create an Array from the first argument,
//as modified by the mapping function in the 2nd argument
Array.from(
  // This could be any array like object.
  // In the case of length it just reads the length property
  // and iterates that number of times,
  // so it could be useful if you want to
  // fill the top array with 100000 arrays.
  {length: 3},
  // x argument for the mapping is irrelevant
  x => {
    // returning the array with 3 "0" strings in it.
    return  new Array(3).fill("0")
  });

docs here for more reference.

A: The problem is that this line of code builds an array of three elements, where each element points to the same exact array:
x = new Array(3).fill(new Array(3).fill('O'))

To help explain, consider this example. Your code is essentially the same as this:
innerArray = new Array(3).fill('O');
x = [innerArray, innerArray, innerArray];

Note that each element is pointing to the same exact array. If you change the code to this instead, the array will behave the way you expect, because each element is a separate array:
x = [new Array(3).fill('O'), new Array(3).fill('O'), new Array(3).fill('O')];


text:
Q: Compute min distance between group member and other group members, looped over many groups I'm trying to add a column to the below dataset that denotes the lowest distance (in feet, which is the measurement currently represented) between a member (Player) of the group (ChanceId) and the other nine members of the group (ChanceId being the group). Basically, how far away is the nearest group member. I need this done for each member of a given group, and then need it looped over thousands of groups (preferably all using dplyr).
Thanks!!
ChanceId <- c("AD885857-5C31-575C-9963-B4D88E320451", "AD885857-5C31-575C-9963-B4D88E320451",
              "AD885857-5C31-575C-9963-B4D88E320451", "AD885857-5C31-575C-9963-B4D88E320451",
              "AD885857-5C31-575C-9963-B4D88E320451", "AD885857-5C31-575C-9963-B4D88E320451",
              "AD885857-5C31-575C-9963-B4D88E320451", "AD885857-5C31-575C-9963-B4D88E320451",
              "AD885857-5C31-575C-9963-B4D88E320451", "AD885857-5C31-575C-9963-B4D88E320451",
              "AC66722F-2813-5D6D-ABF2-9F6F9834A604", "AC66722F-2813-5D6D-ABF2-9F6F9834A604",
              "AC66722F-2813-5D6D-ABF2-9F6F9834A604", "AC66722F-2813-5D6D-ABF2-9F6F9834A604",
              "AC66722F-2813-5D6D-ABF2-9F6F9834A604", "AC66722F-2813-5D6D-ABF2-9F6F9834A604",
              "AC66722F-2813-5D6D-ABF2-9F6F9834A604", "AC66722F-2813-5D6D-ABF2-9F6F9834A604",
              "AC66722F-2813-5D6D-ABF2-9F6F9834A604", "AC66722F-2813-5D6D-ABF2-9F6F9834A604")

Player <- c( "Robert Covington", "Mason Plumlee", "Jusuf Nurkic", "Ish Smith", "Gordon Hayward",
             "Norman Powell", "Miles Bridges", "Anfernee Simons", "C.J. McCollum", "Kelly Oubre Jr.",
             "Patrick Beverley", "Jarred Vanderbilt", "Karl-Anthony Towns", "Bam Adebayo", "P.J. Tucker Jr.",
             "D'Angelo Russell", "Anthony Edwards", "Duncan Robinson", "Kyle Lowry", "Jimmy Butler")

X_RimLocation <- c(-39.77, -40.64, -40.10, -29.98, -34.16, -32.91, -44.77, -37.43, -9.60, -18.24,
                   -37.39, -39.00, -28.75, -30.88, -27.56, -10.09, -20.64, -38.04, -38.29, -12.51)

Y_RimLocation <- c(-7.97, 4.19, 1.51, 18.03, -22.16, 4.39, 0.33, 3.45, -9.68, -10.78, -19.26, 14.25,
                  10.11, 7.05, -8.54, 2.64, -16.71,  11.13, -12.34, 3.89)

data <- data.frame(ChanceId, Player, X_RimLocation, Y_RimLocation)

A: We could do this by joining the data to itself, calculating the distances for each player pairing in each chanceId, and select the minimum.
In this case, since we know there are only 10 players per play, the joined data will only be 10x as big as the original, so for data with only "thousands" of groups this should be pretty performant.
library(dplyr)
library(ggplot2) # to show answer graphically

dists <- data %>%
  left_join(data, by = "ChanceId") %>%
  filter(Player.x != Player.y) %>%
  mutate(dist = sqrt((X_RimLocation.x - X_RimLocation.y)^2 +
                       (Y_RimLocation.x - Y_RimLocation.y)^2)) %>%
  group_by(ChanceId, Player.x) %>%
  summarize(min_dist = min(dist), .groups = "drop")

data %>%
  left_join(dists, by = c("ChanceId", "Player" = "Player.x")) %>%
  ggplot(aes(X_RimLocation, Y_RimLocation, color = min_dist)) +
  geom_point() +
  geom_text(aes(label = Player), hjust = 0) +
  facet_wrap(~ChanceId)


text:
Q: android: I used dlib to get facial landlandmarks in real-time, Want help in increasing speed when face landmarks detection After face detected, it takes 100ms to get facial landmarks. FPS is about 6,full_object_detection shape = sp(img, det); this codes costs 100ms, how can I increase speed in face landmarkes detection?

A: Even I had the same problem initially.
I suggest you do 2 things :

*

*Resize the frame for detection task(ex: 1280*960 frame to 320*240 resolution)
You can make use of opencv method :
#define FACE_DOWNSAMPLE_RATIO 4
cv::resize(image, image_small, cv::Size(), 1.0/FACE_DOWNSAMPLE_RATIO, 1.0/FACE_DOWNSAMPLE_RATIO);

*Skip the frames in detection process :
#define SKIP_FRAMES 4
static int counts=0;
if ( counts % SKIP_FRAMES == 0 ) {
faces = detector(cimg_small);
}
cimg_small is image of dlib type:(pixel_traits: bgr_pixel)
Refer this link : Here. If you do these two process in your native method you will get 13-17 fps. If you still want to raise the rate of FPS/detection should be faster you can do detection in specific ROI like MSQRD App. Further, if there are any other techniques please do suggest. It will help me too. Thank you. Good luck.


text:
Q: Azure IoT Hub - Send message (C2D) to one device on 2 topics instead of devicebound/# As a MQTT client (device), I am using devices/{deviceid}/messages/devicebound/# topic to receive Cloud to Device messages. This device is a gateway for me and there are 3 devices attached to it.
I want to send 3 different commands to 1 gateway on 3 different topics, like
devices/{deviceid}/messages/devicebound/device1
devices/{deviceid}/messages/devicebound/device2
devices/{deviceid}/messages/devicebound/device3

My gateway is registered in iot-hub and I use it at {deviceid}.
Is it possible?

A: Based on the official document "Communicate with your IoT hub using the MQTT protocol", it says:

Since IoT Hub is not a general purpose pub-sub messaging broker, it
  only supports the documented topic names and topic filters.
IoT Hub delivers messages with the Topic Name
  devices/{device_id}/messages/devicebound/, or
  devices/{device_id}/messages/devicebound/{property_bag} if there are
  any message properties.

Here is a solution using system property "messageId" as the filter. So your three topics:
devices/{deviceid}/messages/devicebound/device1
devices/{deviceid}/messages/devicebound/device2
devices/{deviceid}/messages/devicebound/device3

would look like this:
devices/{deviceid}/messages/devicebound/%24.mid=device1&%24.to=%2Fdevices%2Ftest1%2Fmessages%2FdeviceBound&iothub-ack=full
devices/{deviceid}/messages/devicebound/%24.mid=device2&%24.to=%2Fdevices%2Ftest1%2Fmessages%2FdeviceBound&iothub-ack=full
devices/{deviceid}/messages/devicebound/%24.mid=device3&%24.to=%2Fdevices%2Ftest1%2Fmessages%2FdeviceBound&iothub-ack=full

This is the test:
Send C2D message from azure device explorer:

Receive C2D message from MQTTBox:


text:
Q: In-order access to shared resource in python3 Multiprocessing Given the MWE below:
import multiprocessing

def thread_function(shared_resource : dict, val : int) -> None:

    if val not in shared_resource.keys():
        print(f"Value {val} is not in keys!")
        shared_resource[val] = 1

    shared_resource[val] += 1

def main():

    no_of_threads = 5
    manager       = multiprocessing.Manager()

    shared_resource = manager.dict()

    values = [1 , 1 , 2 , 1 , 3, 3, 3, 4, 5]

    with multiprocessing.Pool(no_of_threads) as pool:

        pool.starmap(thread_function,
                     [ (shared_resource, val) for val in values],
                     chunksize=1)

    print(shared_resource)

if __name__ == "__main__": main()

I am having a readers/writers issue that I don't know how to resolve. The dictionary is a shared resource amongst the threads and I wish for the access to it to be atomic i.e., to avoid the scenario where two threads try to write the same value to it. For instance here is an incorrect output:
Value 1 is not in keys!
Value 1 is not in keys! # <-- Nope!
Value 2 is not in keys!
Value 3 is not in keys!
Value 4 is not in keys!
Value 5 is not in keys!

On the other hand, there is the possibility that the threads will access the resource in the correct order and the output will be the correct one i.e.,
Value 1 is not in keys!
Value 2 is not in keys!
Value 3 is not in keys!
Value 4 is not in keys!
Value 5 is not in keys!
{1: 4, 2: 2, 3: 4, 4: 2, 5: 2}

But how can I avoid such scenarios and always have them behave as expected? Thank you in advance.

A: I wouldn't call it exactly criminal, but I would call it malpractice.
Your code in thread_function constitutes a critical section whose execution needs to be serialized so that only a single process can be executing it at a time. Even what appears to be a single statement, shared_resource[val] += 1, consists of multiple bytecode instructions and two processes could read the same initial value of shared_resource[val] and store the same updated value. But clearly multiple processed running in parallel could clearly find that there are no keys in the dictionary and will be storing identical keys.
import multiprocessing

def init_processes(the_lock):
    global lock
    lock = the_lock

def thread_function(shared_resource : dict, val : int) -> None:

    with lock:
        if val not in shared_resource.keys():
            print(f"Value {val} is not in keys!")
            shared_resource[val] = 1

        shared_resource[val] += 1

def main():

    no_of_threads = 5
    manager       = multiprocessing.Manager()

    shared_resource = manager.dict()

    values = [1 , 1 , 2 , 1 , 3, 3, 3, 4, 5]

    lock = multiprocessing.Lock()
    with multiprocessing.Pool(no_of_threads, initializer=init_processes, initargs=(lock,)) as pool:

        pool.starmap(thread_function,
                     [ (shared_resource, val) for val in values],
                     chunksize=1)

    print(shared_resource)

if __name__ == "__main__": main()

Prints:
Value 1 is not in keys!
Value 2 is not in keys!
Value 3 is not in keys!
Value 5 is not in keys!
Value 4 is not in keys!
{1: 4, 2: 2, 3: 4, 5: 2, 4: 2}

NOTE: You have no control, however, over the dispatching of the tasks and therefore cannot control the order in which the keys will be stored.


text:
Q: Force page redirect on token errors with a custom decorator using flask-jwt-extended I am using the Flask JWT-Extended library to implement JWT access tokens.
When a user's token expires, is invalid, or non existent, what happens by default is Flask returns a JSON like:
{"msg": "Missing cookie \"access_token_cookie\""}
I want to make a decorator that wraps the @jwt_required but does an internal redirect (like to a login page) instead of returning a JSON like above.
Here's an example decorator:
def redirect_if_error(view_function):
    @wraps(view_function)
    def wrapper(*args, **kwargs):
        jwt_data = _decode_jwt_from_request(request_type='access')

        # Do custom validation here.
        if 'identity' in jwt_data:
            authorized = True
        else:
            authorized = False

        if not authorized:
            return redirect('login', code=302)

        return view_function(*args, **kwargs)

    return jwt_required(wrapper)

and an example page protected page route, that I'd like Flask to redirect the user to if any sort of token error occurs:
@mod.route('/')
@redirect_if_error
def home():
    return render_template("index.html")

My problem is I cannot figure out how to override the default JSON return with a redirect. If there is any error, the logic instead the wrap function is ignored, and some sort of error message is outputted.
Is there a better way to override the default behavior using a new decorator?

A: Figured out how to accomplish this with a custom decorator. Simply catching the exception with a try - except worked, like:
def redirect_if_jwt_invalid(view_function):
    @wraps(view_function)
    def wrapper(*args, **kwargs):
        # attempt to grab the jwt from request
        try:
            jwt_data = _decode_jwt_from_request(request_type='access')
        except:
            jwt_data = None
        # if the grab worked and the identity key is in the dict then proceed
        if jwt_data and 'identity' in jwt_data:
            return view_function(*args, **kwargs)
        else:
            return redirect('login', code=302)

    return wrapper

and the route:
from Utilities.Helpers import redirect_if_jwt_invalid

mod = Blueprint('page_routes', __name__)

@mod.route('/')
@redirect_if_jwt_invalid
def home():
    return render_template("index.html")


text:
Q: CSV to XLSX VB.NET enter image description hereenter image description hereI am just learning VB.NET and unfortunately I have been tasked with something I do not have a clue how to do.
I need to create a quick windows based application to export csv files into an XLSX file.
Yes, I know that other posts may have a similar topic however this one I believe is unique.
The CSV file will have 5 headers, `Line, Component, Picked, Placed and Missed. We have part numbers in column 2 that would be placed under Component. I am understanding from the powers that be, this file sums the total part numbers i.e. 0-5490045 and the line JUKI 3 and totals Picked, Placed and Missed parts. I have provided a sample rows below. First row is the csv formatted, the second is the output. I am not sure which loop would be best a FOR loop, WHILE loop etc. I am assuming I will need a loop of some sort to get through all the data in the csv file.
The only code I have opens the dialog box and allows for file selection and attempts to read into a datatable. I am attempting to get this working and then restructure some code.
Imports Spire.Xls
Imports System.Windows.Forms
Imports System.Data

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim dialog As OpenFileDialog = New OpenFileDialog
        dialog.Filter="CSV document(*.csv)|*.csv"
        Dim result As DialogResult = dialog.ShowDialog
        If(result=DialogResult.OK) Then
            Dim csvFile As String = dialog.FileName
            Dim workbook As Workbook = New Workbook
            workbook.LoadFromFile(csvFile,",")
            Dim worksheet As Worksheet = workbook.Worksheets(0)
            Dim dt As DataTable=worksheet.ExportDataTable

            Me.dataGridView1.DataSource=dt
        End If
    End Sub

End Class

  JUKI 3    0-5490045 96    96  3

  Line  Component   Picked  Placed  Missed
  JUKI 3    0-5490045   99  96  3

A: I hate to make a suggestion and not show how it would work. Below is an example using a custom object called Machine to hold the data. This class is a bare minimum for an object and is only used as an example to get you started. It has some fields that will come in handy when looping thru the list to do your computations. It is also here you could add some custom functions/subs to help in some task that involves "Machine" objects.  Also here you could add some compare functions which will enable you to sort among other things. After you put all this together you should end up with a list of valid Machine objects.
It is this list you could use to help you move on to the computing/removing duplicates part of your task. In the process of computing the data you could create a final list of Machine objects that you could use to export to excel with headers or display it to a DataGridView. Hope this helps.
Machine Class
Public Class Machine
  Private name As String
  Private partNumber As String
  Private inventoryIn As Integer
  Private inventoryOut As Integer
  Private inventoryMissing As Integer

  Public Sub New(inName As String, inPartNum As String, inInvIn As Integer, inInvOut As Integer, InInvMis As Integer)
    name = inName
    partNumber = inPartNum
    inventoryIn = inInvIn
    inventoryOut = inInvOut
    inventoryMissing = InInvMis
  End Sub

  Property GetName As String
    Get
      Return name
    End Get
    Set(value As String)
      name = value
    End Set
  End Property

  Public Overrides Function ToString() As String
    Return "Name: " + name + " #: " + partNumber + vbTab + " In:" + inventoryIn.ToString() + " Out:" + inventoryOut.ToString() + " Miss:" + inventoryMissing.ToString()
  End Function
End Class

Now to your issue of reading the file
I did not use anything involving excel. Since you have a simple csv file we will use it. Also we will use the Machine class above. Using your open file dialog we get the name of the file to read.   A variable partsList is created to hold the Machine objects created when reading the file.  Then a for each loop goes through the list and displays the results in a text box on the form.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Dim dialog As OpenFileDialog = New OpenFileDialog
  dialog.Filter = "CSV document(*.csv)|*.csv"
  Dim result As DialogResult = dialog.ShowDialog
  If (result = DialogResult.OK) Then
    Dim csvFile As String = dialog.FileName
    Dim partsList As List(Of Machine) = ReadText(csvFile)
    For Each curMac As Machine In partsList
      TextBox1.AppendText(curMac.ToString() + Environment.NewLine)
    Next
  End If
End Sub

Function to read the csv file
Private Function ReadText(filePath As String) As List(Of Machine)
  Dim fileReader As System.IO.StreamReader
  Dim data As List(Of Machine) = New List(Of Machine)
  fileReader = My.Computer.FileSystem.OpenTextFileReader(filePath)
  Dim curline As String = ""
  While (Not curline Is Nothing)
    curline = fileReader.ReadLine()
    '' need to check for valid data
    '' if anything is invalid simply ignore it... i.e. your bad rows
    '' keep in mind this will also ignore good rows that have a single piece of data bad
    If (StringOK(curline)) Then
      Dim newMac = GetMac(curline)
      data.Add(newMac)
    End If
  End While
  Return data
End Function

A couple of helper functions to validate the data
Private Function StringOK(inString As String) As Boolean
  If (String.IsNullOrEmpty(inString)) Then
    Return False
  End If
  Dim splitArray() As String = inString.Split(",")
  Try
    If ((String.IsNullOrEmpty(splitArray(0))) Or (String.IsNullOrEmpty(splitArray(1)))) Then
      Return False
    End If
    Dim value As Integer
    If ((Not Integer.TryParse(splitArray(2), value)) Or
        (Not Integer.TryParse(splitArray(3), value)) Or
        (Not Integer.TryParse(splitArray(4), value))) Then
      Return False
    End If
    Return True
  Catch ex As Exception
    Return False
  End Try
End Function

Function GetMac(inString As String) As Machine
  Dim splitArray() As String = inString.Split(",")
  Dim value As Integer
  Dim name As String = splitArray(0)
  Dim number As String = splitArray(1)
  Integer.TryParse(splitArray(2), value)
  Dim invIn As Integer = value
  Integer.TryParse(splitArray(3), value)
  Dim invOut As Integer = value
  Integer.TryParse(splitArray(4), value)
  Dim invMis As Integer = value
  Return New Machine(name, number, invIn, invOut, invMis)
End Function

A: If you are trying to accomplish how to import the data into a datatable below is a fast way of handling that. This will bring your whole csv into a datatable which you could then do logic on and create your xlsx file.
Friend Shared Function GetExcelFile(ByVal strFileName As String, ByVal strPath As String) As DataTable

Try

    Dim dt As New DataTable

        Dim ConStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & ";Extended Properties=""Text;HDR=Yes;FMT=Delimited\"""
        Dim conn As New OleDb.OleDbConnection(ConStr)
        Dim da As New OleDb.OleDbDataAdapter("Select * from " & strFileName, conn)
        da.Fill(dt)

    Return dt

Catch ex As Exception
    Return Nothing
End Try

End Function


text:
Q: Script do not affect all the element I am posting because I have encountered a problem with one script that I am trying to develop .
What I am trying to create is a gallery that receives it's images from Instagram. In order to accomplish this two tasks I've found two plugins that fits my needs , but I am unable to fusion them both.
I'm relatively new to Jquery , and I do not understand why the script that I'm trying to run only affects one part of the code.
This example gallery has two fundamental parts :
1)Pre-loaded by the developer :

And , the ones that are added dynamically thanks to the instagram api :

Well , the main problem is that the part that handles the gallery seems to read only the part added manually , but not the ones that comes thanks to the instagram api .
I'm pretty sure that my problem is related to the time that the script is loaded , since the script changes some atributes of the images like href to data-href , but I've tried to pre-load that information , and I received the same results.
In order to give a visual idea of my problem , I have the script in codepen :
http://codepen.io/anon/pen/XJdbZR

And , this is the idea I have that tells me that only the per-loaded information is being modified by the script

I appreciate any kind of help or hint. Thanks

A: The short answer? Lose the <> characters in your jQuery identifiers. You should treat the identifiers the same as you would CSS identifiers.
i.e.; $('') should actually be $('a').
To test this, go ahead and run them both in your favorite browser console and see the difference.

A: problem is that the first time that page inits will bind imageflip to all ul#iGallery children and on that moment your new images are not loaded so normally in similar cases must bind your function
 imageflip
into ul again. im sure this will solve your problem but here in your case ther's another problem and that's u cant bind imageflip twice because of plugin structure. i fixed your code at codepen "fixed code" but this will only work if didLoadInstagram function trigges.


text:
Q: Sometimes my Android app views don't show up properly  I have noticed an issue regarding certain layout attributes and 9-patch drawables. Sometimes, it seems that they don't get 'compiled' with the rest of the code. I don't know much about the process by which 9-patch drawables are interpreted (I assume it does at compile time?) but  I assume there are metadata associated to them. If that is the case, let say those metadata are not taken into account. In such cases, what I usually do is to clean my project many times, or restart Eclipse or even... restart my computer.
I don't want to make bold assumptions on why this is happening (like memory issues on the IDE side), but do you guys have any explanations? Does it happen to you as well?
Note that it also applies to other view attributes like margins or paddings.
I have set the max heap space taken by Eclipse up to 1Gb and I have to say that even with that Eclipse crashes a lot. May be all these are related and can be put inside the hat of memory issues.
Thanks!


text:
Q: Flask: importing custom functions into API I come from a background in R and I'm trying to develop an API in Python using Flask. My folder looks something like this:
project
--server.py
--custom_functions
----func1.py
----func2.py
--more_custom_functions
----subfolder1
------func3.py
------func4.py
----subfolder2
------func5.py
------func6.py

I prefer to organise my custom functions into different subfolders based on their purpose, so custom_functions could be for instance functions related to cleaning, et cetera. Ideally, when I launch server.py using (in Windows CMD, if it helps)
python server.py

in the directory /project, I'd like to be able to import every function. A function looks like
import numpy as np
def func1 (x) :
     return(x + 1)

and nothing else.
My question is this: how does one at initialisation of the server (i.e. upon python server.py) import every single module (e.g. numpy/pandas) globally so that all the subfunctions can use these modules without having a call to import inside them, i.e. (in the above example, can we remove import numpy as np), and import all the functions func1, func2, ..., func6? I don't mind if I have to call them as custom_functions.func1 or more_custom_functions.subfolder1.func3, say, if necessary.
I've tried a number of things such as putting __init__.py in some of the folders and adding __all__ = ["func1", "func2"] into this file (as well as leaving it empty). I've also tried
import sys, os
sys.path.append(os.getcwd() + '\\custom_functions')
import custom_functions

and variations of this like from custom_functions import *, all to no avail.
Some of the errors I get involve:
module 'custom_functions' has no attribute func1, or
name 'custom_functions' is not defined.
In R, I would use something along the lines of source(dir, recursive=TRUE, pattern="*.R") and then library/require all the packages at the very start of the code and all is good. Is there an easy equivalent? Or do I have to move every function into a single file (say functions.py) and then import functions?
Thanks for any help.

A: It seems that there is an intermediate solution that more or less suits my needs, even if it might not be best practice when it comes to Python.
import os
import glob
files_names = glob.glob(os.getcwd() + '\custom_functions\**\*.py')
for f in file_names : exec(open(f).read())

This allows me to use the custom functions without needing to call them as modules, i.e. I can use them like
func1()

instead of
custom_functions.func1()


text:
Q: Showing $\sum_0^n {n\choose k}(-1)^k \frac{1}{2k + 2} = 1/(2n + 2)$ I'm wondering if there is an natural way to see that
$\sum_0^n {n\choose k}(-1)^k \frac{1}{2k + 2} = 1/(2n + 2)$  for $n\gt 0$.
Both sides of the equation are equal to a simple integral Integral of $x(1-x^2)^n$
By "natural" I mean that you would be able to deduce the right hand side without knowing it previously. For example, an induction argument is slightly unnatural since we would have to guess the closed form beforehand.

A: $$\binom nk\frac1{2(k+1)}=\frac12\cdot\frac{n!}{(n-k)!\cdot k!\cdot(k+1)}$$
$$=\frac1{2(n+1)}\cdot\frac{(n+1)!}{[n+1-(k+1)]!\cdot(k+1)!}=\frac1{2n+2}\binom{n+1}{k+1}$$
So, $\displaystyle\sum_{k=0}^n\binom nk(-1)^k\frac1{2k+2}=\frac1{2n+2}\sum_{k=0}^n(-1)^k\binom{n+1}{k+1}$
If $\displaystyle S=\sum_{k=0}^n(-1)^k\binom{n+1}{k+1}=-\sum_{k=0}^n(-1)^{k+1}\binom{n+1}{k+1}$
Setting $k+1=r,$
$$S=-\sum_{r=1}^{n+1}(-1)^r\binom{n+1}r\iff-S=\sum_{r=1}^{n+1}(-1)^r\binom{n+1}r$$
$$-S=\sum_{r=0}^{n+1}(-1)^r\binom{n+1}r-\binom{n+1}0(-1)^0=(1-1)^{n+1}-1$$

A: $$(1+x)^n=\sum_{r=0}^n\binom nrx^r$$
Integrate both sides   to get $$\frac{(1+x)^{n+1}}{n+1} =\sum_{r=0}^n\binom nr\frac{x^{r+1}}{r+1}+K $$ where $K$ is an arbitrary constant
Set $x=0$ in the above identity to determine $K$
Finally set $x=-1$

A: You want to prove
$$\sum_{k=0}^n {n\choose k} \frac{1}{k + 1} (-1)^k= \frac{1}{n + 1}$$
i.e.
$$\sum_{k=0}^n {n\choose k}\frac{n+1}{k + 1} (-1)^k = 1$$
which is
$$\sum_{k=0}^n {n+1\choose k+1}(-1)^k  = 1$$
which is
$$\frac{1}{X}\sum_{k=0}^{n+1} {n+1\choose k+1}X^{k+1}\left.\right|_{X=\,-1}  = 1$$
As
$\ \ (X+Y)^n=\sum_{k=0}^n\binom nk X^{n-k}Y^k\ \ $
we find the left hand side is
$$\frac{1}{X}\left((X+1)^{n+1}-1\right)\left.\right|_{X=\,-1}$$
and that's $1$ indeed.


text:
Q: Квантование и дискретизация + кодировка (по сути: реализация АЦП) Допустим у меня есть массив данных, я его импортирую и строю по нему график. Так теперь задача состоит в том, чтобы этому графику задать шаг дискретизации и заквантовать его по уровню плюсом еще было бы если помогли бы разобраться с кодированием, чтобы мы могли получить как бы цифровой сигнал, главное, чтобы еще  можно было регулировать эти параметры. Об этом я и прошу помощи, встроенные методы matplotlib пробовал, но они ограничены. Код предлагать не буду, т.к. его нету.
В качестве примера возьмите функцию sin x ограниченную на отрезке [0,10].

A: Ну давайте так для начала попробуем:
xmax = 10 #интервал в секундах
x = 0
freq = 100  #частота дискретизации в Гц
ff = 1
xstep = 1 / freq
bits = 16
mult = 1 << (bits - 1)

while x < xmax:
    y = sin(x*ff)
    dig = int(y * mul)
    result.append(dig)
    x += чstep


text:
Q: How I can listen for a keyword in a web browser with Javascript How I can listen for a keyword from web browser and when it catched - do something using JavaScript like it implemented in google search app for android with their "Ok, google"?

A: You can do it with pocketsphinx.js:
https://github.com/syl22-00/pocketsphinx.js
See keyword spotting demo
https://github.com/syl22-00/pocketsphinx.js/blob/master/webapp/live_kws.html


text:
Q: Not generating the Activity and layout files while creating project I am using eclipse kepler version and latest ADT plugin. But when i tried to create an android project it is not creating the blank activity and layout file. I could see the same question asked many times. In all those links the answer is given like Help->install new software-> https://dl-ssl.google.com/android/eclipse/.But when i tried this it is displaying like everything is already installed. So i need a proper solution.I am stuck with it. Please do help me.

A: I got the same problem as you
and I found this

ADT 23.0.4 (October 2014)
Dependencies:
Java 7 or higher is required if you are targeting the L Developer Preview.
Java 1.6 or higher is required if you are targeting other releases.
Eclipse Indigo (Version 3.7.2) or higher is required.
This version of ADT is designed for use with SDK Tools r23.0.2. If you haven't already installed SDK Tools r23.0.2 into your SDK, use the Android SDK Manager to do so.

so...I delete the newest version of SDK Tools 24.0.1
download and install older version SDK Tools r23.0.2
http://dl.google.com/android/installer_r23.0.2-windows.exe
it works for me....


text:
Q: Cant See Print in Celery I just started with Django celery and included in my project
but I cant see the print statements or return statements in my console
i looked here :
Print statement in Celery scheduled task doesn't appear in terminal
simple celery test with Print doesn't go to Terminal
System : Windows, Pycharm , Python3, django 1.9, Celery 4.02, django-celery-beat 1.01
drive/celery.py
from __future__ import absolute_import, unicode_literals
from celery import Celery
from celery.schedules import crontab
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'advocate.local_settings')

app = Celery(
     'drive',
     broker='redis://localhost:6379/0',
     include=['drive.celery_tasks']
)

app.config_from_object('django.conf:settings', namespace='CELERY')

app.conf.beat_schedule = {
    'add-every-minute': {
        'task': 'drive.celery_tasks.add',
        'schedule': crontab(),
    },
}

app.conf.timezone = 'UTC'

# Optional configuration, see the application user guide.
app.conf.update(
    result_expires=3600,
)

if __name__ == '__main__':
    app.start()

drive/celery_tasks.py
from __future__ import absolute_import, unicode_literals
from drive.celery import app
from datetime import datetime

@app.task
def add():
    temp = str(datetime.now())
    print(temp)
    return 2 + 3

Celery Run Command
celery -A drive beat -l info

Display in console
LocalTime -> 2017-07-12 14:07:58
Configuration ->
    . broker -> redis://localhost:6379/0
    . loader -> celery.loaders.app.AppLoader
    . scheduler -> celery.beat.PersistentScheduler
    . db -> celerybeat-schedule
    . logfile -> [stderr]@%INFO
    . maxinterval -> 5.00 minutes (300s)
[2017-07-12 14:07:58,548: INFO/MainProcess] beat: Starting...
[2017-07-12 14:07:59,688: INFO/MainProcess] Scheduler: Sending due task add-every-minute (drive.celery_tasks.add)
[2017-07-12 14:08:00,779: INFO/MainProcess] Scheduler: Sending due task add-every-minute (drive.celery_tasks.add)
[2017-07-12 14:09:00,000: INFO/MainProcess] Scheduler: Sending due task add-every-minute (drive.celery_tasks.add)

When i am starting worker  celery -A drive worker -1 info
 -------------- celery@Mathur v4.0.2 (latentcall)
---- **** -----
--- * ***  * -- Windows-10-10.0.15063-SP0 2017-07-12 14:51:00
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app:         drive:0x351b290
- ** ---------- .> transport:   redis://localhost:6379/0
- ** ---------- .> results:     disabled://
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]
  . drive.celery_tasks.add
  . drive.celery_tasks.weekly_digest_mails

[2017-07-12 14:51:00,403: CRITICAL/MainProcess] Unrecoverable error: AttributeError("Can't pickle local object 'Pool.__init__.
<locals>.Process'",)
Traceback (most recent call last):
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\celery\worker\worker.py", line 203, in start
    self.blueprint.start(self)
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\celery\bootsteps.py", line 119, in start
    step.start(parent)
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\celery\bootsteps.py", line 370, in start
    return self.obj.start()
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\celery\concurrency\base.py", line 131, in start
    self.on_start()
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\celery\concurrency\prefork.py", line 112, in on_st
art
    **self.options)
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\billiard\pool.py", line 1008, in __init__
    self._create_worker_process(i)
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\billiard\pool.py", line 1117, in _create_worker_pr
ocess
    w.start()
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\billiard\process.py", line 122, in start
    self._popen = self._Popen(self)
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\billiard\context.py", line 383, in _Popen
    return Popen(process_obj)
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\billiard\popen_spawn_win32.py", line 79, in __init
__
    reduction.dump(process_obj, to_child)
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\billiard\reduction.py", line 99, in dump
    ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'Pool.__init__.<locals>.Process'

(share) C:\Users\Vaibhav\Desktop\DoSelect\trueshare\advocate>Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\billiard\spawn.py", line 165, in spawn_main
    exitcode = _main(fd)
  File "c:\users\vaibhav\desktop\doselect\trueshare\share\lib\site-packages\billiard\spawn.py", line 207, in _main
    self = pickle.load(from_parent)
EOFError: Ran out of input

A: You need to start a worker also.
celery -A drive worker -l info

If you are using windows, check this


text:
Q: how to run selenium code in regular chrome instead of chromedriver? Here is an examle code to explain my problem.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def test():

    username = "gmail"
    password = "password"

    driver = webdriver.Chrome("C://Users//Dell//Desktop//chromedriver.exe")
    driver.implicitly_wait(15)
    driver.get("http://www.facebook.com")

    elem = driver.find_element_by_name("email")
    elem.send_keys(username)
    elem = driver.find_element_by_name("pass")
    elem.send_keys(password)
    elem.send_keys(Keys.RETURN)

    #code after logging

test()

Whenever i run this code the code run in individual chromedriver window.
I want my code to do someting after logging in facebook.
everytime I redirect to facebook the website ask me to allow notificitions.for that reason the whole screen become black and the only clickable element is the popup. so all the other elements are become unclickable. so i get this error.
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate
element:

If i could run this code in my regular browser in which i already allowed/denied notifications for facebook. the pop up will not raise again and the error will not happen.
how can i run this code in my regular browser?

A: You can simply turn off the notifications pop up using this configuration:
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# config to remove pop ups
opt = Options()
opt.add_argument("--disable-infobars")
opt.add_argument("start-maximized")
opt.add_argument("--disable-extensions")
# you can change the values below. 0 means off and 1 means on.
opt.add_experimental_option("prefs", { \
    "profile.default_content_setting_values.media_stream_mic": 1,
    "profile.default_content_setting_values.media_stream_camera": 0,
    "profile.default_content_setting_values.geolocation": 0,
    "profile.default_content_setting_values.notifications": 1
  })

def test():

    username = "gmail"
    password = "password"

    driver = webdriver.Chrome("C://Users//Dell//Desktop//chromedriver.exe", options=opt)
    driver.implicitly_wait(15)
    driver.get("http://www.facebook.com")

    elem = driver.find_element_by_name("email")
    elem.send_keys(username)
    elem = driver.find_element_by_name("pass")
    elem.send_keys(password)
    elem.send_keys(Keys.RETURN)

    #code after logging

test()

It's a very simple fix you can disable notifications by changing the 1 to a 0.


text:
Q: Computing $\max_{1/2 \leq x \leq 2} ( \min_{1/3 \leq y \leq 1} f(x,y) )$ where $f(x,y) = x(y \log y - y) - y \log x$.
Let $f(x,y)=x(y\ln y-y)-y\ln x.$ Find $\max_{1/2\le x\le 2}(\min_{1/3\le y\le1}f(x,y))$.

This problem is quite easy and it is from Spivak; it is the part $c)$ of the general exercise 2-41 page 43 Calculus on manifolds; here it is:

Let $f:\mathbb{R}\times \mathbb{R}\to \mathbb{R}$ be twice continuously differentiable. For each $x\in \mathbb{R}$ define $g_x(y)=f(x,y)$. Suppose that for each $x$ there is a unique $y$ with $g'_x(y)=0$; let $c(x)$ be this $y$.
$a)$: If $D_{2,2}f(x,y)\ne0$ for all $(x,y)$ show that $c$ is differentiable and $c'(x)=-\frac{D_{2,1}f(x,c(x))}{D_{2,2}f(x,c(x))}$
$b)$: Show that if $c'(x)=0$, then for some $y$ we have $D_{2,1}f(x,y)=0$, $D_2f(x,y)=0$.

I cannot visualize how part c) relates to the previous ones. Can you give me a hint?

A: I have given the complete solution below. The part highlighted shows where we use the result of part (a). In short, we use part (a) to compute the derivative of the critical point of $g_x(y)$ for the given function $f(x,y)$. This is used in computing the critical points to maximise $f(x,y)$ w.r.t. $x$ after minimising it w.r.t. $y$.

Let $f : (0,\infty) \times (0,\infty) \to \mathbb{R}$ be the function given by $$f(x,y) = x(y \log y - y) - y \log x.$$
Clearly $f$ is $C^\infty$. For each $x \in (0,\infty)$ define $g_x : (0,\infty) \to \mathbb{R}$ by
$$g_x(y) = f(x,y).$$
To find points where $g_x$ is minimised, we first find the critical points:
$$
{g_x}'(y) = x\log y - \log x,\\
\therefore {g_x}'(y) = 0 \iff y = x^{1/x}.
$$
So, for each $x \in (0,\infty)$ there is a unique $y \in (0,\infty)$ such that ${g_x}'(y)=0$. So, let $c(x) = x^{1/x}$ be this critical point. To check the nature of this critical point, we evaluate ${g_x}''(c(x))$ and check its sign.
$$
{g_x}''(y) = \frac{x}{y} \implies {g_x}''(c(x)) = \frac{x}{x^{1/x}}.
$$
Hence, ${g_x}''(c(x)) > 0$ for all $x \in (0,\infty)$, so $g_x(y)$ has a global minimum at $y=c(x)$. Therefore, we would like to conclude that
$$
\min_{1/3 \leq y \leq 1} \{ f(x,y) \} = f(x,c(x)) = x \cdot x^{1/x},
$$
but this would be a bit hasty, for it is not necessary that $c(x) \in [1/3,1]$ for all $x \in (0,\infty)$. So, let $\alpha \in (0,\infty)$ be the unique element such that $c(\alpha) = 1/3$. Define $h : (0,\infty) \to \mathbb{R}$ by
$$
h(x) =
\begin{cases}
f(x,1/3), & x \in (0,\alpha);\\
f(x,c(x)), & x \in [\alpha,1];\\
f(x,1), & x \in (1,\infty)
\end{cases}
=
\begin{cases}
-(x(1+\log 3)+\log x)/3, & x \in (0,\alpha);\\
-x \cdot x^{1/x}, & x \in [\alpha,1];\\
-x-\log x, & x \in (1,\infty).
\end{cases}
$$
Then,
$$
\min_{ 1/3 \leq y \leq 1 } \{ f(x,y) \} = h(x).
$$

Now, note that the hypothesis of part (a) of the problem is satisfied, because $D_{2,2} f(x,y) = {g_x}''(y) \neq 0$ for all $x,y \in (0,\infty)$. Hence,
$$
D_{2,1} f(x,y) = \log y - \frac{1}{x},
$$
and
$$
\begin{align}
c'(x) = -\frac{D_{2,1}f(x,c(x))}{D_{2,2}f(x,c(x))}
= \frac{x^{1/x}(1 - \log x)}{x^2}.
\end{align}
$$

To find points where $h$ is maximised, we find its critical points. In the interval $(0,\alpha)$,
$$
h'(x) = -\frac{\left(1+\log 3 + \frac{1}{x}\right)}{3}
$$
which is negative for all $x \in (0,\alpha)$. Hence, $h(x)$ is decreasing on this interval. In the interval $(1,\infty)$,
$$
h'(x) = -1-\frac{1}{x},
$$
which is negative for all $x \in (1,\infty)$. Hence, $h(x)$ is decreasing on this interval as well. In the interval $[\alpha,1]$,
$$
h'(x) = -c(x) - x c'(x) = -c(x)\left( 1 + \frac{1-\log x}{x} \right),
$$
which is negative for all $x \in [\alpha,1]$. Hence, $h$ is decreasing on this interval as well. One can check that $h(x)$ is continuous at $x = \alpha$ and $x = 1$, so $h$ is continuous everywhere, and thus it is decreasing on the entire domain.
Lastly, $c(1/2) = 1/4 < 1/3$, so $1/2 < \alpha$. Therefore, we have
$$
\begin{align}
\max_{1/2 \leq x \leq 2} \left\{ \min_{1/3 \leq y \leq 1} \{ f(x,y)\} \right\} &= \max_{1/2 \leq x \leq 2} \{ h(x) \}\\
&= h(1/2)\\
&= f(1/2,1/3)\\
&= -\frac{\left( 1-\log \frac{3}{4} \right)}{6}.
\end{align}
$$


text:
Q: CSS background gradient with image overlay Just a very quick one I'm having a little trouble with - that is, the ordering of background css elements.
I have the following:
background-color: #3C3E89; /* For browsers that do not support gradients */
background: -webkit-linear-gradient(#3C3E89, #6265E4); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#3C3E89, #6265E4); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#3C3E89, #6265E4); /* For Firefox 3.6 to 15 */
background: linear-gradient(#3C3E89, #6265E4); /* Standard syntax */
background-image: url('../images/logo.png');
background-size: cover;

And for some reason the png - although it has the transparency layer - overrides the linear gradients with which I'd like it to sit on.
I've had a little root around to see what the correct method is for this, tried them, with no luck. I was wondering if anyone had a tried and tested method for overlaying a png on top of a gradient background...
I'm sure everyone will scream at me saying this is a duplicated question - but unless I'm missing something I haven't been able to successfully implement their suggestions.
Update:
I have also tried the following:
background-image:
  -webkit-linear-gradient(#3C3E89, #6265E4), /* For Safari 5.1 to 6.0 */
  -o-linear-gradient(#3C3E89, #6265E4), /* For Opera 11.1 to 12.0 */
  -moz-linear-gradient(#3C3E89, #6265E4), /* For Firefox 3.6 to 15 */
  linear-gradient(#3C3E89, #6265E4), /* Standard HTML Syntax */
  url('../images/logo.png');

And...
background:
  -webkit-linear-gradient(#3C3E89, #6265E4), /* For Safari 5.1 to 6.0 */
  -o-linear-gradient(#3C3E89, #6265E4), /* For Opera 11.1 to 12.0 */
  -moz-linear-gradient(#3C3E89, #6265E4), /* For Firefox 3.6 to 15 */
  linear-gradient(#3C3E89, #6265E4), /* Standard HTML Syntax */
  url('../images/logo.png');

A: You're overriding background by setting background-image. Instead you need to use multiple backgrounds:
background-image: url('../images/logo.png'), linear-gradient(#3C3E89, #6265E4);

According to documentation backgrounds are drawn from closest to most distant. So in your case image should came first to be drawn over gradient.

A: linear gradiant is behaving like background-image as you can use this syntax also :

.content {
  background-image: linear-gradient(#3C3E89, #6265E4);
  height:200px;
}

That's why your CSS rules of background-image is overriding it. Instead you need to specify multiple background like this :

.content {
  height: 200px;
  background: linear-gradient(#3C3E89, rgba(98, 101, 228, 0.21)), url(https://lorempixel.com/200/100/);
}

You should pay attention to order. In my example gradient is above the image because it comes first and i added some opacity to be able to see the image. If you use solid color and/or image without transaparency you will only see the first background.


text:
Q: Данные из POST формы не передаются обработчику Прошу помочь советом.
Логика формы следующая: есть список полей, некоторые из них заблокированы, некоторые - активны для ввода. Пользователь вводит ИНН контрагента, через api dadata подгружаются статистические реквизиты и записываются в value заблокированных полей. Оставшиеся поля пользователь заполняет и отправляет на сервер.
Проблема: записанные через js значения в заблокированные поля - не передаются на сервер.
<form action="ссылка на обработчик" method="post">

                    Введите ИНН контрагента
                    <input type="text" name="inn" id="inn" value="" class="form-control">

                    <button id="submit" class="btn btn-primary" type="button" onClick="getdetails()">ЗАПРОС В ФНС</button>

                    КПП контрагента
                    <input type="text" name="kpp" value="" id="kpp" class="form-control" disabled>

                    Полное наименование клиента
                    <input type="text" name="fullname" value="" id="fullname" class="form-control" disabled>

                    Краткое наименование клиента
                    <input type="text" name="shortname" value="" id="shortname" class="form-control" disabled>

                    ОГРН
                    <input type="text" name="ogrn" value="" id="ogrn" class="form-control" disabled>

                    ОКПО
                    <input type="text" name="okpo" value="" id="okpo" class="form-control" disabled>

                    Юридический адрес
                    <input type="text" name="yur" value="" id="yur" class="form-control" disabled>

                    Фактический адрес
                    <input type="text" name="fact" id="fact" class="form-control">

                    Генеральный директор (или подписант)
                    <input type="text" name="director" id="director" class="form-control">

                    Основание полномочий
                    <input type="text" name="cause" id="cause" class="form-control">

                    Номер договора
                    <input type="text" name="numbercontract" id="numbercontract" class="form-control">

                    Дата договора
                    <input type="data" name="datecontract" id="datecontract" class="form-control">

                    <button type="submit">Отправить</button>

            </form>

запись данных в поля формы происходит через

в обработчике присвоение значений переменных происходит вот так
$fullname = $_POST['fullname'];
$shortname = $_POST['shortname'];
$inn = $_POST['inn'];
$kpp = $_POST['kpp'];
$ogrn = $_POST['ogrn'];
$okpo = $_POST['okpo'];
$director = $_POST['director'];
$cause = $_POST['cause'];
$faddress = $_POST['fact'];
$yaddress = $_POST['yur'];
$ncontract = $_POST['numbercontract'];
$dcontract = $_POST['datecontract'];

После отправки на сервер получаю следующие сообщения
Notice: Undefined index: fullname и так далее


text:
Q: C++ exceptions won't be caught inside Poco::Net::HTTPRequestHandler handleRequest method I am doing a very simple HTTP server program using the Poco::Net library. I have my own RequestHandlersFactory class which produces only MyRequestHandler objects. Inside the overridden 'handleRequest' method of MyRequestHandler I want to use exceptions.
#include <iostream>
#include <filesystem>
#include <fstream>
#include <exception>

#include <Poco/Net/HTTPRequestHandler.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>

using namespace Poco::Net;

class MyRequestHandler final: public Poco::Net::HTTPRequestHandler {
     void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) override {
        try {
            throw std::runtime_error("Exception.");
        } catch (const std::runtime_error &re) {
            std::cout << "Exception caught (1)." << std::endl;
        } catch (const std::exception &e) {
            std::cout << "Exception caught (2)." << std::endl;
        }
    };

public:
    MyRequestHandler() = default;
    ~MyRequestHandler() override = default;
};

For some reason, thrown exception will not be caught inside any of the catch blocks. I have this code for the factory:
#include <Poco/Net/HTTPRequestHandlerFactory.h>

#include "MyRequestHandler.h"

using namespace Poco::Net;

class MyRequestHandlersFactory final : public HTTPRequestHandlerFactory {
    HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) override {
        std::cout << "New request: " << request.getURI() << "." << std::endl;
        return new MyRequestHandler();
    };
public:
    MyRequestHandlersFactory() = default;
    ~MyRequestHandlersFactory() override = default;
};

and this code for the HTTP server:
Poco::Net::HTTPServerParams::Ptr params = new HTTPServerParams;
params->setMaxThreads(20);
params->setMaxQueued(100);
params->setTimeout(1000);

const Poco::Net::SocketAddress address(std::string("0.0.0.0:") + std::to_string(port));
const Poco::Net::ServerSocket socket(address);
const MyRequestHandlersFactory::Ptr factory = new MyRequestHandlersFactory();

Poco::Net::HTTPServer server(factory, socket, params);
server.start();
std::cout << "Endpoint is started on the address " << address << "." << std::endl;

while(true)
    std::this_thread::sleep_for(std::chrono::seconds(3));

I am using an apple silicone laptop with the default toolchain of this version:

g++ --version:
Apple clang version 13.1.6 (clang-1316.0.21.2.5)
Target: arm64-apple-darwin21.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

And a simple CakeLists file to build my project:
cmake_minimum_required(VERSION 3.23)
project(HTTPServer)

find_package(Poco REQUIRED COMPONENTS Foundation Net Util)
set(CMAKE_CXX_STANDARD 20)

add_executable(HTTPServer main.cpp MyServerApplication.cpp MyServerApplication.h MyRequestHandlersFactory.cpp MyRequestHandlersFactory.h MyRequestHandler.cpp MyRequestHandler.h)
target_link_libraries(HTTPServer Poco::Foundation Poco::Net Poco::Util

Any suggestions will be much appreciated


text:
Q: RBAC Policy Action Rule definition for excluding the URLS from policy I have below two policy in my Values.yaml file. By default in policy one(USER_POLICY) I am allowing all the end point so i  have just defined my context root(/v2/trans/brokerage/external) and allowed all http method. but out of it i just want exclude the endpoint(/v2/trans/brokerage/external/conditions) which comes under my SUPPORT_POLICY. how to exclude the endpoints specified in one policy with another Policy.
 rules:
        action: ALLOW
        policies:
          USER_POLICY:
            principals:
              - header: { name: "roles", contains_match: "ADMIN_ACCOUNT" }
            permissions:
              - and_rules:
                  rules:
                    - header: { name: ":path", prefix_match: "/v2/trans/brokerage/external" }
                    - or_rules:
                        rules:
                          - header: { name: ":method", exact_match: "GET" }
                          - header: { name: ":method", exact_match: "POST" }
                          - header: { name: ":method", exact_match: "PATCH" }
                          - header: { name: ":method", exact_match: "DELETE" }
Some syntax to exclude : /v2/trans/brk/ext/conditions

        SUPPORT_POLICY:
            principals:
              - header: { name: "roles", contains_match: "SUPPORT" }
            permissions:
              - and_rules:
                  rules:
                    - url_path: { path: { prefix: "/v2/trans/brk/ext/conditions" } }
                    - or_rules:
                        rules:
                          - header: { name: ":method", exact_match: "GET" }
                          - header: { name: ":method", exact_match: "POST" }


text:
Q: How do ionizing and non-ionizing radiation interact with each other? Given an ionizing radiation $ X $ and given non-ionizing radiation $ Y $, how does this radiation 2 interact with each other?
For example I have X-rays (ionizing radiations) and Microwaves (non-ionizing radiations), I want to understand if there are models that explain how they can interact and what is needed for these 2 radiation classes to interact with each other?
What is the common ground?

A: The categories of ionizing and non-ionizing aren't particularly relevant here. They refer to whether or not the radiation can ionize atoms, which aren't present in your scenario. Microwaves and x-rays do not actually have qualitatively different properties from one another, in and of themselves.
Classically, microwaves and x-rays are electromagnetic waves, and Maxwell's equations are linear, so electromagnetic waves don't interact at all. In most real-world contexts, that's basically the whole story.
Quantum-mechanically, there is photon-photon scattering. Note that a scattering between a microwave photon and an x-ray photon can be made into a symmetric scattering problem by switching into the center of mass frame.
Extending this to all types of radiation is much too broad a question for this site. That would essentially mean giving you an entire course in quantum field theory.

A: When electromagnetic waves of any nature pass or meet one another I believe there is the potential for constructive and destructive interference. While this is technically not an "interaction" between waves, which @Ben Crowell pointed out has a specific meaning with respect to electromagnetic waves, I assumed you used the term "interaction" as generally defined in the dictionary being "mutual or reciprocal action or influence" (Webster). If that's not what you meant, please let me know.
Once they pass they generally resume their original form in the absence of any dispersive medium. I would think that the degree of potential interference would depend on how similar the wavelengths are, the closer they are the greater the degree. To that extent, I wouldn't think microwave and x-rays, far apart in wavelength, would involve much if any interference.
That being said, I think of greater interest is how different types of electromagnetic waves interact with matter, particularly regarding ionizing vs non ionizing radiation and human tissue. For a good overview on the interaction of electromagnetic radiation and matter, I recommend you check out the following link:
http://hyperphysics.phy-astr.gsu.edu/hbase/mod3.html
Hope this helps.


text:
Q: Range in message box..? One more question -> i want to show the range content in an message box, how can i do it?
Let's say there are new portfolios:1) ABC, 2)XYZ, 3)GHI in an range....when i use below code i am getting no. of portfolios as 3 but i actually want the names of them
MsgBox "New Portfolios found : " & vbNewLine & Sheets("Macro").Range("T2:T25").Row


text:
Q: How to change primary group? I have a user like this:
uid=501(ironsand) gid=500(foo) groups=500(foo),10(wheel),497(git),501(ironsand)

And to change primary group to ironsand like gid=501(ironsand), I typed this command:
sudo usermod -g ironsand ironsand

It changed groups order but didn't change main group like:
uid=501(ironsand) gid=500(foo) groups=501(ironsand),10(wheel),497(git),500(foo)

I thought someone already asked a question like this, but I couldn't find one.
How can I change primary group?

A: Usually you do it like the following.
To assign a primary group to an user:
$ usermod -g primarygroupname username

To assign secondary groups to a user (-a keeps already existing secondary groups intact otherwise they'll be removed):
$ usermod -a -G secondarygroupname username

From man-page:
...
-g (primary group assigned to the users)
-G (Other groups the user belongs to)
-a (Add the user to the supplementary group(s))
...


text:
Q: Laplace transform - Heaviside algebra I'm strugling with some algebra around a laplace transform with heaviside. The start function is
$L(2tH(1-t)) + L(2H(t-1))$
so from this, I'm supposed to convert it to
$L(2t) + L(2(1-t)H(t-1))$
From that I understand how you continue, but dont see how they get there.
PS: First question ever, so how important is it to write the math with code? I feel I'm getting the point through, even without coding it :)
PSS: The assignment is 6e on this link
Where I have it from!
if someone wants.
Maybe if someone could explain why
$L(f(t)u(a-t)) = L(f(t) - u(t-a)f(t))$
some light would be shed on the first question :)


text:
Q: How can I resolve "Not all control paths return a value" error for integer I have the error "Not all control paths return a value". I've seen it before and have been able to resolve it for a simple bool return value. This is a bit different and  seems to be a challenge for me since it has a for-loop and at the same time returns integers. Please see my code below:
int ArrowedCandleIndex  () {

      for (int i=0; i<NumBars; i++)
      {
         double dnArrow = iCustom(Symbol(),Period(),ARROWS_SIGNAL_NAME,ARROWS_SIGNAL_BUFFER_DN,i);
         double upArrow = iCustom(Symbol(),Period(),ARROWS_SIGNAL_NAME,ARROWS_SIGNAL_BUFFER_UP,i);

         if ((dnArrow!=EMPTY_VALUE) && (DoubleToStr(dnArrow,Digits()) != "0.00000"))  {

            currentArrowedCandleIndex = NumBars;

            return currentArrowedCandleIndex;
            }
         if ((upArrow!=EMPTY_VALUE) && (DoubleToStr(upArrow,Digits()) != "0.00000"))  {
            currentArrowedCandleIndex = NumBars;

            return currentArrowedCandleIndex;
            }
      }
  }

How can I resolve this issue?

A:
Q : "How can I resolve this  (  "Not all control paths return a value" ) issue?"

int ArrowedCandleIndex  () {

      for ( int i = 0; i <  NumBars; i++ )
      {
         ...
         if (  (  EMPTY_VALUE != dnArrow )
            && ( "0.00000"    != DoubleToStr( dnArrow, Digits() ) )
               ) {
                 ...
                 return currentArrowedCandleIndex; // ------------ JIT/RET--(a)
         }

         if (  (  EMPTY_VALUE != upArrow )
            && ( "0.00000"    != DoubleToStr( upArrow, Digits() ) )
               ) {
                 ...
                 return currentArrowedCandleIndex; // ------------ JIT/RET--(b)
            }
      }
      return EMPTY_VALUE; // ------------------------------------- JIT/RET--(c)
  }


text:
Q: Есть ли возможность работать с проектом в PhpStorm сразу на удалённом компьютере по ssh соединению? Мне достаточно проблематично скачивать проекты с удалённого хостинга. Могу ли я настроить PhpStorm для работы сразу с удалённого компьютера по ssh ?

A: Если я Вас правильно понял, то это то что Вам нужно: Running SSH Terminal
Или это: Editing Individual Files on Remote Hosts


text:
Q: cmake and osx frameworks not found I m making some experiments dealing with C++, Android JNIs and the JavaScriptCore framework provided by OSX platforms.
I'm having some troubles while using cmake to load the JavascriptCore framework. It seems that its not able to find it...
I'm having the following code in my cmakelist:
find_library(JSCORE JavaScriptCore)
if (NOT JSCORE)
    MESSAGE(ERROR ": Framework JSCore not found")
endif()

and I'm always passing in it.
I don't know why and I suspect a path problem.
Does anybody know or have some suggestion so that I can load the JSCore framework inside my C++ lib?
Thanks for your help

A: Configuring the following project allows to successfully find the library. Would you have a complete example to share ?
cmake_minimum_required(VERSION 3.10)

project(Test)

find_library(JSCORE_LIBRARY JavaScriptCore)
if(NOT JSCORE_LIBRARY)
    MESSAGE(FATAL_ERROR "Framework JSCore not found")
endif()
message(STATUS "JSCORE_LIBRARY: ${JSCORE_LIBRARY}")

Output:
$ /Volumes/Dashboards/Support/CMake-3.12.0.app/Contents/bin/cmake ../
-- The C compiler identification is AppleClang 8.0.0.8000042
-- The CXX compiler identification is AppleClang 8.0.0.8000042
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works
-- [...]
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- JSCORE_LIBRARY: /System/Library/Frameworks/JavaScriptCore.framework
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/test/bld


text:
Q: how to write pretty URLs without htaccess file in php Pretty URLs without htaccess
I want to write pretty URL like : http://yousite.com/member/1/ instead of http://yousite.com/index.php?page=member&id=1 But i did with htaccess file and now i want to do this without htaccess file because sometimes you don't have permission to edit htaccess file on server.

A: If you have an Apache server and AcceptPathInfo is enabled, then you can just use links like /index.php/nice/looking/url.
The "index.php" in the middle of the URL might look a little strange, but I don't think it's possible to have it look better without .htaccess
Else, you could ask your hoster to redirect any URL to /index.php so that you can handle URL rewriting without having /index.php in your URL.
Then you can just use a regex match to detect what file to include.
preg_match('@[/]{1}([a-zA-Z0-9]+)@', $_SERVER["PATH_INFO"], $matches) ($matches will contain all "parts" of the url in an array)
Be careful with including the files, use a whitelist so you're sure nobody would be able to load internal files.

A: Actually you can create a new folder dynamically for each member with a simple index file inside that includes your front controller, but even if it's possible, you probably don't want to do that, and instead want to change your host.

A: I might have this Single Line of Code inside index.php page if i don't want to use .htaccess.
Pseudo code: Get the ID and Redirect the user
Short Explanation : Concat the id that you got in the url and redirect to your desired location with that id
Real Code
header('Location: http://yousite.com/member/'.$_GET['id'].'/');


text:
Q: Fundamental Group of $\mathbb{RP}^n$ not using Van Kampen I am trying to calculate the fundamental group of $\mathbb{RP}^n$ without using the Van Kampen Theorem. My basic idea consists of the following: First of all, $\mathbb{RP}^1\simeq S^1$ and thus, the fundamental group for $n=1$ is just $\mathbb {Z}$.
For $n\geq 2$ I have thought of the following covering map: $ p:S^n\to S^n/_{x\sim-x}\simeq \mathbb{RP}^n,\ x\mapsto [x]$. This is obviously continuous and surjective. Furthermore, $S^n\simeq \mathbb{RP}^n\times \{x,-x\}$. Thus, this map should be a covering.
Now we look at the function $\phi: \pi_1(\mathbb{RP^n},x_0)\to p^{-1}(x_0)=\{x_0,-x_0\},\ [w]\mapsto L(w,x_0)(1)$ where $w$ is a loop in $\mathbb{RP}^n$ and $L$ is the lift of $w$. Now, it is known that $\phi$ is well-defined and bijective. Now we know that $p^{-1}(x_0)\simeq \mathbb{Z}_2$. Thus, in order to prove that the fundamental group of $\mathbb{RP}^n$ is indeed $\mathbb{Z}_2$, we need to show that $\phi$ is a group homomorphism. This is where I am struggling at. Could someone help me?

A: We will proof that $\pi_1(\mathbb{R}\mathbb{P}^n) \tilde{=} \mathbb{Z}$ for $n = 1$ and $\pi_1(\mathbb{R}\mathbb{P}^n) \tilde{=} \mathbb{Z} / 2 \mathbb{Z}$ for $n \geq 2$:
To establish the assertion for $n=1$, we show that $S^1 / \sim$ is homeomorphic to $S^1$. Thereby, we think of $S^1$ as a subset of $\mathbb{C}$. Let $\psi : S^1 \to S^1$ be the map $\psi(z) := z^2$. Clearly, $\psi$ is continuous and surjective. We have
\begin{equation}
z \sim w \iff \psi(z) = \psi(w).
\end{equation}
Thus there is a bijection $\tilde{\psi} : S^1/\sim \to S^1$, such that $\psi = \tilde{\psi} \circ p_1$. Since $S^1 / \sim$ is endowed with the final topology, $\tilde{\psi}$ is continuous. Since $S^1 / \sim$ is compact and $S^1$ is Hausdorff, $\tilde{\psi}$ is a homeomorphism.
To treat the case $n \geq 2$ we are going to analyse the fundamental group $\pi_1(S^n/ \sim)$ using a covering given by the space $S^n$ and covering projection $p_n$. We get this covering the following way:
For $n \geq 2$ we define $\sim \subseteq S^n \times S^n$ be the equivalence relation
\begin{equation}
x \sim y :\iff (x=y \lor x = -y)
\end{equation}
and let $p_n : S^n \to S^n / \sim$ be the canonical projection. Let $S^n / \sim$ be endowed with the final topology $\mathcal{V}$ induced by $\lbrace p_n \rbrace$. Then $(S^n , \mathcal{T}_n, p_n)$ is a covering of $(S^n/\sim, \mathcal{V})$.
To start with, let us fix notation. Set $x_0 := (1,0, \ldots, 0) / \sim \in S^n / \sim$, which will be used as base point and set $\tilde{x_0} := (1,0, \ldots, 0)$. For a loop $f \in L(S^n / \sim, x_0)$ denote by $\tilde{f}$ the lifting of $f$ with initial point $\tilde{x_0}$.
Now we use that the covering $p_n : S^n \to S^n / \sim$ is 2-fold. For every loop $f \in L(S^n / \sim, x_0)$ the terminal point of a lifting $\tilde{f}$ belongs to the two-element set $\lbrace \tilde{x_0}, - \tilde{x_0}\rbrace$. Now we use that $S^n$ is simply connected. If $f,g \in L(S^n / \sim, x_0)$ with $\tilde{f}(1)= \tilde{g}(1)$, then $\tilde{f} \sim \tilde{g}$ and hence $f \sim g$. We conclude that $\pi_1(S^n/ \sim)$ has at most two elements.
Let $1_{x_0}$ be the constant path at $x_0$. Its lifting $\tilde{1_{x_0}}$ clearly is the constant path at $\tilde{x_0}$. If $f$ is a loop with $f \sim 1_{x_0}$, then by the monodromy theorem $\tilde{f}(1) =\tilde{x_0}$. In order to show that $\pi_1(S^n/\sim) \neq \lbrace 1 \rbrace$, it is thus sufficient to find one loop $f$ with $\tilde{f}(1) \neq \tilde{x_0}$.
Consider the path $\tilde{f} : [0,1] \to S^n$ given as $\tilde{f}(t) := (\cos(\pi t), \sin(\pi t), 0, \ldots, 0)$ for $t \in [0,1]$. Then $\tilde{f}(0) = \tilde{x_0}$ and $\tilde{f}(1) = - \tilde{x_0}$. Pushing $\tilde{f}$ to $S^n / \sim$ gives a loop with base point $x_0$: $f(t) := (p_n \circ \tilde{f})(t) = (\cos(\pi t), \sin(\pi t), 0, \ldots, 0)/ \sim$ for $t \in [0,1]$.
By definition $\tilde{f}$ is the lifting of $f$.
To conclude the proof, note that up to ismorphism there is only one group with two elements, namely $\mathbb{Z} / 2 \mathbb{Z}$.


text:
Q: How to use Wamp Server database url in Android I want to save the username and password in a database, but the app is unfortunately closed. I can't understand what url is used in the java file and how make the url of the Wamp server database.
Please explain this and solve.
Thanks For your Suggestion in advance.
  09-15 07:51:34.866: E/WindowManager(3370): android.view.WindowLeaked:
  Activity com.example.mysqltest.Register has leaked window
  com.android.internal.policy.impl.PhoneWindow$DecorView{b2d949b8 V.E.....
   R.....ID 0,0-304,96} that was originally added here
   09-15 07:51:34.866: E/WindowManager(3370):   at
   android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)

   09-15 07:51:34.866: E/WindowManager(3370):   at
  android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
    09-15 07:51:34.866: E/WindowManager(3370):  at
    android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
  09-15 07:51:34.866: E/WindowManager(3370):    at
  android.app.Dialog.show(Dialog.java:286)
    09-15 07:51:34.866: E/WindowManager(3370):  at
   com.example.mysqltest.Register$CreateUser.onPreExecute(Register.java:86)
   09-15 07:51:34.866: E/WindowManager(3370):   at
    android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
      09-15 07:51:34.866: E/WindowManager(3370):    at
    android.os.AsyncTask.execute(AsyncTask.java:535)
   09-15 07:51:34.866: E/WindowManager(3370):   at
   com.example.mysqltest.Register.onClick(Register.java:68)
  09-15 07:51:34.866: E/WindowManager(3370):    at
  android.view.View.performClick(View.java:4438)
  09-15 07:51:34.866: E/WindowManager(3370):    at
  android.view.View$PerformClick.run(View.java:18422)
   09-15 07:51:34.866: E/WindowManager(3370):   at
    android.os.Handler.handleCallback(Handler.java:733)
  09-15 07:51:34.866: E/WindowManager(3370):    at
  android.os.Handler.dispatchMessage(Handler.java:95)
   09-15 07:51:34.866: E/WindowManager(3370):   at
  android.os.Looper.loop(Looper.java:136)
   09-15 07:51:34.866: E/WindowManager(3370):   at
  android.app.ActivityThread.main(ActivityThread.java:5017)
      09-15 07:51:34.866: E/WindowManager(3370):    at
     java.lang.reflect.Method.invokeNative(Native Method)
      09-15 07:51:34.866: E/WindowManager(3370):    at
      java.lang.reflect.Method.invoke(Method.java:515)
       09-15 07:51:34.866: E/WindowManager(3370):   at

  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
 09-15 07:51:34.866: E/WindowManager(3370):     at
 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
 09-15 07:51:34.866: E/WindowManager(3370):     at
  dalvik.system.NativeStart.main(Native Method)

A: It's not recommended to access mysql database directly from android app. You can create a simple web service with php and then call to that service
with a HTTP Client.


text:
Q: Using mail to with parameters is it possible to set the address of a mailto to the selected value of a drop down list?
Something like: param1 = dropdownlist1.selectedvalue
    Send Email

I can't think of how to get the param1 to work on an .aspx page.

A: if you want to send on single click
then you have to work like this
<a href="mailto:'<%=string.format("param1")%>'?subject=mail">Send Email

typo error may there.


text:
Q: Displaying lines from a randomly opened text file I cant seem to figure out whats wrong. I want to read from a random .txt file when the button 'Next' is pressed, then display the string contained in the array allLines[] at index 3. It only seems to print that index of that file and not randomly select another another file to read from. This is just a small program to help me study, using flash cards. I guess there might be one i could download, but any ideas?
namespace MSU_Flash_Cards
{
public partial class Form1 : Form
{
    DirectoryInfo di = new DirectoryInfo("C:\\Users\\Public\\cards\\");
    Random rand = new Random ();

    int cardside;
    int filecount;
    int fileindex;
    string[] filename;

    string[] allLines;
    // allLines[0] is for Card Name
    // allLines[1] is for Card Description
    // allLines[2] is for Card Front
    // allLines[3] is for Card Back

    public Form1()
    {
        InitializeComponent();
        cardside = 0;
    }
    private void btnNewCardSave_Click(object sender, EventArgs e)
    {
        int x = 0;
        //store the text in the text boxes in an array
        string[] s_temp = new String[4];
        s_temp[0] = txtboxNewCardName.Text.ToString();
        s_temp[1] = txtboxNewCardDesc.Text.ToString();
        s_temp[2] = txtboxNewCardFront.Text.ToString();
        s_temp[3] = txtboxNewCardBack.Text.ToString();
        StreamWriter sw = new StreamWriter(string.Format("C:\\Users\\Public\\cards\\{0}.txt", s_temp[0])); // s_temp[0] is used here to define the file name to use.

        while (x <= 3)
        {
            //write each segment of the array to a file, lines from 0-3
            sw.WriteLine(s_temp[x].ToString());
            x++;
        }
        sw.Close();
    }
    private void btnNext_Click(object sender, EventArgs e)
    {
        // Randomly get the next card
        SetNextCard();
        // Display the next cards 'back'
        txtboxCard.Text = string.Format("{0}", allLines[3]);
    }
    private void btnFlip_Click(object sender, EventArgs e)
    {
        if (cardside == 0)
        {
            // if the front is showing, switch to the back
            txtboxCard.Text = string.Format("{0}", allLines[3]);
            cardside = 1;
        }
        else
        {
            // if the back is listed, switch to the front
            txtboxCard.Text = string.Format("{0}", allLines[2]);
            cardside = 0;
        }
    }
    private void SetNextCard()
    {
        int x = 0;

        // Check the directory for files & count them
        FileInfo[] rgFiles = di.GetFiles("*.*");
        filecount = di.GetFiles().Length;

        // Create a new array based on the filecount
        filename = new String[filecount];

        // Save each file name in the array
        foreach (FileInfo fi in rgFiles)
        {
            filename[x] = fi.FullName;
            x++;
        }

        // Select randomly a file for reading
        fileindex = rand.Next(0, filecount);

        // Read each line of the file and assign to a global array for use later
        allLines = File.ReadAllLines(string.Format("{0}", filename));

        }
    }
}

A: You set the value of fileindex, but never use it. You probably want to change the last line to:
allLines = File.ReadAllLines(filename[fileindex]);

Also, there doesn't seem to be any reason why fileindex should be a field and not a local variable.

A: You're not indexing into your filename array, the index is missing.
allLines = File.ReadAllLines(filename[fileindex]);

A: You're not indexing into your filename array when you try to read a file, so it can't find the file you want to open. Replace your last line
allLines = File.ReadAllLines(string.Format("{0}", filename));

with
allLines = File.ReadAllLines(filename[fileindex]);

to read the selected file.


text:
Q: Number theory problem, 3rd degree diophantine equation How many positive integers are there that can be written in the form
$$\frac{m^3+n^3}{m^2+n^2+m+n+1}$$
where $m$ and $n$ are positive integers.
I invented this problem and was stuck with it for a long time. It is really interesting to know if there is a solution for this problem.

A: A few lines of code trying the first 5000 numbers will give you those answers up to changing order between $m$ and $n$, let $f(m,n) = \frac{m^3 + n^3}{m^2+n^2+m+n+1}$:
$f(1,2) = 1; \qquad f(182,379) = 341; \qquad f(664,4286) = 4200; \qquad f(692, 3847) = 3747$
$f(961,1712) = 1531; \qquad f(996,692) = 896; \qquad f(1112, 270) = 1064$
$f(1712, 961) = 1513; \qquad f(2778,3210) = 3024$
Surely there are more but maybe you could try to find a pattern or see something in common?
As too whether it's interesting, well it's number theory. Fermat's Theorem is hugely famous and Andrew Wiles spent about 5 years to initially find a flawed proof which has then been corrected and yet it has no application whatsoever.
So I guess the interesting bit is purely mental, not practical (or at least not yet).

A: For fixed $n\ge 1$ we can sometimes solve the question as follows. Write
$$
\frac{m^3+n^3}{m^2+m+n^2+n+1}=(m-1) -\frac{(n^2+n)m-(n^3+n^2+n+1)}{m^2+m+(n^2+n+1)}.
$$
The LHS is an integer, if and only if the last fraction on the RHS is an integer. However, for fixed $n$, the denominator grows quadratically, and the nominator only linearly in $m$. For $m$ big enough, the fraction will not be an integer. For small $n$ this works, e.g., say for $n=1$ we have
$$
\frac{m^3+1}{m^2+m+3}=(m-1) -\frac{2m-4}{m^2+m+3},
$$
where the last fraction is an integer if and only if $m=2$. For $n=2$ we obtain
the fraction $\frac{6m-15}{m^2+m+7}$ which is an integer if and only if $m=1$, etc. In general, of course, this still leaves finitely many possible solutions for $m$, if $n$ is fixed, and we have not answered the question.


text:
Q: Getting ZONE_RESOURCE_POOL_EXHAUSTED I'm using Google App Engine Flexible and some kind of rolling restart happened last night and my instance failed right after.
Looking at logs, I see this on new instance creation:
ZONE_RESOURCE_POOL_EXHAUSTED
This appears to be related to this:
https://status.cloud.google.com/incident/compute/18012
But the status shows fixed and I'm still having issues.


text:
Q: C++ Abstract Class error on Constructor in Qt 5 I'm creating a simple abstract class named Asset, the header code looks like this:
#ifndef ASSET_H
#define ASSET_H

#include <QString>
#include <QDate>

class Asset
{
public:
    Asset(QString des, QDate dat);
    ~Asset();
    virtual QString toString();
    virtual double value();
    QString getDescription();

private:
    QString description;

protected:
    QDate date;
};

#endif // ASSET_H

This is what my implementation file looks like:
#include "asset.h"

Asset::Asset(QString des, QDate dat)
{
    description = des;
    date = dat;
}

QString Asset::getDescription()
{
    return description;
}

The error code I'm getting on the implementation constructor is: undefined reference to vtable for Asset
What am I doing wrong here?

A: The methods you do not implement in the abstract class, should be pure virtual methods. That mean they should be followed by = 0.
For example:
virtual double value() = 0;

This tells the compiler that this is a pure virtual method. For an explanation of the difference between virtual methods and pure virtual methods, take a look at this Stackoverflow answer: C++ Virtual/Pure Virtual Explained
On a side note. When you have an abstract class, you should really make sure that your destructor is virtual. Always use virtual destructors in C++ when you deal with class that you intend to be inherited from.
In your class design you have a private member called description, and a public function to get the description that is not virtual. You have no methods to set the description, perhaps you should consider moving the description member variable from private to protected or perhaps even creating a mutator function to set it.


text:
Q: Minimal ARM (low-power) circuit design I know there are tons of these questions here, and I looked at them, but I still feel unsure about some things.
I've never designed anything using a MCU - for this one I mostly followed the recommended circuits from datasheets. My main question is about the power distribution - sometimes people use many caps, sometimes none, why? Why is the ground supposed to be on VSS pins decoupled with a cap to VDD(+3V3)?

It costs 100$ to buy and ship some of the parts to my country, and I can't risk it... so if you catch anything else wrong please tell me.

A: There is few unclear point to me :

*

*There is no pull up resistor on the SPI bus line. I know it's not mandatory but some chip require it.

*3.3v is connected to VSS through capacitor C9? (It may not be a mistake but I'm curious)

A little advice when you edit a schematic : try to keep GND head down and input voltage head up (the arrow to the top). It make the schematic clearer

A: It's not obvious from your schematic because the pins are scrambled but the Vdd-connected pins are distributed around the chip outline. It's better to have a bypass capacitor near each pin if they are separated by much distance. You might want to look at eval boards for this series of chips to see what others have done- I see one with 7 caps mostly 1uF and a 100n.
You can consider placing on the opposite side of the board. It's less critical if you have full ground and power planes.
Be sure to read the data sheet thoroughly and consider each and every pin- one thing I notice is that Vddusb is recommended to be connected to Vdd. I don't see a connection to the RF_RESET port in your schematic. Vbat should probably be connected to Vdd and a few other pins look like they need attention, but I don't think anyone here is going to check these things as carefully as you should.

A: C9 is wrong. It should decouple Vcc but there should be direct connection between uC & Vcc

simulate this circuit – Schematic created using CircuitLab


text:
Q: Gradle Disable Ant Logs I am triggering the jasper report compilation from my gradle build plugin
target.ant {
                    logging.captureStandardOutput LogLevel.WARN
                    taskdef(name: 'jrc', classname: "net.sf.jasperreports.ant.JRAntCompileTask", classpath:target.configurations.jasperreports.asPath)
                    jasperTargetDir.mkdirs()
                    jrc(srcdir: "${target.projectDir}/src/main/resources/META-INF/report-designs", destdir: jasperTargetDir) {
                        classpath(path: target.sourceSets.main.output.classesDir)
                        include(name:'**/*.jrxml')
                    }
                }

This task creates lot of verbose log out put which I need to disable.
I tried adding the below line - but it was not helpful
logging.captureStandardOutput LogLevel.WARN
While creating the taskdef for ant , is it possible to control the log level ?


text:
Q: How to inherit css animations? I have 2 div's. div a and div b. I used jquery .append() to parent div b to div a. How can I make div b inherit all of div a's css animations?

A: Use this:
$('div').css($(this).parent().css());

A: Assign your animations to a CSS class name and give each of your two objects the same class name.  Then, they don't even have to be parent/child relationship to both inherit the exact same CSS animations.