text:
Q: Постоянно вызывается команда "sed" в vs code такая проблема...
Настраивал в mac Os Mojave Visual Studio Code для работы с C++
Но после настройки у меня начало сама прописываться команда sed
Вот что пишет в VS code:

Хотя, если я запущу приложение терминал (Встроенное приложение), то sed нет.

Пытался всё переустанавливать, безуспешно.

A: Решилась проблема!
Необходимо прописать в терминале VS Code
brew install gnu-sed
alias sed=gsed
ln -s /usr/local/bin/gsed /usr/local/bin/sed


text:
Q: Get all dates by month in android database I have table in database where one of column is for date in Long. Is there any simple way to get all dates by month? For example I need all dates for October. For day I use:
public static List<Plan> getPlanListByMonth(SQLiteDatabase db, DateTime date) {

        String where = "date" + " = '"+ "2015-11-04" +"'";

        Cursor cursor = db.query(TABLE_NAME, null, where,
                null, null, null, null, null);

        return getPlanList(cursor);
}

but I have no idea how to create where condition to get all values by month.

A: You can use strftime() function
SELECT * FROM TABLE_NAME WHERE strftime('%m', 'date') = '11'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inkwel ripple effet not work in grid view I have always problem with ripple effects. this is my widget :
  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(30),
        highlightColor: Colors.blue.withOpacity(0.4),
        splashColor: Colors.green.withOpacity(0.5),
        child: Card(
          margin: EdgeInsets.all(0),
          child: Container(
            color: Colors.orange[100 * (index! % 12 + 1)],
            alignment: Alignment.center,
            child: Text(
              "test",
              style: TextStyle(fontSize: 16),
            ),
          ),
        ),
      ),
    );
  }

and I am using in grid view :
   return Scaffold(
        body: SafeArea(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: CustomScrollView(
          slivers: [
            SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                mainAxisSpacing: 8,
                crossAxisSpacing: 8,
                childAspectRatio: 1,
              ),
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  return CategoryItem(
                    index: index,
                    onTap: () {
                      print("clicked");
                    },
                  );
                },
                childCount: 10,
              ),
            )
          ],
        ),
      ),
    ));

Why not work?

A: Wrap the card with an Ink widget. More info about ink
EDIT
 return Card(
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () {
            print("hi");
          },
          borderRadius: BorderRadius.circular(30),
          highlightColor: Colors.blue.withOpacity(0.4),
          splashColor: Colors.green.withOpacity(0.5),
          child: Ink(
            color: Colors.orange,
            child: Container(
              //color: Colors.orange,
              alignment: Alignment.center,
              child: Text(
                "test",
                style: TextStyle(fontSize: 16),
              ),
            ),
          ),
        ),
      ),
    );


text:
Q: Python string formatting for encryption I need help figuring out how to do these following thigns for a string
If the character is an uppercase: change it to lowercase with '!' sign on its both sides (e.g. 'M' --> '!m!');
If the character is a lowercase: change it to uppercase with '!' sign on its both sides (e.g. 'm' --> '!M!');
If the character is a digit: cube the digit, i.e. raise to the power of 3 (e.g. '5' --> '125');
If the character is a blank space: replace it with '$' symbol;
Otherwise: keep it as it is.
I don't know where to start, besides a possible loop statement.

A: You can do this:
string = "Mm5 @"
new_string = ""
for char in string:
    if char.isupper():
        new_string += "!" + char.lower() + "!"
    elif char.islower():
        new_string += "!" + char.upper() + "!"
    elif char.isdigit():
        new_string += str(int(char) ** 3)
    elif char == " ":
        new_string += "$"
    else:
        new_string += char
print(new_string)
>> !m!!M!125$@

A: *

*Iterate over the string.

*According to the transformation rules, transforms each character in the string.

*Returns the new string.

def convertString(input):
    output = ''
    for char in input:
        if char.isupper():
            char = '!' + char.lower() + '!'
            output += char
        elif char.islower():
            char = '!' + char.upper() + '!'
            output += char
        elif char.isdigit():
            char = int(char) * int(char) * int(char)
            char = str(char)
            output += char
        elif char.isspace():
            char = '$'
            output += char
        else:
            char = char
            output += char
    return output

if __name__ == '__main__':

    input = 'Mm 5:)'

    output = convertString(input)

    print(output)

Output
!m!!M!$125:)

A: Here's answer for your question. It is in Kotlin but you can get the logic and convert it in Python.
fun main(){
    println("Enter String: ")
    val str = readln()

    var newString = ""
    for (s in str){
        when{
            s.isDigit() -> newString += (s.digitToInt() * s.digitToInt() * s.digitToInt())

            s.isLowerCase() -> newString += "!" + s.uppercase() + "!"

            s.isUpperCase() -> newString += "!" + s.lowercase() + "!"

            s == ' ' -> newString += "$"
        }
    }
    println("String formatted as: $newString")
}


text: Q: Logistic regression issue I am estimating a logistic regression model to investigate how various factors influence second-year college retention.  I include a variable indicating whether a student is in a minority racial-ethnic group and, as expected, find that this negatively impacts the probability of second-year retention.  However, when I introduce first-year GPA into the model, the sign of the minority variable flips —- minority status positively influences probability of retention.  I'm stumped.  Any help appreciated.


text:
Q: Putting an ID on Element to easily Find Later I'm trying to create a selenium test for a drag and drop table, wherein products from an item catalog are dragged to a container. You are able to drag multiple instances of one type of item and this is the cause of the hard part.
In this scenario, every item has a serial number. I can locate them via xpath, but all the instances would show up in my search.
My question is if there is a way for me to attach a unique identifier to each element I drag to the table, that way later, I can search them using that ID.
Any help is greatly appreciated.


text:
Q: How to get the unique generalized inverse matrix that we need? For matrix equation Ax = b (A is a $3×4$ matrix, x is $4×1$ vector , b is $3×1$ vector).
now, we have matrix A , vector b and already know that the third value of x is zero. How can we get the vector x by using the generalized inverse matrix of A .

A: Let us assume that $G_{4\times 3}$ is a generalized inverse of $A$.
than we know that,
$$AGA=A$$
which means that
for any $x$
$$AGAx=Ax$$
$$\implies AGb=b\quad(\because Ax=b)$$
which shows that $Gb=x$.
so, once you the generalized inverse of $A$ then $Gb$ will be the solution.
That $x=Gb$ is always a solution.
If you want a unique generalized inverse, Moore-Penrose inverse instead of generalized inverse will do the necessary.


text:
Q: graphql - Refer to other fields in mutation I want to create 2 related objects, e.g. 1 Location and 1 Place where Place has a reference to Location like so:
type Location {
    id: String
    name: String
}

type Place {
    id: String
    locationId: String
}

Is it possible to do this with 1 mutation request? Currently I'm doing this with 2 separate mutation requests like below:
mutation ($locationName: String!) {
  insert_Location(objects: {name: $locationName}) {
    returning {
      id
    }
  }
}

//in another request, use the id returned from the request above
mutation ($locationId: String!) {
  insert_Place(objects: {locationId: $locationId}) {
    returning {
      id
    }
  }
}

I'm aware it's possible to have multiple fields in a mutation so I could create 2 Locations in 1 mutation request like below.
mutation ($locationName: String!) {
  location1: insert_Location(objects: {name: $locationName}) {
    returning {
      id
    }
  }

  location2: insert_Location(objects: {name: $locationName}) {
    returning {
      id
    }
  }
}

However if I wanted to do this to create 1 Location and 1 Place, is there a way to retrieve the created Location Id and pass it to the 2nd field to create the Place?

A: For future reference:
As @Xetera pointed out, because the 2 types have a foreign key relationship you can do a nested insert mutation where hasura would handle setting the foreign key value. In my case it would look something like:
mutation ($locationName: String!) {
  insert_Place(
    objects: {
      Location: {data: {name: $locationName}}, //hasura will create Location and assign the id to Place.locationId
    }
  ) {
    returning {
      id
    }
  }
}

Docs here for further reading: https://hasura.io/docs/1.0/graphql/manual/mutations/insert.html#insert-an-object-along-with-its-related-objects-through-relationships


text:
Q: How to get the first class of the class attribute I have this in my class:
fab fa-facebook mbr-iconfont hoversel nosort hoverstamp

I just need to get the font-awesome icon classes from multiple classes as above.
I tried:
jObj.class.split(" ")[0]

But obviously this will get:
fab

But i want:
fab fa-facebook

Also to remember the font awesome class may be different like:
[fa, fas, fab] fa-linedin

So how do I achieve this, I'm thinking regex which i will try now while the question is up.
A possible answer could be:
jObj.class.split(" ")[0] + jObj.class.split(" ")[1]

But I need something more cleaner.

A:

  const classStr = "fab fa-facebook mbr-iconfont hoversel nosort hoverstamp";
  const fontAwasomeClasses = classStr
    .split(" ")
    .filter(word => word.startsWith("fa"));
  console.log(fontAwasomeClasses);

A:

const el = document.querySelector('div[class*="fa-"]')

function getFAClasses(classList){
  const arr = [],
  iterator = classList.values()
  for(value of iterator){
    if(value.includes('fa')){
      arr.push(value)
    }
  }
  return arr
}

const result = getFAClasses(el.classList)

console.log(result)


text:
Q: Does constructing a struct with default move constructor and wrap it in a shared_ptr is safe to pass to a lambda function executed in a tbb::task? Context: On one of my C++11 application, object serialization and publish of message is time consuming. Therefore I want to do it in a separate thread using Intel TBB library (more specifically using a tbb::task_group)
Issue: the object to serialize is a struct where some of the properties are std::vector<std::unique_ptr<SomeObject>>, making it impossible to pass by copy to the lambda executed in a task
Approximately it look like
struct MockedDC {
  MockedDC(int x, std::vector<std::unique_ptr<SomeObject>> v) : x(x),
                                                                v(std::move(v)) {};

  int                                      x;
  std::vector<std::unique_ptr<SomeObject>> v;
};

The "solution" I found, is to reconstruct on the heap with the move-constructor my instance and wrap it in a shared_ptr<MockedDC> which is copyable. In the end the function which invoke the tbb::task_group::run look like
// function called like this `executeInThread(taskGroup, std::move(mockedDC))`

void  executeInThread(tbb::task_group& taskGroup, MockedDC mockedDC) {
  const std::shared_ptr<MockedDC> sharedMockedDC(new MockedDC(std::move(mockedDC)));
  auto f = [sharedMockedDC] {
    const auto serialized(serializer(*sharedMockedDC)); // pass by reference
    publish(serialized);
  };

  taskGroup.run(f);
};

