text:
Q: Plotting interpolation in python I import an excel to python with the Pandas package - this works very well. The excel has two columns - in one column are the "x" values, while in the second column are the "y" values - I would like to plot a cubic spline interpolation, but it doesn't work the way I imagine it:
df = pd.read_excel('test.xls')
f = interp1d(df['x'],df['y '])
plt.plot(f)

where the values are:
x.          y
4,637424    0,00524
4,9027      0,014685
5,082711    0,059966
5,153686    0,124667
5,212604    0,188868
5,227324    0,250883
5,270058    0,319341
5,304338    0,406323
5,315178    0,461895
5,343454    0,82056
5,341876    0,527936
5,4028      0,865394
5,725879    0,989496
5,870601    0,99345
6,497925    0,99956
6,884001    1,00

the y values are probabilities.

A: As shown in the documentation, interp1d returns a function you can use to calculate y-values based on unknown x-values. You cannot plot a function. You have to choose the range of x-values you want, and use it to calculate the y-values, then plot those values together:
f = interp1d(df['x.'], df['y'])
new_x = np.linspace(df['x.'].min(), df['x.'].max(), 100)
new_y = f(new_x)

fig, ax = plt.subplots()
ax.plot(df['x.'], df['y'], 'ro')
ax.plot(new_x, new_y, '-')


text:
Q: activity not displayed after the button is pressed, one-time activity with button how After the "Splash screen" should go to the "about program" activity, which opens once, then click "I read" button, go to "Main Activity" and return should not open the "about program" at all. If you do not click on the button in the "about program" activity, the "about program" activity should open (until the button is pressed). if you have this code, please leave it. thank you.
NEW USER (NOT CLICKED BUTTON)
SPLASH SCREEN > INFORMATION ACTIVITY
| leave app, retry turn app |
SPLASH SCREEN > INFORMATION ACTIVITY
NEWS USER (CLICKED BUTTON)
SPLASH SCREEN > INFORMATION ACTIVITY > MAIN ACTIVITY
| leave app, retry turn app |
SPLASH SCREEN > MAIN ACTIVITY

A: You can hold a boolean value in shared preference .
if it false navigate user to info activity .
on button click change bool value to true.
if true then navigate user to main activity.
in Splash check for boolean value
SharedPreferences sharedpreferences = getSharedPreferences("MyPref",Context.MODE_PRIVATE);

boolean value= sharedpreferences .getBoolean('yourKey',false);

if(!value){

//navigate user to info activity

}else{

//navigate user to Main activity
}

