text:
Q: Spring MVC Returns Response Before Completion of Controller Method I have the following method which is returning an incorrect response to the browser before the method is even complete. This is in Spring 3.2.
@RequestMapping(value="/process1/createEditContract/validate", method=RequestMethod.POST)
public @ResponseBody StatusResponse validateProcess1(@ModelAttribute("contractEditForm") @Valid Process1CreateEditContractDTO dto, BindingResult bindingResult) {

    StatusResponse response = new StatusResponse();
    response.setSuccess(true);
    if (bindingResult.hasErrors()) {
        log.debug("Errors found. Processing status response");
        response.setSuccess(false);
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fe: fieldErrors) {
            response.getMessages().add(messageSource.getMessage(fe, null));
        }

    }

    return response;
}

StatusResponse is a simple object that a javascript function in the JSP reads to generate a Javascript alert stating whether the action was successful or errors occurred. The method makes it all the way through, but as soon as it tries to write the response, I get this:
java.net.SocketException: Software caused connection abort: socket write error

I've been stuck for a day now, any help would be appreciated.
UPDATE
I rolled back from Spring 3.2 to Spring 3.1, and the wording of the error message changed enough to give me more information.
Basically, I'm getting now seeing this:
IllegalStateException: Response already committed

What I don't see is what is causing the response to commit so quickly. Maybe a conflict with the OpenSessionInViewFilter?

A: This error can occur when the local network system aborts a connection, such as when WinSock closes an established connection after data retransmission fails (receiver never acknowledges data sent on a datastream socket).". See this MSDN article. See also Some information about 'Software caused connection abort.
To prove which component fails I would monitor the TCP/IP communication using wireshark and look who is actaully closing the port, also timeouts could be relevant.

A: The javascript runs in browser, and your controller runs on server. You cannot pass a complex object from the controller to the javascript without converting it  to a textual format such as xml or json.
So you should :

*

*choose a format (say json)

*add a produces="application/json" in your RequestMapping annotation

*do generate json in your controller method


text:
Q: How to write an SQL query for this use case? Suppose I've got a table with three fields: event_name, event_timestamp event_result. Each row is an occurrence of an event event_name occurred at event_timestamp with some event_result. For example:
 event_name | event_timestamp  | event_result
 -------------------------------------------
 event_a    | 2018-04-29 00:00 | result_x1
 event_a    | 2018-04-29 00:00 | result_x2
 event_b    | 2018-04-29 00:00 | result_x1
 event_a    | 2018-04-29 00:00 | result_x3
 event_b    | 2018-04-29 00:00 | result_x3

Now I need a SQL query to select rows with the latest event_timestamp for every event_name within given range of event_timestamp.
How would you write such a query ? I guess it should be standard SQL that works with any reasonable SQL database.

A: Use subquery :
select *
from table t
where event_timestamp = (select max(event_timestamp)
                         from table
                         where event_name = t.event_name);

And, in general the most effective method is to use ranking functions (if support)
select * from (
      select *,
             row_number() over (partition by event_name order by event_timestamp desc) Seq
      from table t
      where  event_timestamp between @start and @end
) t
where Seq = 1;

A: The most portable solution would probably be something like:
SELECT    E.*
FROM      Event E
INNER JOIN (
             SELECT  event_name
             ,       MAX(event_timestamp) MAX_DT
             FROM    Event
             WHERE   event_timestamp <= @SomeDate
                  AND event_timestamp > @SomeOtherDate
             GROUP BY event_name
           ) MAXED
        ON MAXED.event_name = E.event_name
        AND MAXED.MAX_DT = E.event_timestamp

A: Something like:
SELECT event_name
    ,MAX(event_timestamp)
FROM myTable
WHERE event_timestamp BETWEEN date1
        AND date2
GROUP BY event_name

A: you can use group by and include the max event_timestamp
In MSSQL:
select
event_name
, MAX(event_timestamp)
from [table_name]
where event_timestamp between '2018-04-20' and '2018-04-30'
group by event_name

A: SELECT * FROM `your_table`
WHERE `event_timestamp` BETWEEN 'your_start_range'AND 'your_end_range'
GROUP BY `event_name`
ORDER BY `event_timestamp` DESC
LIMIT 1;

A: this code work for ms sql
SELECT *
FROM
    (SELECT
        *, ROW_NUMBER() OVER(PARTITION BY event_name ORDER BY event_timestamp DESC) AS row_no
     FROM    Event
     WHERE
        event_timestamp BETWEEN @BeginDate AND @EndDate) as tbl
WHERE row_no = 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to solve this equations in modular arithmetic? $6247x \equiv 1139 \pmod{9461}$
$6247x \equiv 1139 \pmod{9461}$, where $9461$ is a prime number

I just started learning modular equations and I have no idea how to solve this advanced questions.

A: I will show the method step by step for a much easier example :
$$33x\equiv 41\mod 101$$
$$101=3\cdot 33+2$$
$$33=16\cdot 2+1$$
$$2=2\cdot 1+0$$
Therefore, $gcd(33,101)=1$ and the extended algorithm gives
$$1=33-16\cdot 2=33-16\cdot (101-3\cdot 33)=49\cdot 33-16\cdot 101$$
Therefore $33^{-1}=49$ in $\mathbb Z_{101}$
So, the solution is $$x=41\cdot 49=2009\equiv 90\mod 101$$
If you get a negative number $a$ , you can choose $p+a$ instead to get a positive solution. (Here $p=101$ , so if the result would have been $-40$, we could have used $-40+101=61$ instead).
The modulus $p$ need not be a prime number. The method works always , if the $gcd$ is $1$.


text:
Q: What is the optimum precision to use in an arithmetic encoder? I've implemented an arithmetic coder here - https://github.com/danieleades/arithmetic-coding
i'm struggling to understand a general way to choose an optimal number of bits for representing integers within the encoder. I'm using a model where probabilities are represented as rationals.
I know that to prevent underflows/overflows, the number of bits used to represent integers within the encoder/decoder must be at least 2 bits greater than the maximum number of bits used to represent the denominator of the probabilities.
for example, if i use a maximum of 10 bits to represent the denominator of the probabilities, then to ensure the encoding/decoding works, i need to use at least MAX_DENOMINATOR_BITS + 2 = 12 bits to represent the integers.
If i was to use 32bit integers to store these values, I would have another 10 bits up my sleeve (right?).
I've seen a couple of examples that use 12 bits for integers, and 8 bits for probabilities, with a 32bit integer type. Is this somehow optimal, or is this just a fairly generic choice?
I've found that increasing the precision above the minimum improves the compression ratio slightly (but it saturates quickly). Given that increasing the precision improves compression, what is the optimum choice? Should I simply aim to maximise the number of bits i use to represent the integers for a given denominator? Performance is a non-goal for my application, in case that's a consideration.
Is it possible to quantify the benefit of moving to say, a 64bit internal representation to provide a greater number of precision bits?
I've based my implementation on this (excellent) article - https://marknelson.us/posts/2014/10/19/data-compression-with-arithmetic-coding.html


text:
Q: How do i get camera view region latitude and longitude and also user direction of camera view in android Hi I am new to android application development. I need to develop an application from following Scenario:

*

*Firstly i need to get direction(like north,south,east,west) of user camera viewing direction.

*Secondly how to i calculate camera view region/area

*Thirdly how do i get filter the  latitude and longitude of camera view region only

If you didn't get my question, I attached the image for your understanding

I do not have any idea of this. Please any one help to develop the application.
Thanks in Advance

A: For step 1:
You need a kind of a compass to show the user the direction:
http://sunil-android.blogspot.com/2013/02/create-our-android-compass.html
For step 2: You need to do some mathematical calculations.
For step 3:
You have to get the  latitude and longitude of the current location of where you capture the image:
Implement your class like: implements LocationListener
LocationManager mLocationManager;

mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(location != null) {
            lat = location.getLatitude();
            lng = location.getLongitude();
            getWeatherInfo();
        }
        else {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            Toast.makeText(ClimateInfo.this,"GPS / Internet not available, please check the connections and retry!",Toast.LENGTH_LONG).show();
        }

@Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
            lat = location.getLatitude();
            lng = location.getLongitude();
        }

    }


text:
Q: Serve static files with jax.ws I'm building a web front end to monitor the state of a SOAP service.
Is there any way to serve static files with jax.ws? For example Endpoint.publish("/static", new SomeStaticFileHandler()) where any requests to /static just serve the corresponding static file in my folder? Inside the static file I would like to query the state and update the page with AJAX calls.
Thanks!

A: The correct way to serve static files is to add a custom servlet to the web.xml.
As for the hack you want to try: serve any file type, with any content-type? It will not work, I believe. Perhaps you can serve XML files if they follow a predefined schema -- JAX-WS implementation classes return objects, not strings or streams. These objects are serialized to SOAP/XML using the schema and binding. You'd need to parse the files into objects and then return to JAX-WS runtime... and you'll get a SOAP envelope over the file content anyway.

Inside the static file I would like to
  query the state and update the page
  with AJAX calls

This doesn't sound like a static file to me. This is a dynamic method serving XML or JSON. The simplest answer is still a servlet.
JAX-RS (RESTful Java API) is a viable alternative too.


text:
Q: fail2ban error. can´t ban with lighttpd-auth today I installed fail2ban in my ubuntu-server.
After this i had to add the following .conf I got at fail2ban on githunb:
/etc/config/filter.d/lighttpd.conf
# Fail2Ban filter to match wrong passwords as notified by lighttpd's auth Module
#

[Definition]