it compile and run fine, but I can't put it under pressure as it will be in real life condition
so my question is is it safe/sane to do this ?
I found on another stackoverflow question an alternative, but the implementation looks difficult to maintain given my C++ knowledge :) that's why I want to stick with the shared_ptr approach as suggested somewhere else
What I tried so far: I wrote a dummy code to test the thing, but I think its not enough to validate this approach. I also wanted to compile with some sanitization flags, but tbb fail to link with a bunch of errors like undefined reference to __ubsan_handle_pointer_overflow
Here is the dummy example if that help to answer (it compile and run without issues (except some int overflow but that not an issue I guess))
#include <cstdio>
#include <iostream>
#include <memory>
#include <vector>
#include <numeric>
#include "tbb/task_scheduler_init.h"
#include "tbb/task_group.h"

struct MockedDC {
  MockedDC(int seed, size_t baseLen) : seed(seed), baseLen(baseLen) {
    this->a_MDC.reserve(baseLen);
    for (size_t i = 0; i < baseLen; ++i)
      this->a_MDC.emplace_back(new int((seed + i) / (seed + 1)));
    };

    int                               seed;
    size_t                            baseLen;
    std::vector<std::unique_ptr<int>> a_MDC;
  };

void  executeInThread(tbb::task_group& taskGroup, MockedDC mockedDC) {
  const std::shared_ptr<MockedDC> sharedMockedDC(new MockedDC(std::move(mockedDC)));
  auto f = [sharedMockedDC] {
    std::cout <<
      std::accumulate(sharedMockedDC->a_MDC.begin(), sharedMockedDC->a_MDC.end(), 0, [](int acc, const std::unique_ptr<int>& rhs) {
          return acc + *rhs;
      })
      << std::endl << std::flush;
  };
  taskGroup.run(f);
};

void  triggerTest(tbb::task_group& taskGroup) {
  for (size_t i = 0; i < 1000000; ++i) {
    MockedDC  mdc(i, 10000000);
    executeInThread(taskGroup, std::move(mdc));
  }
  return ;
};

int main() {
  tbb::task_scheduler_init  tbbInit(tbb::task_scheduler_init::automatic);
  //tbb::task_scheduler_init  tbbInit(8);
  tbb::task_group           taskGroup;

  triggerTest(taskGroup);
  taskGroup.wait();
  return (0);
};

PS: using C++14 new capture by move doesn't work because of TBB library :/


text:
Q: Are all agents identical except for their abilities? I'd like to know if there is any difference between the agents when ignoring their abilities.
Do all agents for example have the same movement speed while running or walking or jumping? Identical weapon handling such as reload time, draw time, recoil?
Basically I'd like to know if the abilities should be the only criteria for choosing an agent, outside of cosmetic differences.

A: There are no differences between the agents outside of their abilities. All of them will have the same movement speed, weapon handling, and hitboxes.
Each agent gets four unique abilities and one ultimate, and each agent can be categorized as one of four types: Controller, Duelist, Initiator, and Sentinel.
So outside of cosmetics, abilities are the only reason to choose one agent over another. Ideally each team is comprised of a blend of agent types that make up a well rounded team.

A: Jett can jump in a pretty unique way. That's one thing I like. There is no agent who can jump slowly like Jett and make a soft landing no matter how high you go. And this is not one of those 4 abilities that you need to 'activate'. It works all the time.
There is no difference in normal movement speed.


text:
Q: Trouble connecting data to MySQL I can't seem to find out why my PHP code won't allow me to store the info in MySQL when I click the submit button. Can someone tell me whats wrong with the code below?
I want to get it to the point where users submit their registration form and their info can get moved over to a MySQL database. Then, I want the users to be taken to my index.html file.
Any help is appreciated.
Thanks
<?php

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$mysql_database = "21st";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Could not connect database");
        mysqli_select_db($conn, $mysql_database) or die("Could not select database");

$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];

if ($password == $password2)    {
        $sql = "INSERT INTO members (username, email, password) VALUES ('$userrname','$email','$password')";
} else  {
    echo "Your passwords must match";
}
?>

A: Try this using mysqli_query to actually run the query. When you set $sql all that did was set a variable named $sql to the query. Also note you set the variable $userrname in the query when it should be $username as set from the $_POST directly above. My adjusted version of your code below:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$mysql_database = "21st";

$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Could not connect database");
mysqli_select_db($conn, $mysql_database) or die("Could not select database");

$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];

if ($password === $password2) {

  // Set the query.
  $sql = "INSERT INTO members (username, email, password)"
       . " VALUES (?, ?, ?)"
       ;

  // Bind the values to the query.
  mysqli_stmt_bind_param($sql, 'sss', $username, $email, $password);

  // Run the query.
  mysqli_query($conn, $sql);

  // Free the result set.
  mysqli_free_result($sql);

  // Close the connection.
  mysqli_close($conn);

}
else {
  echo "Your passwords must match";
}


text:
Q: Noise in sound after using RDP I don't know why but after using my Office PC remotely (RDP) from any place, its sound is being "bugged": a skratchy noise appears at some interval ~ 20-40 seconds.
Rebooting the PC helps, but I'd like another solution.
Question:
Is there a solution or some clues upon that? (Note this bug appears ONLY after RDP connection)
PC Characteristics:

*

*OS:           Windows 7 X64 Ultimate

*Sound Driver: Realtek HD v6.0.1.6657

*MB:           Asus P8Z77-V LK

A: try this:

*

*Click on 'Start' and type 'remote desktop connections' and Enter.

*In the 'remote desktop connections' click on 'Options' and select 'Local Resource' tab.

*Click on 'Settings' under Remote audio.

*Select 'Play on this computer'.

*Click 'OK'.


text:
Q: Using Excel VBA on PeopleSoft hyperlink and pop-up message My macro loops through and clicks on a list of hyperlinks.  However, each time a link is clicked, a pop-up message is displayed with 3 options: (1) Open, (2) Save, and (3) Save as.
Is it possible with Excel VBA to click on the "Save As" option?  Currently, users have to click on each pop-up (over 200 times).  I would definitely like to automate this if it is possible.
Thanks for your help in advance.........


text:
Q: Probability of having at most a certain number of isolated vertices in random graph? In Erdos-Renyi model of Binomial random graphs $G(n,p)$, if we have $np = \ln n - \ln \ln \ln n$, then what is the probability of having at most $a \ln n$ vertices be isolated.
Having isolated vertices in $G(n,p)$ has sharp threshold probability $p = \ln n / n$. So we are below the threshold probability. There must be isolated vertices. We need to compute $P(G(n,p) \text{has isolated vertices} \leq a \ln n)$; $a>0$.
If I define my event $X:= \text{number of isolated vertices} > a \ln n$, then using Markov's inequality, $P(X \geq 1) \leq EX$, and $EX = \frac{1}{O(\ln n)!}O(e^{\frac{\ln n}{ n} })$ which goes to 0 as $n \rightarrow \infty$.
But only this argument will not ensure that $P(\text{number of isolated vertices} \leq a \ln n) \rightarrow 1$.
Remark: We need to calculate $P(\text{number of isolated vertices}\leq a\ln n)$. By simply calculating the probabilities of all upto $a\ln n$ number of vertices, we get:
(let $X$ be the event of having $j = 1, \ldots, a\ln n$, number of isolated vertices)
$P(X \leq a\ln n) = \sum_{j = 1}^{a\ln n}(1-p)^{jn-j(j+1)/2}$.
Evaluating this, with $p=\ln /n - (\ln \ln\ln n )/ n$, we get something similar to a geometric series $P(X \leq a\ln n) = \sum_{j = 1}^{a\ln n}(\frac{\ln\ln n}{n})^{j+\frac{j(j+1)}{2n}}$.
Can it be written in a close form?
To get an upper bound, I take the max probability term (when j=1), $a\ln n$ times.
$P(X \leq a\ln n) \leq a\ln n(\frac{\ln\ln n}{n})^{1+\frac{1}{2n}}$


text:
Q: password algorithm hash_algos overkill Just curious in the speed and productivity and the security in using all hash_algos
Array
 (
   [0] => md2
   [1] => md4
   [2] => md5
   [3] => sha1
   [4] => sha224
   [5] => sha256
   [6] => sha384
   [7] => sha512
   [8] => ripemd128
   [9] => ripemd160
   [10] => ripemd256
   [11] => ripemd320
   [12] => whirlpool
   [13] => tiger128,3
   [14] => tiger160,3
   [15] => tiger192,3
   [16] => tiger128,4
   [17] => tiger160,4
   [18] => tiger192,4
   [19] => snefru
   [20] => snefru256
   [21] => gost
   [22] => adler32
   [23] => crc32
   [24] => crc32b
   [25] => salsa10
   [26] => salsa20
   [27] => haval128,3
   [28] => haval160,3
   [29] => haval192,3
   [30] => haval224,3
   [31] => haval256,3
   [32] => haval128,4
   [33] => haval160,4
   [34] => haval192,4
   [35] => haval224,4
   [36] => haval256,4
   [37] => haval128,5
   [38] => haval160,5
   [39] => haval192,5
   [40] => haval224,5
   [41] => haval256,5
)

Obviously this would be overkill yet strictly speaking from a whim and wonderment would looping these methods with our password and salts and then using our return saying md5 being our last algorithm to be ran as the store. How long would it be to crack the said password? As ive read in some documentation  with a password 8 or less characters in length it takes only 6 hours to crack so in reference if our stipulations and regulations to a password was
One uppercase letter
Two numbers
And no less than 10 characters in length
Then loop our password in the hash_algs essentially our password could nearly be unbreakable though I shouldn't use that since everything these days is able to be cracked.
So my concerns are is this feasible
Will it have a heavy page load
Regulations to passwords strength stronger like this
Is it truly overkill or is it like fort knox security?

A: Using all of the algorithms is complete overkill. If I were you, just generate a random salt for each user (possibly by MD5 hashing uniqid, just an example), and hash the password with said salt. Blowfish encryption will work great for you.

A: Mixing all hash functions is not a good idea, because they are still too fast and you don't know if they influence each other.
An appropriate password hash function should be slow (need some computing time). If an attacker tries to crack passwords, and the hashing was properly handled, the only way for him is brute-forcing, usually done in combination with a dictionary.
That means, the more passwords he can try per second, the faster he will find the original password. Today you can for example calculate about 8 Giga MD5 hashes per second with common hardware.
There are algorithms like BCrypt and PBKDF2 with a cost factor, you can use the PHP function password_hash() to generate a BCrypt hash. The cost factor defines how many times the hash function is iterated, so you can control how much time the calculation of one try needs. A millisecond to gain access to your website is not much, a millisecond to brute-force is a stopper. With your chaining of hashes you still have only 40 fast calculations.
If your are interested in more information about password storing, you could have a look at my tutorial about secure password storing.