on read button click
//.........make boolena value to true ............
SharedPreferences sharedpreferences = getSharedPreferences("MyPref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences .edit();
editor.putBoolean("yourKey", true);
editor.apply();

A: Best way to save with short code
To save
 PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean("KEY", true).apply();

Get saved boolean
 boolean b = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("KEY", false);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get output "Table created" with perl DBI There is a code I would like to get output with Perl DBI "Table created":
use DBI;
use DBD::Oracle qw(:ora_session_modes);

$dbh=DBI->connect( "dbi:Oracle:", "", "", { ora_session_mode =>
      ORA_SYSDBA , RaiseError => 1, PrintError => 1 } );
$dbh->do(qq{  create table test ( customer_id number(10) NOT NULL )    } );

How can I get this output "Table created" from DBI?

A: I don't think you can get this answer directly from DBI. DBI does not really care about what it is executing, it just passes things to and fom the database. Only you (or the code you wrote) know that the statement you ran was a CREATE TABLE statement.
So if you want to print TABLE CREATED, or even TABLE test CREATED, you must check the return value as suggested by some other answers here and assemble the message yourself.

A: If the Query is not executed successfully print the error message.
  $Local_Dbh->do($Query) or print " Unable to execute the query $Local_Dbh->errstr";

If the table is not created , It will return the undef or -1   otherwise return the value like
     Result : 0E0


text:
Q: accepts_nested_attributes - ActiveRecord::UnknownAttributeError I have a very simple model that each event has many forexes. I am trying to create a nested form to create new event with a bunch of forexes in a go.
class Event < ActiveRecord::Base
  has_many :forexes
  accepts_nested_attributes_for :forexes

end

class Forex < ActiveRecord::Base
  belongs_to :event
end

The schema is like this:
ActiveRecord::Schema.define(version: 20180505093823) do

  create_table "events", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "base"
  end

  create_table "forexes", force: :cascade do |t|
    t.string   "code"
    t.float    "rate"
    t.integer  "event_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "forexes", ["event_id"], name: "index_forexes_on_event_id"

end

And then I tried to create new objects using the following code in rails console. It fails.
Event.new( name: "11", base: "HKD", forexes_attributes: [ {code: "RMB", rate:1}, {code: "CNY",rate:2}])

It throws me back with this error.
ActiveRecord::UnknownAttributeError: unknown attribute 'forexes_attributes' for Event.

I know this is quite a basic question. And I have tried many different ways after researching in different places. I couldn't debug it. Appreciate your help.

A: In your Event controller you need to include the forexes_attributes in event_params method as along with default one
def event_params
  params.require(:event).permit(forexes_attributes: Forexes_attribute_names.map(&:to_sym).push(:_destroy))
end


text:
Q: How to supply external metrics into HPA? Problem setting. Suppose I have 2 pods, A and B. I want to be able to dynamically scale pod A based on some arbitrary number from some arbitrary source. Suppose that pod B is such a source: for example, it can have an HTTP server with an endpoint which responds with the number of desired replicas of pod A at the moment of request. Or maybe it is an ES server or a SQL DB (does not matter).
Question. What kubernetes objects do I need to define to achieve this (apart from HPA)? What configuration should HPA have to know that it needs to look up B for current metric? How should API of B look like (or is there any constraints?)?
Research I have made. Unfortunately, the official documentation does not say much about it, apart from declaring that there is such a possibility. There are also two repositories, one with some go boilerplate code that I have trouble building and another one that has no usage instructions whatsoever (though allegedly does fulfil the "external metrics over HTTP" requirement).
By having a look at the .yaml configs in those repositories, I have reached a conclusion that apart from Deployment and Service one needs to define an APIService object that registers the external or custom metric in the kubernetes API and links it with a normal service (where you would have your pod) and a handful of ClusterRole and ClusterRoleBinding objects. But there is no explanation about it. Also I could not even list existing APIServices with kubectl in my local cluster (of 1.15 version) like other objects.

A: The easiest way will be to feed metrics into Prometheus (which is a commonly solved problem), and then setup a Prometheus-based HPA (also a commonly solved problem).
1. Feed own metrics to Prometheus

*

*Start with Prometheus-Operator to get the cluster itself monitored, and get access to ServiceMonitor objects. ServiceMonitors are pointers to services in the cluster. They let your pod's /metrics endpoint be discovered and scraped by a prometheus server.

*Write a pod that reads metrics from your 3rd party API and shows them in own /metrics endpoint. This will be the adapter between your API and Prometheus format. There are clients of course: https://github.com/prometheus/client_python#exporting

*Write a Service of type ClusterIP that represents your pod.

*Write a ServiceMonitor that points to a service.

*Query your custom metrics thru Prometheus dashboard to ensure this stage is done.

2. Setup Prometheus-based HPA

*

*Setup Prometheus-Adapter and follow the HPA walkthrough.

*Or follow the guide https://github.com/stefanprodan/k8s-prom-hpa
This looks like a huge pile of work to get the HPA. However, only the adapter pod is a custom part here. Everything else is a standard stack setup in most of the clusters, and you will get many other use cases for it anyways.


text:
Q: Rails 5.1.2 bootstrap icons not being served in production This is an Awesome place. I hope to be competent enough soon to contribute solutions.
Please, somebody help!!?!
I have watched hours of youtube and read every post about asset pipeline pre-compilation on the web.
For whatever reason I decided to use Rails 5.1.2 and I don't know if that is the problem.
glyphicons don't render on Heroku or using
rails s -e production

on my local ubuntu.
I type
rake assets:precompile RAILS_ENV=production

and get
I, [2018-01-01T16:05:07.261287 #4745]  INFO -- : Writing /home/dracos/rails/video-store/public/assets/glyphicons-halflings-regular-e395044093757d82afcb138957d06a1ea9361bdcf0b442d06a18a8051af57456.ttf
I, [2018-01-01T16:05:07.261968 #4745]  INFO -- : Writing /home/dracos/rails/video-store/public/assets/glyphicons-halflings-regular-e395044093757d82afcb138957d06a1ea9361bdcf0b442d06a18a8051af57456.ttf.gz
I, [2018-01-01T16:05:07.263049 #4745]  INFO -- : Writing /home/dracos/rails/video-store/public/assets/glyphicons-halflings-regular-fe185d11a49676890d47bb783312a0cda5a44c4039214094e7957b4c040ef11c.woff
I, [2018-01-01T16:05:07.264510 #4745]  INFO -- : Writing /home/dracos/rails/video-store/public/assets/glyphicons-halflings-regular-fe185d11a49676890d47bb783312a0cda5a44c4039214094e7957b4c040ef11c.woff2
I, [2018-01-01T16:05:07.289833 #4745]  INFO -- : Writing /home/dracos/rails/video-store/public/assets/application-c29c47294834d3d47956f910a3182df4a7db7d5864e82c6f758027f30669bafb.js
I, [2018-01-01T16:05:07.290028 #4745]  INFO -- : Writing /home/dracos/rails/video-store/public/assets/application-c29c47294834d3d47956f910a3182df4a7db7d5864e82c6f758027f30669bafb.js.gz
I, [2018-01-01T16:05:14.175848 #4745]  INFO -- : Writing /home/dracos/rails/video-store/public/assets/application-b896db4d9b9e69049347e71a1825dcdc1a4eed9147196fdd761afe6f12b556d4.css
I, [2018-01-01T16:05:14.176068 #4745]  INFO -- : Writing /home/dracos/rails/video-store/public/assets/application-b896db4d9b9e69049347e71a1825dcdc1a4eed9147196fdd761afe6f12b556d4.css.gz

but in log/production.log I get

FATAL -- : [849248f2-cd3c-4912-a10d-4f63bd5857ae] ActionController::RoutingError (No route matches [GET] "/assets/glyphicons-halflings-regular.ttf"):
FATAL -- : [dfae9054-ad8a-4553-85a3-c55d55b1946c] ActionController::RoutingError (No route matches [GET] "/assets/glyphicons-halflings-regular.woff"):

etc...
Me no get?!? I won't pretend to understand all the voodoo goings on under the bonnet of the asset pipeline and want now to not be newbie but this!?!? Why? Can anyone let me know?
My /app/assets/stylesheets/bootstrap.css has been amended to show
@font-face {
    font-family: 'Glyphicons Halflings';

    src: url('../assets/glyphicons-halflings-regular.eot');
    src: url('../assets/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),
    url('../assets/glyphicons-halflings-regular.woff2') format('woff2'),
    url('../assets/glyphicons-halflings-regular.woff') format('woff'),
    url('../assets/glyphicons-halflings-regular.ttf') format('truetype'),
    url('../assets/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}

and, interestingly enough the /assets/ part gets added even if I leave it out of the url path in the above file altogether. I have tried everything. Can anyone help? Any help would be much appreciated.
Cheers

A: If you wish to keep your assets in /assets folder only and not in /public folder.
Firstly, You can place all glyohicons' fonts file in /assets/fonts folder. (If /fonts not created, then create one).
Secondly, convert your .css file into .scss file by renaming it so that you can use assets_path method in stylesheet
Then, let your application know that you have fonts as an asset too by adding following line in your application.rb file
config.assets.paths << "#{Rails.root.to_s}/app/assets/fonts"

Then, change your urls in bootstrap.scss file in a following way.
src: url(asset_path('glyphicons-halflings-regular.eot'));

Restart the server and check, fonts should get loaded as assets.
Thanks.

A: You can write asset pipeline, you can move your font file to public folder like create folder inside public/assets named fonts which looking public/assets/fonts/ then upload your fonts files here this look likes public/assets/fonts/glyphicons-halflings-regular.woff and change paths like /assets/fonts/glyphicons-halflings-regular.woff or /assets/glyphicons-halflings-regular.wof
Hope to help

A: You can solve this problem following this way -

*

*Create a folder name "fonts" inside the app/assets directory and place place bootstrap fonts (glyphicons-halflings-regular.eot, glyphicons-halflings-regular.ttf, glyphicons-halflings-regular.woff etc) fonts inside the fonts directory.

*Now add this line to config/application.rb
config.assets.paths << Rails.root.join("app", "assets", "fonts")

*Now you have to rename app/assets/stylesheets/application.css to app/assets/stylesheets/application.css.scss and place to bellow code-
@font-face {
 font-family: 'Glyphicons Halflings';
 src: url(asset-path("glyphicons-halflings-regular.eot"));
 src: url(asset-path("glyphicons-halflings-regular.eot?#iefix")) format("embedded-opentype"),
     url(asset-path("glyphicons-halflings-regular.woff2")) format("woff2"),
     url(asset-path("glyphicons-halflings-regular.woff")) format("woff"),
     url(asset-path("glyphicons-halflings-regular.ttf")) format("truetype"),
    url(asset-path("glyphicons-halflings-regular.svg#glyphicons_halflingsregular")) format("svg");
}

*Now add fonts to config/initializers/assets.rb for Precompile additional assets.
Dir.glob("#{Rails.root}/app/assets/fonts/**/").each do |path|
  Rails.application.config.assets.paths << path
end

*Restart the web server.
I hope now it should work.

A: Building on fool-dev's answer... Using Rails 5.1.4, yarn, and webpacker... All that was needed was to copy the bootstrap font files from bootstrap/dist/fonts/ to public/fonts and re-deploy.
Didn't have to mess with the supplied bootstrap/dist/css/bootstrap.* files at all.


text:
Q: Weird behaviour of Z-Buffer I'm using Deferred Shading method to render the scene, but I have a problem with a Skybox technique due to weird behaviour of Z-Buffer. I've created additional Framebuffer and attached 5 textures, one of which is being used as a depth buffer. First pass is a geometry pass, which fills the textures with needed data, second pass renders the final objects with textures and lightning applied to the main framebuffer, the last pass renders Skybox. The problem is Skybox being ignored (Z-Buffer check fails, so it is invisible).
When rendering a Skybox, I map the secondary framebuffer as a GL_READ_FRAMEBUFFER and main framebuffer (screen) as a GL_DRAW_FRAMEBUFFER, so the depth buffer of the secondary framebuffer can be used, then I set the depth function to GL_LEQUAL. And only if I change depth function to GL_GREATER (or GL_ALWAYS) the Skybox can be seen, however it is being rendered on top of the objects.
The Vertex Shader:
#version 330

layout (location = 0) in vec3 Position;

uniform mat4 M;
uniform mat4 V;
uniform mat4 P;

out vec3 TexCoord0;

void main()
{
    vec4 MVP_Pos = P * V * M * vec4(Position, 1.0);
    gl_Position = MVP_Pos.xyww;
    TexCoord0 = Position;
}

Model matrix is a product of translation of the Skybox to the camera coordinates.
glDepthFunction set to GL_LEQUAL:

glDepthFunction set to GL_GREATER:

Contents of the Z-Buffer:

UPDATE 1: I've tried to use glBlitFramebuffer like that:
glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo); //Additional framebuffer
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glDepthMask(GL_TRUE);
glBlitFramebuffer(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, GL_DEPTH_BUFFER_BIT, GL_NEAREST);

But it doesn't work. Main depth buffer contains array of black pixels.
UPDATE 2:
//FBO initialization
glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo);

// Create gbuffer textures
glGenTextures(ARRAY_SIZE_IN_ELEMENTS(m_textures), m_textures);
glGenTextures(1, &m_depthTexture);

for (unsigned int i = 0; i < ARRAY_SIZE_IN_ELEMENTS(m_textures); i++) {
    glBindTexture(GL_TEXTURE_2D, m_textures[i]);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, WindowWidth, WindowHeight, 0, GL_RGB, GL_FLOAT, NULL);

    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, m_textures[i], 0);
    }

// depth buffer
glBindTexture(GL_TEXTURE_2D, m_depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, WindowWidth, WindowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT,
        NULL);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);

GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
glDrawBuffers(ARRAY_SIZE_IN_ELEMENTS(DrawBuffers), DrawBuffers);

GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER);

if (Status != GL_FRAMEBUFFER_COMPLETE) {
    fprintf(stderr, "FB error, status: 0x%x\n", Status);
    return false;
}

Skybox buffers:
GLfloat cube_vertices[] = {
        // front
        -1.0, -1.0, 1.0,
        1.0, -1.0, 1.0,
        1.0, 1.0, 1.0,
        -1.0, 1.0, 1.0,
        // back
        -1.0, -1.0, -1.0,
        1.0, -1.0, -1.0,
        1.0, 1.0, -1.0,
        -1.0, 1.0, -1.0,
    };

    GLushort cube_elements[] = {
        // front
        0, 1, 2,
        2, 3, 0,
        // top
        3, 2, 6,
        6, 7, 3,
        // back
        7, 6, 5,
        5, 4, 7,
        // bottom
        4, 5, 1,
        1, 0, 4,
        // left
        4, 0, 3,
        3, 7, 4,
        // right
        1, 5, 6,
        6, 2, 1,
    };

A:
When rendering a Skybox, I map the secondary framebuffer as a
  GL_READ_FRAMEBUFFER and main framebuffer (screen) as a
  GL_DRAW_FRAMEBUFFER, so the depth buffer of the secondary framebuffer
  can be used,

That is not how things work. The GL_READ_FRAMEBUFFER is not relevant for the depth test. It is used as the source for opeations like glReadPixels or glBlitFramebuffer. But for any kind of rendering, only the GL_DRAW_FRAMEBUFFER is relevant. This includes the depth test.
Unfortuanly, you can't mix user-defined render targets like render buffers or textures with window-system provided buffers, so you just can't render to the final screen while using the specific depth test. So you either have to do an additional render pass to an FBO using the custom depth buffer, and blit the result to the screen, or you can blit the contents of the custom depth buffer to the window-system provided one and render with that.

A: I found a solution. Additional framebuffer had 32 bits/pixel, but main framebuffer had only 24, that prevented glBlitFramebuffer from working. So the proper Framebuffer initialization would look like that:
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, WindowWidth, WindowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT,
        NULL);


text:
Q: Draw image from pixel array on canvas with putImageData I am working on a project that can encrypt an image and redraw the decrypted image on canvas. As I am still pretty new to coding and programming, I am currently having issues redrawing the decrypted image data, which is a pixel array in the form R,G,B,A. I thought this would be possible by simply putting the data into
ctx.putImageData(imgd,0,0);

But firebug tells me that the value does not implement the interface for imagedata. I have posted the entire array here. The image is 160px wide and 120px high.
Is there any way to reformat the array so that it is drawable on the canvas?

A: Using Uint8 you can this much quicker:
var canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    img = [27,32,26,28, ... ];

// Get a pointer to the current location in the image.
var palette = ctx.getImageData(0,0,160,120); //x,y,w,h
// Wrap your array as a Uint8ClampedArray
palette.data.set(new Uint8ClampedArray(img)); // assuming values 0..255, RGBA, pre-mult.
// Repost the data.
ctx.putImageData(palette,0,0);

No need to go byte-by-byte unless you need to modify the values first.

A: Assuming imgd is simply an Array containing all byte values, you still need to convert the array to ImageData.
var imgd = [27,32,26,28,33,27,30,35,29,31.....]

// first, create a new ImageData to contain our pixels
var imgData = ctx.createImageData(160, 120); // width x height
var data = imgData.data;

// copy img byte-per-byte into our ImageData
for (var i = 0, len = 160 * 120 * 4; i < len; i++) {
    data[i] = imgd[i];
}

// now we can draw our imagedata onto the canvas
ctx.putImageData(imgData, 0, 0);


text:
Q: Warning: Only got partial types from assembly: Microsoft.Azure.WebJobs.Extensions.Storage I've got a simple .NET V3 WebJob with a timer trigger up and running in a .NET website as outlined in this answer: Scheduled .NET WebJob V3 example
However, in the output, I get this warning:
warn: Host.Startup[0]
      Warning: Only got partial types from assembly: Microsoft.Azure.WebJobs.Extensions.Storage, Version=3.0.6.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
      The following loader failures occured when trying to load the assembly:
         - Could not load file or assembly 'System.ComponentModel.Annotations, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
         - Method 'Commit' in type 'Microsoft.Azure.WebJobs.Host.Blobs.Bindings.DelegatingCloudBlobStream' from assembly 'Microsoft.Azure.WebJobs.Extensions.Storage, Version=3.0.6.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation.
         - Method 'Commit' in type 'Microsoft.Azure.WebJobs.Host.Blobs.Bindings.DelegatingCloudBlobStream' from assembly 'Microsoft.Azure.WebJobs.Extensions.Storage, Version=3.0.6.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation.
         - Method 'Commit' in type 'Microsoft.Azure.WebJobs.Host.Blobs.Bindings.DelegatingCloudBlobStream' from assembly 'Microsoft.Azure.WebJobs.Extensions.Storage, Version=3.0.6.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation.
         - Method 'Commit' in type 'Microsoft.Azure.WebJobs.Host.Blobs.Bindings.DelegatingCloudBlobStream' from assembly 'Microsoft.Azure.WebJobs.Extensions.Storage, Version=3.0.6.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation.
         - Could not load type 'Microsoft.WindowsAzure.Storage.Table.TableQuerySegment' from assembly 'Microsoft.WindowsAzure.Storage, Version=9.3.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
      This can occur if the assemblies listed above are missing, outdated or mismatched.
      Exception message: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
         at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
         at System.Reflection.RuntimeModule.GetTypes()
         at System.Reflection.Assembly.GetTypes()
         at Microsoft.Azure.WebJobs.Host.Indexers.DefaultTypeLocator.FindTypes(Assembly assembly, IEnumerable`1 extensionAssemblies) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Indexers\DefaultTypeLocator.cs:line 115
It's an open issue on GitHub (https://github.com/Azure/azure-webjobs-sdk/issues/2060). Does anyone have a fix?
More importantly, does it affect functionality in any way? The GitHub issue OP said no, but it would be good to have someone confirm this.

A: Install package "Microsoft.Azure.WebJobs.Host.Storage" Version="4.1.0" to fix this error.
Also, to avoid any confusion, before I fixed this, the error message in the original question, due to package updates, had become the following:
warn: Host.Startup[0]
  Warning: Only got partial types from assembly: Microsoft.Azure.WebJobs.Host.Storage, Version=4.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
  The following loader failures occured when trying to load the assembly:
     - Method 'LogFunctionStarted' in type 'WebJobs.Host.Storage.Logging.PersistentQueueLogger' from assembly 'Microsoft.Azure.WebJobs.Host.Storage, Version=4.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation.
  This can occur if the assemblies listed above are missing, outdated or mismatched.
  Exception message: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
     at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
     at System.Reflection.Assembly.GetTypes()
     at Microsoft.Azure.WebJobs.Host.Indexers.DefaultTypeLocator.FindTypes(Assembly assembly, IEnumerable`1 extensionAssemblies) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Indexers\DefaultTypeLocator.cs:line 115


text:
Q: Collapsible navigation bar issues I'm trying to create a navigation bar similar to Bootstrap. If you go to their site and re-size your browser. if you re-size it narrow enough, the top navigation bar will become a button. when you click on the button, it pushes everything down and displays the full navigation again.
That's what I'm trying to accomplish with this jsfiddle, but it has the following issues:

*

*initially, the button is not hidden, it should be hidden and only be visible when the screen gets too narrow.

*(fixed) the button doesn't display background like bootstrap does

*(fixed) re-size browser to make navigation disappear and click on the button. then click on sub menu, the sub menu items does not display well.

issue 1 screen prints:
nav bar should not be visible yet because browser width is larger than 940px

nav bar appears, it's fine because browser width is less than 940px

full html code:

    <title></title>

    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet" />

Home

                            Help

Keep

Screaming

Contact

                other content

A: Is this closer to what you are after?
http://jsfiddle.net/panchroma/R4BEY/
You have a span10 div in your example and I didn't know where you were heading with this so I added a span2 after it to complete the row.
The HTML is below. You had a typo on your opening container div, and you were missing the navbar and navbar-inner divs. I think that was it for the changes I made.
Good luck

Home

        Help

Keep

Screaming

Contact

span 2

  other content

span 2


text:
Q: How to validate the results of pathlib.glob? I'm getting a FileNotFoundError when trying to iterate over a pathlib.glob() result.  The exception is raised on the for line, so I can't iterate over it to validate the paths with something like os.stat().  To wrap it with try/except, I'd have to wrap the whole for loop, failing out of the whole operation as soon as I hit a bad path.
Example code.  This try/except doesn't catch the error.
import hashlib
import pathlib

search_path_root = pathlib.Path("F:\\searchpathroot\\")
paths = search_path_root.glob("**/*.jpg")

for path in paths:
    try:
        with open(path,"rb") as hash_file:
            hash_file_contents = hash_file.read()
        md5_sum = hashlib.md5(hash_file_contents).hexdigest()
        print("{} | {}".format(md5_sum,path))
    except:
        pass

Traceback:
Traceback (most recent call last):
  File "demo.py", line 7, in <module>
    for path in paths:
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1136, in glob
    for p in selector.select_from(self):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 583, in _select_from
    for p in successor_select(starting_point, is_dir, exists, scandir):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 530, in _select_from
    with scandir(parent_path) as scandir_it:
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'F:\\searchpathroot\\broken\\filename'

I have also tried casting the generator to a list, which threw the same exception:
...
paths = search_path_root.glob("**/*.jpg")
paths = list(paths)

for path in paths:
...

Traceback (most recent call last):
  File "demo.py", line 5, in <module>
    paths = list(paths)
...

To be clear, I know what is causing this particular exception (it's being raised when Windows tries to access a backup of a recovered encrypted Linux partition--whole other can of worms, heh).  What I'm trying to figure out is how to properly validate pathlib.glob() paths in general.

A: It looks like pathlib.glob doesn't allow you to add custom error handling, so as soon as a bad spot is hit on the filesystem (e.g. broken symlink), it will raise and abort.
A more flexible alternative is os.walk:
import os

def report_error(ex):
    print(f'Error scanning {ex.filename}: {ex}')

for (dirpath, dirnames, filenames) in os.walk('f:/searchpathroot', onerror=report_error):
    for filename in filenames:
        if filename.endswith('.jpg'):
            abs_filename = os.path.join(dirpath, filename)
            # do something with abs_filename


text:
Q: Using LocationListener in WakefulBroadcastReceiver I want to get the current location in WakefulBroadcastReceiver. What I have tried is..
public class AlarmReceiver extends WakefulBroadcastReceiver implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private static final String TAG = "AlarmReceiver";

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private Location location;

    public void generateAlarm(Context context, long timeInMillis) {

        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(context)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        }

        if (mLocationRequest == null) {
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(60000);
            mLocationRequest.setFastestInterval(5000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        }

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, AlarmReceiver.class);
        PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        alarmManager.set(AlarmManager.RTC_WAKEUP,
                timeInMillis, alarmIntent);

        ComponentName receiver = new ComponentName(context, BootReceiver.class);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v(TAG, "onReceive");
        generateNotification(context);
    }

    public void generateNotification(Context context) {
            Log.v(TAG, "generateNotification");//This gets printed.
            if (location != null) {
                Log.v(TAG, "null != location");//But this doesn't printed, because location object is null.
            }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
        Log.v(TAG, "onLocationChanged : " + location.getLongitude());// this one works.
        this.location = location;// Here I am assigned the value for location object.
    }

So I have assigned the location object in onLocationChanged, but it remains null in generateNotification(). I don't know where I am wrong.


text:
Q: Excel 2010 List Synchronization with SharePoint 2010: Bug in the row 20 in fact I have installed the plugin for the synchronization from Excel 2010 to SharePoint 2010. http://www.microsoft.com/en-us/download/details.aspx?id=9345
It works well, however, when the list table in excel has more than 20 items, I have a problem with the row 20, like that the ID changes if I write or edit the row 20. And that results some excessive rows synchronized in SharePoint. Weird..  In fact it seems that someone else had the same problem before
http://www.softfluent.com/Forums/sharepoint-list-synchronizer/list-synchroniser-problem-with-greater-than-20-rows
Any ideas? Thanks in advance.

A: Well, I haven't found an explaination for this, maybe it's some problem in the setting up MS. The MS codes are all protected so I have no way to confirm this.
However, I have found an alternative way to this. This bug occurs only in the Excel Row 21.
So we could create a table from Row 25 (which is bigger than 21), then there is no bug when we do the synchronization. For all the items are out of ROW 21.


text:
Q: How to disable opensshd's self-introductory banner I have opensshd listening on the non-standard tcp port of 2222. In sshd_config I have ...
Banner none
VersionAddendum none

If from a client host I do a telnet ip.of.server 2222 then I see the service displaying a message introducing itself like so ...
SSH-2.0-OpenSSH_7.8

Is there a way to prevent this happening and instruct the openssh daemon not to reveal itself? I would prefer if "wandering" connections could not learn what is listening here.

A: The minimal identification string for the ssh protocol is:
SSH-2.0-

however OpenSSH will always send at least OpenSSH_*.*. If you want a more stealth behaviour you have several options:

*

*You can patch and recompile openssh so that the server waits for the client's identification string before sending its own (cf. the sshd_exchange_identification function). If the client's identification string does not start with SSH, it's a bogus client and you can close the connection. It might break some clients (if they wait for the server's identification), but it should not break the OpenSSH client. A portscanner will not be able to deduce the server's protocol, unless he sends a valid client authentication string.

*Install and configure nginx. Normally it is a HTTP/HTTPS (proxy) server) and it has an ssl preread module, which is used to apply different configurations to different TLS clients (based on their version and other parameters). However if you connect to nginx using a protocol it does not understand, it will set $ssl_preread_protocol to the empty string and you can redirect the connection to an SSH server. If a portscanner tries to use TLS, nginx will serve him a web page. If he tries any other protocol, he'll receive OpenSSH's identification string.

*There is a small protocol multiplexer (sslh), which guessed a client's protocol and redirects it to the correct server.

These options should answer your question, but it do not believe the security through obscurity is the way to go (besides port 2222 is not very original). You'd be better off:

*

*disabling password logins,

*using something like fail2ban to limit the amount of brute force attacks.


text:
Q: I need to Run this PowerShell script in different servers remotely with credentials & collect data in single csv and send to email I need to Run this PowerShell script in different servers remotely with credentials & collect data in single csv and send to email. i Include the Invoke Command, but getting error.
$servers = Get-Content "c:\serverlist\servers.txt"
$Report = foreach ($server in $servers){
    Invoke-Command -ComputerName $server -ScriptBlock
    }
    {

$props = @(
    @{
        N='ServerName'
        E={ $env:COMPUTERNAME }
    }
    'StartDate'
    'EndDate'
    'ConnectorName'
    'RunProfileName'
    'StepResult'
)

$profiles = @(
    'Delta Import'
    'Delta Synchronization'
    'Full Import'
    'Full Synchronization'
) -join '|'

Get-ADSyncToolsRunstepHistory | Group-Object RunProfileName |
    Where-Object Name -Match $profiles | ForEach-Object {

        $_.Group | Select-Object -First 2
    } }  | Select-Object $props | Export-Csv c:\serverlist\export.csv -NoTypeInformation

A: I followed the steps to Send the date of the csv file to the email
In PowerShell  ISE I have created a file and replaced the code below
the other method is a powerShell
    $CSVFile ="C:\Users\Public\Downloads\users.csv"
$userList = import-csv $CSVFile
$subject = " Here is your Details"
$from ="yourmail"
$passwrod ="your password"|convertTo-secureString -asPlainText -force
$creds = new-object -TypeName System.Management.Automation.PSCredential -ArgumentList $from ,$passwrod

foreach ($user in $userList){
$body = "your Login Id is" +$user.loginname
$body += "your password is" + $user.Passwrod
$body +="your email id is " + $user.mail

Send-MailMessage -From $from $user.mail -Subject $subject -body $body - SmtpServer "pujarisampath80@gmail.com" -UseSs1 -port 587 -Credential $creds
}

*

*I have created csv file In Excel
With .csv extension

Provide your Email address and password and click on Run and check the mail


text:
Q: Memory limit in R Studio I tried to decrease and give some limit to R studio but it didn't work.
I've read this article and this question.

My computer is running Windows 8 64 Bit with RAM 8 GB. I just want to give memory limit to R Studio only 4 GB.

A: The easiest would be to just use:
memory.limit()
[1] 8157
memory.limit(size=4000)

If you are running a server version of RStudio, it will be a bit different. You will have to change the file /etc/rstudio/rserver.conf and add rsession-memory-limit-mb=4000 to it.
If you do find that RStudio is resetting the memory limit with every new instance, you could try and add memory.limit(size=4000) to your .Rprofile file that sets your with every start


text:
Q: SQL query does not execute in afterAll() function while writing test cases I am writing unit test cases using Protractor, Jasmine.
I have a code written in beforeAll() functions which sets up data by fetching from database using sql queries
Similarly, there is an afterAll() function whose task is to reset the data in database as it was before the test cases executed
   beforeAll(() => {
     //get database connection

     // setup database data

   });

   it('should .....', () => {
    //code
   });

   afterAll(() => {
     // we can cleanup the database after we're done running our tests
     cleanup.clearAlerts(connection)
       .then(data => {
         //code
       });
   });

Here the beforeAll() functions executes sql queries correctly
However, the afterAll() function just doesn't execute any cleanup sql queries.

A: Do some browser action in afterall to overcome the problem.
like
afterAll(async function () {
     //your sql query here
    await browser.waitForAngularEnabled(false);
    await browser.get(browser.baseUrl);
});

Hope it help you.


text:
Q: Replace row in data.frame I have a dataframe which looks like that:
'data.frame':   3036 obs. of  751 variables:
 $ X           : chr  "01.01.2002" "02.01.2002" "03.01.2002" "04.01.2002" ...
 $ A: chr  "na" "na" "na" "na" ...
 $ B: chr  "na" "1,827437365" "0,833922973" "-0,838923572" ...
 $ C: chr  "na" "1,825300613" "0,813299479" "-0,866639008" ...
 $ D: chr  "na" "1,820482187" "0,821374034" "-0,875963104" ...
...

I have converted the X row into a date format.
dates <- as.Date(dataFrame$X, '%d.%m.%Y')

Now I want to replace this row. The thing is I cannot create a new dataframe because I after D there are coming over 1000 more rows...
What would be a possible way to do that easily?

A: I think what you want is simply:
dataFrame$X <- dates

if you you want to do is replace column X with dates. If you want to remove column X, simply do the following:
dataFrame$X <- NULL

(edited with more concise removal method provided by user @shujaa)


text:
Q: How do i translate a docker command with -p 80:80 to kubernetes yaml docker run -it -p 80:80 con-1

docker run -it -p hostport:containerport

Lets say i have this yaml definition, does below where it says 80 ports ->  containerPort: 80 sufficent? In other words how do i account for -p 80:80 the hostport and container port in kubernetes yaml definition?
apiVersion: v1
kind: Pod
metadata:
  name: task-pv-pod
spec:
  volumes:
    - name: task-pv-storage
      persistentVolumeClaim:
        claimName: task-pv-claim
  containers:
    - name: task-pv-container
      image: nginx
      ports:
        - containerPort: 80
          name: "http-server"
      volumeMounts:
        - mountPath: "/usr/share/nginx/html"
          name: task-pv-storage

A: Exposing ports of applications with k8s is different than exposing it with docker.
For pods, spec.containers.ports field isn't used to expose ports. It mostly used for documenting purpouses and also to name ports so that you can reference them later in service object's target-port with their name, and not a number (https://stackoverflow.com/a/65270688/12201084).
So how do we expose pods to the outside?
It's done with service objects. There are 4 types of service: ClusterIP, NodePort, LoadBalancer and ExternalName.
They are all well explained in k8s documentation so I am not going to explain it here. Check out K8s docs on types of servies
Assuming you know what type you want to use you can now use kubectl to create this service:
kubectl expose pod <pod-name> --port <port> --target-port <targetport> --type <type>

kubectl expose deployment <pod-name> --port <port> --target-port <targetport> --type <type>

Where:

*

*--port - is used to pecify the port on whihc you want to expose the application

*--target-port - is used to specify the port on which the applciation is running

*--type - is used to specify the type of service

With docker you would use -p <port>:<target-port>
OK, but maybe you don't want to use kubeclt to create a service and you would like to keep the service in git or whatever as a yaml file. You can check out the examples in k8s docs, copy it and write you own yaml or do the following:
$ kubectl expose pod my-svc --port 80 --dry-run=client -oyaml
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    run: my-svc
  name: my-svc
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    run: my-svc
status:
  loadBalancer: {}

Note: notice that if you don't pass a value for --target-port it defaults to the same value as --port
Also notice the selector filed, that has the same values as the labels on a pod. It will forward the traffic to every pod with this label (within the namespace).
Now, if you don't pass the value for --type, it defaults to ClisterIP so it means the service will be accessible only from within the cluster.
If you want to access the pod/application from the outside, you need to use either NodePort or LoadBalancer.
Nodeport opens some random port on every node and connecting to this port will forward the packets to the pod. The problem is that you can't just pick any port to open, and often you dont even get to pick the port at all (it's randomly assigned).
In case of type LoadBalancer you can use whateever port you'd like, but you need to run in cloud and use cloud provisioner to create and configure external loadbalancer for you and point it to your pod. If you are running on bare-metal you can use projects like MetalLB to make use of LoadBalancer type.

To summarize, exposing containers with docker is totally different than exposing them with kubernetes. Don't assume k8s will work the same way the docker works just with different notation, because it won't.
Read the docs and blogs about k8s services and learn how they work.


text:
Q: How to highlight text in chrome I would like to highlight some text in chrome but conditionnaly.
The website is using this type of code for each element on the page and i would like to highlight those with a lenght lower than 1:00:00

"Title"

 Size: 11111111 bytes (111.11 MB), duration: 00:11:11, avg.birate: 111 kb/s

 Audio: aac, 16000 Hz, mono

 Video: h264, 320×240, 15 fps

PS: I know the number don't add up it's an example ;)
I would like if possible to do it in css with stylish but really dont know if it's possible and how to make condition in css.
Thank you for your help.

A: I can't see any way to use css to conditionally highlight an element based on its content. However, a simple bit of javascript could do it:

var divs = document.getElementsByClassName("entry_content");

for (var i = 0; i < divs.length; i++)
{
    if (/duration:\s00:/.test(divs[i].innerHTML))
    {
        divs[i].style.backgroundColor = "yellow";
    }
}

"One Hour Eleven Minutes"

 Size: 11111111 bytes (111.11 MB), duration: 01:11:11, avg.birate: 111 kb/s

 Audio: aac, 16000 Hz, mono

 Video: h264, 320×240, 15 fps

"Eleven Minutes"

 Size: 11111111 bytes (111.11 MB), duration: 00:11:11, avg.birate: 111 kb/s

 Audio: aac, 16000 Hz, mono

 Video: h264, 320×240, 15 fps

"Eleven Hours"

 Size: 11111111 bytes (111.11 MB), duration: 11:11:11, avg.birate: 111 kb/s

 Audio: aac, 16000 Hz, mono

 Video: h264, 320×240, 15 fps


text:
Q: webcoreglue: Should not happen: no rect-based-test nodes found in phonegap I'm developing an application with phonegap cordova 2.7.0, i have an event click binded to an image like this
$("#actu_gauge").live("click",function() {
alert('aaaa');
idExercice =  window.sessionStorage['exercie_selected'];
chargeIndicateurOC(idExercice, 1);

// capturePhoto();
});

The image is over another image with negative margin-top.
When i click to the image i got this error : webcoreglue: Should not happen: no rect-based-test nodes found in phonegap
Any one can help?


text:
Q: Why does serverless require you to be very specific with your dynamodb settings? From: https://github.com/serverless/examples/blob/master/aws-node-rest-api-with-dynamodb/serverless.yml
resources:
  Resources:
    TodosDynamoDbTable:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          -
            AttributeName: id
            AttributeType: S
        KeySchema:
          -
            AttributeName: id
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DYNAMODB_TABLE}

Isn't DynamoDB supposed to be schemaless? And why is throughput provisioning done here? This config is supposed to be committed, right? What's the idea behind including specific config details?

A:
Why does serverless require you to be very specific with your dynamodb settings?

That's AWS' requirement not serverless'.
The resources section is directly passed by serverless to AWS CloudFormation so it should follow CloudFormation's syntax/rules.

Isn't DynamoDB supposed to be schemaless?

It is. And just like ALL schemaless databases, it needs a key for it to work. Other databases (e.g. MongoDB) just simply create the key for you if you don't provide one. DynamoDB only asks you to explicitly set the key (in exchange for speed and scalability) but the rest of the values are all up to you and it's "schemaless".

Why is throughput provisioning done here? This config is supposed to be committed, right? What's the idea behind including specific config details?

The whole point of using the resources section of the serverless.yml file is to manage your infrastructure through code. By defining the infrastructure that your application/web service needs in code, it makes it so much easier to create, update, or delete those resources.
I don't think anyone would enjoy doing any infrastructure change (e.g. increasing provisioned throughput) to five DynamoDB tables in each of ten different regions manually through the AWS DynamoDB web console. :-)

But unlike other variables, throughput provisioning depends on demand and requirements can change.

When demand and requirements change, you change it in your serverless.yml. Again, the whole purpose of infrastructure-as-code is that you should never have to touch AWS console itself.

How do devs usually enter this into serverless.yml? Also, wouldn't it reset every time it deploys?

It will reset. That's why you have to make the change in serverless.yml, not the AWS console.
If you're referring to different environments with different demands and requirements, you can set set different values for each of them.


text:
Q: Excel advanced filter showing identical values This should be extremely simple, but I'm losing my mind over it. In Excel I use Data/Filter/Advanced and select $B$1:$B$369600 as range. I choose "Unique records only", and I select an empty column for the results. But when I get the results, there are two identical values in the list. Repeatedly.
I've changed columns, changed format, shut the program down and restarted, whatever I could think of, but whatever I do, these two values in the "Unique records" column are identical. Here are two iterations of using the filter. What am I missing? Thanks.

Longer story: I ran an R script to aggregate data from hundreds of files. There are 4 versions: Winter, Summer, Spring, Fall (four separate Excel files). The data uses the same "character strings as names" in each version, but they are for different seasons. I have 369,600 rows of data, which is 336*20 "takes", as it should be. But to do a double check, I decided to do a "unique values" to make sure that each of the 336 appropriate items are there. Only I get 337. Every time. For every one of the four Excel files. And it seems to be only "10020001" every time. It's maddening.


text:
Q: Calculating Percentage in Python I am trying to calculate percentage in Python, by hand this works fine but in python this formula for some reason does not work.  I tried multiple ways but just not getting correct results.
getPercent = lambda part, whole: float(1 - (float(part)/float(part))) * 100
Val1= float(3194.15)
Val2= float(3163.84)
getPercent(Val2, Val1)

Output:
0.0
output should be:
0.95

A: Just use whole instead of part in the denominator.
getPercent = lambda part, whole: float(1 - (float(part)/float(whole))) * 100
Val1= float(3194.15)
Val2= float(3163.84)
getPercent(Val2, Val1)

Try it online!

A: you haven't used whole in your lambda function
getPercent = lambda part, whole: float(1 - (float(part)/float(whole))) * 100
Val1= float(3194.15)
Val2= float(3163.84)
getPercent(Val2, Val1)
# output 0.9489222484855064

A: You need to divide by whole. To get just two decimal places:
get_percent = lambda part, whole: float(1 - part / whole) * 100

val_1 = float(3194.15)
val_2 = float(3163.84)
a_float = get_percent(val_2, val_1)

print("{:.2f}".format(a_float))

Returning:
0.95


text:
Q: How to use jwplayer with VAST I'm trying to use the jwplayer. I've successfully configured it for regular, non-VAST video ads. but it failed when I use vast like below:

Error:

No playable sources found.

I'd guessed that I should set the file option with a blank video and then it worked fine but it played the specified file in the file option not the vast:
file: 'Blank Video.mp4',

How can I make it works with VAST?

A: *

*Navigate to the Players section in your Dashboard.

*Click New Player or edit an existing Player.

*Set your desired playback settings and other customizations.

*Open the Advertising pane on the left-hand-side.

*Turn Advertising on.

*Choose the type of ad tag that you would like to associate with this player.
a. VAST uses JW Player's own ad tag parser
b. Google IMA uses Google's IMA SDK
c. VMAP is an external ad schedule
d. JW Player schedule is an advanced schedule that allows you to associate pre, mid, and post rolls with this player.

*Enter the tag URL or URL to your VMAP file in the URL field.

*Set the text for the user interface elements that you desire.
a. Message for while the ad is playing.
b. Cue text - the tooltip over the controlbar cuepoint.
VAST Example:
First, here is a basic advertising setup using a VAST/VPAID pre-roll:
var playerInstance = jwplayer('myElement');
playerInstance.setup({
  file: 'assets/myVideo.mp4',
  primary: 'flash',
  advertising: {
    client: 'vast',
    tag: '//adserver.com/vastResponse.xml'
  }
});


text:
Q: Fatal Error when loading Catalog-settings in backend On a fresh 1.5.0.1 Magento install when choosing Catalog from the settings->settings menu I get the following error:

Fatal error: Undefined class constant 'RANGE_CALCULATION_AUTO' in
  /my-install-dir/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Price/Step.php on line 33

Checked Step.php and it does not look damaged and contains the following:
class Mage_Adminhtml_Model_System_Config_Source_Price_Step
{

    public function toOptionArray()
    {
        return array(
            array(
               'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_AUTO,
               'label' => Mage::helper('adminhtml')->__('Automatic')
            ),
            array(
                'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_MANUAL,
                'label' => Mage::helper('adminhtml')->__('Manual')
            ),
        );
    }

}`

Anyone know this error or how to fix it?

A: PHP is complaining that it can't find the constant on RANGE_CALCULATION_AUTO defined on the class Mage_Catalog_Model_Layer_Filter_Price
Based on your comments above, it sounds like you already checked the file at
app/code/core/Mage/Catalog/Model/Layer/Filter/Price.php

to ensure is had the correct constant defined.
const RANGE_CALCULATION_AUTO    = 'auto';

Based on that, my guess would be there's a different Price.php being loaded for this class.  This can happen if

*

*Someone's placed a different version in community or local

*Someone's monkied with the include path beyond Magento's normal monkey business
Check for files at
app/community/core/Mage/Catalog/Model/Layer/Filter/Price.php
app/local/core/Mage/Catalog/Model/Layer/Filter/Price.php

If that doesn't work, add some temporary debugging code to
app/code/core/Mage/Adminhtml/Model/System/Config/Source/Price/Step.php

that uses reflection to figure out what file PHP is loading the class from
class Mage_Adminhtml_Model_System_Config_Source_Price_Step
{

    public function toOptionArray()
    {
        //NEW LINES HERE
        $r = new ReflectionClass('Mage_Catalog_Model_Layer_Filter_Price');
        var_dump($r->getFileName());
        //echo $r->getFileName(); // if too long for var_dump
        exit("Bailing at line ".__LINE__." in ".__FILE__);
        //END NEW LINES
        return array(
            array(
               'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_AUTO,
               'label' => Mage::helper('adminhtml')->__('Automatic')
            ),
            array(
                'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_MANUAL,
                'label' => Mage::helper('adminhtml')->__('Manual')
            ),
        );
    }

}`

This will dump out a file path that points to the exact place PHP is loading the class from, which should get you where you need to go.


text:
Q: Error seeding my database using seed_dump gem I used the gem, seed_dump to dump and and seed my database when moving from computer to computer. Though I was able to dump my data when it came to seeding I got this error:
SyntaxError: /Users/bowser/rails_projects/project_one/db/seeds.rb:7: syntax error, unexpected ']', expecting end-of-input
/Library/Ruby/Gems/2.0.0/gems/activesupport-4.1.0/lib/active_support/dependencies.rb:241:in `load'
/Library/Ruby/Gems/2.0.0/gems/activesupport-4.1.0/lib/active_support/dependencies.rb:241:in `block in load'
/Library/Ruby/Gems/2.0.0/gems/activesupport-4.1.0/lib/active_support/dependencies.rb:232:in `load_dependency'
/Library/Ruby/Gems/2.0.0/gems/activesupport-4.1.0/lib/active_support/dependencies.rb:241:in `load'
/Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/engine.rb:543:in `load_seed'
/Library/Ruby/Gems/2.0.0/gems/activerecord-4.1.0/lib/active_record/tasks/database_tasks.rb:184:in `load_seed'
/Library/Ruby/Gems/2.0.0/gems/activerecord-4.1.0/lib/active_record/railties/databases.rake:173:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)

