text:
Q: Is it possible to click through an IFrame? So, I basically have a button inside an iframe, which is as big as the screen. Now I want to be able to click the button(in the iframe) and also interact with the page behind the iframe.
I am open for any suggestions!

A: There's not really a way to do this unfortunately. You can set pointer-events: none; on the iframe but that prevents you from interacting with it at all.
Depending on your needs, you could make sure the iframe is literally only as big as the button with no scrolling, no border, etc. That's probably your best bet if you need to iframe it.
You could, theoretically, get the X/Y coordinates of the button from the edge of the frame, and dynamically set the pointer-events: none; style if the mouse is over the frame but outside those coordinates, but… that's probably the most error-prone thing I've ever written out, shame shame shame.
Your overall best bet is to not do this, and to take the button/form/link code and host it yourself, or access it via some other API that's not hacking a partial pointer event based solution together. Next to that, just shrink the iframe to the same literal size as the button.


text:
Q: Will the new 2015 "MacBook" be able to run VMs effectively? Windows especially I currently use a 2Ghz i7 x 8gb Memory 2013 MacAir.  With this I am able to effectively run a windows 8 VM running Visual Studio Professional and other developement apps simultaneously, or Ubuntu and Eclipse with no issues.  I get an occasional memory error in windows guest if I have too much open but this is rare.
My laptop is starting to get super beat up.  I want to get the new MacBook but am concerned about the less the stellar specs on the CPU.  Has anyone ran VM's on this box yet and confirmed that it is capable of such tasks, or are we dealing with a glorified chromebook here ?
Thanks
edit
Review all but saying that this rig will not run vm's smoothly

A: As far as I know, the new MacBooks as of today have only begun shipping from online orders, so I won't be able to speak from personal experience - but I would be very wary about the MacBook being able to handle intensive tasks like Parallels, especially in tandem with Visual Studio or Eclipse.
Parallels' recommended hardware specs for running Windows 7 include "...an Intel Core 2 Duo, Core i3, Core i5, Core i7, or Xeon processor (Core Solo and Core Duo processors are no longer supported)." The new MacBook has sufficient RAM (8 GB minimum) to fulfill their requirements, but the Core M processor (see the tech specs) will be the issue with running these types of tasks on the MacBook.
Check out the benchmark details here compared to the i7 that you are using currently and you'll see a noticeable difference - Core M running at 1.1GHz which effectively makes it a mobile processor if anything.

A: The machine is slower than a MacBook Air, but definitely capable of running VMs (I remember running VMs on the first generation Intel MacBook - which was never an issue).
Try monitoring CPU usage on your Air to get an idea of how much load you put on your system. If it's frequently on the edge you probably won't be happy with the 12" MacBook. If it's in the lower percentages usually, it should work quite well.
Keep in mind that the MacBook is only available with 8GB of RAM. So if you frequently have issues with RAM usage now, you'll see a lot more of those errors..

A: It runs parallels absolutely fine, I use it to run autodesk design review on external monitor whilst having Mac running excel on macbook screen, no issues and very pleased that it can do it as well as my 16Gb Ram quad core MBPro.

A: Yes, I'm running vagrant and docker for development and have had no problems so far. I got the 1.3Ghz version with the largest drive.

A: I'm running VMWare on one now, the highest spec one and it's not usable - epic CPU usage in Windows all the time, currently unzipping a file and it's doing it @ 64KB a second! Disk IO is fast, but the brain is so small the Mac part seems to leave nothing for VMWare.

A: I use VMWare for school on my MBP on a daily basis and it works just fine.  Currently, I am working with 3 "desktops" open:

*

*Desktop 1: Stickies, Firefox w/multiple tabs open, & Activity Monitor

*Desktop 2: VMWare w/SQL Server Mgmt Studio & SQL Server Data Tools

*Desktop 3: MS Word for Mac

It is not SUPER fast but it is definitely usable with little frustration on my part.
MacBook Pro (Late 2011)

*

*Processor: 2.2 GHz Intel Core i7

*Memory: 8 GB

*Graphics: Intel HD 3000

*Storage: 500 GB

*OS: Yosemite (10.10.5)

VMWare Fusion Pro version 7.1.1

*

*OS: Windows 8 - 64-bit

*Hard Disk: 60 GB (smallest option)

*Processor: 1 core

*Memory: 3 GB

A: I am still running a core 2 duo 3.5ghz desktop iMac (late 2009)...running windows 8 and ubuntu in parallels VM.....both windows and ubuntu run OK...cpu mark for my machine is 2.049....for the new macbook its 3.096.

A: I just installed virtualbox on a 12 inch macbook, the only problem I saw is the retina display resolution. There are several ways to downsize the screen resolution to 1440x900px (and less for streaming movies on slow internet connections). Google for the following tutorial "setgetscreenres", it will lead you to a small compilable program that allows command-line access to changing the display resolution (which in OS X 10.11.5 is no longer supported in the system preferences). Here are the instructions
Changing display resolution on Retina machines while in Command Line Mode
One can then make the whole thing "clickable" with a shell script command embedded in an apple script application
do shell script "/path/to/script/set1440x900.sh"

or alike.
the script could look like
#!/bin/bash

/path/to/setgetscreenres 1440 900

To get the mac OS retina functionality back, just go to system preferences > display and select any of the options. However, performance of the VM dramatically suffers in full-screen mode, especially when handling graphics-intense tasks.
Otherwise, I can confirm that the linux VM performance of the macbook 12 inch retina is comparable to that of a macbook air 13 inch, both with 8GB RAM.
The option with the unscaled retina display output in virtualbox 5.1 works, however it is not very useful with the standard configuration of desktop environments like xfce4. One needs to adjust fonts and pointer sizes manually and still the aspect is kind of awful. It is easier to use a lower overall resolution and profit from the much better graphics performance. I am certain that there will be improvements on the VBOX side as well as more adapted desktop environments for linux some of which already support these high-res displays.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamically Update a Form in Django AFTER Initial Creation/Display Is there away to dynamically modify and validate a Django form AFTER it's been created and displayed.(I have found a few snippets that show dynamic form creation, but these require that the dynamic fields are known/defined prior to creating the form.) My requirement is different.
Use Case:
I have a form where I want to display and validate additional input fields based on the selection from a dropdown on the initial form.  Based on the selection additional fields are 1) added and 2)must then be validated with appropriate error handling.
(In case you are wondering the data elements to be added are a set of name/value pairs stored in csv format in the model, but when displayed they are shown as separate input fields - the input data will be converted to a csv string prior to saving).
I got this partially working using ajax to dynamically add the additional fields to a template, but have not found a way to validate these new fields. I'm not  sure if this is a workable approach. I could probably do this in the browser using javascript, but would prefer a Django/server side solution.

A: OK - So none responded to my question so far. However I did a bit more googling and found an excellent article that describe the solution I was looking for. Major Kudo's to the author of this blog.
Create a Django Dynamic Form with JQuery - Dynamic Field Addition and Removal


text:
Q: HttpClient stalls for long periods of time, even with timeout parameters set I have an app that is doing a non trivial amount of downloading of thumbnail images and other resources from a remote service.
I'm using a single instance of DefaultHttpClient and a custom class that I wrote that schedules all of my downloads.  All downloading is run in serial on background threads via AsyncTask.  I don't re-run my download routine until onPostExecute gets executed in the AsyncTask.
This often works perfectly.  If I queue up 20 images, my scheduler does its thing just fine.  However, I run into cases where the procedure just stalls at the point of calling client.execute (where client is my instance of DefaultHttpClient).  I can inexplicably resuscitate the process by navigating around the app and doing random actions (scrolling a list, navigating back and forth between activities, etc).  It's as if something I'm doing is sending a "wake up" message to a thread that has stalled or deadlocked.
I've added an obnoxious amount of logging at all moving parts of my application to see if something external to this procedure is causing some kind of deadlock condition.  I view LogCat by pid to see if anything else is happening in my process at the point of stalling or at the point of resuming, and I don't see anything whatsoever out of the ordinary.  The weirdest part about this is that I can duplicate the exact condition over and over.
FWIW, I have set socket timeouts and connection timeouts on both the HttpClient instance and the HttpGet instance that I pass to the execute method.  This does not cause the execute method to return early or throw an exception or anything like that.  When the procedure "kicks back in", HttpClient.execute returns a valid HttpResponse and everything operates as normal.
Any ideas on things I can debug to find out where this is getting tripped up?  I recognize that this is a very specific condition, but are there any advanced methods for specifically debugging DefaultHttpClient or http traffic in Android in general?
Thanks!

A: Do you share the same HttpClient across threads? It's not thread-safe by default, so you might want to check that. Most likely it's blocking on I/O though, so you should do some wire debugging. You can use something like this to enable HttpClient wire dump logs:
Logger.getLogger("org.apache.http.wire").setLevel(Level.FINEST);
Logger.getLogger("org.apache.http.headers").setLevel(FINEST);
Logger.getLogger("httpclient.wire.header").setLevel(FINEST);
Logger.getLogger("httpclient.wire.content").setLevel(FINEST);

