text:
Q: Client/Server in java : Program gets stuck upon input of second file name I am developing code to send multiple file names to server side and then making sure server recieves those contents and writes it to a file in its own folder. Its working well when I type first file name but when I type second file name the code kind of gets stuck.
Here is my client code:-
package fileTransfer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class EchoClient {

public static void main(String[] args) throws UnknownHostException {

    try {
        Socket clientSock=new Socket("localhost",8888);

        //to read from server
        BufferedReader br=new BufferedReader(new  InputStreamReader(clientSock.getInputStream())); //to read

        //to write to server
        PrintWriter pw=new PrintWriter(clientSock.getOutputStream(), true);

        //for user input
        BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in));
        BufferedReader fileContent=null;
        String str=null;
        String fileContentLine=null;
        while(true){
            if((str=br.readLine()).contains("file name")) //recieve echo from server
                System.out.println(str);

            str=userIn.readLine(); //read user input
            fileContent=new BufferedReader(new FileReader(str));
            pw.println(str);
            while((fileContentLine=fileContent.readLine()) != null){
                pw.println(fileContentLine);
            }

            while((str=br.readLine())!=null)
                System.out.println(str);

            pw.flush();

        }

    }catch(IOException e){
        e.printStackTrace();
    }

}

}
And here is my server code
package fileTransfer;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {

 public static void main(String[] args){
    try {
        ServerSocket serverSock=new ServerSocket(8888);
        System.out.println("Waiting for client");
        Socket connectFromClient=serverSock.accept();

        File file=null;
        //reading data from client
        BufferedReader input=new BufferedReader(new InputStreamReader(connectFromClient.getInputStream()));

        //will write back to client
        PrintWriter pr=new PrintWriter(new OutputStreamWriter(connectFromClient.getOutputStream()));

        PrintWriter writeToFile=null;
        //sending following statements to client
        pr.println("Connection established with server! Give a file name");
        pr.flush();

        String response;

        while(true){

            while((response=input.readLine()) != null)
            {
            if(response==null)
                break;
            else{

            System.out.println(response);
            if(response.contains(".txt")){

                //file=new File("FromClient.txt");
                  file=new File("FromClient"+response);
                if(!file.exists())
                    file.createNewFile();
                writeToFile=new PrintWriter(file);
            }
            else{

                //writeToFile=new PrintWriter(file);
                writeToFile.println(response);
            }

            pr.println("Echo from server -> " + response);

            //System.out.println("Adding these contents to a file");
            writeToFile.flush();
            pr.flush();
            }
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

A: It´s getting stuck in the client in this lines:
 while ((str = br.readLine()) != null) {
     System.out.println(str);
 }

Waiting for more server lines.
You have to tell the client when to stop from reading file data from socket stream and jump for the next file. For instance you can send before the content of the file the number of bytes you are going to transfer, you read that number of bytes from the stream and then go for the next file.
I post this modifications of your code as an example, as the idea I want to express.
First I get the total linenumber of the file (I suppose text file), and I send it to server, which knows exactly how many lines to read before jumping to next file.
It can be changed to use the total size of the file in bytes, for instance.
This code is no 100% correct, it works, take it as an example.
Client:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;

    public class EchoClient {

        public static void main(final String[] args) throws UnknownHostException {

            try {
                final Socket clientSock = new Socket("localhost", 8888);

                // to read from server
                final BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); // to
                // read

                // to write to server
                final PrintWriter pw = new PrintWriter(clientSock.getOutputStream(), true);

                // for user input
                final BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
                BufferedReader fileContent = null;
                String str = null;
                String fileContentLine = null;
                while (true) {
                    System.out.println("Print filename");
                    str = userIn.readLine(); // read user input
                    fileContent = new BufferedReader(new FileReader(str));
                    pw.println(str);
                    // first count the line number:
                    int lineno = 0;
                    while ((fileContentLine = fileContent.readLine()) != null) {
                        lineno++;
                    }
                    fileContent.close();
                    //
                    fileContent = new BufferedReader(new FileReader(str));
                    pw.println(String.valueOf(lineno));
                    while ((fileContentLine = fileContent.readLine()) != null) {
                        pw.println(fileContentLine);
                    }

                    for (int i = 0; i < lineno; i++) {
                        str = br.readLine();
                        System.out.println(str);
                    }

                    pw.flush();

                }

            } catch (final IOException e) {
                e.printStackTrace();
            }

        }
    }

Server:
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;

    public class EchoServer {

        public static void main(final String[] args) {
            try {
                final ServerSocket serverSock = new ServerSocket(8888);
                System.out.println("Waiting for client");
                final Socket connectFromClient = serverSock.accept();

                File file = null;
                // reading data from client
                final BufferedReader input = new BufferedReader(new InputStreamReader(connectFromClient.getInputStream()));

                // will write back to client
                final PrintWriter pr = new PrintWriter(new OutputStreamWriter(connectFromClient.getOutputStream()));

                PrintWriter writeToFile = null;
                // sending following statements to client
                pr.println("Connection established with server! Give a file name");
                pr.flush();

                String response;

                while (true) {
                    final String fileName = input.readLine();
                    file = new File("FromClient" + fileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    writeToFile = new PrintWriter(file);
                    final String sLineNo = input.readLine();
                    final int lineno = Integer.parseInt(sLineNo);
                    for (int i = 0; i < lineno; i++) {
                        response = input.readLine();
                        System.out.println(response);

                        // writeToFile=new PrintWriter(file);
                        writeToFile.println(response);

                        pr.println("Echo from server -> " + response);

                        // System.out.println("Adding these contents to a file");
                        writeToFile.flush();
                        pr.flush();
                    }
                    writeToFile.close();
                }

            } catch (final IOException e) {
                e.printStackTrace();
            }

        }
    }

I Hope to be helpful.


text:
Q: K-theory of a classifying space (part two) Continuing my previous question, given a compact, connected Lie group $G$, there is a sequence of maps
$$R(G) \to \hat{R}(G) \overset\sim\to K^*(BG) \to \hat{H}^*(BG;\mathbb Q)$$
apparently first discussed by Atiyah and Hirzebruch.
The induced map $K^*(BG) \otimes \mathbb Q \to \hat{H}^*(BG;\mathbb Q)$ isn't an isomorphism; the basic point is that $\mathbb Q[[u]]$ is much bigger than $\mathbb Z[[u]] \otimes \mathbb Q$.
The obvious next question is what happens if one replaces $R(G)$ by $R(G) \otimes \mathbb Q$ at the beginning. I suspect (but am not sure) that things "work" then. To wit, approximate $EG \to BG$ by a sequence $E_n G \to B_n G$ of compact $n$-universal principal $G$-bundles (i.e., such that $\pi_{\leq n}(E_n G) = 0$). The sequence
$$R(G) \otimes \mathbb Q \to K^*(B_n G) \otimes \mathbb Q \overset\sim\longrightarrow H^*(B_n G;\mathbb Q)$$
then should induce in the limit isomorphisms
$$(R(G) \otimes\mathbb Q)^\wedge
\overset\sim\longrightarrow
\varprojlim \big(K^*(B_n G) \otimes \mathbb Q\big) \overset\sim\longrightarrow
\hat{H}^*(BG;\mathbb Q).$$
1. Is this right?
If that is correct, there's something else going on I don't understand. Because $\hat R(T)$ is a integral domain and torsion-free over $\mathbb Z$, the same holds of the Weyl invariants $\hat R(T)^W \cong \hat R(G)$. This should mean the obvious map to $\big(R(G) \otimes \mathbb Q\big)^\wedge \cong \hat H^*(BG;\mathbb Q)$ is an injection. This is all very well and satisfying if $\pi_1(G)$ is torsion-free, for then it is known that $R(G)$ is a polynomial ring on $\mathrm{rank}(G)$ generators and so is $H^*(BG;\mathbb Q)$. But this does not hold in general; for example, it is known that
$$R\big(\mathrm{PSU}(3)\big) \cong \mathbb Z[X,Y,Z]/(Z^3-XY)$$
although $\mathrm{PSU}(3)$ has rank $2$, and
$$H^*\big(B\mathrm{PSU}(3);\mathbb Q\big) \cong \mathbb Q[c_2,c_3], \qquad |c_j| = 2j.$$
So if the claim in my first question is right, the completion process makes one generator and one relation redundant.
2. In this example, what does the completion process do?
I should specify that although I found the description of $R\big(\mathrm{PSU}(3)\big)$ in the paper of Brylinski and Zhang, I'm not clear what relation these generators $X,Y,Z$ have to the fundamental representations and so in particular still don't know what the augmentation ideal is. Is there some place these computations are carried out so I could see what's happening?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to detect drawer notification in React Native? I tried to use AppState from react-native with the blur listener but nothing is showing up. I did the same exact code https://reactnative.dev/docs/appstate but the blur listener is not working. I just want to know when the notification drawer (https://developer.android.com/guide/topics/ui/notifiers/notifications#bar-and-drawer) appear on my application screen
  export default class AppStateExample extends Component {
  state = {
    appState: AppState.currentState
  };

  componentDidMount() {
    AppState.addEventListener("blur", this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener("blur", this._handleAppStateChange);
  }

  _handleAppStateChange = nextAppState => {
   console.log("test")
  };
}

Thank s for help !


text:
Q: Remember previous utterance I have a capsule where the user needs to provide Bixby an account name, property, and date range, then Bixby returns the result. What if the user wanted to check a different account with the same property and date range and the user's utterance is something like "What about the foo account?" How could I get Bixby to keep the property and date range from the previous utterance, but change the account name to search for?

A: In the language training, you can define a continuation of the goal.  That will allow you to filter on 'foo' in your action.

For example:
https://bixbydevelopers.com/dev/docs/dev-guide/developers/training.intro-training

A: By default, Bixby will use the conversation history to attempt to provide inputs that have not been defined by the user.
This means that, if the goal Action for your utterance "What about the foo account?" requires the property and date range inputs, Bixby will assume them from the conversation history if any exist.


text:
Q: "I'm looking for a shop with clothes" Can we say

I'm looking for a shop with clothes

For me it's not clear. It indicates that we are with these clothes, like with a friend?
Should be

I'm looking for a clothes shop.

I've done some research, but nothing found.

A: There is a dialect difference.
In the UK, The phrase "clothes shop" is natural and idiomatic.
In the USA, the phrase "clothing shop" is more common.
Fortunately, both are easy to understand by all English speakers.
These ngrams graphs show that both are common. But if you change to "American English" or "British English", you will see that "clothing shop" is more common in the USA.
You can also say "... a shop that sells clothes"  That is useful if you want to make it more complex "I'm looking for a shop that sells high-quality women's clothes in large sizes"

A:
I am looking for a clothing shop.

I hope you could explore the word "clothing" that was used in the sentence above.
As you see below, clothing represents collectively almost all the garments.
A clothes shop is okay too but personally I like a clothing shop for no reasons better than 'a clothes shop'.
https://www.vocabulary.com/dictionary/clothing
Clothing is what your wear, like sweaters, shirts, pants, dresses, and so on. Your favorite piece of clothing might be your purple polka dotted tights.
Clothing is made of fabric and covers our bodies, keeps them warm or protects them from the sun, insects, sharp rocks and thorns, and other hazards. In some situations, clothing keeps people safe, as when medical workers wear scrubs, gloves, and masks to protect themselves and patients from infection. Often clothing reflects your personal values or religion, like a Muslim woman's hijab that covers her hair. The Old English root is claþ, "cloth or woven material."


text:
Q: Eclipse : Importing web application Hi,
 I have to import some web application into Eclipse IDE.I know the way to import :
File->import->web->War file. But in my Eclipse IDE, I am unable to find web.I clicked on File->import, then a window was opened:
It contailns only :

*

*General & CVS & Install & Maven&Run & Debug&Tasks & Team & XML options only.There is now such option "Web". Where I can find it?..Please help me....

A: Ok I got what your eclipse is missing. Its "Web Tool platform for eclipse". Here is the link for it:
Web tool eclipse.
But remember that importing existing projects into Eclipse works only for projects that were created in Eclipse. Install it and the web perspective will appear in eclipse.
And you're definitely not dealing with an Archive File here.
Import from the File System just copies the resources but does not actually create an Eclipse project for you.
So I recommend you to build / create new web dynamic project, configuring all the required facets, and then just copy all the contents of your existing application to the WebContent of the project. But as I said first install the web tool plugin to eclipse. If you need more help let me know.
EDIT : Right click on your project and go to properties and then at the left side select "Project Facets" (If it asks for converting your project to facets, then do it, it helps a lot) then select your Facets.


text:
Q: How to implement JProgressbar for SimpleFileVisitor Class I have simple file visitor class which scans all drives within PC to find specific extensions like .txt. I want to display the progress of this operation with a JProgressBar. With each scan, the number of total matched files may change. This prevents me from calculating the percentage of the process to display on JProgressBar.
My code is based on this: Recursive Pattern Matching
How can I calculate and display the percentage when the total number of files is constantly changing?

A: The problem is, that you do not know in advance how many files you have. Generelly, you have the option to run through the file system twice: the first time, you just enter directories and only count all files.
Based on this number, you can then calculate a percentage on the second run, where you have a look at the files itself.
This obviously enlongates the process and again you do not have a progress on the first scan.
What you can do, is starting the first scan in a different thread. Assuming your pattern matching needs more time than just counting files, the counting will be faster and you can adjust the JProgressBar dynamically. It will then start unreliable and become more accurate over time.
I guess this aproach is similar to the one implemented in the windows copy mechanism. They also scan files first without progress information and then start copying with progress information. However, this may lead to effects you probably know from windows-machines where file operations have information like "2 hours left" and suddenly after 2 minutes it's done, or vice versa.
Edit:
Sorry, I just right now noticed that you want to iterate through all files on a hard drive and not just starting in some point.
You may sum the file size that you have seen already, if you know the free and total disk space, you can compute the percentage that is already done. However, the progress will most likely not be smooth because file sizes tend to be very different.

A: Using this example, execute your host operating system's find command in the background and display the results in the GUI. Because the number of files is unknown in advance, the program invokes setIndeterminate(true) on the progress bar. Here are some typical command lines:
ProcessBuilder pb = new ProcessBuilder("find", ".", "-name", "*.txt");
ProcessBuilder pb = new ProcessBuilder("dir", "/s", "*.txt");


text:
Q: jQuery alert box not working I have a tiny bit of code thats meant to show a javascript alert when a select list is changed value, but it doesnt seem to be working, could anyone give me a hand and let me know where im going wrong.
<script type="text/javascript">
$(document).ready(function(){
    $("#sources").change(function(e) {
        alert('This is what an alert message looks like.');
    });
});

HTML for the select is as follows:
<select name="sources" id="sources" multiple="multiple">
  <option value="">please select</option>
  <option value="5">Seek</option>
  <option value="6">friends</option>
</select>

A: Per your last comment, if jQuery is being used to generate the dropdown list on the fly, you need to use the .live() function to bind your dropdown:
$('#sources').live('change', function(e) { //do stuff });


text:
Q: knockout js selectedOptions is not working I have this code and I need to add default selected value
<select data-bind="options: items, optionsValue: `value`, optionsText:function(item) { return item.name},selectedOptions: selectedItems().item">

and I have this variable to make selected and it works if I am opening the selectedItems in advance like this
self.selectedItems = ko.observableArray([]);
self.selectedItems().item = ko.observable();

then I am adding default
self.selectedItems().item([self.info().item]);

this code is working fine, but in case when I am duing this, without making variable in advance
self.selectedItems().item = ko.observableArray([self.info().item]);

selectedOptions is not working,
can anyone tell me why it is not working? and how to solve this issue without adding a lot of variables in advance
thanks


text:
Q: Encrypting mapped network drives in Windows I have Win Server 2012 and the drives of one of the HDDs connected to it are mapped as network drives in a Windows 10 client. If I encrypt those drives using Bitlocker with the user account on the client, will it also be accessible for the admin account on the server? I want both users on the two machines to be able to access the encrypted content, how is it possible to do so?

A: For other readers; I realized that Bitlocker is basically a password/key-based encryption not tied to any Windows account; and after an encrypted drive is unlocked and opened, it behaves just like any other drives.


text:
Q: Inserting an element in list, at exact location, without array sizing in Python? I have already seen Create an empty list in python with certain size - Stack Overflow; but I just wanted to confirm - consider this MWE:
data = ( ( "x1", ( (3, "a"), (1, "b"),  (5, "c") )  ), ( "x2", ( (2, "a"), (4, "b") )  ) )

outputA = []

for ix in data:
  print ix[0] # x1, x2
  for isnip in ix[1]:
    outputA.append(isnip)

print outputA
# [(3, 'a'), (1, 'b'), (5, 'c'), (2, 'a'), (4, 'b')]

outputB = []

for ix in data:
  print ix[0] # x1, x2
  for isnip in ix[1]:
    outputB.insert(isnip[0], isnip)

print outputB
# [(3, 'a'), (1, 'b'), (2, 'a'), (5, 'c'), (4, 'b')]

outputC = [None] * (5+1) #[]
for ix in data:
  print ix[0] # x1, x2
  for isnip in ix[1]:
    outputC[isnip[0]] = isnip

print outputC
# [None, (1, 'b'), (2, 'a'), (3, 'a'), (4, 'b'), (5, 'c')]

I have data where there are 2D tuples (actually, in my real case, dicts, but nevermind that), whose first element is an ordering index; they are unsorted, and I need them sorted. However, they are at all possible levels of nesting (I have simplified data above for an easier example; in my real situation they can be nested even further), so I cannot easily issue a "sorted" command.
So I thought about inserting elements - as you can see, I cannot get .insert() to preserve the order. So I thought then about explicit assignment - and that works, but only if the list is sized beforehand; and to find the size, I still would have to go through an extra recursion, just to discover what the maximum index is.
Thus, I would like to insert at exact location (not "before" like .insert() does) of a list, but without explicitly sizing the list beforehand - is there any way that this can be achieved?

EDIT: Here is something more like my actual data, showing (hopefully) why it would be difficult to sort it:
data = ( ( "x1", ( (3, "a"), (1, "b"),  (5, "c") )  ), ( "x2", ( "x3", ( (2, "a"), (4, "b") ) )  ), ("x100", 1 ) )

outputA = []

for ix in data:
  #print "[0]", ix[0], "[1]", ix[1] # x1, x2, x100
  try:
    for isnip in ix[1]:
      #print "isnip", isnip[0], "-", isnip[1]
      if int(isnip[0]) == isnip[0]:
        outputA.append(isnip)
      else:
        raise Exception("not good")
  except:
    try:
      for isnip in ix[1][1]:
        #print "isnip", isnip[0], "-", isnip[1]
        if int(isnip[0]) == isnip[0]:
          outputA.append(isnip)
    except:
      #print "skipping this"
      pass

print outputA
# [(3, 'a'), (1, 'b'), (5, 'c'), (2, 'a'), (4, 'b')]

outputB = []

for ix in data:
  try:
    for isnip in ix[1]:
      if int(isnip[0]) == isnip[0]:
        outputB.insert(isnip[0]+1, isnip)
      else:
        raise Exception("not good")
  except:
    try:
      for isnip in ix[1][1]:
        #print "isnip", isnip[0], "-", isnip[1]
        if int(isnip[0]) == isnip[0]:
          outputB.insert(isnip[0]+1, isnip)
    except:
      #print "skipping this"
      pass

print outputB
# [(3, 'a'), (1, 'b'), (5, 'c'), (2, 'a'), (4, 'b')]

A: Think about your data as a tree:
data = ( "x", (
          ( "x1", (
             (3, "a"),
             (1, "b"),
             (5, "c"))),
          ( "x2", (
             (2, "a"),
             (4, "b")))))

I added a root node to bring it into a consistent format. What constitues a leaf in that tree?
def isleaf(x):
    return not isinstance(x[1], tuple)

Now you can just run a simple depth-first search to get the leaves in preorder:
def dfs(x):
    if isleaf(x):
        yield x
        return
    for y in x[1]:
        yield from dfs(y)

Example:
>>> list(dfs(data))
[(3, 'a'), (1, 'b'), (5, 'c'), (2, 'a'), (4, 'b')]
>>> sorted(dfs(data), key=lambda x: x[0])
[(1, 'b'), (2, 'a'), (3, 'a'), (4, 'b'), (5, 'c')]

This can be extended to any other tree-like data.
UPDATE: If you absolutely must avoid the sorting step for some reason, you can just collect the results in a dict and construct the array afterwards.
d = {}

def dfs(x):
    if isleaf(x):
        d[x[0]] = x
        return
    for y in x[1]:
        dfs(y)
dfs(data)

res = [None] * (max(d) + 1)
for i, v in d.items():
    res[i] = v


text:
Q: What is a jQuery Object? JavaScript kind of redefines what an Array means because an array is an object with a .length property and methods like .slice() and .join().
jQuery defines a jQuery object as "Array like", because it has a length property but it doesn't have certain array methods like join().
If I were to define the jQuery object as an object, and forget about mentioning anything to do with an array, how would I define it?  What properties does it have besides length?
I guess all the methods are what you see in the documentation, far exceeding the number of methods that are in an array.

A: A jQuery object is array-like which means that it contains zero or more indexes (properties which names are positive integers starting with zero). Besides those indexes, a jQuery object contains these properties:

*

*length

*context

*selector
And also around 140 inherited methods (which are defined on the jQuery.prototype object - you can do console.dir(jQuery.prototype) to get a full list... ).
Note that jQuery objects do not contain (or inherit) the Array methods (slice, substr, ...). If you want to execute those methods on your jQuery object, use call/apply.

For example, if you have 3 TEXTAREA elements on the page and you do this:
var j = $('textarea');

then this j jQuery object will contain these properties:

*

*0 - reference to the first TEXTAREA element

*1 - reference to the second TEXTAREA element

*2 - reference to the third TEXTAREA element

*length - which is 3

*context - reference to the document object

*selector - which is 'textarea'

*plus all those inherited methods...

A: the jQuery object is an object which has

*

*a length property

*numeric properties which reference the items from the select (0,1,2,3...)

*bindings to jQuery functions

*additional jQuery properties

The length and numeric properties allow the object to respond like an array.  You can run it in a for loop or use functions like map or each on it.
I would recommend using your browser's debugger or Firebug and inspect a jQuery object.  That will teach you a lot about how it is structured.


text:
Q: How to stop Flux buffered writes consistently? I have an event stream as input, want to do a series of transformations on them, then buffer them up into a List, and finally perform a batched write in another system. Once the input stream has been drained I want to manually stop this process which needs to flush the remaining buffer into a write. What is the best way to get this to work consistently?
Example:
Flux.from(<source>)
    .map(<some transform>)
    .buffer(4096)
    .subscribe(<batched writer that takes a List>)

With the above, if I cancel the batched writer subscription I will lose whatever is pending in the buffer. Is there any way I can "complete" the original source, thus causing a flush/drain in the whole pipeline, to ensure no events gets lost?


text:
Q: CGRect change origin in Swift https://drive.google.com/file/d/1Nd6q9OmDppJrxjZIRODzffVDiBXKnB_e/view?usp=sharing
I'd like to change the position of the 'origin' like a picture for compose the watermark.
Bellow is my code.
var watermark = UIImage(named: "logo.png")
var newHeight = filteredImage.image?.size.height
var newWidth = filteredImage.image?.size.width

UIGraphicsBeginImageContext(CGSize(width:newWidth!, height:newHeight!))

watermark.draw(in: CGRect(x:-0, y:-0, width:400, height:300))

let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

watermark = newImage!

filter = CIFilter(name: "CISourceOverCompositing")
filter!.setValue(CIImage(image: watermark), forKey: "inputImage")
filter!.setValue(coreImage1, forKey: "inputBackgroundImage")

How should I change my code?

A: If you want to place watermark to right bottom corner, use:
var watermark = UIImage(named: "logo.png")!
var newSize = filteredImage.image.size

UIGraphicsBeginImageContext(newSize)

watermark.draw(in: CGRect(
    x: newSize.width - watermark.image.width,
    y: newSize.height - watermark.image.height,
    width: watermark.image.width,
    height: watermark.image.height
))

...

Changing the origin is possible but impractical in this case.


text:
Q: I'm just not getting the method
In the first ∆ , it's 5 + 6 + 4 = 15 which is equal to the 15 inside.
But in the 3rd ∆ it's not!!
There's no way visible through which I can get the answer.
( Question no. 26 )

A: Such questions are not proper maths and are actually ridiculous - and here's why:
Consider any function from $f: \mathbb{R}^3 \rightarrow \mathbb{R}$. According to the question, it is given that $f(5,6,4) = 15$ and $f(4,8,8) = 8$. Using this, you have to find the value of $f(6,7,12)$?
There are uncountably infinite functions which could satisfy the constraints of the problem. Even if you restrict the range and domain of $f$ from $\mathbb{R}$ to $\mathbb{N}$, you still get countably infinite possible answers.

A: Hint:
$2 \times \frac{5 \times 6}{4} = 15$

A: I completely agree with @Kaind's answer. Let me give an example to make it a bit clear (or to make it lot confused).
Let's say your pattern is $$\dfrac{\text{left most number} \times \text{right most number}}{\text{position of the triangle}+1}.$$ Then you will get $14$ as the answer, which will be different from the answer you get according to @Jens.


text:
Q: Decoding then re encoding bit masks on int with bitwise operations so I have two flags, and I can decode them correctly... but when I try to encode it again.. I'm getting a negative number.. but when I try to decode that negative number it decodes it correctly... so I'm confused why it's working but isn't getting the expected result
const encoded = 3221225525;
const  FLIPPED_HORIZONTALLY_FLAG = 0x80000000;
const  FLIPPED_VERTICALLY_FLAG   = 0x40000000;
const  FLIPPED_DIAGONALLY_FLAG   = 0x20000000;

function decodeTileId(tileId){
    let flipHor = !!(tileId & 0x80000000);
    let flipVer = !!(tileId & 0x40000000);
    let flipDiag = !!(tileId & 0x20000000);
    tileId &= ~(FLIPPED_HORIZONTALLY_FLAG |
        FLIPPED_VERTICALLY_FLAG |
        FLIPPED_DIAGONALLY_FLAG);

    return { tileId, flipDiag, flipVer, flipHor }
}

var obj = decodeTileId(encoded);
var { tileId, flipVer, flipHor, flipDiag } =obj;
//tile id is 53 here and flags are correct.

if(flipVer && flipHor) { // these were the flags set to true... try to re-encode
  tileId |= FLIPPED_VERTICALLY_FLAG;
  tileId |= FLIPPED_HORIZONTALLY_FLAG;
 //tileId becomes -1073741771 which if i put through the decode function... i get the same result as 3221225525
}


text:
Q: Trouble installing android studio After downloading the Android Studio installer from the website and running it.
I then get these error messages:

then

I have Java installed as well, but the most recent version of java that I got off of the website only came with a jdk and not a jre. But, I have seen videos of people running java with only the jdk and after running javac on my computer it works fine there.
I have googled a few answers and none of them have works and I'm considering reimaging my computer again. I have tried a method using regedit and system file checker tool recently and both haven't done the trick. I have had this issue for a while so I can't remember all of the fixes I have tried.
If anyone could be of assistance it would be a great help.

A: From the error popups it seems that you are trying install 64 bit android studio setup on 32 bit window system. Please check then download 32 bit version and try installing it.


text:
Q: Magento Rest "Admin role not found" error I'm playing with scribe library (https://github.com/fernandezpablo85/scribe-java), trying to get access to a Magento store products, but I'm facing some problems (it's probably Magento configuration).
I'm using the following code:
OAuthService service = new ServiceBuilder().provider(Magento17Api.class).apiKey(MAGENTO_API_KEY).apiSecret(MAGENTO_API_SECRET).build();
OAuthRequest request = new OAuthRequest(Verb.GET, MAGENTO_REST_API_URL
    + "/products");
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println(response.getBody());

But I'm always receiving this response:
{"messages":{"error":[{"code":0,"message":"Admin role not found"}]}}

What am I missing?

A: I found the solution...
You should go to Magento Admin -> System -> Permissions -> Users -> Edit YOUR user and give it an "admin" permission in the "Rest Role" tab.


text:
Q: AngularJS populating an object in a factory that is accessible throughout the website I have a user factory that has an object called userProperties that I populate when a user logs in to the system. A function named login() is then called that calls a function named set() that "sets the user", or populates the userProperties object.
user.factory.js
(function () {
    'use strict';

    angular
        .module('app')
        .factory('user', user);

    /* @ngInject */
    function user($http, authToken, $q, $state) {

        var userProperties = {};

        return {
            login: login,
            logout: logout,
            set: set,
            isSet: isSet,
            get: get,
            isLoggedIn: isLoggedIn
        };

        function login(email, password) {
            return $http.post('/api/login', {
                email: email,
                password: password
            }).then(function (response) {
                authToken.setToken(response.data.jwt);
                set(response.data.user);
                return response;
            });
        }

        function logout() {
            authToken.setToken();
            $state.go('login');
        }

        function set(data) {
            userProperties = data;
        }

        function get() {
            return userProperties;
        }

        function isSet() {
            return !isEmpty(userProperties) ? true : false;
        }

        function isLoggedIn() {
            return authToken.getToken() ? true : false;
        }

        function isEmpty(obj) {
            for (var prop in obj) {
                if (obj.hasOwnProperty(prop)) { return false; }
            }
            return true;
        }

    }

}());

I am then able to use this code in controllers throughout the website. For example inside Header controller, Home controller, Profile controller etc.
But if I don't login manually, but refresh the site, then I have a problem because then I am not populating the userProperties object as I did when someone logged in. So I need to do a check when people click the refresh button.
Something similar to the code below. I tried to run this code in a run block before everything else in the app, but still did not appear in controllers because it is async.
if (user.isLoggedIn() && !user.isSet()) {
    $http.get('/api/user/0') // id: 0 is the id of the logged in user
        .then(function (response) {
            user.set(response.data);
        });
}

but the problem here is that even if I do this I can't use the user factory in controllers and access the userProperties object that got populated because it is async.
Profile.controller.js
(function () {
    'use strict';

    angular
        .module('app')
        .controller('Profile', Profile);

    /* @ngInject */
    function Profile($scope, user) {
        $scope.user = user.get();
        console.log($scope.user);
    }

}());

the code above for Profile controller outputs an empty object to the console.
My alternative is to do something like this in ui-router, resolve it before Profile controller and set the user here. But then I have to do this everywhere I need the user. In Home controller, in Header controller and so on.
.state('profile', {
    url: '/user/:id',
    templateUrl: 'app/profile/profile.tpl.html',
    resolve: {
        userResolve: function ($http, $q, user) {
            return $http.get('/api/user/0')
                .then(function (response) {
                    user.set(response.data);
                });
        }
    },
    controller: 'Profile'
});

What should I do in order to do this once and have it available throughout the website? Or do I need to resolve before every state?


text:
Q: SearchCriteriaBuilder->addFilters() using multiple filters As per title.
This what I've done:
    $filterCode = new Filter();
    $filterCode->setField('SpecialCode')
        ->setValue('')
        ->setConditionType('null');
    $filterItemId = new Filter();
    $filterItemId->setField('ItemId')
        ->setValue('')
        ->setConditionType('null');

    $searchCriteria = $this->searchCriteriaBuilder
        ->addFilters([$filterCode, $filterItemId])
        ->create();
    $customItems = $this->customItemRepository->getList($searchCriteria)->getItems();

What I'm getting is a collection of items with NULL ItemID or NULL SpecialCode (or I have no idea what I'm getting), when what I want is more like this:
select * from ItemRepository where ItemId is null and SpecialCode is null;  //I'm pretty sure what I would get from this

How do I create multiple filters and set conditional ANDfor those filters?

A: In the constructor, notice that I appended the word "Factory" to the classname of the collection. This is a non-existent factory class that Magento will actually create for you. In the function, where I call $this->collectionFactory->create();, that tells Magento to give me a new instance of the collection. It's the same as doing new \My\Custom\Collection(); except for the fact that you do not lose any functionality that might be provided by Magento's object manager. Following this example, this is the same way you would deal with getting rid of new Filter() and instead pass FilterFactory as a constructor argument.
Anyways, with that out of the way, you really don't need the search criteria builder for this task. Simply replace \My\Custom\Collection with the actual name of your collection and this will work.
Reminder: when you create the constructor in your class, if your class extends any other PHP class, don't forget to include the parent classes constructor args and pass them back up to the parent class.
The call to the collection with the filters, as shown, will give you a query exactly as you asked for above.
<?php

class MyCustomClass
{
    /**
     * @var \My\Custom\CollectionFactory
     */
    private $collectionFactory;

    /**
     * MyCustomClass constructor.
     *
     * @param \My\Custom\CollectionFactory $collectionFactory
     */
    public function __construct(
        \My\Custom\CollectionFactory $collectionFactory
    ) {
        $this->collectionFactory = $collectionFactory;
    }

    /**
     * @return \My\Custom\Collection
     */
    public function getFilteredCollection()
    {
        /** @var \My\Custom\Collection $collection */
        $collection = $this->collectionFactory->create();
        $collection->addFieldToSelect('*');
        $collection->addFieldToFilter('ItemId', ['null' => true]);
        $collection->addFieldToFilter('SpecialCode', ['null' => true]);

        return $collection;
    }
}

Version of answer using the SearchCriteriaBuiler. Also, please note that since I know nothing of your custom collection, I wrote this with the OrderItemRepository. You will just need to replace the repository with your own of course and obviously switch out the field names.
<?php

class MyCustomClass
{
    /**
     * @var \Magento\Sales\Api\OrderItemRepositoryInterface
     */
    private $orderItemRepository;

    /**
     * @var \Magento\Framework\Api\SearchCriteriaBuilder
     */
    private $searchCriteriaBuilder;

    /**
     * MyCustomClass constructor.
     *
     * @param \Magento\Sales\Api\OrderItemRepositoryInterface         $orderItemRepository
     * @param \Magento\Framework\Api\SearchCriteriaBuilderFactory     $searchCriteriaBuilderFactory
     */
    public function __construct(
        \Magento\Sales\Api\OrderItemRepositoryInterface $orderItemRepository,
        \Magento\Framework\Api\SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory
    ) {
        $this->orderItemRepository = $orderItemRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilderFactory->create();
    }

    /**
     * @return \Magento\Sales\Api\Data\OrderItemSearchResultInterface
     */
    public function getFilteredList()
    {
        $this->searchCriteriaBuilder->addFilter('applied_rule_ids', true, 'null');
        $this->searchCriteriaBuilder->addFilter('weight', true, 'null');
        $collection = $this->orderItemRepository->getList(
            $this->searchCriteriaBuilder->create()
        );

        return $collection;
    }
}


text:
Q: Rand Index to compare two different labels' size I want to compare two partitions using Adjusted Rand Index.
The first partition contains n clusters separated(no-overlap).
The 2nd contains m clusters overlapped.
When an element exists in 2 different clusters, I count it twice and give it two different indices. That cannot be applied to ARI.
This illustration is intended to make the problem clearer :
Let S and P be 2 partitions where :
S={CLUSTER1, CLUSTER2}
CLUSTER1={A,B}
CLUSTER2={C}

The indices'vector associated to S is : V1=[1,1,2]
P={Group1, Group2, Group3}
Group1={A}
Group2={A,B}
Group3={B,C}

The indices'vector associated to P is : V1=[1,2,2,3,3]
That of course won't work. Because beyond the problem of sizing, there is no order.
Do you have ideas about this problems resolution ?
I am thinking about testing S with P' and S with P" ... where P' is a partition that looks a bit like P but where there is no overlap. For example : P'=[{}, {A,B}, {C}]


text:
Q: Stratified split for instance segmentation problem Instance segmentation is a problem where you have a set of images $X = \{x_i\}_{i=1}^{N_{imgs}}$ and with every image you have associated labels. Labels are polygons which provide accurate location of the objects of a given class within an image. Let's say we have "sheep", "dog", "cat" and "horse" classes.

In the image above we have 1 dog and 3 sheep. We can describe this with a vector $\mathbf{v} = [3, 1, 0, 0]^T$ which provides class counts for this image (with every class instance we have associated label which is a polygon but that is not important for the problem at hand). In the overall $X$ dataset we have a certain distribution of the class counts which we may obtain by summing $\mathbf{v}$ vectors for all images and normalizing. We want to split the $X$ dataset into training and testing subsets, where test subset consists of $M$ samples (does not need to be exact) and the distribution of class counts for these subsets is as similar to the original as possible. It is important that for example if we have only 2 instances of a horse in our $X$ dataset (in separate images) that 1 image goes into training and 1 into test subset. Keeping the same distribution between training and test sets is in general an important assumption in machine learning especially when minority classes exist in the dataset. Precise mathematical formulation of the problem is given below:
Let V = $\{\mathbf{v}_i\}^{N}_{i=1}$, $N \in \mathbb{N}$ be a set of vectors s.t. $\mathbf{v}_i \in \{ \mathbb{N} \cup \{ 0 \} \}^k, k \in \mathbb{N}$. Let $\mathbf{p}_V = \frac{ \sum_{\mathbf{v} \in V} \mathbf{v} }{ \| \sum_{\mathbf{v} \in V} \mathbf{v} \| }$, $r \in (0,1)$ and  $M = \lfloor r \cdot N \rfloor$.
We want to find $S \subset V$ s.t. |S| = M and $S$ maximizes $L_{Total}(S) = L(S) + L(V \setminus S)$, where $L(S) = cos(\mathbf{p}_S, \mathbf{p}_{V})$, $L(V \setminus S) = cos(\mathbf{p}_{V \setminus S}, \mathbf{p}_{V})$,   $\mathbf{p}_S = \frac{ \sum_{\mathbf{v} \in S} \mathbf{v} }{ \| \sum_{\mathbf{v} \in S} \mathbb{v} \| }$, $\mathbf{p}_{V \setminus S} = \frac{ \sum_{\mathbf{v} \in V \setminus S} \mathbf{v} }{ \| \sum_{\mathbf{v} \in V \setminus S} \mathbf{v} \| }$.

A: You can solve the problem via mixed integer nonlinear programming (MINLP) as follows.  For $i\in \{1,\dots,N\}$, let binary decision variable $x_i$ indicate whether $v_i\in S$.  The problem is to maximize $\cos(p_S,p_V)+\cos(p_{V\setminus S},p_V)$ subject to
\begin{align}
p_S &= \frac{\sum_i x_i v_i}{||\sum_i x_i v_i||} \\
p_{V\setminus S} &= \frac{\sum_i (1-x_i) v_i}{||\sum_i (1-x_i) v_i||} \\
\sum_i x_i &= M
\end{align}
If are willing to change the measure of similarity, there are also linear (MILP) approaches.


text:
Q: proof of optimal path in a triangle ABC I'm having a hard time proving this problem.
"Given a triangle ABC, call a hub point H a trisection point if the three angles formed by AH, BH, and CH are equal. For a triangle with no angle greater than 120◦, show that the network with a trisecting hub gives a strictly shorter total length than the shortest path along the edges."
I get stuck at the part where I need to show that the lengths of the three lines extending from H to each vertex are shorter than the perimeter of the triangle.

A: Consider triangle HBC. Since $\angle BHC = 120^0$, we can say that BC must be the longest. In particular, BC is longer than HC. Similarly, ....

A: If $H$ is at the origin of our coordinate system and $A$ at $(1,0)$, then $B$ is at $(-u,u\sqrt 3)$ and $C$ at $(-v,-a\sqrt 3)$ for some positive $u,v$.
The length of $AB$ is given by  $$|AB|^2=(1+u)^2+(u\sqrt3)^2=1+2u+4u^2=\frac34+\left(\frac12+2u\right)^2$$
so that
$$ |AB|>2u+\frac12$$
Likewise,
$$ |AC|>2v+\frac12.$$
On the other hand,
$$ |HA|=1,\qquad |HB|^2=u^2+3u^2=4u^2,\qquad |HC|^2=4v^2.$$
We conclude
$$ |HA|+|HB|+|HC|=2u+2v+1<|AB|+|AC|$$


text:
Q: How to resize the element using jsPlumb? In my application I need to resize the elements. Here I found the perfect example
[http://jsfiddle.net/sporritt/HUKMC/9/][1]

but its not working in my code.
Even when I used the same code without changing it, it didn't work for me.
Any help?
Thank you!

A: Without posting your code it is difficult to debug. Make sure that the object which is resizable is set with below class:
$('#resizable').addClass('ui-widget-content');


text:
Q: how to delete everything between the brackets? s="function(function()function(hii))wait function(function(byee))"

for this string i need output like this
function()wait function()

how to delete the content between the brackets?
def filter_line(line):
    count=0
    ignore=False
    result=[]
    for c in line:
        if c==")" and count!=0:
            count=0
            ignore=False
        if not ignore:
            result.append(c)
        if c=="(" :
            ignore=True
            count=1
        print(count)
    return "".join(result)

i got this code from here and i got output for my problem as
function()function())wait function())

A: s = "function(function()function(hii))wait function(function(byee))"
brack = 0
t = ""
for letter in s:
    if letter == '(':
        brack += 1
        if brack == 1:
            t += letter
        continue
    elif letter == ')':
        brack -= 1
        if brack == 0:
            t += letter
        continue

    if not brack:
        t += letter

output:

function()wait function()

You can change the solution a bit and optimize it for readability, behavior, and performance, but I chose to keep it similar to yours.

A: Here is the regex way
input_str = "function(function()function(hii))wait function(function(byee))"
pattern = r"(function\().*(\)wait function\().*(\))"
output = re.sub(pattern, r"\1\2\3", input_str)
print(output)

Output:
function()wait function()


text:
Q: Javascript loop through JSON object What I am trying to do exceeds my knowledge. Thank you all for your time and help, it is a great pleasure to have the support of such a large community of great developers.
The problem
I need to loop over an object (JSON response) to determine which data is true and then edit the html with the results.
json object is:
  var data = {
  "total": 4,
  "limit": 50,
  "questions": [{
    "date_created": "2015-06-29T18:24:25.000-04:00",
    "item_id": "MLA567045929",
    "seller_id": 186626557,
    "status": "UNANSWERED",
    "text": "Pregunta de Testeo, user 2.",
    "id": 3612747353,
    "deleted_from_listing": false,
    "hold": false,
    "answer": null,
    "from": {
      "id": 186625262,
      "answered_questions": 0
    }
  }, {
    "date_created": "2015-06-29T18:30:16.000-04:00",
    "item_id": "MLA567045929",
    "seller_id": 186626557,
    "status": "UNANSWERED",
    "text": "Lorem ipsum dolor sit amet",
    "id": 3612938882,
    "deleted_from_listing": false,
    "hold": false,
    "answer": null,
    "from": {
      "id": 186625262,
      "answered_questions": 0
    }
  }, {
    "date_created": "2015-06-29T18:30:35.000-04:00",
    "item_id": "MLA567045929",
    "seller_id": 186626557,
    "status": "UNANSWERED",
    "text": "an est odio timeam quaerendum",
    "id": 3612752695,
    "deleted_from_listing": false,
    "hold": false,
    "answer": null,
    "from": {
      "id": 186625262,
      "answered_questions": 0
    }
  }, {
    "date_created": "2015-06-29T18:31:32.000-04:00",
    "item_id": "MLA567045929",
    "seller_id": 186626557,
    "status": "ANSWERED",
    "text": "Responder esta pregunta",
    "id": 3612753455,
    "deleted_from_listing": false,
    "hold": false,
    "answer": {
      "text": "Pregunta respondida",
      "status": "ACTIVE",
      "date_created": "2015-06-29T18:31:58.000-04:00"
    },
    "from": {
      "id": 186625262,
      "answered_questions": 1
    }
  }],
  "filters": {
    "limit": 50,
    "offset": 0,
    "is_admin": false,
    "sorts": [],
    "caller": 186626557,
    "seller": "186626557"
  },
  "available_filters": [{
    "id": "item",
    "name": "Item",
    "type": "text"
  }, {
    "id": "from",
    "name": "From user id",
    "type": "number"
  }, {
    "id": "totalDivisions",
    "name": "total divisions",
    "type": "number"
  }, {
    "id": "division",
    "name": "Division",
    "type": "number"
  }, {
    "id": "status",
    "name": "Status",
    "type": "text",
    "values": ["BANNED", "CLOSED_UNANSWERED", "DELETED", "DISABLED", "UNDER_REVIEW"]
  }],
  "available_sorts": ["item_id", "from_id", "date_created", "seller_id"]
};

The result I'm looking for is:
Of the data object, I need to extract questions with the status unanswered and the id field associated with these unanswered questions.
 "questions1":[{  "status" : "UNANSWERED",
                "id" : 3612747353}],
"questions2":[{  "status" : "UNANSWERED",
                "id" : 3612938882}],
 ...

Based on what I've searched, I've tried with loops, for in, and each without success.
Any suggestions or ideas on how I could achieve the desired result? I need to apply this example to several objects.

A: Try some handy list processing functions to simplify it conceptually. The filter and map functions will help. The function I provided to filter tells it to only let through items that meet the condition of having an unanswered status. The function I provided to map turned all the objects that came out of filter into just their ids.
data["questions"].filter(function(obj) {
    return obj["status"] === "UNANSWERED";
}).map(function(obj) {
    return obj["id"];
});

A: var results = [];
for (var question in data.questions) {
  if (data.questions[question].status === "UNANSWERED") {
    results.push({
      "status" : data.questions[question].status,
      "id" : data.questions[question].id
    });
  }
}

// Now results contains an array of unanswered questions,
// with just their status & id.

A: You can just loop through the questions and save the ids you want to an array:
var questions = data.questions;
var unanswered = [];
for(var i = 0, len = questions.length; i < len; i++) {
    if(questions[i].status === 'UNANSWERED') {
        unanswered.push(questions[i].id);
    }
}

unanswered will be an array of unanswered question ids. You don't need to save the status; you know they are all 'UNANSWERED'.


text:
Q: Toggle Mongo Document Date Property With Single Query Knowing just the _id of a document in Mongo is there a straightforward way to write ONE update query to do the following? I think the answer is "no", but I'd like to know about it if there is something that does let this happen.

*Target a document by _id (single document).

*If the readAt field exists on the document, remove it

*If the readAt field does NOT exist on the document, set it to the current time

Essentially, I want to "toggle" the "read" state (using a Date as a flag) of the document without actually first fetching the document.
Currently I'm using something like:
collection.update(
  {_id: notificationDoc._id},
  notificationDoc.readAt
    ? {$unset: {readAt: true}}
    : {$set: {readAt: new Date()}}
)

which works fine, but requires I first read in that field. I'm not really worried about race conditions or anything, I'd just prefer to cut out the round trip to the DB.

I've thought of a couple of ways to do it with two update queries in serial with distinct conditions, but that doesn't seem like an improvement.

A: If your MongoDB version is >= 4.2 then you can specify aggregate pipeline in you update query.
db.collection.update(
{ _id: notificationDoc._id },
[
  {
    $set: {
      readAt: {
        $cond: [
          {
            $lte: [
              "$readAt",
              null
            ]
          },
          "$$NOW",
          "$$REMOVE" //(previously null)
        ]
      }
    },

  }
])

Above query will set readtAt to null (or remove it if $$REMOVE is provided)  if it exists and to current date time if not exist/null
You can see how the comparison works

A: The update (toggle) logic can be implemented as follows - I will explain with an example. Consider a collection with two documents:
{ "_id" : 1, "readAt" : "2020-07-01", "fld" : "Y" }
{ "_id" : 2, "fld" : "N" }

The following aggregation removes the readAtfield in the document with _id: 1 and sets the readAt: "2020-07-08" for the document with _id: 2.
var NEW_VALUE = "2020-07-08";

db.collection.aggregate([
  {
      $addFields: {
          readAt: {
              $let: {
                  vars: { readAtExists: { $ifNull: [ "$readAt", null ] } },
                  in: { $cond: [ {$eq: [ "$$readAtExists", null ]}, NEW_VALUE, "$$REMOVE"  ] }
              }
          }
      }
  }
])

Based on this aggregation you can update the document in one of the following two ways. The first option works with MongoDB versions 4.2 or newer (uses Update with Aggregation Pipeline), and the second option works with versions earlier than the 4.2.

1) Update with Aggregation Pipeline
db.collection.update(
  { _id: 1 },  // { _id: 2 }
  [
    {
        $set: {
            readAt: {
                $let: {
                    vars: { readAtExists: { $ifNull: [ "$readAt", null ] } },
                    in: { $cond: [ {$eq: [ "$$readAtExists", null ]}, NEW_VALUE, "$$REMOVE"  ] }
                }
            }
        }
    }
  ]
)

2) Aggregate and Update:
db.collection.aggregate( [
  {
      $match: { _id: 1 }  // { _id: 2 }
  },
  {
      $addFields: {
          readAt: {
              $let: {
                  vars: { readAtExists: { $ifNull: [ "$readAt", null ] } },
                  in: { $cond: [ {$eq: [ "$$readAtExists", null ]}, NEW_VALUE, "$$REMOVE"  ] }
              }
          }
      }
  }
] ).forEach( doc => db.collection.replaceOne( { _id: doc._id }, doc ) )

NOTES:
You can use the NOW aggregation variable with MongoDB v4.2 for setting the date value in an aggregation.


text:
Q: iOS - Why my next view callback my previous view? My situation is the next :
I have two view controller.
The first contains an UITableView. When I tap on a cell, the second view is called and display another UITableView.
Problem :
Immediately that my second view has been displayed, it's removed and my app come back on the first view.
In debug mode, I can see that viewDidLoad() is called and the TableView has been initialised because the TableView is filled.
But I don't know why, viewWillDisappear() is called immediately, as if the view was removed...
Could someone to help me out please?
EDIT :
My first View :
#import "CIMSaddlesResearchesSavedViewController.h"
#import <Foundation/Foundation.h>

@interface CIMSaddlesResearchesSavedViewController ()

@property (weak, nonatomic) IBOutlet UITableView    *tableView;

@end

@implementation CIMSaddlesResearchesSavedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"] forBarMetrics:UIBarMetricsDefault];
}

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (UIStatusBarStyle) preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.researches count];
}

- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    static NSString     *reuseIdentifier    = @"researchCell";
    UITableViewCell     *cell               = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    CIMSaddleResearch   *research;

    research = self.researches[indexPath.row];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"researchCell"];
    }

    cell.textLabel.textColor        = [UIColor whiteColor];
    cell.detailTextLabel.textColor  = [UIColor whiteColor];
    cell.backgroundColor            = [UIColor clearColor];

    if (research.dbId && ![research.dbId isEqual:@""]) {
        CIMDbManager    *dbMngr     = [[CIMDbManager alloc] init];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"dd/MM/yyyy"];
        NSMutableString *minPrice    = [NSMutableString stringWithString:@""];
        NSMutableString *maxPrice    = [NSMutableString stringWithString:@""];
        NSMutableString *currencyS   = [NSMutableString stringWithString:@""];
        CIMCurrency *currency = [[CIMCurrency alloc] init];;

        NSMutableString *researchText         = [NSMutableString stringWithString:@""];

        if (research.customer && ![research.customer isEqual:@""]) {
            CIMCustomer     *customer   = [[CIMCustomer alloc] init];
            customer.dbId               = research.customer;
            customer                    = [dbMngr firstObjectFromDb:customer];
            [researchText appendFormat:@"%@ le %@", customer.lastName, [formatter stringFromDate:research.date]];
        }

        CIMSaddleResearchLine *researchLine = [[CIMSaddleResearchLine alloc] init];
        researchLine.saddleResearch = research.dbId;
        NSArray *lines = [dbMngr objectsFromDb:researchLine];

        for(CIMSaddleResearchLine *line in lines){
            if([line.field isEqualToString:@"PRIX_MIN"])
               [minPrice appendFormat:@"%@", line.value];
            else if([line.field isEqualToString:@"PRIX_MAX"])
                [maxPrice appendFormat:@"%@", line.value];
            else if([line.field isEqualToString:@"DEVISE"])
                [currencyS appendFormat:@"%@", line.value];
        }

        if(![minPrice isEqual:@""] || ![maxPrice isEqual:@""]){
            if(currencyS){
                currency.dbId = currencyS;
                currency = [dbMngr firstObjectFromDb:currency];
            } else {
                currency = [dbMngr defaultSocietyCurrency];
            }

            [researchText appendString:@" | Budget : "];
            if(![minPrice isEqual:@""] && ![maxPrice isEqual:@""])
                [researchText appendFormat:@"%@%@ → %@%@", minPrice, currency.symbol, maxPrice, currency.symbol];
            else if(![minPrice isEqual:@""] && [maxPrice isEqual:@""])
                [researchText appendFormat:@"%@%@ min.", minPrice, currency.symbol];
            else if([minPrice isEqual:@""] && ![maxPrice isEqual:@""])
                [researchText appendFormat:@"%@%@ max.", maxPrice, currency.symbol];
        }

        NSMutableString *researchDetailText   = [NSMutableString stringWithFormat:@"Relance le : %@", [formatter stringFromDate:research.deadline]];

        CIMResearchStatus *status = [[CIMResearchStatus alloc] init];
        status.dbId              = research.status;
        status                   = [dbMngr firstObjectFromDb:status];

        if(status){
            [researchDetailText appendFormat:@" (%@)", status.name];
        }

        cell.textLabel.text         = researchText;
        cell.detailTextLabel.text   = researchDetailText;

        if (research.comment && ![research.comment isEqual:@""] ) {
            cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
        }
    } else {
        cell                            = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"saddleCell"];
        cell.backgroundColor            = [UIColor clearColor];
        cell.textLabel.text             = NSLocalizedString(@"The saddle is not in this list", nil);
        cell.textLabel.textAlignment    = NSTextAlignmentCenter;
    }

    return cell;
}

