text:
Q: Apply binary search to combine two sorted sub arrays using recursive merge sort in C++ Apply binary search to combine two sorted sub arrays using recursive merge sort :
void combine(int a[],int low,int mid,int high)
{
int temp[50],i,j,k;
i=low;
j=mid+1;
k=0;
int m=(low+mid)/2;
while(i<=mid&&j<=high)
{
    if(a[m]<a[j])
    {
        for(i=low;i<=m;i++)
        {
            temp[k]=a[i];
            k++;
        }
        low=mid+1;
        j++;
        m=(low+mid)/2;
    }
    else
    {
            high=m-1;
            m=(low+mid)/2;
}

Above Function is to perform binary search and merge to sorted sub arrays
Here sub arrays are:
 1) a[low]to a[mid]
 2) a[mid+1] to a[high]


text:
Q: How to call a function that has a function pointer as an argument in C? I'm writing a program that finds solutions to an equation using Newton's method. I need to use function pointers so that the equation can be quickly replaced if needed.
Function pointers work as long as I just need the value returned by the function, but not when I try to call a function that has function pointers as arguments inside another function.
#define _CRT_SECURE_NO_WARNINGS
#define M_PI 3.14159265358979323846
#define N 2
#include <stdio.h>
#include <math.h>

struct data{
    double theta;
    double gamma;
    double M;
    double epsilon;
    double dx;
};

double funct(double, data);
double derivative(double, data, double(*f)(double, data));
double MST(double, data, double(*f)(double, data));

void main(){
    double results[N];
    data parameters;
    parameters.gamma = 1.4, parameters.epsilon = 0.001;
    printf("Podaj parametry:\nTheta = ");
    scanf("%lf", &parameters.theta);
    printf("M = ");
    scanf("%lf", &parameters.M);

    int index = 0;
    for (int x = 0; x < M_PI / 2.; x++){
        if (funct(x, parameters)*funct(x + 1, parameters) < 0){
            results[index] = MST(x, parameters, (*funct)(x, parameters));
            index++;
        }
    }
}

double funct(double sigma, data parameters){
    return 2. / ((parameters.gamma + 1)*parameters.M*parameters.M*sin(sigma)*sin(sigma)) - tan(sigma - parameters.theta) / tan(sigma) + (parameters.gamma - 1) / (parameters.gamma + 1);
}

double derivative(double x, data parameters, double (*f)(double x, data parameters)){
    double dx = 0.0001;
    return (f(x + dx, parameters) - f(x, parameters)) / dx;
}

double MST(double sigma_0, data parameters, double(*funct)(double sigma, data parameters)){
    double sigma_1 = sigma_0 - funct(sigma_0, parameters) / derivative(sigma_0, parameters, (*funct)(sigma_0, parameters));
    while (fabs(sigma_1 - sigma_0) < parameters.epsilon){
        sigma_0 = sigma_1;
        sigma_1 = sigma_0 - funct(sigma_0, parameters) / derivative(sigma_0, parameters, (*funct)(sigma_0, parameters));
    }
    return sigma_1;
}

I get errors in lines 31, 47, 50 on (*funct).

Error: argument of type "double" in incompatible with parameter of type "double (*)(double x, data parameters)".

A: Here you have an example:
#include <stdio.h>

int function1(int x)
{
    return x + x;
}

int function2(int x)
{
    return x * x;
}

int function3(int x)
{
    int result = 1;
    for(int i = 1; i <= x; i++)
        result *= i;
    return result;
}

int ffunction(int (*f)(int), int arg)
{
    return f(arg);
}

int main()
{
    printf("Function1 call %d\n", ffunction(function1, 5));
    printf("Function2 call %d\n", ffunction(function2, 5));
    printf("Function3 call %d\n", ffunction(function3, 5));

    return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Everybody is not" vs "Not everybody is"
Everybody's got a water buffalo, yours is fast but mine is slow.

You can't say everybody's got a water buffalo! Everyone does not have a water buffalo!

This construction:

Everyone does not have a water buffalo!

really irks me, because there are people who do have a water buffalo, and the sentence seems to imply the opposite. I would much prefer the sentence:

Not everybody has a water buffalo!

Is the first construction somehow grammatically defensible, or is it just used because it better parallels as a negation of the sentence, "Everybody's got a water buffalo"?

A: Well, it's somewhat defensible because "everyone does not have a water buffalo" is not necessarily the same as "no one has a water buffalo".  It can be considered as the negation of the case "everyone has a water buffalo"; negating that requires only that one person exist who does not have a water buffalo.  Since we seem to be dealing with some sort of poetry or lyrics anyway, I'd say that puts the expression well within the bounds of artistic license.

A:
Is the first construction somehow grammatically defensible, or is it just used because it better parallels as a negation of the sentence, "Everybody's got a water buffalo"?

The latter, more or less. Think of it as though quotes were placed around "everyone" in the second sentence, so that it becomes a collective entity: in mathematical terms, a set. It is a true statement (or at least the assertion to be proved) that "everyone" (the set of all people who might own a water buffalo) is not identical to the set that includes all owners of water buffalo.

A: Natural languages are not formal mathematical logic.
In formal logic, you're absolutely right: "Everybody does not have a water buffalo" would mean that everybody is sadly buffalo-less; it would not be the same as the negation of the statement "everybody has a water buffalo", which would be "not everbody has a water buffalo", or "somebody does not have a water buffalo".
However, with natural language, the litmus test of grammaticality is something like: if, within some speech community, a construction gets used, consistently, and understood, then it's grammatically correct, within that community.  And by that test, this usage is grammatically correct — I've come across it pretty widely, in speech and in writing, in the UK and US and Canada, in popular culture and academia.
…and for all that, it irks me a little too — this is a case where what's idiomatic seems to clash particularly badly with what's logical.  As Robusto and chaos show, one can make arguments for how it is in fact logical, but I don't think those are what this usage comes from; I strongly suspect it's just that one normally negates a clause by negating its main verb, and so that pattern gets used here too, even though that also slips the negation past a quantifier, which (as any fule kno) is Not Kosher.
It's this disparity between grammar and logic that makes much legal and technical prose a minefield — but on the other hand, the plasticity of language that gives rise to this is something extremely important and valuable in itself, which one would hardly want to give up.  You can't have your cake and eat it, I guess…

A: Logically, and I would argue, grammatically, "Not everyone has a water buffalo" means the same as "Someone does not have a water buffalo."  For most people, "Everyone does not have a water buffalo" means the same as "No one has a water buffalo."  For some people--in the context cited--"Everyone does not have a water buffalo" means the same as "Not everyone has a water buffalo" and "Someone does not have a buffalo."  This is confusing, though, and blurs a useful distinction.  While it may be found in the wild, I think it should be discouraged.


text:
Q: How can I access and adjust provider inside main() or runApp() to apply the value from firebase auth?   FirebaseAuth.instance.authStateChanges().listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

I have this function inside the main() {}. I want to change riverpod state when it detects changes to Firebase Auth. But, right now I am stuck because I can't access my riverpod state without using WidgetRef ref that uses widget.
If I put that into my main widget, then there is a bit of a delay. Or, is this not recommended to do - putting firebase.auth function inside the main()?

A: This function shouldn't be in your main func, what you can do is to modify your main.dart to look like this:
void updateState(WidgetRef ref) {
FirebaseAuth.instance.authStateChanges().listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
      ///update state with ref....

    } else {
      print('User is signed in!');

      ///update state with ref....

    }
  });
}
    void main() {
      runApp(const ProviderScope(child: MyApp()));
    }

    class MyApp extends ConsumerWidget {
      const MyApp({super.key});

      // This widget is the root of your application.
      @override
      Widget build(BuildContext context, WidgetRef ref) {

        WidgetsBinding.instance.addPostFrameCallback((_) {
         updateState(ref);
        });
        return MaterialApp(
          title: 'Flutter Demo',
          theme: MyTheme.appTheme,
          debugShowCheckedModeBanner: false,
          home: const HomeScreen(),
        );
      }
    }

Another approach could be to use an initstate in a ConsumerStatefulWidget, would look like:
  void updateState(WidgetRef ref) {
FirebaseAuth.instance.authStateChanges().listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
      ///update state with ref....

    } else {
      print('User is signed in!');

      ///update state with ref....

    }
  });
}
    void main() {
      runApp(const ProviderScope(child: MyApp()));
    }

    class MyApp extends ConsumerStatefulWidget {
      const MyApp({super.key});

      @override
      ConsumerState<MyApp> createState() => _MyAppState();
    }

    class _MyAppState extends ConsumerState<MyApp> {
      // This widget is the root of your application.

      @override
      void initState() {
        // TODO: implement initState
        updateState(ref);
        super.initState();
      }

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: MyTheme.appTheme,
          debugShowCheckedModeBanner: false,
          home: const HomeScreen(),
        );

  }
}


text:
Q: Packing problem I want to write a little helper utility to organize my digitized audiobooks collection.
I have a set of folders which I need to write to CDs. The folders can not be split: each folder goes onto one disk.
I want to fill the disks most efficiently:

*

*Minimize the number of disks, and

*The number of disks being equal, maximize the storage available of the least filled disk (80 + 20 remaining space is better than 50 + 50).

Which algorithm should I use?

A: This is called the Bin Packing Problem and is NP-hard, so there is not a simple algorithm to solve it.
The solution I found worked best (I ran a programming contest with a question almost identical to this), was to order the folders by size and put the largest folder that still fits onto the disc until it is full or all remaining folders are too large to fit in the remaining space.
This solves the problem quickly since after the sort the rest of the algorithm is O(n).
In the contest I ran, this resulted in 74 discs instead of the 79 that a naive solution would achieve for our largest test data set.

A: If you would like to pack files/folders on one CD-R disc, than you could do this optimally in pseudo-polynominal time. To do this, you have to round sizes of files/folders into sectors, and count sectors available on CD-R.
After this, we get discrete 1-D knapsack packing problem, which can be solved nicely using dynamic programming, with complexity O(n),
To be more specific:

*

*O(n) = O(nW) , cause W is constant in your case - W is amount of sectors on CD-R.

*n amount of files/folders.

For better performance you can always over-approximate size of sectors, example setup:

*

*over-approximated sector size 70k

*what makes 700M/70k = 10k of all sectors on CD-R

*which should compute in seconds when amount files less than (1G/10k=100k) 100k - n < 100'000

*in minutes when n < 10'000'000

What's more:

*

*solution can be nicely paralleled.

Maybe applying this algorithm in greedy manner "pack one cd, pack next cd" will do it's work?


text:
Q: Building a GUI in SharePoint 2013 I'm planning on building some business processes that use SQL as the data source and allow SharePoint 2013 users to interact with the data. I'm not sure how to give the users a GUI inside SharePoint. I can use InfoPath, but that's more for the data entry/collection etc. I can use an Access Web App, but there are too many drawbacks. Can't trigger workflows, cant access already existing databases, etc. The dashboards, PowerView, etc. are for reports and displaying data, not data manipulation.
What exactly is the preferred method of creating a GUI inside SharePoint 2013 to allow this type of data interaction?

A: If you're starting a new project, your best bet for forward compatibility is to develop it as an app - effectively, it'll be an asp.net application (or other web technology of your choice) that talks to SharePoint for one thing or other and has a few points that can be plugged in to SharePoint (App Parts) to consume/display the information.
You also have the alternative of creating External content types, which can be mappings of your tables into SharePoint. SharePoint will then generate the interfaces for you. Going with this, though, you might be locked out of the SPO market.


text:
Q: "In" or "On" when talking about the "last couple of days of someone's career"? As far as I understand in English you use "on", when talking about days, but is it still correct to use "on" in a sentences like the below one?

He has been running for four hours per day on average for 60 days in a row, but only 1 hour 20 minutes per day on the last 15 days of his career as a marathon runner.

or should we use "in" here?

He has been running for four hours per day on average for 60 days in a row, but only 1 hour 20 minutes per day in the last 15 days of his career as a marathon runner.

Which one is grammatically correct? Do we still use "on" here? The second sentence looks better to me, but I'm not so good at grammar. Can someone help me here with the explanation?


text:
Q: Which rule/guideline does this break (adding attributes to orm instance) I came across this code:
class MyModel(model.Model):
    def __init__(self, *args, **kwargs):
        self._log_data = dict()
        super(MyModel, self).__init__(*args, **kwargs)

    def send_data(self, obj):
        self._log_data['foo'] = obj.foo
        ...

I just have the feeling that adding ._log_data to an orm instance is wrong.
Up to now I just have this feeling that this implementation is not obvious and I am missing the matching term.
According to which rule/guideline is this not clean/good code?


text:
Q: Spark compiles with Eclipse on Windows but not javac on CentOS VM I am trying to compile the spark example from
https://spark.apache.org/docs/latest/quick-start.html
/* SimpleApp.java */

import org.apache.spark.api.java.*;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.Function;

public class Sparktest {
  public static void main(String[] args) {
    String logFile = args[0] + "/README.md"; // Should be some file on your system
    SparkConf conf = new SparkConf().setAppName("Simple Application");
    JavaSparkContext sc = new JavaSparkContext(conf);
    JavaRDD<String> logData = sc.textFile(logFile).cache();

    long numAs = logData.filter(new Function<String, Boolean>() {
      public Boolean call(String s) { return s.contains("a"); }
    }).count();

    long numBs = logData.filter(new Function<String, Boolean>() {
      public Boolean call(String s) { return s.contains("b"); }
    }).count();

    System.out.println("Lines with a: " + numAs + ", lines with b: " + numBs);
  }
}

if I copy the code into eclipse and add the
spark-assembly-1.3.1.2.3.0.0-2130-hadoop2.7.1.2.3.0.0-2130.jar

file to the build path through eclipse everything resolves and eclipse places my class files in the projects bin directory.
When I move the code over to my CentOS VM and execute the following line
javac -cp ./spark-assembly-1.3.1.2.3.0.0-2130-hadoop2.7.1.2.3.0.0-2130.jar:. ./Sparktest.java

in a directory with the jar file it complains about
 package org.apache.spark.api does not exist
 package org.apache.spark     does not exist
 package org.apache.spark.api.java.function does not exist

I have opened the jar file with 7zip on Windows, and know that that directory structure exists and all the class are in the jar. I'm still new to command line compiling java, but am pretty sure that there is some kind of directory structure thing going on here.
What combination of a javac command and directory structure do I need to get this to compile?


text:
Q: Java - Cannot get loop to recognize newly generated array values I am creating a program for class where I can bet on a horse race. The winners are determined by a method given to us by our professor. here is the method:
void readySetGo() {
    System.out.println(array.length);
    int length = array.length;
    Random rgen = new Random();
    for (int i = 0; i < array.length; i++) {
        int randomValue = i + rgen.nextInt(length - i);
        int randomElement = array[randomValue];
        array[randomValue] = array[i];
        array[i] = randomElement;
    }
}

I created a string-based menu using a while loop. In order to make things easier on myself, I created a cheat box that displays the winners before you place your bet.
System.out.print("Cheat: ");
System.out.println(Arrays.toString(racer.getArray()));

Here is the main method:
public static void main(String[] args) {
    race racer = new race();
    wallet balance = new wallet();

    Scanner input = new Scanner(System.in);
    double pick1;
    double pick2;
    String response;

    balance.setUSDbalance(200);

    racer.readySetGo();

    System.out.print("Cheat: ");
    System.out.println(Arrays.toString(racer.getArray()));

    System.out.println("Welcome to Charlie's Horse Racing Bets!");
    System.out.println("\nType one of the strings below and add your horse numbers after:");
    System.out.println("Example: 'Exacta Box 2 3'");
    System.out.println("\n=> Exacta");
    System.out.print("\nEnter your choice: ");

    response = input.nextLine();

    String words[] = response.split(" ");

    while (true) {
        if (words[0].equalsIgnoreCase("Exit")) {
            System.out.println("Thanks for playing! \nSee you soon!");
        } else if (words[0].equalsIgnoreCase("Exacta")) {
            pick1 = Double.parseDouble(words[1]);
            pick2 = Double.parseDouble(words[2]);

            boolean way1 = (pick1 == racer.first()) && (pick2 == racer.second());
            boolean way2 = (pick1 == racer.second()) && (pick2 == racer.first());
            if (way1 || way2) {
                System.out.println("You won the exact box");
                System.out.print("The winning order was: ");
                System.out.println(Arrays.toString(racer.getArray()));
                System.out.print("\nCheat for next round: ");
                racer.readySetGo();
                System.out.println(Arrays.toString(racer.getArray()));
                System.out.print("\nEnter your new choice: ");
                response = input.nextLine();
            } else {
                System.out.println("You chose the wrong order. Play again?");
                System.out.print("\nEnter your new choice: ");
                response = input.nextLine();
            }
        }
    }
}

The problem is that the system recognizes the correct user input the first time, but doesn't work at all the second time. Example:
Cheat: [4, 1, 3, 2]
Welcome to Charlie's Horse Racing Bets!

Type one of the strings below and add your horse numbers after:
Example: 'Exacta Box 2 3'

=> Exacta

Enter your choice: exacta 4 1
You won the exact box
The winning order was: [4, 1, 3, 2]

Cheat for next round: [3, 1, 4, 2]

Enter your new choice: exacta 3 1
You chose the wrong order. Play again?

A: As your code currently stands, you're only parsing the user's input the first time. Inside the loop you're reading the user's input again, but you're not updating the words variable based on the new input.
You should move this line inside your loop:
String words[] = response.split(" ");


text:
Q: Can you get blackboard letter N, R, etc., symbols for mathematical notation? The Special Characters palette includes many mathematical symbols, but I cannot seem to find blackboard bold versions of N, R, and Z, which are commonly used to denote the set of (respectively) the natural numbers, real numbers, and integers.
Right now, when I use the Special Characters palette and configure the Unicode section, and then look for the mathematical symbols, I find blackboard versions of A, B, and others, but inexplicably, certain characters including the N, R, and Z are missing. Here is a screenshot to show what I mean:

Are the blackboard characters available somehow, and I am missing something really obvious?

A: N is at U+2115, R is at U+211D... just as described in the wikipedia article you linked to.  Odd that they aren't in the normal ABC order.  But, they are there.

A: They are available for use directly without any configuration and here they are (and they are in a different Unicode range and hence missing from the range you posted):

*

*ℕ (hex 2115)

*ℝ (hex 211D)

*ℤ (hex 2124)

To type them, you might want to enable Unicode Hex Input and then hold the option key down while typing the 4 hex numbers above. Once you have them, you can add them to your favorites in the Special Characters palette (Control+Command+Space) or make keyboard spelling corrections (System Preferences, Keyboard, Text) to convert other abbreviations to these automatically.


text:
Q: How to use JWT without user and login? I'm making a simple file converter API in Node.js and I'm looking to avoid abuse in requests.
So I'm looking for a way to use JWT without userModel, login etc.
But I can't thing something online.
Thank you

A: we don't need a user or login to create JWT, we can generate a token with any kind of data. Simple just generate a token then pass it to the client after that on file convert request verify the token.
I found similar topic that might help you click here


text:
Q: Ksql Can't find any functions with the name 'COUNT_DISTINCT' I am running ksql cli using
docker run --net=host --interactive --tty confluentinc/cp-ksql-cli:latest http://localhost:8088

I have created a stream
CREATE STREAM RAW (`nodeId` INT,`data` STRING) WITH (kafka_topic='raw-data', value_format='JSON',partitions=3);

When I run query for count_distinct
SELECT COUNT_DISTINCT(`nodeId`) FROM RAW EMIT CHANGES;

It says
Can't find any functions with the name 'COUNT_DISTINCT'

The documentation specifies this function
https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/aggregate-functions/

A: As guided by @OneCricketeer solved by using latest docker images as described in https://ksqldb.io/quickstart.html