System.setProperty("org.apache.commons.logging.Log",
     "org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "debug");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "debug");

To enable it, execute the following shell commands. Wire logs will be output to logcat:
adb shell setprop log.tag.org.apache.http VERBOSE
adb shell setprop log.tag.org.apache.http.wire VERBOSE
adb shell setprop log.tag.org.apache.http.headers VERBOSE

A: I have had a similar problem before.
When I try to do HTTP get in an queue, the method httpClient.execute(get); will not return a response, like deadlock.
HttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();

This is my code, and what I do is call entity.consumeContent();then it works.


text:
Q: How to retrieve variables in php sent by axios post request I want to send a POST request to a PHP script. I am using Axios:
axios.post('inc/vote.php', {
    id: this.selected,
}) .then(function (response) {
    console.log(response);
});

In the PHP file I am trying something like this to retrieve that id variable from axios:
$id = $_POST['id'];

But seems it is not doing anything.
What is the correct way to retrieve variables from the request?

A: Axios sends data as a JSON inside request body not as a Form Data. So you can't access the post data using $_POST['id'].
Frontend Solution
To be able to access data using $_POST['id'] you have to use FormData as the following:
var form = new FormData();
form.append('id', this.selected);
axios.post('inc/vote.php', {
    form
  }) .then(function (response) {
    console.log(response);
  });

Backend Solution
if you are interested in getting the request body as associative array you can use:
$data = json_decode(file_get_contents("php://input"), TRUE);
$id = $data['id'];


text:
Q: Debugging the CPU Caches I'm currently trying to optimize my software for better CPU cache usage. There are some posts on SO which suggest that it's sometimes hard to guess what the CPU cache is doing and why there are some performance drops in certain cases. For example:

*

*Why does the speed of memcpy() drop dramatically every 4KB?

*Why is my program slow when looping over exactly 8192 elements?

*Why is transposing a matrix of 512x512 much slower than transposing a matrix of 513x513?
So in order to get a clue where the cache misses happen, I can run perf to get a count of cache misses and where they occur as well as valgrind --tool=cachegrind to simulate the caches (at least an L1 and a last-level cache).
It's really nice to know where cache misses happen, but I'd like to know why they happen (for example cache trashing etc.). Is there a way to explicitly pause the program and see whats inside the caches (maybe with the program running in valgrind and vgdb attached)?

A: In my experience you'll need to disassemble your binary and, look to see where the program is using the cache. Look to see where the prefetch or cache instructions are called. That will give you the where and whys of it. It's an unfortunately painful process.


text:
Q: Access nested json property with dashes How do I deconstruct a nested json object where every level has dashes in the names?
{"my-data":{"the-values":"are-you-kidding-me?"}}
In my react app, I want to do:
const { "my-data"."the-values": value}
Or something similar to that

A: Destructure the nested object using computed property names (the brackets):

const data = {'my-data':{'the-values':'are-you-kidding-me?'}}

const { ['my-data']: { ['the-values']: value} } = data

console.log(value)


text:
Q: Using ArcGIS Desktop field calculator (python) to parse date I'm trying to parse a datetime field using python (but have never used python for it before).  I have a field that contains a valid date, but not a valid time... and other fields that have valid hour and am/pm information.  I need to grab the date (mm/dd/yy) from the datetime field and then combine that with the valid hour and am/pm fields into a new string field.
Below is the vbscript way that I would do this (and it works fine, but I need to build it using python):
    (DatePart ( "m", [STARTDATE])) &"/"&
    (DatePart ("d", [STARTDATE] )) &"/"&
    (DatePart ("yyyy", [STARTDATE] )) &" until "&
    (DatePart ( "m", [ENDDATE])) &"/"&
    (DatePart ("d", [ENDDATE] )) &"/"&
    (DatePart ("yyyy", [ENDDATE] )) &" (from "&
    [StartHour] &" "&
    [StartAMPM] &" until "&
    [EndHour] &" "&
    [EndAMPM]&" )"

Here's what I've written so far using python (but doesn't work):
    def dateFull(oid)
    startDateObj = datetime.datetime.strptime( !STARTDATE! , "%m/%d/%Y")
    endDateObj = datetime.datetime.strptime( !ENDDATE! , "%m/%d/%Y")
    return startDateObj + " to " +  endDateObj + " from " + !StartHour! + " " + !StartAMPM! + " to " + !EndHour! + " " + !EndAMPM!

Can someone please help me figure out what I'm doing wrong here?

A: Set the python parser (don't use codeblock).
I assume all input fields (!StartHour!,...) are string or date. if not bracket it with str() function
standalone python code:
startdate =  '3/1/15'
enddate =  '2/15/15'

starthour = "5"
startAMPM = "PM"
endhour = "6"
endAMPM = "AM"

print str.format("{0} to {1} from {2} {3} to {4} {5}",
startdate,
enddate,
starthour,
startAMPM,
endhour,
endAMPM)

Field calculator:
str.format("{0} to {1} from {2} {3} to {4} {5}",
!startdate!,
!enddate!,
!starthour!,
!startAMPM!,
!endhour!,
!endAMPM!)

A: It sounds like your issue is more with the malformed dates (some have times, some don't, etc...) than anything else.
You should be able to use a simple Python expression in the field calculator like this:
'{0} to {1} from {2} {3} to {4} {5}'.format(!STARTDATE!.split(' ')[0],
                                            !ENDDATE!.split(' ')[0],
                                            !StartHour!, !StartAMPM!,
                                            !EndHour!, !EndAMPM!)

The important part is the .split(' ')[0] bit. That will return just the date part for dates that have a time and won't fail for those that don't.
Another thing to note is that CalculateField passes dates to Python as strings instead of datetime objects for some reason (so no need to cast).


text:
Q: Remove all files with given extension from GIT history I realised my repository is bloated with large WAV files. I would like to strip them from the repository, including the history and all branches. Any idea on how to do this? Thanks.

A: If the file is gone from history, it is also gone from HEAD as HEAD is part of the history.
Su just use git filter-branch with an --index-filter that uses git rm --cached to eradicate any traces of the waves.


text:
Q: Job spec wraps error with Minitest::UnexpectedError after Rails 6.1 upgrade After upgrading to Rails 6.1, a test is broken:
class MyJob < ActiveJob::Base
  class MyError < StandardError; end

  def perform
    raise MyError
  end
end

describe MyJob, type: :job do
  it "throws an error" do
    expect do
      perform_enqueued_jobs { MyJob.perform_later }
    end.to raise_error(described_class::MyError)
  end
end

This spec fails with the error
expected MyJob::MyError, got #<Minitest::UnexpectedError: Unexpected exception> with backtrace:

When looking closer what error is thrown, it looks like this:
    69:
    70: describe MyJob, type: :job do
    71:   it "throws an error" do
    72:     expect do
    73:       binding.pry
 => 74:       perform_enqueued_jobs { MyJob.perform_later }
    75:     end.to raise_error(described_class::MyError)
    76:   end
    77: end

[1] pry(#<RSpec::ExampleGroups::MyJob>)> perform_enqueued_jobs { MyJob.perform_later }
Minitest::UnexpectedError: MyJob::MyError: MyJob::MyError
    /usr/src/app/spec/lib/my_job_spec.rb:5:in `perform'
    /usr/local/bundle/gems/activejob-6.1.6/lib/active_job/execution.rb:48:in `block in perform_now'
    /usr/local/bundle/gems/activesupport-6.1.6/lib/active_support/callbacks.rb:117:in `block in run_callbacks'
    /usr/local/bundle/gems/airbrake-13.0.0/lib/airbrake/rails/active_job.rb:22:in `block in perform'
    /usr/local/bundle/gems/airbrake-ruby-6.1.0/lib/airbrake-ruby/benchmark.rb:13:in `measure'
    /usr/local/bundle/gems/airbrake-13.0.0/lib/airbrake/rails/active_job.rb:21:in `perform'
    /usr/local/bundle/gems/airbrake-13.0.0/lib/airbrake/rails/active_job.rb:45:in `block (2 levels) in <module:ActiveJob>'
    /usr/local/bundle/gems/activesupport-6.1.6/lib/active_support/callbacks.rb:126:in `instance_exec'
    /usr/local/bundle/gems/activesupport-6.1.6/lib/active_support/callbacks.rb:126:in `block in run_callbacks'

It seems like the error is somehow wrapped with Minitest::UnexpectedError, but the original underlying error is still there.
Any idea how to fix this?

A: These changes were made in Rails 6.1 with perform_enqueued_jobs
So to fix your test you need to rewrite it like shown below:
describe MyJob do
  it "throws an error" do
    expect do
      described_class.perform_later
      perform_enqueued_jobs
    end.to raise_error(described_class::MyError)
  end
end


text:
Q: QGIS field calculator interpolating over raster I want to add a z field to my shapefile. Z value is the elevation of the center of the basin. I wonder how should I acomplish that. x and y values of the centroids are in the table. I have the dem of the region.

A: You'll have to convert those xy coordinates to a point feature class and then you can use the 'Point sampling tool' plugin to assign the value of your basin raster/polygon to each point (similar to the 'Extract Values to Points' tool in ArcGIS).

A: You can query the raster directly in Field Calculator. Create a new field and populate with:
raster_value('Raster', 1, make_point( x(centroid($geometry)), y(centroid($geometry))))

'Raster' is the raster layer, 1 is the band in the raster layer to use, and the make_point() function generates the centroid.


text:
Q: Using linkedin API, which is the better way of know when was accepted my invitation Which is the best way of know when was accepted an linkedin invitation using API?
I'm developing a social search web site using linkedin among other social networks.
In my site, any user, can add many linkedin user account to your site account, for then find people from linkedin using Linkedin People Search API (http://developer.linkedin.com/docs/DOC-1191.html)
with the peoples found, i could be to send and invitation or a direct message, depend of the level connection of linkedin account using for that...
Then, using Linkedin API, what is the best way to monitoring when the invitation was accepted?...

A: Per the documentation, there is no way to directly monitor messages or invitations that you send via the API to another user. So you'll need to come up with some way to monitor this off-line if it is something that you really need.  One idea would be to keep track of the ID of the member's you are sending invitations to, and on subsequent (or periodic) calls to the Connections API, you could scan the returned list to see if any of the stored ID's are now connections, and take the appropriate action.
Hope this helps!


text:
Q: how to remove a list item in a list which uses cloud firestore and javascript function renderlist(doc) {
  const listmon = document.querySelector("#item-list");

  db.collection("cafes")
    .get()
    .then((snapshot) => {
      list(snapshot.docs);
    });

  const list = (data) => {
    let html = "";
    data.forEach((doc) => {
      const guide = doc.data();
      auth.onAuthStateChanged((user) => {
        if (user) {
          const li = `

${guide.name}

              ${guide.city}

            delete

              Last updated 3 mins ago

Modal title

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

          ${guide.name}

            <button
              type="button"
              class="btn btn-secondary"
              data-dismiss="modal"
            >
              Close
            </button>
            <button type="button" class="btn btn-primary">Save changes</button>

`;
          html += li;
          listmon.innerHTML = html;
        } else {
          console.log("logged out");
        }
      });
    });
  };
}

i created it using javascript and i want to remove it by clicking a button also i have used user uid as the lists id, when ever i click the button it should remove the list and from cloud firestore it would also be great if somebody could tell me how to only show users data to that particular user,sorry for the language and thanks in advance

A: I created this simple example to list users with the methods add, delete and show info.
These Firestore/firebase documents [Queries | Modify a document | resource parts  ] can be helpful for you to understand better the methods that I used, please feel free to modify this code.

Users

        <form id="add-user-form">
            <input type="text" name="name" placeholder="user Name">
            <input type="text" name="location" placeholder="user Location">
            <button type="submit">Submit</button>
        </form>

Loading...


text:
Q: rails not registering javascript files under app/assets/javascripts I'm currently trying to integrate d3 with my rails app. After installing the d3-rails gem, I came across this tutorial on d3. Somewhere in the tutorial, the below code is provided
<meta charset="utf-8">

If I were to include the above code as it is into my new.html.erb file, the chart will show.
I then created a new graph.js fiel under app/assets/javascripts and decided to put everything between the  tag inside graph.js. Now when I open up new.html.erb, the chart will not show anymore.
Am I doing something wrong here that's causing rails to not recognize graph.js ?

A: Did you compile the assets?
You'll need to run:
rake asset:precompile


text:
Q: Add up the grades for each semester want to calculate it every tahun_akademik_id
$jumlah = DB::table('penilaian')->where('penilaian.siswa_id', '=' ,$id)->where('kategori_id','=', '2')->sum('nilai');
 $rata = DB::table('penilaian')->where('penilaian.siswa_id', '=' ,$id)->where('kategori_id','=', '2')->avg('nilai');

Database

A: You need the GROUP BY clause which is provided by the ->groupBy() function.
$jumlah = DB::table('penilaian')->where('penilaian.siswa_id', '=' ,$id)->where('kategori_id','=', '2')->groupBy('tahun_akademik_id')->sum('nilai');
 $rata = DB::table('penilaian')->where('penilaian.siswa_id', '=' ,$id)->where('kategori_id','=', '2')->groupBy('tahun_akademik_id')->avg('nilai');

A: You can use groupBy for the same
As per Laravel Documenation:

The groupBy  methods may be used to group the query results.

   $jumlah = DB::table('penilaian')
                ->where('penilaian.siswa_id', '=' ,$id)
                ->where('kategori_id','=', '2')
                ->groupBy("tahun_akademik_id") //add this
                ->sum('nilai');

 $rata = DB::table('penilaian')
            ->where('penilaian.siswa_id', '=' ,$id)
            ->where('kategori_id','=', '2')
            ->groupBy("tahun_akademik_id") //add this
            ->avg('nilai');

Laravel -> Query Builder -> Group By


text:
Q: Cannot access Tomcat Server localhost via IP address on mobile phone I want to be able to test my webpage on a mobile phone. I was using an Apache 2.2 server to host my web page locally. In this case, I connected my development machine and my phone to the same WiFi. I then accessed my localhost on my phone via the machine's external IP address.
Now, I need a servlet so I am switching my application to run on a Tomcat v7 server.  I am now unable to access my localhost via external IP address on my phone. I have tested the IP address on my development machine browser to make sure it is correct. I am trying to access port 80 on both the Apache 2.2 server and the Tomcat server.
I have checked my firewall settings, but I am assuming since port 80 works when I run my Apache 2.2 server, it should also work when I run the Tomcat server?
This is my Tomcat Connector String:
<Connector port="80" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />

Solutions I've tried: I restarted my Tomcat server after each of the following and I still cannot access my localhost
1) add the following to my connector string as posted here: https://stackoverflow.com/a/8850066/4639035
useIPVHosts="true"

2) add a inbound rule in my firewall settings (although I think port 80 has already been allowed since it works when I use my Apache 2.2 server, but I could be wrong):
http://www.mobitechie.com/android-2/how-to-access-localhost-on-android-over-wifi/
Any suggestions? Thanks!

A: `Step 1: Go to directory where tomcat is installed and look for server.xml file.Usually the path is

C:\Program Files\Apache Software Foundation\Tomcat 9.0\conf\server.xml

Open it with editor and look for connector tag.It will be like
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"/>

Add   address="0.0.0.0"   to it and change port to 80.
<Connector port="80" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
               address="0.0.0.0" />

save the file.
step 2:
Go to the firewall and network protection setting of the pc and turn off the public network firewall.
step 3:
Start the tomcat server.Then use the local ip address of pc and port 8080 (used by tomcat server as default unless you have changed it) form other device to connect with the tomcat server on the pc.

eg - http://192.168.8.137:80/ (replace 192.168.8.137 with your pc's local ip address)

A: Hi EveryOne If You want to run your localhost in your mobile phone or other devices
Step-1 : Connect Your current project running device and where you want to access that device with same network(wifi) or hotspot.
Step-2 : Open cmd and type ipconfig
Step-3 : then you will get IPv4 Address. . . . . . . . . . . : 192.168.77.84
Step-4 : Open any browser in other device and type http://192.168.77.84:8080/url
Step-5 : 192.168.77.84 change this number according to your device here 8080 my localhost port number you write your port number.
Thankyou


text:
Q: Calculating the area under multiple Peaks using Python My problem is calculating the area under the peaks in my FT-IR analysis. I usually work with Origin but I would like to see if I get a better result working with Python. The data I'm using is linked here and the code is below. The problem I'm facing is, I don't know how to find the start and the end of the peak to calculate the area and how to set a Baseline.
I found this answered question about how to calculate the area under multiple peaks but I don't know how to implement it in my code: How to get value of area under multiple peaks
import numpy as np
from numpy import trapz
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv(r'CuCO3.csv', skiprows=5)
print(df)
Wavenumber = df.iloc[:,0]
Absorbance = df.iloc[:,1]
Wavenumber_Peak = Wavenumber.iloc[700:916] #Where the peaks start/end that i want to calculate the area
Absorbance_Peak = Absorbance.iloc[700:916] #Where the peaks start/end that i want to calculate the area

plt.figure()
plt.plot(Wavenumber_Peak, Absorbance_Peak)
plt.show()

Plot of the peaks to calculate the area:

A: Okay, I have quickly added the code from the other post to your beginning and checked that it works. Unfortunately, the file that you linked did not work with your code, so I had to change some stuff in the beginning to make it work (in a very unelegant way, because I do not really know how to work with dataframes). If your local file is different and processing the file in this way does not work, then just exchange my beginning by yours.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import peakutils

df = pd.read_csv(r'CuCO3.csv', skiprows=5)

data = np.asarray([[float(y) for y in x[0].split(",")] for x in df.to_numpy()])
Wavenumber = np.arange(700, 916)
Absorbance = data[700:916,1]

indices = peakutils.indexes(Absorbance, thres=0.35, min_dist=0.1)
peak_values = [Absorbance[i] for i in indices]
peak_Wavenumbers = [Wavenumber[i] for i in indices]

plt.figure()
plt.scatter(peak_Wavenumbers, peak_values)
plt.plot(Wavenumber, Absorbance)
plt.show()

ixpeak = Wavenumber.searchsorted(peak_Wavenumbers)
ixmin = np.array([np.argmin(i) for i in np.split(Absorbance, ixpeak)])
ixmin[1:] += ixpeak
mins = Wavenumber[ixmin]

# split up the x and y values based on those minima
xsplit = np.split(Wavenumber, ixmin[1:-1])
ysplit = np.split(Absorbance, ixmin[1:-1])

# find the areas under each peak
areas = [np.trapz(ys, xs) for xs, ys in zip(xsplit, ysplit)]

# plotting stuff
plt.figure(figsize=(5, 7))
plt.subplots_adjust(hspace=.33)
plt.subplot(211)
plt.plot(Wavenumber, Absorbance, label='trace 0')
plt.plot(peak_Wavenumbers, Absorbance[ixpeak], '+', c='red', ms=10, label='peaks')
plt.plot(mins, Absorbance[ixmin], 'x', c='green', ms=10, label='mins')
plt.xlabel('dep')
plt.ylabel('indep')
plt.title('Example data')
plt.ylim(-.1, 1.6)
plt.legend()

plt.subplot(212)
plt.bar(np.arange(len(areas)), areas)
plt.xlabel('Peak number')
plt.ylabel('Area under peak')
plt.title('Area under the peaks of trace 0')
plt.show()


text:
Q: CoreData to-many relationship: "addXxxxlist" - how to replace the list completely I have a Person entity which has Contacts to-many relationship to an entity name Contact.
CoreData creates a NSSet property for me:
@property (nullable, nonatomic, retain) NSSet<Contact *> *contact_list;

What if I need to completely change the person's contact list? Can I just replace the whole set:
person.contact_list = newContactList

Or should I actually always use CoreData-generated accessors and mutators? e.g.:
person.removeContact_list(person.contact_list) // removing all the current contacts
person.addContact_list(newContactList) // setting a new contact list

Could the former approach cause database errors in the relationship configuration?
What is preferred way to completely replace a to-many relationship set?

A: I assume the core data model is like this:

Question 1: Can I just replace the whole set: person.contact_list = newContactList or should I actually always use CoreData-generated accessors and mutators?
Answer: If all data objects are formerly saved in the database, Core Data creates the same SQL update code (i'm using Swift here but with ObjC it is only syntax differences):
Prepare some objects and save it:
    // Create Persons
    let personObjA: Person = Person(context: mainContext)
    personObjA.name = "Person A"
    let personObjB: Person = Person(context: mainContext)
    personObjB.name = "Person B"
    saveContext()
    // Create Contacts
    let contactObj1: Contact = Contact(context: mainContext)
    contactObj1.name = "Contact A"
    let contactObj2: Contact = Contact(context: mainContext)
    contactObj2.name = "Contact B"
    let contactObj3: Contact = Contact(context: mainContext)
    contactObj2.name = "Contact C"
    let contactObj4: Contact = Contact(context: mainContext)
    contactObj2.name = "Contact D"
    saveContext()

Method by assign to a new contact list:
    // Set Contacts for PersonA
    personObjA.addToContacts([contactObj1,contactObj2])
    saveContext()
    // Replace Contacts for PersonA
    personObjA.contacts = [contactObj3,contactObj4]
    saveContext()

Core Data executes this SQL:
CoreData: sql: BEGIN EXCLUSIVE
CoreData: sql: UPDATE OR FAIL ZPERSON SET Z_OPT = ?  WHERE Z_PK = ? AND Z_OPT = ?
CoreData: details: SQLite bind[0] = (int64)3
CoreData: details: SQLite bind[1] = (int64)1
CoreData: details: SQLite bind[2] = (int64)2
CoreData: sql: UPDATE OR FAIL ZCONTACT SET Z2CONTACTS = ?, Z_OPT = ?  WHERE Z_PK = ? AND Z_OPT = ?
CoreData: details: SQLite bind[0] = (int64)1
CoreData: details: SQLite bind[1] = (int64)2
CoreData: details: SQLite bind[2] = (int64)2
CoreData: details: SQLite bind[3] = (int64)1
CoreData: sql: UPDATE OR FAIL ZCONTACT SET Z2CONTACTS = ?, Z_OPT = ?  WHERE Z_PK = ? AND Z_OPT = ?
CoreData: details: SQLite bind[0] = (int64)1
CoreData: details: SQLite bind[1] = (int64)2
CoreData: details: SQLite bind[2] = (int64)3
CoreData: details: SQLite bind[3] = (int64)1
CoreData: sql: COMMIT

Method by using Core Data accessors and mutators:
    // Set Contacts for PersonB
    personObjB.addToContacts([contactObj1,contactObj2])
    saveContext()
    // Replace Contacts for PersonB
    personObjB.removeFromContacts([contactObj1,contactObj2])
    personObjB.addToContacts([contactObj3,contactObj4])
    saveContext()

Core Data will execute SQL like this:
CoreData: sql: BEGIN EXCLUSIVE
CoreData: sql: UPDATE OR FAIL ZPERSON SET Z_OPT = ?  WHERE Z_PK = ? AND Z_OPT = ?
CoreData: details: SQLite bind[0] = (int64)3
CoreData: details: SQLite bind[1] = (int64)2
CoreData: details: SQLite bind[2] = (int64)2
CoreData: sql: UPDATE OR FAIL ZCONTACT SET Z2CONTACTS = ?, Z_OPT = ?  WHERE Z_PK = ? AND Z_OPT = ?
CoreData: details: SQLite bind[0] = (int64)2
CoreData: details: SQLite bind[1] = (int64)3
CoreData: details: SQLite bind[2] = (int64)2
CoreData: details: SQLite bind[3] = (int64)2
CoreData: sql: UPDATE OR FAIL ZCONTACT SET Z2CONTACTS = ?, Z_OPT = ?  WHERE Z_PK = ? AND Z_OPT = ?
CoreData: details: SQLite bind[0] = (int64)2
CoreData: details: SQLite bind[1] = (int64)3
CoreData: details: SQLite bind[2] = (int64)3
CoreData: details: SQLite bind[3] = (int64)2
CoreData: sql: COMMIT

Question 2: Could the former approach cause database errors in the relationship configuration?
Answer: If there are simple updates all done in same thread, same context (...) as described in former answer to Question 1 there will no errors in relationship.
Question 3: What is preferred way to completely replace a to-many relationship set?
Answer: If there are simple update steps all done in same thread, same context (...) as described in former answer to Question 1 both is good.


text:
Q: ReactJS call parent method over two layers typescript I got a problem to call a parents method over two layers.
It either does nothing or says, that it is not a function. So here is my Child-Component:
class Child extends React.Component {
render() { //return some awesome HTML, that at some point calls doStuff }

doStuff() {
 //do some stuff
 this.props.parentState.notifyParent();
}
}

My parent component now got some conditional stuff going on, so it looks like this:
class Parent extends React.Component {
constructor(props : any) {
        super(props);
        this.state = {
            //setSomeProps
            updateParent: this.updateParent
        };
    }
    determineUsedComponent(props: any) {
        //some conditions
            return <Child parentState={props}/>
    }
    updateParent() {
        console.log("Update parent");
    }
    render() {
        return (<this.determineUsedComponent props={this.state}/>)
    }
}

I also tried giving the function as single object to the child. Do stuff looks the following then:
doStuff() {
props.notifyParent()
}

while the Parent component then has the determineUsedComponent method with following signature:
determineUsedComponent(props: Any, updateParent: Function) {}

and it gets called:
<this.determineUsedComponent props={this.state} updateParent={this.updateParent}/>

If I then try inside the determineUsedComponent method to insert it like an attribute:
return <Child parentUpdate={this.parentUpdate}/>

It again throws the exception "this.props.notifyParent() not a function".
Instead if I write it like this:
return <Child parentUpdate={()=>this.parentUpdate}/>

There is no error, instead just nothing happens. (Also no log.)
I am very clueless and now tried every possible option of how to write the function and give it to child, but some gave errors (above two) and most didn´t do anything at all.
Any ideas?
Maybe good to mention: Child component is written in pure JS, while Parent is written in Typescript.

A: Did you try
return <Child parentUpdate={()=>this.parentUpdate()}/>

A: I didn´t manage to implement it with two layers.
However I found another solution:
You can move the conditional rendering from the "determineComponent"-method directly into the render()-method and then input the parent-function directly (syntax as DarioRega wrote it above). Then it works.


text:
Q: NULL pointer exception on timer task what i have is an image view and i have three pictures and i want the image to be changed automatically every 3 seconds , and i have used timer task to do this and here is my code:
public class MainActivity extends Activity {
    private ImageView frame;
    private int[] images = {R.drawable.boz_43, R.drawable.boz_42, R.drawable.boz_44};
    Timer timer;
    int i=0;
     private TimerTask updateTask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frame = (ImageView)findViewById(R.id.imageView1);
         timer = new Timer("TweetCollectorTimer");
         timer.schedule(updateTask, 6000L, 3000L);

         updateTask = new TimerTask() {

             @Override
             public void run() {

                MainActivity.this.runOnUiThread(new Runnable() {

                     @Override
                     public void run() { // TODO Auto-generated method stub
                         frame.setImageResource(images[i]);
                         i++;
                         if (i > 3)
                         {
                             i = 0;
                         }//if
                     }//run

                 });//runnable
             }
         };//timer task
    }
}

but each time i run my code i face a crash and it gives me a fatal exception  :
it says :
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidanim/com.example.androidanim.MainActivity}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at java.util.Timer.scheduleImpl(Timer.java:570)
at java.util.Timer.schedule(Timer.java:481)
at com.example.androidanim.MainActivity.onCreate(MainActivity.java:26)

and 26 line is :
timer.schedule(updateTask, 6000L, 3000L);

can you help me please???

A: You are using updateTask before creating it. Just call
timer.schedule(updateTask, 6000L, 3000L);

after
 updateTask = new TimerTask() { ..

A: Your updateTask is null.So use               timer.schedule(updateTask, 6000L, 3000L); after initiating updateTask
So use onCreate as
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frame = (ImageView)findViewById(R.id.imageView1);
         timer = new Timer("TweetCollectorTimer");

         updateTask = new TimerTask() {

             @Override
             public void run() {

                MainActivity.this.runOnUiThread(new Runnable() {

                     @Override
                     public void run() { // TODO Auto-generated method stub
                         frame.setImageResource(images[i]);
                         i++;
                         if (i > 3)
                         {
                             i = 0;
                         }//if
                     }//run

                 });//runnable
             }
         };//timer task
          timer.schedule(updateTask, 6000L, 3000L);
    }


text:
Q: TF object detection API detection model retraining: "object_detection.protos.SsdFeatureExtractor" has no field named "batch_norm_trainable" I'm retraining mobilenet v2 SSD using Tensorflow Object Detection API and I get this particular error on both Windows and Ubuntu environments.
My environment below is Windows 10 with python 3.5, cuda 9.0, and tensorflow-gpu 1.6. I compiled protobuf with protobuf 3.4.0.
I did the installation test and it was okay, so now I'm trying with my own dataset and getting google.protobuf.text_format.ParseError: 108:7 : Message type "object_detection.protos.SsdFeatureExtractor" has no field named "batch_norm_trainable". error.
Things I tried:

*

*Using tf 1.5 - 1.7

*Training mobilenet v1 SSD

The whole error code:
C:\Users\kazuy\models\research>python object_detection/train.py --logtostderr --train_dir="C:\\Users\\kazuy\\models\\research\\object_detection\\projects\\coco_selfcar\\tests\\test30" --pipeline_config_path="C:\\Users\\kazuy\\models\\research\\object_detection\\projects\\coco_selfcar\\ssd_mobilenet_v2_coco.config"
Traceback (most recent call last):
  File "object_detection/train.py", line 167, in <module>
    tf.app.run()
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\platform\app.py", line 126, in run
    _sys.exit(main(argv))
  File "object_detection/train.py", line 92, in main
    FLAGS.pipeline_config_path)
  File "C:\Users\kazuy\models\research\object_detection\utils\config_util.py", line 93, in get_configs_from_pipeline_file
    text_format.Merge(proto_str, pipeline_config)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 533, in Merge
    descriptor_pool=descriptor_pool)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 587, in MergeLines
    return parser.MergeLines(lines, message)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 620, in MergeLines
    self._ParseOrMerge(lines, message)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 635, in _ParseOrMerge
    self._MergeField(tokenizer, message)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 735, in _MergeField
    merger(tokenizer, message, field)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 823, in _MergeMessageField
    self._MergeField(tokenizer, sub_message)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 735, in _MergeField
    merger(tokenizer, message, field)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 823, in _MergeMessageField
    self._MergeField(tokenizer, sub_message)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 735, in _MergeField
    merger(tokenizer, message, field)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 823, in _MergeMessageField
    self._MergeField(tokenizer, sub_message)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\google\protobuf\text_format.py", line 703, in _MergeField
    (message_descriptor.full_name, name))
google.protobuf.text_format.ParseError: 108:7 : Message type "object_detection.protos.SsdFeatureExtractor" has no field named "batch_norm_trainable".

The config file that I use is mostly unchanged from the sample files from here:
# SSD with Mobilenet v2 configuration for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.

model {
  ssd {
    num_classes:3
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    anchor_generator {
      ssd_anchor_generator {
        num_layers: 6
        min_scale: 0.2
        max_scale: 0.95
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        aspect_ratios: 3.0
        aspect_ratios: 0.3333
      }
    }
    image_resizer {
      fixed_shape_resizer {
        height: 300
        width: 300
      }
    }
    box_predictor {
      convolutional_box_predictor {
        min_depth: 0
        max_depth: 0
        num_layers_before_predictor: 0
        use_dropout: false
        dropout_keep_probability: 0.8
        kernel_size: 3
        box_code_size: 4
        apply_sigmoid_to_scores: false
        conv_hyperparams {
          activation: RELU_6,
          regularizer {
            l2_regularizer {
              weight: 0.00004
            }
          }
          initializer {
            truncated_normal_initializer {
              stddev: 0.03
              mean: 0.0
            }
          }
          batch_norm {
            train: true,
            scale: true,
            center: true,
            decay: 0.9997,
            epsilon: 0.001,
          }
        }
      }
    }
    feature_extractor {
      type: 'ssd_mobilenet_v2'
      min_depth: 16
      depth_multiplier: 1.0
      use_depthwise: true
      conv_hyperparams {
        activation: RELU_6,
        regularizer {
          l2_regularizer {
            weight: 0.00004
          }
        }
        initializer {
          truncated_normal_initializer {
            stddev: 0.03
            mean: 0.0
          }
        }
        batch_norm {
          train: true,
          scale: true,
          center: true,
          decay: 0.9997,
          epsilon: 0.001,
        }
      }
      batch_norm_trainable: true
    }
    loss {
      classification_loss {
        weighted_sigmoid {
        }
      }
      localization_loss {
        weighted_smooth_l1 {
        }
      }
      hard_example_miner {
        num_hard_examples: 3000
        iou_threshold: 0.99
        loss_type: CLASSIFICATION
        max_negatives_per_positive: 3
        min_negatives_per_image: 3
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    normalize_loss_by_num_matches: true
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-8
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SIGMOID
    }
  }
}

train_config: {
  batch_size: 24
  optimizer {
    rms_prop_optimizer: {
      learning_rate: {
        exponential_decay_learning_rate {
          initial_learning_rate: 0.004
          decay_steps: 800720
          decay_factor: 0.95
        }
      }
      momentum_optimizer_value: 0.9
      decay: 0.9
      epsilon: 1.0
    }
  }
  fine_tune_checkpoint: "C:\\Users\\kazuy\\models\\research\\object_detection\\model_zoo\\ssd_mobilenet_v2_coco_2018_03_29\\model.ckpt"
  fine_tune_checkpoint_type:  "detection"
  # Note: The below line limits the training process to 200K steps, which we
  # empirically found to be sufficient enough to train the pets dataset. This
  # effectively bypasses the learning rate schedule (the learning rate will
  # never decay). Remove the below line to train indefinitely.
  num_steps: 200000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    ssd_random_crop {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "C:\\Users\\kazuy\\models\\research\\object_detection\\projects\\coco_selfcar\\tests\\test30\\train.tfrecords"
  }
  label_map_path: "C:\\Users\\kazuy\\models\\research\\object_detection\\projects\\coco_selfcar\\label_map.pbtxt"
}

eval_config: {
  num_examples: 8000
  # Note: The below line limits the evaluation process to 10 evaluations.
  # Remove the below line to evaluate indefinitely.
  max_evals: 10
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "PATH_TO_BE_CONFIGURED/mscoco_val.record"
  }
  label_map_path: "PATH_TO_BE_CONFIGURED/mscoco_label_map.pbtxt"
  shuffle: false
  num_readers: 1
}

And this is the labelmap:
item {
  id: 1
  name: 'Pedestrian'
}

item {
  id: 2
  name: 'Car'
}

item {
  id: 3
  name: 'Truck'
}

When I try the training with mobilenet v1 SSD by using a modified version of this config file I get a different error:
C:\Users\kazuy\models\research>python object_detection/train.py --logtostderr --train_dir="C:\\Users\\kazuy\\models\\research\\object_detection\\projects\\coco_selfcar\\tests\\test30" --pipeline_config_path="C:\\Users\\kazuy\\models\\research\\object_detection\\projects\\coco_selfcar\\ssd_mobilenet_v1_pets.config"
WARNING:tensorflow:From C:\Users\kazuy\models\research\object_detection\trainer.py:257: create_global_step (from tensorflow.contrib.framework.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Please switch to tf.train.create_global_step
Traceback (most recent call last):
  File "object_detection/train.py", line 167, in <module>
    tf.app.run()
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\platform\app.py", line 126, in run
    _sys.exit(main(argv))
  File "object_detection/train.py", line 163, in main
    worker_job_name, is_chief, FLAGS.train_dir)
  File "C:\Users\kazuy\models\research\object_detection\trainer.py", line 275, in train
    clones = model_deploy.create_clones(deploy_config, model_fn, [input_queue])
  File "C:\Users\kazuy\models\research\slim\deployment\model_deploy.py", line 193, in create_clones
    outputs = model_fn(*args, **kwargs)
  File "C:\Users\kazuy\models\research\object_detection\trainer.py", line 198, in _create_losses
    prediction_dict = detection_model.predict(images, true_image_shapes)
  File "C:\Users\kazuy\models\research\object_detection\meta_architectures\ssd_meta_arch.py", line 384, in predict
    preprocessed_inputs)
  File "C:\Users\kazuy\models\research\object_detection\models\ssd_mobilenet_v1_feature_extractor.py", line 121, in extract_features
    scope=scope)
  File "C:\Users\kazuy\models\research\slim\nets\mobilenet_v1.py", line 267, in mobilenet_v1_base
    scope=end_point)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\contrib\framework\python\ops\arg_scope.py", line 183, in func_with_args
    return func(*args, **current_args)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\contrib\layers\python\layers\layers.py", line 1059, in convolution
    outputs = normalizer_fn(outputs, **normalizer_params)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\contrib\framework\python\ops\arg_scope.py", line 183, in func_with_args
    return func(*args, **current_args)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\contrib\layers\python\layers\layers.py", line 651, in batch_norm
    outputs = layer.apply(inputs, training=is_training)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\layers\base.py", line 809, in apply
    return self.__call__(inputs, *args, **kwargs)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\layers\base.py", line 696, in __call__
    outputs = self.call(inputs, *args, **kwargs)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\layers\normalization.py", line 544, in call
    training_value = utils.constant_value(training)
  File "C:\Users\kazuy\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\layers\utils.py", line 240, in constant_value
    raise TypeError('`pred` must be a Tensor, a Variable, or a Python bool.')