-(void) tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    CIMSaddleResearch *research = self.researches[indexPath.row];

    if (research.comment && ![research.comment isEqual:@""] ) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Comment", nil)
                                                                       message:research.comment
                                                                preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:NSLocalizedString(@"Ok", nil)
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction *action){}];

        [alert addAction:actionOk];
        [self presentViewController:alert animated:YES completion:nil];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.navigationController popViewControllerAnimated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"openResultResearch"]) {
        UITableView                         *table          = (UITableView*)[(UITableViewCell*)sender superview];
        NSIndexPath                         *index          = [table indexPathForCell:(UITableViewCell*) sender];
        CIMSaddleResearch                   *research       = self.researches[index.row];

        CIMDbManager                        *dbMngr         = [[CIMDbManager alloc] init];
        CIMSaddleResearchLine               *researchLine   = [[CIMSaddleResearchLine alloc] init];
        CIMSaddleResearchFormViewController *form           = [[CIMSaddleResearchFormViewController alloc] init];
        form.minimumPriceRow                                = [[XLFormRowDescriptor alloc] init];
        form.maximumPriceRow                                = [[XLFormRowDescriptor alloc] init];
        form.minimumYearRow                                 = [[XLFormRowDescriptor alloc] init];
        form.maximumYearRow                                 = [[XLFormRowDescriptor alloc] init];
        form.currency                                       = [[CIMCurrency alloc] init];

        NSMutableDictionary                 *filters        = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                                                   [[NSMutableArray alloc] init], @"brand",
                                                                   [[NSMutableArray alloc] init], @"model",
                                                                   [[NSMutableArray alloc] init], @"size",
                                                                   [[NSMutableArray alloc] init], @"color",
                                                                   [[NSMutableArray alloc] init], @"finishing",
                                                                   nil];

        researchLine.saddleResearch = research.dbId;
        NSArray *lines = [dbMngr objectsFromDb:researchLine];
        NSSortDescriptor    *sortFieldDesc           = [[NSSortDescriptor alloc] initWithKey:@"field" ascending:YES selector:@selector(compare:)];
        NSSortDescriptor    *sortOrderDesc           = [[NSSortDescriptor alloc] initWithKey:@"order" ascending:YES selector:@selector(compare:)];
        lines = [lines sortedArrayUsingDescriptors:@[sortFieldDesc, sortOrderDesc]];

        for(CIMSaddleResearchLine *line in lines){
            if([line.field isEqualToString:@"PRIX_MIN"]){
                form.minimumPriceRow.value = line.value;
            }else if([line.field isEqualToString:@"PRIX_MAX"]){
                form.maximumPriceRow.value = line.value;
            }else if([line.field isEqualToString:@"ANNEE_MIN"]){
                form.minimumYearRow.value = line.value;
            }else if([line.field isEqualToString:@"ANNEE_MAX"]){
                form.maximumYearRow.value = line.value;
            }else if([line.field isEqualToString:@"DEVISE"]){
                form.currency.dbId = line.value;
                form.currency = [dbMngr firstObjectFromDb:form.currency];
            }
            else if([line.field isEqualToString:@"GA_REFCONSTRUC"]){
                form.serialNumberRow.value = line.value;
            }else if([line.field isEqualToString:@"GA_QUARTIER"]){
                form.flapRow.value = line.value;
            }else if([line.field isEqualToString:@"GA_MARQUE"]){
                CIMBrand *brand = [[CIMBrand alloc] init];
                brand.dbId      = line.value;
                [[filters objectForKey:@"brand"] addObject:[dbMngr firstObjectFromDb:brand]];
            }else if([line.field isEqualToString:@"GA_MODEL"]){
                CIMModel *model = [[CIMModel alloc] init];
                model.dbId      = line.value;
                [[filters objectForKey:@"model"] addObject:[dbMngr firstObjectFromDb:model]];
            }else if([line.field isEqualToString:@"GA_TAILLE"]){
                CIMSize *size = [[CIMSize alloc] init];
                size.dbId      = line.value;
                [[filters objectForKey:@"size"] addObject:[dbMngr firstObjectFromDb:size]];
            }else if([line.field isEqualToString:@"GA_COULEUR"]){
                CIMColor *color = [[CIMColor alloc] init];
                color.dbId      = line.value;
                [[filters objectForKey:@"color"] addObject:[dbMngr firstObjectFromDb:color]];
            }else if([line.field isEqualToString:@"GA_FINITION"]){
                CIMFinishing *finishing = [[CIMFinishing alloc] init];
                finishing.dbId      = line.value;
                [[filters objectForKey:@"finishing"] addObject:[dbMngr firstObjectFromDb:finishing]];
            }
        }

        if(!form.currency.dbId && [form.currency.dbId isEqualToString:@""]){
            CIMCustomer *customer = [[CIMCustomer alloc] init];
            customer.dbId = research.customer;
            customer = [dbMngr firstObjectFromDb:customer];
            form.currency.dbId = customer.currency;
            form.currency = [dbMngr firstObjectFromDb:form.currency];
        }

        CIMSaddlesViewController    *saddlesViewController  = segue.destinationViewController;
        saddlesViewController.filters                       = filters;
        saddlesViewController.saddleDbId                    = [NSMutableString stringWithString:@""];
        saddlesViewController.selectionMode                 = NO;
        saddlesViewController.saddleNotFoundOption          = NO;
        saddlesViewController.showSaddlePictures            = YES;
        saddlesViewController.showSaddleWarehouse           = YES;
        saddlesViewController.showToolbar                   = NO;
        saddlesViewController.saddles                       = [dbMngr stockSaddlesWithFilters:filters
                                                                              andSerialNumber:form.serialNumberRow.value
                                                                                andFlap:form.flapRow.value
                                                                          betweenMinimumPrice:form.minimumPriceRow.value
                                                                              andMaximumPrice:form.maximumPriceRow.value
                                                                                inCurrency:form.currency.dbId
                                                                           betweenMinimumYear:form.minimumYearRow.value
                                                                               andMaximumYear:form.maximumYearRow.value
                                                                                inStock:YES];
        saddlesViewController.formResearch                  = form;
        saddlesViewController.saddlesPricesCurrency         = form.currency;
    }
}
@end