text:
Q: How do I create a Circle using a rhombus with the code I have I used this method for the creation of a square:
public void displayCircle() {
    JFrame frame = new JFrame();
    frame.setSize(400, 300);
    int x1 = (int) A.getX();
    int x2 = (int) B.getX();
    int x3 = (int) C.getX();
    int x4 = (int) D.getX();
    // 25, 156, 175, 80
    int y1 = (int) A.getY();
    int y2 = (int) B.getY();
    int y3 = (int) C.getY();
    int y4 = (int) D.getY();

    applet = new CircleApplet(new int[] { x1, x2, x3, x4 }, new int[] { y1, y2, y3, y4 });
    int R = (int) ((Math.random()) * 256);
    int G = (int) ((Math.random()) * 256);
    int Bb = (int) ((Math.random()) * 256);

    applet.setForeground(new Color(R, G, Bb, 200));
    frame.getContentPane().add(applet);
    frame.addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent we) {
            applet.stop();
            applet.destroy();
            System.exit(0);
        }
    });

    frame.setVisible(true);
    applet.init();
    applet.start();

}

with this circle applet:
import java.applet.*;
import java.awt.*;

@SuppressWarnings("deprecation")
public class CircleApplet extends Applet {

    int[] pointsX,pointsY;
    int numPoints=0;
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public CircleApplet() {}

    public CircleApplet(int[] pointsX, int[] pointsY) {
        this.pointsX=pointsX;
        this.pointsY=pointsY;
        this.numPoints=Math.min(pointsX.length, pointsY.length);
    }

    public void paint(Graphics g) {
        //System.out.println(this.numPoints);
        if (this.numPoints>0)
            g.fillPolygon(pointsX,pointsY,numPoints);
        for(int x = 0; x < numPoints; x++){
            g.setColor(new Color(0, 0, 0));
            char alpha = 'X';
            switch (x){
                case 0:
                    alpha = 'A';
                    break;
                case 1:
                    alpha = 'B';
                    break;
                case 2:
                    alpha = 'C';
                    break;
                case 3:
                    alpha = 'D';
                    break;
                default:
                    break;
            }
            g.drawString(alpha +" (" + pointsX[x] + " , " + pointsY[x] + ")", pointsX[x], pointsY[x]);
        }
    }

}

I wanted to create circle mentioned above, how do I create a circle? Do I use arcs or do I have to rewrite it, the problem itself is straight forward but I still do not understand applets.


text:
Q: How to find if there's a cycle within selected nodes in a directed graph?(C++) I'm currently working on a problem of finding cycles consisted of selected nodes in a directed graph.
For the instance described here:

there's a cycle within node 1, 2, 3, and no cycle is found within 1, 2, 4.
I've tried to implement the algorithm myself with the following operation:

*

*Start with the first node within the selected nodes.

*Mark current node as "visited".

*Check if adjacent nodes are within selected nodes.

*Recursive call if the node hasn't been visited, return true if it's visited.

*At the end of the function: return false.

My implementation is as following(the function is called for each selected nodes, and the array storing visited nodes is initialized every time)
bool hasLoop(const int startNode, const bool directions[][MAX_DOT_NUM], const int nodesLen, bool nodesVisited[], const int selectedNodes[], const int selectedNum){
nodesVisited[startNode] = true;

for(int i = 0; i < nodesLen; i++){ //loop through all nodes
    if(withinSelected(i, selectedNodes, selectedNum) == false) continue;  //check loop only for selected nodes
    if(directions[startNode][i] == 1){ //connected and is within selected nodes
        if(nodesVisited[i] == true){
            return true;
        }else{
            if(hasLoop(i, directions, nodesLen, nodesVisited, selectedNodes, selectedNum)){
                return true;
            }
        }
    }
}
return false;

}
However, this implementation doesn't work for all testing data from the online judge I'm using.
I found that my algorithm is different from Depth First Search, which uses White, Grey, Black arrays to store nodes that are not visited, being visited, or not needed to be visited, I wonder if that's the reason causing problems.
Hopefully, I can find the bug causing this implementation not to work for all circumstances with your help!
Thank you so much for reading this!
Edited: it's a directed graph! sorry for that.

Edited: Thanks for your help so much! I revised my implementation to have the function return true only when finding a node pointing to the node where the function started.
Here's the final implementation accepted by the online judge I use:
bool hasLoop(const int currentNode, const bool directions[][MAX_DOT_NUM], const int nodesLen, bool nodesVisited[], const int selectedNodes[], const int selectedNum, const int startNode){
// cout << currentNode << " -> ";
nodesVisited[currentNode] = true;

for(int i = 0; i < nodesLen; i++){
    if(withinSelected(i, selectedNodes, selectedNum) == false) continue;
    if(directions[currentNode][i] == 1){ //connected and is within selected nodes
        if(nodesVisited[i] == true){
            if(i == startNode) return true;
        }else{
            if(hasLoop(i, directions, nodesLen, nodesVisited, selectedNodes, selectedNum, startNode)){
                return true;
            }
        }
    }
}
return false;

}

A: Your implementation is a DFS, but will fail for "side nodes" that do not create a cycle:
Consider the graph with 3 nodes (A,B,C):
      A
    /   \
   /     \
  V       V
  B <---- C

Your algorithm will tell that the graph has a cycle, while in fact - it does not!
You can solve it by finding Strongly Connected Components, and seeing if there are non trivial (size>1) components.
Another solution would be to use Topological Sort - which returns an error if and only if the graph has a cycle.
In both solutions, you apply the algorithm only on the subgraph containing the "selected nodes". Both solutions are O(|V|+|E|) time, and O(|V|) space.


text:
Q: Best way to set a reoccurring android task I am creating the following thread in my onCreate but realized that this call needs to execute every 20 minutes or so:
 Thread t = new Thread() {
    public void run(){
       setTopUsers();
    }
  };

  t.start();

 private void setTopUsers() {
    ...

    for(Map.Entry<Double,String> entry : myMap.entrySet()) {
           key = entry.getKey();
           value = entry.getValue();

           if(...)
              view.setText(...)
       }
}

The method that's being called simply processes information from a TreeMap and displays the results to the UI. I'm trying to figure out what is the best way to handle this: 1) Create a Timer that runs on a separate thread (but I've read that's not a good idea), 2) Create a service Intent that processes every 20 minutes (seems like overkill).
Any suggestions?

A: http://developer.android.com/reference/android/app/AlarmManager.html#setRepeating%28int,%20long,%20long,%20android.app.PendingIntent%29

A: Something like this should work:
Intent intent = new Intent(this, ProcessService.class);
PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.cancel(pIntent);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), INTERVAL, pIntent);

A: Let the user decide. Implement both, there's nothing worse than a repeating process the user can't control.


text:
Q: how can I change the installation path of a desktop app in the setup project? Visual studio 2017 I have made a project and I want to make an installable project to install a desktop app. I have added a setup project to my solution. Everything seems to work fine but in the installation process, I'm asked if I want to change the installation directory. When I change that directory to another path it is still installing the .exe in the same path that is c:\ (the root directory). I've read that changing the property DefaultLocation of the Application Folder is the way to change the default path but even so nothing different occurs and the installation is still in the root path.

I think that from the visual studio 2012 and above there is another way to do that.
I have also seen that question in StackOverflow but I can't find the "Project Assistant" nor the "Installation Interview".
Changing the Default Installation Path in Windows Application
Does anyone know how can I do that? Thank you.


text:
Q: How to change the text color in Blazor via CSS setting I am trying to figure out how I can change the text color for a Blazor application via CSS setting.
As an experiment, I creating a new (default) Blazor WebAssembly application in Visual Studio 2019. Then I am trying to change the test color of the navigation elements on the left-hand side, but no matter which CSS file I am modifying I don't seem to get the correct effect.
The relevant Razor markup looks like this (in NavMenu.razor):

        <NavLink class="nav-link" href="fetchdata">
             Fetch data
        </NavLink>

which renders in HTML like this:

         Fetch data

I have tried both
.nav-item { color: orange; }
and
.nav-link { color: orange; }
in either the NavMenu.razor.css or the css/app.css file but neither seems to work.
What is the correct way to set this css setting so the text 'Fetch data' appears as an orange text?

A: You can modify the styles in NavMenu.razor.css with ::deep option and since CSS isolation combines the application CSS, you clean the application and rebuild to check for your changes.
    .nav-item ::deep a {
    color: orange;
    border-radius: 4px;
    height: 3rem;
    display: flex;
    align-items: center;
    line-height: 3rem;
}

Regards,
Sridhar N

A: You have to use ::deep
.nav-item ::deep a {
    color: orange;
}

The existing value in NavMenu.razor.css
    .nav-item ::deep a {
        color: #d7d7d7;
        border-radius: 4px;
        height: 3rem;
        display: flex;
        align-items: center;
        line-height: 3rem;
    }


text:
Q: Explicit Wait in helper class to be used when needed by test cases I am trying to create a helper class that holds different waits for Selenium WebDriver. This is to give the user more flexibility when creating test cases. I am having some issues with the helper class for Explicit waits.
Test Case
[Test]
[TestCase(Browser.Chrome)]
public void ValidateExpicitWait(Browser browser)
{
    Driver = StaticWebDriverFactory.GetLocalWebDriver(browser);
    Driver.Url = "https://example.com/";
    WaitsHelper.SetExplicitWait(Driver, ElementIdentifierType.LinkText, "More information...", 10);

    var title = Driver.Title;
    Assert.AreEqual(true, title.Contains("Example Domain"), $"Expected title does not match actual: {title}", title);
}

Explicit Wait Class
public static void SetExplicitWait(IWebDriver driver, ElementIdentifierType identifierType, string identifer, int timeout = 10)
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
    IWebElement element = wait.Until<IWebElement>((d) =>
    {
        return d.FindElement(By.identifierType(identifer));
    });

}

It has a issue with identifierType from d.FindElement(By.identifierType(identifier));
Error

'By' does not contain a definition for 'identifierType

A: By class can't convert an Enum to static method, it doesn't have identifierType method. You can send By object instead
public static void SetExplicitWait(IWebDriver driver, By by, int timeout = 10)
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
    IWebElement element = wait.Until<IWebElement>((d) =>
    {
        return d.FindElement(by);
    });
}

WaitsHelper.SetExplicitWait(Driver, By.LinkText("More information..."), 10);