failregex = ^: \(http_auth\.c\.\d+\) (password doesn\'t match .* username: .*|digest: auth failed for .*: wrong password|get_password failed), IP: <HOST>\s*$

ignoreregex =

# Author: Francois Boulogne <fboulogne@april.org>

After this I added the following lines to my Jail.conf:
[lighttpd-auth]

enabled = false
filter  = lighttpd-auth
action  = iptables[name=lighttpd-auth, port="http,https"]
# adapt the following two items as needed
logpath = /var/log/lighttpd/error.log
maxretry = 2

And now I have the following problem, fail2ban can find the wrong logins, but can´t ban the attacker IP -.-
Here the lines from my file2ban.log
2013-11-05 18:23:24,710 fail2ban.actions.action: ERROR  iptables -N fail2ban-lighttpd-auth
iptables -A fail2ban-lighttpd-auth -j RETURN
iptables -I INPUT -p tcp --dport http,https -j fail2ban-lighttpd-auth returned 200
2013-11-05 18:23:59,747 fail2ban.actions: WARNING [lighttpd-auth] Ban 9.999.999.99
2013-11-05 18:23:59,750 fail2ban.actions.action: ERROR  iptables -n -L INPUT | grep -q fail2ban-lighttpd-auth returned 100
2013-11-05 18:23:59,750 fail2ban.actions.action: ERROR  Invariant check failed. Trying to restore a sane environment
2013-11-05 18:23:59,756 fail2ban.actions.action: ERROR  iptables -N fail2ban-lighttpd-auth
iptables -A fail2ban-lighttpd-auth -j RETURN
iptables -I INPUT -p tcp --dport http,https -j fail2ban-lighttpd-auth returned 200
2013-11-05 18:23:59,758 fail2ban.actions.action: ERROR  iptables -n -L INPUT | grep -q fail2ban-lighttpd-auth returned 100
2013-11-05 18:23:59,758 fail2ban.actions.action: CRITICAL Unable to restore environment
2013-11-05 18:24:01,760 fail2ban.actions: WARNING [lighttpd-auth] 9.999.999.99 already banned
2013-11-05 18:24:02,762 fail2ban.actions: WARNING [lighttpd-auth] 9.999.999.99 already banned
2013-11-05 18:24:04,764 fail2ban.actions: WARNING [lighttpd-auth] 9.999.999.99 already banned

Can anyone help me?

A: The reason is that fail2ban is calling iptables wrong.
The -dport http,https option does not work with two ports. It gives:
iptables v1.4.20: invalid port/service `http,https' specified.

The correct call would be
iptables [...] -m multiport -dports "http,https" [...]

Modify your fail2ban configuration so that it uses the correct call.  Here it works like this:
action  = iptables[name=lighttpd-auth, m=multiport ports="http,https"]


text:
Q: Cassandra: Is Linux and Windows compatible? At the moment, I am using a Cassandra database on a Windows 7 system. We'd like to use Cassandra on Linux now and wonder if it's possible to migrate the data with a simple copy of the data directory from Windows to Linux?
Can someone tell me if that's possible, meaning if the Windows data structure on the file system and Linux file structure are compatible?
If not, what'ts the best way to migrate a keyspace or the whole database from Windows to Linux?

A: The storage format does not change between windows and linux, in theory copying the sstables over should work but not testing it would be a tragic mistake as I don't know if anyone has ever done it before. Test it out throughly! but it should work as far as I know. (ensure that token ranges match up or you will lose data)
Couple other options:

*

*Just replace windows hosts with linux ones, one at a time (or if wanna be aggressive 1 per replicas). Then let bootstrapping process manage it.

*If you want you can add a new DC with linux nodes, increase replication to include it in it (make sure app is using LOCAL_QUORUM not QUORUM and set to your Windows DC as local) then switch app to use other DC after repair, but beware of potential consistency issues during the switch. To avoid issues with consistencies at cost of a bit more complexity, do writes at EACH_QUORUM and dont do switch until youve completed a repair cycle to cover all things written to just the one DC. then switch, then remove the Windows DC and decomission.


text:
Q: I'm not able to run test case using selenium + cucumber + java Guys could you please take a look in my project and let me know why it's ignoring the test cases? it's saying undefined and ignored... I already set the glue and feature path but it doesn't run.... I tried fix many times but didn't worked....
Follow the link project to download:
https://drive.google.com/file/d/1dFERFX-kw0ST4qzYUKXDK3tzM6kWxqEL/view?usp=sharing
Thanks


text:
Q: Is the intersection of two arbitrary subsets of a $\sigma$- Algebra a $\sigma$- Algebra over one of the subsets? Let $(\Omega, \mathfrak F)$ be a measure field and $Y \in \mathfrak F$.
I am trying to find out, if the set $\mathfrak L:= \{X \cap Y : X \in F \}$ spans a $\sigma$-Algebra over $Y$.
I am trying to prove these three axioms but I am already doubting that $\mathfrak L$ is a $\sigma$-Algebra, because I can't prove a).
(a) $\Omega \in \mathscr{F}$;
(b) if $A_{1}, A_{2}, \ldots \in \mathcal{F}$ then $\bigcup_{i=1}^{\infty} A_{i} \in \mathcal{F}$;
(c) if $A \in \mathcal{F}$ then $A^{\mathrm{c}} \in \mathcal{F}$.
Any help is much appreciated.


text:
Q: RedisTemplate multi thread not work, why and how to fix? I want to use RedisTemplate, more specific StringRedisTemplate in Junit used with multi thread, but it fails. And if I use only test thread, it work. Why? Isn't StringRedisTemplate thread safe? How to fix that?
@Test
void multiThreadStringRedisTemplate(@Autowired RedisConnectionFactory redisConnectionFactory){
        Runnable runnable = () -> {
            StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(redisConnectionFactory);
            for(int i = 0;i < 50;++i){
                String value = stringRedisTemplate.opsForValue().get("ok");
                System.out.println(i + ":" + value);
            }
        };
        // multi thread not work
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0;i < 1;++i){
            executorService.execute(runnable);
        }
        // runnable.run(); this work fine
    }

I try to use spring's RedisTemplate in multi thread, but not work. The test process just exit with 0 without any exception info.
pom's dependency and properties.yml as:
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>lettuce-core</artifactId>
                    <groupId>io.lettuce</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
    </dependencies>

I've enabled the connection poll with default configuration.
spring:
  redis:
    host: ${romote_host}
    port: 6379
    password: ${password}
    database: 0
    connect-timeout: 3000ms
    jedis:
      pool:
        enabled: true

A: You need to wait for other threads in your executor service to do their work. I think adding this snippet at the end of your test would suffice
taskExecutor.shutdown();
try {
  taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
  ...
}


text:
Q: Open popup when someone clicks on an image/button Basically, I want to create a popup (that collects emails) that appears when someone clicks on an image that acts like a button.
I've placed the following in footer.php (I've replaced my uuid and lid with "xxxx" for privacy considerations:

Next, I tried to make an image of a download button act as a button that, when clicked, opens the popup. I hoped to do that by adding id="open-popup" (again replaced link with "xxxx"):

But it only opens the popup the first time I load the page and click on the image. When I close the popup and click on the image again the popup isn't loaded.
Any ideas?

A: Instead of using document.getElementById
Try writing your img tag using onClick to call the function


text:
Q: Reference variable to a pointer int main() {

    int x=10;
    int *p=&x;
    int &y =*p;

    cout<< x << endl << &x <<endl;
    cout<< *p << endl << p <<endl;
    cout<< y << endl << &y <<endl;

    p++;
   *p = 20;

   cout<< x << endl << &x <<endl;
   cout<< *p << endl << p <<endl;
   cout<< y <<endl<< &y <<endl;

   return 0;
}

Above is the code which would best explain my question. Normally, a variable reference (&) takes the address of a variable and starts referring to the same. I have tried doing the same through a pointer. I have defined a variable, pointer p points to x and a reference variable y refers to *p. Would this mean that y refers to the same variable x now?
As the next step, I stopped pointing to x through *p, what happens to reference variable y now? What would it hold.
In the code above, cout<

Can someone help explain the behavior here.

A: [note: this answer is only about C++. In C, your code shouldn't compile.]
Yes, after you initialize y, it refers to x. Incrementing p doesn't change that -- y still refers to x.
Unfortunately, when you do the p++; *p=20;, you've modified p so it no longer refers to any allocated storage. When you write to it, you get undefined behavior. That means it's perfectly reasonable for the program to halt (or do essentially anything else).
Note, however, that incrementing p is entirely allowable--in this respect, x acts like an array of one element, and forming a pointer to one past the last element of an array is explicitly allowed. It's only when you write to the address that pointer refers to that you get the undefined behavior. (That is: p++; is fine; *p=20; is not).

A: int &y =*p;

is valid in C++. But in C, it is not valid and would give you compile time error.

Would this mean that y refers to the same variable x now?

In C++, yes. But on incrementing p, it is no longer pointing to the variable x but at some un-allocated memory location. Writing to this location invokes undefined behavior. Now anything could happen.

A: There are no reference types in C. The addressof operator is not the same is declaring a reference in C++.
This will not compile in C:
int main()
{
    int j = 0;
    int& i = j;
}

When you do this:
p++;
*p = 20; // undefined behavior

p no longer points to valid memory. You must allocate memory for a pointer to point to.
In C++, if you modify y, it will modify *p.
#include <iostream>

int main()
{
    int x=10;
    int *p=&x;
    int &y =*p; // y becomes a reference to x
    y = 20;
    std::cout << y << " " << *p << " " << x;
}

A: This will give you the behaviour you were expecting
p = new int;
*p = 20;
y = *p;

The reference is assinged to one int - x . It doesn't know that you mean the one that p points to. It only knows that you wanted it to refer to the one p pointed to when you assigned to the reference.

A: Remember that references in C++ are nothing more or less than pointers in disguise. Thus, your code
int x=10;
int *p=&x;
int &y =*p;

cout<< y <<endl<< &y <<endl;
p++;
*p = 20;
cout<< y <<endl<< &y <<endl;

is entirely equivalent to
int x=10;
int *p=&x;
int *y = &*p;

cout<< *y <<endl<< &*y <<endl;
p++;
*p = 20;
cout<< *y <<endl<< &*y <<endl;

Now, what would you expect this code to print? You neither modified y nor the value it points to, so both print statements will output the same thing.

Note
I left the &*y combination in the transformed code for clarity of how I transformed the code. Of course, &*y is equivalent to y, so a more easy to read, equivalent version would be:
int x=10;
int *p=&x;
int *y = p;

cout<< *y <<endl<< y <<endl;
p++;
*p = 20;
cout<< *y <<endl<< y <<endl;

Aside
In C, &*y is always the same as y, in C++ this does not need to be the case. It is in the example above. However, if y were of a type that overloads operator * (smart pointers do this), &*y is not equivalent to y. In the case of a smart pointer, &*y would return a naked pointer to the object the smart pointer pretents to point to.


text:
Q: Symfony2 + Doctrine2: Is it possible to interact with validation annotations within an Entity setter? I have an Entity which i have decorated using validation annotations like this:
use Symfony\Component\Validator\Constraints as Assert;

class Entity
{
    /**
     * @Assert\MaxLength(100)
     */
    protected $property;
    ...
}

Within the setter for $property i want to know if validation was successful of the annotation when a form is submitted. If validation is successful (or not) i will perform other operations in PHP that is not available via the annotations.
Is this possible? i.e.:
...
function setProperty($value)
{
    if(annotation_validation_passed_when_form_submitted)
    {
        $value = do_something($value);
    }
    $this->property = $value;
}
...

A: You can add an EventListener to your FormBuilder to listen for the FormEvents::BIND event. You can either do this in its own class or just in the form builder itself. I'll show an example of the latter because it's faster.
$builder->addEventListener(FormEvents::BIND, function($event) {
        $data = $event->getData();

        $comment = $data->getComment();
        $comment = $comment . $comment;
        $data->setComment($comment);
});

Of course replace the logic with your own.


text:
Q: Why nginx won't work with base64 image in AJAX request (Laravel, Javascript, Nginx) All other AJAX requests (signIn, SignUp, basicInformation, educationDetail etc) successfully done, but when I upload profile picture (base64) and send to laravel controller then nginx server doesn't work and return error...
I don't know where I missed something..
I increase upload file size and also increase buffer size but all time response same.
Please help me ...
Cropped Image function in .js
 jQuery('.cropped_image').on('click', function (ev) {
    $image_crop.croppie('result', {
            type: 'canvas',
            size: 'viewport'
    }).then(function (response) {
        if(response != "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAYAAACI7Fo9AAAGBElEQVR4Xu3TAQEAAAjCMO1f2h5+NmDIjiNA4L3Avk8oIAECY+iegEBAwNADJYtIwND9AIGAgKEHShaRgKH7AQIBAUMPlCwiAUP3AwQCAoYeKFlEAobuBwgEBAw9ULKIBAzdDxAICBh6oGQRCRi6HyAQEDD0QMkiEjB0P0AgIGDogZJFJGDofoBAQMDQAyWLSMDQ/QCBgIChB0oWkYCh+wECAQFDD5QsIgFD9wMEAgKGHihZRAKG7gcIBAQMPVCyiAQM3Q8QCAgYeqBkEQkYuh8gEBAw9EDJIhIwdD9AICBg6IGSRSRg6H6AQEDA0AMli0jA0P0AgYCAoQdKFpGAofsBAgEBQw+ULCIBQ/cDBAIChh4oWUQChu4HCAQEDD1QsogEDN0PEAgIGHqgZBEJGLofIBAQMPRAySISMHQ/QCAgYOiBkkUkYOh+gEBAwNADJYtIwND9AIGAgKEHShaRgKH7AQIBAUMPlCwiAUP3AwQCAoYeKFlEAobuBwgEBAw9ULKIBAzdDxAICBh6oGQRCRi6HyAQEDD0QMkiEjB0P0AgIGDogZJFJGDofoBAQMDQAyWLSMDQ/QCBgIChB0oWkYCh+wECAQFDD5QsIgFD9wMEAgKGHihZRAKG7gcIBAQMPVCyiAQM3Q8QCAgYeqBkEQkYuh8gEBAw9EDJIhIwdD9AICBg6IGSRSRg6H6AQEDA0AMli0jA0P0AgYCAoQdKFpGAofsBAgEBQw+ULCIBQ/cDBAIChh4oWUQChu4HCAQEDD1QsogEDN0PEAgIGHqgZBEJGLofIBAQMPRAySISMHQ/QCAgYOiBkkUkYOh+gEBAwNADJYtIwND9AIGAgKEHShaRgKH7AQIBAUMPlCwiAUP3AwQCAoYeKFlEAobuBwgEBAw9ULKIBAzdDxAICBh6oGQRCRi6HyAQEDD0QMkiEjB0P0AgIGDogZJFJGDofoBAQMDQAyWLSMDQ/QCBgIChB0oWkYCh+wECAQFDD5QsIgFD9wMEAgKGHihZRAKG7gcIBAQMPVCyiAQM3Q8QCAgYeqBkEQkYuh8gEBAw9EDJIhIwdD9AICBg6IGSRSRg6H6AQEDA0AMli0jA0P0AgYCAoQdKFpGAofsBAgEBQw+ULCIBQ/cDBAIChh4oWUQChu4HCAQEDD1QsogEDN0PEAgIGHqgZBEJGLofIBAQMPRAySISMHQ/QCAgYOiBkkUkYOh+gEBAwNADJYtIwND9AIGAgKEHShaRgKH7AQIBAUMPlCwiAUP3AwQCAoYeKFlEAobuBwgEBAw9ULKIBAzdDxAICBh6oGQRCRi6HyAQEDD0QMkiEjB0P0AgIGDogZJFJGDofoBAQMDQAyWLSMDQ/QCBgIChB0oWkYCh+wECAQFDD5QsIgFD9wMEAgKGHihZRAKG7gcIBAQMPVCyiAQM3Q8QCAgYeqBkEQkYuh8gEBAw9EDJIhIwdD9AICBg6IGSRSRg6H6AQEDA0AMli0jA0P0AgYCAoQdKFpGAofsBAgEBQw+ULCIBQ/cDBAIChh4oWUQChu4HCAQEDD1QsogEDN0PEAgIGHqgZBEJGLofIBAQMPRAySISMHQ/QCAgYOiBkkUkYOh+gEBAwNADJYtIwND9AIGAgKEHShaRgKH7AQIBAUMPlCwiAUP3AwQCAoYeKFlEAobuBwgEBAw9ULKIBAzdDxAICBh6oGQRCRi6HyAQEDD0QMkiEjB0P0AgIGDogZJFJGDofoBAQMDQAyWLSMDQ/QCBgIChB0oWkYCh+wECAQFDD5QsIgFD9wMEAgKGHihZRAKG7gcIBAQMPVCyiAQM3Q8QCAgYeqBkEQkYuh8gEBAw9EDJIhIwdD9AICBg6IGSRSRg6H6AQEDA0AMli0jA0P0AgYCAoQdKFpGAofsBAgEBQw+ULCIBQ/cDBAIChh4oWUQChu4HCAQEDD1QsogEDN0PEAgIGHqgZBEJGLofIBAQMPRAySISMHQ/QCAgYOiBkkUkYOh+gEBAwNADJYtIwND9AIGAgKEHShaRgKH7AQIBAUMPlCwiAUP3AwQCAoYeKFlEAgcm/gD7Dx6GVAAAAABJRU5ErkJggg=="){
            html = '<img id="croped-image-source" src="' + response + '" />';
            jQuery("#cropped-image-preview-section").html(html);
            profilePictureTemp = response;
            isPicSet = true;
            let data = new FormData();
            data.append('profile_picture',response);
            jQuery.ajax({
                method: "POST",
                url: "/imag-store",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                headers: {
                    'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')},
                beforeSend: function () {
                    jQuery('#btn_submit').addClass('hidden');
                    jQuery('#loaderClass').removeClass('hidden');
                    console.log("Before Sending");
                },
                success: function (response) {
                    console.log('success');
                    console.log(response);

                },
                error: function (jqXHR, exception) {
                    var msg = '';
                    if (jqXHR.status === 0) {
                        msg = 'Not connect.\n Verify Network.';
                    } else if (jqXHR.status == 404) {
                        msg = 'Requested page not found. [404]';
                    } else if (jqXHR.status == 500) {
                        msg = 'Internal Server Error [500].';
                    } else if (exception === 'parsererror') {
                        msg = 'Requested JSON parse failed.';
                    } else if (exception === 'timeout') {
                        msg = 'Time out error.';
                    } else if (exception === 'abort') {
                        msg = 'Ajax request aborted.';
                    } else {
                        msg = 'Uncaught Error.\n' + jqXHR.responseText;
                    }
                    jQuery('#btn_submit').removeClass('hidden');
                    jQuery('#loaderClass').addClass('hidden');
                    console.log(msg);
                }

            });
        }

    });
});

web.php
Route::post('/imag-store','ExpertInfoController@storeProfilePicture');

ExpertInfoController.php
 public function storeProfilePicture(Request $request){
$data = $request->get('experts_profile_picture');
if(substr($data, 11, strpos($data, ';')-11) == "png"){
  $data = str_replace('data:image/png;base64,', '', $data);
 $data = str_replace(' ', '+', $data);
 $filename = 'experts_img'
               .rand()
                .'_'.time()
              .".png";

   $year = date("Y");
    $month = date("m");
    $path = PUBLIC_PATH_TO_STORE_IMAGE.'/images/experts/'.$year.'/'.$month.'';
     echo "Now entering create";
     echo ($path);

     $file = self::makeDirectory($path,0777,true,true);
      $file_path = $path.'/'.$filename;
      file_put_contents($file_path,base64_decode($data));
      $pic = str_replace(PUBLIC_PATH_TO_STORE_IMAGE,'',$file_path);
        }
        else{
            $pic = $request->get('experts_profile_picture');
        }
  $info = new ExpertInfo;
 $info->experts_profile_picture = $pic;
$info->save();
}

helloexperts.conf
server {
        client_max_body_size 20m;

        listen       80;

        server_name  helloexperts.dev;

        root        /var/www/vhosts/helloexperts.com/httpdocs/html/public;

        add_header X-Frame-Options "SAMEORIGIN";
         add_header X-XSS-Protection "1; mode=block";
        add_header X-Content-Type-Options "nosniff";
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        try_files $uri $uri/ /index.php$is_args$args;
        #try_files $uri $uri/ /index.php?$query_string;
        root         /var/www/vhosts/helloexperts.com/httpdocs/html/public;
        }
        index  index.php index.html index.htm;
        charset utf-8;

        location = /favicon.ico { access_log off; log_not_found off; }
        location = /robots.txt  { access_log off; log_not_found off; }
#       #add_header 'Access-Control-Allow-Origin' '*';

  error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
location ~ \.php$ {
         root         /var/www/vhosts/helloexperts.com/httpdocs/html/public;
        try_files $uri =404;
        fastcgi_param REMOTE_ADDR $http_x_real_ip;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;

        #client_header_buffer_size 64k;
        #large_client_header_buffers 4 64k;

       fastcgi_buffer_size 128k;
            fastcgi_buffers 256 16k;
            fastcgi_busy_buffers_size 256k;
            fastcgi_temp_file_write_size 256k;

        fastcgi_param PHP_VALUE "upload_max_filesize = 20M \n post_max_size = 20M";
         add_header 'Access-Control-Allow-Origin' '*';
        include        fastcgi_params;
# add_header 'Access-Control-Allow-Origin' '*';
    }
 location ~ /\.(?!well-known).* {
        deny all;
    }

A: Can you confirm the route by doing

php artisan route::list

. if the route does not exist try these commands .
php artisan cache:clear

php artisan route:cache

hope it helps. cheers!
Update i see the issue is in your code.you can use the following code to get the image from input . (i assume thats what you are trying to do)
$base64img = $request->input('image');

        if($base64img){
            // get the base-64 from data
            $file = substr($base64img, strpos($base64img ,",")+1);

            // decode base64 string
            $image = base64_decode($file);

            $pos = strpos($base64img, ';');
            $imageType = explode('/', substr($base64img, 0, $pos))[1];


text:
Q: getting the index of starting and ending 1 of a binary list having a sequence of 0s or 1s I have a python list with binary information having either a sequence of 1s or a sequence of 0s for example:
event = [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1]

How can I store the index values of the starting 1 and ending 1?
For example:
if event = [0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1] then result = [2,5,8,11]
EDIT2 i realised that result should ideally be result_start=[2,8] result_end=[5,11], like lazyr solution, this way we understand where just a single 1 located. eg. event=[0,0,1,1,0,1], would yield a wrong list for the last 1. Thanks for trying all!
EDIT1: I need the index of the first and the last 1 but first to the last 1.
I tried to code it like the following:
k=False
j=0
result=[]
for i in event:
   if i==1:
       k=True
       result.append(k)
   else:
       k=False

A: event = [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1,
    1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1]
from itertools import izip_longest

def pair_iterator(event):
    event = [0] + event
    return enumerate(izip_longest(event, event[1:], fillvalue=0), -1)

def one_ranges(event):
    start = [i + 1 for i, pair in pair_iterator(event) if pair == (0, 1)]
    end = [i for i, pair in pair_iterator(event) if pair == (1, 0)]
    return zip(start, end)

print one_ranges(event)

EDIT:
Also find range that starts at index 0.
Created one_ranges function which returns a list of (start, end) tuples.

A: As I see what you really wanted you can do something like this:
result = []
is_one = False
for i in range(len(event)):
    if not is_one and event[i] == 1: #Starting chain of ones
        is_one = True
        result.append(i)
    elif is_one and event[i] == 0: #Finished a chain of ones
        is_one = False
        result.append(i-1)
if is_one: #The list finished with a chain of ones
    result.append(len(event)-1)

A: >>> event = [0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1]
>>> event = [0] + event + [0]
>>> [i-1 for i in xrange(1,len(event)-1) if event[i]==1 and (event[i+1]==0 or event[i-1]==0)]
[2, 5, 8, 11]

We prepend and append the list to ensure we find the corner case of ones at start and/or end of list.


text:
Q: How to find the following number using modular arithmetic Suppose I have a number $x$ such that,
$$
x \equiv 31^{29}  \text{ (mod 57)}
$$
How can I find $x$ using properties of modular arithmetic. Will it involve a special theorem?

A: Here is one solution. By the Chinese Remainder Theorem, one reduces to solving the same equation mod 3 and mod 19, as we can patch those together at the end.
Mod 3: the easy case
$$31^{29} = 1^{29} = 1$$
Mod 19: just a long chain of combining small groups of multiplications and reducing mod 19 as frequently as possible to keep the arithmetic easy
$$31^{29} = 31^{11} = 12^{11} = 12*(12)^{2*5} = 12*(144)^5 = 12*(11)^5= 12*11*(11)^4$$
$$=12*11*(121)^2 = 12*11*7^2 = 12*11*49 = 12*11*11 = 12*7 = 84 = 8$$
So altogether the solution is congruent to 1 mod 3 and 8 mod 19, which we see lifts to 46 mod 57 (as usual for the CRT, just start with one solution, 8 mod 19, and add multiples of 19 until it is congruent to 1 mod 3).
Sometimes there are tricks to speed things up but these numbers look sort of "random" to me.


text:
Q: McAfee download warning message I have two sites both on different server, both sites having same source code but having different urls.
I am generating report in XLS formate, when i tried to download this report one site showing warning message but second working perfectly.
Both sites having the same code written in Classic ASP.
one site working fine for xsl file download but second showing error message.
Screen shot:-Warning message from McAfee
Thanks


text:
Q: I'm trying to see if the first two or three numbers in the "code" variable is in the dictionary, and if it is found it returns the key for that number    code=("569010002151")
    countrycode = {
        "Norway": 70,
        "Denmark": 57,
        "Sweden": 73,
        "Finland": 64,
        "Iceland": 569
        }

    value = (int(code[0:2]) or int(code[0:3]))

    def country(code):
        for k,v in countrycode.items():
            if v == value:
                print("The code is from", k)
                break
            else:
                print("Code not valid")

    (country(code))

The preferred output with this "code" string would be The code is from Iceland
I have found that if I remove "or int(code[0:3])" the code seems to work somewhat, but then the Iceland countrycode does not work.
Any help would be greatly appreciated.

A: You are using an or expression. When the values in or are integers then the following rule applies

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Hence the value of the value variable is 56 and it won't match with Iceland.
You can change the code to the following
def country(code):
    for k,v in countrycode.items():
        if v == int(code[0:2]) or v == int(code[0:3]):
            print("The code is from", k)
            break
        else:
            print("Code not valid")

A: You can use in operator, for example:
countrycode = {
    "Norway": 70,
    "Denmark": 57,
    "Sweden": 73,
    "Finland": 64,
    "Iceland": 569,
}

def country(code):
    for k, v in countrycode.items():
        if str(v) in code[:3]:
            return k
    return "<Not Found>"

print("The code is from", country("569010002151"))
print("The code is from", country("73123"))

Prints:
The code is from Iceland
The code is from Sweden

A: I'm assuming this is Python?
The first thing to improve is to define the country codes as strings instead of ints. Strings are used when comparing patterns vs its which Are used for math operations. That will look like:
  countrycode = {
      "Norway": "70",
      "Denmark": "57",
      "Sweden": "73",
      "Finland": "64",
      "Iceland": "569"
 }

Next, you don't really need 'value'. And it's note going to work the way you expect anyways. The reason it works of you remove the statement after 'or' is because 'or' is actually a logical operator. It actually will evaluate to 'True' or 'False'.
Next, you can probably remove the function declaration in this case since it's only used once and it's being called immediately after. The loop looks ok but instead of comparing equality to value, use the 'in' operator. This checks that a string is contained in another. The entire script will look like this:
 code=("569010002151")
 countrycode = {
      "Norway": "70",
      "Denmark": "57",
      "Sweden": "73",
      "Finland": "64",
      "Iceland": "569"
   }

    for k,v in countrycode.items():
        if v in code[0:3]
            print("The code is from", k)
            break
        else:
            print("Code not valid")

Sorry for the formatting. I'm on mobile…


text:
Q: Protractor not waiting for login redirect before continuing tests in AngularJS, any suggestion? I have a standard username/password/submit button form, when the user clicks on the button the form submits with ng-submit="login.submit()" which does the login and on success redirects to the main page using ui.router ($state.go("main")).
The following test fails:
  describe("login", function() {
    beforeEach(function() {
      var email = element(by.model("login.email"));
      email.clear().sendKeys("mail");

      var password =  element(by.model("login.password"));
      password.clear().sendKeys("pass");

      var submit = element(by.id("submit"));
      submit.click();
    });

    it("should be able to login", function() {
      expect(element(by.css(".loginPage")).isPresent()).toBe(false);
      expect(element(by.css(".mainPage")).isPresent()).toBe(true);
    });
  });

and if I try to add wait times around, I can see that the browser stays on the login page the whole time (after clicking on the button) - then I get a timeout.
After a successful login the browser receives a cookie with a token for authenticating each following request.
EDIT: with some tinkering I found out where it fails..
function login(email, pass) {
  alert("it gets here");
  return _auth.post({ username: email, password: pass }).then(function(data) {
    alert("does not get here");
    console.log("loginok, token:" +$browser.cookies().apiToken); //this should be the received token
    return data;
  });
}

EDIT2: the Auth service
var _auth = Restangular.withConfig(function(Configurer) {
  Configurer.setBaseUrl("/");
}).service("auth/simple");

return {
  login: login,
};

function login(email, pass) {
  return _auth.post({ username: email, password: pass });
}

Manually everything works as expected.

A: @JoMendez's answer was very close but didn't work in my case. Used @DaveGray's here.
Had to wrap the isPresent() call in a function.
browser.wait(function() {
  return element(by.css('.mainPage')).isPresent();
});

A: Try this:
it("should be able to login", function() {

  browser.wait(element(by.css(".mainPage")).isPresent);//this is different from sleep, this will stop the excecution of all the protractor code that is after it, until the element is present, but it won't prevent the application of loading or if is redirecting, it will keep working.

  expect(element(by.css(".loginPage")).isPresent()).toBe(false);
  expect(element(by.css(".mainPage")).isPresent()).toBe(true);
});

});


text:
Q: Error during PayPal Express Checkout Integration in Sandbox I am using React for implementing PayPal Express Checkout. I have implemented it using react-paypal-express-checkout
Now the app is in Sandbox mode. Here I could place the button and it will open the login popup while clicking on the button.
After logged in I couldn't  verify the transaction from the PayPal. It only shows a "Return to Merchant" button in the window as shown below (window titled as please try again).

Don't know what is the problem. But when I am giving a different Client ID from PayPal's sample code, it works perfectly.
Don't know why my Client ID is not working ?
Any help will be appreciated

A: Actually the issue was with my app Client ID. Don't know why
I have generated a new app and client ID for this. Now it is working perfectly.


text:
Q: How to create a Pop up box on laravel I want to create a popup box which will be load after website full loading. I want show some notice or advertisement to user by this pop up box which will be auto appear after web loading. So how do i do this?

A: This is majorly a frontend task. So, Id do it in the following way:

*

*Use laravel to render the page i want to display the popup

*On the blade view of the page I will use html, css and javascript to structure, style and show the pop up when the page loads.

This link might provide you more information: https://websolutionstuff.com/post/how-to-add-bootstrap-modal-in-laravel?ref=morioh.com&utm_source=morioh.com


text:
Q: PyQGIS. Field calculator based on the rank of another field I am trying to make a script to calculate a field "rank" [RANK] based on the feature rank in another field "population" [POP]. My current script can found below. In this script, I created a new field "RANK".
The idea is that the city with the highest number of people will have the highest number in the field [RANK], namely 10. The city with the lowest number of inhabitants will have the lowest number, namely 1. So the idea is a kind of sorting number.

fn = path to the file

layer=iface.addVectorLayer(fn, '', 'ogr')
features=layer.getFeatures()
caps=layer.dataProvider().capabilities()

if caps&QgsVectorDataProvider.AddAttributes:
       res=layer.dataProvider().addAttributes([QgsField("RANK", QVariant.Double)])
   layer.updateFields()

A: This should do it:
layer = iface.activeLayer() # layer to work with
populationfield = 'population' # name of existing population field
rankfield = 'rank' # name of new rank field

request = QgsFeatureRequest()
# setup the orderby request: ascending=True -> smallest city will have rank 1, ascending=False -> biggest city will have rank 1
orderby = QgsFeatureRequest.OrderBy([QgsFeatureRequest.OrderByClause(populationfield, ascending=True)])
request.setOrderBy(orderby) # set the request to the order by clause
rankcounter = 1 # initialize counter

with edit(layer):
    layer.dataProvider().addAttributes([QgsField(rankfield, QVariant.Double)]) # add the new field
    layer.updateFields() # update the fields, so we can work with the new field added

    for feature in layer.getFeatures(request): # iterate over the sorted layer
        feature[rankfield] = rankcounter # assign the current rank to feature
        layer.updateFeature(feature) # update the feature
        rankcounter += 1 # increase rank counter


text:
Q: How to avoid line insert to the file if the line is already present in the file? How should the check be made so that there are no line duplicates in the file
open ( FILE, ">newfile");
for( $a = 1; $a < 20; $a = $a + 1 ) {
    my $random_number = 1+ int rand(10);;
    # check to avoid inserting the line if the line is already present in the file
    print FILE "Random number is $random_number \n";
}

close(FILE);

A: !$seen{$_}++ is a common idiom for identifying duplicates.
my %seen;
for (1..19) {
    my $random_number = 1+ int rand(10);

    say "Random number is $random_number" if !$seen{$random_number}++;
}

But that doesn't guarantee that you will get all numbers from 1 to 10 in random order. If that's what you are trying to achieve, the following is a far better solution:
use List::Util qw( shuffle );

say "Random number is $_" for shuffle 1..10;

A: Enter each line into a hash as well, what makes it easy and efficient to later check for it
use warnings;
use strict;
use feature 'say';

my $filename = shift or die "Usage: $0 filename\n";

open my $fh, '>', $filename or die "Can't open $filename: $!";

my %existing_lines;

for my $i (1..19)
{
    my $random_number = 1 + int rand(10);

    # Check to avoid inserting the line if it is already in the file
    if (not exists $existing_lines{$random_number}) {
        say $fh "Random number is $random_number";
        $existing_lines{$random_number} = 1;
    }
}
close $fh;

This assumes that the intent in the question is to not repeat that  number (symbolizing content to be stored without repetition).
But if it is indeed the whole line (sentence) to be avoided, where that random number is used merely to make each line different, then use the whole line for the key
for my $i (1..19)
{
    my $random_number = 1 + int rand(10);
    my $line = "Random number is $random_number";

    # Check to avoid inserting the line if it is already in the file
    if (not exists $existing_lines{$line}) {
        say $fh $line;
        $existing_lines{$line} = 1;
    }
}

Notes and literature

*

*Lexical filehandles (my $fh) are much better than globs (FILE), and the three-argument open is better. See the quide perlopentut and reference open

*Always check the open call (or die... above).  It can and does  fail -- quietly. In that check always print the error for which it failed, $!

*The C-style for loop is very rarely needed while the usual foreach (with synonym for) is much nicer to use; see it in perlsyn. The .. is the range operator

*Always declare variables with my, and enforce that with strict pragma; always use warnings

*If the filehandle refers to pipe-open (not the case here) always check its close

*See perlintro for a general overview and for hashes; for more about Perl's data types see perldata. Keep in mind for later the notion of complex data structures, perldsc

A: It seems like what you are asking is how to randomize the order of the numbers 1 to 20. I.e. no duplicates, random order. That can be easily done with a Schwartzian transform. For example:
perl -le'print for map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, rand()] } 1..20'
6
7
16
14
5
20
3
13
19
17
4
8
15
10
9
11
18
1
2
12

In this case, reading from the end and backwards, we create a list of numbers 1 .. 20, we feed that into a map statement which turns each number into an array-ref, containing the number, and a random number. Then we feed that list of array refs to a sort, where we sort numerically on the second argument in the array ref: the random number (hence creating a random order). Then we transform the array ref back into a simple number with another map statement. Finally we print the list using a for loop.
So in your case, the code would look something like:
print "Random number is: $_\n" for      # print each number
    map { $_>[0] }                      # restore to a number
    sort { $a->[1] <=> $b->[1] }        # sort the list on the random number
    map { [ $_, rand() ] }              # create array ref with random number as index
    1 .. 20;                            # create list of numbers to randomize order of

Then you can use the program like below to redirect output to a file:
$ perl numbers.pl > newfile.txt


text:
Q: 1980s sci-fi book club trilogy about a rich, space-faring multi-generational family I'm looking for the title of 1980s sci-fi book club trilogy about a multi-generational family. The covers had faces on them and the matriarch had a white streak in her hair. Rich family, space-faring and it had family trees in it. I got it from the Science Fiction Book Club some time in the 80s.

A: Possibly the  Galactic Milieu Series?

The series begins with Intervention: A Root Tale to the Galactic
  Milieu and a Vinculum between it and The Saga of Pliocene Exile
  (1987). This was released in one volume in the UK, but in mass market
  paperback in the USA as two volumes: Surveillance and Metaconcert.
  May calls Intervention a vinculum, or link-tale, between the Saga of
  Pliocene Exile and the Milieu trilogy proper. However, it is a
  near-essential introduction to the Milieu trilogy as well as a
  balanced stand-alone work.
Jack the Bodiless (1991) is the first book of the trilogy proper,
  followed by Diamond Mask (1994), and Magnificat (1996).

Series summary:

The Galactic Milieu Series by Julian May describes the struggle of the
  most powerful of the human metapsychics and their interaction with a
  galactic confederation of exotic beings.
The entire story takes place over roughly a 150 year period, starting
  with the birth of the narrator in 1945. History starts to diverge
  wildly and obviously from ours in the mid 80s as psychic research
  becomes mainstream due to the actual existence of people with operant
  mind powers.

If you look at the "Look Inside" sample of Magnificat at Amazon.com, you can see the family tree(s) in the beginning. This  is the Remillard Family, or Dynasty.
There's a really good description/summary of each of the books in the series on the Galactic Milieu wiki page.

A: It's possible that you're referring to Anne McCaffrey's The Rowan series. Damia, her daughter, has a white streak in her hair. They're definitely rich. Space-faring is a bit trickier of a link in that they generally remain planet-bound, but they do interface with space. They were released in the early 90s, but it's close to your timeframe.

A: Perhaps the Children of the Stars series by Juanita Coulson. Book 1, Tomorrow's Heritage, was released by the SFBC in 1981 and the cover matches your description:

The series was however 4 books, not a trilogy. A description for book 1 is as follows:

"A futuristic, post-cataclysmic, sci-fi soap opera. On an Earth whose
  population has been decimated and whose landscape has been forcibly
  altered by natural causes and the effects of humankind's weapons,
  political and national boundaries have been altered. The Saunder
  family has gained wealth and power due to the actions of the
  manipulative matriarch, and the three offspring are in positions of
  great power and responsibility. But the family has cracks that
  ultimately will risk tearing the family apart. And into this volatile
  mix comes news that an alien spacecraft is approaching Earth."

The series does progress later to space-faring. With the Saunders family spending vast amounts of their fortune to aid in the development of faster-than-light technology.

Her clothes were the ultimate in fashion. Her hands were soft and beautiful. Her lustrous hair, stylishly middle-length, displayed that
  attractive white streak that was Jael's trademark. She covered her
  excess weight with loose, long-sleeved tunics over pants or half
  saris. The outfits flattered her busty figure. She was really doing
  fine, and she knew it. She just wanted to hear her devoted family tell
  her so.


text:
Q: Building Command From Variable Number of Args Passed My method accepts two properties and a json list and returns the corresponding value. It works as expected.
Now, I would like to add the functionality to have it return the corresponding value irrespective of it's depth.
For example, now it accepts parent and child args and returns a value (see below): return jsonprops[parent][child].
Is it possible to make it accept any number of args and return the corresponding value? return jsonprops[parent][child1][child2]....[childN]?
I've found an example of passing variable number of args to a method (below), but I'm not sure how to construct the return jsonprops[parent][child] since it'll have to order the args in [].
The desired solution will return a value for return jsonprops[parent][child] as well as return jsonprops[parent][child1][child2][child3][child4]
Passing variable number of args to a method:
def multipleArgs(*arg):
    print "Called with", len(arg), "arguments:", arg

Reading json file:
import json

def read_json(parent, child, jsonprops=[])
    return jsonprops[parent][child]

exampleFile = json.loads(open(example.json).read())
childInfo = read_json('parentProps', 'childProp1', exampleFile)
print childInfo

Example json
{
  "generalInfo": {
    "name": "example",
    "schemaVersion": "1.0",
    "description": "metadata to be an example"
  },
  "parentProps": {
      "childProp1": "hi 1",
      "childProp2": "hi 2",
      "childProp3": {
        "newParent": [
          {
            "parent1": [
              {
                "grandChild1": "GC1",
                "grandChild2": "GC2",
                "grandChild3": "GC3"
              },
              {
                "numberofKids": "5",
                "grandChild4": "GC4",
                "grandChild5": "GC5",
                "grandChild6": "GC6"
              }
            ],
            "parent2": [
              {
                "numberofKids": "1",
                "grandChild11": "GC11",
                "grandChild12": "GC12",
                "grandChild13": "GC13"
              },
              {
                "grandChild14": "GC14",
                "grandChild15": "GC15",
                "grandChild16": "GC16"
              }
            ]
          }
        ]
      }
    }
  }

A: How about using jsonpath with the objectpath module:
In [22]: from objectpath import Tree

In [23]: j = """
    ...: {
    ...:   "generalInfo": {
    ...:   "name": "example",
    ...:   "schemaVersion": "1.0",
    ...:   "description": "metadata to be an example"
    ...:   },
    ...:   "parentProps": {
    ...:     "childProp1": "hi 1",
    ...:     "childProp2": "hi 2",
    ...:     "childProp3": {
    ...:       "newParent": [
    ...:         {
    ...:         "grandChild1": "GC1",
    ...:         "grandChild2": "GC2",
    ...:         "grandChild3": "GC3"
    ...:         },
    ...:         {
    ...:         "grandChild4": "GC4",
    ...:         "grandChild5": "GC5",
    ...:         "grandChild6": "GC6"
    ...:         }
    ...:       ]
    ...:     }
    ...:   }
    ...: }"""

In [24]: j = json.loads(j)

In [25]: next(Tree(j).execute('$..{}..{}'.format('parentProps', 'childProp1')))
Out[25]: 'hi 1'

In [53]: next(Tree(j).execute('$..{}..{}'.format('newParent', 'grandChild5')))
Out[53]: 'GC5'

Your function will then load the json and return the result with the help of objectpath (if there)

A: To access a value from an arbitrary depth within a data structure, you probably want to use a loop. Here's one easy way to do it:
def get_value(data, *keys):
    for key in keys:
        data = data[key]
    return data

You can also use the the implicit loop performed by the reduce function (which in Python 3 is part of the functools module):
from functools import reduce # this line is only needed in Python 3
from operator import getitem

def get_value(*args): # data should be first argument, followed by any number of keys
    return reduce(getitem, args)


text:
Q: Profile page of logged in user always visible even when editing the URL to go to another users page I am constructing a social networking site. I have created profile_page.php which displays the profile of the current user and will eventually, also show the profile pages of other users on the website.
At the moment, if I am logged in, and click on the button Profile it will direct me to my profile page (http://localhost/profile_page/freddy), however, when I edit the URL to, for example: http://localhost/profile_page/tim, who is a registered user, it will display the page for user freddy.
I know the page is on Tim's profile page, because I have certain buttons which only appear to other users, and I also know it is on Tim's page because of the URL http://localhost/profile_page/tim, but I am unsure to why it is always displays the content (such as profile picture as well as posts) of user freddy.
At the moment, I have the following piece of code which determines whose profile the browser is on:
<?php
$user = "";
if (isset($_GET['u'])) {
    $user = ($_GET['u']);
    if (ctype_alnum($user)) { //check if the user exists
        $check = mysqli_query($connect, "SELECT * FROM users WHERE username='$user'");
        if (mysqli_num_rows($check) === 1) {
            $get        = mysqli_fetch_assoc($check);
            $user       = $get['username'];
            $fname      = $get['first_name'];
        } else { // refresh page
            // if the user doesnt exist i.e. ?u=fakeUser - it will redirect them to the index page.
            echo "<meta http-equiv=\"refresh\" content=\"0; url=http://localhost/index.php\">";
            exit();
        }
    }
}
?>

Edit:
Rewrite Rules:
Options -MultiViews
RewriteEngine On
RewriteBase /

RewriteRule ^(me)?/?$ profile_page.php [L,NC]
RewriteRule ^profile(?:_page)?/([\w-]+)/?$ profile_page.php?u=$1 [L,QSA,NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/?$ profile_page.php?u=$1 [L,QSA]


text:
Q: Can't recover AWS EC2 public IP address I recently created an AWS EC2 Instance and it had an IP address like 3.144.nnn.nnn.
I used that IP address for an application as my IP address and there is no way I can change it.
After stop and start of Instance, I get a random IP address.
Then I found I can allocate static IP address with Elastic IP address.
However, when I try to allocate the Elastic IP it also generates random IP, so I tried this with the AWS CLI:
aws ec2 allocate-address --address 3.144.nnn.nnn --domain vpc (with the same IP above)
But it returns an error:
An error occurred (InvalidAddress.NotFound)
when calling the AllocateAddress operation:
  The Elastic IP address '3.131.nnn.nnn' does not exist or is not available.

I tried with several IPs with the same range( for test purposes). However, it returns the same error.

A: If you want a fixed public IP you need to create an Elastic IP address and check what IP is assigned to it and then you can use that IP. You cannot choose the IP that is assigned to the Elastic IP address.
Also note if you release the Elastic IP address it will cost money if you do not have it assigned to an instance. If you delete the Elastic IP address chances of getting an Elastic IP address with the same IP is slim to none.


text:
Q: Spring JDO - makePersistent not returning created object I'm using Spring and JDO connecting to a MySQL database.
When I persist an object, I am expecting to see the created object returned by the makePersistent() method. It does return an object, but this object only has the ID of the newly created object. All the other fields that were persisted now have a value of null.
In the code example below, I insert a value of 12 with the carouselNumber. The returned object has that value set to NULL and the id has the newly created ID value from the database.
I've used JDOHelper.getObjectState() and found that my object is in a Transient state.
I'm wondering if there is some annotation that I am missing to tell JDO to return all the values on the object, rather than just the newly generated ID.
EDIT:
I've done some further exploring and found that when I use the raw Datanucleus JDP API that thsi works fine. The problem only seems to be when I use Spring's JDO template. I'd really like to get an understanding of why this differs. Thanks
Thanks in Advance,
Brian.
@PersistenceCapable(table = "CAROUSEL", identityType = IdentityType.APPLICATION)

public class Carousel {

    @PrimaryKey(column = "ID")
    @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT)
    private Long id;

   @Column(name = "CAROUSEL_NUM")
    private int carourselNumber;

......
public class CarouselDAOImpl extends JdoDaoSupport implements ICarouselDAO {

  public Carousel insert(Carousel carousel) {
    return getJdoTemplate().makePersistent(carousel);
   }

.....

A: The makePersistent method alters the carousel object you've passed in to generate an ID, so it doesn't need to return anything.  Just make your method void and use the carousel you've passed in.


text:
Q: Simple React/Heroku site not working when deployed, but works locally When running this site locally, no problem. I have my server/client in different folders and the server is set to update the database on Heroku. I have one simple input on the front end which is to add a name to the database. When I enter and submit, it updates the database on heroku no problem. I can see the update in MySQL Workbench.
I then uploaded my backend to heroku and I'm not getting any error messages in the heroku log and the site has the "cannot get /" message as expected.
I updated the url on the frontend for the post and still run the frontend locally but when I test it, it does not update the database. Here are some quick snippets:
frontend function onSubmit:
const addClient = () => {
Axios.post("https://***my-project***.herokuapp.com/create", { name: name }).then(
      (response) => {
console.log(response)
      }
    );
  };

and on the backend:
app.post("/create", (req, res) => {
const name = req.body.name;
db.query("INSERT INTO clients (name) VALUES (?)", [name], (err, result) => {
if (err) {
console.log(err);
    } else {
res.send("Database Updated");
    }
  });
});
app.listen(process.env.PORT || 3001, () => {
console.log("we are up and running");
});

Any obvious reason why this wouldn't work? When I run the heroku logs, it's showing the request came through with a 204 status.
I went through all of the possible solutions from this thread with no luck.
thanks!


text:
Q: For $5$ distinct integers $a_i$, $1\le i\le5$, $f(a_i)=2$. Find an integer b (if it exists) such that f(b) = $9$. Here's an interesting question I came across.The person who gave it to me told me that it should not take more than $3$ minutes to solve this question. But I could not find any definite solution :( Maybe you guys could give me some help.Any hints would be appreciated.Here's the question:
Let $f(x)$ be a polynomial with integer coefficients. Suppose for $5$ distinct integers $a_i$, $1\le i\le5$, $f(a_i)=2$. Find an integer b (if it exists) such that f(b) = $9$.

A: Since $f(a_i)=2$ for $1\le i\le5$, we have that for some polynomial $g(x)$ with integer coefficients,
$$f(x)=(x-a_1)(x-a_2)(x-a_3)(x-a_4)(x-a_5)g(x)+2.$$
If $f(b)=9$ for some $b\in\Bbb Z$, each $b-a_i$ has to be a divisor of $7$, but there are only four integers($1,-1,7,-7$) which can divide $7$, so $b-a_i$ cannot be all distinct.
This makes a contradiction, so there no exists such $b$.
p.s. Since $1\times-1\times-7=7$, I think that $5$ is not necessary to make a contradiction. $4$ is enough to make that.

A: Key Idea $ $ Generally if a polynomial has many factors then so too will its values. For example if $\,g(x) = (x-a_1)(x-a_2)(x-a_3)(x-a_4)h(x)\,$ for distinct integers $\,a_i\,$ then $\,g(n)\,$ has $\ge 4$ distinct factors, so it has at least $2$ factors $\ne \pm 1,\,$ so $\,g(n)\,$ is not prime. Apply this to $\,g := f\!-\!2.$
Remark $\ $ One can push the key idea to the hilt to obtain a simple algorithm  for polynomial factorization using factorization of its integer values and Lagrange interpolation. The ideas behind this algorithm are due in part to $ $ J. I. Bernoulli (1708), F. T. Schubert (1794), L. Kronecker (1882) and B. A. Hausmann (1937). See this answer for references.


text:
Q: How to remove an element from a vector given the element? Is there a simple way to remove an element from a Vec<T>?
There's a method called remove(), and it takes an index: usize, but there isn't even an index_of() method that I can see.
I'm looking for something (hopefully) simple and O(n).

A: This is what I have come up so far (that also makes the borrow checker happy):
let index = xs.iter().position(|x| *x == some_x).unwrap();
xs.remove(index);

I'm still waiting to find a better way to do this as this is pretty ugly.
Note: my code assumes the element does exist (hence the .unwrap()).

A: You can use the retain method but it will delete every instance of the value:
fn main() {
    let mut xs = vec![1, 2, 3];
    let some_x = 2;
    xs.retain(|&x| x != some_x);
    println!("{:?}", xs); // prints [1, 3]
}

A: Your question is under-specified: do you want to return all items equal to your needle or just one? If one, the first or the last? And what if there is no single element equal to your needle? And can it be removed with the fast swap_remove or do you need the slower remove? To force programmers to think about those questions, there is no simple method to "remove an item" (see this discussion for more information).
Remove first element equal to needle
// Panic if no such element is found
vec.remove(vec.iter().position(|x| *x == needle).expect("needle not found"));

// Ignore if no such element is found
if let Some(pos) = vec.iter().position(|x| *x == needle) {
    vec.remove(pos);
}

You can of course handle the None case however you like (panic and ignoring are not the only possibilities).
Remove last element equal to needle
Like the first element, but replace position with rposition.
Remove all elements equal to needle
vec.retain(|x| *x != needle);

... or with swap_remove
Remember that remove has a runtime of O(n) as all elements after the index need to be shifted. Vec::swap_remove has a runtime of O(1) as it swaps the to-be-removed element with the last one. If the order of elements is not important in your case, use swap_remove instead of remove!

A: Is drain_filter() new from the last answers?
Seems similar to Kai's answer:
#![feature(drain_filter)]
let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];

numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();

assert_eq!(numbers, vec![1, 3, 5, 9, 11, 13, 15]);

https://doc.rust-lang.org/std/vec/struct.Vec.html#method.drain_filter

A: If your data is sorted, please use binary search for O(log n) removal, which could be much much faster for large inputs.
match values.binary_search(value) {
  Ok(removal_index) => values.remove(removal_index),
  Err(_) => {} // value not contained.
}

A: There is a position() method for iterators which returns the index of the first element matching a predicate. Related question: Is there an equivalent of JavaScript's indexOf for Rust arrays?
And a code example:
fn main() {
    let mut vec = vec![1, 2, 3, 4];

    println!("Before: {:?}", vec);

    let removed = vec.iter()
        .position(|&n| n > 2)
        .map(|e| vec.remove(e))
        .is_some();

    println!("Did we remove anything? {}", removed);

    println!("After: {:?}", vec);
}


text:
Q: Change variable (and dependent variables) in imported module in Python python_import_test2.py file:
AAA = 'test2'
BBB = AAA + '_BBB'
def showBBB():
    print AAA
    print BBB

python_import_test1.py file:
import python_import_test2 as testimport
testimport.AAA = 'test1'
testimport.showBBB()`

As an out I get:
test1
test2_BBB

How to get:
test1
test1_BBB

?

A: This is because, the value is not assigned to BBB after you reinitialize AAA. When you import with the statement:
    import python_import_test2 as testimport

The value of AAA = 'test2'
The value of BBB = 'test2_BBB'
Then you reinitialize AAA
Now, The value of AAA = 'test1'
The value of BBB = 'test2_BBB'
This is what you are getting.
You can initialize BBB inside the function defination to get the desired result.
python_import_test2.py file:
AAA = 'test2'

def showBBB():
    print AAA
    BBB = AAA + '_BBB'
    print BBB

A: Since BBB is a global variable in python_import_test2.py when you import that module python calculate the global variables so it would be test2_BBB and then you didn't change it, and just changed AAA.
If you want to change that variable you can change it in your function scope.
def showBBB():
    print AAA
    BBB = AAA + '_BBB'
    print BBB

Note that all we have in python is about run time, so till you don't run the function python doesn't execute it,and when you invoke that function after reassigning the AAA python will run it using new variable.


text:
Q: Open Access Form with Filter VBA I'm having trouble opening a form using a filter.  The code that I am trying to run is this:
DoCmd.OpenForm "MyForm", , "[ID] = " & Me.MyListBox.Column(0), , acFormEdit, acDialog

When I run this line, it opens the form, but does not apply the filter.
The FilterOnLoad property is set to True, and I have verified that it is true in the On Load event.
While in the Form_Load event, Me.FilterOn = False and Me.Filter = "".
What happened to the filter?  What am I doing wrong?  I've tried setting the Me.FilterOn property to True via VBA and then saving the form, but when I open the form again, it is reset to False.
If I put the filter in using VBA and then set the Me.FilterOn property to True, the form correctly filters.  I have verified that the correct value is there for "Me.MyListBox.Column(0)"

A: Here is what the DoCmd.OpenForm Method help topic has to say about the FilterName parameter:

A string expression that's the valid name of a query in the current
  database.

But you're not giving it the name of a query.  I think you actually want the WhereCondition parameter instead:
DoCmd.OpenForm FormName:="MyForm", _
    WhereCondition:="[ID] = " & Me.MyListBox.Column(0), _
    DataMode:=acFormEdit, _
    WindowMode:=acDialog


text:
Q: PHP, как получить изображение из ресурса? У меня есть код, который возвращает ресурс изображения видом imagepng($this->image).
Мне нужно каким-то образом сделать из изображения путь к изображению, базируясь на этом мануале: https://core.telegram.org/bots/api#sendphoto
В общем, мне нужно обработать ресурс и отправить фото в Телеграм, но я никак не пойму как и что делать с этим ресурсом

A: Сохрани изображение в файл передав имя файла вторым параметром в imagepng, и отправь файл через curl по Telegram Bot API:
$tmpfilename = tempnam("/tmp", "img");
imagepng($this->image, $tmpfilename);

$bot_url    = "https://api.telegram.org/bot<bot_id>/";
$url        = $bot_url . "sendPhoto?chat_id=" . $chat_id ;

$post_fields = array(
    'chat_id'   => $chat_id,
    'photo'     => new CURLFile($tmpfilename)
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);

unlink($tmpfilename);


text:
Q: glOrtho() not working as I thought it would I am trying to have one of the viewports in my window display an orthographic projection of a teapot.
mat4 view = translate (identity_mat4 (), vec3 (0.0, 0.0, -40.0));
mat4 persp_proj = perspective(50.0, (float)width/(float)height, 0.1, 100.0);
mat4 model = rotate_x_deg (identity_mat4 (), 40);
glViewport (0, 0, width / 2, height / 2);
glOrtho(0,400,0,300,0,1);
    glUniformMatrix4fv (proj_mat_location, 1, GL_FALSE, persp_proj.m);
glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view.m);
glUniformMatrix4fv (matrix_location, 1, GL_FALSE, model.m);
glDrawArrays (GL_TRIANGLES, 0, teapot_vertex_count);