My second view :
#import "CIMSaddlesViewController.h"

@interface CIMSaddlesViewController ()

@property (weak, nonatomic) IBOutlet UITableView    *tableView;

@end

@implementation CIMSaddlesViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"] forBarMetrics:UIBarMetricsDefault];
}

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (UIStatusBarStyle) preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.saddles count];
}

- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    static NSString *reuseIdentifier    = @"saddleCell";
    UITableViewCell *cell               = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    CIMItem         *saddle;

    saddle = self.saddles[indexPath.row];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"saddleCell"];
    }

    cell.textLabel.textColor        = [UIColor whiteColor];
    cell.detailTextLabel.textColor  = [UIColor whiteColor];
    cell.backgroundColor            = [UIColor clearColor];

    if (saddle.dbId && ![saddle.dbId isEqual:@""]) {
        NSMutableString *saddleText         = [NSMutableString stringWithString:saddle.dbId];
        NSMutableString *saddleDetailText   = [NSMutableString stringWithString:saddle.name];

        // Serial number
        if (saddle.serialNumber && ![saddle.serialNumber isEqual:@""]) {
            [saddleText appendFormat:@" - %@", saddle.serialNumber];
        }

        // Warehouse
        if (self.showSaddleWarehouse) {
            CIMDbManager    *dbMngr = [[CIMDbManager alloc] init];
            CIMStock        *stock  = [[CIMStock alloc] init];
            stock.item              = saddle.dbId;
            stock.quantity          = [NSNumber numberWithInt:1];
            stock                   = [dbMngr firstObjectFromDb:stock];
            if (stock) {
                CIMWarehouse *warehouse = [[CIMWarehouse alloc] init];
                warehouse.dbId          = stock.warehouse;
                warehouse               = [dbMngr firstObjectFromDb:warehouse];
                [saddleText appendFormat:@" → [%@]", warehouse.name];
            }
        }

        // Estimed price
        if (self.saddlesPricesCurrency) {
            CIMDbManager    *dbMngr         = [[CIMDbManager alloc] init];
            CIMSaddlePrices *saddlePrices   = [[CIMSaddlePrices alloc] init];
            saddlePrices.item               = saddle.dbId;
            saddlePrices.currency           = self.saddlesPricesCurrency.dbId;
            saddlePrices                    = [dbMngr firstObjectFromDb:saddlePrices];
            if (saddlePrices) {
                NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
                [numberFormatter setMaximumFractionDigits:0];
                [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
                [numberFormatter setCurrencyCode:self.saddlesPricesCurrency.isoCode];

                NSString *isEstimateStr;
                if ([saddlePrices.isEstimate isEqual:@"-"]) {
                    isEstimateStr = NSLocalizedString(@"Official price", nil);
                } else {
                    isEstimateStr = NSLocalizedString(@"Estimation", nil);
                }

                [saddleText appendFormat:@" | %@ (%@)", [numberFormatter stringFromNumber:saddlePrices.price], isEstimateStr];
            }
        }

        cell.textLabel.text         = saddleText;
        cell.detailTextLabel.text   = saddleDetailText;

        // Saddle pictures
        if (self.showSaddlePictures && [[self.saddlesPicturesDictionary allKeys] containsObject:saddle.dbId]) {
            UIButton *accessoryButton       = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)];
            if ([self.saddlesiPadPictures containsObject:saddle.dbId]) {
                [accessoryButton setImage:[UIImage imageNamed:@"SaddleiPadPictureButton"] forState:UIControlStateNormal];
            } else {
                [accessoryButton setImage:[UIImage imageNamed:@"SaddlePictureButton"] forState:UIControlStateNormal];
            }
            accessoryButton.tag             = indexPath.row;
            [accessoryButton addTarget:self action:@selector(showSaddlePicturesViewForSaddleWithSender:) forControlEvents:UIControlEventTouchDown];
            cell.accessoryView              = accessoryButton;
        } else {
            cell.accessoryView              = nil;
        }
    } else {
        cell                            = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"saddleCell"];
        cell.backgroundColor            = [UIColor whiteColor];
        cell.textLabel.text             = NSLocalizedString(@"The saddle is not in this list", nil);
        cell.textLabel.textAlignment    = NSTextAlignmentCenter;
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.selectionMode) {
        CIMItem *saddle = self.saddles[indexPath.row];
        [self.saddleDbId setString:saddle.dbId];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}