text:
Q: Create list from 2 numbers and 2 for loops I have 2 numbers let's say number1=5 and number2=3 and I want to create a list in this form
((1(1 2 3)) (2(1 2 3)) (3(1 2 3)) (4(1 2 3)) (5(1 2 3)))
So the number1 indicates the number of the elements  in the list and number2 indicates the total elements that will be as the second part of every element..
I have smth like this untill now
(define mylist '())

   (define (pushlist item item2)
  (do ((j 1 (+ j 1))) ((> j item2))
   (set! mylist(list mylist (list item j)))))

  (define (createlist number number2)
   (do ((j 1 (+ j 1))) ((> j number))
   (pushlist j number2)
    ))

  (createlist 5 3)

Unfortunately it doesn't work.. It doesn't give the result I want.. It gives me this (((((((((((((((() (1 1)) (1 2)) (1 3)) (2 1)) (2 2)) (2 3)) (3 1)) (3 2)) (3 3)) (4 1)) (4 2)) (4 3)) (5 1)) (5 2)) (5 3))

A: There are many ways to solve this problem - for example, using explicit recursion, or using higher-order procedures. Your approach is not recommended, in Scheme you should try to avoid thinking about loops and mutation operations. Although it is possible to write such a solution, it won't be idiomatic. I'll try to explain how to write a more idiomatic solution, using explicit recursion first:
; create a list from i to n
(define (makelist i n)
  (if (> i n)
      '()
      (cons i (makelist (add1 i) n))))

; create a list from i to m, together with
; a list returned by makelist from 1 to n
(define (makenumlist i m n)
  (if (> i m)
      '()
      (cons (list i (makelist 1 n))
            (makenumlist (add1 i) m n))))

; call previous functions
(define (createlist number1 number2)
  (makenumlist 1 number1 number2))

Now, an even more idiomatic solution would be to use higher-order procedures. This will work in Racket:
; create a list from i to n
(define (makelist n)
  (build-list n add1))

; create a list from i to m, together with
; a list returned by makelist from 1 to n
(define (makenumlist m n)
  (build-list m
              (lambda (i)
                (list (add1 i) (makelist n)))))

; call previous functions
(define (createlist number1 number2)
  (makenumlist number1 number2))

See how we can avoid explicit looping? that's the Scheme way of thinking, the way you're expected to solve problems - embrace it!

A: I don't think that your pushlist procedure is doing what you you expect it to.
(define (pushlist item item2)
  (do ((j 1 (+ j 1)))
      ((> j item2))
    (set! mylist (list mylist (list item j)))))

If you have a list (x y z) and you want to push a new value v into it, you'd do
(set! lst (cons v lst))

because (cons v (x y z)) == (v x y z).  By doing
(set! mylist (list mylist (list item j)))

you're making mylist always have exactly two elements, where the first is a deeper and deeper nested list.   Óscar López's answer gives a more idiomatic approach to this problem.  Here's  a similar idiomatic approach:
(define (range n)
  ; returns a list (1 ... n)
  (let rng ((n n) (l '()))
    (if (zero? n)
        l
        (rng (- n 1) (cons n l)))))

If the sublists (1 ... n) can all be the same list (i.e., the actual list object is the same), then you can create it just once:
(define (createlist m n)
  (let ((sublist (range n)))
    (map (lambda (main)
           (list main sublist))
         (range m))))

Otherwise, if they need to be distinct, you can generate one for each of 1 ... m:
(define (createlist m n)
  (map (lambda (main)
         (list main (range n)))
       (range m)))


text:
Q: Form shrinks on smaller screen in VS. How do I get groupboxes that are now outside the form's border? I'm on the road at the moment and I've opened a WinForms project in VS.
The form was designed to run on a full hd display, so VS has shrunk it for my laptop display. I'm trying to put all the groupboxes in a panel so I can run it on my laptop, but some of them are now outside the form's border. How can I grab them?

A: Use  TableLayoutPanel Control  Because i have also face same issue but when you design winform using TableLayoutPanel  then the size of the form increase or decrease then don't affect on winform. it's resize the every control on form as per screen size.
Hope it will help you thank you.


text:
Q: Directive failing within different views I am developing an app which has an streaming for music, I created a directive and put it in the main view -index.html- because I need that the user be able to stop and start the music once he decide.
So, first, my directive
.directive('audioPlay', function() {
  return {
    restrict: 'E',
    link: function(scope, element, attr) {

      scope.playOrPause = true;

      var player = element.children('.player')[0];

      scope.playMusic = function() {
        scope.playOrPause = false;
        player.play();
      }

      scope.stopMusic = function() {
        scope.playOrPause = true;
        player.pause();
      }

    }
  };
});

then, I put the directive in index.html

    <ion-nav-bar>
      <ion-nav-back-button>
      </ion-nav-back-button>

      <ion-nav-buttons side="right">

        <audio-play>
          <audio class="player">
            <source src="http://fire.wavestreamer.com:9711/UrbanetRadio"/>
          </audio>
          <button class="button button-clear"
                  ng-click="playMusic()"
                  ng-hide="!playOrPause">

          </button>
          <button class="button button-clear"
                  ng-click="stopMusic()"
                  ng-show="!playOrPause">

          </button>
        </audio-play>

      </ion-nav-buttons>

    </ion-nav-bar>
    <ion-nav-view></ion-nav-view>

now, I have 3 views in this order: tab-news.html, tab-promotions.html, tab-signup.html.
You are able to see the directive in the 3 views and also in the nested views which is awesome, but I have an issue with the tab-promotions.html, if the user call playMusic() in any view, the statement changes to that function and the music starts, but the statement never updates in the tab-promotions, in the other views you can stop and start the music once you want and the app has the proper behavior, but in the tab promotions you are still able to play and stop the music without taking care if the other views, this view is independent of the other views in that sense.
It is hard to explain myself here, so in a resume: in every view except tab-promotions, the app has the proper behavior, if the music is sounding and you go to tab-promotions you are to play music also in that view so there will 2 sounds in the background, one for the other 2 views and 1 different for tab-promotions.
It seems as if I need to do a model or something. What do you say community ?
UPDATE
this how it looks so far attached to the body, is the element on the right


text:
Q: No consigo que se manden los archivos de uno en uno Tengo que hacer un lavado de cara al código que ya tenía hecho para que funcione correctamente con varios archivos.
Cuando meto varios archivos a un input file, los recojo con el JS para meterlos en un array llamado pool mediante un bucle for, y después PRETENDO mandar cada objeto a otra función uno por uno, esperando a que se ejecute dicha función de principio a fin para mandar el siguiente.
Esto funciona mal, ya que NUNCA los manda todos, en el código comentado explico lo que hace cada cosa:
function selectFile(){
    let file = _("file1");

    if('files' in file){
      let pool = [], x;

      for(let i=0;i < file.files.length;i++){//iteramos el array de ficheros
          x = file.files[i];//asignamos en cada iteracion al fichero en x
          pool.push(x);//push en pool de x
          console.log(pool);//accion de bucle completa previa a ejecucion de codigo

          //despliegue del temp
          txt = createElement();
          document.body.append(txt);
          //logs
          if ('name' in x) {txt.getElementsByClassName('txt_file_name')[0].innerHTML = 'Name: '+x.name;};
          if ('size' in x) {txt.getElementsByClassName('txt_file_size')[0].innerHTML = 'Size: '+x.size;};
      }

      //salta por alto esta variable
      let snd_upload = () => {
        console.log('Se ejecuta snd_upload');
        if(pool.length){
          console.log(pool.length);
          let p1 = pool.shift();//cogemos el primer objeto de pool
          console.log('Mandando archivo "'+p1.name+'" para descomprimir');
          uploadComplete(p1, function(){snd_upload();console.log('se manda snd_upload')});//mandamos el objeto a upload complete
          //no hay reiteracion...por que
        }
      };

      //y lo manda desde aquí de forma recursiva
      //tantos objetos hay en pool
      snd_upload();
    }
}

SIN EMBARGO, en la función uploadComplete, en la que desfragmento el archivo en chunks y lo mando a otra función, trato de seguir la misma lógica, y me sale bien, mas o menos, ya que también tiene fallos, pero al menos se consigue reiterar:
function uploadComplete(x) {
  console.log(x);

  let pol =[];
  let start = 0;
  let end = BYTES_PER_CHUNK;
  let part = 0;
  let charged = 0;
  //se hace solo una vez
  //se sube el archivo una vez

  while( start < x.size ) {
    //se divide el archivo mientras start sea menor al size total
    //se ejecuta cuantas veces se divida el archivo
    start = end;
    end = start + BYTES_PER_CHUNK;
    part++;
    pol.push({part:part,start:start,end:end});

    console.log(pol);//iteramos los que van a ser los fragmentos del archivo mandado
  }

  console.log('esto va despues del while');
  let fnupload = ()=>{
    console.log('y despues esto');
    if(pol.length){
      let p1 = pol.shift();
      let chunk = x.slice(p1.start, p1.end);
      uploadFile(chunk, p1.part, x, function(){fnupload();console.log('se manda')});//esto se ejecuta a partir de la SEGUNDA vez que lo mando
      //por que
      console.log('complete', p1.part);
    }
  };

  console.log('ejecuta esto primero');
  fnupload();
}

Dicha función llama a otra, uploadFile:
function uploadFile(chunkFile, part, x, uploadLoaded){
  //se ejecuta tantas veces esté dividido el archivo
  let xhr = new XMLHttpRequest();
  let fd = new FormData();
  let chunks = Math.max(Math.ceil(x.size / BYTES_PER_CHUNK), 1);
  let bar = txt.getElementsByClassName('progressBar')[0];

  xhr.upload.addEventListener("progress",(event)=>{uploadProgress(event, bar, x)}, false);
  xhr.addEventListener("error", uploadFailed, false);
  xhr.addEventListener("abort", uploadCanceled, false);
  xhr.addEventListener("loadend", uploadLoaded, false);

  fd.append("file1", chunkFile);
  fd.append("num", part);
  fd.append("chunks", chunks);
  fd.append("namae", x.name);

  xhr.open("POST", "upload.php", true);
  xhr.send(fd);
}

function uploadProgress(event, bar, x){

  _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
  let percent = (event.loaded / event.total) * 100;
  bar.value = Math.round(percent);
  _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}

function uploadFailed(event) {
  _("status").innerHTML = "Upload failed";
}

function uploadCanceled(event) {
  _("status").innerHTML = "Upload canceled";
}

Y no, no tengo uploadLoaded. No entiendo muy bien cómo podría solucionar esto.

[EDIT]
Snippets con el html:
<!DOCTYPE html>

  <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
    <input type="file" name="file1" id="file1" onchange="selectFile()" multiple size="50">

    <input type="submit" id="btn-progressbar" value="Upload" style="visibility:hidden">
  </form>

A: Vale, ya corregí el código (trasteando y sin querer...), así es como quedaría de forma final el código en JS, en HTML y en PHP (lo adjunto todo por si a alguien le llega a interesar):
HTML
<!DOCTYPE html>

  <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
    <input type="file" name="file1" id="file1" onchange="selectFile()" multiple size="50">

    <input type="submit" id="btn-progressbar" value="Upload" style="visibility:hidden">
  </form>

JS
var txt, BYTES_PER_CHUNK = 2097152;

function selectFile(){
    let file = _("file1");

    if('files' in file){
      let pool = [], x;

      for(let i=0;i < file.files.length;i++){//iteramos el array de ficheros
          x = file.files[i];//asignamos en cada iteracion al fichero en x
          pool.push(x);//push en pool de x
          console.log(pool);//accion de bucle completa previa a ejecucion de codigo

          //despliegue del temp
          txt = createElement();
          document.body.append(txt);
          //logs
          if ('name' in x) {txt.getElementsByClassName('txt_file_name')[0].innerHTML = 'Name: '+x.name;};
          if ('size' in x) {txt.getElementsByClassName('txt_file_size')[0].innerHTML = 'Size: '+x.size;};
      }

      //salta por alto esta variable
      let snd_upload = () => {
        console.log('Se ejecuta snd_upload');
        if(pool.length){
          console.log(pool.length);
          let p1 = pool.shift();//cogemos el primer objeto de pool
          console.log('Mandando archivo "'+p1.name+'" para descomprimir');
          uploadComplete(p1, function(){snd_upload();console.log('se manda snd_upload')});//mandamos el objeto a upload complete
          //no hay reiteracion...por que
        }
      };

      //y lo manda desde aquí de forma recursiva
      //tantos objetos hay en pool
      snd_upload();
    }
}

function uploadComplete(x, snd_upload) {
  console.log(x);

  let pol =[];
  let start = 0;
  let end = BYTES_PER_CHUNK;
  let part = 0;
  let charged = 0;
  //se hace solo una vez
  //se sube el archivo una vez

  while( start < x.size ) {
    //se divide el archivo mientras start sea menor al size total
    //se ejecuta cuantas veces se divida el archivo
    pol.push({part:part,start:start,end:end});
    start = end;
    end = start + BYTES_PER_CHUNK;
    part++;
    console.log(pol);//iteramos los que van a ser los fragmentos del archivo mandado
  }

  console.log('esto va despues del while');
  let fnupload = ()=>{
    console.log('y despues esto');
    if(pol.length){
      let p1 = pol.shift();
      let chunk = x.slice(p1.start, p1.end);
      console.log(chunk);
      uploadFile(chunk, p1.part, x, function(){fnupload();console.log('se manda')});//esto se ejecuta a partir de la SEGUNDA vez que lo mando
      //por que
      console.log('complete', p1.part);

      if(pol.length == 0){
        snd_upload();
      }
    }
  };

  console.log('ejecuta esto primero');
  fnupload();
}

function uploadFile(chunkFile, part, x, uploadLoaded){//se manda uploadLoaded
  //se ejecuta tantas veces esté dividido el archivo
  let xhr = new XMLHttpRequest();
  let fd = new FormData();
  let chunks = Math.max(Math.ceil(x.size / BYTES_PER_CHUNK), 1);
  let bar = txt.getElementsByClassName('progressBar')[0];

  xhr.upload.addEventListener("progress",(event)=>{uploadProgress(event, bar, x)}, false);
  xhr.addEventListener("error", uploadFailed, false);
  xhr.addEventListener("abort", uploadCanceled, false);
  xhr.addEventListener("loadend", uploadLoaded, false);//y aqui tambien
  //pero no hay ninguna funcion llamada asi, no lo entiendo

  fd.append("file1", chunkFile);
  fd.append("num", part);
  fd.append("chunks", chunks);
  fd.append("namae", x.name);

  xhr.open("POST", "upload.php", true);
  xhr.send(fd);
}

function uploadProgress(event, bar, x){

  _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
  let percent = (event.loaded / event.total) * 100;
  bar.value = Math.round(percent);
  _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}

function uploadFailed(event) {
  _("status").innerHTML = "Upload failed";
}

function uploadCanceled(event) {
  _("status").innerHTML = "Upload canceled";
}

function createElement(){
  let dv = document.createElement('div');
      dv.setAttribute('class', 'demo');
  let p1 = document.createElement('p');
      p1.setAttribute('class', 'txt_file_name');
  let p2 = document.createElement('p');
      p2.setAttribute('class', 'txt_file_size');
  let pr = document.createElement('progress');
      pr.setAttribute('class', 'progressBar');
      pr.setAttribute('value', '0');
      pr.setAttribute('max', '100');

      dv.append(p1);
      dv.append(p2);
      dv.append(pr);

  return dv;
}

function _(el) {
  return document.getElementById(el);
}

PHP
<?php

$target_path = 'archivos_aaron_pruebas/';
$tmp_name = $_FILES['file1']['tmp_name'];
$size = $_FILES['file1']['size'];
$name = $_FILES['file1']['name'];
$fileType = $_FILES['file1']['type'];
$num = $_POST['num'];
$num_chunks = $_POST['chunks'];
$namae = $_POST['namae'];

move_uploaded_file($tmp_name, $target_path.$num.$name);

// count ammount of uploaded chunks
$chunksUploaded = 0;
for($i = 0; $i <= $num_chunks; $i++){
    if(file_exists($target_path.$i.$name)){
        ++$chunksUploaded;
    }
}

//avengers...
if($chunksUploaded == $num_chunks){

    //reassemble
    for($i = 0;$i <= $num_chunks; $i++){
        $file = fopen($target_path.$i.$name, 'rb');
        $buff = fread($file, 2097152);
        fclose($file);

        $final = fopen($target_path.$namae, 'ab');
        $write = fwrite($final, $buff);
        fclose($final);

        unlink($target_path.$i.$name);
    }
}
?>

A: Como se menciona en el comentario, el primer error es el _, es el getElementById("file1")... Se puede reemplazar por querySelector agregando un # al principio.
document.querySelector("file1")

Lo siguiente no es común verlo en JavaScript:

console.log('files' in {"files": []})

Yo recomendaría usar la función Object.keys, o directamente comprobar que no sea null, de esta manera files.file == null... También es posible comprobar si existe, solamente escribiendo el nombre de la variable dentro del if, así... if(file.files){:

var file = {
  files: []
}
console.log(
  Object.keys(file).includes("files"),
  file.files != null,
)
if(file.files){
  console.log(true)
}else{
  console.log(false)
}

La siguiente manera de iterar se puede cambiar:
for(let i=0;i < file.files.length;i++){
  x = file.files[i];

Mejor usar for in en este caso:
for(let i in file.files){
  x = i;

El getElementsByClassName se puede cambiar por querySelector, agregando un punto al principio .txt_file_name:
if (x.name) {
  txt.querySelector('.txt_file_name')
    .innerHTML = 'Name: '+x.name;
};

En la siguiente línea veo que se está pasando un parámetro que no está siendo recibido por la función.
uploadComplete(p1, function(){snd_upload();console.log('se manda snd_upload')});

Es decir, no está recibiendo la función de retrollamada:
function(){snd_upload();console.log('se manda snd_upload')}

En su lugar, solo está recibiendo x:
function uploadComplete(x) {

Entonces, es mejor que reciba algún parámetro más, podría llamarse retrol, para que tenga nombre corto:
function uploadComplete(x,retrol) {

Para la barra de progreso recomiendo pedir una petición AJAX cada 100 milisegundos, o algo parecido, es un pedido que recibirá el número del porcentaje, estaría bien que use JSON para este caso.

*

*https://www.php.net/manual/es/function.json-encode.php
Un ejemplo:
$arr = array(
  'porcentaje' => "%10.5",
  'cantidad_de_archivos' => "10",
);
echo json_encode($arr);

Entonces desde JavaScript, se decodificaría así:
fetch("/progreso.json").then(function(x){
  return x.text()
}).then(function(respuesta){
  return JSON.parse(respuesta)
})


text:
Q: How can I use HttpRequestMessage.CreateResponse() in ASP.NET 5 I have empty Web API project as well as full MVC project created using VS2015. I notice HttpRequestMessage is in System.Net.Http, thats fine but not for the CreateResponse below:
This code is from my exception logger middleware that also return formatted json from previous Web API 2.
var resp = request.CreateResponse<HttpError>(HttpStatusCode.InternalServerError, new HttpError("Internal Server Error. Reference: " + guid), config);

I am struggling to find out the CreateResponse extension method that supposedly available in System.Net.Http.HttpRequestMessageExtensions as well as HttpError class. Both previously in  Microsoft.AspNet.WebApi.Core package.
After looking on ASP.NET 5 code, I believe it is only available in Microsoft.AspNet.Mvc.WebApiCompatShim. However it does not included in MVC sample project.
Questions:
What is WebApiCompatShim package and can I safely use it in the project?
What is the right way to CreateResponse from HttpRequestMessage?
Update
This WebApiCompatShimWebSite shows that WebApiCompatShim is

to get Web API 2.* like behavior

So seems just for compatibility purpose. I have to restructure the code. Now I discover the MVC doesn't have any message handlers feature and seems custom middleware is the way to go.

A: If you add the NuGet Package Microsoft.AspNet.WebApi.Core, you will get the extensions you are looking for.
reference: https://www.nuget.org/packages/microsoft.aspnet.webapi.core/

A: That is an extension method of HttpRequestMessage class.
You must reference to the below DLL which is included in Nuget Package Microsoft.AspNet.WebApi.Core:
Nuget\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll

This time you then can see CreateResponse method:
var response = request.CreateResponse(...)

A: According to:
https://docs.asp.net/en/latest/tutorials/first-web-api.html
You can achieve similar functionality by creating a new instance of ObjectResult (the status code can later be changed by setting the StatusCode property).


text:
Q: Screen turns of during boot and turns on for loginscreen again I have used Linux a lot in the last two years, and yesterday I installed Ubuntu again after a long term of using Debian. While there was nothing wrong during installation and even booting up a Live-version, while normal booting the screens turns off. More precisely: when I start the computer, the Screen turns on, runs through BIOS Post and finally shows up grub menu. After choosing Ubuntu, the screen turns off instantly (when normally the violet screen with the blinking dots appears), and keeps of until the boot is finished. Then it turns on and presents me the login screen.
While this is not such a big problem, I am wondering why this happens...
About my System:

*

*Intel Xeon E3-1231v3

*8GB DDR3 Ram

*Nvidia (9800GT) -> due to mysterious circumstances it became a 560 ti

*ASUS H97 Pro Gamer

*Hitachi/Apple 320G 2.5" HDD GPT Disk partition table

*Ubuntu fresh installed on the wiped disk (obviously in EFI mode)

What I've tried:

*

*update-grub

*Getting into tty works, the screen shows up everything fine

*Getting into tty during boot turns on the screen

*Getting into tty during boot randomly displays the boot animation (sometimes it does, sometimes not, eventually depending on when pressing CTRL+ALT+F1 ?)

A: It's a question of video support in the various stages of the boot process...

*

*Early on the firmware (EFI) is handling the video display. Everything up to and including GRUB relies on this support.

*Early in the Linux boot process, the kernel is in control of the display. The kernel has a number of video drivers, including both text-mode and video drivers, some of which are generic and some of which support specific cards. It sounds like the correct one is not being used, or it's been misconfigured in some way.

*Late in the Linux boot process, the X server takes over the display, and X has its own drivers. This is obviously working for you.

Given your symptoms, there's a chance that the kernel's text-mode video support is not working even after you boot the system. Ordinarily, if you hit Ctrl+Alt+F1 (or any other function key through F6), you should see a text-mode login screen. Hitting Alt+F7 (or occasionally F8) should bring you back to X. If this doesn't work, and you instead see a blank display, then your text-mode video support is bad. There are a number of possible more specific causes, like a lack of a video driver, the wrong video port being active (built into the motherboard vs. an add-on card, for instance), and the video driver doing something wrong for initializing the video card. You may be able to fix this by adding kernel options, but details depend on your video hardware and maybe even your computer. This question and answer provide suggestions for solutions to a more serious variant on this problem, and they might help you, too.
A less severe type of problem might be partially fixed by removing the quiet splash options from the kernel command line. You can do this in GRUB by hitting e to edit an entry, then removing quiet splash from the kernel options line. This variant assumes that the problem is just in the kernel's use of graphics mode and that text mode works fine. If this is the cause, then you'll probably be able to log in using text mode by hitting Ctrl+Alt+F1, and removing quiet splash at boot will result in a verbose text-mode boot rather than the boot with the Ubuntu logo. As with the previous scenario, adding kernel options might enable the regular logo to appear, but which options you'd want to use depends on your hardware and perhaps other factors. As I'm not an encyclopedia of solutions to these problems, I can't offer specific suggestions on what to try -- but the above linked-to question and answers might be helpful.
One more thing to note is that there are two or three sets of X drivers for Nvidia chipsets. Which one you use affects not just X, but kernel drivers, because some Nvidia drivers (especially the proprietary ones) require kernel support, which in turn means that the kernel needs certain drivers be active and others not. Thus, changing your X drivers can influence the behavior of the system before X even starts.
Overall, video support in Linux is a pretty complex web!


text:
Q: Infinite Redirects Taking Place after deleting .htaccess I recently migrated a wordpress site to a digital ocean droplet. I switched the DNS from namecheap to digital ocean and put the old wordpress site in a directory called /old/.
I then created an .htaccess file and tried to redirect my the root directory to /old using this:
Redirect 301 / /old
Nothing happened. I followed a couple guides and went into my apache2.conf file and changed the <Directory /var/www/> entry to AllowOverride All. I then ran sudo a2enmod Rewrite.
The first then that happened was that visiting my root directory redirected to /oldoldoldoldoldoldoldoldoldoldoldoldoldoldoldold/. I removed the .htaccess files and restarted Apache. Nothing changed.
I then went back into apache2.conf and changed AllowOverride All back to AllowOverride None. I then ran sudo a2dismod Rewrite.
I'm still getting the infinite redirects. Both / and /old redirect to /oldoldoldoldoldoldoldold...
I've restarted apache a bunch using sudo systemctl restart apache2. Nothing has helped; I'm still getting the redirects.
Sub directories, such as /old/wp-admin, work fine.
Any idea why this might be happening?

A: A 301 code means the redirect is intended to be permanent, as opposed to 302 which is temporary. Your browser cached them the first time you tried them, so any future changes you made to the Web server didn't actually matter, since your browser assumed the "permanent" redirect was still there instead of even hitting the server again. You need to clear your browser's cache to fix it.


text:
Q: Xamarin MvvmCross initialize popup menu in ViewModel Is it possible to initialize popup menu in a ViewModel?

For now I'm initializing it on View like this:
var button = activity.FindViewById(Resource.Id.moreButton);

button.Click += (s, arg) =>
{
    PopupMenu menu = new PopupMenu(activity, button);
    menu.Inflate(Resource.Menu.PopupMenu);
    menu.Show();

    menu.MenuItemClick += (s1, arg1) =>
    {
        switch (arg1.Item.TitleFormatted.ToString())
        {
            case "Profile":
                activity.StartActivity(typeof(ProfileView));
                break;
            case "Prices":
                break;
            case "Terms":
                activity.StartActivity(typeof(TermsView));
                break;
            case "Privacy":
                activity.StartActivity(typeof(PrivacyView));
                break;
        }
    };
};

But in my .axml files I want to bind "Open Popup Menu" button with MvxBind and so it would work. How can I do this?
UPDATE 1
Or maybe it is possible to bind clicks on xml file like this, because now it's not working obviously...
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:local="http://schemas.android.com/apk/res-auto">
 <item android:id="@+id/profile"
    android:title="Profile"
    local:MvxBind="Click GoProfileCommand"/>
  <item android:id="@+id/prices"
    android:title="Prices"/>
  <item android:id="@+id/terms"
    android:title="Terms"
    local:MvxBind="Click GoTermsCommand"/>
  <item android:id="@+id/privacy"
    android:title="Privacy"
    local:MvxBind="Click GoPrivacyCommand"/>


text:
Q: How to create a full page layout using pure semantic html + css I have this html body:

How can I make the footer sticky to the bottom in a way that it does NOT overlay the main part if this main part is bigger than the viewport of the browser?
I want to use only css for layout and no additional html elems.

A: Here's a working example:

html{
  height : 100%;
}
body{
  height : 100%;
  min-height : 100%;
}
header{
  background :red;min-height : 10%;
  float :left;
  width : 100%;
}

main{
 background :black;
  min-height : 80%;
  float :left;
  width : 100%;
  color : #ffffff;
}
footer{
  min-height : 10%;
  float :left;
  width : 100%;
  background :blue;
}

     qwe

     qwe

     footer

A: Well there are multiple ways to do so, please take a look here: https://css-tricks.com/couple-takes-sticky-footer/
But here a quick todo by simple using FLEX:

body {
    display: flex;
    min-height: 100vh;
    flex-direction: column;
}

main {
    flex: 1;
}

text

text

text

text

footer text

footer text

footer text

A: You can do this using Flexbox. See this for a complete guide to flexbox.
Check out this fiddle for a working demo:
https://jsfiddle.net/9fr83575/
Using flex-grow: 1; on your main will fill the remaining space.

flex-grow
  This defines the ability for a flex item to grow if necessary. It accepts a unitless value that serves as a proportion. It
  dictates what amount of the available space inside the flex container
  the item should take up.
If all items have flex-grow set to 1, the remaining space in the
  container will be distributed equally to all children. If one of the
  children has a value of 2, the remaining space would take up twice as
  much space as the others (or it will try to, at least).


text:
Q: Swift crashing when casting NSObject subclass to a non-objc protocol I've spent some time figuring this out. This code crashes:
public protocol FourLeggedAnimal: AnyObject {

}

public class Animal: NSObject {

}

public class Dog: Animal, FourLeggedAnimal {

}

public class AnimalProperty<Kind: Animal>: NSObject {

    let animal: Kind

    public init(animal: Kind) {
        self.animal = animal
    }

}

public class FourLeggedAnimalProperty<Kind: Animal>: AnimalProperty<Kind>, NSTextFieldDelegate {

    public override init(animal: Kind) {
        /// Since we cannot express in Swift that the Kind should be an Animal
        /// subclass confirming to a particular protocol, we use a force-cast
        /// which is not a pretty solution, but there aren't any options.

        /// And this crashes.
        let fourLeggedAnimal = animal as! FourLeggedAnimal
        print(fourLeggedAnimal)

        super.init(animal: animal)
    }

}

let dog = Dog()
let property = FourLeggedAnimalProperty(animal: dog)

The code crashes in Swift's library's getGenericPattern() function when you attempt to cas the dog to the FourLeggedAnimal protocol in the intializer.
Notes:

*

*The correct way should be to declare the generics as <Kind: Animal, FourLeggedAnimal>, however, when you do so, you can't call the init(animal:) initializer with Dog, even though it's Animal and FourLeggedAnimal.

*The app crashes even when you use a soft-cast, i.e. it's not a wrong cast, it's actually a bug in Swift's runtime.

A: The solution is to either declare the FourLeggedAnimal as @objc, or to make Animal not to inherit from NSObject.


text:
Q: How to access this hashmap value 'id' in MuleExpression to compare it with queryparam? I have a hashmap payload in my flow, I want to compare its 'id' key with 'id' queryparameter to go to specific flow using a choice router. How to give this condition in MuleExpression for Choice router?
Here is the hashmap payload:

A: #[ payload.id == message.inboundProperties.'http.query.params'.id ]


text:
Q: How to add/commit a new file to SVN with SVNKit Unable to add and commit a file to a subversion repository.
With the following code snippet:
SVNCommitClient svnCommitClient = svnClientManager.getCommitClient();
svnCommitClient.doCommit(new File[]{new File("project/README.txt")}, false, "Commit message", null, null, false, false, SVNDepth.INFINITY);

I get the following exception:
Exception in thread "main" org.tmatesoft.svn.core.SVNException: svn: E200009: Commit failed (details follow):
svn: E200009: 'D:\Java\POC\SvnKit\project\README.txt' is not under version control

Prompt what I did wrong, and I would like to see an example of how to

A: Welcome to Stackoverflow,
like the exception already tells you, the file you want to be committed is not under version control yet, so you have to add it first.
On your CommitEditor you should call something like this:
   SVNRepository repository = SVNRepositoryFactory.create( SVNURL.parseURIDecoded( url ) );

   ISVNEditor editor = repository.getCommitEditor( logMessage , null /*locks*/ , true /*keepLocks*/ , null /*mediator*/ );

   //the second and the third parameters are the path and revision respectively
   //of the item's ancestor if the item is being added with history
   editor.addFile( "your/path/project/README.txt" , null , -1 );

You should also have a look at the full example at SVNKit


text:
Q: undefined is not an object this.props.navigation.navigate react native I'm a newbie, and I created a react native app that contains a stack navigator, so I get this error when I click on a button to navigate from one page to another.
the App.js contains the app container:
export default class App extends React.Component {
  render(){
    return (
      <AppNavigator />
        );
  }

}
const AppDrawerNavigator = createDrawerNavigator({
  Welcome:{
    screen: WelcomeScreen
  },
  SeConnecter: {
    screen:ConnectionScreen} ,
  About : {
    screen: AboutScreen
  },
  list :{
    screen: ListMed
  },
});
const screens = {
  Welcome:{
    screen : AppDrawerNavigator
  },
  SeConnecter: {
    screen:AppDrawerNavigator
  } ,
  About : {
    screen: AppDrawerNavigator
  },
  list :{
    screen: AppDrawerNavigator
  },
}
const AppStackNavigator = createStackNavigator(screens,{
  defaultNavigationOptions:{
    title: 'MediClic',
    headerTintColor :'#fff',
    headerStyle :{
      backgroundColor:'#3498db',
      height: 100,
    },
    headerTitleStyle :{

      justifyContent:'center',
      fontSize: 30,
      fontFamily: 'serif',
      fontWeight:'bold'

    }

  }
});
const AppNavigator= createAppContainer(AppStackNavigator);

the welcome screen contains a component search that i created
class WelcomeScreen extends React.Component {
  render(){
    return (
      <View style={styles.container}>

          <Search navigation={this.props.navigation}/>

      </View>
    );
  }
export default WelcomeScreen

and then the component search where there is a textinput + a search button customized
class Search extends React.Component{
    constructor(props){
        super(props)
    }

    render(){

        return(

            <KeyboardAvoidingView style ={styles.main_container} behavior='padding'>
                <Text style={styles.text}>Trouvez votre Medecin!</Text>
                <TextInput style={styles.text_input}  placeholder='Médecin,Centre...' />
                <View style={styles.btn_ctr}>
                    <TouchableOpacity style={styles.btn} onPress={()=>this.navigation.navigate('ListMed') }>
                    <Text style={styles.btn_txt}>Rechercher</Text>
                    </TouchableOpacity>
                </View>
             </KeyboardAvoidingView>

        )
    }
}

Please help me i wasted a lot of times on this, i tried passing the navigation props to  it didn't work

A: <Search navigation={this.props.navigation}/>

as you pass this.props.navigation in navigation on Search component the function call will be - this.props.navigation
<TouchableOpacity style={styles.btn} onPress={()=>this.props.navigation.navigate('ListMed') }>

not this.navigation.navigate('ListMed')


text:
Q: Assinging multiple users to a task in Azure Devops Is there any way that a can assign multiple people or a group to a task item in Azure Devops?

A: Not now. This feature is registered and under review: Assign a Work Item to Multiple People
As a workaround, you can copy your task (Copy or clone a work item) and assign it to an additional user.


text:
Q: Ring isomorphic to endomorphism ring I have conflicting notes that say different things and I wanted some clarity. One says that $\text{End}_R (R) \cong R $ as rings but another says that if $M$ is a free $R$-module if rank $n$ then $\text{End}(M) \cong M_n (R^{\text{opp}}) $ which would seemingly imply that since $R$ is a module of rank 1 that $\text{End}(R) \cong R^{\text{opp}} $ which differs slightly from the first.

A: This occurs when one changes sides (or not) for the action of the endomorphisms. Suppose $M$ is a right $R$-module and that we write endomorphisms on the left (changing sides) so
$$ \mathrm{End}_R(M) = \{\theta\in\mathrm{End}_{\mathbb Z}(M)\mid\theta(mr)=\theta(m)r\textrm{ for all $m\in M$ and $r\in R$}\}, $$
In this case, when $M$ is free of rank $n$, we get
$$ \mathrm{End}_R(M) \cong \mathrm M_n(R). $$
For example, if $n=1$, then the isomorphism is given by rescaling, so $\lambda\in R$ corresponds to the endomorphism $m\mapsto\lambda m$, and the composition of endomorphisms $\lambda\circ\mu$ gives
$$ (\lambda\circ\mu)(m) = \lambda\mu m= (\lambda\mu)(m). $$
If instead we take a left $R$-module and write endomorphisms on the left (same side), then
$$ \mathrm{End}_R(M) = \{\theta\in\mathrm{End}_{\mathbb Z}(M)\mid\theta(rm)=r\theta(m)\textrm{ for all $m\in M$ and $r\in R$}\}. $$
In this case, when $M$ is free of rank $n$, we get
$$ \mathrm{End}_R(M) \cong \mathrm M_n(R^{\mathrm{op}}). $$
Again, if $n=1$, then $\lambda\in R$ gives the endomorphism $1\mapsto\lambda$, and $r=r1\mapsto r\lambda$. Composition of endomorphisms thus gives
$$ (\lambda\circ\mu)(1) = \lambda(\mu) = \mu\lambda = (\mu\lambda)(1). $$
For this reason I often find it better to change sides when considering the module structure and the endomorphisms, and since I prefer to write $\theta(m)$ I usually write endomorphisms on the left, and so consider right modules.


text:
Q: Stuck with mongodb connection in DigitalOcean app platform I'm stuck in connecting my Nestjs server to the MongoDB database both are on the same app platform in the digital ocean. The main problem is in providing the ca.certificate.crt file to the Nestjs server. I'm using MongoDB with typeorm and nestjs.

const mongodb_config: ConnectionOptions = {
  type: "mongodb",
  url: `${getValue("MONGO_URL")}/${MONGODB_DATABASE}`,
  name: DB_CONNECTION.MONGO_CONNECTION,
  entities: [LivePriceEntity],
  logging: ENVIRONMENT === ENVIRONMENTS.LOCAL,
  useUnifiedTopology: true,
  useNewUrlParser: true,
  ssl: ENVIRONMENT === ENVIRONMENTS.LOCAL ? false : true,
  sslValidate: ENVIRONMENT === ENVIRONMENTS.LOCAL ? false : true,
  sslCert: ENVIRONMENT === ENVIRONMENTS.LOCAL ? "" : SSL_CA_CERT,
  cli: {
    entitiesDir: "src/app/**/entities/*.entity{.ts,.js}",
  }
};

This is my typeorm connection config. Please help me out.


text:
Q: How to update Android Datepicker maxdate I have two datepickers in one activity. One datepicker has a MinDate set from the current day. The other one has a MinDate from the current day and MaxDate from the first choosen datepicker. It's working fine but when i change the first datepicker again, the MaxDate from the second datepicker isn't changing.
How can i change the MaxDate after changing the datepicker?
public class EventCreator extends AppCompatActivity {
    Button btnDate;
    TextView txtViewDate;
    Button btnDaterRes;
    TextView txtViewDateRes;
    TextView testtxt;
    int year_x,month_x,day_x;
    int year_res_x,month_res_x,day_res_x;
    static final int Dialog_id = 0;
    static final int Dialog_res_id = 1;
    SimpleDateFormat dateFormat = new SimpleDateFormat("DD-MM-YYYY");
    DatePickerDialog datePick;
    Calendar cal_max;
    DatePickerDialog datePickRes;
    long maxDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_creator);
        findViewById(R.id.txtResDatum);
        final EditText txtResUur = (EditText) findViewById(R.id.txtResUur);
         txtViewDate = (TextView) findViewById(R.id.txtViewDate);
         txtViewDateRes = (TextView) findViewById(R.id.txtViewDateRes);
        testtxt = (TextView) findViewById(R.id.testtxt);

        final Calendar cal = Calendar.getInstance();
        year_x  = year_res_x= cal.get(Calendar.YEAR);
        month_x = month_res_x= cal.get(Calendar.MONTH);
        day_x =  day_res_x = cal.get(Calendar.DAY_OF_MONTH);
        cal_max = Calendar.getInstance();

        showDialogOnClick();
    }

    public void showDialogOnClick(){
        btnDate = (Button) findViewById(R.id.btnDatePicker);
        btnDaterRes = (Button) findViewById(R.id.btnDatePickerRes);

        btnDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog(Dialog_id);
            }
        });

        btnDaterRes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog(Dialog_res_id);

            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        if(id == Dialog_id) {
            datePick = new DatePickerDialog(this, dpickerListner, year_x, month_x, day_x);
            datePick.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
            return datePick;
        }
        if(id == Dialog_res_id){
            datePickRes = new DatePickerDialog(this, dpickerListner_res, year_res_x, month_res_x, day_res_x);     datePickRes.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
            return datePickRes;
        }else{
            return null;
        }
    }

So when i set de date of the first datepicker, i want to update the MaxDate of the second datepicker.
    private DatePickerDialog.OnDateSetListener dpickerListner = new DatePickerDialog.OnDateSetListener(){
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth){
            year_x = year;
            month_x = monthOfYear + 1;
            day_x = dayOfMonth;
            String dateOfPicker = day_x + "/" + month_x + "/" + year_x;
            txtViewDate.setText(dateOfPicker);

            cal_max.set(year , monthOfYear, dayOfMonth);//Year,Mounth -1,Day
            maxDate = cal_max.getTimeInMillis();
            testtxt.setText(cal_max.getTime().toString());
            try {
                datePickRes.getDatePicker().setMaxDate(maxDate);
            }catch (Exception e){
                Log.d("Time: ", cal_max.toString());
            }
        }
    };

    private DatePickerDialog.OnDateSetListener dpickerListner_res = new DatePickerDialog.OnDateSetListener(){
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth){
            year_res_x = year;
            month_res_x = monthOfYear + 1;
            day_res_x = dayOfMonth;
            String dateOfPicker = day_res_x + "/" + month_res_x+ "/" + year_res_x;
            txtViewDateRes.setText(dateOfPicker);

        }
    };
}


text:
Q: Express 4 Routes Using Socket.io Having a rough time adding Socket.io in my Express 4 Routes. In my routes/index.js I have:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/message', function(req, res) {
  console.log("Post request hit.");
  // res.contentType('text/xml');
  console.log(appjs);
  io.sockets.emit("display text", req);
  // res.send('<Response><Sms>'+req.body+'</Sms></Response>');
});