This is the part in the code that I would like to use glOrtho to draw an orthographic view of the teapot. First of all, am I even using glOrtho correctly? I think I am, but I'm not getting what I hopped to get so I'm doubt I am.
Why doesn't what I have work, and how I would go about fixing it?
If I am supposed to put glOrtho in a specific place it would be helpful to know where.
Also, as I am supposed to have several viewports will all of the viewports have an orthographic projection after that?
Here's my entire program
code snipet is taken from lines 192-204

A: I don't have full knowledge of your program, but given what I see, I doubt glOrtho will work at all. It is a (deprecated) function used to multiply the current matrix in the fixed function pipeline by an orthographic projection matrix. However, your program appears to use shaders and construct its own matrices (as a modern OpenGL program should). So if what you currently have sans glOrtho works, what you really need to do is replace your mat4 persp_proj with a mat4 ortho_proj that contains the orthographic projection you want.


text:
Q: Prove that : $\Omega =\frac{10^{n}-7}{3}$ Has many numbers not prime? Prove that : $n\in\mathbb{N^{*}}$
$$\Omega =\frac{10^{n}-7}{3}$$
Has many numbers not prime ?
My try :
$n=1$ then $\Omega =1$ not prime
$n=2$ then $\Omega =31$ prime number
$n=3$ then $\Omega =331$ prime number
$n=4$ then $\Omega =3331$ prime number
I have tried many value but I can't find in degree such that this number are not prime

