text:
Q: Tensorflow: OP_REQUIRES failed at save_restore_v2_ops.cc:184 : Not found: Key global_step not found in checkpoint I have been trying to load a pretrained model and use it for further training. But the model I have downloaded is not working for me. Even after reading a lot about this issue I am still lost.
The error is:

I0616 16:24:36.320715 139841803228928 mpi.py:337] parameter_count =
16892227 INFO:tensorflow:Resume training from previous checkpoint
I0616 16:24:36.326457 139841803228928 mpi.py:343] Resume training from
previous checkpoint WARNING:tensorflow:From
/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/saver.py:1276:
checkpoint_exists (from
tensorflow.python.training.checkpoint_management) is deprecated and
will be removed in a future version. Instructions for updating: Use
standard file APIs to check for files with this prefix. W0616
16:24:36.326805 139841803228928 deprecation.py:323] From
/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/saver.py:1276:
checkpoint_exists (from
tensorflow.python.training.checkpoint_management) is deprecated and
will be removed in a future version. Instructions for updating: Use
standard file APIs to check for files with this prefix.
INFO:tensorflow:Restoring parameters from
/home/stereo_magnification/stereo-magnification-master/model/siggraph_model_20180701/model.latest
I0616 16:24:36.330070 139841803228928 saver.py:1280] Restoring
parameters from
/home/stereo_magnification/stereo-magnification-master/model/siggraph_model_20180701/model.latest
2022-06-16 16:24:36.548759: W
tensorflow/core/framework/op_kernel.cc:1502] OP_REQUIRES failed at
save_restore_v2_ops.cc:184 : Not found: Key global_step not found in
checkpoint INFO:tensorflow:Error reported to Coordinator: <class
'tensorflow.python.framework.errors_impl.NotFoundError'>, Restoring
from checkpoint failed. This is most likely due to a Variable name or
other graph key that is missing from the checkpoint. Please ensure
that you have not altered the graph expected based on the checkpoint.
Original error:
Key global_step not found in checkpoint    [[node save/RestoreV2
(defined at
home/stereo_magnification/stereo-magnification-master/stereomag/mpi.py:329)
]]

Please let me know how to proceed with this.
Here is the pretrained model: https://drive.google.com/open?id=1CZGJxRl0GK0js0MbL7cn7tHtdRrtnjOB
Part of the script:
def train(self, train_op, checkpoint_dir, continue_train, summary_freq,
        save_latest_freq, max_steps):
"""Runs the training procedure.

Args:
  train_op: op for training the network
  checkpoint_dir: where to save the checkpoints and summaries
  continue_train: whether to restore training from previous checkpoint
  summary_freq: summary frequency
  save_latest_freq: Frequency of model saving (overwrites old one)
  max_steps: maximum training steps
"""
parameter_count = tf.reduce_sum(
    [tf.reduce_prod(tf.shape(v)) for v in tf.trainable_variables()])
global_step = tf.Variable(0, name='global_step', trainable=False)
incr_global_step = tf.assign(global_step, global_step + 1)
saver = tf.train.Saver(
    [var for var in tf.model_variables()] + [global_step], max_to_keep=10)
sv = tf.train.Supervisor(
    logdir=checkpoint_dir, save_summaries_secs=0, saver=None)

with sv.managed_session() as sess:
  tf.logging.info('Trainable variables: ')
  for var in tf.trainable_variables():
    tf.logging.info(var.name)
  tf.logging.info('parameter_count = %d' % sess.run(parameter_count))
  if continue_train:

    checkpoint = tf.train.latest_checkpoint(checkpoint_dir)
    if checkpoint is not None:
      tf.logging.info('Resume training from previous checkpoint')
      tf.reset_default_graph()
      saver.restore(sess, checkpoint)

This is the original project: https://github.com/google/stereo-magnification


text:
Q: What is the reason for the error message "Library not loaded: libmysqlclient.18.dylib"? I have no experience working with Perl, and I'm trying to run the geo_to_mysql.pl program for a project I'm working on. I made no modifications to the program other than the database, username, password and file directory path in the first few lines.
When running the program, I keep getting this error:

install_driver(mysql) failed: Can't load '/Library/Perl/5.10.0/darwin-thread-multi-2level/auto/DBD/mysql/mysql.bundle' for module DBD::mysql: dlopen(/Library/Perl/5.10.0/darwin-thread-multi-2level/auto/DBD/mysql/mysql.bundle, 1): Library not loaded: libmysqlclient.18.dylib
Referenced from: /Library/Perl/5.10.0/darwin-thread-multi-2level/auto/DBD/mysql/mysql.bundle
Reason: image not found at /System/Library/Perl/5.10.0/darwin-thread-multi-2level/DynaLoader.pm line 207.
at (eval 7) line 3
Compilation failed in require at (eval 7) line 3.
Perhaps a required shared library or dll isn't installed where expected

I've made sure that I installed the DBD required for MySQL from CPAN, so I don't think that's the issue. Can anyone shed some light on this issue?

A: It sure sounds like you might want to read this blog post:
http://probably.co.uk/problems-installing-dbdmysql-on-os-x-snow-leopard.html
The issue seems to be that the mysqlclient dynamic library doesn't have path information in it.  You need to manaully fix this (as the post above notes).
One of the cheaper solutions is to symlink or copy the libmysqlclient library to /usr/lib.
Hope this helps anyone looking for this question in the future.

A: The DBD::mysql module needs access to the MySQL client libraries in order to work. I'm surprised that DBD::mysql even installed without them being on your system. How did you install the DBD::mysql module?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show an alert if all checkboxes aren't checked? I want alert if check-box is not checked (- this is working )
and
Alert if ALL check-box is not checked  ( need help in this )
CheckBox :
<input type="checkbox" value="1" id="data" name="data[]">
<input type="checkbox" value="2" id="data" name="data[]">
<input type="checkbox" value="3" id="data" name="data[]">

Button :
<input name=\"submitclose\" type=\"submit\"  value=\"Close\" id=\"submitclose\">

Below is my Jquery :
echo "<script>
jQuery(function($)  {
$(\"input[id='submitclose']\").click(function() {

                var count_checked = $(\"[id='data']:checked\").length;
                if (count_checked == 0)  {
                        alert(\"Please select a Packet(s) to Close.\");
                        return false;
                } else{
                        return confirm(\"Are you sure you want to Close these Packet?\");
                }
        });
});
</script>";

A: Try,
HTML:
<input type="checkbox" value="1" id="data1" name="data[]">
<input type="checkbox" value="2" id="data2" name="data[]">
<input type="checkbox" value="3" id="data3" name="data[]">

JS:
var allCheckBox = $("[id^='data']")
var count_checked = allCheckBox.filter(":checked").length;
if (count_checked == 0)  {
    alert("All check boxes are not checked");
} else if(count_checked != allCheckBox.length) {
    alert("some of the check boxs are not checked");
} else{
    return confirm("Are you sure you want to Close these Packet?");
}

A: $(\"input[id='submitclose']\").click(function(){
    var count = 0;
    $('input#data').each(function(){
    if ($(this).attr('checked') == true){
    count++  //if a checkbox is checked the variable count will be greater then 0.
    }
})
    if (count == 0){      //nothing is checked.
    alert("Please check at least one of the checkboxes");
}else{       //something is checked.
    //code to execute.
}

})


text:
Q: How to score/measure the change in a time series from t-x,...t-1 to t0 (Relative change) I think about having data such as:
Time   1   2   3   4   5   6   7   8   9 ... n

Set1  12  13  13  23  26  27  40  13  13
Set2   2   3   4   2   4   3  10  12  11
.
.
.
Setn ...

All datasets are equivalent in terms of the meaning what a sudden (relative) change in values indicate. Means when in set1 is a change from 13 to 23 it indicates the same as when there is a change from 3 to 10 in set2. It only depends on the relative change of the actual t0 to the average of the past x periods.
My question is what is the best way to quantify such change?
My goal is to have a value in each period for each dataset that indicates the change. This value should be comparable to the other datasets. Means when I have a change from 13 to 23 the value should approximately similar to a change from 3 to 10.
Would appreciate any advice!
Thanks and Best :)

A: To capture the relative effect i would go for x_t - x_t-1 / x_t-1
If you want the same result in your example x_t-1 = 13 x_t = 23 & z_t-1 = 3 z_t = 13 you could just go for the difference x_t - x_t-1
And if you want to put everything to respect of some stylized statistic, you could just change the denominator
x_t-1 to t0 (t0 being median, mean, whatever you like)


text:
Q: Aggregate contents of array column in Azure Data Explorer I have some data stored in the customEvents property bag that I want to perform aggregation and analytics on. I'm new to the analytics queries that you can run against AppInsights using the Azure Data Explorer query language and am stuck.
I have a handle on converting the contents of one of the property bag's key-value-pairs into an array of numbers (in the example below, that output is represented by items.
let items = parse_json('{"operation_Id": "12345Z12", "days":[43, 21, 65]}');
print items.operation_Id, items.days;

However, when I need to calculate the average value of the items in the array for each operation_Id, I run into a documentation wall. I've looked at mvexpand, let (using a lambda expression), datatable, using dynamic data types, etc. The blocking issue I've had with using mvexpand is that I want to associate every row in the output correlated with its operation operation_Id, and mvexpand only seems to persist that relationship in the first row. With a datatable, the type doesn't support a pipeline input.
Another common error I've (including from the code sample below is Operator Source Expression should be table or column).
let items = parse_json('{"days":[43, 21, 65]}');

let arraySum = (T:(x: long))
{
   T
   | summarize sum(x)
};
items
| project days | invoke arraySum()

If necessary, I can perform the aggregation code in JavaScript and only pass the calculated average in the property bag, but it feels like a waste to throw away the raw data values. Is there some obvious calculation or aggregation function that solves this problem?

A: Both the following options should allow you to calculate the average as you're interested in:
(caveat: this is based on the example you've shown, which may potentially be "dumbed down" to not reflect your real-life scenario, so please clarify in case this isn't helpful):
let items = dynamic({"operation_Id": "12345Z12", "days":[43, 21, 65]});
print operationId = tostring(items.operation_Id), days = items.days
| mvexpand days to typeof(int)
| summarize avg(days) by operationId

// or

let items = dynamic({"operation_Id": "12345Z12", "days":[43, 21, 65]});
print operationId = tostring(items.operation_Id), days = items.days
| project operationId, series_stats_dynamic(days)['avg']

Your second example is indeed invalid (scalars and tabular arguments are not born equal), but could be rewritten as follows:
(same caveat as above)
let items = dynamic({"days":[43, 21, 65]});
let arraySum = (T:(x: long))
{
   T
   | summarize sum(x)
};
print items
| mvexpand x = items.days to typeof(long)
| invoke arraySum()

// or

let items = dynamic({"days":[43, 21, 65]});
print items
| project sum = series_stats_dynamic(items.days)["avg"] * array_length(items.days)

Updated examples following up the comments provided later on:
datatable (Operation_id:string, customDimensions:dynamic)
[
    "MTFfq", dynamic({"siteId": "1", "fileCount": "3", "pendingDays":[15,10,11]}),
    "LXVjk", dynamic({"siteId": "2", "fileCount": "1", "pendingDays":[3]}),
    "jnySt", dynamic({"siteId": "3", "fileCount": "2", "pendingDays":[7,11]}),
    "NoxoX", dynamic({"siteId": "4", "fileCount": "4", "pendingDays":[1,4,3,11]})
]
| mvexpand days = customDimensions.pendingDays to typeof(int)
| summarize avg(days) by Operation_id

