text:
Q: AngularJS - cannot reference $index inside ng-model using a directive I am currently facing an issue whereby I would like to generate a dynamic number of input forms and also name them dynamically (as defined by a JSON) so that I can reference them separately.
For example, if my JSON object had three items in it, I would generate three input boxes with ng-model="1", ng-model="2" and ng-model="3" respectively. In real life the ID's will come from the JSON itself.
I'm currently using ng-repeat to generate the forms in a table;

{{ $index }}
{{ x.Description }}
{{ x.Metric }}

And using a directive & the $compile function to dynamically generate an input form with a unique ng-model name.
app.directive("outDynamic", function($compile){
return{
    link: function(scope, element, attrs){
        var template = "<input type='number' ng-model='" + scope.ray[attrs.element1] + "'>";
        var linkFn = $compile(template);
        var content = linkFn(scope);
        element.append(content);
    }
} });

However: none of the following works (when nested in the ng-repeat)

 <input type='number' ng-model="array[$index]">
 <input type='number' ng-model="array['$index']">

Summary of issue;

Every time I try and reference the $index tracker, I get an
  undefined error in my directive code.

A: You should use {{}} to assign $index value for attribute. so use
element1={{$index}} instead of element1=$index

I guess your scope.arr is perfect.
PLUNKER DEMO


text:
Q: warning about pdfpages with hyperref Package pageslts prints out this warning since I use pdfpages and hyperref in the same document.

Package pageslts Warning: Package pdfpages detected.
  (pageslts)                Using hyperref with pdfpages can cause problems. See
  (pageslts)                ftp://ftp.ctan.org/tex-archive/
  (pageslts)                macros/latex/contrib/pax/
  (pageslts)                for project pax (PDFAnnotExtractor)..

What does this mean?
Am I supposed to change anything in the document or when am I going to see any problem?

A: I really don't know why pageslts issues this warning, as the problem doesn't seem to concern it.
It's a fact that PDF included partially or totally via pdfpages's \includepdf but also with the standard \includegraphics command lose their hyperlinks, but this has nothing to do with having loaded hyperref (of course, without it there will be no link whatsoever).
A partial solution to the "lost links" is provided by Heiko Oberdiek's project PAX (PDFAnnotExtractor) with the script pdfannotextractor and related programs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ERROR in NaN but they point to different modules. ... Webpack cannot distinguish on context and would fail to load the proper one ERROR in NaNbut they point to different modules "(/Users/USER/eclipse-workspace/nms/bin/main/webapp/app/admin/admin.module.ts and "/Users/USER/eclipse-workspace/nms/src/main/webapp/app/admin/admin.module.ts"). Webpack cannot distinguish on context and would fail to load the proper one.
I have done ./gradlew -Pprod
And with ./gradlew -Pprod --debug --info --scan --stacktrace
Gives this error: https://scans.gradle.com/s/czc6mol6ipsg6
Works well with ./gradlew
and
./gradlew -Pdev bootWar
node version v10.13.0
jhipster version
Using JHipster version installed locally in current project's node_modules
5.6.1
yarn --version
1.12.3
MacOS 10.12.6
Any Suggestion ?

A: I got similar error after upgrading JHipster from 5.7.2 to 5.8.2
Finally I deleted ./bin/ folder and it resolve the problem.

A: I was face same problem on my application and Finally I got a solution from Github issue in angular-cli Project. It's working fine for me. Working code:
export const ROUTES: Routes = [
     {
         loadChildren: "../<whatever the folder name of parent module>/admin/admin.module#AdminModule",
         path: "admin",
     },
];


text:
Q: How to align RGB and Depth image from Kinect in Matlab I am trying to align RGB and Depth image from Kinect using Matlab. I am trying to do it using the algorithm from this page.
Here is the code I have written so far
depth = imread('depth_00500.png');
color = imread('rgb_00500.png');

rotationMat=[9.9984628826577793e-01 1.2635359098409581e-03 -1.7487233004436643e-02;
 -1.4779096108364480e-03 9.9992385683542895e-01 -1.2251380107679535e-02;
1.7470421412464927e-02 1.2275341476520762e-02 9.9977202419716948e-01 ];

 translationMat=[1.9985242312092553e-02, -7.4423738761617583e-04, -1.0916736334336222e-02 ];

%parameters for color matrix
fx_rgb= 5.2921508098293293e+02;
fy_rgb= 5.2556393630057437e+02;
cx_rgb= 3.2894272028759258e+02;
cy_rgb= 2.6748068171871557e+02;
k1_rgb= 2.6451622333009589e-01;
k2_rgb= -8.3990749424620825e-01;
p1_rgb= -1.9922302173693159e-03;
p2_rgb= 1.4371995932897616e-03;
k3_rgb= 9.1192465078713847e-01;

%parameters for depth matrix
fx_d= 5.9421434211923247e+02;
fy_d= 5.9104053696870778e+02;
cx_d= 3.3930780975300314e+02;
cy_d= 2.4273913761751615e+02;
k1_d= -2.6386489753128833e-01;
k2_d =9.9966832163729757e-01;
p1_d =-7.6275862143610667e-04;
p2_d =5.0350940090814270e-03;
k3_d =-1.3053628089976321e+00;

row_num=480;
col_num=640;

for row=1:row_num
    for col=1:col_num

pixel3D(row,col,1) = (row - cx_d) * depth(row,col) / fx_d;
pixel3D(row,col,2) = (col - cy_d) * depth(row,col) / fy_d;
pixel3D(row,col,3) = depth(row,col);

    end
end

pixel3D(:,:,1)=rotationMat*pixel3D(:,:,1)+translationMat;
pixel3D(:,:,2)=rotationMat*pixel3D(:,:,2)+translationMat;
pixel3D(:,:,3)=rotationMat*pixel3D(:,:,3)+translationMat;

P2Drgb_x = fx_rgb*pixel3D(:,:,1)/pixel3D(:,:,3)+cx_rgb;
P2Drgb_y = fy_rgb*pixel3D(:,:,2)/pixel3D(:,:,3)+cy_rgb;

I am especially failing to understand why we're assigning value of depth pixel to dimension x,y and z of 3-dimensional space, shouldn't we assign (x,y,z) dimension to the depth pixel value?
I mean this part:
P3D.x = (x_d - cx_d) * depth(x_d,y_d) / fx_d
P3D.y = (y_d - cy_d) * depth(x_d,y_d) / fy_d
P3D.z = depth(x_d,y_d)

Also I'm not sure If I can represent 3d space using matrix. I am trying to use it in my code but for sure it has wrong size as multiplication by 3x3 rotation matrix is impossible.
Thank you for very much for every suggestion and help!

A: This is a quite complex topic to explain in a short answer. As per me, the code is correct. Please read about intrinsic and extrinsic camera matrices. And reading about perspective projection will also help you to understand 2D to 3D projection.
P3D.x = (x_d - cx_d) * depth(x_d,y_d) / fx_d

In above line, depth(x_d, y_d) gives you the depth value at a pixel from the depth image. Then it is multiplied by the (x_d - cx_d), which is the difference along x-axis with the x coordinate of the centre point of depth map to the current pixel. Then finally this is divided by the fx_d, which is the focal length of the depth camera.
Following two references will help you to understand this mathematically well if you are interested in.

*

*Mueller, K., Smolic, A., Dix, K., Merkle, P., Kauff, P., & Wiegand, T. (2008). View synthesis for advanced 3D video systems. EURASIP Journal on Image and Video Processing, 2008(1), 1-11.

*Daribo, I., & Saito, H. (2011). A novel inpainting-based layered depth video for 3DTV. Broadcasting, IEEE Transactions on, 57(2), 533-541.


text:
Q: Event data, sent from via Google Tag Manager, not visible in Google Bigquery I created some usual events in Google Tag Manager: Category, Action Label. I see them in Google Analytics Reports, but I don't see them in row Google Bigquery Streaming.
Here is an event in Tag Manager

I see it in Google Analytics Row

But nothing in Big Query

Has anybody met this problem? I have found absolutely nothing anywhere (but maybe I queried Google Search incorrectly).
Please help.

A: To avoid errors while exporting data from GA to BigQuery you need to verify the following as described in Google official documentation
Avoiding export failures

Failure to complete and maintain each of the following items can temporarily disable your account and cause daily BigQuery Exports from Analytics to fail. Keep in mind that we cannot reprocess failed exports that are caused by your failure to complete or maintain each of the following.
Make sure the service account has the necessary permissions
If at any point the service account (analytics-processing-dev@system.gserviceaccount.com) does not have EDIT access to the project, then data won't be exported.
  Ensure that billing is enabled.
  If you created your BigQuery account using the free-trial option, make sure you upgrade to a paid account before the trial ends.
  You can use a backup credit card to further avoid billing interruptions.
  If you prefer to use Invoices instead of paying for Google Cloud using credit cards, contact Google Cloud Sales to discuss payment options.
  Ensure that the BigQuery API is enabled.
In Google Cloud Platform > your project > APIs & Services > Dashboard, make sure the BigQuery API is enabled.

If from your side everything is setup correctly I suggest you ask Analytics 360 support for additional help


text:
Q: Who, if anybody, can see grace period edit history? I recently made a post with an image in it that had some mildly sensitive information that I forgot to blur out.
I edited the image, then edited the post and replaced it. I managed to do it during the grace period, so plebs such as myself aren't able to go back and look. I'm satisfied with that.
But I'm wondering, mostly out of curiosity, who can see grace period edit histories? Site mods? Community mods? Employees? Special employees? Joel? Shog9 through his top secret backdoor that I promised him I'd never mention in public?

A: It's not stored in a database, but I wouldn't be surprised if it is still logged:

*

*Log all your inbound traffic. We keep logs on all in-bound connections. This enabled all of our investigations. You can't investigate what you don't log.

Whether they rely on standard IIS logs (which log URLs and some headers) or log POST bodies as well, I can't tell.
Also, one of the community projects out there may have noticed your new post through one of the websockets and retrieved the initial version through e.g. the API. Now and then, we see a post in Metasmoke which seems gibberish, but on the site it looks normal. (Or the other way around.) In those cases, the author edited the post during the grace period, but the original version is still archived somewhere.
What @rene says in the comments about the image being on imgur's servers is also true; the IDs are fairly random but it's plausible somebody accidentally stumbles on the image. I'm not sure if images from i.stack.imgur.com are shown on the Newest feed but haven't we all tried putting random characters in the URL and see what we get?


text:
Q: Do we must make a complex query in PySpark or a simple, and use .filter / .select? I have a question. Suppose I run a python script on the server where my data are stored. What is the faster way to have a spark dataframe of my data between :

*

*Make a complex query with lot of conditions but it return me the exact dataframe I need or

*Make a simple query and make the dataframe I need with .filter / .select

You can also suppose that the dataframe I need is small enough to fit on my RAM.
Thanks