@end

To be honest, this project is very big, I begun to work on it since 2 month ago and I'm alone to work on it. I didn't work in Objective-C before and even less with X-Code. I'm discovering features and Objective-C gradually...

A: In your first VC you call [self.navigationController popViewControllerAnimated:YES]; which tells the navigationVC to pop the currently visible view controller. If you set breakpoints to the  tableview didSelectRowAtIndexPath: in first VC and to viewDidLoad in your second VC you'll see in what order they are called. I have a feeling that the order of execution could be the following:

*

*prepare for segue in firstVC

*view did load in secondVC

*didSelectRowAtIndexPath in first VC

*finally your second VC unloads

This is my idea without testing it. Please make sure you really need to pop the VC in didSelectRow


text:
Q: sqlaclhemy - mapping a column to separate table I have model with a list in it. The list contains id values. These ids need to be stored in separate table and no model is defined for this table in the xsd.
The class models are generated using generateDS tool from the xsd file automatically.
Basically the id table is like a lookup (association) table which maintains associations between two entities.
How do I handle this scenario?
ClassA:
   id String,
   name String,
   listIds String

TableA = ('TableA', meta,
   id String(255),
   name String(255)

TableB = (TableB', meta,
   tableA_id String(255),
   listIds String(255)


text:
Q: PayPal express checkout button - are there different variations/colors? In order to use Express Checkout, i have to use button from PayPal's server. But it offers  only one button style: https://www.paypal.com/express-checkout-buttons. It looks really bad on dark background. Is there another "official" page which offers more styles (similar to what FB offers for LIKE button for example)?
Thank you.

A: The following link is the official page on the latest button styles
https://www.paypal.com/au/webapps/mpp/logos-buttons


text:
Q: Changing iPhone's language settings effect on my App I'm working on an app that's support Arabic Language.
My problem is : when the user change the language of the iPhone to Arabic all the menu and component of my app changed in a very bad way.
How to prevent my app to take the iPhone's language settings?

A: In Project Info uncheck use base internationalization.
and if u want to add Language then click on + sign to add.see i have upload image


text:
Q: Reading AND Writing Access 2 with SSIS I went for a job interview this morning, and one of the scenarios that the IT manager (a former programmer) told me about was the following .... If anyone could give me any pointers that I can email him pointers to tomorrow (Wednesday 22nd) it may just help tip his decision in my direction. So there's beer in it if you answer a relevent answer, and I get the job.
Old systems using Access 2 databases. These systems are not due to be updated any time soon.
New systems need access to that data, so each night he exports information using SSIS. However, he needs to also write data back, and more often than just overnight.
However, when he connects to the database, using ODBC connections I think, he says that the app (SSIS) opens the tables / database exclusively, even if he selects the option NOT to open it exclusively.
Any ideas, suggestions or comments ?

A: Could it be that the  Access db itself is set up to open exclusively. Gosh it's been about a million years since I used Access 2.
Another possibility to fix is to consider making the SQl server tables that mimic the access tables and making them linked tables in access and using them instead of access. I can't remember if you can do this with Access 2 or not. If you can do this, then you will be making changes directly to the sql servver tables and not locking them up in Access 2. It's at least something to try. The use of linked tables should't break anything in Access if they have the same names and all tables havea primary key. ANd then you can performance tune as well if there are problems.
I'm throwing out ideas here, up to you to research the feasibilty before sending them on. But honestly, do you really really want to work for an organization that still uses Access2? If they haven't upgraded that, what else are they years out of date on? Access2 came out in 1993. So they haven't upgraded it in 17 years, scary stuff.


text:
Q: jQuery Toggle not working on generated divs I have a form that generates divs. I need to add information below the div that toggles show/hide on click. I have all the functionality working but I cannot get the toggle action to work on the generated divs.
The fiddle is here, http://jsfiddle.net/clintongreen/BMX4J/20/
I have made a static test div that works, but when I generate a div it dosent work although when I look at the code both divs are identical.
Thanks

A: Change to $('#toggleshow').live('click', function() ...
http://jsfiddle.net/BMX4J/21/

A: You can add the click handler for all current and future buttons using jQuery live(), eg
$('.div_menu_button').live('click', function() {
    $(this).next().slideToggle('slow');
});

Fiddle - http://jsfiddle.net/BMX4J/22/


text:
Q: Barplot: plot range of values I want to plot the range of values of a variable among years.
I have done it using plot points, however points make viewing difficult. Therefore I would like to use bars. Does anyone know how to do it?
I put below the code of an example about what I want, but using plot points.
Degrees <- c(20, 19, 18, 20, 19, 18, 17, 10, 9,  8)
Year <- c("85", "85", "85", "86", "86", "86", "86", "87", "87", "87")
df <- data.frame (Degrees=Degrees, Year=Year)
p <- ggplot(df, aes(Year, Degrees))
p + geom_point()

A: Or perhaps something like this?
ggplot(df, aes(Year, Degrees)) +
     stat_summary(fun.y = mean, fun.ymin = min, fun.ymax = max, col = 'red')

A: Programmatically find min and max values per year and give columns proper names:
year_min <- setNames(aggregate(df$Degrees, by = list(df$Year), min), c("Year", "Degrees"))
year_max <- setNames(aggregate(df$Degrees, by = list(df$Year), max), c("Year", "Degrees"))

Concatenate them into a dataframe:
df_merge <- rbind(year_min, year_max)

Then do a box plot
boxplot(Degrees~Year, data=df_merge)

A: I think you might want a boxplot, i.e. something to depict the range of values for a given year, instead of a barplot...
p <- ggplot(df, aes(Year, Degrees))
p + geom_boxplot()

A bar plot would look like this (the values get summed by year):
p <- ggplot(df, aes(Year, Degrees))
p + geom_bar(stat="identity")


text:
Q: Card views in recycler view using motionlayout I have a recycler view that displays a horizontal list of cards.
When I select a single card the card's size is meant to scale up by 1.1 and the other cards will remain the same size, but they are supposed to be equidistant from each other, the margins (left and right) should be maintained.
When another card is selected the previous card will then scale down
The current issue is when I select a card the margins are not equal between the selected card and the unselected cards, but the unselected cards have the same margins see image below

motion layout XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/profileSelectorMotionLayout"
    android:animateLayoutChanges="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clipToPadding="false"
    android:background="@android:color/transparent"
    app:layoutDescription="@xml/control_item_profile_selector_expanded_scene">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="wrap_content"
        android:layout_height="82dp"
        android:minWidth="190dp"
        app:cardCornerRadius="6dp"
        app:cardElevation="4dp"
        app:cardBackgroundColor="?attr/colorInteractive"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_goneMarginBottom="2dp">

    </androidx.cardview.widget.CardView>
</androidx.constraintlayout.motion.widget.MotionLayout>

and the motion scene
<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ConstraintSet android:id="@+id/start">
        <Constraint
            android:id="@+id/cardView"
            android:layout_width="wrap_content"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_goneMarginBottom="2dp">

            <Layout
                android:layout_width="wrap_content"
                android:layout_height="82dp"
                android:layout_marginStart="@dimen/spacing_s"
                android:layout_marginTop="10dp"
                android:layout_marginEnd="@dimen/spacing_xxs"
                android:padding="4dp"
                app:cardCornerRadius="6dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_goneMarginBottom="2dp" />

            <Transform
                android:elevation="4dp"
                android:scaleX="1"
                android:scaleY="1" />

            <CustomAttribute
                app:attributeName="cardBackgroundColor"
                app:customColorValue="@color/colorScene" />
        </Constraint>
    </ConstraintSet>

    <ConstraintSet
        android:id="@+id/scaleUp"
        app:deriveConstraintsFrom="@id/start">
        <Constraint android:id="@+id/cardView">
            <Transform
                android:elevation="6dp"
                android:scaleX="1.1"
                android:scaleY="1.1" />

        </Constraint>
    </ConstraintSet>

    <Transition
        app:constraintSetEnd="@id/scaleUp"
        app:constraintSetStart="@id/start"
        app:duration="500" />

    <Transition
        app:constraintSetEnd="@+id/start"
        app:constraintSetStart="@+id/scaleUp"
        app:duration="500" />
</MotionScene>

I have tried adding another  tag and adding constraints in the scaleUp constraint set but it does work.
Adjusting the constraints in the start constraint set does not help as well


text:
Q: How to use conditional statements/ternary inside a flutter widget I need to know is it possible to use ternary/if else inside flutter widgets.
I'm trying to create a buttonCreator widget which will take few parameters, one of which will be the background. I need to check whether the widget has background enabled or not. What i have is this but i have no idea how to use it in real dart code.
Container buildButton(String text, bool bg){
  return new Container(
    decoration: new BoxDecoration(
      border: new Border.all(color: Colors.white),
      if (bg != true ? color: Colors.white : '')
    ),
    padding: new EdgeInsets.all(15.0),
    margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
    child: new Center(
      child: new Text(
        text, style: new TextStyle(color: Colors.white, fontFamily: 'Monsterrat')
      )
    ),
  );
};

A: I think this is what your question is actually about ?

import 'package:flutter/material.dart';

void main() => runApp(new MaterialApp(
  home: new Home(),
));

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Flexible(
                          child: new MyContainer(
                color: Colors.red,
              ),
            ),
            new Flexible(
                          child: new MyContainer(
                img: "http://www.clker.com/cliparts/F/v/O/6/E/c/cartoon-rubber-duck-hi.png",
              ),
            )
          ],
        ),
      ),
    );
  }
}