// or

datatable (Operation_id:string, customDimensions:dynamic)
[
    "MTFfq", dynamic({"siteId": "1", "fileCount": "3", "pendingDays":[15,10,11]}),
    "LXVjk", dynamic({"siteId": "2", "fileCount": "1", "pendingDays":[3]}),
    "jnySt", dynamic({"siteId": "3", "fileCount": "2", "pendingDays":[7,11]}),
    "NoxoX", dynamic({"siteId": "4", "fileCount": "4", "pendingDays":[1,4,3,11]})
]
| project Operation_id, series_stats_dynamic(customDimensions.pendingDays)['avg']

and:
let arraySum = (T:(x: long))
{
   T
   | summarize sum(x)
};
datatable (Operation_id:string, customDimensions:dynamic)
[
    "MTFfq", dynamic({"siteId": "1", "fileCount": "3", "pendingDays":[15,10,11]}),
    "LXVjk", dynamic({"siteId": "2", "fileCount": "1", "pendingDays":[3]}),
    "jnySt", dynamic({"siteId": "3", "fileCount": "2", "pendingDays":[7,11]}),
    "NoxoX", dynamic({"siteId": "4", "fileCount": "4", "pendingDays":[1,4,3,11]})
]
| mvexpand x = customDimensions.pendingDays to typeof(long)
| invoke arraySum()

// or

datatable (Operation_id:string, customDimensions:dynamic)
[
    "MTFfq", dynamic({"siteId": "1", "fileCount": "3", "pendingDays":[15,10,11]}),
    "LXVjk", dynamic({"siteId": "2", "fileCount": "1", "pendingDays":[3]}),
    "jnySt", dynamic({"siteId": "3", "fileCount": "2", "pendingDays":[7,11]}),
    "NoxoX", dynamic({"siteId": "4", "fileCount": "4", "pendingDays":[1,4,3,11]})
]
| project Operation_id, sum = series_stats_dynamic(customDimensions.pendingDays)["avg"] * array_length(customDimensions.pendingDays)

Some references for operators/functions used above:

*

*series_stats_dynamic

*array_length

*mvexpand


text:
Q: Change Keyboard in XCUITest/Simulator I want to change the keyboard language programatically for my XCUITests to try various different keyboards. I've tried:
XCUIApplication().launchArguments += ["-AppleLanguages", "(fr)"]
XCUIApplication().launchArguments += ["-AppleLocale", "fr_FR"]

But this only changes language and locale, but it still keeps simulator default keyboard. I know I could probably do it by going to the settings app (inside of the UITest) and just change keyboard, but I'd like to do it as an input argument or similar.
I also don't want to have all keyboard languages installed on the simulator at the same time, only the one language I choose.
How can I accomplish this?

A: Since you do it in Simulator, you can access the entire macOS disk space, including Simulator support files.
Each simulator has its own setting located in
$HOME/Developer/CoreSimulator/Devices/SIMULATOR_ID/data/Library/Preferences/.GlobalPreferences.plist
In this file, you can change AppleKeyboards programmatically.

A: New path for .plist file to change properties of keyboard from Roman Zakharov's answer:
/Users/YOUR_USER/Library/Developer/CoreSimulator/Devices/YOUR_SIMULATOR_ID/data/Library/Preferences/com.apple.keyboard.preferences.plist
Simulator ID can be found from Xcode: Window -> Devices and Simulators -> Simulators. The Identifier value is the UDID.


text:
Q: Using jQuery to trigger a method on a different HTML element I am writing a JavaScript behavior that will create a CSS-sprite button automatically, with no need for any custom CSS. My first question is: has this been done before? It seems an obvious idea, but I haven't found anything or I'm looking in the wrong places.
I can get the script to work when the user presses the button itself. What I am failing to do is to set the state of one button when the user clicks on another. (For radiobuttons, this is important :)
I've uploaded a page showing my progress so far.
I use...
    $(image).on("setFrame", this.setFrame);
... to add a setFrame method to an image, and then I create a plugin to trigger that method:
    (function($){
      /* A plugin to trigger a setFrame() method on a different
       * element than the one that was clicked.
       */
      $.fn.setImageFrame = function(frame) {
        return this.each(function() {
          console.log(this);
          // Q. Nothing happens on the next line. Why not?
          $(this).trigger('setFrame', frame);
        });
      };
    })( jQuery );

The call to .trigger() does nothing.
For bonus points, how can I test whether the setFrame method is set on the image? I've seen different solutions, but none that I have tested gives me a positive result.
EDIT: The problem was that the setFrame method is attached to an img element, and the call t trigger() was sent to its parent div element.


text:
Q: What is this `@sp` syntax in this quick sort code for scala? I am trying to understand this quick sort code from the following repo
  object QuickSort {
    @inline final def limit: Int = 16

    final def sort[@sp A:Order:ClassTag](data:Array[A]): Unit = qsort(data, 0, data.length - 1)

    final def qsort[@sp A](data:Array[A], left: Int, right: Int)(implicit o:Order[A], ct:ClassTag[A]): Unit = {

      if (right - left < limit) return InsertionSort.sort(data, left, right + 1)

      val pivot = left + (right - left) / 2
      val next = partition(data, left, right, pivot)
      qsort(data, left, next - 1)
      qsort(data, next + 1, right)
    }

    final def partition[@sp A](data:Array[A], left:Int, right:Int, pivot:Int)(implicit o:Order[A], ct:ClassTag[A]): Int = {

      val value = data(pivot)

      //swap(pivot, right)
      var tmp = data(pivot); data(pivot) = data(right); data(right) = tmp

      var store = left
      var i = left
      while (i < right) {
        if (o.lt(data(i), value)) {
          //swap(i, store)
          tmp = data(i); data(i) = data(store); data(store) = tmp
          store += 1
        }
        i += 1
      }
      //swap(store, right)
      tmp = data(store); data(store) = data(right); data(right) = tmp
      store
    }
  }

What is the purpose of [@sp A] ? I know [A] syntax is for generics, but what does adding @sp do? Can someone shed some insight on this?
Thanks

A: @sp is an alias for @specialized that is defined in the spire package object.
We are using specialization a lot in spire, so having to write @specialized or renaming in imports got too tedious.
Note that the definitions from the spire package object will only be visible form subpackages if you have individual package statements.
So this works
package spire
package math

class Foo[@sp T]

Whereas this would not
package spire.math

class Foo[@sp T]

The same approach is used in the scala standard library. If you look at a class like scala.collection.immutable.Set, note that the package statement is done in three parts
package scala
package collection
package immutable


text:
Q: How do I create a network connection with other computers (JAVA)? I'm developing a game that can be played with computer or versus other players. The GUI is Swing but irrelevant for the matter. My question is : how do I connect with other players in a network?
I am familiar with terms like client / server, sockets etc, and i can write a basic client/server program, but it can only be run from ONE computer. I don't know how to connect to this network from a computer, say, half way across the country.

A: You are probably setting behind a router which hides your local IP address from the rest of the world (look for NAT for more info on this). Basically, the world only sees your YOUR_ROUTER_IP, your router takes care of carrying all IP packets from the outside world to you and vice versa. You will need to change your router settings so that your computer/server gets the router ip address. This way you can access your server application from anywhere in the world by using simple socket operations.
I hope this helps.

A: I like to use Kryonet for network connections, it works very well and has really good documentation.

A: You indicated you know how to use client and server sockets, so I'll just throw out there that you ought to try connecting with "real" ip address instead of localhost (127.0.0.1). Take two machines on your local network, get the IP address of the "server" machine and use that address to connect from the client.
This will work all the way around the world, except for the fact that you are likely behind some Network Address Translation (NAT) firewalls and will likely need to "open" or "forward" the ports you need. If you need more information on NAT, google and serverfault will be pretty helpful.

A: If your client and server is located on the same machine, then you can use loopback address(ie 127.0.0.1), in LAN you can do with private ip addresses
Private ip address for LAN

CLASS A - 10.x.x.x
CLASS B - 172.16.0.0 - 172.31.255.255
CLASS C - 192.168.0.0 - 192.168.255.255
you can use this for LAN environment
For connecting someone over the internet, you will need Public ip addresses.
Address apart from the private ip in every range are public address.
Now if you have a server which is having a static ip then it wont be a problem for the client to access it anywhere from the world over internet.
But if its over a LAN , and accessing the internet from a gateway, then there will be a NAT, then you will need to set the inbound and outbound traffic rules at the gateway, for letting the client access the server.


text:
Q: Set different markersizes for plotting pandas dataframe with matplotlib I want to decrease the markersize for every line I plot with my dataframe. I can set a unique markersize like that:
df = pd.read_csv(file_string, index_col=0)
df.plot(style=['^-','v-','^-','v-','^-','v-'], markersize=8)

I set a different style for every line (I new that there are 6), now I wanted to do the same with the sizes, this doesn't work:
df = pd.read_csv(file_string, index_col=0)
df.plot(style=['^-','v-','^-','v-','^-','v-'], markersize=[16,14,12,10,8,6])

How can I achieve something like this?

A: The above earlier answer works fine for a small number of columns. If you don't want to repeat the same code many times, you can also write a loop that alternates between the markers, and reduces the marker size at each iteration. Here I reduced it by 4 each time, but the starting size and amount you want to reduce each marker size is obviously up to you.
df = pd.DataFrame({'y1':np.random.normal(loc = 5, scale = 10, size = 20),
                   'y2':np.random.normal(loc = 5, scale = 10, size = 20),
                   'y3':np.random.normal(loc = 5, scale = 10, size = 20)})
size = 18
for y in df.columns:
    col_index = df.columns.get_loc(y)
    if col_index % 2 == 0:
        plt.plot(df[y], marker = '^', markersize = size)
    else:
        plt.plot(df[y], marker = 'v', markersize = size)
    size -= 4
plt.legend(ncol = col_index+1, loc = 'lower right')

A: markersize accepts only a float value not a l ist acording to the documentation.
You can use matplotlib instead, and plot each line independently
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv(file_string, index_col=0)
plt.plot(df[x], df[y1],markersize=16,'^-')
plt.plot(df[x], df[y2],markersize=14,'v-')

#and so on...

plt.show()


text:
Q: How to react to firebase auth email change I'd like a safe way to update a user document in Firestore when a user changes their email address.
At the moment, the only way I can see to do it is by doing it client-side, after the user.updateEmail() is successfully called, but that call could fail for a variety of reasons, resulting in a mismatch between emails on the auth & the user's doc.
I was expecting to find a firebase function like functions.auth().onChange() but nothing like that seems to exist.


text:
Q: Same permalink structure for all post types? We have a pretty complicated site that has a lot of different custom post types.  Each of the post types has an array of custom fields and stuff like that.  Also I have added the ability to organize all of our custom posts using the "posts" categories and tags.  I am thinking about changing the permalink structure to allow "category" to be displayed before postname.
Are there any issues with across the board sharing permalink structure across post types?
Therefore we might have post types - product-specs, product-docs, product-installation.
And I would see permalink structure:
/products/product1/productspecs1
/products/product1/productdocs1
/products/product1/productinstallation1
/products/product2/productspecs1...
Given that this structure is OK is there an easy way to make all custom post types default to the WP settings for permalinks?  ** Note that I understand how to register a different permalink structure for a given custom post type (which has been answered many times here) but not how to make any new custom post type default to the WP settings - in case custom post types are made without me knowing.