A: IIUC, everything depends on from where you are reading the data, So here are some scenarios
DataSource: RDBMS(oracle, postgres, mysql....)
If you want to read data from RDBMS system then you have to establish a JDBC connection to the database then fetch the results.
Now remember spark is slow when fetching data from relational databases over JDBC and it is recommended you filter most of your records on database side itself as it will allow the minimum data to be transferred over the network
You can control the read speed using some tuning parameters but it is still slow.
DataSource: Redshift, Snowflake
In this scenario if your cluster is large and relatively free then pushdown the query to the cluster itself or if you want to read data using JDBC then it is also fast as BTS it unloads the data to a temp location and then spark reads it as file source.
DataSource: Files
Always try to pushdown the filter as they are there for a reason, so that your cluster needs to do the minimum work as you are reading only the required data.
Bottom line is that you should always try to pushdown the filters on the source to make your spark jobs faster.

A: The key points to mind is

*

*Restrict/filter data to maximum possible level while loading into dataframe, so as only needed data resides in dataframe
for non file sources: filtering data at source by using native filter and fetching only needed columns (aim for minimum data transfer).
for file sources: restricting/modifying data in file source is not feasible. so the first operation is to filter data once loaded

*In complex operations first perform narrow transformations (filters, selecting only needed columns) and then perform wide transformations(joins, ordering) which involves shuffle towards the end, so that less data will be shuffled between worker nodes.
The less the shuffles the faster your end dataframe would be.

A: First of all I think we should be careful when dealing with small data in our Spark programs. It was designed to give you parallel processing for big data.
Second, we have something like Catalyst query optimizer and lazy evaluation, which is a good tool for Spark to optimize everything what was put either in SQL query or API call transformations.


text:
Q: Exclude measurements using regex in influxql I have an influxql query used in grafana as follows:
SELECT mean("value") FROM /^concourse\.(worker*|web*).*\.system_mem_percent$/ WHERE $timeFilter GROUP BY time($__interval), * fill(null)

This works as expected, I get only the results of measurements with worker... or web... in it.
I'm trying to now build the inverse query of this. I.E all measurements that do not have worker... or web... in it.
I'll need to be able to do this with regex on measurements itself. (Assume no tags)
How could this be achieved in influxql (influxdb 1.7).

A: It looks like you need negative lookahead in your regexp. But InfluxDB uses Golang's regular expression syntax, where negative lookahead is not supported.
You may use workaround with more complicated regexp with negated character classes - see Negative look-ahead in Go regular expressions
But I would go with better InfluxDB design and I would use tags. It is also recommended approach https://docs.influxdata.com/influxdb/v1.8/concepts/schema_and_data_layout/#avoid-encoding-data-in-measurement-names


text:
Q: Reshape (Melt?) data whilst combining columns with Python Pandas I have the below dataframe:
df = pd.DataFrame({'Date':['01/01/2021','08/01/2021'],
                  'a_score':[7,3],
                  'b_score':[2,4],
                  'a':['north','south'],
                  'b':['south','north']})

Date        a_score b_score a       b
01/01/2021  7       2       north   south
08/01/2021  3       4       south   north

How can I best reshape this to stack the data in columns a and b together and also stack a_score and b_score together?  The desired output looks like this:
Date        Region  score   score_against
01/01/2021  north   7       2
01/01/2021  south   2       7
08/01/2021  north   4       3
08/01/2021  south   3       4

Many thanks

A: You can take the inner numpy array and manipulate it to get the required result:
import numpy as np
new_df = pd.DataFrame(np.vstack((df.values,df.values[:, [0,2, 1, 4,3]]))[:, :-1], columns = ['Date', 'score', 'score_against', 'Region'])

OUTPUT:
         Date score score_against Region
0  01/01/2021     7             2  north
1  08/01/2021     3             4  south
2  01/01/2021     2             7  south
3  08/01/2021     4             3  north

Explanation:
np.vstack((df.values,df.values[:, [0,2, 1, 4,3]]))[:, :-1]

Take the inner numpy array (df.values) swap the columns and then vertically stack it with the original numpy array:
array([['01/01/2021', 7, 2, 'north'],
       ['08/01/2021', 3, 4, 'south'],
       ['01/01/2021', 2, 7, 'south'],
       ['08/01/2021', 4, 3, 'north']], dtype=object)

Now, you can use the above array to create a new dataframe.
NOTE:
If required -> sort via Date column.
new_df = new_df.sort_values('Date')

OUTPUT:
         Date score score_against Region
0  01/01/2021     7             2  north
2  01/01/2021     2             7  south
1  08/01/2021     3             4  south
3  08/01/2021     4             3  north


text:
Q: Difference between ethernet and TCP/IP protocol in programming? Say ff a socket is open for Ethernet then is it same as socket in TCP/IP ? In some existing code i have found that, it supports Ethernet protocol, does that mean i can connect to this Ethernet socket using TCP socket client.
I am in confusion, please help.
Thanks in advance
Sagar

A: A raw ethernet socket, e.g. SOCK_RAW, cannot be used for TCP communication without you writing the protocol handler (you don't want to do that). You are expected to know how to serialize/deserialize ethernet frames when a socket is opened in raw ethernet mode. SOCK_STREAM is the mode for TCP and the internet is awash with examples of TCP client/server code.

A: There is some confusion. Ethernet is a layer 1 and 2 technology in the OSI model and the TCP/IP model. For communicating directly over 802.3, in Linux you can use packet sockets to directly generate an 802.3 frame and send it out through the NIC. You can also use packets sockets to receive 802.3 frames. Something different is TCP socket, stream sockets. Use stream sockets for a TCP connection. With a packet socket you can always receive a 802.3 frame containing an IP datagram which contains a TCP segment. However, in order to establish a TCP connection you need to have a TCP communication established between two points. If the code you saw says "Ethernet protcol", you should check it is actually doing, it could just be a misconception on the programmer side. Check the type of socket they are using.


text:
Q: Calling Emacs from Java file For vhdl beautifier, I am using Emacs and in Linux I am using the command in terminal:
emacs --batch --visit=FILENAME.vhd --funcall=vhdl-beautify-buffer --funcall=save-buffer

And this working fine, however when trying to call this command within a java file as below not working! :
String command = "emacs --batch --visit=FILENAME.vhd --funcall=vhdl-beautify-buffer --funcall=save-buffer";
Process p = Runtime.getRuntime().exec(command);

what can be causes for that?


text:
Q: How to pass variable around functions within plugin's Observer.php? In my plugin's Model/Observer.php I have 2 functions which are corresponding to 2 different events, but I want to pass a variable from first function to next one. I tried something like this:
class ContactologyProduct_LogProductUpdate_Model_Observer
{

(...)

public function beforeAddressSave(Varien_Event_Observer $observer) {

  $contactologyClientIdBeforeEdit = $this->getCustomerAddress();

  $this->setData('contactologyClientIdBeforeEdit', $contactologyClientIdBeforeEdit);  // won't work

}

public function afterAddressSave(Varien_Event_Observer $observer) {

  $contactologyClientIdAfterEdit = $this->getCustomerAddress();

  $contactologyClientIdBeforeEdit = $this->getData('contactologyClientIdBeforeEdit');  // won't work

  var_dump($contactologyClientIdBeforeEdit); // won't work
  var_dump($contactologyClientIdAfterEdit);

}

}

but setData() doesn't work, I get error:
Call to a member function setData() on a non-object

Which way would be the proper one to save $contactologyClientIdBeforeEdit in beforeAddressSave() function, so that it could be accessed later in afterAddressSave()?

A: public function beforeAddressSave(Varien_Event_Observer $observer) {
   $contactologyClientIdBeforeEdit = $this->getCustomerAddress();
   $this->setData('contactologyClientIdBeforeEdit', $contactologyClientIdBeforeEdit);  // won't work
}

You should use $observer instead of $this, but fist you should look where the event is created, since you can have something like:
$contactologyClientIdBeforeEdit = $observer->getEvent()->getCustomerAddress();

Then you can implement the setData and getData in your class, or have your class extend Varien_Object class.
So, I think you will have:
class ContactologyProduct_LogProductUpdate_Model_Observer extends Varien_Object {
public function beforeAddressSave(Varien_Event_Observer $observer) {
   $contactologyClientIdBeforeEdit = $observer->getCustomerAddress(); //or $observer->getEvent()->getCustomerAddress() look how the event data is set.
   $this->setData('contactologyClientIdBeforeEdit', $contactologyClientIdBeforeEdit);
}
public function afterAddressSave(Varien_Event_Observer $observer) {
   $contactologyClientIdAfterEdit = $observer->getCustomerAddress();
   $contactologyClientIdBeforeEdit = $this->getData('contactologyClientIdBeforeEdit');
}


text:
Q: C OpenMP parallel bubble sort I have an implementation of parallel bubble sort algorithm(Odd-Even transposition sort) in C, using OpenMP. However, after I tested it it's slower than the serial version(by about 10%) although I have a 4 cores processor ( 2 real x 2 because of Intel hyperthreading). I have checked to see if the cores are actually used and I can see them at 100% each when running the program. Therefore I think I did a mistake in the implementation the algorithm.
I am using linux with kernel 2.6.38-8-generic.
This is how I compile:
gcc -o bubble-sort bubble-sort.c -Wall -fopenmp or
gcc -o bubble-sort bubble-sort.c -Wall -fopenmp for the serial version
This is how i run:
./bubble-sort < in_10000 > out_10000
#include <omp.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
        int i, n, tmp, *x, changes;
        int chunk;
        scanf("%d ", &n);
        chunk = n / 4;
        x = (int*) malloc(n * sizeof(int));
        for(i = 0; i < n; ++i)
            scanf("%d ", &x[i]);
    changes = 1;
    int nr = 0;
    while(changes)
    {
    #pragma omp parallel private(tmp)
    {
            nr++;
            changes = 0;
            #pragma omp for \
                    reduction(+:changes)
            for(i = 0; i < n - 1; i = i + 2)
            {
                    if(x[i] > x[i+1] )
                    {
                            tmp = x[i];
                            x[i] = x[i+1];
                            x[i+1] = tmp;
                            ++changes;
                    }
            }
            #pragma omp for \
                    reduction(+:changes)
            for(i = 1; i < n - 1; i = i + 2)
            {
                    if( x[i] > x[i+1] )
                    {
                            tmp = x[i];
                            x[i] = x[i+1];
                            x[i+1] = tmp;
                            ++changes;
                    }
            }
    }
    }

    return 0;
}

Later edit:
It seems to work well now after I made the changes you suggested. It also scales pretty good(I tested on 8 physical cores too -> took 21s for a set of 150k numbers which is far less than on one core). However if I set the OMP_SCHEDULE environment variable myself the performance decreases...

A: You should profile it and check where threads spend time.
One possible reason is that parallel regions are constantly created and destroyed; depending on OpenMP implementation, it could lead to re-creation of the thread pool, though good implementations should probably handle this case.
Some small things to shave off:
- ok seems completely unnecessary, you can just change the loop exit condition to i<n-1;
- explicit barrier is unnecessary - first, you put it out of parallel regions so it makes no sense; and second, OpenMP parallel regions and loops have implicit barriers at the end;
- combine at least the two consequent parallel regions inside the while loop:
#pragma omp parallel private(tmp)
{
    #pragma omp for bla-bla
    for (i=0; i<n-1; i+=2 ) {...}

    #pragma omp for bla-bla
    for (i=1; i<n-1; i+=2 ) {...}
}


text:
Q: Dynamically hiding a section on Wordpress pages I have a floating social bar on my website www.fashionsuggest.in
I only need this social bar on my wordpress posts and would like to to be removed from all pages.
There are only 5 or 6 pages in total. Can someone please suggest a solution to hide the floating social bar on these pages?
Please refer the attachment to see a screenshot of the social bar

A: You can try this CSS code.
.page-template-default .kiwi-floating-bar { display: none; }
.post-template-default .kiwi-floating-bar { display: block; }

try using !important if it doesn't reflect.
.page-template-default .kiwi-floating-bar { display: none !important; }


text:
Q: Slow order confirmation? I have magento version 1.9.2.3 installed and the new order e-mail is delivered late for some unexpected reason. It takes 8-10 min to receive the order e-mail.
I've searched on forum but found nothing.
Anyone has the same issue?

A: From Magento 1.9.1, 'core_email_queue' is added to the database, emails are queued up here and sent via cron instead of directly being sent out. So you're seeing the emails go out when cron is executed.
More info http://jakesharp.co/magento/magento-emails-not-sent/


text:
Q: JavaFX progress bar component activated from Spring Listener Method I have three layer(gui->services->dao) desktop application (JavaFX+Spring 4).
Some of my methods realized in my services layer (without fx dependency) have long time computing. I'd like to report their progress in gui.
But there is a problem. My service layer hasn't got direct access to gui, make a log of IO operations and returns only summarize of it. GUI layer, doesn't know about progress of intermediate operations.
I try to make a generic progress component. It could be realized as a Spring Bean with listener method located id GUI layer. My services can publish ApplicationEvent, which can be received via progress component in gui. When it gets the event, should activate progress bar and report next events.
In init methods I have started ProgressTask, and bind progressProperty with my gui progress bar control.
Call method of my ProgressTask runs while actual counter is less that max number of steps.
There is my component:
@Component
@Controller
public class ProgressBarComponent  {

    @FXML
    private ProgressBar progressBar;

    private ProgressTask actTask;

    @FXML
    public void initialize(){
    }

    private void initProgressBar(int aMax){
        actTask=new ProgressTask();
        actTask.initState(aMax);
        progressBar.progressProperty().bind(actTask.progressProperty());
    new Thread(actTask).start();
    }

    @EventListener
    public void handleProgressEvent(ProgressEvent event) {
        if(event.getGetActStep()==0){
            initProgressBar(event.getMaxStep());
        }
        actTask.changeState(event.getGetActStep());
    }

    class ProgressTask extends Task<Object>{
        private int max=100;
        private int act=0;
        private volatile boolean cancelled;

        public void initState(int aMax){
            this.max=aMax;
        }

        public void changeState(int newVal){
            act=newVal;
            updateProgress(act, max);
            updateMessage("progress: " + act);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new IllegalArgumentException(e);
            }
        }

        @Override
        protected Object call() throws Exception {
            while(act<max){
            }
            return null;
        }

    }

}

