text:
Q: Is there a way to enter back tick (backtick) on SO when using iPad or iPhone? There are times when I only can use iPad to access SO, and the back tick ` is needed to quote the literals...  but it seems on iPad, there is no way to enter a back tick on the keyboard?  Can it be somehow entered?

A: @MarkTrapp said that iPad defaults to the non-mobile version of Stack Overflow, so you don't really need to press the `.
Just click the Code Sample icon over the textarea, and it will insert two backticks. If you select the literals first, it will automatically wrap them in backticks.
Note that the Code Sample button insert four spaces rather than backticks if triggered on an empty or entire line.

A: Assuming you're using the US keyboard layout, tap the .?123 key, then tap and hold the ' key: a popup will appear where you can tap the ` key. If I remember correctly, this only works in iOS 4 and later: if you're still running iPhone OS 3.2, you're out of luck and you really should just upgrade already.

A: You can surround the text you want to inline monospace with .
This works for questions and answers, but not for comments -- right now, I don't think there's a workaround for comments.

A: Comments
In a comment box, click help at the bottom right, select and copy the `code` from there and paste it, replacing the word code with your actual code.
Answers
Similarly, in an answer box, you can click the ? at the top right and under Code, you can select and copy $ and then paste in the textbox, editing $ out to be your actual code.
your code here also works in an answer box.


text:
Q: Laravel queue with Twitter api I'm using the thujohn/twitter package on https://github.com/thujohn/twitter to update user status posts from my site to twitter.
I want to use larvae's queues to post this function in the background. But i keep getting a failed-job. with an error:
exception 'Exception' with message '[220] Your credentials do not allow access to this resource.' in /home/vagrant/sites/pms/vendor/thujohn/twitter/src/Thujohn/Twitter/Twitter.php:297

Stack trace:
my job looks like this:
namespace PMS\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Twitter;
use Session;
use Illuminate\Http\Request;

class PostToTwitter implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;

public $tweetLength;

public $userPage;

public $body;

//public $twitterToken;

//public $secret;
/**
 * Create a new job instance.
 *
 * @return void
 */
public function __construct($tweetLength, $userPage, $body)
{
    $this->tweetLength = $tweetLength;
    $this->userpage = $userPage;
    $this->body = $body;
}

/**
 * Execute the job.
 *
 * @return void
 */
public function handle()
{
    Twitter::postTweet(['status' => str_limit($this->body . $this->userpage,$this->tweetLength), 'format' => 'json']);
}
}

and in my controller I'm dispatching like this:
$this->dispatch(new PostToTwitter($tweetLength, $userPage, $body));

my function works fine if i run it in my controller , but if i try to dispatch it to a job, my jobs fail

A: I managed to fix this by switching to a different library, following this blog post: http://markusos.github.io/engage/2014/12/06/1000-tweets-per-week.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: C SDL Object movement flow I just started with SDL and made a small square moving around on a window.
I used DL_GetKeyboardState, and got it moving kind of smoothly. However, just when I start moving it one direction by holding down one key, it moves a bit, stops, then move like I want. This messes up the smoothness. My best guess is that it waits for a doubleclick from the mouse, but im not sure. Any suggestions?
The code:
#include <stdio.h>
#include <SDL.h>

int main(int argc, char * argv[])
{
   SDL_Window *window;
   SDL_Renderer *renderer;
   SDL_Event event;

   SDL_Init(SDL_INIT_VIDEO);
   window = SDL_CreateWindow("Yelda!", SDL_WINDOWPOS_UNDEFINED,        SDL_WINDOWPOS_UNDEFINED, 1600, 1200, 0);
   renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

   const Uint8 *state;
   int run = 1;
   int xpos=300;
   int ypos=300;
   int projectileYPos;
   int projectileXPos;
   int loop;
   int lanceLength = 10;

   while(run)
   {
      while(SDL_PollEvent(&event))
      {
         state=SDL_GetKeyboardState(NULL);

         if(state[SDL_SCANCODE_ESCAPE])
            run=0;
         if(state[SDL_SCANCODE_W])
            ypos-=10;
         if(state[SDL_SCANCODE_S])
            ypos+=10;
         if(state[SDL_SCANCODE_A])
            xpos-=10;
         if(state[SDL_SCANCODE_D])
            xpos+=10;

         SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
         SDL_RenderClear(renderer);
         SDL_SetRenderDrawColor(renderer, 255, 255, 255 ,255);
         SDL_Rect rect = {xpos, ypos, 20, 20 };
         SDL_RenderFillRect(renderer, &rect);
         SDL_RenderPresent(renderer);

         SDL_Delay(20);
      }
   }

   SDL_DestroyWindow(window);
   SDL_DestroyRenderer(renderer);
   SDL_Quit();
   return 0;
}

A: The SDL wiki says that you should use SDL_PumpEvents() to update the keyboard state array.
And indeed, if we

*

*remove the while(SDL_PollEvent(&event)) loop (not its contents) as it's unneeded,

*move state=SDL_GetKeyboardState(NULL); before the while(run) loop (the address of the array "will be valid for the whole lifetime of the application", so it always returns the same pointer), and

*only call SDL_PumpEvents() inside the loop,

then the movement is smooth.


text:
Q: jQuery Post: Appending data to post I'm using jQuery's post on a WordPress page.
var thename = jQuery("input#name").val();
    jQuery.post(the_ajax_script.ajaxurl, jQuery("#theForm").serialize(),
    function(response_from_the_action_function){
    jQuery("#response_area").html(response_from_the_action_function);
});

It posts the selections made in a form. Is it possible to append data to a post. So in addition to the form data, I need a couple lat longs added to the jQuery post. How can I do that. Is it possible?
Thnak you.
-Laxmidi

A: .post() takes a string as the second argument, so you can concatenate a custom string using + followed by your string.
var thename = jQuery("input#name").val();
    jQuery.post(the_ajax_script.ajaxurl, jQuery("#theForm").serialize() + "&foo=bar",
    function(response_from_the_action_function){
    jQuery("#response_area").html(response_from_the_action_function);
});

Do be careful, though; the string has to be correctly formatted as a URL, so you need key=value pairs separated by &s.
In the example above, you'll see + "&foo=bar. The first & finishes the last value created by .serialize(), then foo= is a key, followed by bar as the value.
If you want to add more values afterwards, you can do something like  this:
&foo=bar&baz=zip

A: var thename = jQuery("input#name").val();
var data = {'anycolortoulike':'transparent'}; // any data;
jQuery.post(the_ajax_script.ajaxurl, data.concat(jQuery("#theForm").serializeArray()),
    function(response_from_the_action_function){
       jQuery("#response_area").html(response_from_the_action_function);
    }
);

try this, $.post can use arrays


text:
Q: Difference between tracking_uri and the backend store uri in MLFLOW I am using Mlflow for my project hosting it in an EC2 instance. I was wondering in MlFlow what is the difference between the backend_store_uri we set when we launch the server and the trarcking_uri ?
Thanks,

A: tracking_uri is the URL of the MLflow server (remote, or built-in in Databricks) that will be used to log metadata & model (see doc).  In your case, this will be the URL pointing to your EC2 instance that should be configured in programs that will log parameters into your server.
backend_store_uri - is used by MLflow server to configure where to store this data - on filesystem, in SQL-compatible database, etc. (see doc). If you use SQL database, then you also need to provide the --default-artifact-root option to point where to store generated artifacts (images, model files, etc.)


text:
Q: How can I make a page move onMouseRelease with html/css? I have a website and I would like it to do this: When I click on an image on the left side of the page, the page moves backward and when I click on an image on the right side, the page moves forward. I got everything set up correctly so I tried doing this simply with css, onmouseover move the margin of the page so many pixels to the right or left:

But that doesn't give me any result. So I tried using an example from w3Schools for javascript onmouseclick:
function myFunction()
{
document.getElementById("demo").innerHTML="Hello World";
}

<button onclick="myFunction()">Click me</button>

I tried just putting the button on the image for the sake of testing it out. The button was there but it didn't scroll when i clicked it. What did I do wrong? It seems like the first approach I took should have definitely worked.
Thanks

A: Your first snippet won't work anyway, because it's not dynamic. Additionaly, text-indent isn't the best way of handling offsets for block elements. The second one can't work, because the JavaScript won't scroll, but output 'Hello, World' to the
 element.
Better have a look here:
http://tympanus.net/codrops/2010/06/02/smooth-vertical-or-horizontal-page-scrolling-with-jquery/
That's a nice way of vertical scrolling with the use of HTML ankers, that will even work with browsers that don't support or allow JavaScript.
May that help you?


text:
Q: Vert.x event looping with single thread I am using vert.x 2.1.5 version. And I was trying to use  event looping in my project. sample code given below
JsonObject result = null;
//loop starting
for (int i=0;i<length;i++)
{

 final JsonObject jsonObject1 = jsonObject.getArray("result").get(i);
 int x = jsonObject1.getInteger("X");
 String Data = "X="+x+"&Y="+y;
 //calling another event
vertx.eventBus().send("event1", Data,new Handler<Message<String>() {public void   handle(Message<String>response)
{
JsonObject jsonObject = new JsonObject(response.body());
result_arry.addArray(jsonObject.getArray("details"));
                                            }
});
} // loop end
result = resultJson("Ok",result_arry );
//it will create one json object with proper format
message.reply(result.toString());

In this code my event bus is returning  value before executing event loop.
I need to populate my output as per event loop output
How can I achieve that

A: Basically, the problem is that you're not waiting for messages to arrive.
For my example to be more clear I removed most of the Json logic.
Vertx vertx = Vertx.vertx();
int messages = 10;

// First register your consumer
MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer("event1");
consumer.handler(o -> {
    System.out.println("Got message" + o.body());

    // Consumer replies to sender with the same message
    o.reply(o.body());
});

// Now send your messages
for (int i=0;i<messages;i++) {
    JsonObject data = new JsonObject();
    data.put("value", i);

    vertx.eventBus().send("event1", data, response -> {
        if (response.succeeded()) {
            // Each time consumer replies, print it
            System.out.println("Consumer replied: " + response.result().body());
        }
    });
}

Note that the reply is within handler body, and that sender must check that response is successful before accessing it.


text:
Q: Sharded MongoDb collection with ~1 million records - Aggregation $group is I am using Mongo Atlas as a service. We have a collection of around 1 million records. I have sharded the collection. Now the aggregation query is not returning the correct data.
Why $group is only returning 100k records?

Total Documents in the collection: 882496
Documents Count by $count: 882496
Documents Count by $group: 100,000
Connection string: mongodb+srv://name:password@cluster0.ohw5a.mongodb.net/dbname?retryWrites=true&w=majority

A: The connection string you have mentioned in the answer corresponds to a replica set - which in a sharded environment corresponds to ONE SHARD, which is clustered for HA.
Hence the count is returning the count of documents that exists on that shard itself.
Connect to mongos and then run the query. It should work just fine.


text:
Q: HttpMessageNotWritableException: No converter for [...] with preset Content-Type 'null'] with OpenApi Spring generator I am implementing the petstore API with openAPI in a (gradle) spring boot project. I generate a server with the openapi generator plugin and implement a simple request:
@Service
@RestController
public class PetApiController implements PetApi {

    @Override
    public ResponseEntity<Pet> getPetById(Long petId) {
        Pet p = new Pet();
        p.setId(0L);
        p.setName("fido");
        p.setPhotoUrls(new ArrayList<String>());
        p.setStatus(StatusEnum.AVAILABLE);
        p.setTags(new ArrayList<Tag>());
        Category c = new Category();
        c.setId(3L);
        c.setName("dummy category");
        p.setCategory(c);

        ResponseEntity<Pet> r = new ResponseEntity<Pet>(p, HttpStatus.OK);

        return r;
    }
}

The swagger-ui that I generate offers both xml and json queries for a request, but xml doesn't seem to work:
$ curl -X GET "http://localhost:8080/pet/1" -H  "accept: application/xml"; echo ""

$ curl -X GET "http://localhost:8080/pet/1" -H  "accept: application/json"; echo ""
{"id":0,"name":"fido","category":{"id":3,"name":"dummy category"},"photoUrls":[],"tags":[],"status":"available"}

I even get an error message:
2020-09-10 09:04:34.213  WARN 23958 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class com.petstore.server.model.Pet] with preset Content-Type 'null']

However I cannot catch this exception and print the whole context, it only happens after return r
There is already a question with my exact error message:
Springboot HttpMessageNotWritableException: No converter for [...] with preset Content-Type 'null'] But I still think my context is different since I generate my POJOs so I have no controll over them and I shouldn't have this problem in the first place since the plugin should generate everything fittingly.

A: for me a problem was in lines:
responses:
        "200":
          description: default response
          content:
            '*/*' # <---- here
              schema:

instead of '*/*' it should be 'application/json'

A: The spring generator discriminates against xml by default, see the documentation: https://openapi-generator.tech/docs/generators/spring under
Option  | Description                                       | Default
--------+---------------------------------------------------+---------
withXml | whether to include support for application/xml    | false
        | content type and include XML annotations in the   |
        | model (works with libraries that provide support  |
        | for JSON and XML)                                 |

A: You need to add support for xml format using the below dependency in your pom file:
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.1.1</version>
</dependency>

Note : here version is the latest as per today.

A: In my case, my class Pet didn't have a getter at all.
So I fixed the problem just by adding get methods for fields.

A: According awnser by Peer, i have resolve my issue but it is different way. You need add "text/xml" to tell spring. Even though this limits your API to being JSON-based (which is fine for your needs), you're welcome to set produces to an array of String for multiple content types. For example, to allow for XML output, you could add "text/html" to the produces attribute:
@RequestMapping(path = "your_path", produces = {"application/json", "text/xml"})

A: People with similar errors and most things correct, try to add this header in the API request! I faced this too
Accept : application/json (Or application/xml whichever media your response is producing)

A: For my case, I was getting HttpMessageNotWritableException: No converter for [java.io.File] with preset Content-Type 'null'].
This was in file download api while converting file object into Java Object class.
Issue I fixed by converting java.io.File object into byte array like below:
 @GetMapping(value="/download/{migrationType}",produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)

    return ResponseEntity.ok()
                        .body(Files.readAllBytes(Paths.get(filePath)));

There is no need to put any external jar in spring boot based project. HttpMessageConverter is a part of spring-boot-starter-web dependency. org.springframework.http.converter.ByteArrayHttpMessageConverter is responsible to convert Byte array to APPLICATION_OCTET_STREAM_VALUE media type.

A: I got the same error for the below piece of code.
@GetMapping(value = "/sample", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> sample() {

    return ResponseEntity.ok(new Object());
}

Error message:

No converter for [class java.lang.Object] with preset Content-Type
'null'

To fix it, I replaced the new Object() with new ArrayList()


text:
Q: delete by primary key takes forever mysql I am trying to delete by primary key from Table (300 rows) and it takes up to max query execution time and at the end returns ERROR 2013: 2013: Lost connection to MySQL server during query. This table has foreign key to the large table (200k rows). What can be an issue?
Query: DELETE FROM Table Where table_id=x
EDIT:
There are no triggers associated with this DELETE statement. DELETE/INSERT/UPDATE statements in some database tables work really slow while SELECT statements in whole database work perfectly fine.
EDIT#2:
Additional information from innodb trx table for the query:
trx_lock_structs 429704
trx_lock_memmory_bytes 34698792
trx_rows_locked 214938
trx_isolation_level REPEATABLE READ
trx_unique_checks 1
trx_foreign_key_checks 1
This query deletes 1 row and doesn't have child rows, why locked rows value is so high?
EDIT#3
Investigating situation further I have determined that tables that have slow insert/update/delete operations are the tables that have foreign key with the big table (200k). Is it necessary to remove this foreign keys or data integrity is more important? Although 200k rows is not that much what can be reasons for this slow operations?
EDIT#4
SHOW CREATE TABLE:
CREATE TABLE `Table` (
`table_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`tableb_id` bigint(20) unsigned NOT NULL,
`tablec_id` bigint(20) unsigned DEFAULT NULL,
`bigtable_id` bigint(20) unsigned NOT NULL,
 PRIMARY KEY (`table_id`),
 KEY `fk_tableb_id_idx` (`tableb_id`),
 KEY `fk_bigtable_id_idx` (`bigtable_id`),
 KEY `fk_tablec_id_idx` (`tablec_id`),
 CONSTRAINT `fk_bigtable_id` FOREIGN KEY (`bigtable_id`) REFERENCES `Bigtable`
 (`bigtable_id`) ON DELETE CASCADE ON UPDATE CASCADE,
 CONSTRAINT `fk_tableb_id` FOREIGN KEY (`tableb_id`) REFERENCES `tablebs`
 (`tableb_id`) ON DELETE CASCADE ON UPDATE NO ACTION,
 CONSTRAINT `fk_tablec_id` FOREIGN KEY (`tablec_id`) REFERENCES `tablecs`
 (`tablec_id`) ON DELETE CASCADE ON UPDATE NO ACTION
 ) ENGINE=InnoDB AUTO_INCREMENT=271 DEFAULT CHARSET=utf8