I have been successfully training mobilenetv1 ssd models on ubuntu last month, and I started encountering this error after installing the repository from scratch today.
I'd appreciate any help! Thank you!

A: For ssd mobilenet v2, you could remove "batch_norm_trainable: true" as this field is deprecated now.


text:
Q: image comparisson, having trouble grabbing the x and y coordinate of the pixels i have the following code which compares two images and outputs how many pixels are different. I'm trying to figure out how to make it output the x and y coordinates of the pixels. Anyone have an idea?
        public int count2;
        public Boolean flag;
        private void button1_Click(object sender, EventArgs e)
        {

            string img1_ref, img2_ref;
            //this image is 10x10
            Bitmap img1 = Properties.Resources.black;
            //this image is a screenshot
            Bitmap img2 = Properties.Resources.bigimg;
                for (int i = 0; i < img1.Width; i++)
                {
                    for (int j = 0; j < img1.Height; j++)
                    {
                        img1_ref = img1.GetPixel(i, j).ToString();
                        img2_ref = img2.GetPixel(i, j).ToString();
                        if (img1_ref != img2_ref)
                        {
                            count2++;
                            flag = false;
                            break;
                        }
                    }
                }
                if (flag == false)
                    MessageBox.Show(count2 + " wrong pixels found");
        }