But it doesn't work.
Progress bar control is activated but in one step and at once it has a 100 percent value.
I have found a lot of examples Progress Bar FX control, but all of them assume that main logic is computed inside call() method of ProgressTask. In my case it isn't possible.
It is possible to make a ProgressBar Component, which is activated from listener method ? If yes, what code should be in ProgressTask.call() method ?

A: The point of a Task is to define some functionality that should be run on a background thread. So if this functionality is already implemented elsewhere, there is no need for a task.
Assuming the service is being invoked on a background thread (i.e. not on the FX Application Thread), you should just be able to do:
@Component
@Controller
public class ProgressBarComponent  {

    private int max ;

    @FXML
    private ProgressBar progressBar;

    @FXML
    public void initialize(){
    }

    private void initProgressBar(int aMax){
        this.max = aMax ;
    }

    @EventListener
    public void handleProgressEvent(ProgressEvent event) {
        if(event.getGetActStep()==0){
            Platform.runLater(() -> initProgressBar(event.getMaxStep()));
        }
        Platform.runLater(() ->
            progressBar.setProgress(1.0 * event.getGetActStep() / max));
    }
}

Here's a complete SSCCE:
ProgressViewer.java:
package springevent;

import org.springframework.context.event.EventListener;

import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ProgressViewer {

    private Stage stage = new Stage();
    private Scene scene ;
    private ProgressBar progressBar ;

    public ProgressViewer() {
        progressBar = new ProgressBar();
        StackPane root = new StackPane(progressBar);
        root.setPadding(new Insets(20));
        scene = new Scene(root);
        stage.setScene(scene);
    }

    @EventListener
    public void progressUpdate(ProgressEvent event) {
        if (event.getCurrent() < event.getMax()) {
            Platform.runLater(stage::show);
        } else {
            Platform.runLater(stage::hide);
        }
        final double progress = 1.0 * event.getCurrent() / event.getMax() ;
        Platform.runLater(() -> progressBar.setProgress(progress));
    }
}

Service.java:
package springevent;

import javax.inject.Inject;

import org.springframework.context.ApplicationContext;

public class Service {

    @Inject
    private ApplicationContext context ;