BigTable is a typical Users table id and additional information.
EDIT#5
EXPLAIN DELETE:
select_type : SIMPLE,
table : Table,
type  : range,
possible_keys : PRIMARY,
key : PRIAMRY,
key_len : 8,
ref : const,
rows : 1,
Extra : Using where

A: The reason is cascade on big table. Do you understand the complexity of this computation? it is not just a delete operation on 300 rows. It is basically 300 rows * 200k. Each delete would go and pass through the big table and would perform delete operation on the corresponding rows (based on the id).
Just follow the below mentioned steps:
1) Remove the references of this primary id of this table from other tables (if any)
2) Alter this table and add NO ACTION to the UPDATE & CASCADE of big table foreign key
   OR
   remove all the foreign key contraints
3) delete from tableName

A: I may suggest an empirical approach...
Delete ops with cascade impacts on indexes, slow execution time may depend on time needed to elaborate fKey indexes, btw your tables aren't huge. You say you have no triggers, functions or procedure, so you have to benchmark your query to find what's part is taking so much time...
I assume that you have already verified indexes efficency.
So to benchmark your delete query you should handy write "inner deletion" queries and benchmark each one, using BENCHMARK().
This way you will find which part of that deletion took so long.
What if each single part is reasonably fast?
You may have some misconfiguration in your my.cnf, so you could try checking with https://tools.percona.com/wizard recommendations...
Maybe you have some memory allocation limit or some thread/memory limit.
You can find many tutorials on mysql optimization like http://www.codingpedia.org/ama/optimizing-mysql-server-settings/
You can also find some scripts that may help you in finding mysql optimizations.
Without knowing your architecture, mysql configuration and your database structure, it's quite hard to give a 100% solution, but I hope you can find the way, I'll be glad to read about your findings. If something more will come to my mind I'll keep you posted.


text:
Q: Expression or idiom for overacting when assuming a blame In Romanian we have an expression that translates word-by-word as "pouring ashes onto one's head" -- used when someone exaggerates in assuming the blame for something that went wrong, e.g., by repeatedly stating it:
"I'm such an idiot, I shouldn't have left the door open... how could I be so stupid? What was I thinking?"
"Alright, stop pouring ashes onto your head and let's focus on what we can do to fix this!"
What would be the closest English equivalent?

A:
Beat (oneself) up
To continually criticize or question oneself, usually about something that one cannot change.
—TFD

In the context of your example, it's normally used with "...about it." For example...

So you spilled the ashes. Don't beat yourself up about it.

A: to self-flagellate merriam-webster
extreme criticism of oneself
As in:

"Alright, stop with the self flagellation and let's focus on what
  we can do to fix this!"

A: We have a similar phrase in England and it is 'Donning sackcloth and ashes' from an old religious custom of wearing a rough hessian garment and covering oneself in Ashes to give penance to God for a grievous sin

A: The way you have worded the example I would think that you could say: "Don't make a mountain out of a mole hill."
Example: "I'm such an idiot, I shouldn't have left the door open... how could I be so stupid? What was I thinking?"
"Alright, stop (or 'don't make') making a mountain out of a molehill, just focus on what we can do to fix this!"


text:
Q: Como adicionar +1 em uma variável contadora à cada clique? Cada vez que eu clicar em um botão, quero adicionar +1 a uma variável.
Por exemplo: tenho uma variável count recebendo o valor 5, ao clicar em um botão quero que o valor 5 mude para 6 e assim sucessivamente, exibindo em um alert().
É possivel?

A: Mais uma opção, usando closure. É basicamente o que fez o Paulo Roberto, mas sem variável global:
function criaCounter(init) {
    var count = init || 0;
    return function() {
        count++;
        alert(count);
    }
}
// Cria contador que começa em 5, e usa como listener do click
$('#addCount').click(criaCounter(5));

A: Seria isto?
HTML:
<input type=button id=addCount value="Adicionar Count">

Javascript:
var count = 5;//recebendo o valor 5 que você disse
$('#addCount').click(function(){
  alert(count);
  count++;
});

Exemplo no JSFiddle

A: Poderia fazer algo assim:
HTML
<button id="count" data-valor="5">Clique Aqui!

jQuery
$('#count').click( function ( ) {
  var valorVelho = this.data('valor');
  var valorNovo = valorVelho++;
  this.data('valor', valorNovo);
  alert( valorNovo );
} );

Atualização
Sendo que a base é da variável count, podeira fazer algo assim:
HTML
<button id="count">Clique Aqui!