Aside from having the file created none of the code was altered which makes me wonder if it was outputted correctly to begin with.
Seed File
Article.create!([
  {title: "RailsConf", body: "RailsConf is the official gathering for Rails developers..", published_at: "2013-04-13 00:00:00", excerpt: nil, location: nil, user_id: nil},
  {title: "Introduction to Active Record", body: "Active Record is Rail's default ORM..", published_at: "2014-08-14 00:00:00", excerpt: nil, location: nil, user_id: nil}
])
#<Class:0x007f92d712a108>.create!([
  {article_id: 1, category_id: 1}
])
Category.create!([
  {name: "sports"}
])
#<Class:0x007f92d70e2268>.create!([
  {article_id: 1, category_id: 1}
])
Profile.create!([
  {user_id: nil, name: "Joe", birthday: "2014-08-14", color: "blue", twitter: "twitter.com/joe"}
])

A: Bad News!
seed_dump doesn't work for the tables which don't have corresponding Models, e.g. HABTM mapper table.
In your case, its problem of HABTM mapper table which has columns article_id and category_id but as per implementation, it doesn't have model so seed_dump is adding wrong code to db/seed.rb
#<Class:0x007f92d70e2268>.create!([
  {article_id: 1, category_id: 1}
])

It'll not work when you will try to run rake db:seed.
Alternative solution:
Just extract database dump from your server and add use that on new machine by importing it into your db server on that new machine.
If you are using mysql, you will need to do:
mysqldump -u USERNAME -p DATABASE_NAME > FILE_NAME.sql