these are the images, and the small black square should be found in the middleish of the big image:

A: How about having a List that stores all the wrong pixels?
List<Point> wrongPixels = new List<Point>();
[...]
if (img1_ref != img2_ref){
  wrongPixels.Add(new Point(i,j));
  [...]
}
[...]
for (int i=0, max=wrongPixels.Count;i<max;i++){
  MessageBox.Show("Wrong pixel at: " + wrongPixels[i].ToString());
}


text:
Q: C# - How to decode a json array that does not contain any assignments I receive a json array that I need to decode:
[143084,[8906.3,24.990013919999996,8906.8,32.58931742,-32.6,-0.0036,8907,7171.16062768,9075,8620]]

It seems to be a valid json array but I am not sure how to decode it.
Usually I use:
JsonConvert.DeserializeObject<object>(json);

but that doesn't work here because the json code has no "assignments", for the lack of a better word.
It should be like something this:
{
"channelId":"456456564",
"values":[ "8906.3,24.990013919999996,8906.8,32.58931742,-32.6,-0.0036,8907,7171.16062768,9075,8620" ]
}

I am not even sure what to google for because I do not know the correct word for
"channelId":

All examples use json arrays that look "normal" :/
Sorry for that vague question :/
Any help would be greatly appreceated! Thanks!