jQuery
var count = 5;
$('#count').click( function ( ) {
  count++;
  alert( count );
}


text:
Q: Proof verification: if $W_1 \subseteq W_2$ then $\dim(W_1) \le \dim(W_2)$
Let $W_1$ and $W_2$ be subspaces of vector space $V$. Prove that
  If $W_1 \subseteq W_2$ then $\dim(W_1) \le \dim(W_2)$.

My proof:
Let $v_1, ...,v_n$ be base vectors of vector space $W_1$ and $W_1 \subseteq W_2$. Then $\dim(W_1) = n$.
From the assumptions we have that $v_1, ..., v_n \in W_2$ and because they are base vectors in $W_1$ they are lineary independent. Therefore
if $\operatorname{span}(v_1, ...,v_n) = W_2$ then $\dim(W_2) = n = \dim(W_1)$. Otherwise there exists vector $v_{n+1} \in W_2$ such that $v_{n+1}$ is not linear combination of $v_1, ...,v_2$ and therefore $\dim(W_2) \ge n+1$. Hence $\dim(W_1) \le \dim(W_2)$.

A: Well, this is a consequence of the famous Steinitz exchange lemma:
If $\{v_{1},\dots ,v_{m}\}$ is a set of $m$ linearly independent vectors in a vector space V, and $\{w_{1},\dots ,w_{n}\}$ spans $V$, then $m\leq n$ and after reordering $\{v_{1},\dots ,v_{m},w_{m+1},\dots ,w_{n}\}$ spans $V$.
Here you take $\{v_{1},\dots ,v_{m}\}$ as a basis of $W_1$ and $\{w_{1},\dots ,w_{n}\}$ as a basis of $W_2$, where $W_1$ is a subspace of $W_2$.

A: you can just say: Let $\{w_1, \ldots, w_n\}$ be a base for $W_1$, and  let $\{w_1, \ldots, w_m \}$ be a base for $W_2$.
Because $W_2 \subseteq W_1 \to  Sp(W_2) \subseteq Sp(W_1) \to \{w_1, \ldots, w_m \} \subseteq \{w_1, \ldots, w_n \}$, hence $m \le n$
(if $W_1 \subseteq W_2 \to m=n$, and $W_1 = W_2$).


text:
Q: error in ubuntu bash:. ./setenv.sh: No such file or directory i am setting environment in ubuntu terminal for eclipse and running this command
. ./setenv.sh
but its showing an error.
bash:. ./setenv.sh: No such file or directory
how it should be resolve ?

A: The error simply says, that within your current directory, there is no file setenv.sh.
If you have the location of the script in your PATH environment variable, simply call setenv.sh, without the leading ./, because its meaning is "in the current directory".
Otherwise, locate setenv.sh via find ~ -name setenv.sh, and make sure you are within the correct folder, before you call ./setenv.sh


text:
Q: How to pass a function as parameter in class(C++) I am doing Sort a List Of Student via:
1.Via Name
2.Via Date Of Birth
Both only differ type of compare,the rest is the same.
Because I do not want duplicate code I have used template type to do this:
class Student
{
    Date date;  // Date is a class
    Name name;  // Name is a class
   public:
    Date getDate() { return date; }
    Name getName() { return name; }
};
class ListOfStudent
{
    vector<Student> List;

   public:
    bool CompareDate(Date &d1, Date &d2);  // define d1<d2
    bool CompareName(Name &n1, Name &n2);  // define n1<n2

    void SortViaName()
    {
        for (int i = 0; i < List.size(); ++i)
            int min = i;
        for (int j = i + 1; j < List.size(); ++j)
        {
            if (CompareName(List[j].getName(), List[min].getName()))
                min = j;
        }
        if (min != i)
            swap(List[i], List[min]);
    }

    void SortViaDate()
    {
        for (int i = 0; i < List.size(); ++i)
            int min = i;
        for (int j = i + 1; j < List.size(); ++j)
        {
            if (CompareName(List[j].getDate(), List[min].getDate()))
                min = j;
        }
        if (min != i)
            swap(List[i], List[min]);
    }

    // Because i do not want to duplicate code so I do:
    template <typename T>
    void Sort(bool (*f)(T, T), T (*t)())
    {
        for (int i = 0; i < List.size(); ++i)
            int min = i;
        for (int j = i + 1; j < List.size(); ++j)
        {
            if ((*f)(DS[j].(*t)(), List[i].(*t)()))
                min = j;
        }
        if (min != i)
            swap(List[i], List[min]);
    }
};

It has  something wrong at template function so I need your supports.

A: In order to make things generic, the simplest way to set things up is to make the CompareThing function optionally take a Student& instead of a Date or Name.
Note: CompareDate and CompareName should be either static or global, that way you can pass them around as function pointers.
// We'll keep these
// Also they should either be static or global
bool CompareDate(Date &d1,Date &d2); //define d1<d2
bool CompareName(Name &n1,Name &n2); //define n1<n2

// Because these can both be used with Student, it's easy to template over them
bool CompareDate(Student &s1, Student &s2) {
    return CompareDate(s1.getDate(), s2.getDate());
}
bool CompareName(Student &s1, Student &s2) {
    return CompareName(s1.getName(), s2.getName());
}

Then, we can write Sort like this:
void Sort(bool(*compare)(Student&, Student&)) {
    std::sort(List.begin(), List.end(), compare);
}
void SortViaName() {
    Sort(CompareName);
}
void SortViaDate() {
    Sort(CompareDate);
}

Using your selection sort
We can write Sort to take the function as a parameter, and then use your selection sort instead of std::sort:
void Sort(bool (*compare)(Student&, Student&))
{
    for (int i = 0; i < List.size(); ++i) {
        int min = i;
        for (int j = i + 1; j < List.size(); ++j)
        {
            if (compare(List[j].getName(), List[min].getName()))
                min = j;
        }
        if (min != i)
            swap(List[i], List[min]);
    }
}


text:
Q: Why an operator $A:D(A)\to F$ is called "unbounded"? Let $E,F$ Banach spaces.

*

*We says that a linear operator $O: E\to F$ is bounded if $$\|Ox\|_F\leq C\|x\|_E,$$
for a certain $C>0$. This definition makes sense because this is equivalent at $$\|O\|_{L(E,V)}=\sup_{x\neq 0}\frac{\|Ox\|_F}{\|x\|_E}<C,$$ and thus, $O$ is bounded in $(L(E,V),\|\cdot \|_{L(E,V)})$.

*We call an unbounded operator a linear operator $A:D(A)\to F$ where $D(A)$ is a subspace of $E$. $D(A)$ is call the domain of $A$.
Remark : 1) If $\|Au\|_{F}\leq C\|u\|_E$ for all $u\in D(A)$, we says that $A$ is bounded. So, an unbounded operator can be bounded.
Question : What is the motivation to call it "unbounded" ? I really don't get it, and it sounds so confusing... (this definition come from Brezis : Analyse fonctionelle, théorie et application.) Moreover, it's not said that $D(A)$ must be proper, i.e. $D(A)=E$ could happen... so all linear operator $A:E\to F$ is call unbounded... so every bounded operator $E\to F$ are unbounded. This really don't make sense for me !

A: You are not the first person who is confused. See Confused about Domain of Unbounded Operators (Hilbert Spaces).
Also see the dicussion in https://ncatlab.org/nlab/show/unbounded+operator with its reference to the "red herring principle" https://ncatlab.org/nlab/show/red+herring+principle.

A: I agree that the terminology is a little confusing. Here 'linear operators' and 'unbounded linear operators' are seen as separate concepts, where the difference is rather subtle.  Let  me rewrite the two definitions:
Let $E,F$ be Banach spaces.

*

*A linear operator from $E$ to $F$ is a linear map $A:E\to F$;

*An unbounded linear operator from $E$ to $F$ is a linear map $A:D(A)\to F$ where $D(A)$ is a subspace of $E$.
As you can see in both cases we are referring to operators from $E$ to $F$ but the meaning is slightly different - in the first case the domain is actually $E$, whereas in the second case it isn't. So we could say that the main difference lies in the perspective - the second definition implies that you are first taking a large space $E$ and a map $A$, and then you realize that $A$ cannot be defined on the whole $E$ but only on a subspace. In practice, this often makes things simpler when treating actually unbounded operators.
For instance, differential operators are typically defined as unbounded operators on large spaces of functions, such as $L^2(\Omega)$ or $C(\Omega)$, but their actual domain is smaller because not all of these functions are differentiable.


text:
Q: Debugging a linked list implementation DList.java this contains the methods, we were given the first 4 methods, the last 4 we had to write ourselves , and frankly I have just gotten my self confused. I got this error on running the program
Exception in thread "main" java.lang.NullPointerException
    at javaapplication13.DList.remove(Dlist.java:41)
    at javaapplication13.Driver.main(Driver.java:18)
Java Result: 1

I know what this error is but I feel like I implemented the methods wrong at the end and my professors does not directly go through examples.
DList./java, these are the methods
package javaapplication13;

import java.util.NoSuchElementException;

/**
 *
 * @author thomas
 */
class DList<E> {
    public DLink<E>  head , tail , curr ;
    private  int  cnt ;

  /**
     * Insert "it" at current position
     */
    public void insert(E it) {
        curr.setNext(new DLink<E>(it, curr, curr.next()));
        curr.next().next().setPrev(curr.next());
        cnt++;
    }

    /**
     * Append "it" to list
     */
    public void append(E it) {
        tail.setPrev(new DLink<E>(it, tail.prev(), tail));
        tail.prev().prev().setNext(tail.prev());
        cnt++;
    }

    /**
     * Remove and return current element
     */
    public E remove() {
        if (curr.next() == tail) {
            return null; // Nothing to remove
        }
        E it = curr.next().element(); // Remember value
        curr.next().next().setPrev(curr);
        curr.setNext(curr.next().next()); // Remove from list
        cnt--; // Decrement the count
        return it; // Return value removed

    }
 public void moveToPrev() {
        if (curr != head) // Can't back up from list head
        {
            curr = curr.prev();
        }
    }

 public void moveToPos(int pos)
 {
     assert (pos>=0) && (pos<=cnt) : "Position out of range";
  curr = head;
  for(int i=0; i<pos; i++) {curr = curr.next();
 }}

 public void moveToValue(E it)
 {
while (it!=curr)
{

}
  }
   public  void insertBefore(E it) {
   curr.setNext(new DLink<E>(it, curr, curr.prev()));
        curr.next().prev().setPrev(curr.next());
        cnt++;

  }

 public void removePrev()
 {
moveToPrev();
 if (curr==null) {
      throw new IndexOutOfBoundsException("empty list.");
    }
    if (curr == head) {
      throw new NoSuchElementException("cannot remove the head");
    }
    remove();

  }

 public void printAll()
 {

        while(curr != null){
            System.out.print(curr +" ");
            curr = curr.next;
        }
        System.out.println();
             }
}

DLink.java, this was also given too us.
package javaapplication13;

/**
 * Doubly linked list node
 */
class DLink<E> {

  public E element; // Value for this node
public DLink<E> next, prev; // Pointer to next node in list
 // Pointer to previous node

    /**
     * Constructors
     */

    /** Constructors */
DLink(E it, DLink<E> p, DLink<E> n)
{ element = it; prev = p; next = n; }
DLink(DLink<E> p, DLink<E> n) { prev = p; next = n; }
/** Get and set methods for the data members */
DLink<E> next() { return next; }
DLink<E> setNext(DLink<E> nextval)
{ return next = nextval; }
DLink<E> prev() { return prev; }
DLink<E> setPrev(DLink<E> prevval)
{ return prev = prevval; }
E element() { return element; }
E setElement(E it) { return element = it; }

}

Driver.java , this is the file that the instructor supplied to test with
public class Driver{

public static void main(String args[])
{
    DList<Integer> dlList = new DList<Integer>();

    System.out.println("removing from empty list");
    dlList.remove();
    dlList.remove();

    dlList.insert(30);
    dlList.insert(20);
    dlList.insert(10);

    dlList.append(40);
        dlList.append(50);
        dlList.append(60);

    dlList.printAll();

    System.out.println("Moving to Position 3..");
    dlList.moveToPos(3);

    dlList.append(200);

    dlList.insert(180);
    dlList.insert(140);
    dlList.insert(120);

    System.out.println("Moving to Previous Position..");
    dlList.moveToPrev();

    dlList.printAll();

    System.out.println("Removing node..");
    dlList.remove();

    dlList.printAll();

    System.out.println("Moving to First Position..");
    dlList.moveToStart();

    System.out.println("Removing node..");
    dlList.remove();

    dlList.printAll();

    System.out.println("Moving to Value 2..");
    dlList.moveToValue(2);

    System.out.println("Moving to Value 120..");
        dlList.moveToValue(120);

    System.out.println("Inserting 25..");
    dlList.insert(25);
        dlList.printAll();

    System.out.println("Removing previous node..");
        dlList.removePrev();
        dlList.printAll();

    System.out.println("Moving to First Position..");
    dlList.moveToStart();

    System.out.println("Inserting 45..");
        dlList.insert(45);

    System.out.println("Insert before 35..");
    dlList.insertPrev(35);
        dlList.printAll();

    System.out.println("Moving to 50..");
        dlList.moveToValue(50);

    System.out.println("Inserting 55..");
        dlList.insert(55);
    dlList.printAll();

    System.out.println("Removing previous nodes twice.");
    dlList.removePrev();
        dlList.removePrev();
        dlList.printAll();

    System.out.println("Removing nodes thrice.");
        dlList.remove();
    dlList.printAll();
    dlList.remove();
        dlList.printAll();
        dlList.remove();

        dlList.printAll();

}
}

A: curr.next()  is null. You didn't initialize it. So calling a method next in it will give NullPointerException