A: There are definitely some issues, I'd question what exactly you'd gain from having the same structure for all.
You could create conflicts if you have two different posts with the same slug. There would be nothing enforcing slug uniqueness between post types, so you'd have to write that code yourself to run whenever a post is saved or updated.
You'll need a post_type_link filter to generate the URLs with categories when any permalink API function is called.
You'll have to modify the queries via pre_get_posts to have WordPress look in all post types for the requested slug. I'm not sure what performance impact this may have, as it's an IN on multiple values rather than a straight post_type =.
As for the structure when you register the post type- the rules you'd need would already exist (they were created for the built in post type), so having more of the same rules generated is redundant. In that case it's probably best to just set rewrite to false for all post types.
Personally I would make the leading products segment unique for each type. You can still have the categories in all of them.


text:
Q: JavaScript - Least finite number What is the least finite number (i.e., the negative number furthest away from zero) in JavaScript? Is it -Number.MAX_VALUE?
I'm only concerned with primitive numbers, not BigInts.
Thanks in advance!

A: FINITE NUMBER, in that case it is (Number.MAX_VALUE * -1)
Number type is a signed integer.
which is
-1.7976931348623157e+308

A: The smallest finite number is -Number.MAX_VALUE = -1.7976931348623157e+308
The smallest infinite number is Number.NEGATIVE_INFINITY. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY


text:
Q: persistently replicating RDS MySQL database to external slave AWS now allows you to replicate data from an RDS instance to an external MySQL database.
However, according to the docs:

Replication to an instance of MySQL running external to Amazon RDS is only supported during the time it takes to export a database from a MySQL DB instance. The replication should be terminated when the data has been exported and applications can start accessing the external instance.

Is there a reason for this?  Can I choose to ignore this if I want the replication to be persistent and permanent?  Or does AWS enforce this somehow?  If so, are there any work-arounds?

A: It doesn't look like Amazon explicitly states why they don't support ongoing replication other than the statement you quoted.  In my experience, if AWS doesn't explicitly document a reason for why they do something then you're not likely to find out unless they decide to document it at a later time.
My guess would be that it has to do with the dynamic nature of Amazon instances and how they operate within RDS.  RDS instances can have their IP address change suddenly without warning. We've encountered that on more than one occasion with the RDS instances that we run.  According to the RDS Best Practices guide :

If your client application is caching the DNS data of your DB instances, set a TTL of less than 30 seconds. Because the underlying IP address of a DB instance can change after a failover, caching the DNS data for an extended time can lead to connection failures if your application tries to connect to an IP address that no longer is in service.

Given that RDS instances can and do change their IP address from time to time my guess is that they simply want to avoid the possibility of having to support people who set up external replication only to have it suddenly break if/when an RDS instance gets assigned a new IP address.  Unless you set the replication user and any firewalls protecting your external mysql server to be pretty wide open then replication could suddenly stop if the RDS master reboots for any reason (maintenance, hardware failure, etc). From a security point of view, opening up your replication user and firewall port like that are not a good idea.


text:
Q: how to avoid page to scroll upon clicking on asp.net radio button I have an asp.net radio button and on clicking that I call a method, when user clicks on that radio button, the system scrolls up to the top of page, In order to avoid it I have used different solutions mentioned by other people like the one below, but the problem is this that the page scrolls to the top of page and then returns to its original location. Is there any solution to prevent scrolling ?
This is the source code:
<asp:TableCell>
    <asp:RadioButton ID="rbSubscription" runat="server"  OnCheckedChanged="HighlightSubscription" AutoPostBack="true"/>
</asp:TableCell>

<%--Script to avoids Page Scroll--%>
<asp:HiddenField runat="server" ID="hfPosition" Value="" />
<script type="text/javascript">
    $(function () {
        var f = $("#<%=hfPosition.ClientID%>");
        window.onload = function () {
            var position = parseInt(f.val());
            if (!isNaN(position)) {
                $(window).scrollTop(position);
            }
        };
        window.onscroll = function () {
            var position = $(window).scrollTop();
            f.val(position);
        };
    });
</script>


text:
Q: javax.faces.el.PropertyNotFoundException - Base is null: item I'm getting this "Base is null: item" jsf1.1 error in datatable that I just couldn't quite figure out.  It is a two level datatable and the error is happening on the 2nd level datatable.  The first level datatable is bind to the value of ArrayList deviceListDeviceReferences.  In this datatable, it has a column that contains another datatable.  This 2nd level datatable is bind to the value of ArrayList holderNameMasks.  This value it retrived from DeviceReferenceJTO, which is basically the row item from the first datatable.
Below is what a snippet of the html:
<h:dataTable border="0" cellspacing="0"
    value="#{deviceReferenceBean.deviceListDeviceReferences" var="item"
    rendered="#{not empty deviceReferenceBean.deviceListDeviceReferences }"
    binding="#{deviceReferenceBean.deviceListDeviceReferencesTable}"
>
    <h:column>
        <h:outputText value="Holder Name:" />
        <!--  device heading -->
        <h:outputText value="#{item.deviceLabel }" styleClass="DeviceReferenceTitleBarBorder" style="width:100%; height:30px; background-color:#f9f9f9"/>
        <!-- holder name -->
        <h:panelGrid columns="2" rendered="#{item.hasHolderNameMasks}" >
            <h:outputText value="Holder Name:" />
            <h:dataTable border="0" cellspacing="0"
                value="#{item.holderNameMasks}" var="holderMaskItem"
                rendered="#{not empty deviceReferenceBean.deviceListDeviceReferences and item.hasHolderNameMasks}"
                binding="#{item.holderNameMasksTable}"
            >
                <h:column>
                    <h:outputText value="#{holderMaskItem.fieldLabel}" />
                </h:column>
                <h:column>
                    <h:panelGrid columns="1">
                        <h:inputText value="#{holderMaskItem.fieldValue}" />
                        <h:outputText value="#{holderMaskItem.instruction }" rendered="#{holderMaskItem.hasInstruction"/>
                    </h:panelGrid>
                </h:column>
            </h:dataTable>
        </h:panelGrid>
    </h:column>
</h:dataTable>

Below is what the component looks like:
<HtmlForm enctype="application/x-www-form-urlencoded" id="_idJsp323" rendered="true" styleClass="MAForm" submitted="false" transient="false">

    <HtmlDataTable border="0" cellspacing="0" first="0" id="_idJsp324" rendered="#{not empty deviceReferenceBean.deviceListDeviceReferences }=true" rowIndex="-1" rows="0" transient="false" var="item" binding="#{deviceReferenceBean.deviceListDeviceReferencesTable}">

        <UIColumn id="_idJsp325" rendered="true" transient="false">

            <HtmlOutputText escape="true" id="_idJsp326" rendered="true" style="width:100%; height:30px; background-color:#f9f9f9" styleClass="DeviceReferenceTitleBarBorder" transient="false"/>

            <HtmlPanelGrid border="-2147483648" columns="2" id="_idJsp327" rendered="#{item.hasHolderNameMasks}=true" transient="false">

                <HtmlOutputText escape="true" id="_idJsp328" rendered="true" transient="false" value="Holder Name:"/>

            </HtmlPanelGrid>

        </UIColumn>

    </HtmlDataTable>

</HtmlForm>

A: The culprit is here:
<h:dataTable
    binding="#{item.holderNameMasksTable}"
>

The binding (and id) attributes of UI components are resolved during view build time (that moment when JSF parses the XHTML file into a component tree). However, the #{item} is only available during view render time (that moment when JSF encodes the component tree to HTML output). Thus, there where you're using binding="#{item.xxx}" would always fail because the #{item} is null. Note that this is exactly what the exception is trying to tell you.
You've 2 options:

*

*Get rid of binding attribute altogether.

*Bind to #{deviceReferenceBean} instead. It's available during view build time.

See also:

*

*JSTL in JSF2 Facelets... makes sense? - the same answer applies here.


text:
Q: How the sorting method of integer array works ? JS var anArray = [ 5, 4, 8 , 1, 3] ;

anArray.sort(function (a,b){return a - b});

1) Can someone run me through how JavaScript will execute the sort method with function that is passed as a parameter ?

*

*It will compare 5 with 4 then because it's positive, 4 will be before 5. Then it will compare 5 with every other number but 1 and 3 are also smaller than 5. So how java script know which position to put them before 5?

*then it will compare 4 with every other number and 8 with every other number etc...
how java script do this? I want to do it with pen and paper.
2) why the function that is passed as an parameter is nameless ?
thank you.

A: *

*Exactly how the comparator function will be called — that is, the sequence of values passed in — is not defined by the specification of the language. It completely depends on the particular JavaScript implementation and (probably) on the values in the array being sorted. Suffice to say that the sorting algorithm calls your function when it wants to compare two numbers, and that's that.The function is expected to return a value that's negative, zero, or positive, indicating that the ordering of the two numbers should be that the first one comes first, that either can come first, or that the second one should come first. A quick way to do that is to just subtract the second number from the first.

*The function in your sample code is an anonymous function. It needs no name because it will be bound to a symbol in the receiving function as a result of the function call itself. You can give the function a name if you want to.


text:
Q: How to increase /boot partition size when installing Ubuntu 14.04 using the "use entire disk and set up encrypted LVM" option? How to edit the size of the /boot partition when installing Ubuntu?
Using the guided partitioning option "use the entire disk and set up encrypted LVM" results is a /boot partition which is only 236MB.