text:
Q: Yeoman project aborting due to not finding compass Following a tutorial from "JavaScript Frameworks for Modern Web Development" (ch. 3 on Yeoman) to setup Yeoman and scaffold a simple project:
Working in git-bash, I installed the Yeoman generator "modernweb" (cmd: npm install -g generator-modernweb) and successfully scaffolded my project (cmd: yo modernweb). When I run the grunt command to build and launch, I get the following error:
Warning: not found: compass  Use --force to continue  Aborted due to warnings
I can find the compass module in my node_modules folder and, if I look inside Gruntfile.js, I can see where grunt-contrib-compass is loaded and configured. So why is grunt not able to find Compass?
After some research I learned that Compass is a Ruby gem so I downloaded Ruby and installed SASS and Compass. Still unable to get this to work however.
I'm running version 3.10.6 of npm and 6.0.0 of node.
Github repo: https://github.com/ahvar/market-maps.git
I would greatly appreciate any help or advice.
Thank you!

A: Please ensure that the path the gems were installed is in your PATH.
For example, on Ubuntu: export PATH=$PATH:/var/lib/gems/1.8/bin (note that this exact command might not work depending on the OS and the ruby version you're using)


text:
Q: Accessing member parent function to child The problem is I have a Sort parent class (Sorter) and many children( merge,bubble,quick)
What I m trying to do is to access the function  "runOnce" which is a function in parent class.
Main.cpp
int main()
{
    fstream Data;
    Data.open("Test.txt",ios::in|ios::out);

    Sorter<int>* bubble = new BubbleSort<int>;
      Sorter<int>* quick = new QuickSort<int> ;
    Sorter<int>* merge = new MergeSort<int> ;
    vector<int> list;
     while(!Data.eof())
    {
      int temp;
     Data >> temp;
      list.push_back(temp);
    }
    Sorter<int>::runOnce(bubble, list);
    Data.close();
}

Sorter.cpp
#ifndef SORTER_H
#define SORTER_H
#include <vector>
using namespace std;

template <class T>
class Sorter {
    public:
        Sorter(){};
        virtual void sort(vector<T>&, int, int) = 0;
        double runOnce(Sorter<T>&, vector<T>&);

};

#endif // SORTER_H

but I m getting an error in main in line of

Sorter::runOnce(bubble, list);

it says:

no matching function for call to 'sorter::
  runOnce(Sorter*&, std:: vector < int , std :: allocator < int > > &)

And I tried to change it to be
bubble->Sorter->runOnce(bubble, list);

and it said

invalid use of Sorter< int >::Sorter

How can I fix this?

A: The function takes a Sorter&, not a Sorter*&. Dereference the pointer when passing it in, e.g:
Sorter<int>::runOnce(*bubble, list);

A: I Solved it with making runOnce a function in the main and calling it and it solved everything. Also I used the header files of the parent class in the children because I was using the cpp file.


text:
Q: Play Scala Action not receiving Multipart Form Data I want to upload a file into my web server using Play Scala Framework. But the server is responding Bad Request (400). I have separate client hosted in different web server.
I have made file upload action as minimul which is as follow:
  def upload() = Action.async(parse.multipartFormData) { request =>
    val body = request.body
    val optFile = body.files.headOption.map(_.ref.file)

    optFile match {
      case None => Future.successful(Ok("Missing Upload File").as("text/json"))
      case Some(file) => Future.successful(Ok("uploaded").as("text/json"))
    }
  }

The jQuery ajax request is set as follow:
var frm = new FormData() ;
frm.append('file', $('#uploadfiles')[0].files[0]);
    $.ajax( {
        url: 'http://localhost:9000/notes/upload',
  data: frm,
  processData: false,
        method: 'post',
        crossDomain: true,
  xhrFields: {
    withCredentials: true
  },
  contentType: 'multipart/form-data',
        success: function ( uploadStatus ) {
            alert('uploaded');
        },
        error: function ( error ) {
            alert('error');
        }
    } );

The update request is :
General
Remote Address:[::1]:9000
Request URL:http://localhost:9000/notes/upload
Request Method:POST
Status Code:400 Bad Request
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:3000
Content-Length:2148
Content-Type:text/html; charset=utf-8
Date:Mon, 28 Sep 2015 07:45:02 GMT
Vary:Origin
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:511
Content-Type:multipart/form-data
Cookie:connect.sid=s%3AWqi9VT3x3VctZ0_k1V0X5PWMJB0evrZG.8ux2doySJchVgqJC9tmt%2BOBMHCN%2FD1KBOXnfhGa%2BOfM
Host:localhost:9000
Origin:http://localhost:3000
Referer:http://localhost:3000/home
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
Request Payload
------WebKitFormBoundaryhrfHwiE7FJD7GgSo
Content-Disposition: form-data; name="file"; filename="README"
Content-Type: application/octet-stream

------WebKitFormBoundaryhrfHwiE7FJD7GgSo--

Although, the request header is content type is multipart/form-data. My action is not letting upload files. Even body of action is not executed.
Am I missing anything here or doing wrong? Any help will be of great appreciation. Thanks


text:
Q: Does Scrollr = Javascript? Are Scrollr and WOW just plain javascript? If so, why does everyone refer to it as if it's its own thing?
I've looked at a few tutorials, but at this point, it's all over my head, but I'm getting there. I've just started learning basic javascript (learning about arrays right now), and in my javascript handbook, it doesn't mention anything about Scrollr.

A: Welcome to the world of javascript. Skrollr is a javascript library for doing scrolling animations. A javascript book probably wouldn't mention Skrollr if it's talking about pure javascript. Skrollr is a tool that you can use to make your webpages have some fancy animations when you scroll on the page. There a literally hundreds, if not thousands of these kinds of libraries all over the web. However, some are known more than others. Similar libraries using jQuery can do the same things. Who knows, once you get the hang of javascript, maybe you'll be making your own.

A: They are both JavaScript libraries. Which means that yes, it's made of plain JavaScript. In the same way you make a .js file of function declarations and call them in another .js file. They are a bit more complicated than that, but the idea is the same.


text:
Q: Postgresql won't run on Mac How can this be? Up util now it hase been working fine.
$ brew services start postgresql
Service `postgresql` already started, use `brew services restart postgresql` to restart.

$ psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

How to fix that?
   Version psql (PostgreSQL) 11.1

A: Is there's a chance You've had PostgreSQL already installed before and a newer version appeared in brew so postgresql was upgraded to newer version?
If this is Your case Your datafiles are not compatible with newer version of postgresql and database upgrade is necessary. It should be safe to run it even if it's not needed.
PostgreSQL post install message:
==> Caveats
To migrate existing data from a previous major version of PostgreSQL run:
  brew postgresql-upgrade-database

To have launchd start postgresql now and restart at login:
  brew services start postgresql
Or, if you don't want/need a background service you can just run:
  pg_ctl -D /usr/local/var/postgres start```


text:
Q: Camera Roll/DCIM sorting This is a question that keeps coming up as I try to merge my older Rolls and the current Camera Roll on iOS11.
What I've done:
-Prepared old Camera Rolls for import (EXIF fixes for dates, setting Date Created/Modified to the same dates).
-Merged new CR with names adjusted to avoid conflicts
-Copied to DCIM
-Nuked Photos.sqlite db
As expected, Moments picks up the correct date (as it should), but Camera Roll is weird.
It appears that files are sorted by date, but ONLY per each folder. E.g. photos in 100-111APPLE show up sorted by dates taken by each folder, but overall in the camera roll they are not. Is there a reason sorting is applied per folder?
Also, for some reason 109APPLE appeared at the very end of the camera roll - why could that be?
I was going through the Photos db (wow it got much messier since iOS 6), and couldn't deduce the sort order in the Camera Roll. Previously, the general belief was it is sorted by Date Created or Date Added, but when I sort the db by these parameters, photo order is different from what I see in the roll.
To make matters worse, not all (per-folder) sorting appears to be correct, as I have at least 2 photos from Jan12 that follow Apr12, and these 2 photos go from 17Jan12 to 16Jan12. I've tried sorting the folder in Explorer by pretty much all the attributes Windows gives me, and could not replicate this order. So my question is, what is going on? What is the primary key used for sorting the db in iOS 11?
P.S. I am aware I can manually run an sql query to copy ZDATECREATED to ZDATEADDED, but I want to understand, what is going on in the first place. Also not sure how manual sql edits would impact future exports to iCloud Photo Library.
TLDR: iOS Camera Roll sorting is weird - by what attribute is it sorted? When I sort the sql table by ZDATEADDED it is not the same order as on device, however if I run a manual query to set ZDATEADDED to ZDATECREATED, it seems to sort by the updated Date Added/Date Created timestamp, making it look like ZDATEADDED is indeed the primary sort key.    Where does iOS even get Date Added (not from file/EXIF?), and how do I import photos into the camera roll preserving/setting the correct Date Added?
Thanks for any help.

A: Right, the way iOS generates ZDATEADDED appears to be dependent on indexing order, and hence naming (correct me if I am wrong).
So if you want the Camera Roll to be ordered correctly by EXIF/file data, you'd need to bulk rename pre-sorted files in order, and then import.
Thank you iOS Photos.app for being such a delight


text:
Q: Oculus Quest Issue with UnityWebRequest I am trying to make a unityWebRequest to an API and everything runs smoothly on a normal unity app, but when I transfer the application to my oculus quest as soon as the method "checkCode()" is called triggering the GetAuthRequest() method that does the unityWebRequest the oculus application crashes.
I've tried rewriting the code in a couple of different ways and nothing seems to be fixing the issue. My Quest has internet access and I believe I have Android SDK installed.
public void CheckCode()
{
    StartCoroutine(GetAuthRequest("http://myURL/", attemptedCode));
}

IEnumerator GetAuthRequest(string uri, string attemptedCode)
{
    setValue("IN_REQ");
    using (UnityWebRequest webRequest = UnityWebRequest.Get(uri + attemptedCode))
    {
        //// Request and wait for the desired page.
        yield return webRequest.SendWebRequest();
        if (webRequest.isNetworkError)
        {
           setValue("NET_ERROR");
        }
        else
        {
           if (webRequest.downloadHandler.text.Equals("true"))
           {
               ClearCode();
               setValue("Authenticated!");
           }
           else
           {
                ClearCode();
                setValue("Error...");
           }
       }
   }
}

A: try using "https://myURL/" instead of "http://myURL/"


text:
Q: Issue with switch case in Recyclerview as it opens wrong activity when items are filtered I have used a switch case in a RecyclerView to open different Activitys. It works perfectly when items are not filtered. But when the items are filtered, items show wrong Activitys. I think it happens because when items are filtered they get upper position. I don't know how to come over this issue.
public void onItemClick(int position)  {
    switch (position ){
        case 0:
            Intent pope = new Intent(this, Pope.class);
            startActivity(pope);
            break;
        case 1:
            Intent austin = new Intent(this, AlfredAustine.class);
            startActivity(austin);
            break;
        case 2:
            Intent housman = new Intent(this, AlfredHousman.class);
            startActivity(housman);
            break;
        case 3:
            Intent tennyson = new Intent(this, LordTennyson.class);
            startActivity(tennyson);
            break;
        case 4:
            Intent swinburn = new Intent(this, AlgernonSwinburn.class);
            startActivity(swinburn);
            break;
        case 5:
            Intent lang = new Intent(this, AndrewLang.class);
            startActivity(lang);
            break;
    }
}

A: It looks like you are using a switch case on the item position. This can lead to problems when your adapter is modified. When you 'filter' your adapter (however you are implementing it), positions of the items can change and this will lead to your switch case not working as expected.
Consider using switch case on an item's parameter or if you must use position, store the position in your item object instead of relying on the adapter position.

A: This looks like a software design issue question. This is the way I would solve that. In the Adapter probably you have a list of models. Something like this:
List<MyModel> modelList = new ArrayList<>();

So in MyModel class you should define an id for the model. E.e:
public class MyModel {
  @NonNull
  private int id;
  ....
}

Then the switch will be something like:
public void onItemClick(int position)  {

    switch (models.get(position).getId()){
        case POPE_ID:
            Intent pope = new Intent(this, Pope.class);
            startActivity(pope);
            break;
        case ALFRED_ID:
            Intent austin = new Intent(this, AlfredAustine.class);
            startActivity(austin);
            break;
        case ALFRED_HOUSMAN_ID:
            Intent housman = new Intent(this, AlfredHousman.class);
            startActivity(housman);
            break;
        .....
    }
}


text:
Q: What does it means a Media Set with 26 weeks Overwrite protection period and 1 year appendable period? On Symantec Backup Exec, I see there is a Media set with 26 Weeks Overwrite protection period and 1 year appendable period.  On all the help information I was able to find the appendable period is usually smaller than the overwrite period.
Thanks.

A: Backup Exec "protects" media from being overwritten with the "Overwrite Protection Period". So, in your question, a media will not be permitted to be overwritten until 26 weeks have elapsed since the completion of the last write operation on that media.
Because you might want to continue to append to a media after the initial write (but not actually overwrite what's already there), Backup Exec tracks a separate "Appendable" period. For 1 year after the last write operation completes on a given media, in your question, additional data can be appeneded to the media.
Bear in mind that any appending causes additional writes to the media, and any future checks as to whether the media is able to be appended-to or overwritten will be based on that last write time.
Typically, where you see this used is in libraries where you have, say, multiple tape cartridges loaded and you want to do "one tape per day" type rotations. Let's imagine a library with 5 tapes in it and a once-per-weekday backup rotation. You'd put the media into a set with an "Overwrite Protection Period" of 6 days.
You load the library with tapes "1" thru "5", all of which are brand new and are overwritable.

*

*On Monday evening at 7PM the library chooses tape "1" (though it won't necessarily choose the numerically lowest number-- I'm just doing that to make the example easier) and writes to it. That tape is now overwrite-protected for 6 days-- 'til sometime after 7PM on the next Sunday.

*On Tuesday evening at 7PM the library choose tape "2" and writes to it. That tape is now overwrite-protected until sometime late on the following Monday. The library can't choose tape "1" for this operation because it's overwrite protected.

*This continues until Friday, when all the tapes in the library are overwrite protected except "5", forcing the library to choose that one.

*When the following Monday's backup rolls around, the library is forced to use tape "1" because all the other tapes are still overwrite protected. From this time on, the tapes come off of overwrite protection less than 24 hours before they're actually needed, but no sooner.
You can imagine how this could apply to multiple sets of medias (rotating an entire week in and out of the library, etc) with a little mental extrapolation.
The append period is a bit more involved. Take the same scenario above, but say that you run an "incremental" backup during the day each day, Tuesday thru Saturday at noon, and want that incremental backup to be appended to the tape used for the prior night's full backup. You'd set an append period of, say, 20 hours.

*

*On Monday at 7PM the backup runs normally. Tape "1" is used and marked overwritable on the following Sunday evening. It remains appendable until late afterooon on Tuesday.

*At noon on Tuesday the incremental backup runs. Since this is an append job, the library choose a tape that's "appendable". Because tape "1" is still appendable (the append period has expired for all the other tapes), the library chooses tape "1" and appends to it.

*Tuesday night's full backup runs on tape "2", just like we'd expect.

*Wedneday at noon, the incremental backup runs. Since tape "1" became non-appendable during Tuesday afternoon it cannot be used. The library chooses tape "2" since it became appendable after the completion of the Tuesday night backup.
There's a crash course in Backup Exec media protection.  >smile<

A: My guess is that:

*

*Overwrite protection period is the lenth of time that needs to expire before a bit of data is overwritten

*Appendable period is how long you can "add on" to the backup set. Note that "adding on" to the backup set does not overwrite any of the data on the set, it just adds to it.

The of the backup/media set as a file. To do the backup the first time it will write all data to that file. To save disk and processing time, it only adds changes to those original files to the backup set, it does not actually change the backup media.
This means that if someone creates a file and then deletes it, you can still restore it from the backup set.


text:
Q: Needing PHP to show multiple rows, but it is only showing me the last row The output from the code below only shows me the last row of my data. Any ideas? I want it to show me all rows.
Here is the code:
$FinalSet = array();
while ($ResultSet = mysqli_fetch_array($Query)){

 $FinalSet = array(
'idExam' => $ResultSet[0],
'SubjectName' => $ResultSet[1],
'ExamTime' => $ResultSet[2],
 'ExamDate' => $ResultSet[3],
 'IntakeCode' => $ResultSet[4],
'Scope' => $ResultSet[5],
);
 }

 echo json_encode($FinalSet);

A: You have to add them to your array. At the moment you are replacing the array itself.
You can do this by using
$FinalSet[] = array(

instead of
$FinalSet = array(

You can also use array_push, which does the same:
array_push($FinalSet, array(......));

A: You are already initialized $FinalSet = array(); and you are storing data single index so your data has been override and you found last row your data. Now you can use $FinalSet[] instead of $FinalSet. You will get all data.

A: Try this, You can use $FinalSet[] or array_push() to push the array content into the main array. Currently, you are jut replacing the same array respective of the loop counts. So you getting the last array value in the variable.
$FinalSet[] = array(
     'idExam' => $ResultSet[0],
     'SubjectName' => $ResultSet[1],
     'ExamTime' => $ResultSet[2],
     'ExamDate' => $ResultSet[3],
     'IntakeCode' => $ResultSet[4],
     'Scope' => $ResultSet[5]
 );

instead of
$FinalSet = array(
     'idExam' => $ResultSet[0],
     'SubjectName' => $ResultSet[1],
     'ExamTime' => $ResultSet[2],
     'ExamDate' => $ResultSet[3],
     'IntakeCode' => $ResultSet[4],
     'Scope' => $ResultSet[5],
 );

A: Try the following in the loop:
while (...) {
   $FinalSet[] = array(...);
}


text:
Q: Default destructor when using pointer to base class class A
{
    int a;
};

class B : public A
{
    int b;
};

int main(void)
{
    A * p = new B;
    delete p;   // (1)
    return 0;
}

In the above code both classes have default compiler-generated destructors. Both classes also have only Plain Old Data as members so I don't need manually written d'tors which would free any resources. So my question is - after the call in (1) will the default destructor free the entirety of B's instance or will there be any memory leaks? I know that I could use a virtual destructor here but I'm not sure how default d'tors behave.

A: What you are trying to do invokes undefined behavior, so declaring A destructor as virtual can be considered mandatory.
delete p

Will try to delete p as an instance of A but since the destructor is not declared virtual the correct runtime implementation is not called.
Mind that this doesn't happen when you don't have a pointer but just a concrete object, eg
A a = B();

Because object slicing occurs before, so when a exits the scope it's just an A


text:
Q: Eclipse git plugin, tag double click Im a bit new on Eclipse and git. Happend to double click on my latest TAG. See screen shot.
What does the black/white marker mean and how can I get rid of it without damaging my TAG?
Thanks!

A: The little black marker means that you're currently checking out that branch.
Best EGit tutorial, right here.
My suggestion is you allocate a Saturday afternoon, and follow this tutorial carefully. By the end of the day, you'll be a damn pro with EGit. :) Good luck.


text:
Q: Show that the question "Is there life beyond earth?" is decidable I was given a question to prove that there exists a turing machine that solves the question

Is there life beyond earth?

and is decidable. I actually don't understand how to show a turing machine decides this.
Thanks.

A: This is a trick question, the idea being that the answer doesn't depend on the input (or rather, has no input; but Turing machines are usually assumed to have an implicit input). If the answer is YES, then the Turing machine that prints YES solves the problem. The same goes for the answer NO. Of course, we don't know which of these two Turing machine solves the problem, but we know that one of them does.
In contrast, suppose you wanted to solve the halting problem in this way. Then you would need a table where for each program you record whether it halts on the empty input or not. This table is infinite, and so this approach doesn't work.


text: Q: The Lie group corresponding to the Lie algebra $\frak{so}_n$ As is standard knowledge - there is a bijective correspondence between compact simply connected simple Lie groups and complex simple Lie algebras. So what is the The Lie group corresponding to the Lie algebra $\frak{so}_n$? Is it the special orthogonal group $SO_n$ or is it the spin group $\mathrm{Spin}_n$? Since the special orthogonal group is not simply-connected, the corresponding Lie group should be $\mathrm{Spin}_n$. But it seems weird to me that the notations do not match . . . I am afraid that I missing something here.


text:
Q: How to delete file on Windows Remote Server? How to delete specific file on Windows Remote Server using Python?
I'm able to connect to remote Windows Server using WMI, but not sure how to delete file remotely on windows server.


text:
Q: My iPhone front camera won't work (it freezes) I dropped my phone in the water and everything works, except my front facing camera. When I go to change from back to front, it freezes and won't let me go back to the back camera, and it's blurry.

A: Deleted Pinterest, suddenly works for me


text:
Q: How to play NSData audio or video in iOS? I need to present an audio or video content in iOS.
Unfortunately, I do not receive the audio/video as URL, but as NSData with content-type (MIME type).
It seems UIWebView does not play the audio/video data properly when using the loadData:MIMEType:textEncodingName:baseURL:
only when using the loadRequest: (thanks Apple for this wonderful controller)
So I wanted to save the NSData to a temp file, but I don't have the file extension (just MIME type).
What is the best way to accomplish this?
Maybe implement an audio/video player using some other iOS controls?
Thanks in advance.

A: make a method that mapps the MIME type to the suitable extension
-(NSString *)getExtenstionFromMimeType:(NSString *)mimeType
{

   if ( [mimeType isEqualToString:@""video/mp4"] )
       return @"mp4";
   else if  ( ..... )
         and so on

}

you can also use the MPVideoPlayerController to play audio video but you will also need the source media as a url or a local file path

A: If anyone wants to know here is the solution:
You need to use UTType functions
declared in a framework called MobileCoreServices.
The basic idea is to get the UTI from the MIME type, then get the extension from the UTI:
MIME-Type --> UTI --> file-extension.
An example of MIME-Type to UTI conversion can be found here.


text:
Q: Vaadin: Collapse all Tabs in an Accordion I'm wondering if there's a way to collapse all tabs on an accordion. Found no such method in TabSheets either. I would like to basically display the tab names and show the content when I select the tab. By default the first tab is always opened.
Thanks in advance!

A: Last time I checked, I found no way either.  You can workaround this by adding an "empty" Tab.  Combined with some styling, that worked quite well.  E.g.:
@Grapes([
@Grab('org.vaadin.spring:spring-boot-vaadin:0.0.3'),
@Grab('com.vaadin:vaadin-server:7.4.0.beta1'),
@Grab('com.vaadin:vaadin-client-compiled:7.4.0.beta1'),
@Grab('com.vaadin:vaadin-themes:7.4.0.beta1'),
])
import org.vaadin.spring.VaadinUI
import com.vaadin.server.VaadinRequest
import com.vaadin.ui.*

@com.vaadin.annotations.Theme('valo')
@VaadinUI
class MyUI extends UI {
    protected void init(VaadinRequest request) {
        setContent(new Accordion().with{ c->
            ['A','B','C'].each{ c.addTab(new Label("Some $it"), it) }
            c.addTab(new CssLayout(), "[x] close all") // XXX
            return c
        })
    }
}


text:
Q: Available suitable solutions for web app importing DWG || DXF files? I need directions to what are possible solutions for web app handling autoCAD files(importing).
The app will have to render 2D architectural plans from imported autoCAD files with possibility to move walls, furniture etc.
I was thinking about using Unity with webGL build, as I already know it, but it's not a perfect tool for simple 2d application and there will be a problem(as always) with external .NET DWG/DXF handling libraries(old mono won't compile most(if not every) of libraries out there).
As an alternative I found this nice little engine - http://www.babylonjs.com/ - which also builds webGL apps, but much smaller and many times faster loading. But I have no idea if it's possible to use external libraries for it to handle autoCAD files. Any suggestions? Thanks for your time.

A: You can use Forge translator and viewer on your website. The rest service, Model Derivative, translate a .DWG into a json stream that can viewed on browsers with uses WebGL and Three.js.
There are many examples at this github org, but this sample implements something similar to what you described for Revit models.


text:
Q: Plotting continuous and discrete data in the variable I am working to plot a dataset of snow depth in a grid, with depth as a continuous variable.
But, some plots in the grid were partially covered. These are divided into plots >50% and <50% covered in the same variable as the depth measurements, marked as 'over' and 'under'.
When I try to plot the data with ggplot 2 using:
myplot <- ggplot()+
geom_tile(data=table, aes(x=factor(Row), y=Colum, fill= Snow_depth))+
scale_fill_gradient(low="#0066CC", high="#FF3333")

I of course get the error:
Error: Discrete value supplied to continuous scale

How can I include this discrete data and give them a clear colour label, so all the information is shown in the same image?

A: Edit:
After thinking about it some more, one approach could be to use a pattern from ggpattern on the covered plots:
set.seed(3)
table <- data.frame(Row = rep(1:9,times=9), Colum = rep(1:9,each=9),
                   Snow_depth = runif(81,10,100),
                   Cover = as.logical(round(runif(81,0,1),0)))

#remotes::install_github("coolbutuseless/ggpattern")
library(ggpattern)
library(ggplot2)
ggplot(data=table, aes(x=as.factor(Row), y=as.factor(Colum))) +
  geom_tile(aes(fill= Snow_depth)) +
  scale_fill_gradient(low="#0066CC", high="#FF3333") +
  geom_tile_pattern(aes(pattern_alpha = Cover),
                    fill = NA, pattern = 'crosshatch',
                    pattern_fill = "black",
                    pattern_angle = 45,
                    pattern_density = 0.1,
                    pattern_spacing = 0.025,
                    pattern_key_scale_factor = 0.5) +
  scale_pattern_alpha_discrete(range = c(0,0.5), labels = c("No","Yes")) +
  labs(x = "Row",y = "Column")


text:
Q: How does this EQ circuit work? This is a "basic transformerless 5-band EQ using gyrators" schematic.
I think I understand the top part (pots remove the frequency from either input of the op-amp, either increasing or decreasing it from the output), but I don't understand what the bottom part is supposed to do, and why it requires those op-amps.

A: Gyrator is a theoretical circuit element (like ideal voltage sources, resistors, capacitors etc... ) which has simple and well defined operation equations. Read them here https://en.wikipedia.org/wiki/Gyrator
The same article presents ways to have approximately the same operating equations with practical circuits. You seemingly know one such circuit, the opamp gyrator.
The same article shows as a practical application the "simulated inductor".  In your example the simulated inductors are used in series LC resonators. A multiband equalizer made with real LC resonators would need plenty of inductors which would cost much more than simulated inductors.
The capacitors connected to the vipers of the potentiometers are the capacitive halves of the resonators.

A: Here is the behavior of one "block", measured input impedance.
One can easily retrieve essential data.

And an approximative "equivalence" of these two circuits ...


text:
Q: Empty array at any search using FOSElasticaBundle in Symfony2 I have a problema that I cannot sort it out, I have tried everyhing I have found on the web for this.
So, I am fairly new in Symphony, I did not have any problems so far until I needed to implement a search engine. I have looked and found out that Elastico was a very good choice and I decided to implement it.
I have installed it using composer, no problems. For the very most basic of search, my config looks like this :
fos_elastica:
 clients:
    default: { host: localhost, port: 80 }
 indexes:
    search:
        client: default
        types:
            story:
                mappings:
                    name: ~
                persistence:
                    driver: orm
                    model: Website\WebBundle\Entity\Story
                    provider: ~
                    listener: ~
                    finder: ~

I do not have any problems generating the data with php app/console fos:elastica:populate. The result are corectly inserted ( matching number or entries with the database entries ).
So, my problem is cannot display ANY results. I always have empty array as result for :
$finder = $this->container->get('fos_elastica.finder.search.story');
$results = $finder->find('name');

Also empty result for :
$repositoryManager = $this->container->get('fos_elastica.manager');
$repository = $repositoryManager->getRepository('WebsiteWebBundle:Story');
$results = $repository->find('name');
And I have a record in the database with the name 'name' so I should get results. Searching for a letter doesn't work also.
So, can anybody tell me what I am doing wrong ? Or is there any way of displaying all the results so I can see that the results are there and only the searching fails ?
Thanks

A: You miss your mapping config.
You have to specify the attributes of the Class story to be indexed
ie:
mappings:
      id:
       type: integer


text:
Q: Spring WebClient: Passing username and password in request body to get a token Following the Spring WebClient tutorial here I'm trying to pass username and password in the request body (no basic auth) to the API endpoint as it expects these as parameters.
I've tested in Postman supplying the username and password as separate fields in the body and setting the contentType as application/x-www-form-urlencoded. This results in getting the expected token, however when I print out the response below using my implementation using WebClient, it prints:
{"error":"invalid_request","error_description":"Missing form parameter: grant_type"}

|
TcpClient tcpClient = TcpClient.create().option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECTION_TIMEOUT_MILIS)
                .doOnConnected(connection -> {
                    connection.addHandlerLast(new ReadTimeoutHandler(CONNECTION_TIMEOUT_MILIS, TimeUnit.MILLISECONDS));
                    connection.addHandlerLast(new WriteTimeoutHandler(CONNECTION_TIMEOUT_MILIS, TimeUnit.MILLISECONDS));
                });

        WebClient client = WebClient.builder().baseUrl(BASE_URL)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient))).build();

        LinkedMultiValueMap<String, String> multiMap = new LinkedMultiValueMap<>();

        multiMap.add("username", username);
        multiMap.add("password", password);

        BodyInserter<MultiValueMap<String, Object>, ClientHttpRequest> inserter = BodyInserters.fromMultipartData(multiMap);

        WebClient.RequestHeadersSpec<?> request = client.post().uri(API_CALL_GET_TOKEN).body(inserter);

        String response = request.exchange().block().bodyToMono(String.class).block();
        System.out.println(response);

A: Providing .accept(MediaType.APPLICATION_JSON) provided the response:
WebClient client = WebClient.create();

LinkedMultiValueMap<String, String> credentials = new LinkedMultiValueMap<>();

credentials.add("username", username);
credentials.add("password", password);

String response = client.post()
      .uri(BASE_URL + API_CALL_GET_TOKEN)
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .accept(MediaType.APPLICATION_JSON)
      .body(BodyInserters.fromFormData(credentials))
      .retrieve()
      .bodyToMono(String.class)
      .block();

return response;


text:
Q: Show that a finite union of compact subspaces of a topological space $X$ is compact. I am aware that there is a similar question elsewhere, but I need help with my proof in particular. Can someone please verify my proof or offer suggestions for improvement?

Show that a finite union of compact subspaces of a topological space $X$ is compact.

Let $A_1, \ldots, A_n$ be compact subspaces of a topological space $X$. Let $\mathscr{B}$ be a collection of open sets of $X$ which covers $\displaystyle{\bigcup_{i=1}^n A_i}$. Then, $\mathscr{B}$ covers $A_i$ for each $1 \leq i \leq n$. Since each $A_i$ is compact, we can choose a finite subcover $\mathscr{B}_i$ of $A_i$. But then, $\displaystyle{\bigcup_{i=1}^n \mathscr{B}_i}$ forms a finite subcover of $\displaystyle{\bigcup_{i=1}^n A_i}$.

A: There is nothing wrong with your proof. It´s  ok.

A: everything is  ok ...nice proof


text:
Q: IIS Missing MIME cshtml When I run my application locally ( VS2013 installed ) everything works fine, but when I deploy the files to another server with only basic IIS installed I get missing CSHTML missing.
Error details:
 HTTP Error 404.3 - Not Found
 The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

 Module
 StaticFileModule

 Notification
 ExecuteRequestHandler

 Handler
 StaticFile

 Error Code
 0x80070032

 Requested URL
 http://localhost:80/myapp/Default.cshtml

 Physical Path
 C:\inetpub\wwwroot\myapp\Default.cshtml

 Logon Method
 Anonymous

 Logon User
 Anonymous

...if I add the MIME type it literally just renders some text of my razor view.
I feel like I'm missing some root dependency in my nuget packages that are deployed that is installed by vs out of the box.
My project references look like: http://www.screencast.com/t/BKoB4MSWX and http://www.screencast.com/t/NOOMxD3sYn ... anyone know what im missing?
Updates:
No MVC components are installed, I'm not using any MVC just this one page is cshtml.  I also don't have any razor dependencies installed at the moment.  My app is targeted at .net 4.5.1 .  I'm using IIS 7.5.  App pool is integrated 4.0 on Windows Server 2008 R2

A: Your problem is probably that you have Razor dependencies in your GAC, but when you deploy they are not there on the remote server.
Install the Web Pages package: Install-Package Microsoft.AspNet.WebPages
You might be missing more things, but that's the minimal starting point

A: IIS returns 404 for ASP.NET MVC3 file (.cshtml)
Enable runAllManagedModulesForAllRequests:
<modules runAllManagedModulesForAllRequests="true" />

Is this what you're looking for?

A: Check if 'CSHTML' is mapped in IIS Manager. From IIS Manager, select the site you want to add the MIME to from the Connections left pane,
In the Home pane, double-click MIME Types.
In the MIME Types pane, click Add... in the Actions pane.
    mimeMap fileExtension=".cshtml" mimeType="application/x-cshtml"
Alternatively, you could use the conf file applicationHost.conf C:\Windows\System32\inetsrv\Config:
•   And running from command: aspnet_regiis –iru
•   C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -iru


text:
Q: jQuery - how to show dropdown selected values through textbox in dynamic table I created dynamic table and i want to show the selected dropdown values in textbox, i tried many ways using javascripts and jQuery but its not working in my dynamic table..
I just want to pass the values in my text box
Can you help me please?

Note: Pass the values only table dropdown..

here is my detailed Fiddle
Fiddle

Jquery code for creating dynamic table

$(document).ready(function() {
  $("#cashacc_sel").html($('#cashacc').html());
  var i = 1;
  $("#add_row").click(function() {
    var oSelectedValue = $('#cashacc').val();
    $('#addr' + i).html("<input name='cashpayment[" + i + "].name' type='text' placeholder='Enter code' id='cashacc_code' class='form-control input-md'/>	<select class='form-control input-md' name='cashpayment[" + i + "].name' id='dynamic_sel'><option>Choose an items</option></select>	");
    // {/* " + (i + 1) + "	 */}
    $("#cashacc_sel").find("select").append().appendTo($("#dynamic_sel"));
    $('#tab_logic').append('

');
    // $('#cashacc_sel').append($('#dynamic_sel').html());
    $("select[name='cashpayment[" + i + "].name']").html($('#cashacc option:not(:selected)'));
    $("#cashacc").html($('#cashacc_sel').html());
    $("#cashacc").val(oSelectedValue);
    i++;

  });
  $("#delete_row").click(function() {
    if (i > 1) {
      $("#addr" + (i - 1)).html('');
      i--;
    }
  });

});

  Cash Account :
  <select class="form-control selectsch_items" name="cashacc" id="cashacc" required>
    <option value="">Choose an items</option>
    <option value="acc1">Account 1</option>
    <option value="acc2">Account 2</option>
    <option value="acc3">Account 3</option>
  </select>

              Account Code

              A/c Name*

          Add RowDelete Row

              <input type="text" id="cashacc_code" name='cashacc_code' placeholder='Enter A/c Code' class="form-control" />

              <select class="form-control" name="cashacc_sel" id="cashacc_sel">
                <option value="">Select A/c name</option>
                <option value="1">Plumz</option>
                <option value="2">Plumz 2</option>
                <option value="3">Plumz 3</option>
              </select>

A: I think you need something like this.

$(document).ready(function() {
  $("#cashacc_sel").html($('#cashacc').html());
  var i = 1;
  $("#add_row").click(function() {
    var oSelectedValue = $('#cashacc').val();
    $('#addr' + i).html("<input name='cashpayment[" + i + "].name' type='text' placeholder='Enter code' id='cashacc_code' class='sel_text form-control input-md'/>	<select class='sel_sel cashacc_sel form-control input-md' name='cashpayment[" + i + "].name' id='dynamic_sel'><option>Choose an items</option></select>	");
    // {/* " + (i + 1) + "	 */}
    $("#cashacc_sel").find("select").append().appendTo($("#dynamic_sel"));
    $('#tab_logic').append('

');
    // $('#cashacc_sel').append($('#dynamic_sel').html());
    $("select[name='cashpayment[" + i + "].name']").html($('#cashacc option:not(:selected)'));
    $("#cashacc").html($('#cashacc_sel').html());
    $("#cashacc").val(oSelectedValue);
      bindScript();
    i++;

  });
  $("#delete_row").click(function() {
    if (i > 1) {
      $("#addr" + (i - 1)).html('');
      i--;
    }
  });
    bindScript();
});

function bindScript() {
  $(document).find('.sel_sel').on("change", function () {
      $(this).parent().parent().find('.sel_text').val($(this).val());
  })
}

  Cash Account :
  <select class="form-control selectsch_items" name="cashacc" id="cashacc" required>
    <option value="">Choose an items</option>
    <option value="acc1">Account 1</option>
    <option value="acc2">Account 2</option>
    <option value="acc3">Account 3</option>
  </select>

              Account Code

              A/c Name*

          Add RowDelete Row

              <input type="text" id="cashacc_code" name='cashacc_code' placeholder='Enter A/c Code' class="form-control sel_text" />

              <select class="form-control sel_sel" name="cashacc_sel" id="cashacc_sel">
                <option value="">Select A/c name</option>
                <option value="1">Plumz</option>
                <option value="2">Plumz 2</option>
                <option value="3">Plumz 3</option>
              </select>

A: You need to use clone and not IDs

$(function() { // on page load
  $("#add_row").on("click",function() { // on click of add
    $("tbody").append($("tbody tr").first().clone()); // clone and append
    $("tbody tr").last().find("select").val($("#cashacc").val()); // set the value
  });
  $("#delete_row").on("click",function() {
    if ($("tbody tr").length > 1) { // remove last entry if more than one
      $("tbody tr").last().remove()
    }
  });
  // copy the value from select to input field
  $("tbody").on("change","[name=cashacc_sel]",function() {
    $(this).closest("tr").find("[name=cashacc_code]").val(this.value);
  })
});

  Cash Account :
  <select class="form-control selectsch_items" name="cashacc" id="cashacc" required>
    <option value="">Choose an item</option>
    <option value="acc1">Account 1</option>
    <option value="acc2">Account 2</option>
    <option value="acc3">Account 3</option>
  </select>

            Add Row
            Delete Row

              Account Code

              A/c Name*

              <input type="text" name='cashacc_code' placeholder='Enter A/c Code' class="form-control" />

              <select class="form-control" name="cashacc_sel">
                <option value="">Select A/c name</option>
                <option value="acc1">Plumz</option>
                <option value="acc2">Plumz 2</option>
                <option value="acc3">Plumz 3</option>
              </select>


text:
Q: How to configure NGINX with php-fpm on mac Been facing this issue now for quite a long time. New on nginx so need help
Basically Im trying to configure nginx settings to use my PHP projects. Before I was using Apache (MAMP) to run all my php proj. Now im shifting to nginx. I have configured all possible settings needed in nginx.conf file (have a look below). But still im facing rather the same issue and im not able to correctly address it for some reason.
...nginx default settings
nginx.conf
server{
    listen 80;

    error_log /usr/local/etc/nginx/log/freespinswizard-error.log;
    access_log /usr/local/etc/nginx/log/freespinswizard-access.log;
    access_log off;

    #location / {
        root   /Applications/MAMP/htdocs/freespinswizard/;
        index  index.php index.html index.htm;
    #}

    #root /Applications/MAMP/htdocs/freespinswizard/;
    #index index.php index.html index.htm;

    server_name www.freespinswizard.com freespinswizard.com;

    location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml|otf)$ {
        access_log        off;
        log_not_found     off;
        expires           30d;
        add_header Pragma public;
        add_header Cache-Control "public";
    }

    location ~ \.php$ {
        try_files $uri =404;
        #fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #fastcgi_pass unix:/tmp/freespinswizard.sock;
    fastcgi_pass 127.0.0.1:9000;
    #fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
        #fastcgi_buffer_size 128k;
        #fastcgi_buffers 256 16k;
        #fastcgi_busy_buffers_size 256k;
        #fastcgi_temp_file_write_size 256k;
        include fastcgi_params;
        add_header X-Frame-Options SAMEORIGIN;
    }

    rewrite ^/offers/([^/\.]*)/?$ /page-handler.php?story-page-slug=$1 break;
    rewrite ^/ab/([^/\.]*)/?$ /page-handler.php?group-key-name=$1 break;

    if ($request_uri !~ "(^/scripts/)"){
        rewrite ^/.*.php.* /page-handler.php break;
    }

    if ($request_uri !~ "(^/.*\..*)"){
        rewrite ^(.*)$ /page-handler.php break;
    }
}
......nginx default settings continued

Error im facing in log file regarding the website im trying to host
2020/11/04 20:14:49 [error] 21300#0: *1 kevent() reported that connect() failed (61:
Connection refused) while connecting to upstream, client: 127.0.0.1, server:
www.freespinswizard.com, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000",
host: "freespinswizard.com"

I have no clue what is wrong in my configurations. Please any kind of help would be appreciated, thnx in advance.


text:
Q: False sharing and Java memory model I am using the example described here https://jenkov.com/tutorials/java-concurrency/false-sharing.html where we have the following class:
public class Counter {

    public volatile long count1 = 0;
    public volatile long count2 = 0;

}

and two threads are each updating the variables count1 and count2 at the same time. Because count1 and count2 are in the same cache line, each time a thread updates one of the variables, the other thread needs to refresh the cache line.
My question is regarding the volatile keyword. The way volatile is usually presented is that when a thread A updates a volatile variable x, and then another thread B reads x, that other thread B is guaranteed to see the updated value of x. But here volatile is used on two different variables. So another property of volatile would be that when a thread A updates a volatile variable, if another thread B then reads any other (also volatile?) variable from the same cache line, then that other thread B needs to refresh the whole cache line?

A: Both variables need to be volatile. Caches on modern CPUs are always coherent. So it doesn't matter if a cache line is falsely shared or not since the cache ensures coherence. It is the compiler that can still mess things up.
If there is data race, then the JMM allows for any written value to be seen the read is in data race with (*). So imagine the following example:
class FalseSharing{
   int a;
   volatile int b;
}

The FalseSharing instance is shared between multiple threads and one thread does the following:
while(shared.a==0){
    print(shared.b);<== triggers the false sharing
}

And another thread at some point calls 'shared.a=1'. Because there is a data race on 'a', the compiler can rewrite the code to:
if(shared.a==0){
     while(true){
         print(shared.b);
     }
}

This is legal since the JMM mandates that the possible read values of 'a' are {0,1}. And JVM is allowed to produce executions that produce a subset; in this case {0}.
After this code transformation, it is clear that it doesn't matter if 'a' is piggybacking on a falsely shared cache line.
(*) Happens-before consistent is the JMM's solution to prevent undefined behavior in case of a data race. It states that a read needs to see the most recent write before it is in the happens-before order, or a write it is in data race with.


text:
Q: How to save a dynamically created button in android How to save a dynamically created button in android. My button dissapears when the app is restarted.
Thanks in advance.

A: The idea behind dynamically creating buttons is that they won't be created when the app is initially opened and will be created only when required.
If you require the buttons to be created everytime, just call your dynamic button creation code in onCreate.
In case you create multiple dynamic buttons, you'll need to store the data associated with the buttons by some means, retrieve the data when the app is opened and then recreate the buttons based on the data.


text:
Q: How to pass an object to a web component generated width Vue? My component has to render an object to fill the content. When I am working in the Vue project, I have not problem to pass this object with
<my-compnent :card="card"></my-component>

But when I tried to use the built component, it doesn't read "MyCard" as an object, ir reads as a string... please, some help
I have tried in the same way that vue, using :card but it doesn´t work, if I only use card="card" it get access to the component but without the object
My code:
<script>
 card =
     {
        name: 'card',
        graphic: 'https://static.anychart.com/images/gallery/v8/line-charts-line-chart.png',
        subtitle: 'about this card',
        info: 'this is a test content card',
        selector1: [
          { name: 'opt 1' },
          { name: 'opt 2' },
          { name: 'opt 3' }
        ],
        selector2: [
          { name: 'opt A' },
          { name: 'opt B' },
          { name: 'opt C' }
        ]
      }
</script>
<script src="https://unpkg.com/vue"></script>
<body>
   <my-component card="card"></card>
</body>

And the error:
[Vue warn]: Invalid prop: type check failed for prop "card". Expected Object, got String with value "card".
Also I have tried
<my-component :card="card"></card>

but this only works in a vue project, not in exported web-components. It gives this error:
[Vue warn]: Error in render: "TypeError: can't access property "name", _vm.card is undefined"

A: card="card" will pass the string 'card' as value to the card attribute. If you want to pass a JS object tp an exported web component outside Vue, then you'll have to do it in JS itself.
<script>
 const card =
     {
        name: 'card',
        graphic: 'https://static.anychart.com/images/gallery/v8/line-charts-line-chart.png',
        subtitle: 'about this card',
        info: 'this is a test content card',
        selector1: [
          { name: 'opt 1' },
          { name: 'opt 2' },
          { name: 'opt 3' }
        ],
        selector2: [
          { name: 'opt A' },
          { name: 'opt B' },
          { name: 'opt C' }
        ]
      }
  let comp = document.querySelector('my-component')
  comp.card = card
</script>
<body>
   <my-component card="card"></card>
</body>

You can use v-bind:card or simply ':card' only if you're working inside vue project, in which case you don't need to use exported component. But in this case the object card needs to be passed to the data property of your Vue instance, otherwise Vue can't find it. This is why you get the error.
<script>
const app = new Vue({
  el: '#app',
  data: {
    card,
  },
}
</script>


text:
Q: Input number auto change value by stepUp and stepDown I have this input type="number"
</div>
  <input id="data-filter" class="form-control form-control" type="number" value="2021"/>
</div>

What i need is a script that change the input value using the stepUp and stepDown buttons from "2021" to "2022" and then "2021" again. This because i have a function related to that input and the function doesn't read the default value of element input. It happens only if i fill the input text with "2021" again, or i use the stepUp/stepDown buttons.
Edit:
I use that input to perform a search in a table-rows, what i need on the page load is to filter only the rows that contains the year 2021. The function works great, but it doesn't on page load using a default value. So i need to change manualty the input value.
the filter:
$('#data-filter').on('load', function () {
    changeFilter.call(this, 'data');
});

the function changeFilter:
function changeFilter(filterName) {
    filters[filterName] = this.value;
    updateFilters();
}

update filters function:

function updateFilters() {
    $('.task-list-row').hide().filter(function () {
        var
            dataValue = $(this),
            result = true;

        Object.keys(filters).forEach(function (filter) {

            if (filters[filter] && (filters[filter] != 'Tutti') && !filters[filter].includes('-')) {
                result = result && dataValue.data(filter).toLowerCase().includes(filters[filter].toLowerCase())
            }
            else if (filters[filter] && (filters[filter] != 'Tutti') && filters[filter].includes('-')) {
                result = result && convertDate(filters[filter]) === dataValue.data(filter);
            }
            if (filters[filter] === '') {
                result = true;
            }
        });
        return result;
    }).show();
}

A: function setUp() {
    let dataValue = document.getElementById('data-filter').value;
    document.getElementById('data-filter').value = ++dataValue;
}

function setDown() {
    let dataValue = document.getElementById('data-filter').value;
    document.getElementById('data-filter').value = --dataValue;
}

A: function setUp()
{
    dataValue = document.getElementById('data-filter').value;
    document.getElementById('data-filter').value = ++dataValue;
}

function setDown()
{
    dataValue = document.getElementById('data-filter').value;
    document.getElementById('data-filter').value = --dataValue;
}


text:
Q: Error opening files read from socket I have a simple pair of client / server FTP classes using TCP protocol. I'm able to transfer small text files, but when I try a larger file like this, the file appears corrupted (editors are locked up trying to open it, less gets stuck jumping to the end.) I have a feeling I'm not closing it correctly, or reading and saving it correctly from the socket. Here are both get() functions from client and server. Hopefully someone can catch what I'm doing wrong.
Server:
public void get(){

    // get file path from client
    try {
        this.filePath = controlIn.readLine();
    } catch (IOException e) {
        controlOut.println(ERROR);
        dataOut.println("Server Error: Unable to read file path");
        System.out.println("error reading filepath");
        return;
    }

    // if client sends 0, abort GET (file exists in client directory)
    if(filePath == "-1"){
        return;
    }

    // check if file exists
    File f = new File(filePath);
    if(!f.exists()){
        controlOut.println(ERROR);
        dataOut.println("Server Error: File does not exist: " + filePath);
        return;
    }

    // send file size as success msg
    int fileSize = (int)f.length();
    controlOut.println(fileSize);

    //read file to buffer, write buffer to socket
    byte [] buf  = new byte [fileSize];

    try {
        FileInputStream fis = new FileInputStream(f);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(buf,0,buf.length);
        OutputStream os = dataSocket.getOutputStream();
        os.write(buf,0,fileSize);
        fis.close();
        bis.close();
        os.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

Client:
public void get(String filePath){

    // check if file exists. If not, send ERROR to server
    File f = new File(filePath);
    if(f.exists()){
        controlOut.println(ERROR);
        System.out.println("Client Error: File: " + filePath + " already exists");
        return;
    }

    // send file path to server
    controlOut.println(filePath);

    // read status from server. Status > 0 = file size
    int status = readStatus();
    if(status == ERROR){
        System.out.println(readError());
        return;
    }

    int fileSize = status;
    int bytesRead;
    int totalBytesRead = 0;

    byte [] buf  = new byte [fileSize*2];
    try {
        InputStream is = dataSocket.getInputStream();
        FileOutputStream fos = new FileOutputStream(f);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        do{
             bytesRead = is.read(buf,0,fileSize);
        } while(bytesRead != -1);
        bos.write(buf, 0 , fileSize);
        is.close();
        bos.close();
        fos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

One more thing. The data socket is closed on the server side after the get method returns, and fileSize seems to be correct on the client side.

A: File size is to big for an Integer
Honestly: just make it a loop like
byte[] buffer = new byte[256];
int len;
while ((len = in.read(buffer)) != -1) {
   //do something with the buffer, eg:
   StringBuilder.append(new String(buffer, 0, len));


text:
Q: Show that $T$ is a contraction.
Let $A$ and $B$ be nonempty, closed and convex subsets of a Hilbert space $H$. Let $\alpha, \beta \in (0,1)$ such that $\alpha + \beta <1 $. Define $T:H \rightarrow H$ by
  $$ Tx = \alpha P_A x + \beta P_B x .$$
  Show that $T$ is a contraction.

Here, $P_A$ and $P_B$ are the projection operators onto $A$ and $B$, respectively.
I need to show that there exists $\gamma \in [0,1)$ such that
$$ d(Tx,Ty) \leq \gamma d(x,y) \text{ for every $x,y\in H$}. $$
Let $x,y \in H$. Then
$$d(Tx,Ty) = d(\alpha P_A x + \beta P_B x, \alpha P_A y + \beta P_B y)$$
Please help. Thank you.

A: since you are in a Hilbert space, you can you the norm :
$$||\alpha P_Ax+\beta P_Bx-\alpha P_Ay-\beta P_By||$$
$$\le \alpha|| P_Ax-P_Ay||+\beta||  P_Bx-P_By||$$
Since $P_A$ and $P_B$ are projection on convex closed set in a Hilbert space, they are contractant (see this answer for a demonstration)
Finally :
$$||\alpha P_Ax+\beta P_Bx-\alpha P_Ay-\beta P_By||\le (\alpha+\beta)|| x-y||$$


text:
Q: What is the probability that a man arrives at work later than on the previous day but not more than 5 minutes later.? A man leaves his house at the same time every morning and the time taken for journey to work has the following probability density function:
$f(t) = \  \left\{
\begin{array}{ll}
      0 &; t<30  \\
      k &;30<t<60 \\
      2k &;60<t<70 \\
      0 &;70<t  \\
\end{array}
\right. $
What is the probability that on one particular day, he arrives at work later than on the previous day but not more than 5 minutes later.?
Attempt:
Let the man reach office on day $1$ at the $x^{th}$ minute and on day $2$ at the $y^{th}$ minute.
Then, the required condition is as follows:
$y-x \le 5\\y>x\\30<x,y<70$
Our area of interest is the area bounded between the above curves.
Lets find out the value of $k:  ~k(60-30)+2k(70-60)=1\implies k=\frac{1}{50}$.
With reference to the diagram attached, The required answer is $\sum A_k . P(A_k)$ Where $A_k$ belongs to the bounded region defined above and $P(A_k)$ is the associated probability density with that area.
Is my method correct? Because when I calculate based on the above, I get a final answer $>1$ which is absurd. ( Please see the diagram )
Any help will be deeply appreciated. Thank You!


text:
Q: jQuery Delegate - Find Delegate Object Inside Event Closure How can I access a delegated object inside a delegate event handler? Hopefully an example should clarify my vague question.
$parent.delegate('a.some_class', 'click', someHandler);

function someHandler(e) {
  //how do I find $parent here?
}

This is partly down to how I've structured my particular .js file, where declarations are separate from implementation (yeah, old skool I know).
In someHandler, e.target and $(this) refer to the a.some_class object. Does e also have a reference to $parent? If not, what is the recommended way of finding the $parent?
Thanks for any help.

A: UPDATE: There is a way to grab the original element - e.originalEvent.currentTarget:
$parent.delegate('a.some_class', 'click', someHandler);

function someHandler(e) {
  var originalParent = $(e.originalEvent.currentTarget);
}

DEMO: http://jsfiddle.net/pjHQ6/

Original answer:
I'd probably do it like this:
$parent.delegate('a.some_class', 'click', someHandler);
function someHandler(e) {
  var parent = $(this).parent();

  // Or if $parent isn't the immediate ancestor of the links:
  var parent = $(this).closest('.parentClass');
}

A: Stupid me. Should have read the jQuery docs better.
This should do it:
$parent.delegate('a.some_class', 'click', $parent, someHandler);

function someHandler(e) {
  var parent = e.data;
}

e.data (in SomeHandler) always points to eventData, if using this delegate call.
.delegate( selector, eventType, eventData, handler )

Hope this helps someone.

A: Jens Roland is correct.
To add, the e.currentTarget should have given you the $parent where the event is actually handled.
There's a bug that explains why currentTarget is not working the way it's supposed to
http://bugs.jquery.com/ticket/11756


text:
Q: Why is NSTextAttachment image not displayed? I'm trying to add an image to an attributed string:
NSTextAttachment *locationIcon = [[NSTextAttachment alloc] init];
locationIcon.image = [UIImage imageNamed:@"location-pin-icon"];
NSAttributedString *iconString = [NSAttributedString attributedStringWithAttachment:locationIcon];
[string appendAttributedString:iconString];
NSAttributedString *locationNameString = [[NSAttributedString alloc] initWithString:@"some text" attributes:linkAttributes];
[string appendAttributedString:locationNameString];

Then I simply set myLabel.text = string; (where myLabel is a TTTAttributedLabel)
location-pin-icon is a valid image (I've checked it in debugging too). However, the location pin icon is not being displayed in the label (the following "some text" is displayed perfectly though, and linkAttributes is just a collection of system font with a custom blue color). I've also tried manually setting bounds to the text attachment, or leaving a space before the text, but nothing seems to work.
What am I doing wrong?

A: It was apparently due to implementation of TTTAttributedLabel. The library seems broken. When I've switched from it, the attachment started displaying correctly.


text:
Q: Laravel pagination redirects to home route after clicked on link for page 2 My Laravel pagination is not working properly. When I try to click on second link in laravel pagination or another one instead of first, it redirects me to home url (localhost:8000).
Laravel pagination links are redirecting to same route but with "page=" parameter but the problem is that on this route I have controller with if statements which redirects me to home page. How can I send my pagination results to another route and display every pagination page properly without get affected by controllers.
Here is controller:
    $per_page = 5; //default

    //Za ispis kategorija i tagova u filteru
    $filter_categories = Category::all();
    $filter_tags = Tag::all();

    if($request->per_page){ $per_page = $request->per_page; }

    //Ako ne postoji zahtjev za kategorijama i tagovima
    if(!$request->category && !$request->tags) {

        //Provjera da li postoji zahtjev za broj jela po stranici
        if(only_meals_per_page($request)){

            $meals = Meal::paginate($per_page);

            return view('index', compact('meals', 'filter_categories', 'filter_tags'));
        }

        //Ako ne postoji nikakvi zahtjev vrati se na početak
        return redirect('/');

    //Zahtjev za kategorijom
    } else if($request->category && !$request->tags) {

        $result = filter_meals_by_category($request->category, $per_page);

    //Zahtjev za tagovima
    } else if(!$request->category && $request->tags) {

        $result = filter_meals_by_tags($request->tags, $per_page);

    //Zahtjev za kategorijama i tagovima
    } else {

        $result = filter_meals_by_categories_and_tags($request->category, $request->tags, $per_page);

    }

    $meals = $result['meals'];
    $message = $result['message'];

    Session::flash('message', $message);
    return view('index', compact('meals', 'filter_categories', 'filter_tags'));

..and example of $result array with pagination metod
$meals = Meal::where('category_id','=', NULL)->paginate($per_page);

I know that the problem is probably in first if statement which redirects me to home because there were no categories and tags in request anymore.

A: Problem fixed with appending query string of get request in pagination links:
$meals->appends(request()->input())->links()


text:
Q: Google Glass and data from sensors Based on what I've read, Google Glass supports most/all sensors, and existing Android APIs are available to access sensors on a mobile device.
However, the GDK (gdk.jar) contains only gesture and voice-related class files, which means that custom 'glue' code is required in order to render sensor-specific data (from the gyroscope, accelerometer, and so forth) on the Glass screen.
Is this correct?

A: tl;dr: Try it like you would on any other Android device, probably using SensorManager. It should just work. They're also covered in the GDK documentation.
The API surface of GDK Glassware is not limited to the classes contained in the GDK Add-on. The GDK Add-on merely closes the gaps between the Android SDK and features that are unique to Glass. This means, in general, given a problem that isn't covered by the GDK library directly, just attempt the Android solution.


text:
Q: Unbound Error when posting data to JSONRPC When making my RPC server allow external connections and posting data to the server, e.g
{
  "jsonrpc": "2.0",
  "params": { "token":"my_token_here" },
  "method": "listShards",
  "id": "1.0"
}

I recieve this error. UnboundLocalError: local variable 'params' referenced before assignment

Here is my code. http://pastebin.com/NzkfEYn9
Thank you.
edit: I've looked around the internet and most answers don't help me or my situation.


text:
Q: How to automatically rotate images based on text? I am currently working on my eagle project for boy scouts. We are taking pictures of graves to preserve family's pasts but these pictures have been saved in google drive initially meaning that the EXIF information is lost. I need to go through around 3000 photos and see which direction they need to be rotated and do that rotation not through EXIF but rather by saving the actual pictures as the correctly oriented version of themselves. I have some experience in java but not much and will be open to solutions in any language as long as there is some description of how to import the correct libraries. Not all the photos are turned the same way and some are upsidedown so I need a way for the program to understand which direction the words are oriented in and from there I need to rotate them. If you can only find the angle they are rotated at I know a way to actually do the rotations. Here are some examples of the pictures I have. Here are some test cases left rotate, upsidown, right rotate, correct orientation
Thanks for any help

A: Honestly, the best way will be... by hand (an automated solution will be very hard and extremely time consuming to develop).
Write a short program that presents the images one after another and lets you apply the correct rotation with a single keystroke (all pictures first set to landscape orientation*). 3000 photos can be processed in one or two hours, much faster than programming an application that will cause many false decisions, taking more time to fix.
Possibly even faster, show multiple thumbnails at a time and let the user click on the mis-oriented ones (like single click = 180° rotation, shift/ctrl-click for ±90°). My bet is that you can reduce the processing time to a quarter.
Finally, the poor man's solution is by using the File Explorer and right-click to Rotate left or Rotate right. [Not kidding this will be globally the fastest.]
*For pre-rotation of the portrait images, consider a sample of images to see which among left or right rotation is most often required.

A: First you must detect the objects which is charecters in your case and there are many pre-trained object detectors for your data, Secondly you are going estimate the rotation from the detected object to the correct position of the charecter in general.