module.exports = router;

but io is undefined. I have seen several examples of how to do this, but none that worked for me. Any help would be appreciated.

A: How about exploiting events? This could add an extra layer of self-awareness to the app, including socket messaging.
Since express's app() inherits from node's eventEmitter, I app.emit('EVENT_NAME', payload) at any point in my route handlers,
and then just handle that with app.on('EVENT_NAME', function(payload){})
with any logic available. I'm using it in my current setup.

A: You need to pass your socket.io variable to the router module so that it has access. You could do this by wrapping your module in a function call.
var express = require('express');
var router = express.Router();

/* GET home page. */
var returnRouter = function(io) {
    router.get('/', function(req, res, next) {
        res.render('index', {
            title: 'Express'
        });
    });

    router.post('/message', function(req, res) {
        console.log("Post request hit.");
        // res.contentType('text/xml');
        console.log(appjs);
        io.sockets.emit("display text", req);
        // res.send('<Response><Sms>'+req.body+'</Sms></Response>');
    });

    return router;
}

module.exports = returnRouter;

Then, whever you import this route you would call this function like: require(./routefile)(io)
Here's a good article about creating modules that require being passed a variable: Node.Js, Require and Exports

A: This is super old, but I was looking to do the same thing and didn't find a suitable answer. I came up with a good solution using app.set('socketio', io) and req.app.get('socketio') in my route.  I was then able to create a reference to the sender's socket in my route without using io.on().
See the answer I added here for the code:
Use socket.io inside a express routes file