A: Note that $\frac {10^9-7}3$ has a factor $17$ and $10^{16} \equiv 1 \pmod {17}$, so any number of the form $\frac {10^{16k+9}-7}3$ is divisible by $17$


text:
Q: Dropdown onchange function call not working In my page I used a drop down. When change the dropdown values it will call the function named sample. But onchange function is not working. Anyone can help me to solve this issue.
<!doctype html>

    <meta charset="utf-8" />
    <title>jQuery UI Autocomplete - Combobox</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />

    <link rel="stylesheet" href="/resources/demos/style.css" />

JS file

HTML coding

    Your preferred programming language:
    <select id="combobox" onchange="sample();">
        <option value="">Select one...</option>
        <option value="ActionScript">ActionScript</option>
        <option value="AppleScript">AppleScript</option>
        <option value="Asp">Asp</option>
        <option value="BASIC">BASIC</option>
        <option value="C">C</option>
        <option value="C++">C++</option>
        <option value="Clojure">Clojure</option>
        <option value="COBOL">COBOL</option>
        <option value="ColdFusion">ColdFusion</option>
        <option value="Erlang">Erlang</option>
        <option value="Fortran">Fortran</option>
        <option value="Groovy">Groovy</option>
        <option value="Haskell">Haskell</option>
        <option value="Java">Java</option>
        <option value="JavaScript">JavaScript</option>
        <option value="Lisp">Lisp</option>
        <option value="Perl">Perl</option>
        <option value="PHP">PHP</option>
        <option value="Python">Python</option>
        <option value="Ruby">Ruby</option>
        <option value="Scala">Scala</option>
        <option value="Scheme">Scheme</option>
    </select>