A: Thanks to Daniel A. White!
I ended up doing this:
message = message.Replace("[", "");
message = message.Replace("]", "");
var array = message.Split(',');

It gives me single level array that I can now convert into the object I need.
Might not be pretty, but works. Thanks Daniel!

A: You could have a function something like this
        var jsonArray = @"[143084,[8906.3, 24.990013919999996, 8906.8, 32.58931742, -32.6, -0.0036, 8907, 7171.16062768, 9075, 8620]]";
        var deserializedArray = JArray.Parse(jsonArray);
        var result = new MyObject
        {
            channelId = deserializedArray.First.ToString(),
            values = JsonConvert.SerializeObject(deserializedArray.Last)
        };

        return result;

where MyObject looks like this:
    public class MyObject
    {
        public string channelId { get; set; }
        public string values { get; set; }
    }

This produces result:
{
  "channelId": "143084",

  "values": "[8906.3,24.990013919999996,8906.8,32.58931742,-32.6,-0.0036,8907,7171.16062768,9075,8620]"
}

A: I think that there are two options to you
1) Create a view model class that represents this
public class ViewModel
{
  public string channelId { get; set; }
  public string[] values { get; set; }
}

I'm considering that the values in the json is an array of strings with one value.
2) Use the JObject class like in this example
https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_Parse.htm


text:
Q: When to use Scala Vector, when Scala Array? If I need an Array with multiple degrees, I can't use a Vector. But let's consider the simple case of having only one degree: When to use Scala Vector, when Scala Array?

A: When it comes to time and space complexity, arrays are surprisingly versatile. You might expect that arrays are slow with regard to inserts and deletes until you consider modern memory architectures. CPUs can prefetch and stream arrays straight from memory while performing linear operations on them, such as copying for an insert or delete. Most other data-structures requires expensive indirections, defeating prefetching caches.
Immutability
Since linear access to arrays is very fast, I often (for smaller arrays) consider them as immutable and copy them on write.
How to choose
When I consider a data-structure for a certain task, I start by analyzing the performance implemented as a simple array. Only after this first step, I weigh the benefits and penalties of existing abstractions, such as vectors. Possible benefits of other data structures might be readability, code complexity, performance at scale, opportunities for garbage collection, ease of serialization and cache coherence. Readability and code complexity are on the top of my list, and this often weighs in favor of abstract data structures such as Vectors, Lists, Streams and Maps.
Consider GPU acceleration
When starting with arrays, I always consider the possibility of GPU execution. For example, machine learning heavily relies on vector (not to be confused with Scala vector) and matrix operations (linear algebra), which is accelerated on GPU hardware and often less memory intensive.

A: Choosing a data structure is, as always, a matter of context.
First of all, you have to take into account the issue at hand, the access pattern you expect to have and the performance characteristics. The Scala documentation includes a great comparison. Both collection share the common trait of being indexed, allowing fast random access, but you'll notice some differences between the two.
A key difference between the two, as suggested in the comments, is that a Vector is an immutable collection, while Arrays are mutable.
Furthermore, Arrays in Scala are effectively mapped over Java native arrays, making it quite easy to write idiomatic Scala code that can be used by just as idiomatic Java code elsewhere.
For further details, both the Array and Vector pages of the official Scala documentation include a good description. You can learn even more in the documentation section reserved to collections.