class MyContainer extends StatelessWidget {
  String img;
  Color color;
  MyContainer ({this.img,this.color});
  @override
  Widget build(BuildContext context) {
    return this.img!=null? new Container(
      decoration: new BoxDecoration(
        image:new DecorationImage(
          image: new NetworkImage(this.img)
        )
      ),
    ): new Container(
      decoration: new BoxDecoration(
        color: this.color
      ),
    );
  }
}

A: Container buildButton(String text, bool bg){
  return new Container(
    decoration: new BoxDecoration(
      border: new Border.all(color: Colors.white),
      color: bg ? Colors.white : null, // you can use ternary operator here
    ),
    padding: new EdgeInsets.all(15.0),
    margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
    child: new Center(
      child: new Text(
        text, style: new TextStyle(color: Colors.white, fontFamily: 'Monsterrat')
      )
    ),
  );
};

A: decoration: new BoxDecoration(
    border: new Border.all(color: Colors.white),
    color: bg ? Colors.transparent : Colors.red, // you can use ternary operator here
),

Modified from AleksTi's answer. color property cannot be null.


text:
Q: Bulk-insertion into couchbase via python I am trying to do some bulk-insertion in couch-base. I tried to search examples over SO and google, but I could not get any clue. Here someone mention that its not possible.
How to insert a documents in bulk in Couchbase?
but I guess this question was asked 3 years ago. I search and if I understand correctly from below given link, its possible to insert document in bulk.
https://developer.couchbase.com/documentation/server/current/sdk/batching-operations.html
https://pythonhosted.org/couchbase/api/couchbase.html#batch-operation-pipeline
Here is my code on which I want to implement bulk-insertion in couchbase
import time
import csv
from couchbase import Couchbase
from couchbase.bucket import Bucket
from couchbase.exceptions import CouchbaseError
c = Bucket('couchbase://localhost/bulk-load')
from couchbase.exceptions import CouchbaseTransientError
BYTES_PER_BATCH = 1024 * 256 # 256K