    public void runService() {
        context.publishEvent(new ProgressEvent(0, 100));
        try {
            for (int i = 1 ; i <= 100; i++) {
                Thread.sleep(200);
                context.publishEvent(new ProgressEvent(i, 100));
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

ProgressEvent.java
package springevent;

public class ProgressEvent {

    private final int current ;
    private final int max ;

    public ProgressEvent(int current, int max) {
        this.current = current ;
        this.max = max ;
    }

    public int getCurrent() {
        return current ;
    }

    public int getMax() {
        return max ;
    }
}

MainController.java
package springevent;

import java.util.concurrent.Executor;

import javax.inject.Inject;

import org.springframework.context.event.EventListener;

import javafx.fxml.FXML;
import javafx.scene.control.Button;

public class MainController {

    @Inject
    private Executor exec ;

    @Inject
    private Service service ;

    @FXML
    private Button startButton ;

    public void startProcess() {
        exec.execute(service::runService);
    }

    @EventListener
    public void progressUpdate(ProgressEvent event) {
        startButton.setDisable(event.getCurrent() < event.getMax());
    }

}

Main.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>

<StackPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="springevent.MainController">
    <padding>
        <Insets top="20" bottom="20" left="20" right="20"/>
    </padding>
    <Button fx:id="startButton" text="Start process" onAction="#startProcess" />
</StackPane>

Main.java
package springevent;

import java.io.IOException;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    private AbstractApplicationContext context ;

    @Override
    public void start(Stage primaryStage) throws IOException {
        context = new AnnotationConfigApplicationContext(AppConfig.class);
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
        loader.setControllerFactory(context::getBean);
        Scene scene = new Scene(loader.load());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

and AppConfig.java:
package springevent;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public Service service() {
        return new Service();
    }

    @Bean
    public MainController mainController() {
        return new MainController();
    }

    @Bean
    public ProgressViewer progressViewer() {
        return new ProgressViewer();
    }

    @Bean
    public Executor exec() {
        return Executors.newCachedThreadPool(runnable -> {
            Thread t = new Thread(runnable);
            t.setDaemon(true);
            return t ;
        });
    }
}


text:
Q: Tomcat no encuentra los recursos Bueno tengo una aplicación con AngularJS que hace peticiones al API de gitHub como un ejemplo para aprender a usar AngularJS, pero el problema es que cuando meto la pagina con todas las dependencias en un Dynamic Web Project de Java (esto lo hago porque necesito usar servicios REST definidos con Jersey), y lo corro con Tomcat 8.0.36, me tira los siguientes errores en la dev console de Chrome (lo pruebo en Chrome porque en el navegador de Eclipse no tengo consola de desarrollador para tracear los errores).
La primera vez que intento entrar a localhost:8080/MissingDog pasa esto:

Después muestra este log cuando sigo tratando de entrar:

Este es el log si abro el index.html directamente desde una carpeta, sin meterlo dentro del Dynamic Web Project de Java:

Les dejo mi arbol de directorios del proyecto de Java (MascotaService.js no esta implementado todavia, no hace nada):

A: Las imágenes del error muestran la causa del problema, junto con la imagen de la estructura de tu proyecto. Tus recursos están dentro de la carpeta WEB-INF, la cual no es visible por los navegadores. Los servidores de aplicaciones en Java no muestran el contenido de esta carpeta.
Para resolver tu problema, basta con mover los archivos de ubicación a fuera de la carpeta WEB-INF. La estructura de tu proyecto sería como sigue:
WebContent
- META-INF
- resources (aquí van tus recursos JS, CSS, etc)
  - css
  - fonts
  - images
  - js
  - lib
  - (otras carpetas...)
- WEB-INF
  + web.xml
  - (otros archivos y carpetas para la configuración de tu proyecto como web.xml)

A: Solo una pequeña aclaración, los archivos de la carpeta web-inf si pueden ser accesados, solo paginas web(jsp,xhtml,html), pero para accesarlos archivos dentro de esta carpeta, se tiene que pasar por un controlador, no serán accesibles a través de una url, por lo cual es una buena practica por seguridad y sigue el patron MVC.
Saludos


text:
Q: Powershell: Unable to insert into MySQL date, int values with null I have a MySQL table table_foo with columns col1 of type DATETIME ,col2 of type int, both accepts NULL values but when inserted from Powershell throws error.
$oMYSQLCommand.CommandText='INSERT into `table_foo` (`col1`,`col2`) VALUES("' + $null + '", "' + $null + '")'
 $iRowsAffected=$oMYSQLCommand.ExecuteNonQuery()

also tried using [DBNull]::Value as  ref in
$oMYSQLCommand.CommandText='INSERT into `table_foo` (`col1`,`col2`) VALUES("' + [DBNull]::Value + '", "' + $null + '")'

Error
Error: Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect datetime value: '' for column 'col1' at row 1"

A: Since you're constructing a string into which the null values are to be embedded, you must represent the null values using SQL syntax, which means: verbatim NULL (without surrounding single quotes):
$oMYSQLCommand.CommandText =
  'INSERT into `table_foo` (`col1`,`col2`) VALUES (NULL, NULL)'

If the values come from PowerShell variables that are situationally $null and must therefore conditionally be translated to verbatim NULL, the best approach is to use a helper function, as demonstrated in this answer.
In the simplest case, with all variables containing strings, if you want to treat an empty string or a $null value as a SQL NULL,
you could define a function tf (short for: transform) as follows:
function tf ($val) {
  if ([string]::IsNullOrEmpty($val)) { 'NULL' } else { "'{0}'" -f $val }
}

You could then use the function as follows, with $var1 and $var2 containing the values to embed:
$oMYSQLCommand.CommandText =
  'INSERT into `table_foo` (`col1`,`col2`) VALUES ({0}, {1})' -f
     (tf $var1), (tf $var2)

A: One more simple way of @mklement0's answer is. So the issue here is MySQL accepts variable values with quotes and NULL without quotes. If NULL in enclosed in quotes it is treated as string value.  So while using variable concatenate quotes " if the variable value is not NULL
 if($var_x -eq ""){$var_x ="NULL"}else{'var_x = '"'+ $var_x +'"'}
 if($var_y -eq ""){$var_y ="NULL"}else{'var_y = '"'+ $var_y +'"'}
$oMYSQLCommand.CommandText='INSERT into `table_foo` (`col1`,`col2`) VALUES(' + $var_x + ',' + $var_y  + ')'
 $iRowsAffected=$oMYSQLCommand.ExecuteNonQuery()

A: try typing NULL, dont use variable:
VALUES('NULL','NULL')

something like this:
$oMYSQLCommand.CommandText="INSERT into `table_foo' (`col1`,`col2`) VALUES('NULL','NULL')"


text:
Q: sound plays automatically - flash On one frame in my flash project there are 6 buttons.  When you click a button a different song plays.  Simple.  The problem is, the first song in the list is playing the second the project loads instead of waiting for someone to click the button!
import fl.events.SliderEvent;
var snd:Sound;
var channel:SoundChannel;
var trans:SoundTransform;
var currSong:String;
var currVol:Number = .5;
var currPan:Number = 0;

var songList:Array=new Array("Drifting.mp3","Push.mp3",
                             "Stupid.mp3","Train Wreck.mp3","World on Fire.mp3","Fallen.mp3");

panSlide.visible=false;
volSlide.visible=false;

song1.addEventListener(MouseEvent.CLICK, chooseSong);
song2.addEventListener(MouseEvent.CLICK, chooseSong);
song3.addEventListener(MouseEvent.CLICK, chooseSong);
song4.addEventListener(MouseEvent.CLICK, chooseSong);
song5.addEventListener(MouseEvent.CLICK, chooseSong);
song6.addEventListener(MouseEvent.CLICK, chooseSong);
panSlide.addEventListener(SliderEvent.CHANGE, panChange);
volSlide.addEventListener(SliderEvent.CHANGE, volumeChange);

function chooseSong(e:MouseEvent):void {
    switch (e.currentTarget.name) {
        case "song1":
            currSong = "../MP3s/"+songList[0] as String;
            break;

        case "song2":
            currSong = "../MP3s/"+songList[1] as String;
            break;

        case "song3":
            currSong = "../MP3s/"+songList[2] as String;
            break;

        case "song4":
            currSong = "../MP3s/"+songList[3] as String;
            break;

        case "song5":
            currSong = "../MP3s/"+songList[4] as String;
            break;

        case "song6":
            currSong = "../MP3s/"+songList[5] as String;
            break;
    }
    if (snd != null) {
        channel.stop();
    }
    snd = new Sound();
    snd.load(new URLRequest(currSong));

    channel = new SoundChannel  ;
    trans = new SoundTransform(currVol,currPan);
    channel = snd.play();
    channel.soundTransform = trans;
    panSlide.visible = true;
    volSlide.visible = true;
}

function volumeChange(e:SliderEvent):void {
    currVol = e.target.value;
    trans.volume = currVol;
    channel.soundTransform = trans;
}

function panChange(e:SliderEvent):void {
    currPan = e.target.value;
    trans.pan = e.target.value;
    channel.soundTransform = trans;
}

A: This is just a shot in the dark, but you didn't happen to accidentally add the song to the stage somewhere? That may or may not cause the song to play automatically when the movie loads.
Check your controls as well, a simple mis-click could be the issue.

A: Are you sure you haven´t accidentally added a sound to the timeline? If not you should add a trace inside the method chooseSong and check if it is triggered when you load the project.
I created a new file with a mc (song1) on stage and this script. Does this work for you?
song1.addEventListener(MouseEvent.CLICK, chooseSong);

function chooseSong(e:MouseEvent):void {
    trace (e.currentTarget.name)
}


text:
Q: How to save temporary session variables in PostgreSQL Say I have a simple SQL statement like this:
SELECT * from birthday WHERE date < now() + INTERVAL '1 day' AND date > now() - INTERVAL '1 day';

but the equations for the "From" and "To" variables would be something more sophisticated than that. And I will be reusing the results of these equations in multiple queries. So, can I store them temporarily as we do in any programming language? I imagine something like:
$from := now() - INTERVAL '1 day';
$to:= now() + INTERVAL '1 day';
SELECT * from birthday WHERE date < $from AND date > $to;

I tried using SELECT INTO as suggested in this question but that's not what I want because it creates a whole database table just to save the variable, which also causes an error when reusing it in a later session even when using the TEMP parameter. It says "relationship already exists"!
I also tried some dollar sign $ syntax and some colon+equal := syntax and none works

A: SQL is not any programming language.  If you want to store the values so you can re-use them in one query, then you can use a CTE:
WITH params as (
      SELECT now() - INTERVAL '1 day' as _from,
             now() + INTERVAL '1 day' as _to
     )
SELECT *
FROM params CROSS JOIN
     birthday b
WHERE date < params._to AND date > params._from;

If you want to repeat this across multiple queries, then I would recommend a temporary table:
CREATE TEMPORARY TABLE params AS
      SELECT now() - INTERVAL '1 day' as _from,
             now() + INTERVAL '1 day' as _to;

SELECT *
FROM params CROSS JOIN
     birthday b
WHERE date < params._to AND date > params._from;

You can also encapsulate the code in a procedure/function. Or use some sort of scripting language or language such as Python.


text:
Q: Ubuntu 20.04 with kernel 5.11.0-40-generic does not recognize intel wi-fi 6E ax210 160mhz $ uname -r
5.11.0-40-generic

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal

Thinkpad p14s, and bluetooth works. From what I can tell, the wifi should "just work" for this kernel version, so not sure what i'm missing. Also, the wifi worked before a recent ubuntu update I installed. I reinstalled ubuntu but it's still not working.
Another weird thing, I am using ethernet (because no wifi), but it is 20x to 30x slower than the same ethernet connection when booted in Windows. UPDATE: toggling bluetooth fixed this??

*

*I've disabled fast boot

*I've disabled secure boot

$ dmesg | grep iwl
...
[    3.503770] iwlwifi 0000:09:00.0: Failed to run INIT ucode: -110

A: I've restored wifi functionality. The solution found in this this email thread worked:
https://www.spinics.net/lists/linux-wireless/msg209307.html
As per that email, removing this file and rebooting restored wifi functionality:
sudo rm /lib/firmware/iwlwifi-ty-a0-gf-a0.pnvm

This bug report gives from March gives some context: https://bugs.gentoo.org/777324


text:
Q: fit model using all columns as DV individually Is there a simple way to use each column of a dataframe (one at a time) in a multi-level model? I found this post, but it supplies a DV, using other columns as IV's. I am trying to do the opposite- have an unknown DV and a known IV (1)in order to test column means:
library(nlme)
exampledf<- data.frame(matrix(ceiling(runif(16,0,50)), ncol=4))
colnames(exampledf)<-c("a","b","id_num","d")
my.control<-list(opt='optim',method='ML')

lme(.~1,random=~1|id_num,na.action=na.fail,data=exampledf,control=my.control) #fails

my goal output (the values of these without specifying specific column names):
lme(a~1,random=~1|id_num,na.action=na.fail,data=exampledf,control=my.control)
lme(b~1,random=~1|id_num,na.action=na.fail,data=exampledf,control=my.control)
lme(d~1,random=~1|id_num,na.action=na.fail,data=exampledf,control=my.control)

A: abc <- function(i){
  form <- as.formula(paste0(colnames(exampledf)[i], "~1"))
  lme(form,random=~1|id_num,na.action=na.fail,data=exampledf,control=my.control)
}

lapply(seq_along(colnames(exampledf)), abc)


text:
Q: How can I combined Realm Results<> into a single Result<> set? The model is as follows (simplified example)
class Parent: Object {
   let id = ObjectId()
   let name: String = "some name"

   let children = List<Child>
}

class Child: Object {
   let id = ObjectId()
   let name: String = "some name"

}

How can I get all the parents children back as a since results set ?  It seems odd to define the var all as a LazySequence<FlattenSequence<LazyMapSequence<Results<Parent>, List<Child>>.Elements>>
extension Child {

   var all: Results<Child> {
      let parents = realm.objects(Parent.self)

      // Returns LazyMapSequence<Results<Parent>, List<Child>>
      let children = parents.map({$0.children})

      // Returns LazySequence<FlattenSequence<LazyMapSequence<Results<Parent>, List<Child>>.Elements>>
      let all = children.joined()

      return all
   }
}

A: I think you need a inverse relationship from Child to Parent:
// in Child
let parents = LinkingObjects(fromType: Parent.self, property: "children")

Then, you can get all the children, and filter by whether they have parents:
realm.objects(Child.self).filter("parents.@count > 0")

This will give you a Result<Child>.


text:
Q: Accessing the IHostingEnvironment in ConfigureServices method I need to check in ConfigureServices method whether the current hosting environment name is 'Development'.
So using IHostingEnvironment.IsDevelopment() method may be ok for me, but unlike in Configure method, I do not have IHostingEnvironment env.

A: IHostingEnvironment is deprecated in Core 3.1
        private readonly IWebHostEnvironment _env;

        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            _env = env;
            Configuration = configuration;
        }

should do the trick...
Then reference anywhere with _env.IsDevelopment() etc...

A: Copied here from question marked as duplicate of this one and deleted. Credit to a-ctor.
If you want to access IHostingEnvironment in ConfigureServices you will have to inject it via the constructor and store it for later access in ConfigureServices:
public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment environment)
    {
        Configuration = configuration;
        Environment = environment;
    }

    public IConfiguration Configuration { get; }

    public IHostingEnvironment Environment { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        System.Console.WriteLine($"app: {Environment.ApplicationName}");
    }

    // rest omitted
}

A: just create a property in the Startup class to persist the IHostingEnvironment. Set the property in the Startup constructor where you already have access, then you can access the property from ConfigureServices

A: If you aren't using a Startup class and are calling .Configure() directly, you can access the IHostingEnvironment or IWebHostEnvironment using GetService:
ASP.NET Core 2.2:
.Configure(app => {
    var hostingEnvironment = app.ApplicationServices.GetService<IHostingEnvironment>();
    if (hostingEnvironment?.IsDevelopment() == true)
    {
        app.UseDeveloperExceptionPage();
    }

    // .. Other stuff
});

ASP.NET Core 3.x:
.Configure(app => {
    var hostingEnvironment = app.ApplicationServices.GetService<IWebHostEnvironment>();
    if (hostingEnvironment?.IsDevelopment() == true)
    {
        app.UseDeveloperExceptionPage();
    }

    // .. Other stuff
});

A: If you don't have a Startup class (you may be creating a service) you can get the environment from the hostContext in ConfigureServices like so:
 public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    IConfiguration config = hostContext.Configuration;
                    Configuration = config;

                    var env = hostContext.HostingEnvironment;
                    EnvironmentName = env?.EnvironmentName;

...

A: There are some examples here but none of them seem accurate to the newest release of dotnet, so here we go.
First, in your Startup.cs you should have a reference in your initial constructor like this:
public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            this.Configuration = configuration;
            this.Environment = env;
        }

We can take the Env and tack it onto ServiceCollection like so:
services.AddSingleton(sp => this.Environment);

Then we can access it in any extension method or other place like so:
var hostEnvironment = services.BuildServiceProvider().GetRequiredService<IHostEnvironment>();

if (hostEnvironment.IsDevelopment())
   {
   //do something if in dev
   }


text:
Q: Django Form post action So I can't figure it out how to make form submit action link to external website be invisible in inspect element. For example I got my html form something like this:
<form method='POST' action='some link to external website'> <div>{{ form }}</div>

Is it possible to make it hidden or not ?

A: You shouldn't do this, the browser has to know where to send requests. Although, this answer may help you.


text:
Q: Make vb.net program accessible for multiple users and computers Can someone tell me how to make my vb.net program accessible by multiple users from different computers at a time. My program has forms that will take input and save in MySQL. If multiple users from different computers fill forms it should be saved into mysql.
I am using VS 2013.
Please give me an idea about how to make this.

A: As an idea, you could make two programs , 1 called Server found on your personal PC and the other is called Client on every other user's PC, when client makes a change it calls a function on servers PC using .Net Remoting technology, and the server makes the appropriate changes to the MySQL.
So every change would affect one Database over WAN , and you can add event to each change that will invoke all users to update information.
hope to help :)


text:
Q: A linear order with sequences of length $\omega_0$ but without sequences of length $\omega_1$. Given a set $S$ of cardinal $|S|\geq \omega_1$, can I give a linear < order on S such that at least one of the following two options A) or B) happen?
Option A): A.1) and A.2) are satisfied.
A.1) There are infinite countable increasing sequences.
A.2) There aren't uncountable increasing sequences.
Option B): B.1) and B.2) are satisfied.
B.1) There are infinite countable decreasing sequences.
B.2) There aren't uncountable decreasing sequences.