text:
Q: How to move Primefaces-Upload-Temp-Files instead of doing a time intensive copy process? I want to upload files larger than 2 GB with Java EE with the use of primefaces. In general that it's not that big deal, but I have a little problem. The usually way with PrimeFaces is to upload a file, have that UploadedFile-Object, obtain the InputStream from that and then write it to disk.
But writing to disk large files is a time intensive task. Instead I would like to find the uploaded file in the file system and then move it to the folder, where I store all the files, because moving files is not wasting time.
So, according to this question here I figured out to set PrimeFaces-Tmp-folder and the size-limit, when files will put there. Now every uploaded file just goes directly into that folder. The point is, that I now have a file on disk, while the user is uploading - and not creating it afterwards.
So far, so good. I could identify the file and just move it (although it has a strange name). But pointing to Primefaces Userguide (Page 187), this Tmp-Folder is just used internally. And I even would steal the contents of the UploadedFile-Object from Primefaces. Seems not to be a clean solution to me.
Any hints how to achieve this ?
I also saw this question. Could also be my title, but it's not what I am looking for.
EDIT:
Because of the comment, some code. First I am collecting the UploadFile-Objects in the fileUploadListener:
   public void handleFileUpload(FileUploadEvent event) throws IOException {
    FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);

    getUploadedFilesDTO().add(new UploadedFileDTO(event.getFile(), uploadedFilesCounter));
    uploadedFilesCounter++;

}