text:
Q: Regression Loop by category I have a data set that has multiple engines and I want to create a for loop function to run a linear regression for each engine and to extract the coefficients of each regression. So I want the first regression to run across the six weeks with engine= Google and then the second one to run across the six weeks with engine =Bing, etc. A sample of the data set looks like this:
Engine  Wk   Imp   Clicks  lnSpend  Actions CPA
google  1   100302  15791   10998    31     354.79
google  2   23893   4734    2866     16     179.18
google  3   318       16    37.83    11     3.44
google  4   7992    1980    1704.81  27     63.14
google  5   13206   3292    2732.13  26     105.08
google  6   10888   2966    2293.86  22     104.27
bing    1   23536   1808    1028.95  3      342.98
bing    2   86873   7196    2740.28  14     195.73
bing    3   54654   4398    1786.96  13     137.46
bing    4   45553   3353    1860.47  13     143.11
bing    5   41254   3322    1811.80  13     139.37
bing    6   38305   3117    1501.01  19     79.00

The regression equation is actions~ spend and this would remain constant across all the engines.
This is the code that I have so far:
for(i in unique(mydata$engine))
  {
  reg<- append(reg, lm(mydata$Actions~ mydata$lnspend, data=mydata[mydata$engine== i,]))
}
summary(reg)

However, when I do that, the regression runs on the full data set combining all of the engines together.
I also tried using a by function. The code that I have for that is
reg<- by(mydata$engine, function(mydata) lm(Actions~ lnspend, data=mydata))
sapply(reg, coef)

When I run that I get the following error:

"Error in unique.default(x, nmax = nmax)"

Any idea how to fix it?

A: Using data.table:
library(data.table)
mydata=data.table(mydata)
mydata[,as.list(lm(Actions~lnSpend)$coeff),by=Engine]

    Engine (Intercept)     lnSpend
1: google   17.632263 0.001318611
2:   bing    4.735979 0.004341699

A: You can also make it work by adjusting your first for loop a bit:
Engine <- c('g','g','g','g','g','g','b','b','b','b','b','b')
Actions <- c(31,16,11,27,26,22,3,14,13,13,13,19)
lnSpend <- c(10998,2866,37.83,1704.81,2732,2293,1028,2740,1786,1860,1811,1501)
df <- data.frame(Engine,Actions,lnSpend)
reg <- c()
for (eng in unique(Engine)){
  m <- lm(Actions~ lnSpend, data = df[which(df$Engine == eng),])
  reg <- append(reg, m$coeff)
}
reg
# > reg
# (Intercept)      lnSpend  (Intercept)      lnSpend
# 17.632629162  0.001318568  4.734059476  0.004344177

A: Your for/loop should work. You just did not filter your dependent and independent variables in for/loop by engine type, so R takes the full dataset:
Consider either explicitly referencing the subset filter in each variable:
for(i in unique(mydata$engine))
  {
  reg<- append(reg, lm(mydata$Actions[mydata$engine== i] ~ mydata$lnspend[mydata$engine== i],
               data=mydata[mydata$engine== i,]))
}

Or leave anonymously so data argument dictates the structure:
for(i in unique(mydata$engine))
  {
  reg<- append(reg, lm(Actions ~ lnspend,
               data=mydata[mydata$engine== i,]))
}
summary(reg)


text:
Q: Gráfico do ggplot com vãos sem que existam NA's Estou tentando plotar um gráfico de linhas que compare o PIB nominal com o PIB real. Estou usando os dados do IBGE com o pacote sidrar, além do pacote tidyverse e o janitor para manipular os dados, além do deflateBR para conseguir os valores reais do PIB com preços de 2015:
pib <- get_sidra(api = "/t/1846/n1/all/v/all/p/all/c11255/90687,90691,90696,90707/d/v585%200") %>%
    clean_names() %>%
    select(trimestre_codigo, valor, setores_e_subsetores)  %>%
    filter(trimestre_codigo >= '2015 Q1') %>%
    pivot_wider(names_from = setores_e_subsetores, values_from=valor) %>%
    mutate(presidente = case_when(trimestre_codigo < '2016 Q1' ~ "Dilma",
                               trimestre_codigo >= '2016 Q1' & trimestre_codigo < '2019 Q1' ~ "Temer",
                               trimestre_codigo >= '2019 Q1' ~ 'Bolsonaro',
  ))

pib$trimestre_codigo <- as.yearqtr(pib$trimestre_codigo,format='%Y%q')

pibreal <- deflate(pib[,5], nominal_dates = as.Date(pib$trimestre), real_date = '01-2015', index = 'ipca')
pib<- cbind(pib,pibreal)

nomes <- c('trimestre', "agropecuaria", "industria", "servicos", "pib","presidente", "pib_real_2015")
colnames(pib.corrente) <- nomes

Com esses dados consigo fazer um gráfico simples comparando o PIB nominal e o real como esse:

O código usado foi:
ggplot(pib.corrente) +
  geom_line(aes(x = trimestre, y = pib, size = 1, color = 'black') +
  geom_line(aes(x = trimestre, y = pib_real_2015, color = , size = 1, color = '#69b3a2') +
  labs(x = "Trimestre", y = "R$ (Milhões)", caption = 'Fonte: Elaboração própria com dados do IBGE',
       title = 'PIB Nominal X PIB real de 2015') +
  theme_light()
ggsave("pib nominal e real.png")

A questão é que queria destacar o período de cada governo e para isso adicionei a opção color = presidente dentro de cada aes(), ficando assim:
ggplot(pib.corrente) +
  geom_line(aes(x = trimestre, y = pib, color = as.factor(presidente)), size = 1) +
  geom_line(aes(x = trimestre, y = pib_real_2015, color =
                  as.factor(presidente)), size = 1) +
  labs(x = "Trimestre", y = "R$ (Milhões)", caption = 'Fonte: Elaboração própria com dados do IBGE',
       title = 'PIB Nominal X PIB real de 2015') +
  theme_light()

O problema é que sai do seguinte modo:

Eu tentei trocar o geom_line() por geom_path() e também tentei colocar a opção color = fora do aes(): geom_line(aes(x = trimestre, y = pib), size = 1, color = as.factor(presidente)) sem sucesso.
O que posso fazer para que as linhas do último gráfico fiquem contínuas?

A: Vou usar um exemplo genérico para facilitar a reprodução por outros usuários:
library(ggplot2)
library(dplyr)

dados <- data.frame(
  ano = 2001:2012,
  irrelevante = 5:16,
  nivel_a = Nile[1:12],
  qualquer = letters[2:13],
  nivel_b = Nile[1:12] + 1:12*100,
  grupo = rep(LETTERS[1:3], each = 4))

Como apontado nos comentários, linhas são criadas ligando os pontos dos dados. Ao quebrar em grupos de cor está definindo 3 linhas distintas, sem conexão entre elas:
ggplot(dados, aes(x = ano, color = grupo)) +
  geom_line(aes(y = nivel_a)) + geom_point(aes(y = nivel_a))  +
  geom_line(aes(y = nivel_b)) + geom_point(aes(y = nivel_b))

Pode usar geom_segment ao invés de geom_line, atribuindo a cor de cada segmento pelo grupo (presidentes, no seu caso). Para isso, precisa gerar um novo data.frame com a informação das coordenadas de início e fim de cada segmento.
dados.s <- dados %>%
  mutate(across(c("ano", starts_with("nivel")), ~lead(.x), .names = '{col}.f')) %>%
  filter(complete.cases(.))

ggplot(dados.s, aes(ano, xend = ano.f, color = grupo)) +
  geom_segment(aes(y = nivel_a, yend = nivel_a.f)) +
  geom_segment(aes(y = nivel_b, yend = nivel_b.f))

A: Apesar de não ser isto o pedido na pergunta, com os presidentes a definirem as cores não há cores diferentes para os dois PIB's e creio que é melhor deixar as cores das linhas para os PIB's e ter os presidentes assinalados em cores de fundo do gráfico.
Dados
Primeiro carregar os pacotes que vão ser utilizados e baixar os dados.
suppressPackageStartupMessages({
  library(tidyverse)
  library(janitor)
  library(zoo)
  library(sidrar)
  library(deflateBR)
  library(viridis)
})

pib <- get_sidra(api = "/t/1846/n1/all/v/all/p/all/c11255/90687,90691,90696,90707/d/v585%200") %>%
  clean_names() %>%
  select(trimestre_codigo, valor, setores_e_subsetores)  %>%
  filter(trimestre_codigo >= '2015 Q1') %>%
  pivot_wider(names_from = setores_e_subsetores, values_from = valor) %>%
  mutate(presidente = case_when(
    trimestre_codigo < '2016 Q1' ~ "Dilma",
    trimestre_codigo >= '2016 Q1' & trimestre_codigo < '2019 Q1' ~ "Temer",
    trimestre_codigo >= '2019 Q1' ~ 'Bolsonaro',
  ))

pib$trimestre_codigo <- as.yearqtr(pib$trimestre_codigo, format = '%Y%q')

pibreal <- deflate(
  nominal_values = pib[, 5],
  nominal_dates = as.Date(pib$trimestre_codigo),
  real_date = '01-2015',
  index = 'ipca'
)
pib.corrente <- cbind(pib, pibreal)

nomes <- c('trimestre', "agropecuaria", "industria", "servicos", "pib", "presidente", "pib_real_2015")
colnames(pib.corrente) <- nomes

Tabelas
O gráfico é baseado em duas tabelas, uma tabela para as linhas dos PIB's e outra para as áreas dos presidentes.
pib.plot <- pib.corrente %>%
  select(-(2:4)) %>%
  pivot_longer(
    starts_with('pib'),
    names_to = 'pib',
    values_to = 'R$'
  ) %>%
  mutate(pib = if_else(pib == 'pib', 'PIB Nominal', 'PIB Real de 2015'))

pib.rect <- pib.corrente %>%
  select(-(2:4)) %>%
  pivot_longer(starts_with('pib'), names_to = 'pib') %>%
  group_by(presidente, pib) %>%
  summarise(xstart = first(trimestre), .groups = 'drop') %>%
  arrange(xstart) %>%
  group_by(pib) %>%
  mutate(xend = lead(xstart, default = as.yearqtr(Sys.Date()))) %>%
  ungroup() %>%
  mutate(presidente = factor(presidente, levels = c('Dilma', 'Temer', 'Bolsonaro'))) %>%
  select(-pib)

Gráfico
Finalmente o gráfico.
ggplot() +
  geom_rect(
    data = pib.rect,
    mapping = aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf, fill = presidente),
    alpha = 0.1) +
  geom_line(
    data = pib.plot,
    mapping = aes(trimestre, `R$`, color = pib),
    size = 1.2) +
  scale_color_manual(values = c(`PIB Nominal` = 'black', `PIB Real de 2015` = '#69b3a2')) +
  scale_fill_viridis(discrete = TRUE, option = "H") +
  labs(
    x = "Trimestre",
    y = "R$ (Milhões)",
    caption = 'Fonte: Elaboração própria com dados do IBGE',
    title = 'PIB Nominal X PIB Real de 2015') +
  guides(
    color = guide_legend(title = "PIB"),
    fill = guide_legend(title = "Presidente")) +
  theme_light()

Created on 2022-06-01 by the reprex package (v2.0.1)


text:
Q: CommunicationException in WCF Service My problem is that AddExcursionAsync doesn't work, it shows CommunicationException.
In Console application this code works well. But in Silverlight it makes error. Functions
AddListOgTourNumbersAsync and GetListOfTourNumberAsync work correctly. Where I did the error?
Code:
private AdminServiceClient client;
    public AddExcursionDialog()
    {
        InitializeComponent();
        DurationElement.Value = new DateTime();
        client = new AdminServiceClient();
        client.GetListOfTourNumberCompleted += new EventHandler<GetListOfTourNumberCompletedEventArgs>(GetListOfTourNumber);
        client.AddListOgTourNumbersCompleted += new EventHandler<AsyncCompletedEventArgs>(AddListOfTourNumbers);
        client.AddExcursionCompleted += new EventHandler<AsyncCompletedEventArgs>(AddExcursion);
    }
    private void OKButton_Click(object sender, RoutedEventArgs e)
    {
        excursion = new Excursion();
        excursion.Name = NameText.Text;
        excursion.Cost = Convert.ToDouble(CostText.Text);
        excursion.Place = PlaceText.Text;
        excursion.Duration= (DateTime)DurationElement.Value;
        excursion.Agency_id = tour_names[AgencyCB.SelectedValue.ToString()];
        excursion.MaxPpl = Convert.ToInt32(MaxPplText.Text);
        client.GetListOfTourNumberAsync();
        client.AddExcursionAsync(excursion);
        client.AddListOgTourNumbersAsync(tour_id, excursion.NumberOfList);
        this.DialogResult = true;
    }

A: I have also battled with CommunicationException(s). At that point, I believe the network were experiencing regular problems.
In my scenario I had to stabilise this call with a retry algorithm.
I'm not saying you should do this all the time, but use it to test.
In this code, the exception is allowed to be thrown if the 3rd attempt fails.
    string[] Images64;

    try { /* 1st try */
        Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
    }
    catch (CommunicationException) {

        try { /* 2nd try */
            Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
        }
        catch (CommunicationException) {

            try { /* 3rd try */
                Images64 = _VideoClient.GetImagesStr(ImagePaths[0], ImagePaths[1], LFrame, RFrame);
            }
            catch (CommunicationException) {

                throw;
            }
        }
    }


text:
Q: Maven run ant builds in subdirectories I have multiple JavaFX 2.0 apps (built with the default ant scripts generated by netbeans 7.0) which I want to be wrapped up into a war by a maven pom in the parent directory.
The war-building pom has lots of ant tasks in the compile phase that look like this:
<ant antfile="FXapplication1/build.xml" target="jar"/>

But when I go to run 'mvn compile', I get this error from ant:
"C:\path\to\warbuilder\FXapplication1\nbproject\build-impl.xml:209: Must set src.dir"
The ant script builds fine when explicitly called inside its own directory, so I'm assuming that the problem is that it's looking in the war builder's local directory for its source files, rather than looking for them relative to the build.xml. Is there a way to specify a working path for a given ant task?

A: Try making the JavaFX apps modules of the warbuilder app, each with their own pom which executes <ant antfile="build.xml" target="jar"/>,
rather than running <ant antfile="FXapplication1/build.xml" target="jar"/> from the parent.
The parent should list the children as modules, they will then be executed as part of the parent build process.


text:
Q: how do i make my images slide in and out? ive created a slideshow on my page but instead of my pictures just changing i want them to have an effect of sliding in and out. any suggestions?

;

A: Just playing around...
LIVE DEMO
Having images the exact width as #slideshow:

All you need is:
#slideshow{
  overflow:hidden;
  width:300px;
  height:150px;
  white-space:nowrap;
  font-size:0;
}