A: Guided partition sizes are specified in /lib/partman/recipes[-arch]/*. The file format is here: http://ftp.dc.volia.com/pub/debian/preseed/partman-auto-recipe.txt
To increase the /boot size, change the maximum size (third number) in the boot section of the default recipe: sudo nano /lib/partman/recipes/30atomic
...

128 512 256 ext2
    ...
    mountpoint{ /boot } .

 ....

Change the 256 to a something bigger and save. Then, start the installer and use the guided option.

A: Use manual partitioning and try the steps I outline in this solution. The process I use is for Ubuntu 16.04.2 though. With manual partitioning, I was able to create a boot partition 1GB in size with no problem. As an added benefit, you can also create additional logical volumes for /home or any other partition you might want to keep separate.


text:
Q: Fail to run Java Spark on EMR I got a simple Java Spark program running locally, but it failed on Amazon EMR. I tried both AMI 3.2.1 and AMI 3.3.1, all same errors. The failing code is at the JavaSparkContext below :
public static void main(String[] args) throws Exception {

    if (args.length < 1) {
        System.err.println("Usage: JavaWordCount <file>");
        System.exit(1);
    }

    SparkConf sparkConf = new SparkConf().setAppName("JavaWordCount");
    sparkConf.setMaster("local").set("spark.executor.memory", "1g");
    JavaSparkContext ctx = new JavaSparkContext(sparkConf);
        :

The error I got is:
   Exception in thread "main" java.lang.NoSuchMethodError: scala.collection.immutable.HashSet$.empty()Lscala/collection/immutable/HashSet;
        at akka.actor.ActorCell$.<init>(ActorCell.scala:305)
        at akka.actor.ActorCell$.<clinit>(ActorCell.scala)
        at akka.actor.RootActorPath.$div(ActorPath.scala:152)
        at akka.actor.LocalActorRefProvider.<init>(ActorRefProvider.scala:465)
        at akka.remote.RemoteActorRefProvider.<init>(RemoteActorRefProvider.scala:124)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at akka.actor.ReflectiveDynamicAccess$$anonfun$createInstanceFor$2.apply(DynamicAccess.scala:78)
        at scala.util.Try$.apply(Try.scala:191)
        at akka.actor.ReflectiveDynamicAccess.createInstanceFor(DynamicAccess.scala:73)
        at akka.actor.ReflectiveDynamicAccess$$anonfun$createInstanceFor$3.apply(DynamicAccess.scala:84)
        at akka.actor.ReflectiveDynamicAccess$$anonfun$createInstanceFor$3.apply(DynamicAccess.scala:84)
        at scala.util.Success.flatMap(Try.scala:230)
        at akka.actor.ReflectiveDynamicAccess.createInstanceFor(DynamicAccess.scala:84)
        at akka.actor.ActorSystemImpl.<init>(ActorSystem.scala:550)
        at akka.actor.ActorSystem$.apply(ActorSystem.scala:111)
        at akka.actor.ActorSystem$.apply(ActorSystem.scala:104)
        at org.apache.spark.util.AkkaUtils$.createActorSystem(AkkaUtils.scala:104)
        at org.apache.spark.SparkEnv$.create(SparkEnv.scala:152)
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:202)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:53)
        at examples.JavaSparkProfile.main(JavaSparkProfile.java:54)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:212)

Does anyone have any idea?
Thanks a lot!

A: Check scala version. Select 2.10.*


text:
Q: Getting order by order id in Magento I have custom controller that knows order id, is it possible to get order by order id in custom controller?

A: This is how I solved this:
    $orderId = $_GET['orderId'];
    $order = Mage::getModel('sales/order');
    $order->load($orderId);


text:
Q: I am not understanding this math about alternate angles This is the math. This is the given solution :-
This
and this
Now, my problem here is, $\angle ABC$ and $\angle DAC$ are supposed to be alternate angles here, and thus equal.
But as far as I know, angles are alternate only when a transversal intersects two parallel lines.
But in the given figure, there are no such transversals or parallel lines.
So how can we prove that, $\angle ABC = \angle DAC$?

A: I think what the solution meant to refer to was the alternate segments theorem:

The angle between a chord of a circle and a line tangent to the circle at one end of the chord is equal to the angle of the alternate segment.

The angle $\angle ABC$ is the angle in "the alternate segment" because it is the angle subtended by the chord $AC$ at $B,$ because $B$ is in one of the segments into which the chord $AC$ cuts the circle, and because the segment $B$ is in is the one that is not included in the angle $\angle DAC$ (making it the "alternate" segment).


text:
Q: Consuming file sent via PUT method in rails 3.2 I am integrating with a 3rd party API (echosign) and one of the things I need to specify is a callbackURL.
"A publicly accessible url to which EchoSign will do a HTTP PUT operation with the final signed PDF. HTTP authentication is supported using standard embedded syntax - i.e. http://username:password@your.server.com/path/to/file. EchoSign can also ping your system using HTTP GET every time there is a new agreement event. Please contact support@echosign.com if you wish to use this option."
How would this work in rails?
I was going to expose a controller method. Would this need to be PUT method?
How would I access the contents of the file?

A: Yes, you need to provide a put route to an action that will consume the upload.
Check http://guides.rubyonrails.org/form_helpers.html#what-gets-uploaded for the upload action
Enter s.th. like the following to your config/routes.rb to add a PUT Route to the eccording controller..
match '/mycallbackurl' => 'MyEchoController#upload', :via => :put


text:
Q: Distributing Giving out Quarters Suplus and Shortage Problem Amy, Betty, and Chloe have some quarters. Amy gives some of her quarters to Betty and Chloe, making their quarters doubled. Then Betty dos the same thing, making Amy and Chloe's quarters doubled. And Chloe does the same thing, making Amy's and Betty's quarters doubled. After all these, the number of quarters of each one is 8. So in the beginning, how much quarters does everyone have?
The equations that I get seem overly complicated, so I need the formula for this kind of problem. I got
A=Amy's amount
B=Betty's amount
C=Chloe's amount
$(((A-B-C)2)2)$=8
$((2B-(A-B-C))2)=8$
$4C-(2[A-B-C])-2B-[A-B-C]=8$

A: I would not use equations: work backwards. As a start, note that before C's gift, A and B had $4$ each, and C had $16$. Continue.


text:
Q: mat-selection-list in reactive form Has anyone successfully used mat-selection-list with Angular's reactive forms.
When I try to use it I am getting

values.map is not a function

below is my html code:
<div class="form-group" [formGroup]="activityForm">
      <mat-selection-list formControlName="activity" (selectionChange)="onActivitySelected($event)">
        <mat-list-option *ngFor="let act of activities"
                         [value]="act.id">
          {{act.name}}
        </mat-list-option>
      </mat-selection-list>
</div>

and this is my form definition:
this.formGroup1 = this.fb.group({
      destinationForm: this.fb.group({
        destination: [null, Validators.required]
      }),
      activityForm: this.fb.group({
        activity: [[''], Validators.required]
      }),
      travellerForm: this.fb.group({
        firstName: ['', Validators.required],
        lastName: '',
      })
});

could someone help with this issue please
stack trace:

A: this.formGroup1 = this.fb.group({
      destinationForm: this.fb.group({
        destination: [{value: null, disabled: false}, [Validators.required]]
      }),
      activityForm: this.fb.group({
        activity: [{value: '', disabled: false}, [Validators.required]]
      }),
      travellerForm: this.fb.group({
        firstName: [{value: '', disabled: false}, [Validators.required]]
        lastName: [{value: '', disabled: false}]
      })
});


text:
Q: ReactJS with Fetch on older browsers I am implementing React JS, with Webpack and Babel. However, I am having trouble getting Fetch to work with IE 11.
I have the following in my .babelrc file:
{
  "presets" : ["env", "stage-0", "react"]
}

and the following in my webpack.config.js file:
var webpack = require('webpack');
var path = require('path');

var DIST_DIR = path.resolve(__dirname, 'dist');
var SRC_DIR = path.resolve(__dirname, 'src');

var config = {
  entry: {
    bundle: [
      'babel-polyfill',
      SRC_DIR + '/app/index.js',
    ]
  },
  output: {
    path: DIST_DIR + '/public/js',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        include: SRC_DIR,
        loader: 'babel-loader'
      }
    ]
  }
};

module.exports = config;

From my understanding implementing babel-preset-env, stage-0, and babel-polyfill should have allowed for the Fetch API to be transpiled into something older browsers could understand. Is there something else that I am missing?

A: fetch isn't part of EcmaScript but its part of the web platform. Babel is only a compiler to write the latest Javascript. If you want to use fetch in older browsers you need a polyfill like this one
Fetch API: read more

A: fetch must be made available by the browser you use and is not included in babel-polyfill. If your browser doesn't support fetch, you can either fall back to using XMLHttpRequest or use a polyfill such as isomorphic-fetch.


text:
Q: Need help optimizing a slow Postgres query It feels like we have all appropriate indexes created, but something feels off that it takes so long. It runs a sequential scan on snippets despite there being indexes on both fields it's filter on.
There's 4.7M records in snippets and 5.1M records in abuse_types_snippets.
SELECT count(1)
    FROM snippets
    WHERE snippets.id IN (
        SELECT abuse_types_snippets.snippet_id
        FROM abuse_types_snippets
        WHERE abuse_types_snippets.abuse_type_id = 1047122679
    )
    AND snippets.status IN (3,4,5)
    AND snippets.created_at BETWEEN '2018-01-01' AND '2018-08-22'

Aggregate  (cost=1053185.69..1053185.70 rows=1 width=0) (actual time=52116.440..52116.441 rows=1 loops=1)
  ->  Hash Join  (cost=40922.22..1052044.88 rows=456325 width=0) (actual time=3779.600..51979.138 rows=500147 loops=1)
        Hash Cond: (snippets.id = abuse_types_snippets.snippet_id)
        ->  Seq Scan on snippets  (cost=0.00..948983.91 rows=3321771 width=4) (actual time=0.009..45231.634 rows=3277699 loops=1)
              Filter: ((created_at >= '2018-01-01 00:00:00'::timestamp without time zone) AND (created_at <= '2018-08-22 00:00:00'::timestamp without time zone) AND (status = ANY ('{3,4,5}'::integer[])))
              Rows Removed by Filter: 1502893
        ->  Hash  (cost=30179.02..30179.02 rows=654816 width=4) (actual time=3778.402..3778.402 rows=668040 loops=1)
              Buckets: 16384  Batches: 8  Memory Usage: 3283kB
              ->  Index Only Scan using index_abuse_types_snippets_on_abuse_type_id_and_snippet_id on abuse_types_snippets  (cost=0.43..30179.02 rows=654816 width=4) (actual time=0.916..3457.052 rows=668040 loops=1)
                    Index Cond: (abuse_type_id = 1047122656)
                    Heap Fetches: 398150
Planning time: 0.319 ms
Execution time: 52117.034 ms

Added, alternative approach (join instead of sub-select, no better performance):
EXPLAIN ANALYZE SELECT count(1)
    FROM snippets
    join abuse_types_snippets on abuse_types_snippets.snippet_id = snippets.id
    WHERE abuse_types_snippets.abuse_type_id = 1047122656
    AND snippets.status IN (3,4,5)
    AND snippets.created_at BETWEEN '2018-01-01' AND '2018-08-22'

Aggregate  (cost=1061553.74..1061553.75 rows=1 width=0) (actual time=53597.015..53597.015 rows=1 loops=1)
  ->  Hash Join  (cost=1003482.48..1060412.92 rows=456325 width=0) (actual time=49697.488..53445.218 rows=500147 loops=1)
        Hash Cond: (abuse_types_snippets.snippet_id = snippets.id)
        ->  Index Only Scan using index_abuse_types_snippets_on_abuse_type_id_and_snippet_id on abuse_types_snippets  (cost=0.43..30183.02 rows=654816 width=4) (actual time=0.977..3060.787 rows=668108 loops=1)
              Index Cond: (abuse_type_id = 1047122656)
              Heap Fetches: 396932
        ->  Hash  (cost=948983.91..948983.91 rows=3321771 width=4) (actual time=49233.187..49233.187 rows=3277699 loops=1)
              Buckets: 16384  Batches: 64  Memory Usage: 1819kB
              ->  Seq Scan on snippets  (cost=0.00..948983.91 rows=3321771 width=4) (actual time=0.010..47723.895 rows=3277699 loops=1)
                    Filter: ((created_at >= '2018-01-01 00:00:00'::timestamp without time zone) AND (created_at <= '2018-08-22 00:00:00'::timestamp without time zone) AND (status = ANY ('{3,4,5}'::integer[])))
                    Rows Removed by Filter: 1503495
Planning time: 0.324 ms
Execution time: 53597.528 ms

Table schema:
CREATE TABLE "public"."snippets" (
    "id" int4 NOT NULL DEFAULT nextval('snippets_id_seq'::regclass),
    "status" int4 DEFAULT 0,
    "provider" varchar NOT NULL,
    "score" jsonb DEFAULT '{}'::jsonb,
    "connection_id" int4,
    "child_id" int4,
    "flagged" bool DEFAULT false,
    "created_at" timestamp(6) NOT NULL,
    "updated_at" timestamp(6) NOT NULL,
    "posted_at" timestamp(6) NOT NULL,
    "other_id" text,
    "other_name" text,
    "content_hash" varchar,
    "locked_at" timestamp(6) NULL,
    "activity_ids_for_dynamodb" varchar[] DEFAULT '{}'::character varying[],
    "filter_media" bool DEFAULT false,
    "severity" float8 DEFAULT 1.0,
    "migrated" bool DEFAULT false,
    "notified_authorities_at" timestamp(6) NULL,
    CONSTRAINT "snippets_pkey" PRIMARY KEY ("id") NOT DEFERRABLE INITIALLY IMMEDIATE,
    CONSTRAINT "fk_rails_2c8d6dd3ab" FOREIGN KEY ("connection_id") REFERENCES "public"."connections" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE,
    CONSTRAINT "fk_rails_bf28d24ffc" FOREIGN KEY ("child_id") REFERENCES "public"."children" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE
)
WITH (OIDS=FALSE);
ALTER TABLE "public"."snippets" OWNER TO "bark";
CREATE INDEX "index_snippets_on_child_id" ON "public"."snippets" USING btree(child_id ASC NULLS LAST);
CREATE INDEX "index_snippets_on_child_id_and_status" ON "public"."snippets" USING btree(child_id ASC NULLS LAST, status ASC NULLS LAST);
CREATE INDEX "index_snippets_on_connection_id" ON "public"."snippets" USING btree(connection_id ASC NULLS LAST);
CREATE INDEX "index_snippets_on_content_hash" ON "public"."snippets" USING btree(content_hash ASC NULLS LAST);
CREATE INDEX "index_snippets_on_created_at" ON "public"."snippets" USING btree(created_at ASC NULLS LAST);
CREATE INDEX "index_snippets_on_created_at_and_status" ON "public"."snippets" USING btree(created_at ASC NULLS LAST, status ASC NULLS LAST);
CREATE INDEX "index_snippets_on_locked_at" ON "public"."snippets" USING btree(locked_at ASC NULLS LAST);
CREATE INDEX "index_snippets_on_posted_at" ON "public"."snippets" USING btree(posted_at ASC NULLS LAST);
CREATE INDEX "index_snippets_on_status" ON "public"."snippets" USING btree(status ASC NULLS LAST);

CREATE TABLE "public"."abuse_types_snippets" (
    "abuse_type_id" int4 NOT NULL,
    "snippet_id" int4 NOT NULL,
    CONSTRAINT "fk_rails_4e19f07aa3" FOREIGN KEY ("abuse_type_id") REFERENCES "public"."abuse_types" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE,
    CONSTRAINT "fk_rails_c0ca4cc2fc" FOREIGN KEY ("snippet_id") REFERENCES "public"."snippets" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE
)
WITH (OIDS=FALSE);
ALTER TABLE "public"."abuse_types_snippets" OWNER TO "bark";
CREATE INDEX "index_abuse_types_snippets_on_abuse_type_id" ON "public"."abuse_types_snippets" USING btree(abuse_type_id ASC NULLS LAST);
CREATE UNIQUE INDEX "index_abuse_types_snippets_on_abuse_type_id_and_snippet_id" ON "public"."abuse_types_snippets" USING btree(abuse_type_id ASC NULLS LAST, snippet_id ASC NULLS LAST);
CREATE INDEX "index_abuse_types_snippets_on_snippet_id" ON "public"."abuse_types_snippets" USING btree(snippet_id ASC NULLS LAST);

A: As you say, the issue here is the sequential scan that runs despite of indexes. This happens when the query planner deems there is not enough to be gained by using an index.
It should be using the index index_snippets_on_created_at_and_status when selecting the data, but it doesn't, most likely due to the wrong cardinality. In short, you need to switch places on status and created_at
In case you don't know how a btree index works, here is a (bad) attempt to explain it.
the index is laid out like a tree, with the first column as the top leaf (root/stem), and the second column as child leafs (or branches) to that leaf. This means that when going through the index, it looks up the first column, and then picks out the child that matches the second column.
Assuming that you have a timestamp in the created_at column, and say 5 different statuses, there are 864000 possible positions in the top row per day that it needs to look up, and then filter out those rows that do not match the status. This would incur a heavy cost, especially since you're including most of the table already in the selection.
On the other hand, if status would be first, it would only have to look up 3 positions in the index, and then do a range scan on the second column, which would have a lower cost.
So, changing the positions might help, but it is of course no guarantee. Since you are selecting 3.2M rows out of 4.7M, the planner might chose not to use the index anyway since the main cost might be the actual fetching of the rows.
If that happens, you could try to include id in the index as well (as the last column) since then the planner might be able to use that to filter from abuse_types_snippets without looking up the rows until the last minute.


text:
Q: Why does Firefox still make connections to server although the HTTP resources are shown as "cached"? I am confused by the way Firefox shows loaded resources as cached but then I can see the browser issues new DNS query for the domain name and contact the HTTP server again.
Below is a simple example of this behavior. I visited https://example.com then reload the webpage. As expected, the loaded resources are shown as cached. But, at the same time, I run tcpdump in background and notice that the browser issues DNS query for example.com again and also connects to the HTTP server after getting the DNS response.

Is this an expected behavior or am I missing something?
Thank you for reading my question <3

A: Firefox has cached your object and is revalidating the object with the origin server. You can tell this because it sent the If-Modified-Since: and Cache-Control: request headers.
Firefox will generally revalidate cached objects in two situations:

*

*The cached object is stale, as determined by the Cache-Control: and Expires: response headers that were sent with the object when it was previously cached.

*You hit Reload.

You can see that the web server sent a 304 Not Modified response, and thus Firefox served the existing cached object.

HTTP caching can get quite complex. To learn all about it, spend an evening studying RFC 7234.


text:
Q: Is there a confirmed way to add a product to the cart using URL in magento 1.8? There are loads of articles and posts about doing this in previous versions using several different URL strings, all of which none work in Magento 1.8
Has anyone actually figured out a way to do it yet?
For example, this is listed on the Magento Wiki and was added in 2010:
http://www.magentocommerce.com/wiki/4_-_themes_and_template_customization/catalog/adding_a_product_to_the_cart_via_querystring
/path/to/app/checkout/cart/add?product=[id]&qty=[qty]

However when clicked, this link just refreshes the cart.
Just incase anyone wants to see how I'm trying to code it:
<button type="button" title="Add Loan Phone" class="button" onclick="setLocation('URL HERE')">Add a Loan Phone (+£10)</button>

A: You can use the checkout's cart helper for that
echo (string)Mage::helper('checkout/cart')->getAddUrl($_product);

Make sure $_product is an instance of the class Mage_Catalog_Model_Product
So putting it all together as requested
<?php $_product = Mage::getModel('catalog/product')->load([product id]);?>

<button type="button" title="Add Loan Phone" class="button" onclick="setLocation('<?php echo (string)Mage::helper('checkout/cart')->getAddUrl($_product);?>')">Add a Loan Phone (+£10)</button>


text:
Q: What does "matriculated" mean in following para? The Doctor, seeing his client more attentive than alarmed,
was greatly surprised. He must be matriculated, said he to himself—
' A h ! ah!' added he aloud; 'you have been obliged to shave off the
lock. You have been prudent; however you need not have done so,
when putting yourself under my hands. The case is serious; but you
don't know what I have courage to do in a time of need.'
To understand this mistake of the Doctor's, it must be known,
that at that time, bravoes by profession, and villains of every kind,
used to wear a long lock of hair, which they drew over the face like
a visor on meeting any one.

A: This appears to be a case of mistranslation from the Italian. The quote is from The Betrothed (I Promessi Sposi) by Alessandro Manzoni. In the Project Gutenberg edition, this passage reads as follows:

The doctor, perceiving his new client more attentive than dismayed, marvelled greatly. "He must be enrolled as one of the bravoes," said he to himself; "Ah! ah!" exclaimed he, addressing Renzo, "you have shaved off the long lock! Well, well, it was prudent; but placing yourself in my hands, you need not have done so. The case is a serious one—you can have no idea how much resolution is required to conduct these matters wisely."
To understand this mistake of the doctor's, it should be known, that the bravoes by profession used to wear a long lock of hair, which they pulled over the face as a mask in enterprises that required prudence as well as strength.

I expect neither matriculated nor enrolled conveys the real Italian meaning well. My guess is that the original means he has taken part in some ceremony in which you join the bravos. It would be good to have somebody who knows Italian look at the original.
Finally, since Project Gutenberg offers for free a translation that appears from this passage to be much better than the one you are reading, you might want to consider reading the Project Gutenberg translation instead.


text:
Q: Run process in background as SU from Dockerfile This is my dockerfile:
FROM python:3.8

RUN useradd -m client && echo "client:client" | chpasswd

SHELL ["/bin/bash", "-c"]

RUN mkdir /execute
RUN mkdir /super
WORKDIR /super

COPY /run /super

RUN python supervisor.py & sleep 1

WORKDIR /execute

RUN chown -R client /execute/

USER client

supervisor.py is:
def run_supervisor():
    while True:
        filename = "/execute/" + "".join([random.choice(string.ascii_letters) for j in range(8)]) + ".txt"

        helper.execute(f"echo floose > {filename}")

        time.sleep(10)

#

run_supervisor()

Finally, I run the container with:
docker run --network host -it --entrypoint '/bin/bash' --privileged client_image:latest -c "bash /super/start_client.sh && /bin/bash"

My intention is for supervisor.py to continue running as root, while the user is logged in as user "client".
supervisor.py does run, as there is one randomly titled .txt file in /execute when the container starts.  However at some point during the start process it appears that the process is terminated.
How can I have supervisor.py continue running as root?


text:
Q: Dockerfile not creating selfsigned Cert I have the following Dockerfile.  It is supposed to create the selfsigned cert when I first build the image.  Then letsencrypt should auto renew it.  The issue that I am having is that the cert never gets created.  When I run the exact openssl command on the /etc/apache2/certificate directory manually it works, but something is off on Dockerfile.  When call the docker file I see that it creates the key in red letters, but never writes it to the dir.  What am I missing?
FROM php:7.4.3-apache
RUN apt-get update -y && apt-get install -y apt-utils libhtml-template-pro-perl default-mysql-client libtemplate-perl openssl
RUN docker-php-ext-install mysqli pdo pdo_mysql && docker-php-ext-enable pdo_mysql
RUN mkdir /ztp_data
RUN a2enmod ssl
RUN a2enmod rewrite
RUN mkdir /etc/apache2/certificate
RUN cd /etc/apache2/certificate
RUN openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out apache-certificate.crt -keyout apache.key -subj "/C=US/ST=GA/L=Atlanta/O=CompanyABC/CN=`hostname -f`"
RUN sleep 20
RUN service apache2 restart


text:
Q: How can I check if a string has one of the characters "\" ":" "/" "_"? I need a condition to return true or false if the string contains or not this characters.
if re.match('^*_|:|/|*$', code):
    raise VCompilerIllegalCharacterUsedError

-- this is not working as it should  work

A: Your regex pattern is slightly off and this is what you were most likely intending to do:
if re.search('[\/:_]', code):
    raise VCompilerIllegalCharacterUsedError

The regex pattern ^.*[\/:_].*$ would match any code having one of the characters back slash, forward slash, colon, or underscore.


text:
Q: Is there a way how can I specify Youtube search command? Is there a way how can I improve my script to stop returning me data from the same channel?
For example, I want my code to skip parsing video data from channels that were actually scraped yet and get me only one data result per one channel, not more.
youtube = build('youtube','v3',developerKey = api_key)

print(type(youtube))
pp = PrettyPrinter()
nextPageToken = ''

for x in range(1):
#while True:
    request = youtube.search().list(
        q='I stand with Ukraine',
        part='id,snippet',
        maxResults=5,
        order="viewCount",
        pageToken=nextPageToken,
        type='video')

    print(type(request))
    res = request.execute()
    pp.pprint(res)

    if 'nextPageToken' in res:
        nextPageToken = res['nextPageToken']

A: To filter items to consider channels only once, just keep track of considered channels with a Python set and reconstruct items by filtering with this set.
To do so add before your loops:
channelIds = set()

And before the nextPageToken management, add:
    items = []
    for item in res['items']:
        channelId = item['snippet']['channelId']
        if not channelId in channelIds:
            channelIds.add(channelId)
            items += [item]

    res['items'] = items


text:
Q: Extracting The particular atribute value using other attribute value in c# Suppose I have the XML file
<?xml version="1.0" ?>
<Tasks>
    <Task>
         <id>1234</id>
         <name>abc</name>
    </Task>

    <Task>
         <id>5678</id>
         <name>xyz</name>
    </Task>
<Tasks>

How can I extract the value of id using the value of name? For example I know the name is abc. How can i extract the value 1234 from the above file?

A: Use the following XPath query to get the id element for a Task with the name of abc:
/Tasks/Task[name='abc']/id

Example of this is here.


text:
Q: How to make if statement with color code I got a little problem, what I think, can't be hard.
but somehow, I miss that "can't be hard" part :).
I got a code, that reads the colors of an image:
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.four_colors);

    //define the array size
    rgbValues = new int[bmp.getWidth()][bmp.getHeight()];

    //Print in LogCat's console each of one the RGB and alpha values from the 4 corners of the image
    //Top Left
    for (int j = 0; j < 1000; j++){
        for (int k = 0; k < 1000; k++){
    Log.i("Pixel Value", "pixel x="+j +k + Integer.toHexString(bmp.getPixel(j, k)));
    test = Integer.toHexString(bmp.getPixel(j,  k));

        }
    }

    //get the ARGB value from each pixel of the image and store it into the array
    for(int i=0; i < bmp.getWidth(); i++)
    {
        for(int j=0; j < bmp.getHeight(); j++)
        {
            //This is a great opportunity to filter the ARGB values
            rgbValues[i][j] = bmp.getPixel(i, j);
        }
    }

    System.out.println(PixelNumber);
    System.out.println(test);
}

This code works like a charm.
But I tried to implement an if statement like:
if (color == black){
    number++;
}

So every pixels he sees that is black, he must increase the number with 1.
Tried almost everything I could came up to make a good if statement around this code, but nothing seems to work.
So what is the correct place and if statement to make in this code?
And maybe if you got more time (do not put too much effort in this if you don't want) is it possible to check on a color-range instead of 1 color only, So it picks all green colors. (same as Color range in photoshop).

A: getPixel returns the 4bytes of ARGB in an integer. What you should do is to compose the color you want to count (the argb method of Color will help you) and test on this value with getPixel(x, y).
For black this will be easy:
if(Color.BLACK == bmp.getPixel(x, y))
     //doit

For ranges you can use the green/red/blue methods, each returning the value of that component. If it is non-zero, the pixel has color from that component.

A: you can to that with the condition like  if(rgbValues[i][j] == Color.BLACK).
that code will be like the following.
 //get the ARGB value from each pixel of the image and store it into the array
    for(int i=0; i < bmp.getWidth(); i++)
    {
        for(int j=0; j < bmp.getHeight(); j++)
        {
            //This is a great opportunity to filter the ARGB values

            rgbValues[i][j] = bmp.getPixel(i, j);
            if(rgbValues[i][j] == Color.BLACK) {

        }
    }

A: Bitmap#getPixel(int, int) returns an int value that represents transparency (alpha) and color (rgb) of a given pixel.
The RGB value of black is (0x00, 0x00, 0x00). So if you want to test for black and ignore the alpha value, the test should go like this:
if ((rgbValue[i][j] & 0x00ffffff) == 0) {
   // this pixel is black
   number++;
}

Color range is very difficult. First we need computable definition of green (for instance). green is pretty subjective. Once you have an algorithm at hand, put it in a different method and do a call like this:
if (isGreenish(rgbValue[i][j])) {     // magic method
   // this pixel is some sort of green
   number++;
}


text:
Q: Can't escape a closing parenthesis in Java? I have a very long regular expression that seems to be having issues, but only when imported from a text file. I've narrowed it down to the following section (shown here as a literal String):
"(?i)(?<!\\w)\\w{2,3}(?=\\))"

As you can see, near the end, I am trying to escape a closing parenthesis for a lookahead. Now, if this is hard-coded, like:
Pattern myPattern = Pattern.compile("(?i)(?<!\\w)\\w{2,3}(?=\\))");

It works completely as expected. If, however, I read it from a text file, like:
File patternFile = new File("patterns.txt");
List<String> patternText = FileUtils.readLines(patternFile);
String ucText = patternText.get(0).trim();
Pattern myPattern = Pattern.compile(ucText);

Then I get the error message:
Exception in thread "Thread-4" java.util.regex.PatternSyntaxException: Unmatched closing ')' near index 25
(?i)(?<!\\w)\\w{2,3}(?=\\))
                         ^

So, why is this happening? Why is escaping a closing parenthesis legal when hard-coded, but not when reading from a text file?

A: You're writing a Java string literal.  \) is not a legal escape code for Java string literals.
You need to escape every backslash with \\ to create a string with a single backslash for the regex.

A: only when imported from a text file
You have to print that to the console.
If it prints out (?i)(?<!\w)\w{2,3}(?=\)) its ok,
if it prints out with it double escaped, you have to un-escape those
A good way to un-escape the escape character is  do a global find/replace
(this is %90 of the parsing)
Find "(?x)\\\\ \\\\"
Replace "\\\\"
Un-escape non-escapes is a relative approach.
And it depends upon the character and the substitution,
or no action on either.  This is mostly language specific,
but you can roll your own. For this, the basic's are ...
Find "(?xs)\\\\ (.)"
Replace roll your own"


text:
Q: Converting upTime Function from Javascript to Jquery and use single functions for multiple IDs I have this code in Javascript, that counts up from a specific date-time. I intend to use one function for multiple IDs so I'm trying to convert to jQuery but can't seem to get it to work.

Based on Eric's comment. I've come up with this jQuery plugin below. Is there anything I'm missing or not doing right?
      jQuery.fn.extend({
    upTime: function() {

    return this.each(function() {
        var  countTo = $(this).attr('val');
      var  yearField = $(this).find(".y1");
      var  daysField = $(this).find(".d1");
      var  hoursField =  $(this).find(".h1");
      var minutesField =  $(this).find(".m1");
     var   secondsField =  $(this).find(".m1");

        now = new Date();
        countTo = new Date(countTo);
        difference = (now-countTo);

        days=Math.floor(difference/(60*60*1000*24)*1);
        years = Math.floor(days / 365);
        if (years > 1){ days = days - (years * 365)}
        hours=Math.floor((difference%(60*60*1000*24))/(60*60*1000)*1);
        mins=Math.floor(((difference%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
        secs=Math.floor((((difference%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);

        $(yearField).prepend(years);
        $(daysField).prepend(days);
         $(hoursField).prepend(hours);
         $(minutesField).prepend(mins);
         $(secondsField).prepend(secs);
    });
 }
});

// Use the newly created  method
$(".counter").upTime();

Need it to work with loops such as these below:


text:
Q: add shortcode to p element and reload it I am trying to add a shortcode to the page after the page loaded and here are my requirements
1- add a shortcode to p element when I select an option from a select element.
** here I was able to add the shortcode as a text but I don't get the expected value from it and this is because the page was loaded so I had to load the element that has that shortcode.
2- load shortcode's element but it has to have the new added shortcode
** because when you just reload the element all what you did on point 1 will got deleted if you will just reload the element.
here is the code
<form action="">خزنات الروايات المتوفرة<select id="select_novel" onchange="gAj()">
<option value="Youjo Senki">ملحمة تانيا الاثمة</option>
<option value="Isaac">اسحاق</option>
</select></form>

I didn't want to explain the javascript anymore so one last thing
thank you @CBroe he gave me the hint that lead me to this solution and thanks to everyone who helps noobs like me.


text:
Q: Can I use Solid Fill or Gradient Like Smart Objects Photoshop gives a lot of power for web designers using smart objects. I can create re-usable elements like buttons, drop downs etc. using smart objects and sue them across a project. Later if I need to make a change, I can only edit that smart object and the change will show everywhere I have used that smart object. Can I use some same mechanism with colorus and fill also? What I want to achieve is lets say use Orange colour as base colour in my design, later if the client wants green colour, I want to change that orange colour at one place and somehow change it everywhere. Is that possible somehow?

A: Yes it's possible to do through Shape Layer or Layer Comps.


text:
Q: How to replace a portion of a std string with its own substring I am a beginner in C++. Consider the following definition for a C++ string
std::string str(10, 0); // str needs to be fixed size throughout its lifetime
str = "abcdefgh";  // could be underfilled

Let the length of the string be n. I need to move the last k characters ( < n) to the head of the string. I don't care about the contents after this k substring once I move it to the head. But, I want the size of my string to remain fixed and want to perform this without having to allocate any temporary strings.
std::string:replace() could help me do this, but is it safe to pass str as the string argument to str.replace()?
Another option is to do something like this
str = str.substr(/* last k chars */) + str.substr(/* don't care */)