It will ask you for mysql password. Enter that and it will export data to FILE_NAME.sql
Now for importing db on another machine,
mysql -u USERNAME -p DATABASE_NAME < FILE_NAME.sql

More about db import/export


text:
Q: Determine probabilites based on an array python Let's say I have and array.shape = (296,3)
Where the first column contains 0 or 1, the second column contains 0,1 or 2 and the final column contains also 0,1 or 2.
I want to know how I can calculate all the probabilities for each one of the 18 possible combinations (2x3x3) of the 3 columns. Possible sequences are [0,0,0];[0,0,1];etc... .

A: You can use numpy.unique to collect the unique sequences, along with their counts.
>>> (unique, counts) = numpy.unique(data, return_counts=True, axis=0)
>>> unique
array([0, 1, 1],
      [0, 1, 2],
      [1, 1, 1],
       ...])
>>> counts
array([2, 2, 1, ...])

Therefore the probability of the i-th element from uniques is its corresponding value from counts over the number of rows from your original data. In other words for example a count of 28 over 296 rows would be a probability of ~9.46%.


text:
Q: How to get the stdout from Ghostscript and use it with PHP to present a PDF from a HTML page? I need to get the stdout from GS and use it with PHP to present a PDF from a HTML page.
This is how I pick the from GS:
gs -sOutputFile=%stdout -q | lpr
This is how I use to read a file with fopen and present its contents with fpassthru:
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Type: '.mime_content_type($filepath));
header('Content-Length: '.filesize($filepath));
header('Content-Disposition: attachment; filename="NameOfTheFile.pdf";');
fpassthru(fopen($filepath,'rb'));
fclose($f);