A: It's not totally clear what you mean by "sequence". In this answer, I assume you're talking about sequences indexed by ordinals. So, e.g., an increasing sequence is $(x_\beta)_{\beta<\alpha}$, where $\alpha$ is an ordinal and $x_\beta < x_\gamma$ for all $\beta<\gamma<\alpha$.
Let $\kappa$ be an uncountable cardinal (viewed as an initial ordinal). The linear order $\omega^{\mathrm{op}}+\kappa$ satisfies your Option B. Indeed, the copy of $\omega^{\mathrm{op}}$ is a countable decreasing sequence. And any decreasing sequence includes only finitely many elements of $\kappa$ (since $\kappa$ is well-ordered), followed by elements of $\omega^{\mathrm{op}}$, so it is at most countable. In fact, an ordinal-indexed decreasing sequence in this order cannot be indexed by any ordinal greater than $\omega$.
The order $\omega^{\mathrm{op}}+\kappa$ has cardinality $\kappa$, so if $S$ is any set of cardinality $\kappa$, we can equip $S$ with a linear order isomorphic to $\omega^{\mathrm{op}}+\kappa$.
Similarly, $\kappa^{\mathrm{op}} + \omega$ satisifes your Option A, and any set of cardinality $\kappa$ can be equipped with a linear order isomorphic to $\kappa^{\mathrm{op}} + \omega$.

A more interesting question is to determine the possible cardinalities of linear orders satisfying both Option A and Option B. That is, linear orders with infinite increasing and descending sequences, but no uncountable increasing or decreasing sequences.
Let me first point out:
Theorem 1: Every infinite linear order has an infinite increasing sequence or an infinite decreasing sequence.
Proof: Let $(L,<)$ be a linear order, and choose a well-order $\lessdot$ on $L$ (which may have nothing to do with $<$). Now for each pair $a\neq b$ in $L$ with $a\lessdot b$, color $\{a,b\}$ blue if $a<b$, and color $\{a,b\}$ red if $b<a$. By Ramsey's theorem,  $L$ has an infinite monochromatic subset $L'\subseteq L$. Note that $L$ is well-ordered by $\lessdot$, so we can naturally view it as an infinite ordinal-index sequence. If it is monochromatic blue, it is an increasing sequence, and if it is monochromatic red, it is a decreasing sequence. $\square$
Now suppose $(L,<)$ is an infinite linear order with no uncountable increasing or decreasing sequences. By Theorem 1, $L$ has either an infinite increasing sequence or an infinite decreasing sequence. Define $L' = L+L^{\mathrm{op}}$. Then $|L'| = |L|$, $L'$ has both infinite increasing and infinite decreasing sequences (one in $L$ and one in $L^{\mathrm{op}}$), and $L'$ has no uncountable increasing or decreasing sequences (since the intersection of such a sequence with $L$ or with $L^{\mathrm{op}}$ would again be uncountable).
This shows that the problem reduces to: What are the possible cardinalities of infinite linear orders with no uncountable increasing or decreasing sequences? Let's call such a linear order "short".
It's a classic fact that $\mathbb{R}$ has no uncountable increasing or decreasing sequences (because it has a countable dense set $\mathbb{Q}$). See here, for example. So there is a short linear order of cardinality $2^{\aleph_0}$.
Now for any $\kappa$ with $\aleph_0\leq \kappa\leq 2^{\aleph_0}$, let $L\subseteq \mathbb{R}$ be a subset of cardinality $\kappa$. The induced order on $L$ is short, because any sequence in $L$ is a sequence in $\mathbb{R}$.
Ok, so we can get short linear orders of any infinite cardinality $\kappa\leq 2^{\aleph_0}$. What about $\kappa>2^{\aleph_0}$? The answer is no, by a strengthening of Theorem 1.
Theorem 2: Every linear order $(L,<)$ with $|L|>2^{\aleph_0}$ has an uncountable increasing sequence or an uncountable decreasing sequence.
Proof: Same as Theorem 1, but this time we apply the Erdös-Rado theorem. As a special case of Erdös-Rado, we have $(2^{\aleph_0})^+\rightarrow (\aleph_1)^2_{\aleph_0}$. In English, this says that if $S$ is a set with $|S|>2^{\aleph_0}$ and we color each pair from $S$ by one of a countable number of colors, then we can find a monochromatic subset of cardinality $\aleph_1$. Applying the same coloring as in the proof of Theorem 1, we find an uncountable subset of $L$, well-ordered by $\lessdot$, which is either an increasing sequence or a decreasing sequence in $L$.
This shows that if a linear order is short, then it has cardinality $\leq 2^{\aleph_0}$.


text:
Q: Update labels text inside of a foreach loop foreach ($question['a'] as $a) {
    ?>

            <input type="radio" name="answer" id="answer" value="<?php echo $count ?>"><?php echo $a['name'] ?>
            <?php $count = $count + 1; ?>

<?php } ?>

$.ajax({
    ///url,data etc
    success: function (data) {
        $('#index').val(data.index);
        $answers = data.question.a;
        $answers.forEach(function(item) {
            console.log(item['name']);
            $('#answerLabel').html(item['name']);
        })
    }
});

I'm trying to update the label text inside the foreach loop but only the first value updates and the  radio button also disappears. The console log show 4 items as it should.
var_dump of questions['a']:
array(4) {
  [0]=>
  array(4) {
    ["id"]=>
    string(2) "12"
    ["questionId"]=>
    string(1) "4"
    ["name"]=>
    string(7) "correct"
    ["correct"]=>
    string(1) "0"
  }
  [1]=>
  array(4) {
    ["id"]=>
    string(2) "10"
    ["questionId"]=>
    string(1) "4"
    ["name"]=>
    string(7) "correct"
    ["correct"]=>
    string(1) "0"
  }
  [2]=>
  array(4) {
    ["id"]=>
    string(1) "9"
    ["questionId"]=>
    string(1) "4"
    ["name"]=>
    string(7) "correct"
    ["correct"]=>
    string(1) "1"
  }
  [3]=>
  array(4) {
    ["id"]=>
    string(2) "11"
    ["questionId"]=>
    string(1) "4"
    ["name"]=>
    string(7) "correct"
    ["correct"]=>
    string(1) "0"
  }
}

Based on the answer of  jameshwart lopez, I appended the $count to the id of the label then made a count =1 in the ajax and added 1 in  the foreachloop.
This solved the problem.

A: Id's are for unique elements only.in your case answerLabel you can try to concat the name or add something to that id that will make it unique element.
Sample
    $count =0;
    foreach ($question['a'] as $a) {
        ?>

                <input type="radio" name="answer" id="answer<?php echo $count;?>" value="<?php echo $count ?>"><label id="answerLabel<?php echo $count;?>" for="answer"><?php echo $a['name'] ?>
                <?php $count = $count + 1; ?>

    <?php } ?>

           $.ajax({
                ///url,data etc
                success: function (data) {

                    $('#index').val(data.index);
                    $answers = data.question.a;
                    count =0;
                    $answers.forEach(function(item) {
                        console.log(item['name']);
                        $('#answerLabel'+count).html(item['name']);
                        count = count+1;
                    })
                }

        });

hope that helps.