Does this line update str in-place? If so, does it still maintain the length that I had constructed it with?


text:
Q: App crash with actionbar i'm new on Android. I'm trying to implent an actionbar im my activity. Everytime i run that, the app crash.
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_percorsodisabili);
    //Option Bar
    getSupportActionBar().setTitle("Percorso Bici");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    Resources res = getResources();

    myVist3 = (ListView) findViewById(R.id.myVist3);
    items = res.getStringArray(R.array.nomi_percorsi3);
    descriptions = res.getStringArray(R.array.desc_percorsi3);
    content = res.getStringArray(R.array.desc_percorsi3);
    ItemAdapter itemAdapter = new ItemAdapter(percorsodisabili.this, items,foto,descriptions,content);
    myVist3.setAdapter(itemAdapter);
}

}

A: Add the toolbar to your activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="wrap_content"
    android:layout_height="56dp" />

<RelativeLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/toolbar">

    <!--YOUR LAYOUT CODE-->
</RelativeLayout>

Then initialize java code for activity:
Use android.support.v7.widget.Toolbar in case you are using AppCompactActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
    Toolbar toolbar=findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}


text:
Q: Insert Figures Error: Not in outer par mode this is my first time that i use latex but im trying to put some pngs and eps image files but i get the error "Error: Not in outer par mode. "
please help.
\documentclass[journal]{IEEEtran}
\usepackage{graphicx}