with open('/home/royshah/Desktop/bulk_try/roy.csv') as csvfile:
    lines = csvfile.readlines()[4:]
for k, line in enumerate(lines):
    data_tmp = line.strip().split(',')
    strDate = data_tmp[0].replace("\"", "")
    timerecord = datetime.datetime.strptime(strDate,
                                           '%Y-%m-%d %H:%M:%S.%f')
    microsecs = timerecord.microsecond
    strDate = "\"" + strDate + "\""
    ts = calendar.timegm(timerecord.timetuple())*1000000 + microsecs
    datastore = [ts] + data_tmp[1:]

    stre = {'col1 ': datastore[1],  # I am making key-values on the fly from csv file
            'col2': datastore[2],
            'col3': datastore[3],
            'col4': datastore[4],
            'col5': datastore[5],
            'col6': datastore[6]}
  cb.upsert(str(datastore[0]), (stre))    # datastore[0] is used as document
                                      id and (stre) is used as key-value to be
                                      inserted for respective id.

cb.upsert(str(datastore[0]), (stre))
   is doing single insertion and I want to make it bulk-insertion to make it faster. I had no idea how to turn this in bulk-insertion in couchbase. I find this example but not sure how to implement.
https://developer.couchbase.com/documentation/server/current/sdk/batching-operations.html
If someone point out some examples of bulk-load in couchbase or help me to figure out how can I do bulk-insertion via my code. I would be really really grateful. .thanx a lot for any idea or help.