Thanks.


text:
Q: Cannot run an application without admin rights (UAC issue) I have attempted to use the old "Run as Administrator" fix for this particular program that is forcing the user to provide Admin elevation every time they launch with no success.  It still asks for admin elevation every time.  I am reticent to allow local admin for this one program, but don't have much of a choice.
If it helps, the application is a GUI written probably 20 years ago that layers on top of an Access database.  It had been updated to work with Access 2010, but that was long before I arrived on the scene.  The program runs from a mess of a shortcut that throws a bunch of arguments that I'm not familiar with.  The shortcut ultimately points to "runaccess.exe" which also requires administrative elevation.  I have tried setting both the shortcut and the executable to Run as Administrator with no luck.  Still prompts for admin elevation every time.
To clarify - I am not just trying to bypass accepting a UAC prompt.  It is asking for an administrator password every time the application is run.  I would like to have this program running for users "the right way" and not just give them local admin, as has been done in the past.
To summarize, I have tried:
-Properties -> Compatibility -> Run as Administrator
-Looking through the registry for a 'runasadmin' flag tied to Access - it didn't exist
And that's about all I could find.  Thanks for the advice!

A: I have read your message several times over and it appears to me that you really don't know what "Run as Administrator" does. This command triggers a UAC prompt! However, from your question, it appears you have been meaning to use this command to suppress a UAC prompt instead of triggering it.