text:
Q: Adiabatic free expansion of real (Van der Waal's model) gas below/at/above inversion temperature For an adiabatic free expansion, $W = 0$ and $Q=0$. Therefore, by the first law of thermodynamics, $\Delta U = Q -W = 0$.
For a Van der Waals model of a real gas, $\Delta U = n C_v \Delta T - a\,n^2 \left(\frac{1}{V_2}-\frac{1}{V_1} \right)$. This means that $n C_v \Delta T - a\,n^2 \left(\frac{1}{V_2} -\frac{1}{V_1} \right) = 0$, or $n C_v \Delta T =  a\,n^2 \left(\frac{1}{V_2} -\frac{1}{V_1} \right)$. Now, since the gas is expanding, $V_2 > V_1$. So, $a \, n^2 \left(\frac{1}{V_2}-\frac{1}{V_1} \right) < 0$. Therefore, $n C_v \Delta T<0$. This means that the temperature of the gas decreases in an adiabatic free expansion.
Will the temperature always decrease? I mean, what if the gas is above its inversion temperature or at it? Does inversion temperature play no role in adiabatic free expansion?

A: Your calculation indeed shows that the temperature of the van der Waals gas always decreases in adiabatic free expansion. It is only when the gas flows between two regions of different pressures that the sign of the variation of temperature depends on the temperature. Enthalpy, rather than energy, is conserved in this case. Using the expression of pressure for the van der Waals gas
   $$P={Nk_BT\over V-Nb}-{N^2a\over V^2}$$
enthalpy reads
   $$\eqalign{
   H=U+PV&\simeq {3\over 2}Nk_BT-{N^2a\over V}
   +\left({Nk_BT\over V-Nb}-{N^2a\over V^2}\right)V\cr
   &={3\over 2}Nk_BT-{2N^2a\over V}
   +Nk_BT\left(1-{Nb\over V}\right)^{-1}\cr
   &\simeq {3\over 2}Nk_BT-{2N^2a\over V}
   +Nk_BT\left(1+{Nb\over V}\right)^{-1}\cr
   &={5\over 2}Nk_BT-{2N^2a\over V}+{N^2bk_BT\over V}\cr
   &={5\over 2}Nk_BT+{N^2\over V}\big(bk_BT-2a\big)\cr
   }$$
which can be rewritten as
   $$H=C_pT+{N^2bk_B\over V}(T-T_i)$$
where the inversion temperature is
   $$T_i={2a\over bk_B}$$
For $T>T_i$, the expansion leads to an increase of the temperature.

A: this is more a comment on your answer: in any free expansion the pressures in each side are not kept constant: the pressure decreases in one side and increases in the other side.  The correct statement is: "It is only when the gas flows between two regions of different pressures (each kept constant) that the total entalpy $H_1 +H_2$ is conserved. For a real gas, it follows that the sign of $\Delta T$ depends on T".


text:
Q: Read gzip stream line by line I've got a compressed gzip file which I would like to read line by line.
var fs = require('fs')
var zlib = require('zlib')
var gunzip = zlib.createGunzip()
var inp = fs.createReadStream('test.gz')
var n = 0

var lineProcessing = function (err, data) {
    if (!err) {
        n += 1
        console.log ("line: " + n)
        console.log (data.toString())
    }
}

inp
  .on('data', function (chunk) {
      zlib.gunzip (chunk, lineProcessing)
  })
  .on('end', function () {
    console.log ('ende');
  });

I guess I need to set a chunksize for zlib.createGunzip that I only read until the next \n. But how to determine it dynamically?

A: If anyone is still looking into how to do this years later, and wants a solution that works with async/await, here's what I'm doing (TypeScript, but you can just ditch the type annotations).
import fs from "fs";
import zlib from "zlib";
import readline from "readline";

const line$ = (path: string) => readline.createInterface({
    input: fs.createReadStream(path).pipe(zlib.createGunzip()),
    crlfDelay: Infinity
});

const yourFunction = async () => {
    for await (const line of line$("/path/to/file.txt.gz")) {
        // do stuff with line
    }
}

A: Read plain text or gzip files line by line, in TypeScript:
import * as fs from 'fs';
import * as zlib from 'zlib'
import * as readline from 'readline'

function readFile(path: string) {
    let stream: NodeJS.ReadableStream = fs.createReadStream(path)

    if(/\.gz$/i.test(path)) {
        stream = stream.pipe(zlib.createGunzip())
    }

    return readline.createInterface({
        input: stream,
        crlfDelay: Infinity
    })
}

async function main() {
    const lineReader = readFile('/usr/share/man/man1/less.1.gz')

    for await(const line of lineReader) {
        console.log(line)
    }
}

main().catch(err => {
    console.error(err);
    process.exit(1)
})

A: It might be easier to use readline for this:
const fs       = require('fs');
const zlib     = require('zlib');
const readline = require('readline');

let lineReader = readline.createInterface({
  input: fs.createReadStream('test.gz').pipe(zlib.createGunzip())
});

let n = 0;
lineReader.on('line', (line) => {
  n += 1
  console.log("line: " + n);
  console.log(line);
});


text:
Q: NiFi decimal number format Given the CSV input file below:
name,amount
Abc,"1,234.56"
Def,"2,222,222.222222"

The amount field contains decimal number with comma. How to parse it into a number in NiFi? I don't want to parse it into a string.
I thought of using the UpdateRecord processor, Expression Language, and Java's NumberFormat to parse it, but it seems that NumberFormat is inaccessible from Expression Language. Alternatively, I want to use ScriptedRecordSetWriter to parse, but couldn't find any working example out there.
Appreciate any help especially with a working example.

A: When we are reading the incoming data we still needs to use String type(as the data is enclosed in ") while writing out the data from UpdateRecord processor we can use int/decimal types to write the output flowfile records.
1. Using Record Path Value:
You can read the incoming data as String datatype, Output flowfile will have integer type defined() and using UpdateRecord processor replace the ',' with ''
Add new property in UpdateRecord processor as
/amount
substringBefore(replace(/amount,',',''),'.')

Now the output flowfile will have integer datatype for the amount field.
2. Using Literal Value:
If we are using literal value we can use NiFi expression language functions on field.value by using replace and toNumber functions we are able to get int value for amount field.

Both ways we are going to get output flowfile in json format as
[{"name":"Abc","amount":1234},{"name":"Def","amount":2222222}]

In the same way if you want to have decimal as output flowfile type define avro schema with decimal type and don't use substringBefore and toNumber functions.


text:
Q: Creating a record on a module when inserting on an other module I want to create a record on inventory with quantity = 0 whenever I add a new record to products. Is it possible?
I have 2 modules like so :
class productss(models.Model):
      _name = 'productss.productss'
      name = fields.Char()
      description = fields.Text()
      price =fields.Float()
class inventory(models.Model):
      _name = 'inventory.inventory'
      id_product = fields.Many2one(comodel_name='productss.productss')
      qte = fields.Integer(compute="_value_qte", store=True)

A: Yes, it is possible. Just override productss.productss's create() and create an inventory record within:
@api.model
def create(self, values)
    record = super().create(values)
    # create an inventory
    inv_values = {'id_product': record.id, 'qte': 0}
    self.env['inventory.inventory'].create(inv_values)
    return record

This code requires the "new" Odoo API (V8+) and Python3


text:
Q: TFLite model conversion shows warning and using the converted model with interpreter crashes python kernel I have a tensorflow keras model which has the following architecture:
Model: "model_2"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_3 (InputLayer)        [(None, 199)]             0

 token_and_position_embeddin  (None, 199, 256)         2611456
 g_2 (TokenAndPositionEmbedd
 ing)

 lstm_4 (LSTM)               (None, 199, 150)          244200

 lstm_5 (LSTM)               (None, 150)               180600

 dense_2 (Dense)             (None, 10001)             1510151

=================================================================
Total params: 4,546,407
Trainable params: 4,546,407
Non-trainable params: 0
_________________________________________________________________

I am trying to convert it to tflite in this way:
converter = tf.lite.TFLiteConverter.from_saved_model(str(model_saved_dir))
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
converter.target_spec.supported_types = [tf.float16]
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()
# Save the model.
with open(model_home / 'model.tflite', 'wb') as f:
    f.write(tflite_model)

During conversion it shows the following warnings:
2022-04-12 20:17:23.584937: I tensorflow/cc/saved_model/loader.cc:301] SavedModel load for tags { serve }; Status: success: OK. Took 329307 microseconds.
2022-04-12 20:17:23.771051: I tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.cc:237] disabling MLIR crash reproducer, set env var `MLIR_CRASH_REPRODUCER_DIRECTORY` to enable.
2022-04-12 20:17:23.983377: W tensorflow/compiler/mlir/lite/flatbuffer_export.cc:1892] TFLite interpreter needs to link Flex delegate in order to run the model since it contains the following Select TFop(s):
Flex ops: FlexTensorListFromTensor, FlexTensorListGetItem, FlexTensorListReserve, FlexTensorListSetItem, FlexTensorListStack
Details:
    tf.TensorListFromTensor(tensor<199x?x256xf32>, tensor<2xi32>) -> (tensor<!tf_type.variant<tensor<?x256xf32>>>) : {device = ""}
    tf.TensorListFromTensor(tensor<?x?x150xf32>, tensor<2xi32>) -> (tensor<!tf_type.variant<tensor<?x150xf32>>>) : {device = ""}
    tf.TensorListGetItem(tensor<!tf_type.variant<tensor<?x150xf32>>>, tensor<i32>, tensor<2xi32>) -> (tensor<?x150xf32>) : {device = ""}
    tf.TensorListGetItem(tensor<!tf_type.variant<tensor<?x256xf32>>>, tensor<i32>, tensor<2xi32>) -> (tensor<?x256xf32>) : {device = ""}
    tf.TensorListReserve(tensor<2xi32>, tensor<i32>) -> (tensor<!tf_type.variant<tensor<?x150xf32>>>) : {device = ""}
    tf.TensorListSetItem(tensor<!tf_type.variant<tensor<?x150xf32>>>, tensor<i32>, tensor<?x150xf32>) -> (tensor<!tf_type.variant<tensor<?x150xf32>>>) : {device = ""}
    tf.TensorListStack(tensor<!tf_type.variant<tensor<?x150xf32>>>, tensor<2xi32>) -> (tensor<?x?x150xf32>) : {device = "", num_elements = -1 : i64}
See instructions: https://www.tensorflow.org/lite/guide/ops_select
WARNING:absl:Buffer deduplication procedure will be skipped when flatbuffer library is not properly loaded

But the file is created after this and when trying to use this model in this way:
interpreter = tf.lite.Interpreter(model_path=str(model_home / 'model.tflite'))
interpreter.allocate_tensors()
input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]

# dummy input
ip = [[0 for _ in range(198)] + [1]]
ip = np.array(ip, dtype=np.int32)

interpreter.set_tensor(input_index, ip)
interpreter.invoke()
predictions = interpreter.get_tensor(output_index)
print(predictions)

my jupyter notebook kernel dies and python program crashes. My tensorflow version is '2.8.0' and python version is '3.8.10'. When I try to use the model from Android studio it also crashes showing error ByteBuffer is not a valid FlatBuffer model.

A: I have solved the problem of crashing python kernel and also crashing when loading in Android Studio by adding input and output size to the model signature before converting the model:
run_model = tf.function(lambda x: model(x))
# This is important, let's fix the input size.
BATCH_SIZE = 1
INPUT_SIZE = 199
concrete_func = run_model.get_concrete_function(
    tf.TensorSpec([BATCH_SIZE, INPUT_SIZE], model.inputs[0].dtype))

converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()


text:
Q: how to prevent the insertion of extra quotes in the JSONOBject value? public JSONArray updatedGames() {
    JSONArray ar = new JSONArray();

    try {
        conn = connection.getConnection();
        String query = "CALL websocket_games(2)";
        CallableStatement custStmt = conn.prepareCall(query);
        rs = custStmt.executeQuery();

        while (rs.next()) {
            System.out.println("id "+rs.getString("our_game_id"));
            JsonProvider provider = JsonProvider.provider();
            JsonObject updatemessage = provider.createObjectBuilder()
                    .add("game_id", rs.getString("our_game_id"))
                    .add("date", rs.getString("dat"))
                    .build();
            ar.put(updatemessage);
        }
        if(ar.length()>0){
            System.out.println("provider "+ar.getString(0) );
        }

        rs.close();
        custStmt.close();
        conn.close();
    } catch (Exception e) {
        System.out.println(e);
    }
    System.out.println("number of games " + ar.length());
    return ar;
}

the output for the above function is {"game_id":"\"8240\"","date":"\"2015-08-18\""}
however my desired output is {"game_id":"8240","date":"2015-08-18"}.
how can i prevent the insertion of those extra quotes in the JSONOBject value?

A: Your issue is not in your Java code.
Either your database contains those fields with already quoted values or your websocket_games stored procedure adds those quotes.

A:     //------please try this instead of your while loop ----------
   JSONArray ar = new JSONArray();
   while (rs.next()){
         System.out.println("id "+rs.getString("our_game_id"));
         JsonObject updatemessage = new JsonObject();
         updatemessage.put("game_id", rs.getString("our_game_id"));
         updatemessage.put("date"   , rs.getString("dat"));
         ar.add(updatemessage);
   }

   if(ar.length()>0){
          System.out.println("provider "+ar.getString(0) );
   }

note : please check your database fields values...


text:
Q: Is enthought.mayavi.mlab broken? I used to be able to do this in EPD, but this does not work in Canopy. Am I missing something? Thanks,

from enthought.mayavi import mlab
      Traceback (most recent call last):
        File "", line 1, in
        File "/home-research/jkitchin/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/enthought/mayavi/mlab.py", line 3, in
          from mayavi.mlab import *
      ImportError: No module named mayavi.mlab