and:
var $s = $('#slideshow'),
    $i=$('img', $s),
    N=$i.length+1,
    C=0;

$i.eq(0).clone().appendTo($s);

function anim(){
    if(C===N){$s.scrollLeft(0);C=0;}
    $s.delay(C?2000:0).animate({ scrollLeft: ++C*300 },400, anim);
}
anim(); // Use this fn 'call' wherever you want to start the animation.

What this does is an infinite slide movement achieved by simply cloning and appending the first image to the end,
this way (after we register that incremented variable C reached the total number of images) we can immediately set scrollLeft to 0 making the reset unnoticeable to the eye.
The loop is achieved by simply recalling our function anim in the .animate() callback.

If you want it to stop on mouseenter:
var $s = $('#slideshow'),
    $i = $('img', $s),
    N = $i.length+1,
    C = 0,
    m = 0; // flag for mouseover

$i.eq(0).clone().appendTo($s);

function anim(){
    if(m)return setTimeout(anim, 200);
    if(C===N){$s.scrollLeft(0);C=0;}
    $s.delay(C?2000:0).animate({ scrollLeft: ++C*300 },400, anim);
}anim();

$s.hover(function(){ m^=1; });

A: You could save yourself some time and use Bootstrap. It has this all implemented using JQuery.
http://getbootstrap.com/javascript/#carousel

        ...

    ...

    ...

A note regarding the alternative slide wrapper. When I was implementing the Bootstrap3 carousel I found that it didn't work, but if I used the Bootstrap2 slide wrappers it did. No rhyme or reason to it but that's what I found. As for where you'd put the carousel-caption div in this secondary layout. I haven't the foggiest, probably within the container and not the contributor.
The indicators you'll see at the link aren't necessary cause they're generated by the JavaScript initializer. Which is initiated like this.
$(".carousel").carousel({
    interval: false
});

But you needn't add any arguments for your purposes. I set interval:false on mine so it didn't auto-scroll but it sounds like you may want this behaviour. So all you need is .carousel(); and you can initialize by id or class. I'm initializing by class.
On a totally different note I'd suggest installing an Apache host on your machine so that your code is ready to publish. Also using windows file links like that isn't good practice and can cause all sorts of issues while you're developing especially when including CSS files. At least use relative links to the directory you're running the page from.
My personal preference is a Linux OS with Apache natively installed using SublimeText and Chrome for editing and testing respectively. But that's my preference, mainly because most of my pages are built using PHP and MySQL integration.


text:
Q: ListView onItemClickListener never triggered I created a custom view which overrides onTouchListener in order to have differents images drown depending on the action performed by the user. (To change the background of the view when the user click on it for example).
I want to use this custom view in a ListView, so I created a custom adapter which displays all my views but the onItemClickListener of my ListView is never triggered.
What can I do ?
Here's the code from my Custom View:
    @Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        setMode(MODE_SELECTED);
        invalidate();
        break;
    case MotionEvent.ACTION_UP:
        setMode(MODE_NONE);
        invalidate();
        break;
    case MotionEvent.ACTION_CANCEL:
        setMode(MODE_NONE);
        invalidate();
        break;
    case MotionEvent.ACTION_OUTSIDE:
        setMode(MODE_NONE);
        invalidate();
        break;
    default:
        break;
    }
    return true;
}

A: Ok, I found a solution : I use StateListDrawable and it avoids me to override the onTouch of my custom view !


text:
Q: How to speed up website loading for opposite side of planet I am currently running a small piece of PHP software which is being accessed by two groups of people, one group in China, the other in Ireland. The server is hosted in Ireland, and no doubt pages load between 0.3 and 0.8 seconds.
The Chinese people are recording times of between 3.0 seconds and 10 seconds.
I have run speed tests and the Chinese have an internet connection of 1.5 mbit (testing server in Ireland) and a ping of 750ms.
So far, to improve load time I have redone a lot of the MySQL database interaction to maximize efficiency, but this did not help. I presume this only slightly reduces server process time but has little effect on page download time.
I was thinking, could I get hosting in China, and use this as a gateway for the system in Ireland. Surely the latency and download speed between this Chinese server would be better than the average person.. And the average persons requests would've re-routed through here.
Does this sound at all feasible? Or does anyone else have suggestions in relation to this?

A: Your biggest problem is the latency. If you can minimize the http requests, you should see large gains.
But, it's probably easier to just the buy services of a content delivery network and move all your static files to them, making sure they have well connected servers in china and ireland. I think this is easier than redesigning your website.
The cheapest bang for the buck would come from sending suitable http headers to indicate to the web browsers that they don't need to constantly check with your servers for freshness validation(don't do conditional http requests). If you can do this for all external webpage objects(images, css, js etc...) then the first page load will still take 10 seconds or whatever, but subsequent page loads should be very close to your irish visitors. THis is just a matter of webserver configuration. Heres a tutorial if needed. To be honest, sending cache friendly headers is always a good idea, this is how you get those snappy responsive websites we all love.

A: First of Follow best practices to speed up you website.Then also check YSlow to measure your site's speed and check what you can do to improve performance.
I think that changing servers won't give you better responce time.
I think you should worry first for optimization and then check for a good and powerful hosting company and hosting plan.
Cheers

A: Hosting/mirroring in China is definitely the way to go. It'll be faster for the people there and more reliable. Ideally you would also have it hosted in Ireland too, and have some kind of load balancing in place.

A: I would definitely mirror your site to a server somewhere in asia. You already did some performance improvements that didn't result in much better results from China so I assume the network latency is causing most of the load times.
You can deploy your website to one of the cloud services. Amazon EC2 instances are available in Singapore and Tokyo for example. Or you can deploy to a "regular" web hoster in China.
If you have to deliver mostly static files, check for a Content Distribution Network (CDN) service.