I have attempted to use the old "Run as Administrator" fix for this particular program that is forcing the user to provide Admin elevation every time they launch with no success.

The long and short of it is: If double-clicking on an EXE file causes a UAC prompt to appear, issuing a "Run as Administrator" command (be it from the context menu, shortcut properties or compatibility settings) makes ZERO difference.
It also appears that in addition to wanting to suppress the UAC prompt, you also (reluctantly) want to give the admin rights! Sorry, but you can't keep your pie and eat it too.


text:
Q: How do I adjust Player's physical bounds? Object Boundary
I'm a new Phaser developer, in the beginning stages of my first game. My problem is, when my player hits the ground, the bounding box defining his bounds is way bigger than he is (see pic). So in the example shown, the player will bounce when the borders touch, not his feet.
In action

Physics Matter
Do I have to change from ARCADE physics to a more robust physics engine, in order to accomplish my goal?
Code
There's really not much to show, but here is what I have:
/// <reference path="../defs/phaser.d.ts" />

class MainGame extends Phaser.Scene {
  constructor() {
    super("MainGame");
  }

  preload() {
    this.load.image("bg1", "assets/bg-level1.png");
    this.load.image('ground', 'assets/platform.png');
    this.load.spritesheet('dude', 'assets/final-jump.png', {
      frameWidth: 118,
      frameHeight: 118
    });
  }

  create() {

    this.setupBackground();
    this.setupPlayer();

    this.add.text(0, 0, 'Use Cursors to scroll camera.\nQ / E to zoom in and out', {
      font: '18px Courier',
      fill: 'black'
    });

    this.physics.add.collider(this.player, this.platforms);

  }

  update() {

    // Set Player Animations
    this.setPlayerAnimation();

    if (this.player.body.onFloor()) {
      console.log("FLOOR");
      this.player.body.setAccelerationX(31);
      this.player.body.setAccelerationY(31);

    }

  }

  //---------------------------------
  // CREATE RELATED FUNCTIONS
  //---------------------------------

  setupBackground() {
    this.background = this.add.image(0, 0, "bg1");
    this.background.setOrigin(0, 0);

    //this.background.setInteractive();
    this.background.setAlpha(.2, .2, .2, .2);

    //  The platforms group contains the ground and the 2 ledges we can jump on
    this.platforms = this.physics.add.staticGroup();

    //  Here we create the ground.
    //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
    this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();

  }

  setupPlayer() {

    this.player = this.physics.add.sprite(100, 283, 'dude');
    console.log(this.player.body.touching.down);

    this.player.setVelocity(200, 100).setBounce(.8, .8).setCollideWorldBounds(true);

    // Re-Size Player Size
    this.player.setDisplaySize(220, 210);

    // Collision Handler
    this.physics.add.overlap(this.player, this.platforms, this.showJump, null, this);

    // ANIMATIONS
    this.anims.create({
      key: 'jump-up',
      frames: this.anims.generateFrameNumbers('dude', {
        start: 1,
        end: 2
      }),
      frameRate: 5,
      repeat: 1
    });

    this.anims.create({
      key: 'falling',
      frames: this.anims.generateFrameNumbers('dude', {
        start: 0,
        end: 1
      }),
      frameRate: 5,
      repeat: 1
    });

    this.anims.create({
      key: 'onGround',
      frames: this.anims.generateFrameNumbers('dude', {
        start: 4,
        end: 4
      }),
      frameRate: 24,
      repeat: 1
    });

  }