<button id="toggle">Show underlying select</button>

A: Default onchange event of the selectbox will not work as it gets converted by jquery UI.
Use jQuery UI built in event for the same:
$( "#combobox" ).autocomplete({
change: function( event, ui ) { alert("testing");}
});

Ref: http://api.jqueryui.com/autocomplete/#event-change
----EDIT----
Solution is here :
Possible duplicate of : jquery UI Combobox ONCHANGE

A: This is because jqueryUI (or your code?!) hides the original combobox, replacing it with its own.
Use firebug or similar to insprect the combobox. It is hidden!
You can use a js-eventlistener to fix it, like you did it here:
$( "#toggle" ).click(function() {
 $( "#combobox" ).toggle();
});

However,
$(".ui-combobox input").change(function(){
    sample();
});

this does not work, because change is not triggered by a selection.
Only by manual input.
So you will have to trigge it:
select: function( event, ui ) {

                $(this).trigger("change"); // here
                            ui.item.option.selected = true;
                            that._trigger( "selected", event, {
                                item: ui.item.option
                            });
                        },


text:
Q: Using "ctrl" + "shift" + "arrow" with merged cells in Excel I am trying to use the shortcut ctrl + shift + arrow, such as the down arrow, to select an entire column of data.
The issue is that some of the rows in that column have been merged or split. For example, rows 4 and 5 have been merged together for the first few columns, but then re-split for the last few.
If I am using ctrl + shift + down in a column where the rows have been split again, the selection does not extend all the way to the next empty row. It stops at the next merged/split row.
How can I use this shortcut to extend all the way to the next empty row?