A: To speed up the load time, you may consider hosting your static files (images, css, javascript, documents) to a CDN (Content Delivery Network). CDNs work by hosting your files in multiple nodes around the world. Once it receives a request, the closest server to the visitor will serve the file - thus reducing latency.
You may want to try CloudFlare (http://cloudflare.com), it's a free product that serves as a reverse proxy and CDN of your website. Instead of the user accessing the site directly, CloudFlare will be the one to access your site and optimize it for delivery to the visitor.

A: Move to the cloud.
http://en.wikipedia.org/wiki/Cloud_computing

A: I'm in the process of doing the same thing. I will create a site mirror on aliyun.com cloud. I'm hosting my site (www.discoverwish.com) at siteground in singapore, but load times for my Chinese users without VPN is incredibly slow.
I will use rsync to keep the information sync'd up, then redirect chinese users using DNSpod

A: Regarding this comment: "You may want to try CloudFlare (http://cloudflare.com), it's a free product that serves as a reverse proxy and CDN of your website. Instead of the user accessing the site directly, CloudFlare will be the one to access your site and optimize it for delivery to the visitor."
We tried this for a client in China but, unfortunately, CloudFlare don't yet have a local version of their CDN working in China. We are currently testing Amazon's CDN, which seems to have positive reviews.


text:
Q: Fechar modal depois que salvar no Banco Fala Meus amigos
Tenho o seguinte Modal:

gostaria que ao apertar em salvar ele feche o modal e atualiza somente a tabela, fiz o seguinte codigo:

Ele esta fechando porem fica td escuro na pagina e para usar tenho que carregar td novamente com o F5:

Segue o Código JS:

$('#salvarPro').click(function() {

            var Ndesc = $("#NDesc").val();
            var Nqtd = $("#NQtd").val();
            var Nvalor = $("#NValor").val();

            $.ajax({
                method: "POST",
                url: "salvar.php",
                data: {
                    desc: Ndesc,
                    qtn: Nqtd,
                    valor: Nvalor
                }
            }).done(function(resposta) {
                $('#ModalNovo').hide();
                alert(resposta);
                GerarTabela();
            }).fail(function() {
                $('#ModalNovo').hide();
                alert('falha ao Cadastrar');
                GerarTabela();
            });
        });

E o HTML do Modal:

Novo

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

                        Desc
                        <input type="text" id="NDesc" class="form-control">

                        Qtd
                        <input type="text" id="NQtd" class="form-control">

                        Valor
                        <input type="text" id="NValor" class="form-control">

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
                    <button type="button" id="salvarPro" class="btn btn-success">Salvar Produto</button>

A: VocÊ está utilizando o modo hide, que somente diminui a opacidade da modal. De um remove, ".remove()", que a modal será desfeita. Você pode até botar um fade pra não ser muito seco. Troque o hide por remove e vê se vai te ajudar.

A: Olá Consegui resolver de uma forma simples, na hr de salvar eu dei um click virtual no botão cancelar
desse jeito:

 $('#salvarPro').click(function() {

            var Ndesc = $("#NDesc").val();
            var Nqtd = $("#NQtd").val();
            var Nvalor = $("#NValor").val();

            $.ajax({
                method: "POST",
                url: "salvar.php",
                data: {
                    desc: Ndesc,
                    qtn: Nqtd,
                    valor: Nvalor
                }
            }).done(function(resposta) {
                $("#FecharModal").trigger('click');
                GerarTabela();
            }).fail(function() {
                $("#FecharModal").trigger('click');
                GerarTabela();
            });
        });

vlw a todos

A: O que eu percebi é que você está usando $('#ModalNovo').hide() mas conforme a documentação do Bootstrap o evento para fechar o modal é $('#ModalNovo').modal('hide') para exibir $('#ModalNovo').modal('show'), lá há outros eventos de controle do modal, da uma olhada lá e aconselho a usar conforme orientações deles e não fazendo .trigger() que é um paliativo.

A: Tente retirar o alert, depois me diga se funcionou, pois o alerta é bloqueante e bloqueia tudo que estiver em volta enquanto não clicar em ok, e não sei se o alert está sendo exibido, esse é o problema aparentemente.
Edit: Então talvez o erro seja na sua função GerarTabela que faz ter este comportamento porque seu códico até onde mostrou está correto, poste o códico da função que ajuda nós te ajudar :)

A: Você pode fazer isso usando o seguinte código:
$("#SuaModal").modal('hide');

Um exemplo de implementação:
           $.ajax({
                type: "post",
                url: "/Receita/Create",
                data: viewModel,
                datatype: "json",
                success: function (d) {
                    swal({
                            title: "Sucesso!",
                            text: "Item criado com sucesso.",
                            confirmButtonColor: "#66BB6A",
                            type: "success",
                        });
                        $("#ReceitaModal").modal('hide');
                },
                error: function (data) {
                    swal({
                        title: "Falha ao Cadastrar!",
                        text: "Código do erro: " + data.status + ", tente novamente.",
                        confirmButtonColor: "#EF5350",
                        type: "error"
                    });
                 //em caso de falha mantenho a modal aberta, mas se quiser pode por aqui tbm o código q falei
                }
            });


text:
Q: Spark alternatives for reading incomplete files I am using Spark 2.3 to read Parquet files. The files average about 20mb each and currently have about 20,000 of them. The file directories are partitioned down to the day level across 24 months.
The issue I am facing is that on an occasional basis most of the files are rewritten by an Hbase application. This does not occur every day, but when it does it takes several days for that process to complete for all files. My process needs to look at the data in ALL files each day to scan for changes based on an update date stored in each record. But I am finding if I read the HDFS dir during the period of the mass file rewrite, my Spark program fails and I get errors like these:
java.io.EOFException: Cannot seek after EOF
OR
java.io.IOException: Could not read footer for file: FileStatus{path=hdfs://project/data/files/year=2020/month=02/day=10/file_20200210_11.parquet
OR
Caused by: java.lang.RuntimeException: hdfs://project/data/files/year=2020/month=02/day=10/file_20200210_11.parquet is not a Parquet file. expected magic number at tail
I assume the errors are because it is trying to read a file that is not finalized (still being written to). But from Spark's perspective it looks like a corrupt file. So my process would fail and not be able to read the files for a couple days until all files are stable.
Code is pretty basic:
val readFilePath="/project/data/files/"

val df = spark.read
    .option("spark.sql.parquet.mergeSchema", "true")
    .parquet(readFilePath)
    .select(
       $"sourcetimestamp",
       $"url",
       $"recordtype",
       $"updatetimestamp"
    )
    .withColumn("end_date", to_date(date_format(lit("2021-08-23"), "yyyy-MM-dd")))
    .withColumn("start_date", date_sub($"end_date", 2))
    .withColumn("update_date", to_date($"updatetimestamp","yyyy-MM-dd"))
    .filter( $"update_date" >= $"start_date" and $"update_date" <= $"end_date" )

Is there anything I can do programmatically to work around a problem like this? It doesn't seem like I can trap an error like that and make it continue. In Spark version 3 there is an option "spark.sql.files.ignoreCorruptFiles", that I think would help, but not in version 2.3 so that doesn't help me.
I considered reading a single file at a time and loop through all files, but that would take forever (about 12 hours based on a test of just a single month). Outside of asking the application owner to write changed files to a temp dir then move and replace them as each is completed into the main dir, I don't see any other alternatives so far. Not even sure if that would help or if I would run into collisions during the small period of time the file was being moved.


text:
Q: Como pego o nome com a extensão do arquivo em uma URL em Python? Quero extrair o nome de uma imagem com sua extensão dada usa URL completa, por exemplo:
image_url = 'http://dominio.com.br/caminho/da/imagem/imagem.png'

Quero ter somente:
image = 'imagem.png'

Existe uma função pronta em Python para simplificar isso?

A: Basta pegar o valor de path da URL e dividí-la no caractere barra:
from urllib.parse import urlsplit

url = 'http://dominio.com.br/caminho/da/imagem/imagem.png'

parts = urlsplit(url)
paths = parts.path.split('/')

print(paths[-1])  # imagem.png


text:
Q: ListView + Current row + ImageButton I have a MSSQL table named "Account" which stores account info:
AccountID
SupplierID
AccountNumber
AccountDate
AccountFileName (name of pdf file)
AccountFileData (contents of PDF file, varbinary(max))
I also have a ListView (bound to table "Account" via DataSource) that displays Account info and a ImageButton inside ItemTemplate.
When I click ImageButton inside a row of ListView I want to open according PDF file.
Does anybody have an idea how can I do that?

A: That should be simple. Configure your image button in the item template and give it a CommandName and CommandArgument (bound to the ID):
 ...
 <ItemTemplate>
     ...
     <asp:ImageButton runat="server" id="foobar" CommandName="DownloadPDF" CommandArgument='"<%# Eval( "AccountID" ) #>' />
 </ItemTemplate>

Then, add the OnItemCommand to your ListView:
 <asp:ListView .... OnItemCommand="TheListView_ItemCommand"

and implement it to catch the DownloadPDF notification from the child control (the ImageButton):
    protected void TheListView_ItemCommand( object sender, ListViewCommandEventArgs e )
    {
        switch ( e.CommandName )
        {
            case "DownloadPDF":

                string accountID = e.CommandArgument;

                // now create the PDF and send it back to the client

                break;
        }
    }


text:
Q: How to auto populate email field on mfa page when display control is used in custom policies I have to use custom email template so I added a display control in my custom policy, now I have following issues because of this.

*

*When user logs in, mfa page with empty text box appears. I would like it to be auto populated.
I followed the steps provided in Populate the email address text box in Azure AD B2C Orchestration
but seems like it doesn't work with dispaly control.

*How to access/update "extension_mfaByPhoneOrEmail" field using ms graph api. I found one sample for this but it uses some id for "extension_mfaByPhoneOrEmail" which I could not find on azure portal. where I can get this id?
"https://graph.microsoft.com/v1.0/me/extensions/{{ExtensionId}}"

A: *

*You can use InputClaims elements to prepopulate the value of claims to collect from the user on the page. Any InputClaimsTransformations can be defined in the self-asserted technical profile which references this display control.
Please refer the document

*In the Graph API you will get the extentions attribute value as: extension_[GUID]_[ClaimName], To find GUID you can check in the azure portal open ad app registrations -> b2c-extensions-app -> properties -> app id.


text:
Q: SharePoint User Specific Key Value settings I need to create functionality to save user specific data like bookmark, favorites etc.
I want to know about the best approach I can take to save the user specific data so that logged in user can see their settings like we can use Property Bags to store site/web specific data.

A: You can create a user profile property and store the information in the field.
Here's a couple articles on how to interact with user profile service and properties...
http://iedaddy.com/2010/06/sharepoint-2010-updating-user-profile-properties-with-powershell/
http://iedaddy.com/2012/03/sharepoint-2010sql-view-to-get-user-profile-property-bag-values/

A: You could save these settings to a database if that is an option and you have the resources.
An easier way could be just to save the data to xml files, one for each user. I have done this before.
regards,
KS