  showJump() {

    this.player.anims.play('jump-up', true);
  }

  //---------------------------------
  // UPDATE RELATED FUNCTIONS
  //---------------------------------

  setPlayerAnimation() {
    //this.player.anims.play('jump-up', true);

    if (this.player.body.deltaY() > 0 && this.player.body.onFloor()) {
      this.player.anims.play('falling', true);
    }

  }

}

Oh, Yeah...
I am very impressed with the functionality of the local documentation package I downloaded and installed, however, I'm confused on where to begin looking for something. For instance, let's say I am struggling with making my player jump and play an animation when in the air, and change back when he hits the ground. Given that information, how do I find the correct class or function I need???

A: You do not have to change from arcade physics. Try something like this:
// Change the size of the bounding box.
this.player.setSize(32, 32);
// Change the location of the bounding box.
this.player.setOffset(0, 28);

// If that doesn't work, try this instead:
// this.player.body.setOffset(0, 28);

Obviously you need to adjust the width/height and offsets for your scenario.
References:

*

*Sprite setSize method

*Sprite setOffset method

*Body setOffset method


text:
Q: Add an Image from url into custom InfoWindow google maps v2 I'm am working in an android app. The user make a search at google maps for restaurants. In google map display markers for all of his neighbor's restaurant. If he tap at a marker it show up a custom InfoWindow. My problem is that I can't load the image that return form Google places. Im getting right the url of image but I can't show it at Window.
InfoWindow
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@color/bg_color" >

<ImageView
        android:id="@+id/place_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"" />

<TextView
    android:id="@+id/place_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/place_vicinity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/bg_color" >

    <RatingBar
         android:id="@+id/place_rating"
         style="?android:attr/ratingBarStyleSmall"
         android:numStars="5"
         android:rating="0"
         android:isIndicator="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dip" />

    <ImageView
        android:id="@+id/navigate_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:src="@drawable/navigate" />

</LinearLayout>

On create i have this
mGoogleMap.setInfoWindowAdapter(new InfoWindowAdapter() {

            // Use default InfoWindow frame
            @Override
            public View getInfoWindow(Marker arg0) {
                return null;
            }

            // Defines the contents of the InfoWindow
            @Override
            public View getInfoContents(Marker arg0) {

                // Getting view from the layout file info_window_layout
                View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);

                // Getting the snippet from the marker
                String snippet = arg0.getSnippet();

                // Getting the snippet from the marker
                String titlestr = arg0.getTitle();

                String cutchar1= "%#";
                String cutchar2= "%##";
                String ratingstr = snippet.substring(0,snippet.indexOf( cutchar1 ));
                String vicinitystr = snippet.substring(snippet.indexOf( cutchar1 )+2, snippet.indexOf( cutchar2 ) );
                String iconurl= snippet.substring(snippet.indexOf( cutchar2 )+3);

                // Getting reference to the TextView to set latitude
                TextView title = (TextView) v.findViewById(R.id.place_title);

                TextView vicinity = (TextView) v.findViewById(R.id.place_vicinity);

                ImageView image = (ImageView) v.findViewById(R.id.navigate_icon);

                // Setting the latitude
                title.setText(titlestr);

                // declare RatingBar object
                RatingBar rating=(RatingBar) v.findViewById(R.id.place_rating);// create RatingBar object
                if( !(ratingstr.equals("null")) ){
                    rating.setRating(Float.parseFloat(ratingstr));
                }
                vicinity.setText(vicinitystr);

                final DownloadImageTask download = new DownloadImageTask((ImageView) v.findViewById(R.id.place_icon) ,arg0);
                download.execute(iconurl);
                // Returning the view containing InfoWindow contents
                return v;

            }

});
and the DownloadImage code is:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;
      Marker marker;
      boolean refresh;

      public DownloadImageTask(final ImageView bmImage, final Marker marker) {
          this.bmImage = bmImage;
          this.marker=marker;
          this.refresh=false;
      }

     public void SetRefresh(boolean refresh ){
         this.refresh=true;

     }

    /*  @Override
      protected void onPreExecute()
      {
          super.onPreExecute();
          bmImage.setImageBitmap(null);
      }*/

      @Override
      protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
          return mIcon11;
      }
      @Override
      protected void onPostExecute(Bitmap result) {
          if(!refresh){
              SetRefresh(refresh);
              bmImage.setImageBitmap(result);
              marker.showInfoWindow();
          }
      }
    }

Finally when I execute the code and tap the marker the getInfoContents doesn't stop execute and the icon does not appear.
Why this happen?

A: Whatever you return from getInfoContents(), at that moment, is converted into a Bitmap and is used for displaying the results. You are not displaying the image until later, when the download is complete, by which point in time the Bitmap is already created and used.
You will need to download the image before getInfoContents() has been called.

A: I've been building a similar app.
First of all, the reason your InfoWindow is not showing the downloaded image is because the MapFragment renders the view into a Canvas, and then draws that.  What you're seeing in the info window aren't the views you created, but a "picture" or "screenshot" of them. You basically need to call showInfoWindow() again on the Marker object, and that will re-render the Canvas and your image will now be visible.
However, that being said, in my experience loading the Bitmap from the URL and then setting it isn't the best solution. Android doesn't handle Bitmaps very well. After loading several bitmaps, an OutOfMemoryError exception is just a matter of time, depending on the amount of system memory you have.
I'd recommend using the Picasso library, which handles the asynchronous downloading, and caching (in memory and disk) and makes the actual image loading just one line (Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);). (more info at http://square.github.io/picasso/)
The previous answer was good, except that as he said, that "delay" is a little bit too magical for my taste. Picasso has the option of using callbacks, and I'd recommend using that (I'm using that in my app).
First create a class (it can be internal to your activity) that implements Picasso's Callback interface, and receives a Marker in the constructor (so you can call showInfoWindow() on that marker again.
private class InfoWindowRefresher implements Callback {
   private Marker markerToRefresh;

   private InfoWindowRefresher(Marker markerToRefresh) {
        this.markerToRefresh = markerToRefresh;
    }

    @Override
    public void onSuccess() {
        markerToRefresh.showInfoWindow();
    }

    @Override
    public void onError() {}
}

The info window looks like this:
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
    @Override
    public View getInfoWindow(Marker marker) {
        // inflate view window

        // set other views content

        // set image view like this:
        if (not_first_time_showing_info_window) {
            Picasso.with(ActivityClass.this).load(restaurantPictureURL).into(imgInfoWindowPicture);
        } else { // if it's the first time, load the image with the callback set
            not_first_time_showing_info_window=true;
            Picasso.with(ActivityClass.this).load(restaurantPictureURL).into(imgInfoWindowPicture,new InfoWindowRefresher(marker));
        }

        return v;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }
});

The callback is pretty simple, as you can see. However, when using this method you MUST be careful to only use the callback in the first call, and not in subsequent calls (I just put in that not_first_time_showing_info_window to reflect the idea... you'll have to see how to include that in your program logic. If you don't do that, the Picasso callback will call showInfoWindow() and that will re-call the callback, which will recall showInfoWindow()... well, you can see where that recursion's going. :)
The main thing is getting the Picasso load with the callback to only run once, and on the subsequent calls, without the callback.

A: I solved this problem using black magic (aka setting a delay). I took advantage of Picasso's caching and just called showInfoWindow a few milliseconds after the initial loading had began.
Here is my CustomWindowAdapter.
class CustomWindowAdapter implements InfoWindowAdapter{
   LayoutInflater mInflater;
   Map<Marker, String> imageStringMapMarker;
   Context context;

   public CustomWindowAdapter(LayoutInflater i,  Map<Marker, String> imageStringMapMarker2, Context context ){
      mInflater = i;
      imageStringMapMarker = imageStringMapMarker2;
   }

   @Override
   public View getInfoContents(final Marker marker) {

      View v = mInflater.inflate(R.layout.custom_info_window, null);

      ImageView ivThumbnail = (ImageView) v.findViewById(R.id.ivThumbnail);
      String urlImage = imageStringMapMarker.get(marker).toString();
      Picasso.with(context).load(Uri.parse(urlImage)).resize(250,250).into(ivThumbnail);

      return v;

   }

   @Override
   public View getInfoWindow(Marker marker) {
    // TODO Auto-generated method stub
     return null;
   }
}

And here is the method for calling the info window in my Main Activity where I implement the delay.
myMap.setInfoWindowAdapter(new CustomWindowAdapter(this.getLayoutInflater(),
imageStringMapMarker, getApplicationContext()));
myMap.setOnMarkerClickListener(new OnMarkerClickListener() {

    @Override
    public boolean onMarkerClick(final Marker mark) {

    mark.showInfoWindow();

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mark.showInfoWindow();

            }
        }, 200);

        return true;
    }
});

A: I do this, also referencing to the @Daniel Gray answer:
if (userImg.getDrawable() == null) {
  Picasso.with(ctx).load(UtilitiesApp.urlServer + user.getImgUrl())
      .error(R.drawable.logo)
      .into(userImg, new InfoWindowRefresher(marker));
} else {
  Picasso.with(ctx).load(UtilitiesApp.urlServer + user.getImgUrl())
      .error(R.drawable.logo)
      .into(userImg);
}