text:
Q: Want to know the position of ESP partition in HDD I have a laptop with 2 SSD connected, named as Disk0 & Disk1 in Disk management. ESP partition and the OS are both present in Disk0. I am using Disk1 as data partition. I am planning to install another OS on the Disk1. Suddenly I had a doubt while looking into the partition structure. ESP is present in Disk0.
Is it possible to create ESP on Disk-1 instead of Disk-0? Or should ESP always be present in Disk0?

A: Assuming that the new OS can see and access disk zero, then you should not have to do anything with the EFI system partition except possibly enlarge it (if you're using Linux, chances are it's already more than large enough, but the same may not be true if it's Windows on disk zero). The installer for the new OS should see it and use it by default, and things should Just Work.
However, this setup does have it's drawbacks, namely that if disk zero is removed from the system, this new OS on disk one will not be able to boot (because there will be no EFI system partition any more). You can avoid this by creating a second EFI system partition on disk one, but that brings in it's own issues, namely that the firmware may just ignore it and only look at the ESP on disk 0 (this is technically incorrect behavior per the EFI spec, but I've seen multiple implementations that behave this way).


text:
Q: How do you get only one output from a swi-prolog query? How do I get only one output from a SWI-Prolog query? I have tried using cut (!) but it does not seem to work.
For example:
I already filled my knowledge base up with statements and I wanted to find any one name who is both female and is the mother of someone.
I have already tried:
mother(X,Y), female(X).

...but that gives me all of the X-__ and Y-__
I have also tried:
mother(X,Y), female(X), !.

... but that still gives me both the X-__ and Y__
I only want to find the X. Does anyone have any tips for me to somehow only get one?

A: ?- setof(t, Y^ ( mother(X, Y), female(Y) ), _).

which will remove duplicates (redundant answers/solutions), too. Or using library(lambda):
?- X+\ ( mother(X, Y), female(Y) ).

which does not remove redundant answers.


text:
Q: Can NetworkX library read RDF data in Ntriple format and build a Graph object along with attributes or node features Can NetworkX library read RDF data in Ntriple format and build a Graph object along with attributes or node features.
I tried the below code to convert the RDF data(.nt file) in to Graph using the rdflib,
from rdflib.extras.external_graph_libs import *
from rdflib import Graph, URIRef, Literal
import networkx as nx

graph = Graph()
graph.parse("Airports-with-lables.nt", format="nt")
nx_graph = rdflib_to_networkx_multidigraph(graph)
nx.write_graphml(nx_graph,"example_airport.graphml")

However the generated grahml file doesn't have attributes, because of which I am not able to proceed with StellarGraph Hinsage algorithm(https://github.com/stellargraph/stellargraph/tree/develop/demos/node-classification/hinsage) which expects the node features as one of the parameter.
Can anyone help on this please.


text:
Q: How does air-drop detect other air-drop devices? It is clear from other posts that AirDrop "uses" Bluetooth Low Energy to "find" other AirDrop enabled devices. How does it do this? Specifically, how does an apple device differentiate between just another bluetooth device and one with airdrop enabled?
It could 1) try to pair with every transmitting device, 2) use the bluetooth friendly name, 3) additional data in the radio without pairing?
The BluetoothDeviceInfo structure that comes back from creating a radio on the Microsoft stack doesn't include any identifying info besides the Friendly Name: https://msdn.microsoft.com/en-us/library/windows/desktop/aa362924%28v=vs.85%29.aspx
The other possibility is that it tries to pair with all broadcasting bluetooth devices - but that could be slow.
Thanks for any help and/or insight!

A: I thought I would share what I found in case this information can shortcut someone else's learning.
Bluetooth Low Energy is a completely different Spec than older versions of bluetooth. There are completely different APIs from Microsoft to support BT LE: https://msdn.microsoft.com/en-us/library/windows/hardware/jj159880%28v=vs.85%29.aspx
Unlike older versions of bluetooth, a BT LE "Peripheral" device (sending device) can advertise it's capabilities so that a connecting device (Also known as a "Central") can tell what the Peripheral is capable of without actually connecting/pairing with the Peripheral.
The capabilities of a Peripheral are communicated using a Generic Attribute Profile, or GATT for short.
Per my previous question, the BluetoothDeviceInfo structure is part of the older Microsoft API for bluetooth supporting non-BT LE devices: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363058%28v=vs.85%29.aspx
Also, the C# 32feet.net library to help with Bluetooth does not support BT LE.
I hope that helps someone.