A: To understand the behaviour you are seeing, you need to understand what merged cells are really doing, which is to delete everything except the top-left cell of the merged area and then do a presentational trick.
The gaps caused by the deletion of the cells explain all the behaviour you see. For example, the ctrl-shift-arrow shortcut will stop when you hit one of these deleted cells, because it is an empty cell.
So the short answer is:
The short cut is working as it is supposed to. So there is no easy work around
But worse, it is easy to be misled as to what your spreadsheet is calculating and it is important to understand precisely what Merge Cells is really doing - and I don't like it! So I say:
It is better to not use merged cells on anything you are doing calculations on (preferably not even column/row headings on tables either.)
If you must, make sure you know what you are doing. If you must use them, it might be a good idea to
(1) do the cell merges you want, then
(2) UN-merge them all while you work on the sheet and then
(3) only re-merge them once you are finished and want to make pretty outputs!
Let me explain (I have made this long explanation because cell merging causes far bigger problems that keyboard shortcuts acting oddly and far too few people understand this):
WHAT DOES MERGEING A CELL MEAN
The message box you get when you hit merge tells most of the story: when you merge cells Excel deletes the contents of all the cells except the top-left cell in the range. Behind the scenes, for calculations and key-presses it is behaving entirely normally - it is just that you aren't seeing what it sees.
(The one truly changed behaviour is they way it expand selections so that you can't select part of a merged cell).
EXAMPLE - A 4x4 TABLE
Let us image we have a simple table (4 x 4, arbitrary data) with sums and averages being calculated by rows, by columns and in one go.

Everything matches up as you would expect.
Now let's say we merge the four central cells:

The figures change - but in ways that are inconsistent and non-intuitive and important to understand. For example you can see that the different rows and columns have different sums and averages despite appearing to be the same. And it now matters whether I take an average over the whole table or by rows first or by columns first, which is not necessarily what you would be expecting. What is going on?
WHAT IS GOING ON?
What is really happening is that Excel (as that dialog box that popped up said) has deleted all except the top left cell, so now there are three empty cells on your sheet:

When you understand that this is how Excel sees your spreadsheet you can see why Excel behaves as it does. For example, Ctrl-Shift-Arrow stops there because there is an empty cell there.
But as I said above, the bigger issue is that it is easy to loose track of what the sheet is as actually calculating. It is even possible to format a merge so that it doesn't look like a merge but shows data in the wrong cell!
Lets say that you had without thinking about it, re-formatted your table (which has merged cells somewhere on it) to align its cells bottom-right (maybe you re-aligned some other bits of it by mistake and were correcting that). It might end up lookign like this:

Hopefully you can see now what Merge Cells is doing and why it behaves in the way you have found (and see why I call it dangerous, and don't use it if I can possibly avoid it!)


text:
Q: How to get the index of the max value of each list in the array? So I have this array,
a = np.array([[5,10,1,3], [1,5,1,5], [0,3,1,8]])
and I wish to show the index of the max value of each.
the output will be shown like this
'1,1,3'
as 5 is the max value of the 1st element and it's index is 1,
as 5 is the max value of the 1st element and it's index is 1, and
as 8 is the max value of the 1st element and it's index is 3.
I have tried some function, like max and do the looping, and argmax, but I couldn't find the right answer. I am really new to python.
please help me with the function that can return the output regardless the length of the array.
Thank you..

A: Your idea works fine for me:
a.argmax(axis=1)

yields:
Out[]: array([1, 1, 3])

same for np.argmax(a,axis=1)


text:
Q: Does VMWare Fusion (5) use logical CPU cores before physical ones? I have a Intel Core i7 quad core CPU in my Mac Book Pro. The processor supports hyperthreading, so I have 4 physical CPU core and 8 logical ones.
Now, when I assign 4 CPU cores to a virtual machine in VMWare Fusion (version 5, if it matters), does VMWare Fusion use the physical ones before using the logical ones?
I.e. which solution will be used (PC = physical core, LC = logical core):

*

*PC1-LC1, PC2-LC1, PC3-LC1, PC4-LC1

*or: PC1-LC1, PC1-LC2, PC2-LC1, PC2-LC2

Does this even matter?


text:
Q: Amazon MWS DateTime issue depending how initalized I am requesting a report from Amazon MWS using their SDK (https://developer.amazonservices.com/doc/bde/reports/v20090101/cSharp.html). I am calling Request Report (http://docs.developer.amazonservices.com/en_US/reports/Reports_RequestReport.html). I have to submit a start and end date. The issue I am running into is the SDK won't accept my DateTime input if initialized a certain way but does the other way and I can't understand why that is.
Here is my code. When I initialize using DateTime.Today.AddDays(-14) it does NOT work. When I initialize by setting a specific date, new DateTime(2019, 1, 23) it DOES work. When I run both through LINQPad the structure looks the same to me.
The commented code does not work. The code right after does.
MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
            config.ServiceURL = "https://mws.amazonservices.com";

            MarketplaceWebServiceClient service =
                new MarketplaceWebServiceClient(
                    ConfigurationManager.AppSettings["AWSAccessKey"],
                    ConfigurationManager.AppSettings["SecretKey"],
                    "Easy MWS Reports",
                    "1.0",
                    config);

            RequestReportRequest request = new RequestReportRequest();
            request.Merchant = ConfigurationManager.AppSettings["SellerId"];
            request.MarketplaceIdList = new IdList();
            request.MarketplaceIdList.Id = new List<string>( new string [] { ConfigurationManager.AppSettings["MarketplaceId"] } );

            request.ReportType = "_GET_AMAZON_FULFILLED_SHIPMENTS_DATA_";

            //request.StartDate = DateTime.Today.AddDays(-14);
            //request.EndDate = DateTime.Today;
            request.StartDate = new DateTime(2019, 1, 6);
            request.EndDate = new DateTime(2019, 2, 5);

            RequestReportResponse response = service.RequestReport(request);

The really strange thing is when I inspect the request object before calling the API my start and end dates are correct. When I get that response back Amazon is telling me my start and end dates are both .Now. That leads me to believe that DateTime objects are serializing different based on how I initialize them and that I don't understand.
[UPDATE] I beleive eitamal is correct but there doesn't seem to be any way to do that that is easier then what I settled on which is the following.
var then = DateTime.Today.AddDays(-15);
var now = DateTime.Today;
request.StartDate = new DateTime(then.Year, then.Month, then.Day);
request.EndDate = new DateTime(now.Year, now.Month, now.Day);


text:
Q: How to use glob command in sed command through tcl script I am having below file:
File path: ???

I want to replace this line with below:
File path: Path1/Path2/Path3/File.txt

I have tried the following through the tcl file. But it's not working:
sed -i "s|File path: ???|File path: glob $WORK_AREA/../../../*.txt|g" $file

Note: This path is having only 1 .txt file
How can i use the glob command in sed command through the .tcl file?

A: Use several lines of code. It's so much easier.
set targetFile [lindex [glob $WORK_AREA/../../../*.txt] 0]
# You might also want to normalize the filename...
exec sed -i "s|File path: ???|File path: $targetFile|g" $file

You're strongly suggested to use exec explicitly in Tcl. You might also like this (which stops you from getting surprises in the directory path):
set targetFile [lindex [glob -directory $WORK_AREA/../../.. *.txt] 0]

And if WORK_AREA is an environment variable, you refer to those in Tcl using the env global array, like this: $env(WORK_AREA) or like this: $::env(WORK_AREA).
I've not fixed the ???. It might be replaceable with .* or maybe .*txt or any number of other regular expressions to match the text you want to remove. Without knowing your actual input data in depth, it's hard to be sure.


text:
Q: how to validate the json string in asp.net c#? I have json string which will pass to the webservice to perform some action on it. My json string will b like this example:
{"ID":"2","Name":"Tom","data":"[22.3,23.4,21.5]"}

I want to validate the json string if I remove the , (coma):
{"ID":"2""Name":"Tom""data":"[22.3,23.4,21.5]"}

From the json string so its return error message json is not in the correct format.

A: JSON.net and JSONSharp allow you to parse JSON into an object and will have the ability to validate or at least catch an exception on errors

A: Try
var dynamicObject = Json.Decode(jsonString);

And see if it raises an error.
You may need to install the DLL for this separately.  I believe it is in the MVC library download.
http://msdn.microsoft.com/en-us/library/system.web.helpers.json%28v=vs.111%29.aspx

A: Maybe you can try creating the JSON with the function ToJSON()
List<MyObject> people = new List<MyObject>{
                   new MyObject{ID = 1, Name= "Tom", Data= "[22.3,23.4,21.5]"},
                   new Person{ID = 2, Name= "Tome", LastName = ""[22.3,23.4,21.5]"}
                   };

string jsonString = people.ToJSON();

And if you with have the string as JSON you can do something like:
JsonConvert.SerializeObject(jsonString ).Dump();

Or using the Networking JSON:
http://james.newtonking.com/json

A: A working code snippet
public bool isValidJSON(String json) {
try {
JToken token = JObject.Parse(json);
return true;
}
catch(Exception ex){
return false;
}
}
Source


text:
Q: ViewState in the ASP.NET, does it really go away? I have read different topics, tutorials etc... Everywhere there is an information that ASP.NET MVC has an advantage for not using/containg a ViewState stuff.
Really?
So... How could it be (look at the screenshot)?
http://s18.postimg.org/rvgm2ypjt/Screenshot_568.png
As you can see in the screen it isn't a WebForms project.
I just added the next code in the one View:
http://ideone.com/iPkmdO
Why do I have a Viewstate in my ASP.NET MVC project?

A: <form class="form-horizontal" id="MainForm" runat="server">

If you are using runat="server", then you are invoking webforms; don't do that. This is MVC - you don't need that. Just change it to:
<form class="form-horizontal" id="MainForm">

A: It's because you are using aspx pages in MVC project. (In the screenshot I can see ViewMaps.aspx)
Aspx pages are webforms. Webforms have viewstate.
If use use the proper Controllers and Views, you will not see any viewstate. Just because the project is MVC doesn't mean that viewstate will not be present on aspx pages.
Also, people generally don't use aspx pages in MVC projects.


text:
Q: ksoap2 nested items with similar namespace but different types This is how the request envelope should look like:
<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
  <v:Header />
  <v:Body>
    <getLijst xmlns="http://OAM/OMZETAPPMETHODS.xsd">
      <selectie i:type="n1:OAM_ArtstructselobjUser" xmlns:n1="http://OAM/OMZETAPPMETHODS.xsd">
        <filiaal i:type="d:decimal">4</filiaal>
        <artnivsel i:type="n1:OAM_ArtstructobjUser">
          <asonummer i:type="d:decimal">1</asonummer>
          <asotype i:type="d:string">P</asotype>
        </artnivsel>
      </selectie>
    </getLijst>
  </v:Body>
</v:Envelope>

And this is a part of my code:
String nameSpace = "http://OAM/OMZETAPPMETHODS.xsd";
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setAddAdornments(false);
SoapObject request = new SoapObject(nameSpace, _soapMethod);

OAM_ArtstructselobjUser obj = new OAM_ArtstructselobjUser();
// .. This is where the properties are added, irrelevant
request.addProperty("selectie", obj);

OAM_ArtstructobjUser obj2 = new OAM_ArtstructobjUser();
// .. This is where the properties are added, irrelevant
request.addProperty("artnivsel", obj2);

envelope.setOutputSoapObject(request);

Marshal floatMarshal = new MarshalFloat();
floatMarshal.register(envelope);

envelope.addMapping(nameSpace, "OAM_ArtstructselobjUser", OAM_ArtstructselobjUser.class);
envelope.addMapping(nameSpace, "OAM_ArtstructobjUser", OAM_ArtstructobjUser.class);

So I want artnivsel to have a custom type, but inherits the namespace of selectie.
If I run the above code i get an 05-07 14:22:21.034: ERROR/AndroidRuntime(16417): Caused by: java.lang.RuntimeException: Unknown Property: asotype
If I change the nameSpace of the second addMapping to anything else, my code runs fine. But my envelope XML isn't correct. anymore.
Anyone who can give me a pointer, I'm not that experienced with ksoap2 or soap in particular.

A: Okay looks like updating to ksoap2.6.4 fixes this.
Just add avoidExceptionForUnknownProperty to true on the SoapSerializationEnvelope


text:
Q: Why does assignment to python type 'list' work? In Python, I noticed my brother was assigning lists using the 'list' function, which I told him was wrong to do as you should always create a variable. The problem is, his code was working, and I don't know why?
eg:
list = [1,2,3,4,5]
a = list
print(a)

Why does this work?
Also, can someone explain to me why if I create two variables referencing list, and modify one, the other variable gets modified too? Is this a reference to an object in memory? What is a use for this?
eg:
list = [1,2,3,4,5]
a = list
b = list
b.pop(0)
print(a, b)

Outputs:
[2, 3, 4, 5] [2, 3, 4, 5]

I cant seem to find any documentation on this specific case, so I thought I would ask everyone here :) Thanks


text:
Q: Listing the all the cosets efficiently I want to list all the cosets of $S_4$ in $S_5$, where $S_4$ means symmetric group on 4 elements. One way is try to do composition with all the elements of $S_5$ with $S_4$. A little better is eliminate the set of all elements of $S_4$ which are in $S_5$. Working further on this to me it appears that if I do composition with $4$ transpositions of $S_5$ with $S_5$ will be sufficient.
Question : How to listing the all cosets efficiently? ( without using GAP )

A: Take the set $M = \{1,2,3,4,5\}$. Then $S_4 \leq S_5$ is the stabilizer of $5$ under the standard action of $S_5$ on $M$. Thus, by the orbit stabilizer theorem, there is a bijection between $M$ and the cosets. Namely, the cosets are given by
$$C_i = \{\pi \in S_5 \mid \pi(5) = i\}$$
for $1 \leq i \leq 5$.
There are different ways to write all elements of these sets down, depending on what you want them for.


text:
Q: Have issues with Java splitting with given line of words String cityStateZip = ResultSetHelper.getString(resultSet, "line_3_addr"); // PU ABCDEF, CS 12345
if (StringHelper.isValid(cityStateZip)) {
    String[] splited = cityStateZip.split("\\s+");

    if (splited[0].length() > 0) {
        String city = splited[0].substring(0, splited[0].length() - 1);
        super.setFieldValue(OFFICECITY, city);  //PU
    }

    if (splited[1].length() > 0) {
        super.setFieldValue(OFFICEST, splited[1]); //ABCDEF
    }

    if (splited[2].length() > 0 ) {
        super.setFieldValue(OFFICEZIP, splited[2]); // CS 12345
    }
}