Second in the EJB I am calling copyFile for every UploadedFile-Object:
private void copyFile(UploadedFile uploadedFile, String randomFilename) throws IOException {

    InputStream originalFile = uploadedFile.getInputstream();
    OutputStream fileOutput = null;

    try {
        fileOutput = new FileOutputStream("/pvtfiles/" + randomFilename);
        IOUtils.copy(originalFile, fileOutput);
    } finally {
        IOUtils.closeQuietly(fileOutput);
        IOUtils.closeQuietly(originalFile);
    }
}

A: I was able to do this by writing a custom filter, as AZ_ suggested, and adding the following:
FileItem fileItem = multipartRequest.getFileItem("form:fileUpload");
File file = new File(uploadDir + "/" + fileItem.getName());
fileItem.write(file);

The trick is to usethe MultipartRequest object to get the a FileItem object. FileItem's
write method can be used to save the file in a different location or using a different name. According to the documentation, some implementations may still do this with a copy, but what I am using (Apache Commons 1.3) seems to do this with a rename/move as desired. Note that the string used in getFileItem to find the FileItem is the ID attribute from the <p:fileUpload> tag.
More Code:
Modified portion of web.xml:
<filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>some.package.CustomFileUploadFilter</filter-class>
</filter>

Sample jsf:
<h:form id="form">
    <h:panelGrid columns="1" class="blockleft">
        <p:fileUpload
            id="fileUpload"
            auto="true" />
    </h:panelGrid>