text:
Q: Streamreader: How do I break out of an outside loop from an if block when reading I am updating a line in a daily-generated file, but I know the line I'm looking for will be in the first 20 lines of at least 30,000 more. Is there a way to cancel the stream reading when the line replace is completed? What I'm looking for is to update the errant line and overwrite the existing file. (The program that generates it does not have the ability to fix it before creating the file.
StreamReader sr = new StreamReader(strSourcePath);
    while (!sr.EndOfStream)
    {
         string line = sr.ReadLine();
         if (line.Contains("hello world"))
         {
             line.Replace("hello world","Hello World!");
         }//if
    }//while

A: Use break; to break out of loops.

A: Based on Alexi's comment, I realized that I need to go through the whole file anyway, if I'm processing it through StreamWriter. Break gets me out of the block, but ended up not being the ideal way to run the program.
StreamReader sr = new StreamReader(strSourcePath);
StreamWriter swUpdatedFile = new StreamWriter(strSourcePath.Replace(".txt", ".dat"), false, Encoding.GetEncoding(1250));
while (!sr.EndOfStream)
{
      string line = sr.ReadLine();
      if (line.Contains("hello world"))
      {
           swUpdatedFile.WriteLine("Hello World!");

      }//if
      else
      {
           swUpdatedFile.WriteLine(line);
      }

  }//while


text:
Q: How to format HTML in Sublime Text 3 I'm using Sublime 3 to prepare HTML files that will eventually be turned into an epub in Sigil. This is working very well except that the formatting isn't helping the readability.
I have HTMLbeautify and HTML/CSS/JSPrettify. They do a great job with the indentation but I would also like a method of putting the opening and closing paragraph tags on new lines, something like
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum dolor in lacus efficitur consequat. Cras turpis dolor, pretium sit  amet tincidunt sed, porta iaculis lectus. Morbi consectetur vitae justo eu  pretium.
</p>

Can anybody help?
I've read all the other Sublime/HTML formatting queries and i can't find anything that quite covers this.

A: Just select all lines (Ctrl A) and then from the menu select Edit → Line → Reindent. This will work


text:
Q: OpenTelemetry JVM and System metrics I have used micrometer.io for most of my career to collect metrics. One of the coolest micrometer features is binding to collect information about the host system and jvm: https://micrometer.io/docs/ref/jvm on the basis of which it was possible to run the Grafana dashboard without much effort: https://grafana.com/grafana/dashboards/4701
Currently, I am starting to learn about OpenTelemetry, but I cannot find a description of the above functionalities. I do not want to use instrumentation, I want to depend on a manual definition of what is to be measured. Can you show me a way to do this? How to easily manually provide system/JVM metrics?

A: I don't think such a component exist in OTel, see:
Metrics API spec: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md
Metrics SDK spec: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md

A: See Is there an equivalent of Prometheus simpleclient_hotspot with Opentelemetry?.
You can use opentelemetry-java-instrumentation and manually register JVM metrics observers.


text:
Q: PHP mySQL 404 function The following function is designed to check whether this row in this tables exists. I know that it does not yet whether I $row or !$row the if function it does not do anything.
function four_zero_four($name){
    $four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");

    while($row = mysql_fetch_array($four_zero_four)) {
      echo 'no'; die();
    }
};

$name is the name field from the row and is working correctly in other functions.

A: Another way to check whether a row exists is by using the mysql_result function in conjunction with the COUNT function as such:
$query = mysql_query("SELECT COUNT(1) FROM `table` WHERE `field` = 'something'");
$result = mysql_result($query, 0);

When you now print out the $result variable, you will see the amount of rows that are actually being returned by the query. This is generally faster than using mysql_num_rows.

A: I'm not sure I understand the logic, aren't you printing "no"; die() when there IS a row found, instead of when now row is found?  Either way, here's how I would check:
function four_zero_four($name){
    $four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");

    if (mysql_num_rows($four_zero_four) == 0) {
        // ROW DOES NOT EXIST
    } else {
        // ROW EXISTS
    }
};

A: Your code does not work because it wont even be executed if there is no row returned by your query.
Use mysql_num_rows() instead:
$count = mysql_num_rows($four_zero_four);

if($count <= 0){
    die("no rows in this table!");
}

Also, you should maybe consider to use MYSQLi commands instead of the old mysql_query() implementation and SELECT *, as they are deprecated.


text:
Q: Magento - getting the wrong number of the method count() Hi
I have assign 12 product to category Phone(id=12), and

{{block type="catalog/product_list" category_id="12" template="catalog/product/list2.phtml"}}

in a CMS page, I have placed

<?php
  $_productCollection=$this->getLoadedProductCollection();
  echo $_productCollection->count()
  ?>

to list2.phtml
Why it get 9 instead of 12?
I set "Products per Page on Grid Default Value=9" in backend, is this affecting the result above, and how to fix it?
Thanks you

A: Instead of...
echo $_productCollection->count()

...try this method:
echo $_productCollection->getSize()

Internally getSize() uses getSelectCountSql() which takes the original select statement, strips off page limitations and queries the database directly. So it returns the correct answer even after the shorter, paginated, list has been loaded. Whereas count() returns the actual number of items in the loaded list.


text:
Q: If $aHow do I prove the above problem?
I tried finding discriminant, It wasn't very useful as it didn't yield any useful conclusion.

A: Note that
$$f(x)=(x-a)(x-c)+2(x-b)(x-d)=0$$
$$\iff g(x)=(x-a)(x-c)=-2(x-b)(x-d)=h(x)$$
and

*

*$g(x)$ is a parabola concave up which intercepts $x$ axis at $x=a$ and
$x=c$

*$h(x)$ is a parabola concave down which intercepts $x$ axis at $x=b$ and
$x=d$

thus by IVT $2$ distinct real roots exist for $f(x)=0$.


text:
Q: Return function from background thread My function execution is taking time
    func hasValidValues() -> Bool{
        let leftValue = Double(leftTextValue) ?? 0
        let rightValue = Double(rightTextValue) ?? 0
        switch self.stackViewType {
            let leftValid = self.hasValidValue(min: targetMin, max: targetMax, value: CGFloat(leftValue), unitConversation: true)
            let rightValid = self.hasValidValue(min: 0, max: plusMinusLimit, value: CGFloat(rightValue), unitConversation: true)
            return leftValid && rightValid
}

Now I need to execute this in background thread, and wanted to return so UI thread can access it and I can change UI in another controller.
Can anyone help me on this?

A: Use DispatchQueue:
DispatchQueue.global().async {
    let result = self.hasValidChanges()
    DispatchQueue.main.async {
        // Use result
    }
}

A: You can't return value from another tread because each thread has its own stack. So you have to use callback here.
func checkValidValues(completionHandler: @escaping ((Bool) -> Void)) {
    DispatchQueue.global().async { [unowned self] in
        let result = self.hasValidChanges()
        DispatchQueue.main.async {
        completionHandler(result)
    }
}

A: You could use a dispatch group
var b: Bool = false
let queue = DispatchQueue(label: "myQueue")

let group = DispatchGroup()
group.enter()

DispatchQueue.global().async {
    b = hasValidValues()
    group.leave()
}

group.notify(queue: queue) {
    //use b
}


text:
Q: Will repackaging a ship remove all of its upgrades? I have a ship, capable of transporting 2-3 other ships in its cargo hold. If I wanted to transport some of my other ships to another station, I could repackage these ships, put them into the cargo hold of the bigger ship, and then set out to the new station.
The ships I would be repackaging all have a variety of weapons and rigs on them. If I repackage these ships, what will happen to all of these items?
Obviously I could remove the weapons and other stuff to test, but rigs can't be removed without destroying them so I am a bit reluctant to test it.

A: Yes, repackaging will destroy your rigs, and automatically strip all the leftover fitted mods. (Non-rigs modules are not destroyed.)
There is no way to repackage a ship without losing the rigs. The only way to transport them is in a carrier or in the ship bay of an Orca.


text:
Q: Angular description of @Input / @Output property I want to describe my @Input() and @Output() property in my component, that I see it in the HTML.
for example.
   /**
   * Columndefinition of the right grid.
   */
  @Input()
  rightColumnDef?: ColumnDefinition[] = [
    {
      ...
    }
  ];

Now I want to see this in the tooltip of my IDE
<component
        [rightColumnDef]="columnDef"
></component

Please help me how can I do this.
t.

A: You need Angular Language Service. There is documentation how to install it for popular IDE's. Be very attentive, the tool is system resources demanding.


text:
Q: How to include header files to c++ dll file I want to include iostream inside a c++ dll file but am getting "fatal error: iostream: No such file or directory" error.
How can I include header files in a dll file?

A: There's no such a thing like "include header files in a dll file".
What you can do is:
include header files in a source code file (i.e. *.cpp),
then compile it to create a shared library (DLL file on Windows platform).


text:
Q: Socketio events aren't emitting from other python files I'm building an app using socketio and flask in python.
For the purposes of maintaining sockets and rooms I've created the following class to hold each user that connects:
class Socket:
  def __init__(self, sid):
    self.sid = sid
    self.connected = True
    self.character = None

  def emit(self, event, data):
    socketio.emit(event, data, room=self.sid)

This allows me to emit events to this user specifically. This class is declared in my server.py for the time being (my main script)
In a separate file I have the following class:
from __main__ import socketio
from __main__ import Socket

class Battle():
    def __init__(self, contestant_one=None, contestant_two=None, room_name=""):
        self.contestant_one = contestant_one
        self.contestant_two = contestant_two
        self.room_name = room_name

    def start_battle(self):
        if self.contestant_one and self.contestant_two is not None:
            self.contestant_one.emit('start battle', JSONEncoder().encode(self.contestant_one.character.__dict__))

The above class is imported into server.py (my mains script) as seen below:
app = Flask(__name__, static_folder="static")
app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#'
socketio = SocketIO(app)

class Socket:
def __init__(self, sid):
    self.sid = sid
    self.connected = True
    self.character = None

def emit(self, event, data):
    socketio.emit(event, data, room=self.sid)

from battle import Battle

Notice how I am importing after the socketio and socket definitions? this is according to:
Flask socket.io message events in different files
contestant one and contestant two are both socket objects that are defined in server.py, and have the ability to emit messages to specific users but the event isn't being emitted in battle. I've checked in both clients browsers for the simple log I have setup to listen for that message and nothing is coming. No errors are occurring either.
JS code on client:
    socket.on('start fight', function(characters){
        console.log(characters)
    })

i've also tried testing this with print statements in the start_battle method so I know the code is executing because the prints happen.
I'll mention that I'm new to python and have worked mostly with node when it comes to socketio. Any suggestions appreciated.

A:  socket.on('start fight', function(characters){
    console.log(characters)
})

is listening for 'start fight' but the battle event is emitting 'start battle'
This worked after correcting it.


text:
Q: Separate columns with constant numbers and condense them to one row in R data.frame I have a data.frame called d. In this data.frame, some columns consist of constant numbers across the rows of the first column: study.name (see below).
For example, columns ESL, ESL.1, prof, and prof.1 are constant numbers for all rows of Shin.Ellis and also constant for all rows of Trus.Hsu and so on.
Q: In BASE R, how can I separate such constant variables, and then condense them to one row with only one number?
My desired output is shown further below. A functional answer is appreciated.
d <- read.csv("https://raw.githubusercontent.com/izeh/m/master/irr.csv", h = T)[-(2:3)]

## FIRST 8 ROWS:

#    study.name ESL prof scope type ESL.1 prof.1 scope.1 type.1
# 1  Shin.Ellis   1    2     1    1     1      2       1      1
# 2  Shin.Ellis   1    2     1    1     1      2       1      1
# 3  Shin.Ellis   1    2     1    2     1      2       1      1
# 4  Shin.Ellis   1    2     1    2     1      2       1      1
# 5  Shin.Ellis   1    2    NA   NA     1      2      NA     NA
# 6  Shin.Ellis   1    2    NA   NA     1      2      NA     NA
# 7    Trus.Hsu   2    2     2    1     2      2       1      1
# 8    Trus.Hsu   2    2    NA   NA     2      2      NA     NA

Desired output:
#    study.name ESL prof  ESL.1 prof.1
# 1  Shin.Ellis   1    2      1      2
# 2  Trus.Hsu     2    2      2      2
# .     .         .    .      .      . # AND SO ON !!!

A: If you just want to remove repeated values across all columns unique() is base R
unique(d)

EDIT - Thanks for the clarification @CalumYou - I think this is what OP is looking for in base R.
is_constant = lapply(split(d, d$study.name), function(data){
  unlist(lapply(data,function(col){
    length(unique(col)) == 1
  }))
})
is_constant = as.data.frame(do.call(rbind, is_constant))
all_constant = d[,unlist(lapply(is_constant,all))]
all_constant = unique(all_constant)

A: May be we need
library(dplyr)
d %>%
   group_by(study.name) %>%
   slice(1)

Or in base R after grouping by 'study.name', get the first row while specifying the na.action = NULL as the default option is na.omit which can omit any row having NA in any of the columns
aggregate(.~ study.name, d, head, 1, na.action = NULL)

If we want to subset the columns
nm1 <- names(which(!colSums(!do.call(rbind, by(d[-1], d$study.name,
     FUN = function(x) lengths(sapply(x, unique)) == 1)))))
unique(d[c("study.name", nm1)])

A: d_list <- lapply(split(d,d$study.name),
                 #Find columns with similar values using sapply and length(unique(cols))
                 #then get the 1st row
                 function(x) x[1, sapply(x,function(y) length(unique(y))==1)])
do.call('rbind.data.frame',d_list)

           study.name ESL prof ESL.1 prof.1
Bit.KnoA     Bit.KnoA   1    3     1      3
Bit.KnoB     Bit.KnoB   1    2     1      2
ChandlerA   ChandlerA   1    2     1      2
Mubarak       Mubarak   2   NA     2     NA
SheenA         SheenA   1    2     1      2
Shin.Ellis Shin.Ellis   1    2     1      2
Sun               Sun   2    2     2      2
Trus.Hsu     Trus.Hsu   2    2     2      2

A: You could try something like this, though it feels a bit clumsy. Basically, check which columns have constant values by group for all groups, keep only those columns, and then keep only unique values (since now they are constant by group).
d <- read.table(header = TRUE,
text = "study.name ESL prof scope type ESL.1 prof.1 scope.1 type.1
Shin.Ellis   1    2     1    1     1      2       1      1
Shin.Ellis   1    2     1    1     1      2       1      1
Shin.Ellis   1    2     1    2     1      2       1      1
Shin.Ellis   1    2     1    2     1      2       1      1
Shin.Ellis   1    2    NA   NA     1      2      NA     NA
Shin.Ellis   1    2    NA   NA     1      2      NA     NA
  Trus.Hsu   2    2     2    1     2      2       1      1
  Trus.Hsu   2    2    NA   NA     2      2      NA     NA")

is_constant <- function(x) length(unique(x)) == 1L

keep_constants <- function(df, group_col) {
  data_cols <- colnames(df)[setdiff(1:ncol(df), group_col)]
  check_df <- aggregate(df, by = list(df[[group_col]]), FUN = is_constant)
  cols_to_keep <- sapply(check_df[, -1], all)
  unique(df[, cols_to_keep])
}

keep_constants(d, 1)
#>   study.name ESL prof ESL.1 prof.1
#> 1 Shin.Ellis   1    2     1      2
#> 7   Trus.Hsu   2    2     2      2

Created on 2019-10-09 by the reprex package (v0.3.0)


text:
Q: How to show Document library documents based on User I need to show documents in document library based on a user.
For example, I have one list in which I have some Projects for the user. Based on the Projects he has I need to show the documents in document library based on Project folders.
For example I have folders Abc, xyz, sss. The user has only abc ,sss Projects so I need to show only those folders.
Please help me how to achieve this.


text:
Q: How Sample mean equals Population Mean? I did try searching here before posting, but could not find a satisfactory answer. This is my attempt to prove mean of sample means equals to population mean where I am stuck.
Note: Rewritten as per Aaron's feedback (not fully though yet, due to a pending question described below)
Step 1:
Population Mean

Let $Y$ denote a random variable from a population of size $T$ with mean $\mu$ and $\sigma$

So,
$
\text{Population Mean,} \ \ \
\mu = E[Y] = \dfrac{\sum\limits_{i=1}^T y_i}{T} \tag{1}
$

Step 2:
Sample Mean

Let $\widehat{Y_k}$ denote a sample set of size $n$. Let no of experiements = $N$
For any $k$th sample set $\widehat{Y_k}$ and, $k = 1,2,3,....N$

$
\text{Mean of sample set,  } \ \
\overline{\widehat{Y_k}} = \dfrac {\sum\limits_{j=1}^n \widehat{y_{kj}}}{n} \tag{2}
$
$\overline{\widehat{Y_k}}$ is a random variable, not constant

Step 3:
Mean of Sample Means
Suppose we take the sample means, N number of times. In resulting sampling distribution,  the mean of sample means  can be calculated as follows

$
\text {Mean of Sample Means, } \ \ \
\mu_{\overline{\widehat{Y_k}}}
= E\Bigg[\overline{\widehat{Y}}\Bigg]
= \overline{\overline{\widehat{Y}}}
= \sum\limits_{k=1}^N
\dfrac{1}{N}\overline{\widehat{Y_k}} \\
$

Using eq. $2$
$
 E\Bigg[\overline{\widehat{Y}}\Bigg]
= \sum\limits_{k=1}^N
\dfrac{1}{N}
\sum\limits_{j=1}^n \dfrac{\widehat{y_{kj}}}{n}  \tag{3}
$

Main question:

*

*How do I prove further equation $3$ equals population mean $\mu$? This is where I got stuck.

*How do we derive similary for variance of sampling distribution of sample means, $\sigma_\overline{\widehat{Y_k}}^2 = \dfrac {\sigma^2}{n}$?

Aaron's Lemma:
Aaron Montgomery has done a great job trying to explain the issue in my semantics in his answers below, however there are few areas I am still missing to understand.
$$
\mathbb E \left[ \overline{ \widehat{Y_k} } \right] = \sum_{i \in \bigstar} \frac{1}{\binom T n} \sum_{j=1}^n \frac{\widehat{y_{ij}}}{n}
\tag {4}
$$
where $\bigstar$ is taken over all possible samples of size $n$ that can be drawn from the population.
Eq $4$ expands further as,
$$
\frac{1}{\binom T n \cdot n} \sum_{i=1}^T \binom{T-1}{n-1} y_i = \frac{\frac{(T-1)!}{(n-1)!(T-n)!}}{\frac{T!}{n!(T-n)!} n} \sum_{i=1}^T y_i = \frac 1 T \sum_{i=1}^T y_i = \mu. \qquad \qquad  \tag {5}
$$
My questions in his lemma:

*

*How do I equate equations $3$ to $4$?

*Equation $5$ evolves because Aaron says  "In the double summation, y will appear in exactly $\binom{T-1}{n-1}$ of the $\binom{T}{n}$ terms". How?

A: One important distinction is between the expected value, which represents a theoretical long-run average of sorts, and the observed sample average, which is the sum of your observed sample elements divided by the size of the sample. This distinction is key. The sample average is indeed a random variable, because it depends upon the sample that was collected. But the expected value is not a random variable; it's a constant. The symbols $E$ and $\mu$ should only be used when discussing the theoretical, long-run averages -- not the observed sample results. The following equalities are both fine:
$$\mu_{\overline{\widehat{Y_k}}} = \mathbb E \left[\overline{\widehat{Y_k}} \right]$$
$$\overline{\widehat{Y_k}} = \frac{\sum_{j=1}^n \widehat{y_{kj}}}{n}$$
but the two quantities are not equal to one another. I think this disconnect lies at the heart of the issue in your post. In particular, it is why (2) is incorrect, as is the last line of (3).
Next: I would encourage you to revisit the link you posted, armed with some additional knowledge about the notation. Traditionally, in probability and statistics we use capital letters for random variables (such as the individual items selected in a sample), Greek letters for parameters, and Roman letters for other constants (such as a sample size). There are no rules about this, of course, but these are good conventions to adopt if for no other reason than that they will help you read existing literature on the subject.  In the article you linked, $X_1$ is in fact not a constant; it is a random variable, and its mean is essentially defined to be $\mu$. Notice the remark at the top of the page; each $X_i$ is an individual observation drawn from an underlying population with mean $\mu$ and variance $\sigma^2$.
Now, I'll try to repair the calculations you listed in your question by sticking to the ideas you've presented as closely as possible. I'll also use your notation for the sake of this answer, but I should again stress that it's worth trying to adopt the standard conventions instead. We first prove a lemma:
Lemma 1: For each $k$, $\mathbb E \left[ \overline{\widehat{Y_k}} \right] = \mu$.
Proof: To compute this expected value, we average over all the possibilities: $$\mathbb E \left[ \overline{ \widehat{Y_k} } \right] = \sum_{i \in \bigstar} \frac{1}{\binom T n} \sum_{j=1}^n \frac{\widehat{y_{ij}}}{n}$$
where $\bigstar$ is taken over all possible samples of size $n$ that can be drawn from the population. Since this is a random sample, we note that each sample of size $n$ is equally likely, which is why we weight each one with a factor of $1 / \binom T n$.

Expanding that idea further: The fundamental question is how many ways there are to draw a sample of size $n$ from a population of size $T$ that contain the distinguished element $y$. This, like all probability, comes down to a counting argument. If we demand that a sample must contain $y$, then we can fill the other $n-1$ spots with any of the available $T-1$ choices. Hence, there are $\binom{T-1}{n-1}$ ways to accomplish this.

Fix any $y$ in the original population. In the double summation, $y$ will appear in exactly $\binom{T-1}{n-1}$ of the $\binom T n$ terms.
Hence, the expectation is equal to
$$\frac{1}{\binom T n \cdot n} \sum_{i=1}^T \binom{T-1}{n-1} y_i = \frac{\frac{(T-1)!}{(n-1)!(T-n)!}}{\frac{T!}{n!(T-n)!} n} \sum_{i=1}^T y_i = \frac 1 T \sum_{i=1}^T y_i = \mu. \qquad \qquad \square$$
Important remark: This is not the best way to prove this! It is complicated, messy, and convoluted. The link you attached has the best way to prove this result.
Using that lemma, I think you can repair (3). I think you may have neglected a $\frac 1 N$ somewhere in (3), but it's hard to tell because I can't interpret the meaning of $\mu_{\overline { \widehat Y}}$. Perhaps Lemma 1 above was what you were trying to show there?
For main question 2: Since $\overline{\widehat{Y_k}} = \frac 1 n \sum_{j=1}^{n} \widehat{y_{kj}}$ and the $y_{kj}$ terms are independent of one another, it follows from a classical theorem I referenced in my other post that
$$\operatorname{Var} \left(\overline{\widehat{Y_k}} \right) = \left( \frac 1 n \right)^2 \sum_{j=1}^n \operatorname{Var}(\widehat{y_{kj}}) = \frac 1 n \cdot \sigma^2.$$
Taking square roots of both sides gives the desired result.


text:
Q: Share a photo to facebook via javascript I'm using a very simple javascript to share an URL to facebook wall:
window.open('https://www.facebook.com/sharer/sharer.php?u='+something);

This allows user to finish the sharing in facebook confirmation window. However, now I need to share an image in a similar way.
I'm also using open graph protocol to make facebook display preview of my site properly. But preview invoked by using proper facebook tags is useless:

I wonder: how can I force facebook to appear in english?
Is it possible to either share site as an image or share image by it's URL directly?
If possible, I wan't to do without Facebook API scripts on my site, as well as any iframes or other ugly external stuff.
I also have no interest in knowing what the user did with the share window.

A: You'll need the image meta tag in your page head. (add your image url to the facebook og:image meta tag and so on and so forth)

<meta name="description" content="" />
<meta name="keywords" content="" />

<meta name="author" content="" />
<meta name="copyright" content="" />
<meta name="application-name" content="" />

<meta property="og:title" content="" />
<meta property="og:type" content="article" />
<meta property="og:image" content="" />
<meta property="og:url" content="" />
<meta property="og:description" content="" />

<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="" />
<meta name="twitter:description" content="" />
<meta name="twitter:image" content="" />

A: Did you try using this one?
Add this after the body

and this to where your share button to appear

A: One way, that I can think of, is sharing an image in the form of a Facebook post. But again, it requires the use of Facebook API. Anyways, I'll just share this method here and you can use it in case you feel like using Facebook API.
For this you can make a POST request to the /{user-id}/feed endpoint. For example:
me/feed?message="Test"&link={Image_URL}&access_token={User_Access_Token}

This method requires a valid User Access Token with publish_stream permission.


text:
Q: Javascript (Jest) tests on Semaphore CI ruby project I've had a Ruby on Rails project for several years set up with Semaphore CI. The Semaphore project is set to use Ruby 2.2.2 as it's language. Over time the project adopted npm with browserify and babelify, and we're using all the latest ES6 features. We added npm install as a setup step to our Semaphore build, and this was working fine.
Now we are starting to use Jest to test our javascripts, and this is working fine locally. But when I added npm test to our Semaphore test commands, npm test fails on semaphore CI with the following errors:
FAIL app/assets/javascripts/tests/selectors/conversations.test.js
● Test suite failed to run

SyntaxError: Unexpected token {

  at _load_jsdom (node_modules/jest/node_modules/jest-cli/node_modules/jest-environment-jsdom/build/index.js:17:41)

FAIL app/assets/javascripts/tests/reducers/conversations.test.js
● Test suite failed to run

SyntaxError: Unexpected token {
  at _load_jsdom (node_modules/jest/node_modules/jest-cli/node_modules/jest-environment-jsdom/build/index.js:17:41)

Test Suites: 2 failed, 2 total
Tests:       0 total
Snapshots:   0 total
Time:        0.65s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

This is some relavent information from the project's package.json:
"scripts": {
  "test": "jest --debug --verbose"
},
"jest": {
  "roots": [
    "<rootDir>/app/assets/javascripts"
  ]
},
"dependencies": {
  "babel-plugin-syntax-async-functions": "^6.3.13",
  "babel-plugin-transform-class-properties": "^6.24.1",
  "babel-plugin-transform-regenerator": "^6.3.18",
  "babel-polyfill": "^6.3.14",
  "babel-preset-env": "^1.5.2",
  "babel-preset-es2015": "^6.24.1",
  "babel-preset-es2016": "^6.24.1",
  "babel-preset-es2017": "^6.24.1",
  "babel-preset-react": "^6.3.13",
  "babel-preset-stage-0": "^6.3.13",
  "babelify": "^7.2.0",
  "browserify": "^14.0.0",
  "browserify-incremental": "^3.1.0",
  "es6-promise": "^3.0.2",
  "fetch": "^0.3.6"
},
"devDependencies": {
  "babel-core": "^6.26.0",
  "babel-jest": "^22.1.0",
  "babel-plugin-transform-class-properties": "^6.24.1",
  "bootstrap": "^4.0.0-beta.3",
  "browserify": "^14.4.0",
  "browserify-incremental": "^3.1.1",
  "jest": "^22.1.1"
}

This is the .babelrc file located in the project :
{
  "presets": ["env", "es2015", "es2016", "es2017", "stage-0", "react"]
}

Locally, I am on node v7.10.0. I SSH'ed into my Semaphore CI session and discovered that node v4.8.4 is installed there. I tried installing node v4.8.4 on my local machine and with that version installed, I get the same test errors (posted above) locally as I did on CI. So this is a node version issue.
I added:
"engines": {
  "node": ">= 7.1.0"
}

to my package.json file, but that did not affect the node version installed on Semaphore.
So if I already have Ruby 2.2.2 chosen as my language and version in the Semaphore Build Settings, how to I change my node version?
Thanks in advance for the help.

A: It looks like SemaphoreCI is not using the same version of NPM as you. But you can set that within the build settings like this :
nvm install v8.9.4
npm install
npm test

You can test it out in the SSH

A: Ervin from Semaphore here,
To change the current Node.js version in the environment, whilst Ruby 2.2 is selected, add nvm use 7.1 to your setup steps. This will switch to the desired Node.js version and everything should work as expected. There's also an example of this in the docs.
Get in touch on support if you run into any issues.


text:
Q: Error installing pygame: "error: command 'x86_64-linux-gnu-gcc' failed with exit status 1" So I've tried pretty much all the answers to similar questions I've been able to find, but I still haven't found a working solution. The complete info I get is:
(first_kivy_app)bemery94@bemery94-XPS-15-9530:~/Downloads/pygame-1.9.1release$ python setup.py install
running install
running build
running build_py
running build_ext
building 'pygame._camera' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -D_REENTRANT -I/usr/X11R6/include -I/usr/include/SDL -I/usr/include/python2.7 -c src/_camera.c -o build/temp.linux-x86_64-2.7/src/_camera.o
In file included from src/_camera.c:36:0:
src/camera.h:42:32: fatal error: linux/videodev.h: No such file or directory
 #include <linux/videodev.h>
                            ^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

Does anyone know a solution?
Thanks you!

A: Since the issue is a missing linux/videodev.h, try installing a package which provides it:
sudo apt-get install gcc-i686-linux-android


text:
Q: Given a Flask app object, how can I obtain the templates folder absolute path? After initializing the app, I would like to determine the absolute path of the 'templates' folder (to read a yaml file located inside it).
app = Flask(__name__)

for example, I'm looking for something like this:
templates_path = app.get_absolute_path_to_templates()

A: Found it:
templates_path = os.path.join(app.root_path, app.template_folder)

Thanks to: Get root path of Flask application


text:
Q: R: Problems with copula due to safeUroot function not found. I am trying to fit a copula with a script I have used many times before, but suddenly I get an error because of a function safeUroot. It says the function is not found, even if it appears to be defined. CAn anyone help and explain why I get this error and how I can overcome this. This only appears when fitting the Frank copula - other copulas seem to work.
> FrankFit = fitCopula(archmCopula("frank"), pseudo)
Error in FUN(X[[i]], ...) : could not find function "safeUroot"
> safeUroot
function (f, interval, ..., lower = min(interval), upper = max(interval),
    f.lower = f(lower, ...), f.upper = f(upper, ...), Sig = NULL,
    check.conv = FALSE, tol = .Machine$double.eps^0.25, maxiter = 1000,
    trace = 0)
{
    if (is.null(Sig) && f.lower * f.upper > 0 || is.numeric(Sig) &&
        (Sig * f.lower > 0 || Sig * f.upper < 0)) {
        if (trace)
            cat(sprintf("search in [%g,%g]%s", lower, upper,
                if (trace >= 2)
                  "\n"
                else " ... "))
        Delta <- function(u) 0.01 * pmax(1e-07, abs(u))
        if (is.null(Sig)) {
            delta <- Delta(c(lower, upper))
            while (isTRUE(f.lower * f.upper > 0) && any(iF <- is.finite(c(lower,
                upper)))) {
                if (iF[1])
                  f.lower <- f(lower <- lower - delta[1])
                if (iF[2])
                  f.upper <- f(upper <- upper + delta[2])
                if (trace >= 2)
                  cat(sprintf(" .. modified lower,upper: (%15g,%15g)\n",
                    lower, upper))
                delta <- 2 * delta
            }
        }
        else {
            delta <- Delta(lower)
            while (isTRUE(Sig * f.lower > 0)) {
                f.lower <- f(lower <- lower - delta)
                if (trace)
                  cat(sprintf(" .. modified lower: %g\n", lower))
                delta <- 2 * delta
            }
            delta <- Delta(upper)
            while (isTRUE(Sig * f.upper < 0)) {
                f.upper <- f(upper <- upper + delta)
                if (trace)
                  cat(sprintf(" .. modified upper: %g\n", upper))
                delta <- 2 * delta
            }
        }
        if (trace && trace < 2)
            cat(sprintf("extended to [%g, %g]\n", lower, upper))
    }
    if (!isTRUE(f.lower * f.upper <= 0))
        stop("did not succeed extending the interval endpoints for f(lower) * f(upper) <= 0")
    if (check.conv) {
        r <- tryCatch(uniroot(f, ..., lower = lower, upper = upper,
            f.lower = f.lower, f.upper = f.upper, tol = tol,
            maxiter = maxiter), warning = function(w) w)
        if (inherits(r, "warning"))
            stop("convergence problem in zero finding: ", r$message)
        else r
    }
    else uniroot(f, ..., lower = lower, upper = upper, f.lower = f.lower,
        f.upper = f.upper, tol = tol, maxiter = maxiter)
}
<bytecode: 0x000000004464ff18>
<environment: namespace:copula>
>

As mentioned, this has worked many times before, but stopped working today.


text:
Q: JPQL - filter based on last updated timestamp attribute inside @ElementCollection elements I have @Entity-s (Order) that may change their state. Each state-change is represented with an @Embeddable object (OrderUpdate), added to an @ElementCollection (Order.updates). How can I query Orders based on the most recent update?
My goal is to select those Orders, where the last update's state is DONE.
Order:
@Entity
public class Order {

    @Id
    @GeneratedValue
    private UUID id;

    @ElementCollection
    private List<OrderUpdate> updates;
    ...

OrderUpdate:
@Embeddable
public class OrderUpdate {

    @ManyToOne
    private User host;

    private String state;

    @CreationTimestamp
    private Timestamp timestamp;
    ...

OrderRepository:
@Repository
public interface OrderRepository extends CrudRepository<Order, UUID> {

    @Query("select o from Order o where [o.updates.last.state TODO] = DONE")
    Set<Order> findDone();

}

A: @Query("select o from Order o inner join o.updates u where u.state = ''DONE'' and u.timestamp = (select max(u2.timestamp) from Order o2 inner join o2.updates u2 where o2.id = o.id))  If I understand correclty


text:
Q: Parameter and Functions in Bash Trying to get a function to work called grepme (in a script). its suppose to take 2 parameters that do the following:
a. Parameter 1 will specify the full path to the file you want to search
b. Parameter 2 will specify the text you would like to search for.
When I run this script nothing happens still new to scripting
#!/bin/bash
function grepme {
grep $1 $2
}

grepme "/home/user/testfile"
grepme "TEXT"


text:
Q: Equality of two complex expressions for $\log\dfrac{1+iz}{1-iz}$ I am considering the complex expression:
$w=\log\dfrac{1+iz}{1-iz}$
where $z=x+iy$
On substitution $z=x+iy$ in above expression, I got:
$w=\log\dfrac{1+i(x+iy)}{1-i(x+iy)}$
$=\log\dfrac{(1-y)+ix}{(1+y)-ix}........(*)$
Now there are two ways in which one can proceed. For first one I attempted the following:
$w=\log((1-y)+ix)-\log((1+y)-ix))$
Now using the identity $\log(x+iy)= \log(\sqrt{x^2+y^2})+i\tan^{-1}\dfrac{y}{x}$
Next,
$w=\dfrac{1}{2}(\log((1-y)^2+x^2)-\log((1+y)^2+x^2)))+i(\tan^{-1}\dfrac{x}{1-y}-\tan^{-1}\dfrac{-x}{1+y})$
$=\dfrac{1}{2}(\log\dfrac{(1-y)^2+x^2}{(1+y)^2+x^2})+i\tan^{-1}(\dfrac{2x}{1-x^2-y^2}). ..........(1)$
For the second way, I rationalized the denominator of expression given by $...(*)$ and got the following:
$w=\log\dfrac{(1-y)+ix}{(1+y)-ix}*\dfrac{(1+y)+ix}{(1+y)+ix}$
$=\log\dfrac{(1-x^2-y^2)+i(2x)}{(1+y)^2+x^2}$
$=\log\dfrac{\sqrt{(1-x^2-y^2)^2+4x^2}}{(1+y)^2+x^2}+i\tan^{-1}\dfrac{2x}{1-x^2-y^2}.......(2)$
The two expressions given by equations $....(1)$ and $...(2)$ must be equal but they are not. Their real parts do not match. Why are the two expressions not equal?

A: Since $z\ne \pm i,$ \begin{align}
& \frac12\log\frac{(1-y)^2+x^2}{(1+y)^2+x^2} = \log\frac{\sqrt{(1-x^2-y^2)^2+4x^2}}{(1+y)^2+x^2}
\\\iff{}& \sqrt{\frac{(1-y)^2+x^2}{(1+y)^2+x^2}} = \frac{\sqrt{(1-x^2-y^2)^2+4x^2}}{(1+y)^2+x^2}
\\\iff{}& \sqrt{(1-y)^2+x^2}\;\left((1+y)^2+x^2\right)  = \sqrt{(1+y)^2+x^2}\sqrt{(1-x^2-y^2)^2+4x^2}
\\\iff{}& \left((1-y)^2+x^2\right)\; \left((1+y)^2+x^2\right)^2 = \left((1+y)^2+x^2\right)\;\left((1-x^2-y^2)^2+4x^2\right)
\\\iff{}& \text{True}.
\end{align}
Btw,

using the identity $\log(x+iy)= \log(\sqrt{x^2+y^2})+i\tan^{-1}\dfrac{y}{x}$

is false: \begin{align}\operatorname{Log}(-1-i)-\operatorname{Log}\sqrt{(-1)^2+(-1)^2} &=-\dfrac{3\pi}4 i\\&\ne i\arctan\dfrac{-1}{-1}.\end{align}


text:
Q: Should I learn Classical Physics if I want to learn Quantum Physics? I don't remember anything from school, so please what do you say about the title?

A: You need at least a rudimentary understanding of classical physics in order to even understand why quantum physics is useful/important.  That being said, you can learn them both at the same time.
If you are interested in physics, pick up whatever book interests you the most and start learning.  When you run into concepts from other areas of physics that are necessary, you will have to take a break in order to learn them.  Don't get discouraged along the way; learning physics takes a lot of effort and dedication, but the payoff is well worth it!


text:
Q: Curly Braces with {} grep and regular expressions: Why does it exceed the maximum value? I've been self-studying shell scripting for a while now, and I came across this section of a Linux Fundamentals manual concerning grep and curly braces {}. My problem is that when I'm demanding a string pattern to search for using grep from a minimum to a maximum number of occurrences using {} or curly braces, my result exceeds the maximum that I specified.
Here is what happened:
Express11:~/unix_training/reg_ex # cat reg_file2
ll
lol
lool
loool
loooose
Express11:~/unix_training/reg_ex # grep -E 'o{2,3}' reg_file2
lool
loool
loooose
Express11:~/unix_training/reg_ex #

When according to the manual, should not be the case as I am specifying here that I am only looking for strings containing two consecutive o's to three consecutive o's.
EDIT: Actually, the reason why I did not understand how the curly braces worked was because of this simplistic explanation by the manual. And I quote:

19.4.10. between n and m times
  And here we demand exactly from minimum 2 to maximum 3 times.
paul@debian7:~$ cat list2
ll
lol
lool
loool
paul@debian7:~$ grep -E 'o{2,3}' list2
lool
loool
paul@debian7:~$ grep 'o\{2,3\}' list2
lool
loool
paul@debian7:~$ cat list2 | sed 's/o\{2,3\}/A/'
ll
lol
lAl
lAl
paul@debian7:~$

Thanks to all those who replied.

A: # grep -E 'o{2,3}' reg_file2
lool
loool
loooose

Command works perfectly, that it matches the first three o's in the last line. That's why you get also last line in the final output.
I think the command you're actually looking for is,
$ grep -P '(?<!o)o{2,3}(?!o)' file
lool
loool

Explanation:

*

*(?<!o) negative lookbehind which asserts that the match won't be preceded by the letter o.

*o{2,3} Matches 2 or 3 o's.

*(?!o) Negative lookahead which asserts that the match won't be followed by the letter o.
OR
$ grep -E '(^|[^o])o{2,3}($|[^o])' file
lool
loool

Explanation:

*

*(^|[^o]) Matches the start of a line ^ or any character but not of o

*o{2,3} Matches 2 or 3 o's

*($|[^o]) Matches the end of the line $ or any character but not of o

A: You are not clear with how regex works.
The pattern o{2,3} in grep will go through each line looking for oo and ooo, As long as there is a match, Grep will get you that line. Since you didn't add other rules in your pattern, What you get from grep -E 'o{2,3}' reg_file2 is correct.
I guess in your case you only want a two or three consecutive letter 'o's, Thus you will need to use regex like what Raj answesed. Matching oo or ooo which is neither following nor followed by the letter 'o'.


text:
Q: Can I delete flashlogs.txt? As a ActionScript3 developer I must use debugging tools to trace output to the console. I stumbled across a file that is used with debugging called flashlogs.txt. Can I delete this file? It is located in the users/user/library/preferences/macromedia/flashplayer/logs/ directory?

A: Yes, you can, next time FlashRuntime will create it again if you have ErrorReportingEnable=1 in your mm.cfg.
You can also change file location and change mode for log write PolicyFileLogAppend = 0|1.
For more info check out that doc http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-7fc9.html


text:
Q: Can't link button to modal window I am following along with the answer to this question: Modal window in Jinja2 template. Flask
I've made the following snippet in page.html:
<button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="placeholder-id">Test Modal</button>

        <button type="button" class="close" data-dismiss="modal">×</button>

Modal Title

Modal Stuff

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

The button shows up, but nothing happens when I click it. I can't tell if I'm just supposed to make data-target match id or if I need to do something else.
Alternately, this is just an intermediate step so I can understand the basics of how it's supposed to work.  What I ultimately want to do is separate this out, so that clicking the button allows me to load a blueprint in python to make a modal window pop up.
What I would like is to have something like:
in page.html:

<button something="{{ url_for('sandbox/some_path') }}">Test Modal</button>

in sandbox.py:
@bp.route('/some_path')
def dosomethingwithmodal():
    data = None
    return render_template('generate_modal.html', data=data)

and finally in generate_modal.html:

        <button type="button" class="close" data-dismiss="modal">×</button>

Modal Title

Modal Stuff

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

What do I need to do to alter this pattern to make it work?

A: Your problem is in your button that leads to the modal in page.html. You have:
<button ... data-target="placeholder-id">Test Modal</button>

But it should be:
<button ... data-target="#placeholder-id">Test Modal</button>

The # is needed to correctly point to the modal.


text:
Q: Binomial expansion manipulation Can someone help me manipulate the following binomial expansion such that I can pull a factor of $z$ out of $$\sum_{j=0}^k \binom{k}{j} (-1)^j x^{k-j} \left( y^j - \sum_{i=0}^j \binom{j}{i} y^{j-i} z^i \right)$$
If you put this into Wolfram, every factor has a $z$ in it, but I can't figure out how to manipulate the above expression such that I can write $$z \left( \sum_{j=0}^k \cdots \right)$$

A: \begin{align}
&\;\sum_{j=0}^k \binom{k}{j} (-1)^j x^{k-j} \left( y^j - \sum_{i=0}^j \binom{j}{i} y^{j-i} z^i \right)\\
=&\;\sum_{j=0}^k \binom{k}{j}  x^{k-j}(-y)^j  - \sum_{j=0}^k\binom{k}{j} (-1)^j x^{k-j}\sum_{i=0}^j \binom{j}{i} y^{j-i} z^i \\
=&\;(x-y)^k  - \sum_{j=0}^k\binom{k}{j} (-1)^j x^{k-j}(y+z)^j \\
=&\;(x-y)^k  - \sum_{j=0}^k\binom{k}{j}  x^{k-j}(-y-z)^j \\
=&\;(x-y)^k  - (x-y-z)^k \\
\end{align}
If you want to pull out a factor of $z$,
\begin{align}
&\;(x-y)^k  - (x-y-z)^k \\
=&\;(x-y)^k -\sum_{j=0}^k \binom{k}{j} ( x-y)^{k-j}(-z)^j \\
=&\;(x-y)^k - ( x-y)^{k}-\sum_{j=1}^k \binom{k}{j} ( x-y)^{k-j}(-z)^j \\
=&\;z\sum_{j=1}^k \binom{k}{j} ( x-y)^{k-j}(-z)^{j-1}
\end{align}

A: If the main focus is factoring out $z$ only, note the summand of the inner sum with $i=0$ is equal to $y^j$.

So, $y^j$ cancels out and we obtain
  \begin{align*}
\sum_{j=0}^k& \binom{k}{j} (-1)^j x^{k-j} \left( y^j - \sum_{i=0}^j \binom{j}{i} y^{j-i} z^i \right)\\
&=\sum_{j=0}^k \binom{k}{j} (-1)^{j+1} x^{k-j}\sum_{i=1}^j \binom{j}{i} y^{j-i} z^i\\
&=z\left(\sum_{j=0}^k \binom{k}{j} (-1)^{j+1} x^{k-j}\sum_{i=1}^j \binom{j}{i} y^{j-i} z^{i-1}\right)\\
&=zP(x,y,z)
\end{align*}
  with $P(x,y,z)$ a polynomial in $x,y$ and $z$.


text:
Q: Problem with adding an item to an array of mongoose reference objects In my NodeJS and MongoDB app, I have 2 mongoose schemas:
companySchema:
const companySchema = new Schema({
  name: {
    type: String,
    required: true
  },
  products: [{
      type: Schema.Types.ObjectId,
      ref: 'Product',
      required: false
  }]
});

companySchema.statics.addProduct = function (productId) {
  let updatedProducts = [...this.products];
  updatedProducts.push(productId);
  this.products = updatedProducts;
  return this.save();
}

module.exports = mongoose.model('Company', companySchema);

productSchema:
const productSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  quantity: {
    type: Number,
    required: true
  }
});

module.exports = mongoose.model('Product', productSchema);

Every time I add a new product to productSchema, I would like to add the _id of the newly created product to products array in companySchema in order to easily access products later on.
To accomplish this, I wrote:
const Company = require('../models/company');
const Product = require('../models/product ');

exports.postAddProduct = (req, res, next) => {
  const name = req.body.name;
  const quantity = req.body.quantity;

  const product = new Product({
    name: name,
    quantity: quantity
  });
  product.save()
    .then(product => {
      return Company.addProduct(product._id);
    })
    .then(result => {
      res.redirect('/');
    })
    .catch(err => console.log(err));
}

I am getting an error:  TypeError: this.products is not iterable.

A: You are setting a static method, which is a method on the model rather than the document instance.
Therefore, this refers to the model itself, not the individual document.
Unlike the document, the model doesn't have an array (iterable) called products so it can't be spread into a new array.
Try using methods instead of statics:
companySchema.methods.addProduct = function (productId) {
  ...
}

I hope this helps.


text:
Q: Postgres: Finding max value in an int array? using Postgres 9.3...
Can someone please explain why I can't use a max function directly on an unnested array..?
It is my understanding the unnest function returns a "setof" just like the select statement.  So why does the short version of this query not work?  (Am I missing something conceptually or is my issue a syntax related one?)
table: foo_history:

id | history::smallint
-----------------------------------
1  |  {10,20,30,50,40}

This doesn't work ?
Select id, max(unnest(history)) as vMax from foo_history;

...but this one does...?
WITH foo as (
    select id, unnest(history) as history
    from foo_history
)
Select
    id, max(history) as vMax
From foo
Group by id;

A: If you install the intarray module it provides some extra array operators that'll let you write what you want, albeit somewhat inefficiently:
CREATE EXTENSION intarray;

SELECT id, (sort_desc(history))[1] as vMax
FROM foo_history;

It would be pretty easy to write greatest and least functions for arrays to add to intarray, the code is pretty simple.
Otherwise you can just write an SQL function:
CREATE OR REPLACE FUNCTION array_greatest(anyarray)
RETURNS anyelement
LANGUAGE SQL
AS $$
  SELECT max(elements) FROM unnest($1) elements
$$;

and use that:
SELECT id, array_greatest(history) as vMax
FROM foo_history;

A: in PostgreSQL 9.6 and 8.4:
SELECT max(x) FROM unnest(ARRAY[1,2,80,3,15,4]) as x;

A: You must remember that SQL is designed to operate on sets of data.  The MAX function actually does work in the first example, it just doesn't work as you are expecting it to.  It will return the maximum value for each row that matches.
The group by clause works as expected because you are now aggregating into a set and then getting the maximum from the set. :)

A: That work for me
select *,
(SELECT max(a) from unnest(ARRAY[1,2,80,3,15,4]) a ) as mx,
 from table

this find max in array


text:
Q: Compiler is out of heap space I am trying to port a plugin written in C++ which actually does a lot of stuff, so there are lots of classes and ofcourse a lot of code as well!
But when I try to compile the plugin, the compiler throws the following error: fatal error C1060: compiler is out of heap space. If I check my task manager it shows that there is quite some space left on the memory. I even tried restarting.
I tried the usual answers on the internet on memory allocation limit and on stack overflow previously asked questions as well. None of them have seemed to work for me, hence I am here.
A few things that might be important. The plugin is extensively using the following libraries:
FreeImage &
protobuf-2.4.1
p.s. I compiled the source code using VS2012 compiler.
Using a 64-bit machine
the error shows up in the second line of this code:
#if GOOGLE_PROTOBUF_VERSION < 2004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please update
#error your headers.
#endif
#if 2004001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please
#error regenerate this file with a newer version of protoc.
#endif

I am lost, could anyone point me in the right direction? Thanks alot!

A: I had the same problem with VC++ 2015 latest update (Update 3).  Eventually I worked out that turning off pre-compiled headers avoids the problem.
This was a small project so the difference in build time was minor for us. If you have a large project and must use pre-compiled headers maybe you can try removing some of them.

A: So there were 2 work-arounds for that.
Firstly, I could just simply comment out the provided header descriptions, and that seemed to work magically.
Second, since, the first option did not sound very appropriate, I just recompiled the whole library, and it worked. I am guessing, it was a compiler version mismatch or something. But that seems to work fine..


text:
Q: How to compare two columns and find differences in Excel? I have two columns in Excel that I want to compare and find the differences between them.
Suppose:

*

*Col A has 50 numbers, i.e. 0511234567

*Col B has 100 numbers in the same format

A: Using Conditional Formatting
Highlight column A. Click Conditional Formatting > Create New Rule > Use this formula to determine which cells to format > Enter the ff. formula:
=countif($B:$B, $A1)

Click the Format button and change the Font color to something you like.
Repeat the same for column B, except use this formula and try another font color.
=countif($A:$A, $B1)

Using a Separate Column
In column C, enter the ff. formula into the first cell and then copy it down.
=if(countif($B:$B, $A1)<>0, "-", "Not in B")

In column D, enter the ff. formula into the first cell and then copy it down.
=if(countif($A:$A, $B1)<>0, "-", "Not in A")

Both of these should help you visualize which items are missing from the other column.

A: If I understand your question well:
=if(Ax = Bx; True_directive ; False_directive)

Replace True/false directives by a function or by a string like "Equal" or "different".

A: Say you want to find those in col. B with no match in col. A. Put in C2:
=COUNTIF($A$2:$A$26;B2)

This will give you 1 (or more) if there's a match, 0 otherwise.
You can also sort both columns individually, then select both, Goto Special, select Row Differences. But that will stop working after the first new item, and you will have to insert a cell then start again.

A: It depends on the format of your cells and your functional requirements. With a leading "0" they could be formatted as text.
Then you could use IF function to compare cells in Excel:
=IF ( logical_test, value_if_true, value_if_false )

Example:
=IF ( A1<>A2, "not equal", "equal" )

If they are formatted as numbers, you could subtract the first column from the other in order to get the difference:
=A1-A2

A: This formula will directly compare two cells. If they are the same, it will print True, if one difference exists, it will print False. This formula will not print what the differences are.
=IF(A1=B1,"True","False")

A: Microsoft has an article detailing how to find duplicates in two columns. It can be changed easily enough to find unique items in each column.
For example if you want Col C to show entries unique to Col A, and Col D to show entries unique to Col B:
A   B   C                                          D
1   3   =IF(ISERROR(MATCH(A1,$B$1:$B$5,0)),A1,"")  =IF(ISERROR(MATCH(B1,$A$1:$A$5,0)),B1,"")
2   5   (fill down)                                (fill down)
3   8   ..                                         ..
4   2   ..                                         ..
5   0   ..                                         ..

A: Here's the formula that you are looking for:
=IF(ISERROR(NOT(MATCH(A1,$B$1:$B$11,0))),A1,"")

Source: Excel: Find differences between two columns

A: I'm using Excel 2010 and just highlight the two columns that have the two sets of values I'm comparing, and then click the Conditional formatting dropdown on the home page of Excel, choose the Highlight Cells rules, and then differences. It then prompts to highlight either differences or similarities and asks what colour highlight you want to use...

A: The comparing can be done with Excel VBA code. The compare process can be made with the Excel VBA Worksheet.Countif function.
Two columns on different worksheets were compared in this template. It found different results as an entire row was copied to the second worksheet.
Code:
Dim stk, msb As Worksheet
Set stk = Sheets("Page1")
Set msb = Sheets("Page2")

Application.ScreenUpdating = False
sat = (msb.Range("A" & Rows.Count).End(xlUp).Row) + 1
For i = 2 To stk.Range("A" & Rows.Count).End(xlUp).Row
    If WorksheetFunction.CountIf(msb.Range("A2:A" & msb.Range("A" & Rows.Count).End(xlUp).Row), stk.Cells(i, "A")) = 0 Then
        msb.Range("a" & sat).EntireRow.Value = stk.Range("a" & i).EntireRow.Value
        msb.Range("a" & sat).Interior.ColorIndex = 22
        sat = sat + 1
    End If
Next
...

The tutorial's video: https://www.youtube.com/watch?v=Vt4_hEPsKt8
Example file can be downloaded here

A: This is using another tool but I've just found this very easy to do.
Using Notepad++:
In Excel make sure your 2 columns are sorted in the same order, then copy and paste your columns into 2 new text files and then run a compare (from plugins menu).

A: The NOT MATCH function combination works well. The following works too:
=IF(ISERROR(VLOOKUP(<<item in larger list>>,<<smaler list>>,1,FALSE)),<<item in larger list>>,"")
REMEMBER: the smaller list MUST be SORTED ASCENDING - a requirement of vlookup