public class InfoWindowRefresher implements Callback {
  private Marker markerToRefresh;

  public InfoWindowRefresher(Marker markerToRefresh) {
    this.markerToRefresh = markerToRefresh;
  }

  @Override
  public void onSuccess() {
    markerToRefresh.showInfoWindow();
  }

  @Override
  public void onError() {}
}


text:
Q: How do I rewrite on client side a svg file I fetched from the server? Background:
I running an express server with a route to all my static files.
In the static files, I have a folder full of map .svg's.
On the client side (React), I fetch the maps and adding them to to a component.
Question:
I need to rewrite the .svg's, and add this to their path attribute: fill=url(#some_flag).
Svg before:
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
 width="1024pt" height="1024pt" viewBox="0 0 1024 1024"
 preserveAspectRatio="xMidYMid meet">
    <g transform="translate(0,1024) scale(0.1,-0.1)"
        fill="#000000" stroke="none">
        <path d="... numbers...-78 -28 -115 "/>
    </g>
</svg>

Svg After:
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
 width="1024pt" height="1024pt" viewBox="0 0 1024 1024"
 preserveAspectRatio="xMidYMid meet">
    <g transform="translate(0,1024) scale(0.1,-0.1)"
        fill="#000000" stroke="none">
        <path d="... numbers...-78 -28 -115"
         fill="url(#some_flag)"/>  <!--THE ADDED ATTRIBUTE -->
    </g>
</svg>

I had a few directions in mind:

*

*Pure Javascript: setAttribute of path, which means I'll have to give each path an id?

*somehow penetrate the .svg with CSS? I tried it and its impossible to override inline SVG attributes
Have you dealt with it before (of course you did...)? What are my options?

A: As I think you've discovered, including SVG's via an img tag is limiting. Avoid it.
You can set up a sort of proxy component that fetches the SVG contents, converts them to JSX, and lets you include the SVG contents inline. This will allow them to be easily manipulated with CSS and JavaScript.
Here's a library that will handle translating the files to JSX format.
https://www.npmjs.com/package/svg-to-jsx

A: I'm answering this part: << I had a few directions in mind:
   1- Pure Javascript: setAttribute of path, which means I'll have to give each path an id? >>.
It can be the best solution, but I wouldn't use "id" because it is not reliable enough (no unicity guaranty, if inadvertently duplicated).
You want to add an attribute fill="url(#some_flag)", and your #some_flag is probably indexed somewhere (flag[i]), and linkable to the sequence of path. If #some_flag must be computed from the geometry, you may pre-process it into an array, or compute at run-time. The CSS selector can be more complex also, depending on your needs. This may answer that part of your question:
document.querySelectorAll("g > path")
.forEach((x,i) => x.setAttribute("fill",`url(${flag[i]})`));

Actually I did experiment it with a svg map excerpted from The Economist Big Mac Index (a local copy):
fetch("./bigMacSvg1.txt", {method:"GET"})
.then(res => res.text())
.then(res => {
    //console.log(res);
    document.querySelector(".here").innerHTML = res; //div for svg
    document.querySelectorAll("path:nth-child(n+2)")
    .forEach(x => x.setAttribute("fill","#a1b2c3"));
})
.catch(err => {console.log(err)});

The above code sets a light color to every country, but not to the ocean (first path).


text:
Q: Failsafe plugin for Integration tests I am reading this tutorial on how to write integration tests using failsafe plugin
https://www.javacodegeeks.com/2015/01/separating-integration-tests-from-unit-tests-using-maven-failsafe-junit-category.html
its good. but I need to write test setup hooks. in these hooks I will provision docker containers. I also need to write tear-down hooks where the containers will be shutdown.
I found this code where there is logic for create, start of container, and shutdown of container.
https://github.com/wouterd/hippo-docker/blob/master/myhippoproject/integrationtests/pom.xml
but I am not sure how will the test run and how will these goals defined in the XML get called in the right order for the integration test to run.
Basically, I need first the build-images to get called, then start-containers, then the test has to be run and finally stop-and-cleanup.
Can someone help me in connecting these dots. (these may be obvious).

A: You need to have an understanding of the Maven Lifecycle. This defines the "path" that maven will execute various phasese of the a build. If you read through the Lifecycle Reference you will see the various phases listed in order of execution.
Each of these phases can be attached to by different plugins. The particular docker maven plugin used in hippo-docker defines the different "goals" (e.g. start-containers) to be, by default, attached to the pre-integration-test lifecycle phase.
Plugins will be executed in a particular phase in the order they were declared within the pom.xml. If you have plugin-a bound to phase-x and then declare plugin-b bound to phase-x the order will be plugin-a then plugin-b.
In the case of integration tests, maven-failsafe-plugin ensures that any failures within the unit test execution are trapped and recorded so that the post-integration-test phase can run. Typically you would run "mvn verify" to ensure that you execute through pre-integration-test, integration-test, post-integration-test.


text:
Q: jquery .done() still runs before deferred.resolve() I have read several questions here on this topic and I still can't see what is wrong. I have two functions, one initializes an image from a file and reads its dimensions, setting them to object's variables. The second one checks if the dimensions are within limits.
The functions:
  checkDimensions: function() {
      console.log('entering chekDimensions');
      if (options.maxDimensionsWH > 0) {

        console.log(this.checkWidth);
        console.log(this.checkHeight);
        if ((this.checkWidth <= options.maxDimensionsWH || this.checkHeight <= options.maxDimensionsWH)
             && (this.checkWidth > 0 && this.checkHeight > 0)) {
            console.log('returning true');
            return true;
        } else {
            console.log('returning false');
            return false;
        }

    } else {
        return true;
    }
  },
  initializeCheckImage: function(file) {
    console.log('entering initialization');
    var d = $.Deferred();
    var reader = new FileReader();
      reader.onload = function (e) {
        var img = new Image;
        img.onload = function() {
          this.checkWidth = img.width;
          this.checkHeight = img.height;
          console.log('initializing the image');
          console.log(this.checkWidth);
          console.log(this.checkHeight);
          d.resolve();
        };
        console.log('assigning reader.result');
        img.src = reader.result;
      };
      console.log('assigning a file to the reader');
      reader.readAsDataURL(file);
      console.log('returning deferred');
      return d.promise();
  }

And how they are called:
this.initializeCheckImage(file).done(check = this.checkDimensions());

From the console, it is clearly visible, that execution of the second function occurs before the d.resolve(); is called.
> 21:13:34.460 entering initialization
> 21:13:34.461 assigning a file to the reader
> 21:13:34.462 returning deferred
> 21:13:34.462 entering chekDimensions
> 21:13:34.462 0
> 21:13:34.463 0
> 21:13:34.463 chekDimensions returning false
> 21:13:34.478 assigning reader.result
> 21:13:34.493 initializing the image
> 21:13:34.494 30
> 21:13:34.494 30

What am I doing wrong? Thank you!

A: The promise function is being immediatly invoked:
this.initializeCheckImage(file).done(check = this.checkDimensions());

The done function should accept as a parameter an executer:

A function that is passed with the arguments resolve and reject. The
  executor function is executed immediately by the Promise
  implementation, passing resolve and reject functions (the executor is
  called before the Promise constructor even returns the created
  object).

So it should be only a reference to function, notice that when you call it with checkDimensions() the JS execute the function immediately.
So you will need it to be wrapped with a function reference, but the problem is the context of function has changed and the checkDimensions() is no longer exist inside the new context.
In order to keep the dimension variable context you can call the checkDimensions function from inside the img.onload with:
if (checkDimensions(img.width, img.height)) {
    return d.resolve();;
}
else {
    return d.reject("Wrong dimensions");
}

this.initializeCheckImage(file)
    .then(() => console.log("RESOLVED"))
    .catch(() => console.log("REJECTED"));

Edit:
In order to keep the context of the wanted object you can use binding, with bind().
var readerOnload = function(e) {
    //code
}

reader.onload = readerOnload.bind(this);

Or with:
var self = this;

reader.onload = function() {
    //you can use self
}

In your case will have to do it once again for imgOnload.

A: I would suggest pass the value to resolve and receive on done.
  checkDimensions: function(dimensions) {
      console.log('entering chekDimensions');
      if (options.maxDimensionsWH > 0) {

        console.log(dimensions.width);
        console.log(dimensions.height);
        if ((dimensions.width <= options.maxDimensionsWH || dimensions.height <= options.maxDimensionsWH)
             && (dimensions.width > 0 && dimensions.height > 0)) {
            console.log('returning true');
            return true;
        } else {
            console.log('returning false');
            return false;
        }

    } else {
        return true;
    }
  },
  initializeCheckImage: function(file) {
    console.log('entering initialization');
    var d = $.Deferred();
    var reader = new FileReader();
      reader.onload = function (e) {
        var img = new Image;
        img.onload = function() {
          this.checkWidth = img.width;
          this.checkHeight = img.height;
          console.log('initializing the image');
          console.log(this.checkWidth);
          console.log(this.checkHeight);
          d.resolve(
          {
             width:img.width,
             height:img.height
          });
        };
        console.log('assigning reader.result');
        img.src = reader.result;
      };
      console.log('assigning a file to the reader');
      reader.readAsDataURL(file);
      console.log('returning deferred');
      return d.promise();
  }

then
this.initializeCheckImage(file).done(function(dimensions)
{
check = this.checkDimensions(dimensions)
});