A: I tried to adapt the example from the docs to your use case. You maybe have to change one or two details but you should get the idea.
c = Bucket('couchbase://localhost/bulk-load')
from couchbase.exceptions import CouchbaseTransientError
BYTES_PER_BATCH = 1024 * 256 # 256K

batches = []
cur_batch = {}
cur_size = 0
batches.append(cur_batch)

with open('/home/royshah/Desktop/bulk_try/roy.csv') as csvfile:
    lines = csvfile.readlines()[4:]
for key, line in enumerate(lines):
    #Format your data
    data_tmp = line.strip().split(',')
    strDate = data_tmp[0].replace("\"", "")
    timerecord = datetime.datetime.strptime(strDate,
                                           '%Y-%m-%d %H:%M:%S.%f')
    microsecs = timerecord.microsecond
    strDate = "\"" + strDate + "\""
    timestamp = calendar.timegm(timerecord.timetuple())*1000000 + microsecs

    #Build kv
    datastore = [ts] + data_tmp[1:]
    value = {'col1 ': datastore[1],  # I am making key-values on the fly from csv file
            'col2': datastore[2],
            'col3': datastore[3],
            'col4': datastore[4],
            'col5': datastore[5],
            'col6': datastore[6]}

    key = str(datastore[0]
    cur_batch[key] = value
    cur_size += len(key) + len(value) + 24

    if cur_size > BYTES_PER_BATCH:
        cur_batch = {}
        batches.append(cur_batch)
        cur_size = 0

print "Have {} batches".format(len(batches))
num_completed = 0
while batches:
  batch = batches[-1]
  try:
      cb.upsert_multi(batch)
      num_completed += len(batch)
      batches.pop()
  except CouchbaseTransientError as e:
      print e
      ok, fail = e.split_results()
      new_batch = {}
      for key in fail:
          new_batch[key] = all_data[key]
      batches.pop()
      batches.append(new_batch)
      num_completed += len(ok)
      print "Retrying {}/{} items".format(len(new_batch), len(ok))


text:
Q: Make scrapy export to csv I want to use scrapy in the following way
from scrapy.crawler import CrawlerProcess

process = CrawlerProcess({
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' })

process.crawl(my_super_scraper)
process.start()

It works with my_super_scraper, but I cannot figure out how to export to CSV. I cannot find it in the documentation either.

A: You need to set FEED_FORMAT and FEED_URI parameters as follow:
from scrapy.crawler import CrawlerProcess

process = CrawlerProcess({
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
    'FEED_FORMAT': 'CSV',
    'FEED_URI': 'file:///tmp/export.csv',
})

process.crawl(my_super_craper)
process.start()

More information about feed export here https://docs.scrapy.org/en/latest/topics/feed-exports.html
This post shows how to export to JSON format:
Scrapy process.crawl() to export data to json


text:
Q: Multipart passthrough in API Gateway I have a web application that accepts multipart/form-data and have set up api gateway to pass through the requests to it. However, any time I upload images as part of the form they end up being larger than the original file I uploaded and corrupted. If I execute the same method without going via AWS API gateway the image uploads fine. Any ideas what I'm missing here?
the below is my S3 code that reads the form data in flask:
    f = request.files['attachment']
    fp = StringIO(f.read())
    file_uuid = str(uuid.uuid4())
    bucketkey.key = "att_%s%s" % (file_uuid, file_extension(f.filename))
    bucketkey.set_contents_from_file(fp)

I'll attach a link to a sample jpg that is corrupted if its useful at all.
https://s3.eu-central-1.amazonaws.com/agendacommunities/att_ef7375b1-bb19-4df9-9162-5582ed66797c.jpeg

A: What is your intent with StringIO?  f.read() will give you bytes, not a string.  I think you can pass f directly to set_contents_from_file and it will read from f.
f = request.files['attachment']
file_uuid = str(uuid.uuid4())
bucketkey.key = "att_%s%s" % (file_uuid, file_extension(f.filename))
bucketkey.set_contents_from_file(f)

A: You need to set content-type header for your data to be recognized as binary by API Gateway.


text:
Q: ARR and URL rewrite for node express website for iis server I have an express.js website running on my localhost in my Webserver (IIS8.5). When I use ARR and url rewrite to point to localhost port 3000 where my express website is, I can access part of it from the Internet.
Also, the style sheet does not seem to render.
For example:
When I type in mywebsite/Nodewebsite/ - that works but style sheet does not render
When I type in mywebsite/Nodewebsite/blog - that works but style sheet does not render
When I type in mywebsite/Nodewebsite/admin - I get my admin page but when I try to log on I get a 404 err.
My express.js mvc website has a couple of pages (a blog) and When I try to update the content in my blog from my admin page, it shows a 404 error and when I check the URL, the path is not right.
This is the tutorial I followed : http://code.tutsplus.com/tutorials/build-a-complete-mvc-website-with-expressjs--net-34168. It works fine from my server with localhost.
I am so confused on what the issues may be on why part of the express.js site would work but not other parts. But I am suspecting it has to do with my URL rewrite but I am not sure.
Here is my web.config file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
    <rewrite>
        <rules>
            <rule name="ReverseProxyInboundRule1" stopProcessing="true">
                <match url="(.*)" />
                <action type="Rewrite" url="http://127.0.0.1:3000/{R:1}" />
                <conditions logicalGrouping="MatchAny" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>
</configuration>

Hopefully someone can shed some light into this, thanks.