from enthought.mayavi.mlab import *
      Traceback (most recent call last):
        File "", line 1, in
        File "/home-research/jkitchin/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/enthought/mayavi/mlab.py", line 3, in
          from mayavi.mlab import *
      ImportError: No module named mayavi.mlab

A: Are you sure Mayav is installed. The enthought namespace has been removed some time ago. You probably have ETSProxy installed but not Mayavi. Can you check in the package manager?


text:
Q: ClassCastException using jersey with custom object as response I am getting a ClassCastException
java.lang.ClassCastException: java.lang.String cannot be cast to com.mcruiseon.common.contracts.IRegistrationResponse
    at com.mcruiseon.common.message.response.RegistrationResponse.getRegistrationResponse(RegistrationResponse.java:43)
    at com.mcruiseon.carpool4all.RegistrationService.post(RegistrationService.java:81)

Jersey based service code
@POST
@Path ("Request")
@Consumes({ MediaType.APPLICATION_JSON })
public Response post(JAXBElement<ClientIdentityConcrete> element) {
    RegistrationRequest request = new RegistrationRequest((ClientIdentityConcrete)(element.getValue()));
    RegistrationResponse response ;
    try {
        clientSession = new ClientSession(God.mCruiseOnServer) ;
    } catch (InvalidServerDNSorIPException e) {
        e.printStackTrace();
        return Response.serverError().build() ;
    }
    sessionKey = sessionManager.setClientSession(clientSession) ;
    clientSession.setSessionKey(sessionKey) ;

    clientSession.getSendQueue().sendRequest(request) ;
    try {
        response = (RegistrationResponse)clientSession.waitAndGetResponse(request) ;
    } catch (WaitedLongEnoughException e) {
        return Response.serverError().build() ;
    } catch (UnableToResolveResponseException e) {
        return Response.serverError().build() ;
    }

// Getting Exception in line below
    return Response.ok(response.getRegistrationResponse()).build();
}

Supporting Code
public IRegistrationResponse getRegistrationResponse() {
        return ((IRegistrationResponse) super.getMessage());
    }

public interface IRegistrationResponse {
    public String getIdentityHash() ;
    public String getSessionKey() ;
}

A: My server was returning a String, I forgot to upload my server with the latest jar's. Once I did that, the ClassCastException disappeared.


text:
Q: Add armor attributes with /item modify- 1.17 datapack issue I am trying to modify the armor a certain entity is wearing (based on material) by adding a very slight movement speed decrease, which I should be able to do with attributes. I have the entity tagged so I can access it with /execute as @e[tag=…] run .
According to the internet,  /item modify is the way to do this, yet there are no examples or command generators I could find. I found plenty of ways to get items with attributes through the /attribute and /give commands, but no examples for /item modify.
I currently have:
item modify entity @s armor.feet __________

In the blank location, I attempted to fill this with the following words: set_attribute, attribute, etc. Regardless of what I seem to put in the "modifiers" spot, it always returns unknown item modifier.
How would I add a custom movement speed attribute decrease to it? It's probably easy but I can't seem to figure it out.

A: An item modifier is a separate file in your data pack. Your question has the implication you already are using a data pack so that is what I will assume.
Let's use a concept from /loot, and bring it over to /item modify.

/loot is used to call upon a loot table, see what items it generates, and output the generated items to the location you set. For example,
loot give @p loot _________

In the blank is where you specify which loot table you want to call upon. But loot tables are separate data pack files. So you don't type a loot table's contents into the blank, you type the loot table's ID into the blank.
Say I have a loot table that drops one stone. That's a giant JSON file I have right there. As I stated above, I don't type its name into the blank, instead, I put that JSON file into the designated folder for loot tables, and call upon its name.
After doing this, my data pack structure looks like this:
my_datapack
├ pack.mcmeta
└ data
  └ my_namespace
    ├ functions
    │ └ give_loot.mcfunction
    └ loot_tables
      └ stone_loot.json

where stone_loot.json is that loot table above, and give_loot.mcfunction is the function with the /loot command.
So to give the loot to the player, we call upon the filename of the loot table we made, formatted as namespace:id. In this case, we have stone_loot as the ID, and our namespace is my_namespace. So the proper thing to type in the blank is my_namespace:stone_loot. This makes:
loot give @p loot my_namespace:stone_loot

The above snippet should make sense to you. If it doesn't, please ask for clarification in the comments below.
It's the same concept for /item modify. This is the exact same text, translated for item modifiers:

/item modify is used to call upon an item modifier, look at the contents of said item modifier, and interpret the contents as instructions for how to modify the item in the slot you set. For example,
item modify entity @p weapon.mainhand _________

In the blank is where you specify which item modifier you want to call upon. But item modifiers are separate data pack files. So you don't type an item modifier's contents into the blank, you type the its ID into the blank.
Say I have an item modifier that adds Sharpness II onto an item. That's quite the JSON file I have right there. As I stated above, I don't type its name into the blank, instead, I put that JSON file into the designated folder for item modifiers, and call upon its name.
After doing this, my data pack structure looks like this:
my_datapack
├ pack.mcmeta
└ data
  └ my_namespace
    ├ functions
    │ └ modify_mainhand.mcfunction
    └ item_modifiers
      └ sharpness_two.json

where sharpness_two.json is that item modifier above, and modify_mainhand.mcfunction is the function with the /item modify command.
So to invoke our item modifier, we call upon the filename of the item modifier we made, formatted as namespace:id. In this case, we have stone_loot as the ID, and our namespace is my_namespace. So the proper thing to type in the blank is my_namespace:sharpness_two. This makes:
item modify entity @p weapon.mainhand my_namespace:sharpness_two

Does this make sense how the same concept is applied to more things?
Oh, and as for how to make the JSON files for loot tables and data packs? That's what the wiki is for, the official documentation. But if you find the wiki confusing, you probably will need a generator. Here is the most competent item generator on the block for data pack files. I like this website because it only gives you the names of text inputs, but doesn't tell you what they do. You will have to cross-reference the wiki to figure out what each thing does.


text:
Q: Excel 2007 - Formula changes to #REF So I've got this Workbook which contains a lot of data. And I've got this one sheet which basically copies the data based on certain conditions.
Each cell in each row looks like this (the last specified cell is the one where the formula is in):
=IF(Numbers1!E2<>0;Numbers1!A2;"")
=IF(Numbers1!E3<>0;Numbers1!A3;"")
=IF(Numbers1!E4<>0;Numbers1!A4;"")
=IF(Numbers1!E2<>0;Numbers1!B2;"")
=IF(Numbers1!E3<>0;Numbers1!B3;"")
=IF(Numbers1!E4<>0;Numbers1!B4;"")