\begin{document}

\title{Bare Demo of IEEEtran.cls for Journals}

\author{Michael~Shell,~\IEEEmembership{Member,~IEEE,}
       John~Doe,~\IEEEmembership{Fellow,~OSA,}
      and~Jane~Doe,~\IEEEmembership{Life~Fellow,~IEEE}% <-this % stops a space
\thanks{M. Shell is with the Department of Electrical and Computer Engineering, Georgia Institute of Technology, Atlanta, GA, 30332 USA e-mail: (see http://www.michaelshell.org/contact.html).}% <-this % stops a >space
\thanks{J. Doe and J. Doe are with Anonymous University.}% <-this % stops a space
\thanks{Manuscript received April 19, 2005; revised December 27, 2012.}}

\markboth{Journal of \LaTeX\ Class Files,~Vol.~11, No.~4, December~2012}%
{Shell \MakeLowercase{\textit{et al.}}: Bare Demo of IEEEtran.cls for Journals}

\maketitle

\begin{abstract}
The abstract goes here.
\end{abstract}

\begin{IEEEkeywords}
IEEEtran, journal, \LaTeX, paper, template.
\end{IEEEkeywords}

\IEEEpeerreviewmaketitle

\section{Actividades}
Se lanzo un dado equilibrado de seis caras un numero suficiente de veces hasta hasta completar 120 series. Una serie consiste en un numero de lanzamientos que terminaba cuando aparecia el primer exito. El exito consistia en conseguir un multiplo de 3. Acontinuacion se procedio a registrar los datos sus frecuencias relativas y compararlas >con el modelo matematico.

\section{Experimentos}

\begin{table}
\begin{tabular}{|c|c|c|}
\hline
($i$)&($f_i$)&($P_i$)\\
\hline
1&0.317&0.333\\
2&0.292&0.222\\
3&0.150&0.148\\
4&0.058&0.099\\
5&0.058&0.066\\
6&0.033&0.044\\
7&0.058&0.029\\
8&0.017&0.020\\
9&0.008&0.013\\
10&0.000&0.009\\
11&0.008&0.006\\
\hline
\end{tabular}

\begin{figure}
\centering
        \includegraphics[widht=\textwidht]{C:/Users/Tzukasa/Pictures/grafico.png}
\label{fig:grafico}
\end{figure}

\begin{figure}
\includegraphics[width=0.90\textwidth]{barra2.eps}
\caption{Frecuencias empiricas y teoricas para el numero de lanzamientos de un dado necesarios para obtener un multiplo de 2}
\label{barra2}
\end{figure}

\caption{Frecuencuas relativas ($f_i$) y probabilidades te\'oricas ($P_i$) para el numero de intetos necesarios ($i$) para obtener el primer m\'ultiplo de 3 al lanzar un dado.}
\label{tablaExp1}
\end{table}

\IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file''
for IEEE journal papers produced under \LaTeX\ using
IEEEtran.cls version 1.8 and later.

I wish you the best of success.

\hfill mds

\hfill December 27, 2012

\subsection{Subsection Heading Here}
Subsection text here.

\subsubsection{Subsubsection Heading Here}
Subsubsection text here.

\section{Conclusion}
The conclusion goes here.

\appendices
\section{Proof of the First Zonklar Equation}
Appendix one text goes here.

\section{}
Appendix two text goes here.

\section*{Acknowledgment}

The authors would like to thank...

\ifCLASSOPTIONcaptionsoff
 \newpage
\fi

\begin{thebibliography}{1}

\bibitem{IEEEhowto:kopka}
H.~Kopka and P.~W. Daly, \emph{A Guide to \LaTeX}, 3rd~ed.\hskip 1em plus
  0.5em minus 0.4em\relax Harlow, England: Addison-Wesley, 1999.

\bibitem{Esparza2013}
A. Esparza, \emph{A Guide to \LaTeX}, 3rd~ed \hskip 1em plus 0.5em minus 0.4em\realx Harlow England: Addison-Wesley, 1999.

\end{thebibliography}

\begin{IEEEbiography}{Michael Shell}
Biography text here.
\end{IEEEbiography}

\begin{IEEEbiographynophoto}{John Doe}
Biography text here.
\end{IEEEbiographynophoto}

\begin{IEEEbiographynophoto}{Jane Doe}
Biography text here.
\end{IEEEbiographynophoto}

\end{document}

A: the error is being reported because you can't nest one float inside another,
and you appear to be trying here to include two figures inside a
(floating) table.
if they are meant to be a unit, then omit the figure wrappers, and just
include the \includegraphics commands, using a separate package to add
the captions.  the package caption provides the command \captionof to
handle such situations.
the first figure, with the \label{fig:grafico}, will not be properly
referenceable, since there is no caption that the label can be attached to.

A: Several things appear to gone amiss when the existing template was edited. The immediate cause of the error you're getting is that the following three instructions:
\caption{Frecuencuas relativas ($f_i$) y probabilidades te\'oricas ($P_i$) para el numero de intetos necesarios ($i$) para obtener el primer m\'ultiplo de 3 al lanzar un dado.}
\label{tablaExp1}
\end{table}

appear to have gotten separated from the rest of the table environment. You should move these lines to immediately after the line that contains \end{tabular}.
There are several other, typo-kind errors that need to be fixed. E.g., \realx -> \relax, and widht=\textwidht -> width=\textwidth.
Even with these modifications, the document won't look right, primarily because the graphics in both figure environments are much too wide. Change \textwidth to \columnwidth in both figures and see if the resulting look is what you want.
Here's a version of your code that compiles and fixes the width issues of both figure environments:
\documentclass[journal]{IEEEtran}
\usepackage[demo]{graphicx} % omit 'demo' option in real document
\usepackage[spanish]{babel}
\usepackage[T1]{fontenc}

%% The following three directives are optional
\usepackage{caption}
\captionsetup[figure]{font=footnotesize,
                      labelsep=period}
\captionsetup[table]{font={footnotesize,sc},
                     labelsep=newline,
                     justification=centering}
\begin{document}

\title{Bare Demo of IEEEtran.cls for Journals}

\author{Michael~Shell,~\IEEEmembership{Member,~IEEE,}
       John~Doe,~\IEEEmembership{Fellow,~OSA,}
      and~Jane~Doe,~\IEEEmembership{Life~Fellow,~IEEE}% <-this % stops a space
\thanks{M. Shell is with the Department of Electrical and Computer Engineering, Georgia Institute of Technology, Atlanta, GA, 30332 USA e-mail: (see http://www.michaelshell.org/contact.html).}% <-this % stops a >space
\thanks{J. Doe and J. Doe are with Anonymous University.}% <-this % stops a space
\thanks{Manuscript received April 19, 2005; revised December 27, 2012.}}

\markboth{Journal of \LaTeX\ Class Files,~Vol.~11, No.~4, December~2012}%
{Shell \MakeLowercase{\textit{et al.}}: Bare Demo of IEEEtran.cls for Journals}

\maketitle

\begin{abstract}
The abstract goes here.
\end{abstract}

\begin{IEEEkeywords}
IEEEtran, journal, \LaTeX, paper, template.
\end{IEEEkeywords}

\IEEEpeerreviewmaketitle

\section{Actividades}
Se lanzo un dado equilibrado de seis caras un numero suficiente de veces hasta hasta completar 120 series. Una serie consiste en un numero de lanzamientos que terminaba cuando aparecia el primer exito. El exito consistia en conseguir un multiplo de 3. Acontinuacion se procedio a registrar los datos sus frecuencias relativas y compararlas >con el modelo matematico.

\section{Experimentos}

\begin{table}[h!]
\centering
\begin{tabular}{|c|c|c|}
\hline
($i$)&($f_i$)&($P_i$)\\
\hline
1&0.317&0.333\\
2&0.292&0.222\\
3&0.150&0.148\\
4&0.058&0.099\\
5&0.058&0.066\\
6&0.033&0.044\\
7&0.058&0.029\\
8&0.017&0.020\\
9&0.008&0.013\\
10&0.000&0.009\\
11&0.008&0.006\\
\hline
\end{tabular}
\caption{Frecuencuas relativas ($f_i$) y probabilidades te\'oricas ($P_i$) para el numero de intetos necesarios ($i$) para obtener el primer m\'ultiplo de 3 al lanzar un dado.}
\label{tablaExp1}
\end{table}

\begin{figure}[h!]
%%%\centering
\includegraphics[width=\columnwidth]{C:/Users/Tzukasa/Pictures/grafico.png}
\label{fig:grafico}
\end{figure}

\begin{figure}[ht!]
\includegraphics[width=\columnwidth]{barra2.eps}
\caption{Frecuencias empiricas y teoricas para el numero de lanzamientos de un dado necesarios para obtener un multiplo de 2}
\label{barra2}
\end{figure}

\IEEEPARstart{T}{his} demo file is intended to serve as a ``starter file''
for IEEE journal papers produced under \LaTeX\ using
IEEEtran.cls version 1.8 and later.

I wish you the best of success.

\hfill mds

\hfill December 27, 2012

\subsection{Subsection Heading Here}
Subsection text here.

\subsubsection{Subsubsection Heading Here}
Subsubsection text here.

\section{Conclusion}
The conclusion goes here.

\appendices
\section{Proof of the First Zonklar Equation}
Appendix one text goes here.

\section{}
Appendix two text goes here.

\section*{Acknowledgment}

The authors would like to thank...

\ifCLASSOPTIONcaptionsoff
 \newpage
\fi

\begin{thebibliography}{1}

\bibitem{IEEEhowto:kopka}
H.~Kopka and P.~W. Daly, \emph{A Guide to \LaTeX}, 3rd~ed.\hskip 1em plus 0.5em minus 0.4em\relax Harlow, England: Addison-Wesley, 1999.

\bibitem{Esparza2013}
A. Esparza, \emph{A Guide to \LaTeX}, 3rd~ed \hskip 1em plus 0.5em minus 0.4em\relax Harlow England: Addison-Wesley, 1999.

\end{thebibliography}

\begin{IEEEbiography}{Michael Shell}
Biography text here.
\end{IEEEbiography}

\begin{IEEEbiographynophoto}{John Doe}
Biography text here.
\end{IEEEbiographynophoto}

\begin{IEEEbiographynophoto}{Jane Doe}
Biography text here.
\end{IEEEbiographynophoto}

\end{document}


text:
Q: DateFormatter turns 2017 to 2016 when locale is set to "nl" I'm having trouble understanding the behaviour of the following code:
let enDateFormatter: DateFormatter = {
    let df = DateFormatter()
    df.dateFormat = "YYYY-MM-dd"
    df.locale = Locale(identifier: "en")
    return df
}()

let nlDateFormatter: DateFormatter = {
    let df = DateFormatter()
    df.dateFormat = "YYYY-MM-dd"
    df.locale = Locale(identifier: "nl")
    return df
}()

let date1 = enDateFormatter.date(from: "2017-01-01")!

enDateFormatter.string(from: date1)
nlDateFormatter.string(from: date1)

let date2 = nlDateFormatter.date(from: "2017-01-01")!

enDateFormatter.string(from: date2)
nlDateFormatter.string(from: date2)

This produces the following the result in playground:

For some reason nlDateFormatter always returns 2016-01-01. Obviously this is off by a year and I'm trying to understand why it happens and how I can correct this. For reference I'm using xcode 8.
EDIT Found the issue
The problem was with using 'YYYY' as opposed to 'yyyy', where the first refers to ISO8601 year and the second to Gregorian year. Given that the 1st of January 2017 comes in to week 52 of 2016 this is translated to ISO year 2016. This is not the case with the gregorian year, which corresponds to the actual year as specified in the date object.

A: this can be only in simulator. You can add plus one DateFormatter that export date to current locale. Like this:
let enDateFormatter: DateFormatter = {
    let df = DateFormatter()
    df.dateFormat = "YYYY-MM-dd"
    df.locale = Locale(identifier: "en")
    return df
}()

let nlDateFormatter: DateFormatter = {
    let df = DateFormatter()
    df.dateFormat = "YYYY-MM-dd"
    df.locale = Locale(identifier: "nl_NL")
    return df
}()

let currentLocale : DateFormatter = {
    let df = DateFormatter()
    df.dateFormat = "YYYY-MM-dd"
    return df
}()

let date1 = enDateFormatter.date(from: "2017-01-01")!
let date2 = nlDateFormatter.date(from: "2017-01-01")!

currentLocale.string(from: date2)
currentLocale.string(from: date2)

mb this helps.


text:
Q: How to allow to use not-yet-known-type in its type-definition in c? I would like to use type, which is yet not know, becuase I am using it in its own definition:
typedef struct{
 int value;
 node_t *next;
} node_t

I do not to create new variable (which I would do, If I use tag of that struct (typedef struct foo{...} foo_t, where foo is a concrete variable) I just want to create new type and use it even in its definition. Is it possible in c?

A: Create the struct first and define a new type based on :

struct node {
   int value;
   struct node *next;
};

typedef struct node node_t;

A: Just declare the structure with the the tag node_t beside the typedef alias of node_t.
This provides a forward declaration of the structure node_t, which can be used for pointers to this structure type.
Note that you need to use the struct keyword at the declaration of next.
typedef struct node_t {
     int value;
     struct node_t *next;
} node_t;


text:
Q: Laravel query builder doesn't work with COALESCE This MySQL query works perfectly and return values in both subject and body_html columns.
SELECT
    translations.id,
    COALESCE(locale.subject, fallback.subject) as subject,
    COALESCE(locale.body_html, fallback.body_html) as body_html
FROM
    translations
LEFT JOIN
    translations AS locale
    ON locale.translatable_id = translations.translatable_id
    AND locale.translatable_type = translations.translatable_type
    AND locale.locale = "fr"
LEFT JOIN
    translations AS fallback
    ON fallback.translatable_id = translations.translatable_id
    AND fallback.translatable_type = translations.translatable_type
    AND fallback.locale = "en"
WHERE
    translations.translatable_id = 1
    AND translations.translatable_type = "App\\Models\\Email"
LIMIT 1;

Now the same with the Laravel query builder, (note: the variables used here have a correct value):
return Translation::selectRaw(
        'translations.id,'.
        'COALESCE(locale.subject, fallback.subject) AS subject,'.
        'COALESCE(locale.body_html, fallback.body_html) AS body_html'
    )
    ->where('translations.translatable_id', $this->id)
    ->where('translations.translatable_type', get_class($this))
    ->leftJoin('translations AS locale', function ($join) use($locale) {
        $join->on('locale.translatable_id', 'translations.translatable_id')
            ->where('locale.translatable_type', 'translations.translatable_type')
            ->where('locale.locale', $locale);
    })
    ->leftJoin('translations AS fallback', function ($join) {
        $join->on('fallback.translatable_id', 'translations.translatable_id')
            ->where('fallback.translatable_type', 'translations.translatable_type')
            ->where('fallback.locale', config('app.fallback_locale'));
    })
    ->first();

The id column value is correct but subjectand body_html column values are empty.
Why ?

A: Your query is mostly correct, but there's a mistake in both of your joins:
->leftJoin('translations AS locale', function ($join) use($locale) {
    $join->on('locale.translatable_id', 'translations.translatable_id')
        ->where('locale.translatable_type', 'translations.translatable_type') // <- HERE
        ->where('locale.locale', $locale);
})

->leftJoin('translations AS fallback', function ($join) {
    $join->on('fallback.translatable_id', 'translations.translatable_id')
        ->where('fallback.translatable_type', 'translations.translatable_type') // <- HERE
        ->where('fallback.locale', config('app.fallback_locale'));
})

When you do where('fallback.translatable_type', 'translations.translatable_type'), it's not comparing the 2 columns.  It's trying to match fallback.translatable_type to the string literal 'translations.translatable_type'.
Simply replace those where methods by either whereColumn or on and it should work.
DB::table('translations')->selectRaw(
        'translations.id,'.
        'COALESCE(locale.subject, fallback.subject) AS subject,'.
        'COALESCE(locale.body_html, fallback.body_html) AS body_html'
    )
    ->where('translations.translatable_id', 1)
    ->where('translations.translatable_type', 'App\\Models\\Translation')
    ->leftJoin('translations AS locale', function ($join) {
        $join->on('locale.translatable_id', 'translations.translatable_id')
            ->whereColumn('locale.translatable_type', 'translations.translatable_type')
            ->where('locale.locale', 'fr');
    })
    ->leftJoin('translations AS fallback', function ($join) {
        $join->on('fallback.translatable_id', 'translations.translatable_id')
            ->whereColumn('fallback.translatable_type', 'translations.translatable_type')
            ->where('fallback.locale', config('app.fallback_locale'));
    })
    ->first();

DB::table('translations')->selectRaw(
        'translations.id,'.
        'COALESCE(locale.subject, fallback.subject) AS subject,'.
        'COALESCE(locale.body_html, fallback.body_html) AS body_html'
    )
    ->where('translations.translatable_id', 1)
    ->where('translations.translatable_type', 'App\\Models\\Translation')
    ->leftJoin('translations AS locale', function ($join) {
        $join->on('locale.translatable_id', 'translations.translatable_id')
            ->on('locale.translatable_type', 'translations.translatable_type')
            ->where('locale.locale', 'fr');
    })
    ->leftJoin('translations AS fallback', function ($join) {
        $join->on('fallback.translatable_id', 'translations.translatable_id')
            ->on('fallback.translatable_type', 'translations.translatable_type')
            ->where('fallback.locale', config('app.fallback_locale'));
    })
    ->first();


text:
Q: How can I solve this weird collider bug in Unity? So I am new to Unity and I am working on a 2d game. Here I only have a background, a boat and an island. The problem is that the boat should not go under the island.
I did a little bit of research and I found out that I should have colliders so know my boat has a box collider 2d and a rigidbody 2d and my island a polygon collider 2d. The problem with this is that whenever I try to go through the island, the boat gets in a weird angle.
EDIT: Sorry there is no video for now but here is a full sequence:

This is the script for my boats movement if you need it:
public float moveSpeed;
    private Animator anim;
    private bool playerMovement;
    private Vector2 lastMove;

    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        playerMovement = false;
        if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f) {
            transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime,0f,0f));
            playerMovement = true;
            lastMove = new Vector2(Input.GetAxisRaw("Horizontal"), 0f);
        }

        if (Input.GetAxisRaw("Vertical") > 0.5f || Input.GetAxisRaw("Vertical") < -0.5f)
        {
            transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") * moveSpeed * Time.deltaTime, 0f));
            playerMovement = true;
            lastMove = new Vector2(0f, Input.GetAxisRaw("Vertical"));
        }
        anim.SetFloat("MoveX", Input.GetAxisRaw("Horizontal"));
        anim.SetFloat("MoveY", Input.GetAxisRaw("Vertical"));
        anim.SetBool("PlayerMoving", playerMovement);
        anim.SetFloat("LastMoveX", lastMove.x);
        anim.SetFloat("LastMoveY", lastMove.y);
    }

Animator -

A: I think you are getting strange behavior because you are trying to control your object both with animation and physics. Whenever you hit a collider physics simulation is interrupted by the animator. You can try to change the Rigidbody2D BodyType to Kinematic:

Anyway as long as your boat animation/movement is that simple it it better to control movement with physics not animator. Use animator for animations like ship exploding, sinking etc. and control your ship position with physics or transform.

A: Change your sortingLayerName to what you want.
myCanvasObject.GetComponent(Canvas).sortingLayerName="mySortingLayer";

you can also do it in the unity editor.

A: In order to the physics to apply, you should use the Rigidbody2D instead of the Transform.
Instead of using transform.Translate() to move the ship, use the Rigidbody2D.velocity instead.
At the start you can get the Rigidbody2D like you are getting the Animator by doing:
rb = gameObject.GetComponent<Rigidbody2D>();

Then you can set it's velocity depending on the input:
rb.velocity = new Vector2(
    Input.GetAxisRaw("Horizontal") * moveSpeed,
    Input.GetAxisRaw("Vertical") * moveSpeed);

Also, make sure that the rigidbody is not set to Kinematic (unlike what a previous answer suggested).


text:
Q: Can we run appium test scripts through flask server on locally connected device I am trying to run my appium scripts on button click in a html template, but unfortunately I have searched everywhere but still I found no solution.
My html template is inside a templates folder in the flask project directory and I am taking path as an input and want to pass that string to my Appium script and as soon as I click on the Submit button on my template it should launch the test script on my locally connected phone taking the path as a parameter.
Any kind of help will be appreciated.
Regards
I tried adding functions of my test script in the flask route but I have multiple functions in my python script and for every function I would have to create multiple routes. I was expecting to run the python script all at once on the default flask route ('/').
Following is my code for flask_server.py file as per now I am just getting the parameter in it and showing it in the next route but instead I want to pass my appium script here and run it on device on submit.
from flask import Flask
from flask import render_template
from flask import request

from Instagram.instagram_android_automation import
InstagramAndroidAutomation

from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/dashboard/<name>')
def dashboard(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
  if request.method == 'POST':
    user = request.form['name']
    return redirect(url_for('dashboard',name = user))
  else:
    user = request.args.get('name')
    return render_template('login.html')

if __name__ == '__main__':
  app.run(debug = True)


text:
Q: Why doesn't the background color change first?

'use strict';

const sum = num => {
  let acc = 0;
  while (num) {
    acc = acc + num;
    num = num - 1;
  }
  return acc;
};

new Promise((res, reject) => {
  document.querySelector('body').style.backgroundColor = 'red';
  res();
}).then(() => {
  const res = sum(1000000000);
  console.log(res);
});

I want to change the bgcolor to red first and get result of the sum function.
But it's not working well.
After receiving the sum result, change the bg color.
what i missed?

A: I believe the code is working correctly.  However, after setting the background color, you immediately lock up the processor with an extremely long loop. The browser does not have time to color the background before it gets frozen calculating the sum of 1 to a billion.  While the property of the background color will be set before the function, the actual re-rendering takes a non-zero amount of time.
You can see this by setting a delay before letting the promise return.  In this case (or at least on my processor anyway), the background will turn red first.

'use strict';

const sum = num => {
  let acc = 0;
  while (num) {
    acc = acc + num;
    num = num - 1;
  }
  return acc;
};

new Promise((res, reject) => {
  document.querySelector('body').style.backgroundColor = 'red';
  setTimeout(res, 250);
}).then(() => {
  const res = sum(1000000000);
  console.log(res);
});