</h:form>

Sample custom filter class:
package some.package;

import java.io.File;
import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.primefaces.webapp.MultipartRequest;
import org.primefaces.webapp.filter.FileUploadFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CustomFileUploadFilter extends FileUploadFilter {

    private static final Logger LOG = LoggerFactory.getLogger(CustomFileUploadFilter.class);

    private String thresholdSize;

    private String uploadDir;

    private final static String THRESHOLD_SIZE_PARAM = "thresholdSize";

    private final static String UPLOAD_DIRECTORY_PARAM = "uploadDirectory";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        thresholdSize = filterConfig.getInitParameter(THRESHOLD_SIZE_PARAM);
        uploadDir = filterConfig.getInitParameter(UPLOAD_DIRECTORY_PARAM);

        LOG.info("CatalogFileUploadFilter initiated successfully");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);

        if (isMultipart) {
            LOG.info("Parsing file upload request");

            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

            if (thresholdSize != null){
                diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize).intValue());
            }
            if (uploadDir != null){
                diskFileItemFactory.setRepository(new File(uploadDir));
            }

            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest, servletFileUpload);

            try {
                FileItem fileItem = multipartRequest.getFileItem("form:fileUpload");
                File file = new File("path/to/location/" + fileItem.getName());
                fileItem.write(file);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            LOG.info("File upload request parsed successfully, continuing with filter chain with a wrapped multipart request");

            filterChain.doFilter(multipartRequest, response);
        } else {
            filterChain.doFilter(request, response);
        }

    }
}

A: By creating your own filter It will not create temp files. Please read my answer below on another post
https://stackoverflow.com/a/19581257/185022


text:
Q: $select and $expand break ODataQueryOptions -- how to fix? We are using Microsoft ASP.NET MVC OData WebAPI for our web services. Because of some data architecture issues surrounding hierarchy ID (which are outside the scope of this conversation), some of our GET operations have to use ODataQueryOptions and manually manipulate the expression to add additional restrictions. We do so like this (error handling code removed and calls to other methods inlined for clarity):
public IQueryable<Person> Get(ODataQueryOptions<Person> oDataQueryOptions)
{
    IQueryable<Person> result;
    IQueryable<Person> dataSet = context.Persons;

    var tempQuery = oDataQueryOptions.ApplyTo(dataSet).Cast<Person>();
    var modifier = new HierarchyNodeExpressionVisitor(GetDescendantsOfNode, GetAncestorsOfNode);
    var expression = modifier.ModifyHierarchyNodeExpression(tempQuery.Expression);

    result = context.Persons.Provider.CreateQuery<Person>(expression);

    return result;
}

This has worked great for some time, but we've been eagerly awaiting select-and-expand so that we can better control the data we receive from our services. Monday we updated our dev environment to WebApi OData 5.0.0-rc1 and got select-and-expand working, but we can't use it against these services that use ODataQueryOptions. We can only use it against our other services. If we query the code above using $select and/or $expand, we get the following error:
"message": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"type": "System.InvalidOperationException",
"stacktrace": "",
"internalexception":
{
    "message": "Unable to cast the type 'System.Web.Http.OData.Query.Expressions.SelectAllAndExpand`1' to type 'OurCompany.Domains.Data.Models.Person'. LINQ to Entities only supports casting EDM primitive or enumeration types.",
    "type": "System.NotSupportedException",
    "stacktrace": " at System.Data.Objects.ELinq.ExpressionConverter.ValidateAndAdjustCastTypes(TypeUsage toType, TypeUsage fromType, Type toClrType, Type fromClrType) at System.Data.Objects.ELinq.ExpressionConverter.GetCastTargetType(TypeUsage fromType, Type toClrType, Type fromClrType, Boolean preserveCastForDateTime) at System.Data.Objects.ELinq.ExpressionConverter.CreateCastExpression(DbExpression source, Type toClrType, Type fromClrType) at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.CastMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) at System.Data.Objects.ELinq.ExpressionConverter.Convert() at System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.IEnumerable.GetEnumerator() at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteFeed(IEnumerable enumerable, IEdmTypeReference feedType, ODataWriter writer, ODataSerializerContext writeContext) at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders) at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.WebHost.HttpControllerHandler.d__10.MoveNext()"
}

I've done some Googling and stumbled upon this and this, but neither were helpful. Nobody appears to be doing quite what we're doing and trying to use select-and-expand. How do we fix this? I'm at a loss here...

A: The problem is in this line of code,
var tempQuery = oDataQueryOptions.ApplyTo(dataSet).Cast<Person>();

The Cast is invalid as once $select and $expand are applied the result is no longer a Person. It would be a Wrapper<Person> that contains only the properties that the client asked for. You might have to modify your HierarchyNodeExpressionVisitor to take this into consideration.
Also, try changing your action to this to handle the fact that the result might not be a IQueryable<Person> anymore.
    public IHttpActionResult Get(ODataQueryOptions<Person> oDataQueryOptions)
    {
        IQueryable result;
        IQueryable<Person> dataSet = context.Persons;

        IQueryable tempQuery = oDataQueryOptions.ApplyTo(dataSet);
        var modifier = new HierarchyNodeExpressionVisitor(GetDescendantsOfNode, GetAncestorsOfNode);
        var expression = modifier.ModifyHierarchyNodeExpression(tempQuery.Expression);

        result = context.Persons.Provider.CreateQuery(expression);

        return Ok(result, result.GetType());
    }

    private IHttpActionResult Ok(object content, Type type)
    {
        Type resultType = typeof(OkNegotiatedContentResult<>).MakeGenericType(type);
        return Activator.CreateInstance(resultType, content, this) as IHttpActionResult;
    }


text:
Q: Open existing file from stream of drill down data by SSRS in excel of Syncfusion I have the url of the file as below. First I want to download content of the file. The file has drill down from SSRS configuration. After that I am opening  a stream with the code app.Workbooks.Open(stream);
    using (var client = new WebClient())
    {
        var content = client.DownloadData(url); // Get Existing file

        Stream stream = new MemoryStream(content);
        stream.Position = 0;

        using (ExcelEngine xlsEngine = new ExcelEngine())
        {
            IApplication app = xlsEngine.Excel;
            IWorkbook workBook = app.Workbooks.Open(stream);
        }
    }

Syncfusion Version:
Syncfusion.XlsIO.Base, Version=15.4460.0.20

Question:
If I try to create a new workbook from existing stream (SSRS report has drill down) file I get the following error
object not set to an instance of an object

A: The issue is raised based on the worksheet data in your source document. So, it will be more easier to analyse, if you could share the below information

*

*The stack trace of the exception.

*The input document loaded as URL.

*Working version of Syncfusion Assemblies.

We have prepared simple sample to open the file retrieved from URL as stream and the sample can be downloaded from following link.
Sample Link: https://www.syncfusion.com/downloads/support/directtrac/general/ze/Sample84020950.zip
Regards,
Abirami.


text:
Q: How to calculate iterative independent event? Say you iteratively go through an event that has 1/800 success rate and 799/800 failure rate. What's the probability that you draw successfully within the first 100 attempts, or generally x attempts? is it as simple as 1/8?
Furthermore, say you now have a similar independent event but this time it has a 798/800 failure rate, but event A occurs 1/800 and event B occurs 1/800. A or B can only be drawn once, so once drawn it is removed from the table and the other event is now 2/800. What would be the likelihood of hitting both A and B within the first 100 attempts? What would be the likelihood of missing both within 800 attempts?
lastly, what branch of probability would these events come under as I don't know the terminology?
This question is in relation to a game drop table.


text:
Q: Modifying images for better OCR I'm using tesseract for optical character recognization of images which contain only single character per image but I'm having some problem in recognizing some characters.
I'm cropping the characters from a larger image and am saving them with pbm extension using convert. Here are some sample images :

These are four separate images. Letters 'S', 'P' and 'E' are recognized correctly but the letter 'T' is is not being recognized. There's a problem with few other characters too. Here's how I'm using the tesseract :
tesseract character.pbm stdout -l eng -psm 10

So, is there any way that I can improve the results? May be modifying the image in some way with convert?