So the formula in cell A2 is the first one, formula in A3 is the second line etc.
I want to copy the value from the same column and row from the sheet Numbers1, IF the value in the same row of column E is not 0. This seems to be working just fine.
But, when I update the data in Numbers1 sheet, the formulas are all of a sudden invalid and the formula now looks like this:
=IF(Numbers1!#REF!<>0;Numbers1!#REF!;"")

Each formula in each cells look identical to the formula above. And I can't have that, why can't Excel just keep the formula as it is without "helping" me?

A: Since you may be better off using a macro to rewrite your formulas, here are the basics:
Sub RewriteFormulas()

    Dim row, col As Integer
    row = 1               'row you want your target formulas to be on

    For row = 1 To 60
        For col = 1 To 13

            ActiveSheet.Cells(row, col).Formula = "=IF(Numbers1!" & Cells(row,col).Address & "<>0,Numbers1!" & Cells(row+2,col).Adddress & ","""")"

        Next row
    Next col

End Sub

You can play around with using different sheets (or different workbooks) instead of just ActiveSheet so you can have 1 workbook that stores the macro and alters data in whatever workbooks provide your updated datasets.
Hope that helps...


text:
Q: Render QML without being visible, like a background task Suppose I have a map, and a few polygons. I want to render them and take a screenshot of each one of them.
If the QQuickView is visible, thats easy.
But, how could I achieve this, with the QQuickView not visible, like a background task?
Any ideas?
I`m using Qt 5.12.


text:
Q: SSH into networked server remotely? I have setup a virtual server running MediaWiki (a TurnKey appliance). I have got the server up and running and have assigned it a static IP address on the local network.
I have also assigned the server a public IP address by setting up a DMZ host on the router. The router is a Draytek Vigor 2820.
I have tried using SSH/SFTP/FTP to access the server remotely but they all timeout. The turnkey appliance comes with Shell in a box as standard and that works fine.
I have checked the firewall using the webmin interface and port 22 is allowed.
Am I missing any vital steps?
For reference the appliance product page can be seen here: http://www.turnkeylinux.org/mediawiki
Update:
The public ip address fails when I ping it from the remote location (any remote location) and a port test shows port 22 as closed. I presume this narrows the problem down to the router?

A: "I'm unsure how to open port 22 for multiple servers."
If you want to run multiple servers/applications on the same/overlapping standard port number assignments, then you will need multiple routable IP addresses for access to each across the Internet.

A: Inbound ssh and http ports is probably not open on router. You will need to consult your router's documentation and understand from there how open firewall ports on the router to the server on the DMZ.
That said, since Draytek Vigor 2820 support port redirection:
http://www.draytek.co.uk/products/vigor2820.html
I might suggest that you put the server off the DMZ and just redirect port 80, 443 and ssh to that server's IP.


text:
Q: https://dl.bintray.com/kotlin/kotlin-eap 502 bad gateway My apk is failing to compile saying it could not get
Plugin [id: 'org.jetbrains.kotlin.jvm', version: '1.4.21'] was not found in any of the following sources:
When I try to visit: https://dl.bintray.com/kotlin/kotlin-eap I get a 502 bad gateway
is this the reason why it's failing to build?
my gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        jcenter()
        google()
        gradlePluginPortal()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.1'
        classpath 'com.google.gms:google-services:4.3.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.0'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.4.21'
}

allprojects {
            repositories {
                maven { url "https://maven.google.com" }
                maven { url "https://jitpack.io" }
                maven { url "http://dl.bintray.com/jlmd/maven" }
                maven{
                    url "https://oss.sonatype.org/content/repositories/snapshots"

                }
                maven {
                    url "https://cardinalcommerceprod.jfrog.io/artifactory/android"
            credentials {
                username 'braintree_team_sdk'
                password 'AKCp8jQcoDy2hxSWhDAUQKXLDPDx6NYRkqrgFLRc3qDrayg6rrCbJpsKKyMwaykVL8FWusJpp'
            }
        }
        maven{
            url 'https://zendesk.jfrog.io/zendesk/oss-releases-local'

        }
        jcenter()
        google()

        mavenCentral()

    }
}

repositories {
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    mavenCentral()
}
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
}
compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

i can't find the reason why my apk suddenly stopped building it was working last month i need to find the solution before tomorrow please someone help me.
full error code
Plugin [id: 'org.jetbrains.kotlin.jvm', version: '1.4.21'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'org.jetbrains.kotlin.jvm:org.jetbrains.kotlin.jvm.gradle.plugin:1.4.21')
  Searched in the following repositories:
    maven(https://dl.bintray.com/kotlin/kotlin-eap)
    MavenRepo
    maven2(https://plugins.gradle.org/m2/)

A: Bintray and JCenter is not supported yet
Remove all Bintray and JCenter repository configure in your gradle file. And use mavenCentral() instead.
Here is the solution:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        // jcenter()
        mavenCentral() // use this instead
        google()
        gradlePluginPortal()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.1'
        classpath 'com.google.gms:google-services:4.3.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.0'
        classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.4.21'
}

allprojects {
            repositories {
                maven { url "https://maven.google.com" }
                maven { url "https://jitpack.io" }
                // maven { url "http://dl.bintray.com/jlmd/maven" }
                maven{
                    url "https://oss.sonatype.org/content/repositories/snapshots"

                }
                maven {
                    // url "https://cardinalcommerceprod.jfrog.io/artifactory/android"
            credentials {
                username 'braintree_team_sdk'
                password 'AKCp8jQcoDy2hxSWhDAUQKXLDPDx6NYRkqrgFLRc3qDrayg6rrCbJpsKKyMwaykVL8FWusJpp'
            }
        }
        maven{
            // url 'https://zendesk.jfrog.io/zendesk/oss-releases-local'

        }
        // jcenter()
        google()

        mavenCentral()

    }
}

repositories {
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    mavenCentral()
}
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
}
compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

A: just go to 'settings.gradle' file and comment
maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' } line that fixed my problem
how and why I don't know


text:
Q: invalid initialization of non-const reference of type 'MyVector&' from an rvalue of type 'MyVector' I know that there are many threads on this, but after going through several, I still haven't solved my problem.
I have a custom vector class and I am trying to create a function that takes in a vector and adds it to the current vector, then returns it.
Below is the code for my vector class.
MyVector.h

template<class type>
class MyVector {
    private:
        type* m_data;
        size_t m_capacity = 1;
        size_t m_size = 0;

    public:
        MyVector() {
            this->m_size = 0;  // this->m_size is 0 because there are no elements
            this->m_capacity = 1;  // this->m_capacity starts off 1 more than this->size
            this->m_data = new type[this->m_capacity];  // Allocate the memory required
        }

        MyVector(MyVector<type>& other) {
            this->m_capacity = other.m_capacity;  // The capacity will be the same
            this->m_size = other.size();  // The size will also be the same
            this->m_data = new type[this->m_capacity];  // Allocate the memory required to hold the data

            /* Copy all the data from the vector to this object */
            for (size_t i = 0; i < other.size(); i++) {
                this->m_data[i] = other[i];
            }
        }
        MyVector(std::initializer_list<type> init_list) {
            int init_list_size = init_list.size();  // This will be the size of the initializer list: { 1, 2, 3, ... }
            this->m_capacity = init_list_size + 1;  // Make the capacity one more to make it work when trying to append
            this->m_data = new type[this->m_capacity];  // Allocate the memory required

            /* Copy all the data */
            for (type t : init_list) {
                this->m_data[this->m_size++] = t;
            }
        }

        MyVector<type>& operator=(MyVector<type> other) {
            this->m_capacity = other.m_capacity;  // The capacity will be the same as the other vector
            this->m_size = other.m_size;  // The size will be the same as the other vector
            this->m_data = new type[this->m_capacity];  // Allocate the memory required

            /* Copy the data from the other vector to this */
            for (size_t i = 0; i < other.size(); i++) {
                this->append(other.get(i));
            }
            return *this;
        }
        /* Functionality to append, delete, etc... */

        type get(size_t index) const {
            return this->m_data[index];
        }

        /* PROBLEMATIC CODE */
        MyVector<type> add(MyVector<type>& other) {
            MyVector<type> result;
            for (size_t i = 0; i < this->size(); i++) {
                result.append( this->get(i) + other.get(i) );
            }
            return result;
        }

};

The following is how I implemented the MyVector class.
main.cpp
#include "../include/MyVector.h"

int main() {
    MyVector<int> a = { 1, 2, 3, 4, 5 };
    MyVector<int> b = a;
    MyVector<int> c = a.add(b);  // error: invalid initialization of non-const reference of type 'MyVector<int>&' from an rvalue of type 'MyVector<int>'

    return 0;
}

The error I get is error: invalid initialization of non-const reference of type 'MyVector&' from an rvalue of type 'MyVector'.
Along with note:   initializing argument 1 of 'MyVector::MyVector(MyVector&) [with type = int]'
What I don't understand is why the left-side of the equation cannot be assigned to an rvalue.


text:
Q: Creating a title page
How can I create such a frame? What I did s as follows:
Note: I use overleaf
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{xcolor}

\begin{document}

        %  \includegraphics[width=.75\textwidth]{odtu-lang-en}\\
    {\large {\textcolor{red}{MIDDLE EAST TECHNICAL UNIVERSITY}}%

    \hfill Ankara, Turkey
}

\end{document}

what I obtain is this

A: Here is one way to do it, which is a bit the way you'd do it in TeX, i.e. without all those nice macros from Latex. Alternatives are e.g. using tables.

In the beginning I define your color green. Next I introduce 4 variables using \newcommand, which kind of simplifies the code to use later, and simplifies manipulating appearance. They are basically constructed like this:

*

*they contain the text to be displayed

*next they manipulate the font using \large and \scshape (small caps)

*finally some get some \color

*later it turned out that most have to end with \par to avoid a nasty blank at the end

I used the small caps and also some variations in writing more for demonstration purposes. You could also type all in caps instead and remove the \scshape  from the 2 macros. // It's worth noticing the double braces {{ .. }} . First pair is needed to define the macro. Second pair makes the changes local, i.e. reverts fonts to "normal" once the macro was expanded.
Now the TeX-ish typesetting.
First line removes the indenting of the first paragraph. It outputs uni and city and uses \hfill, which simply drives both text fragments as much appart as possible, just like a spring would do.
Next \medskip and \hrule try to mimick vertical white space and of course the horizontal line.
Finally, inst and web are output, and this time driven from the left to its outmost right positions by a starting \hfill.
P.S.: Followed Mico's advice and replaced \sc by \scshape, and \tt by \ttfamily.
\documentclass[12pt]{article}

\usepackage{xcolor}
\definecolor{green}{rgb}{0,0.6,0}% your green

% constants
\newcommand\uni[0]{{\large \scshape \color{red} Middle East Technical University}}
\newcommand\inst[0]{{\large \scshape \color{green} Institute of applied mathematics\par}}
\newcommand\city[0]{Ankara, Turkey\par}
\newcommand\web[0]{{\large \ttfamily http://iam.metu.edu.tr\par}}

\begin{document}

    \parindent=0pt\uni{}\hfill\city{}
    \medskip
    \hrule
    \medskip
    \hfill\inst{}\par
    \hfill\web{}
    \medskip
    \hrule

\end{document}

A: I have simplified your MWE, among other things many unneeded packages for your problem.
% ankaraprob.tex  SE 649949

\documentclass{article}

\begin{document}

    {\large {MIDDLE EAST TECHNICAL UNIVERSITY}}
%
    \hfill Ankara, Turkey % \mbox{}
%}

    \rule{0.96\textwidth}{1mm}

    \mbox{} \hfill INSTITUTE OF ...

    \mbox{} \hfill \verb!http://...!

    \rule{0.96\textwidth}{1mm}

    And more text after this.

   \end{document}

You may want to change some of the lengths to suit your documentstyle better.

A: I can think of two separate solution approaches:

*

*Use all-uppercase letters for the two long strings

*Use \large small-caps letters for these strings
As the following screenshot shows, the second approach is marginally more refined, mainly because of the improved kerning between the letters.
I would also load the xurl and hyperref packages to ensure that the URL string acts as a proper hyperlink.

\documentclass[svgnames]{article}
\usepackage[svgnames]{xcolor}
\usepackage{xurl}
\usepackage[hidelinks]{hyperref}

\begin{document}

% Version A: uppercase lettering
\noindent
\textcolor{red}{MIDDLE EAST TECHNICAL UNIVERSITY}
\hfill
Ankara, Turkey%
\smallskip
\hrule
\medskip
\hfill\textcolor{ForestGreen}{INSTITUTE OF APPLIED MATHEMATICS}

\hfill\url{http://iam.metu.edu.tr}%
\smallskip
\hrule

\bigskip\bigskip

% Version B: large/smallcaps lettering
\noindent
\textcolor{red}{\large\scshape middle east technical university}
\hfill
Ankara, Turkey%
\smallskip
\hrule
\medskip
\hfill\textcolor{ForestGreen}{\large\scshape institute of applied mathematics}

\hfill\url{http://iam.metu.edu.tr}%
\smallskip
\hrule

\end{document}


text:
Q: Reduce length of URLs in Liferay Is there a way to reduce the URL's length in Liferay? IE only allows a maximum length of 2,083 but when I have a lot of parameters to pass between JSPs this causes a problem as each parameter has projectname_WAR_portletname_id in front of it.
I use tinyurl's wherever possible but when I dynamically create a URL using Liferay tags I cannot do that.
The only thing I could think of is to shorten the name of the portlet. I have done this but it is still not enough.
Saving these parameters in the session is not an option as there are a lot of them, say when carrying out an advanced search, and performance is my number one priority
Thanks

A: Liferay provides this feature, and it is not very difficult to configure. Checkout http://www.liferay.com/documentation/liferay-portal/6.2/development/-/ai/portlet-friendly-url-mapping-liferay-portal-6-2-dev-guide-03-en page for details.


text:
Q: SQL runs on localhost but throws SQLSTATE[42883] error on deployment to heroku i have a laravel/vuejs project i just deployed to heroku. Everything works well both on local and production except for a query that is throwing up SQLSTATE[42883] error on production. The sql query retrieves a count of models created every week:
public function getProductWeeklyData(){
    $products= Product::selectRaw('COUNT(*) AS product_count')
            ->selectRaw('FROM_DAYS(TO_DAYS(created_at) -MOD(TO_DAYS(created_at) -1, 7)) AS week_starting')
            ->groupBy('week_starting')
            ->orderBy('week_starting')
            ->take(10)->get();
    $products->each->setAppends([]);

    return response()->json($products, 200);
}

This works on localhost and return an array like so:
0: {product_count: 7, week_starting: "2021-10-31"}
1: {product_count: 12, week_starting: "2021-11-07"}
2: {product_count: 15, week_starting: "2021-11-14"}

which was exactly what i wanted.
However, after deploying to heroku and changing the database connection to PostgreSQL, the query fails and start returning this error.

"message": "SQLSTATE[42883]: Undefined function: 7 ERROR:  function to_days(timestamp without time zone) does not exist\nLINE 1: select COUNT() AS product_count,FROM_DAYS(TO_DAYS(created_at...\n                                                  ^\nHINT:  No function matches the given name and argument types. You might need to add explicit type casts. (SQL: select COUNT() AS product_count, FROM_DAYS(TO_DAYS(created_at) -MOD(TO_DAYS(created_at) -1, 7)) AS week_starting from "products" group by "week_starting" order by "week_starting" asc limit 10)"

i tried casting the date like was suggested in the error by doing this

...(created_at::text, 'YYYY-MM-DD')
but still got an error of invalid query.
How do i get this query working with PostgreSQL on production?