text:
Q: nginx not serving site on cellular data connection I have a web server running nginx. If I access the website through a wifi connection, it loads the website. If I access it using LTE on my phone, it just shows the default "Welcome to nginx!" page
Here is my site config file:
server {
    listen 80;
    listen 443 ssl;
    server_name {mysite.com};

    root   /path/to/public;
    index  index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
        include   /etc/nginx/conf.d/php-fpm;
    }

    ssl_certificate /etc/letsencrypt/live/{mysite.com}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/{mysite.com}/privkey.pem;
}

A: That "Welcome" makes me suspect nginx is not reading the Host header in the request and the response is the default virtual host definition (which is the welcome message).
Remove your default vhost, on debian should be:
rm /etc/nginx/sites-enabled/default

Then add default_server to your site vhost definition:
listen 80 default_server;
listen 443 ssl default_server;

Reload: nginx -s reload
Test with curl:
curl -H "Host: mysite.com" mysite.com
curl mysite.com

The first request is sending the host header, the second does not. Both should return the same becase mysite.com is default now for ports 80 and 443 (one default_server for port).
This is like a brute force method, a smarter way would be debugging the requests, if all is correctly set up this should not happen.


text:
Q: Undefined method if @admin.save I have a really strange error, when i submit my form to create a new admin i get this error:
NoMethodError in AdminsController#create
undefined method `admin?' for #<Admin:0x6c7f098>

in line:
if @admin.save

How is this error produced? I mainly used scaffold code and i only deletet the views of the controller! Here is my controller: I thank everybody for help!
class AdminsController < ApplicationController
  before_action :set_admin, only: [ :edit, :update, :destroy]

  # GET /admins/new
  def new
    @admin = Admin.new
  end

  # GET /admins/1/edit
  def edit
  end

  # POST /admins
  # POST /admins.json
  def create
    @admin = Admin.new(admin_params)

    respond_to do |format|
      if @admin.save
        format.html { redirect_to adminpage_index_path, notice: 'Admin was successfully created.' }
      else
        redirect_to adminpage_index_path
      end
    end
  end

  # PATCH/PUT /admins/1
  # PATCH/PUT /admins/1.json
  def update
    respond_to do |format|
      if @admin.update(admin_params)
        format.html { redirect_to adminpage_index_path , notice: 'Admin was successfully updated.' }
        format.json { head :no_content }
      else
        redirect_to adminpage_index_path
      end
    end
  end

  # DELETE /admins/1
  # DELETE /admins/1.json
  def destroy
    @admin.destroy
    respond_to do |format|
      format.html { redirect_to adminpage_index_path }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_admin
      @admin = Admin.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def admin_params
      params.require(:admin).permit(:username, :vorname, :nachname, :strasse, :ort, :plz, :telefon, :handy, :email, :password, :password_confirmation)
    end
end

A: From what I can see, your Admin model probably does not inherit from ActiveRecord::Base. Make sure it does. The model should look like this:
class Admin < ActiveRecord::Base
  # ...
end

A: Your admin model has a callback of some kind.  i.e. before_save, after_save, after_validations.  Something like that that is trying to call admin?
Post admin.rb file and the stack trace of the error and this should be easy to find.

redpajama_set_name: RedPajamaStackExchange


text:
Q: change date format into "DD-MM-YYYY" I used input type "date" as below,
<input type="date" class="form-control input-sm pull-right" name="order_date" placeholder="Created At"
          id="l1" [(ngModel)]="order_date">

It gives the result with "YYYY-MM-DD" format.
I need the result as "DD-MM-YYYY" with the input type of "date'.Any idea to overcome this!

A: Use {{date | date:'ddMMyyyy'}} instead of {{date | date:'dd MM yyyy'}}

A: Use:
(ngModelChange)=setDate(order_date)

And in component:
setDate(date:Date){
  payload.date = date; // to save payload
}

A:

{{order_date| formatDate: order_date:'d/M/yyyy'}}

A: var newDatepickerDate = new Date(23/03/1999);
var startup = newDatepickerDate.toLocaleDateString();
var datePickerdate =startup.replace(/\b(\d\/)/g,'0$1');
var i = datePickerdate;
var dayMonthYear= i.replace(/(\d\d)\/(\d\d)\/(\d{4})/, "$3-$1-$2");


text:
Q: Install linux to NVMe drive w/o USB TL;DR:  How do I install Linux directly onto a NVMe for a different PC?
I am trying to fix a laptop (Microsoft Surface Go 2) where I needed to replace the NVMe & the single USB A port has decided to crap out* too (and it won't boot off the USB C port w/o or w/ a docking dongle attached--I tried a USB C thumbdrive right into the USB C port, as well as USB A thumbdrives plugged into it).
I typically use openSUSE Tumbleweed w/ KDE.  I don't think this is a distro/DE specific issue.
I have a working desktop w/ openSUSE TW, and, as of now, an external USB3 NVMe adapter. I am thinking that I can just install the OS to the laptop, but it has some different components from my home-made workstation, and I don't want to confuse my little installer.
Anyone know if there is a way to pull this off?
Can I just write a live distro to it, or do a multiboot ISO (I think I have a few options on how to do that already installed, and could boot into Windows and use one of the swell multi-boot installers) w/ either a live edition ISO or install ISO?
I just don't want grub to fire up and be all disappointed that there really isn't an NVIDIA card when it goes to switch from framebuffer to full GUI mode.  It isn't a particularly special set of components, except a very irritating Microsoft BIOS.
*Known QC problem.
PS: NVMe doesn't even have a partition table and I don't plan on installing Windows, even if it is MS HW.


text:
Q: How to get only distinct values based on one column from different tables - SQL? I have a MySQL database that I imported to Google Data Studio, and I have made the following query to get the data from multiple tables:
SELECT sw.waybill_number, sw.order_id as sworder_id, sw.status, sw.cod, sw.id AS sw_id, sw.created_at as sw_ca, c.shipping_price, c.id as c_id, oi.id as oi_id, oi.created_at as oi_ca, oi.order_id as oiorder_id, oi.product_id as oip_id, p.created_at as p_ca, p.id as p_id, p.name
FROM shipping_waybills sw
JOIN cities c
ON sw.state = c.name_en
LEFT JOIN order_items oi
ON sw.order_id = oi.order_id
LEFT JOIN products p
ON oi.product_id = p.id;

However, there are multiple values related to the column i want (sw.waybill_number), but I only want one value, it doesn't matter which one.
How can I do that??

A: Since you don't care which values are on each sw.waybill_number...
SELECT sw.waybill_number
, MIN(sw.order_id) as sworder_id
, MIN(sw.status) as status
, MIN(sw.cod) as cod
, MIN(sw.id) AS sw_id
, MIN(sw.created_at) as sw_ca
, MIN(c.shipping_price) as shipping_price
, MIN(c.id) as c_id
, MIN(oi.id) as oi_id
, MIN(oi.created_at) as oi_ca
, MIN(oi.order_id) as oiorder_id
, MIN(oi.product_id) as oip_id
, MIN(p.created_at) as p_ca
, MIN(p.id) as p_id
, MIN(p.name) as name

FROM shipping_waybills sw
  INNER JOIN cities c ON sw.state = c.name_en
  LEFT OUTER JOIN order_items oi ON sw.order_id = oi.order_id
  LEFT OUTER JOIN products p ON oi.product_id = p.id

GROUP BY sw.waybill_number


text:
Q: How to extend a SherlockFragmentActivity when implementing Facebook SDK 3.0 I'm trying to implement the Facebook SDK (3.0 beta) in an Android app that relies on ActionBarSherlock but I don't understand how since I can't extend both SherlockFragmentActivity and FacebookActivity.
The sample app in the Facebook SDK has:
public class MainActivity extends FacebookActivity {

  private static final int SPLASH = 0;
  private static final int SELECTION = 1;

And the FacebookActivity looks like:
public class FacebookActivity extends FragmentActivity {

Any ideas on how to do this?

A: extending FacebookActivity is not a requirement, but it does make your life easier when working with the Facebook integration.  See the SessionLoginSample in our sample apps to see how to integrate Facebook without using FacebookActivity.  You will just have to handle your own Session serialization and onActivityResult callbacks.
I would suggest extending SherlockFragmentActivity and then handling the Facebook integration manually.  This SO answer might also have more relevant information: http://facebook.stackoverflow.com/a/13018745/931354


text:
Q: Jquery UI 1.12.1 : Issues dynamically adding checkboxradio widget when within a tab I have an issue when adding dynamic checkradioboxes within tabs.  If I add the checkbox outside of a Tab, it generates correctly.  If I add within a Tab, the 'Tick' becomes a ^ icon.
<input type="submit" value="Add" class="submit1" name="btnGo" id="btnGo" />

Detail

Jquery Code
    $('#btnGo').unbind('click').on('click', function(e) {
        e.preventDefault();

        $('#z')
            .html('<input Type="checkbox" name="wsKh" id="wsKh" checked="checked "/>' +
                        '<input Type="checkbox" name="wsKh1" id="wsKh1" checked="checked " disabled="disabled" />');
        $('#wsKh,#wsKh1').checkboxradio();

        $('#y')
            .html('<input Type="checkbox" name="wsyKh" id="wsyKh" checked="checked "/>' +
                        '<input Type="checkbox" name="wsyKh1" id="wsyKh1" checked="checked " disabled="disabled" />');
        $('#wsyKh,#wsyKh1').checkboxradio();
    });

The problem is that the background-postion-x is wrong and I don't know what do do to correct it (the icon being shown is the ^ and not the tick).  I've made no changes.
Correct styling :
background-position-x:
-64px   jquery-ui.theme.min.css:5.ui-icon-check
initial jquery-ui.theme.min.css:5.ui-state-checked
initial jquery-ui.theme.min.css:5.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus, .ui-button:hover, .ui-button:focus
-64px   jquery-ui.min.css:7.ui-icon-check
initial jquery-ui.min.css:7.ui-state-checked
initial jquery-ui.min.css:7.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus, .ui-button:hover, .ui-button:focus

Incorrect styling :
background-position-x:
initial jquery-ui.theme.min.css:5.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus, .ui-button:hover, .ui-button:focus
initial jquery-ui.min.css:7.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus, .ui-button:hover, .ui-button:focus
-64px   jquery-ui.theme.min.css:5.ui-icon-check
initial jquery-ui.theme.min.css:5.ui-state-checked
-64px   jquery-ui.min.css:7.ui-icon-check
initial jquery-ui.min.css:7.ui-state-checked

A: When you use jQuery UI, they have a sprite sheet of all the icons then use background position to display them. (This saves them file space).
For a checkmark, they have this declared:
.ui-icon-check {
    background-position: -64px -144px;
    background-position-x: -64px;
    background-position-y: -144px;
}

However, when your checkbox is in the container ui-widget-content, they appply a background-position of initial, but when in a tab, it is set to 50% 50%.
What you can do is either target all of your checkboxes like so:
.ui-icon-check {
    background-position: -64px -144px !important;
    background-position-x: -64px;
    background-position-y: -144px;
}

or, target only the checkboxes in .ui-widget-content.
.ui-widget-content .ui-icon-check {
    background-position: -64px -144px !important;
}

Here is an updated fiddle, I chose to target all check boxes.


text:
Q: SQL: Select the same column twice in one query? I'm currently working on a query where I need to pull a list of items, as well as the date they were entered into the system and the name and user ID of the person who entered them.
My Items table contains the columns CreateDate, CreatedBy (this is the person's user ID), LastChanged (this is a date), and LastChangedBy (also a user ID, being as the person who entered the item isn't always the same person who created it).
I have the Items table joined with a User table so I can pull the first and last name of the users who match the CreatedBy and LastChangedBy user IDs. The way I have the query written now, I've concatenated the two fields so they end up displayed as "LastName, FirstName" in a single column. I also want to only pull results for a certain user, and this user just needs to be the last person who changed the item - it doesn't matter whether or not they created it.
My query looks something like this:
SELECT
    i.ItemName, i.CreateDate,
    (u.LastName + ', ' + u.FirstName) as [Created By Name],
    i.CreatedBy, i.LastChanged,
    (u.LastName + ', ' + u.FirstName) as [Last Changed By Name],
    i.LastChangedBy
FROM
    Items i
JOIN
    Users u ON i.CreatedBy = u.UserID
WHERE
    i.LastChangedBy = 0001;

My issue though is that since I have the exact same piece of code to pull the user's name both times, it's pulling the same name regardless of whether the user IDs are different in the CreatedBy and LastChangedBy columns. So I end up with results that look like this:
ItemName     CreateDate     Created By Name    CreatedBy    LastChanged    Last Changed By Name    LastChangedBy

Item A       12/01/2015     Smith, John        0001         12/03/2015     Smith, John             0001
Item B       12/02/2015     Smith, John        0001         12/04/2015     Smith, John             0001
Item C       12/02/2015     Doe, Jane          1002         12/05/2015     Doe, Jane               0001

So even though John Smith was the last person to change Item C, it's still displaying Jane Doe's name there because (I assume) the strings of code to display the user's name is the same in both instances and it's just pulling the same name both times.
Is there a way to pull the first and last names from the User table twice in the same query but make sure they correspond with the correct user IDs?

A: I think you are missing a join in your query:
SELECT i.ItemName, i.CreateDate,
       (uc.LastName + ', ' + uc.FirstName) as [Created By Name],
       i.CreatedBy, i.LastChanged,
       (ucb.LastName + ', ' + ucb.FirstName) as [Last Changed By Name],
       i.LastChangedBy
FROM Items i LEFT JOIN
     Users uc
     ON i.CreatedBy = uc.UserID LEFT JOIN
     Users ucb
     ON i.LastChangedBy = ucb.UserId
WHERE i.LastChangedBy = 0001;

You need to join twice to get both users.


text:
Q: Apache Camel ThreadPoolExecutor(InMemorySagaService) RequestContext Problem I have RequestContext class. Scope is Request context and proxyTargetClass mode. I am using it also in a aspectj class in order to log.
I am using also Apache Camel in order to provide saga pattern by using InMemorySaga service. When the service compansate it s getting an error. By the way, i m not calling as API just examining to call in proc.

Is there anyway to use RequestContext in a async thread in Apache Camel?

I have used xx.setExecutorServiceManager(new DefaultExecutorServiceManager()) with no success
    at org.apache.camel.component.bean.MethodInfo.invoke(MethodInfo.java:481)
        at org.apache.camel.component.bean.MethodInfo$1.doProceed(MethodInfo.java:300)
        at org.apache.camel.component.bean.MethodInfo$1.proceed(MethodInfo.java:273)
        at org.apache.camel.component.bean.AbstractBeanProcessor.process(AbstractBeanProcessor.java:198)
        at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:53)
        at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:548)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:138)
        at org.apache.camel.processor.Pipeline.process(Pipeline.java:101)
        at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
        at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:76)
        at org.apache.camel.processor.SharedCamelInternalProcessor.process(SharedCamelInternalProcessor.java:186)
        at org.apache.camel.processor.SharedCamelInternalProcessor.process(SharedCamelInternalProcessor.java:86)
        at org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:541)
        at org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:506)
        at org.apache.camel.impl.ProducerCache.doInProducer(ProducerCache.java:369)
        at org.apache.camel.impl.ProducerCache.sendExchange(ProducerCache.java:506)
        at org.apache.camel.impl.ProducerCache.send(ProducerCache.java:213)
        at org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:139)
        at org.apache.camel.builder.DefaultFluentProducerTemplate.send(DefaultFluentProducerTemplate.java:305)
        at org.apache.camel.impl.saga.InMemorySagaCoordinator.lambda$doFinalize$7(InMemorySagaCoordinator.java:184)
        ... 10 common frames omitted
    Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
        at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
        at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:42)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:353)
        ... 53 common frames omitted

A:     ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setThreadNamePrefix("task-executor-");
    executor.setCorePoolSize(20);
    executor.setMaxPoolSize(300);
    executor.setQueueCapacity(20000);
    executor.setDaemon(true);
    executor.afterPropertiesSet();


text:
Q: What are some ways to improve a voltage multiplier? I am working on a Nixie power supply, but I would like to improve it.

*

*I have 4x9V batteries in series for a total of 36V to be switched across a multiplier.

*A (TTL) 555 timer is running astable from only the first 9V battery to generate a 8.5-ish volt square wave, 10kHz (or any frequency you want, I guess),  approx. 50% duty.

*The 555 output drives the gate of an N-channel BS170 MOSFET.

*The MOSFET drain is connected up to 36V through an approx 1.2kΩ resistor. This resistance needs to be as low as possible to push current into:

*a 6-stage Cockcroft-Walton multiplier, which produces a nice ~220VDC output under no load. Unfortunately, it sags to about 155VDC when loaded by a 47kΩ resistor in series with the tube.

Things I like about this circuit:

*

*It Works™

*It can be built by extremely common parts I'm likely to have on-hand, e.g.:

*It requires no inductors.

*It requires no specialized IC's such as boost converters.

*It requires only capacitors and diodes with voltage ratings to handle each stage, not the full shebang.

*It crashes Multisim.

Things I don't like about this circuit:

*

*The output voltage sags to ~155VDC under only ~600μA load.

*I'm too stupid to think of a better way to switch 36V across the multiplier:

*While the 555 timer output is high, I'm wasting over 1W across the drain resistor just to drive the multiplier.

*The multiplier input voltage is hampered by the drain resistor.

How can I:

*

*make improvements that can enable ~10mA to be sourced with less than 40V drop in supply output?

I have tried:

*

*Replacing the MOSFET driver section with something like this:

simulate this circuit – Schematic created using CircuitLab
I toasted quite a few transistors trying this inverter. As shown, the gates of the inverter are pulled up to 36V by the 10kΩ resistor. Is it possible that the gate charge time is what destroyed the transistors?
EDIT: I just realized that the maximum ratings for gate-source voltage on both inverter FETs is ±20V. That would explain why they fried. Hmm, maybe instead of a single 10kΩ, I could make a voltage divider to drive each gate separately?

*

*reading the Wikipedia article regarding improvement methods:

For these reasons, CW multipliers with large number of stages are used only where relatively low output current is required. These effects can be partially compensated by increasing the capacitance in the lower stages, by increasing the frequency of the input power and by using an AC power source with a square or triangular waveform.

*

*studying other popular Nixie power supply designs, such as these.

I suspect that switching the 36V across the multiplier more efficiently would go a long way toward improving the performance.
EDIT/SUMMARY: Switching the 36V across the multiplier more efficiently went a long way toward improving the performance. As several people suggested, something called "push-pull" was a quick fix here. A CMOS inverter with separately-driven gates makes the charge pump much more effective:

The supply now stands at ~216VDC when loaded with two tubes, a huge improvement:

A: You need to ditch Rd from your first schematic, and use a low impedance push-pull output as in your second schematic. However, as you correctly say, 36v will toast the gates of 20v Vgs FETs. There are few fets with Vgsmax greater than 20v, and none to my knowledge with more than 30v.
Amongst the options are to use
a) suitable level shifters to control the FET gates, small bipolars would work well here
b) a gate drive transformer (though usually only used for higher power applications)
c) how about 18v push-pull drive from two batteries, but in push-pull, like this ...

simulate this circuit – Schematic created using CircuitLab
I've illustrated 4 stages here, the extension to more stages is obvious.
Now, I've not connected the upper capacitor. There are two options
a) Cockcroft Walton stylee, where you are limited by maximum voltage. Here, you'd connect C5 to the D1/D2 junction. This allows low voltage across each capacitor, but results in high output impedance. Also known as a Villard cascade, though invented by Greinacher.
b) Dickson charge pump stylee, which results in a much lower output impedance. C5 connects back to the driven end of C2. This means C5 needs a higher voltage rating, but if you can get caps with a suitable voltage rating cheaply, 250v or even 400v are commonly available, then this configuration has a much lower voltage droop with current.

A: Replace resistor \$R_D\$ by an inductor which gives you a boost converter.
That way you start the voltage multiplication already with voltage \$\gg 36V\$.
But make sure that

*

*the MOSFET can hable the voltage (for BS170 \$V_{DS,max}\$ is 60V) and

*the MOSFET can handle the max. current (mainly depending on operating voltage, switching frequency and inductance); for BS170 \$I_{D,max}\$ is 0.5A.

A: 36 V on the gate will destroy the devices.  You need to find proper MOSFET driving circuits.
Absolute maximum rating for BS170 Gate-Source voltage: \$|V_{GSS}| < 20~V\$.
The simplest way to fix the circuit will be to use a transistor push-pull stage. The pull-up resistor \$R_1\$ will only have to be a little bit smaller.  Say \$3.3 ~k\Omega\$?

A: as a voltage multiplier, its current output is inversely related to its voltage output. so to increase the current output, you have two choices, without stepping out the topology:
1) increase drive current: the 555 can deliver 200ma and your bs170 a few ma. you could try an emitter follower as a buffer; or a dedicated driver;
2) increase drive voltage: run the whole thing at as high of a voltage as you can;
if i were you, i would try driving the multiplier directly with the 555 first. if that doesn't deliver enough current, think about a different approach, like a step-up converter.

A: What kind of batteries do you use? The internal resistance of a 9V battery can be quite high. I think a normal alkaline can only provide around 3 Amps because of that. 36V * 3A / 220V is about 500mA at the output without considering any losses in the circuit. I think rechargeables could perform better.


text:
Q: IDW interpolation of point data using python and gdal I have a CSV file with the Lat, Long and Rainfall Information. I would like to interpolate those point and create tiff file. Can any one can suggest me the easiest way to do that.
I am trying to using gdal_grid. I am very new on using gdal in python.

A: This is actually several questions. Assuming you have some scattered data for lats and longs you'll to build all the location were you want to make estimation (all lats and longs for the pixels of you Tiff image).
Once you have that you can use any of the solutions around to do IWD over your data (using a recent example in another question):
class Estimation():
    # IWD. Check: https://stackoverflow.com/questions/36031338/interpolate-z-values-in-a-3d-surface-starting-from-an-irregular-set-of-points/36037288#36037288
    def __init__(self,lon,lat,values):
        self.x = lat
        self.y = lon
        self.v = values

    def estimate(self,x,y,using='ISD'):
        """
        Estimate point at coordinate x,y based on the input data for this
        class.
        """
        if using == 'ISD':
            return self._isd(x,y)

    def _isd(self,x,y):
        #d = np.sqrt((x-self.x)**2+(y-self.y)**2)
        d =  x.copy()
        for i in range(d.shape[0]):
            d[i] = haversine(self.x[i],self.y[i],x,y)
        if d.min() > 0:
            v = np.sum(self.v*(1/d**2)/np.sum(1/d**2))
            return v
        else:
            return self.v[d.argmin()]

The code above is actually adapted to calculate distance with the Haversine formula (which gives great-circle distances between two points on a sphere from their longitudes and latitudes). Notice again you can find all sorts of solutions for the haversine distance like this one:
def haversine(lon1, lat1, lon2, lat2):
    """
    Check: https://stackoverflow.com/questions/15736995/how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude-points
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    km = 6367 * c
    return km

Finally once you have your array ready you should just build the Tiff using GDAL. For this check the following question for which I quote a part of it's solution:
driver = gdal.GetDriverByName('GTiff')
ds = driver.Create('output.tif',xsize, ysize, 1, gdal.GDT_Float32, )
# this assumes the projection is Geographic lat/lon WGS 84
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
ds.SetProjection(srs.ExportToWkt())
gt = [ulx, xres, 0, uly, 0, yres ]
ds.SetGeoTransform(gt)
outband=ds.GetRasterBand(1)
outband.SetStatistics(np.min(mag_grid), np.max(mag_grid), np.average(mag_grid), np.std(mag_grid))
outband.WriteArray(mag_grid)


text:
Q: How can I reference a document outside of the Docusaurus docs directory? I would like to organize all of my Docusaurus docs under a docs directory. However, I would also like to reference existing markdown documents such as README.md etc. How can I reference documents that are outside the docs directory from sidebar.js?

A: My solution has been to include them as React Component
e.g. if you want to include the Readme from the root, place a file like this in your docs dir:
---
title: Custom README title (for sidebar etc)
hide_title: true
---

import Readme, { toc as ReadmeTOC } from '@site/../READ';

<Readme />

export const toc = ReadmeTOC;


text:
Q: Combine List>> to an OR clause LINQ In this example I have a list of People with some random data that are being filtered by a number of options.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        var people = GetPeople();
        ConsolePeople(GetPeopleFiltered(GetFilters(new FilterRequest {Male = true}), people));
        ConsolePeople(GetPeopleFiltered(GetFilters(new FilterRequest {Female= true}), people));
        ConsolePeople(GetPeopleFiltered(GetFilters(new FilterRequest {Male = true, TwentyToThirty = true}),people));
        ConsolePeople(GetPeopleFiltered(GetFilters(new FilterRequest {Male = true, Female=true, TwentyToThirty = true}),people));
    }

    public static void ConsolePeople(List<Person> people)
    {
        if(people.Count == 0)
            Console.WriteLine("No people found");
        foreach(var person in people)
        {
            Console.WriteLine(string.Format("FirstName: {0}, LastName: {1}, Age: {2}, Gender: {3}", person.FirstName, person.LastName, person.Age, person.Gender.ToString()));
        }
        Console.WriteLine(string.Empty);
    }

    public static List<Person> GetPeople()
    {
        var people = new List<Person>();
        people.Add(new Person { FirstName = "Philip", LastName = "Smith", Age = 29, Gender = GenderEnum.Male});
        people.Add(new Person { FirstName = "Joe", LastName = "Blogs", Age = 40, Gender = GenderEnum.Male});
        people.Add(new Person { FirstName = "Mary", LastName = "Ann", Age = 10, Gender = GenderEnum.Female});
        people.Add(new Person { FirstName = "Lisa", LastName = "Dunn", Age = 60, Gender = GenderEnum.Male});
        people.Add(new Person { FirstName = "Terry", LastName = "Banks", Age = 89, Gender = GenderEnum.Male});
        people.Add(new Person { FirstName = "John", LastName = "Doe", Age = 32, Gender = GenderEnum.Male});
        people.Add(new Person { FirstName = "Sally", LastName = "Shields", Age = 19, Gender = GenderEnum.Female});
        return people;
    }

    public static List<Expression<Func<Person, bool>>> GetFilters(FilterRequest request)
    {
        var filters = new List<Expression<Func<Person, bool>>>();
        if(request.Male)
            filters.Add(x=>x.Gender == GenderEnum.Male);
        if(request.Female)
            filters.Add(x=>x.Gender == GenderEnum.Female);
        if(request.TentoTwenty)
            filters.Add(x=>x.Age >= 10 && x.Age < 20);
        if(request.TwentyToThirty)
            filters.Add(x=>x.Age >= 20 && x.Age < 30);
        if(request.ThirtyToFourty)
            filters.Add(x=>x.Age >= 30 && x.Age < 40);
        if(request.FourtyPlus)
            filters.Add(x=>x.Age >= 40);
        return filters;
    }

    public static List<Person> GetPeopleFiltered(List<Expression<Func<Person,bool>>> filters, List<Person> people)
    {
        var query = people.AsQueryable();
        foreach(var filter in filters)
        {
            query = query.Where(filter);
        }
        return query.ToList();
    }
}

public class FilterRequest
{
    public bool Male {get;set;}
    public bool Female {get;set;}
    public bool TentoTwenty {get;set;}
    public bool TwentyToThirty {get;set;}
    public bool ThirtyToFourty {get;set;}
    public bool FourtyPlus {get;set;}
}

public class Person
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int Age {get;set;}
    public GenderEnum Gender {get;set;}
}

public enum GenderEnum
{
    Male,
    Female
}

You can see this at DotNetFiddle
I want my  List<Expression<Func<Person, bool>>> to become a list of || clauses in certain situations. So in this example if you have both male and female selected and an age range then I would expect
(x.Gender == GenderEnum.Male || x.Gender == GenderEnum.Female)
&& ((x.Age > 10 && x.Age < 20) || (x.Age >= 20 && x.Age < 30))

How do I achieve this? I know the example could be reworked differently but it is just an example.
Note: the real piece of code will be working against several millions rows of information so it should be fairly optimized.

A: Here is an implementation of a PredicateBuilder that is able to Or two expressions together:
public static class PredicateBuilder
{
    public static Expression<Func<T, bool>> True<T>() { return f => true; }
    public static Expression<Func<T, bool>> False<T>() { return f => false; }

    public static Expression<Func<T, bool>> Or<T>(
        this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var secondBody = expr2.Body.Replace(
            expr2.Parameters[0], expr1.Parameters[0]);
        return Expression.Lambda<Func<T, bool>>
              (Expression.OrElse(expr1.Body, secondBody), expr1.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(
        this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var secondBody = expr2.Body.Replace(
            expr2.Parameters[0], expr1.Parameters[0]);
        return Expression.Lambda<Func<T, bool>>
              (Expression.AndAlso(expr1.Body, secondBody), expr1.Parameters);
    }
}

public static Expression Replace(this Expression expression,
    Expression searchEx, Expression replaceEx)
{
    return new ReplaceVisitor(searchEx, replaceEx).Visit(expression);
}
internal class ReplaceVisitor : ExpressionVisitor
{
    private readonly Expression from, to;
    public ReplaceVisitor(Expression from, Expression to)
    {
        this.from = from;
        this.to = to;
    }
    public override Expression Visit(Expression node)
    {
        return node == from ? to : base.Visit(node);
    }
}

This allows you to write:
var predicate = listOfPredicateExpressions.Aggregate(PredicateBuilder.Or);

A: What you will want to do is group the filters of the same category. For example two gender filters should be or'ed, while a gender filter and an age filter should be and'ed. Therefore you will need to replace the method that returns the filter to return an enumerable of enumerables of filters. Each enumerable represents a category of filters you can have.
In the example you gave above, you will get an object that looks something like this:
{
    {
        x => x.Gender == GenderEnum.Male,
        x => x.Gender == GenderEnum.Female
    },
    {
        x => x.Age >= 10 && x.Age < 20,
        x => x.Age >= 20 && x.Age < 30
    }
}

Your query will then change into the following method:
public static List<Person> GetPeopleFiltered(IEnumerable<IEnumerable<Func<Person,bool>>> filterCategories, List<Person> people)
{
    var query = people;
    foreach(var filterCat in filterCategories)
    {
        query = query.Where(x => filterCat.Any(f => f(x)));
    }
    return query.ToList();
}

Or, getting rid of the outer foreach loop as well:
public static List<Person> GetPeopleFiltered(IEnumerable<IEnumerable<Func<Person,bool>>> filterCategories, List<Person> people)
{
    return people.Where(x => filterCategories.All(cat => cat.Any(f => f(x)))).ToList();
}

The Any method iterates through all elements of a set and if it encounters an element that yields true, it returns true. All does the same, but returns false if it enounters an element that yields false.


text:
Q: The event in jquery popup is triggered more than once I am working on a survey application using Asp.net MVc. My events in jquery popup are triggered more than once. The more a popup is opened, the more it triggers in the event in the popup. What is the reason of this. Every time browsers are opened, the temporary javascript file that starts with the VM is removed. When the popup is closed, these opened virtual javascript files are not destroyed. What is the reason of this?
These events include adding rows to the table, updating and deleting rows.The AddOrEdit.cshtml file contains both screen components and javascript codes.
Images;

AddOrEdit.cshtml(Jquery Popup)
@using MerinosSurvey.Models
@model Questions
@{
 Layout = null;
}

@using (Html.BeginForm("AddOrEdit", "Question", FormMethod.Post, new { onsubmit = "return SubmitForm(this)", onreset = "return ResetForm(this)", id = "questionForm" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })

@Html.Label("QuestionId", "Soru No", new { @class = "col-form-label col-md-3" })

@Html.TextBoxFor(model => model.QuestionId, new { @readonly = "readonly", @class = "form-control", })

@Html.Label("QuestionName", "Soru Adı", new { @class = "col-form-label col-md-3" })

@Html.EditorFor(model => model.QuestionName, new { htmlAttributes = new { @class = "form-control"
} })
@Html.ValidationMessageFor(model => model.QuestionName)

    @Html.CheckBoxFor(m => m.IsOtherOptionRequired, new { @class = "custom-control-input ", id = "IsOtherOptionRequired", })
    Diğer Seçeneği Eklensin mi?

@Html.ValidationMessageFor(model => model.Options)

Options

        <button type="button" class="btn btn-success add-new" style="margin-bottom: 10px">Add Option</button>

        Seçenek Id
        Option Name
        Update/Delete

    @foreach (Options options in Model.Options)
    {

            @options.OptionId
            @options.OptionName

                    Approve

                    Update

                    Delete

    }

 <button type="submit" class="btn btn-primary" style="margin-bottom: 10px; color: black">Kaydet</button>

}

Jquery add, edit, delete click events


text:
Q: Trying to use Dependency Injection in Blazor on Navigation Manager in c# class I'm trying to use Dependency Injection in order to use the Navigation Manager in a c# class I've created because I'm using a MVVC model. But the [Inject] isn't recognized by Visual Studio. I tried adding a "using Microsoft.AspNetCore.Components" statement, but the only Namespace i get in the suggestion is Mivrosoft.Win32.... . Is it even possible to use the Navigation manager/ inject it in a c# pure class?

A: Use the constructor injection for a class, [Inject] attribute works only for components (class deriving from ComponentBase)


text:
Q: How does this query populate data? It is my understanding that when this query runs it would not populate any data any number of times it runs because of the where clause
where c.company_id = lot.company_id
  and p.product_id = lot.product_id
  and l.packlevel_id = lot.packlevel_id

It looks to me that at the very beginning when the table fact_table_lot is empty the where clause would return with empty data because it would not find anything in an empty table and it would happen everytime. Is my understanding wrong?
insert into fact_table_lot(company_id, product_id, packlevel_id, l_num, sn_count, comm_loct, comm_start, commdate_end, man_date, exp_date, user_id, created_datetime)
select c.company_id, p.product_id, l.packlevel_id, l_num, sn_count, comm_loct, comm_start, commdate_end, man_date, exp_date, user_id, sysdate
from staging_serials s
  left outer join fact_table_lot lot on s.lotnumber = lot.l_num
  join company c on c.lsc_company_id = s.companyid
  join product p on s.compositeprodcode = p.compositeprodcode
  join level l on l.unit_of_measure = p.packaginguom
where c.company_id = lot.company_id
  and p.product_id = lot.product_id
  and l.packlevel_id = lot.packlevel_id
  and lot.created_datetime is null

A: In your query staging_serials s left outer join fact_table_lot lot on s.lotnumber= lot.l_num this will give the result set containing all records from staging_serials and since fact table is empty null values for those column from fact table. If you want no records to be returned use a inner join instead of left join.


text:
Q: bundle install --without production "gemfile:13: syntax error, unexpected keyword_end, expecting $end" I am learning RoR via The Odin Project.  Using Windows 8. I was able to do my first commit, however when I attempted a "bundle install _without production" I received the error in the question title.  In order to try and solve this error message, so far I have:

*

*Edited the gemlock file per http://guides.railsgirls.com/openshift.  eg. change pg (0.16.0-x86-mingw32) to pg (0.16.0) and sqlite3 (1.3.8-x86-mingw32) to sqlite3 (1.3.8)).

So I DID delete  x86-mingw32 from  sqlite3 file, however I did NOT find "pg" in the gemlock file. So I could not edit it.  Gemlock file:

The instructions I am following  at:
http://installfest.railsbridge.org/installfest/create_and_deploy_a_rails_app?back=create_a_heroku_account
at step 7.2 say that if I get this error:
"If this fails, get a volunteer to help you edit config/environments/production.rb"
so I opened up the "production.rb" file in Sublime Text 3, but didn't know what to edit by myself. ? I attached the screenshots of the production.rb file below:

*

*Git 1.8.4mysygit.o

*ruby 1.9.3p484 (2013-11-22) [i386-mingw32]

*rails 4.0.2

*sqlite3 (1.3.9)

Here's the Gemfile:

A: I think it's on line 10 - remove the comma:
group :production do


text:
Q: On line integrals of $\frac{xdy-ydx}{x^2 +y^2}$ There are a few questions on MSE about integrals of the form $$\int_C \frac{xdy-ydx}{x^2 +y^2},$$ where $C$ is a smooth simple closed positively oriented curve; but none of them gave me a complete understanding of what's going on.
Basically, there are two cases depending on whether $C$ encloses the origin or not. Is there a general result saying that in the former case $C$ can be replaced with a homotopic closed curve and the value of the integral won't change (a particular case of this is proved here, I believe)? If so, does it follow from the well-known similar theorems from complex analysis? In the latter case (if $C$ does not enclose the origin) I guess one cannot replace $C$ with a homotopic path. Does it have anything to do with complex analysis residues? Is such integral always zero?
(Note that I'm not familiar with winding numbers.)

A: You can rewrite $I$ as a contour integral. Let $z = x + i y$, then
$$I = \int_{\mathcal C} \frac {x dy - y dx} {x^2 + y^2} =
\int_a^b \frac {\operatorname{Im}(\overline z z')} {|z|^2} dt =
\operatorname{Im} \int_a^b \frac {z'} z dt =
\operatorname{Im} \int_{\mathcal C} \frac {dz} z.$$
This holds whether or not the curve is closed. The imaginary part of the logarithm is $\arg z$.
In vector terms, this is the two-dimensional version of Gauss's law. Let $\mathbf r = (x, y), \mathbf n = (y', -x')$. If the region $D$ enclosed by the curve does not contain the origin, then
$$I = \int_a^b \frac {\mathbf r \cdot \mathbf n} {r^2} dt =
\int_{\mathcal C} \frac {\mathbf r \cdot \mathbf n} {r^2 |\mathbf r'|} ds =
\int_{\mathcal C} \frac {\mathbf r \cdot \hat {\mathbf n}} {r^2} ds =
\iint_D \nabla \cdot \frac {\mathbf r} {r^2} dS = 0,$$
because $\nabla \cdot (\mathbf r / r^2) = 0$. Otherwise, if $\mathcal C_\epsilon$ is a small circle around the origin, the sum of $I$ and the integral over $\mathcal C_\epsilon$ with consistent orientations is zero by the same argument, and $\mathbf r \cdot \mathbf n / r^2 = \epsilon^2/\epsilon^2$ on $\mathcal C_\epsilon$.


text:
Q: Why does Web Platform installer try to repair itself every 40 mins? I'm seeing Web Platform installer do a repair/reinstall on my win 2008 r2 server (Build: 7601: Service Pack 1).
Web Platform installer has been initially installed on this machine via chef (the 'iis' and 'webpi' community cookbooks).
Now Web PI seems to have started reinstalling itself at ~40 min intervals, ultimately causing IIS to restart and disrupt my web apps on the machine.
I've tried to investigate the event logs, which do nothing to explain why this is happening / how I can prevent it.
I got a bit more info by turning on verbose logging for the MS Installer, but nothing is jumping out: http://pastebin.com/5yRYnQ0e
What would trigger Web Platform Installer to attempt to reinstall, and how would I prevent it?

A: The Google keywords are msi self repair. They uncover vast depths of related issues. The answer to this question contains detailed roundup of possible causes for self-repair: How can I determine what causes repeated Windows Installer self-repair?
In addition, the regular interval you mention could be related to the Group Policy propagation or some scheduled tasks running, that cause files\registry entries to be modified and trigger self-repair.
To rule out scheduled tasks, you could try my Windows Task Scheduler chart script and see if there some task running in the mentioned intervals.
Also, this article provides nice step-by-step debugging of MSI self-repair issue: Solving MSI self-repair issues in ThinApp


text:
Q: OpenGL how to create, and render to, a framebuffer that's larger than the window? I gather that I can create a Framebuffer with Renderbuffer and Texture attachments in whatever size I want (that's supported by the card). However, how can I actually draw to the whole thing when glViewport is limited by the GL_MAX_VIEWPORT_DIMS, which needs to be at least as large as the window, and in my case, is no larger. https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml
In my use case I'm looking to create a shadow cubemap for a point light that's a nice big sexy size. My window is 1600x900. Due to some post-processing affects that render to quads, which are downsampled, I have previous calls to glViewport that's setting the size to various things.
But I can't make it any larger than the window, so I can't ever draw to the outside areas of my Framebuffer?
Or do games never exceed the size of the window when creating framebuffers?

A: The language in the spec talking about the screen size is only part of the guaranteed minimum that needs to be supported by an implementation. The spec says:

The maximum viewport dimensions must be greater than or equal to the larger of the visible dimensions of the display being rendered to (if a display exists), and the largest renderbuffer image which can be successfully created and attached to a framebuffer object [..]

This means that GL_MAX_VIEWPORT_DIMS will also be at least as large as GL_MAX_RENDERBUFFER_SIZE. The guaranteed minimum for that limit is version dependent. It's for example 1024 in OpenGL 3.3, and 16,384 in OpenGL 4.5.
If you query GL_MAX_VIEWPORT_DIMS, you will mostly find it to be considerably larger than the screen size. It's common for it to be the same as the maximum texture size. So it shouldn't normally stop you from rendering to any texture/renderbuffer you can create.
Before rendering to the FBO, you need to make sure that you call glViewport() with the size of the render targets in your FBO. Note that the viewport size is not part of the FBO state, so you have to do this each time before starting to render to a different framebuffer (FBO or default framebuffer).
If you have the scissor test enabled, you will also need to make sure that you either disable it, or update the scissor rectangle, when switching to a FBO that is larger than your default framebuffer.


text:
Q: Facebook's Messaging Feature Review API giving permission error for page editors I have a Facebook page listed in Facebook NPI. I am an editor of that page. When I am trying to check the subscription/news messaging permission status programmatically using this api:
https://developers.facebook.com/docs/messenger-platform/reference/messaging-feature-review-api/?hc_location=ufi
I am getting the following permission error:

(#200) User does not have sufficient administrative permission for this action on this page. If the page business requires Two Factor Authentication, the user also needs to enable Two Factor Authentication.

But when Facebook page owner calls this API, it returns the status successfully.
Can anyone tell me why page editor is getting the permission error?

A: Guess that is simply considered a page management action you do not have access to using that "role".
Roles have been replaced by Tasks by now, see https://developers.facebook.com/docs/pages/overview-1#tasks
The only difference in the tasks they can perform, between old Admin and Editor roles, was MANAGE - so I guess you will need to have a page admin approve your user account for that task on the page now first, if you want to be able to use this particular API.


text:
Q: .htaccess redirect all requests to index.php even if the requested file exists I'm writing my first .htaccess file. I would like to know how to rewrite localhost/home/user/ to localhost/index.php?home&id=user even if the 'home' directory exists.
Is this possible?

A: It's a bad practice doing that, however, if you really want this the lines you need are:
RewriteEngine On
RewriteBase /

#(things you want to do beforehand)

RewriteCond %{HTTP_REFERER} !^$
RewriteRule !^http://localhost/index.php?home&id=user [R,L]
#(things you want to do after redirect)

(you may need $1 instead of 'user', depending on security you use; and $_SERVER['PHP_AUTH_USER'] from PHP if using .htpasswd from Apache)
You can add different flags of course, the RewriteRule Flags doc is here.


text:
Q: Generating a query fails for integration of Redmine and Mylyn in eclipse I installed the Redmine-Mylyn-Connector in Eclipse and had our admin install the Mylyn-Plugin for Redmine. The connection to Server seems to work:

When I try to add a query, I receive a Server Error:. Unfortunately no more details are available.

What are potential reasons for this error, and how can I solve the problem?

A: There might be useful details in the Error Log. Open the Error Log view (Alt+Shift+Q then L, or use Window > Show View...). I would clear the log first (using the red X button in its toolbar), then reproduce the error. You should see error details in the Error Log which might point you to the source of the problem.


text:
Q: How to create a backend to hide API keys in Reactjs app? I am currently developing an app using Reactjs. I had hidden my API keys and AWS keys in the dotenv file. But I just realized that this was absolutely not secured. My current set up is that my app is running in an S3 bucket on AWS, and I was wondering if I could use my EC2 instance to hide my keys from users, but still being able to get them in the app.
This is the first time I am developing an app in Reactjs and I don't really know where to start.

A: Have a look at AWS Amplify, it makes that process super easy.
Using React & AWS Amplify, you can create a serverless architecture for this type of setup with minimal work.  You can get started by following the instructions at https://aws-amplify.github.io/docs/
In a nutshel :
Install with:
npm install -g @aws-amplify/cli
$ amplify configure

Then in your project :
amplify init
amplify add api #this will create your API as AWS Lambda functions exposed through Amazon API Gateway)
amplify push #to create all this on your AWS account for you

If you search for 'aws amplify react' you will easily find a dozen blog posting showing you how to get started.  There are so many I can not recommend one in particular.


text:
Q: Figuring out how to do elementary matrix row operations by multiplication of other matrices I'm having trouble figuring out how to find matrices such that when I multiply on either side of a given matrix, I get some desired matrix out of it. For example using matrix $A$ find matrix $X$ and $Y$ such that $XAY=B$.
$$
A=
\begin{bmatrix}
a&b&0&c\\
d&e&f&0\\
0&r&s&t\\
u&0&v&w\\
\end{bmatrix}
\qquad\qquad
B=\begin{bmatrix}
v&w&u&0\\
s&t&0&r\\
f&0&d&e\\
0&c&a&b\\
\end{bmatrix}
$$
I'm running in circles trying to find the correct matrix. Is there an easier way to do this other than just brute forcing it?

A: Notice that
$$
\begin{bmatrix}
0&0&0&1\\
0&0&1&0\\
0&1&0&0\\
1&0&0&0\\
\end{bmatrix}
\begin{bmatrix}
a&b&0&c\\
d&e&f&0\\
0&r&s&t\\
u&0&v&w\\
\end{bmatrix}
\begin{bmatrix}
0&0&1&0\\
0&0&0&1\\
1&0&0&0\\
0&1&0&0\\
\end{bmatrix}
=
\begin{bmatrix}
v&w&u&0\\
s&t&0&r\\
f&0&d&e\\
0&c&a&b\\
\end{bmatrix}\;.
$$
Does this look familiar? Can you tell me why this is true?


text:
Q: Is it possible to save PHP PEAR SMTP Object as an EML file? I'm building an email to send via the PEAR Mail package, using the SMTP option;
require_once 'Mail.php';

$email  = Mail::factory('smtp', $this->connection);
$status = $email->send($content['To'], $final['headers'], $final['body']);

In addition to firing it off at the mailserver, is there a way of packaging that object  and storing it in the filesystem as an EML file?

A: No.

No, there is no way of packaging that object and storing it in the filesystem as an EML file.

A: The PEAR Mail package doesn't inherently provide that facility...
But if you use the PEAR Mail_mime package to create your email (it generates both body & headers for use by Mail::send()), then it provides a saveMessage() method to do just that:
https://pear.php.net/package/Mail_Mime/docs/latest/Mail_Mime/Mail_mime.html#methodsaveMessage
You would have to include the To: header as an additional parameter when calling this method, or it wouldn't be included in the saved file.
I'm not sure if Mail_mime always generates multi-part MIME-format emails, or if it can also generate regular plaintext email if that's all you provide to it, so you might want to check that.


text:
Q: adding loggers to Grails classes I use the following approach to access a logger instance from classes in a Grails app:
In Grails artefacts (controllers, services, domain classes, etc.) I simply use the logger that is added by Grails, e.g.
class MyController {
  def someAction() {
    log.debug "something"
  }
}

For classes under src/groovy I annotate them with @groovy.util.logging.Slf4j, e.g.
@Slf4j
class Foo {

  Foo() {
    log.debug "log it"
  }
}

The logger seems to behave properly in both cases, but it slightly bothers me that the class of the loggers differs. When I use the annotation, the class of the logger is org.slf4j.impl.GrailsLog4jLoggerAdapter, but when I use the logger that's automatically added to Grails artefacts the class is org.apache.commons.logging.impl.SLF4JLog.
Is there a recommended (or better) approach to adding loggers to Grails classes?

A: I don't see any problem with what you described. SLF4J isn't a logging framework, it's a logging framework wrapper. But aside from some Grails-specific hooks in the Grails class, they both implement the same interface and delegate eventually to the same loggers/appenders/etc. in the real  implementation library, typically Log4j.
What I'm pretty sure is different though is the log category/name, because you need to configure the underlying library based on what the logger names become. With annotations the logger name is the same as the full class name an package. With the one Grails adds, there's an extra prefix based on the artifact type. I always forget the naming convention but a quick way to know the logger name is to log it; add this in your class where it will be accessed at runtime:
println log.name

and it will print the full logger name (using println instead of a log method avoids potential misconfiguration issues that could keep the message from being logged
I like to keep things simple and consistent and know that being used, so I skip the wrapper libraries and use Log4j directly. Access the logger is easy. Import the class
import org.apache.log4j.Logger

and then add this as a class field:
Logger log = Logger.getLogger(getClass().name)

This can be copy/pasted to other classes since there's no hard-coded names. It won't work in static scope, so for that I'd add
static Logger LOG = Logger.getLogger(this.name)

which also avoids hard-coding by using Groovy's support for "this" in static scope to refer to the class.

A: Have you tried the @Log4j (for log4j) instead.
@Log4j (for log4j)

How can i use 'log' inside a src/groovy/ class


text:
Q: Removing SOME line breaks from srt/txt file I have a text file which has numbered entries, a timecode and a transcript. I am trying to remove the line breaks in the transcript and leave the others. I'm trying to use grep or awk.
File is like

1
  00:00:27,160 --> 00:00:29,054
  Sometimes there's not much dialogue.

  2
  00:00:30,100 --> 00:00:31,090
  But other times there is quite a bit,
  and it's formatted into two lines

  3
  00:00:31,500 --> 00:00:33,700
  I want to remove the line breaks only on
  these long lines, leaving all other formatting.

  4
  00:00:33,805 --> 00:00:37,285
  So that all dialogue ends up being on a single
  line no matter how long that line.

Output would look like:

1
  00:00:27,160 --> 00:00:29,054
  Sometimes there's not much dialogue.

  2
  00:00:30,100 --> 00:00:31,090
  But other times there is quite a bit,
  and it's formatted into two lines

  3
  00:00:31,500 --> 00:00:33,700
  I want to remove the line breaks only on
  these long lines, leaving all other formatting.

  4
  00:00:33,805 --> 00:00:37,285
  So that all dialogue ends up being on a single line no matter how long that line.

thanks to all who have provided help

A: Don't rely on lines starting (or not) with any specific characters - just attach the 4th and subsequent lines in each record to the end of the 3rd line of that record:
$ awk '
BEGIN { RS=ORS=""; FS=OFS="\n" }
{
    print $1,$2,$3
    for (i=4;i<=NF;i++)
        printf " %s", $i
    print "\n\n"
}
' file
1
00:00:27,160 --> 00:00:29,054
Sometimes there's not much dialogue.

2
00:00:30,100 --> 00:00:31,090
But other times there is quite a bit, and it's formatted into two lines

3
00:00:31,500 --> 00:00:33,700
I want to remove the line breaks only on these long lines, leaving all other formatting.

4
00:00:33,805 --> 00:00:37,285
So that all dialogue ends up being on a single line no matter how long that line.

A: Delete all new lines that are preceded by a letter or a space or tab:
perl -pe 's/([a-zA-Z \t])\n$/$1/'

A: I think you need something like
awk '/[0-9]+/,/^$/{ if(NR<3) print $0; else {while($0!=""){ printf $0;next; }}}' file

It's not working, but you may get the idea.

A: You can try something like this with awk:
awk '!NF{print}/[a-z]/{printf "%s ", $0;next}1' file

$ cat file
1
00:00:27,160 --> 00:00:29,054
Sometimes there's not much dialogue.

2
00:00:30,100 --> 00:00:31,090
But other times there is quite a bit,
and it's formatted into two lines

3
00:00:31,500 --> 00:00:33,700
I want to remove the line breaks only on
these long lines, leaving all other formatting.

4
00:00:33,805 --> 00:00:37,285
So that all dialogue ends up being on a single
line no matter how long that line.

$ awk '!NF{print}/[a-z]/{printf "%s ", $0;next}1' file
1
00:00:27,160 --> 00:00:29,054
Sometimes there's not much dialogue.

2
00:00:30,100 --> 00:00:31,090
But other times there is quite a bit,  and it's formatted into two lines

3
00:00:31,500 --> 00:00:33,700
I want to remove the line breaks only on these long lines, leaving all other formatting.

4
00:00:33,805 --> 00:00:37,285
So that all dialogue ends up being on a single line no matter how long that line.

A: I had the same problem and wrote this little code, which solved my problem:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
FILE *quelle,*ziel;
int i;
long maxsub,count,tmp,sub;
char puffer[10][200], *ptr,line[400];

if(argc != 3)
    {
    printf("Usage: srtlinejoin Filename CountOfSubtitles\n");
    return EXIT_FAILURE;
    }

maxsub = strtol( argv[2], &ptr, 10);

if( (quelle=fopen(argv[1],"r")) == NULL) {
        fprintf(stderr, "Can't open %s\n", argv[1]);
        return EXIT_FAILURE;
    }
if( (ziel=fopen("out.srt","w")) == NULL) {
        fprintf(stderr, "Can't open out.srt\n");
    fclose(quelle);
        return EXIT_FAILURE;
    }

//read and write first line
fgets(puffer[0], 200, quelle);
fputs(puffer[0], ziel);

for(count=1; count < maxsub;count++)
//for(count=1; count <= 3;count++)
    {
    //printf("Processing subtitle %d\n",count);

    tmp=0;
    //Read and write time
    fgets(puffer[0], 200, quelle);
    fputs(puffer[0], ziel);

    do  {
        fgets(puffer[tmp], 200, quelle);
        //Scan for next Subtitle
        sub = strtol( puffer[tmp], &ptr, 10);
        tmp++;
        }
    while(sub != (count+1));

    //Der Untertitel hat nur eine Zeile
    if (strlen(puffer[1]) == 2)
        {
        fputs(puffer[0], ziel);     //New Subtitle
        fputs(puffer[1], ziel);     //Next empty line
        fputs(puffer[2], ziel);     //Next number
        }

    //Der Untertitel hat zwei Zeile
    if ((strlen(puffer[1]) > 2) && (strlen(puffer[2]) == 2))
        {
        for(i=0;i<400;i++)
            line[i]=0;

        strncpy(line,puffer[0],(strlen(puffer[0])-2));
        strcat(line," ");
        strcat(line,puffer[1]);
        fputs(line, ziel);      //New Subtitle
        fputs(puffer[2], ziel); //Next empty line
        fputs(puffer[3], ziel); //Next number
        }

    //Der Untertitel hat mehr als zwei Zeile
    if ((strlen(puffer[1]) == 2) && (strlen(puffer[2]) == 2))
        {
        printf("Attention: The subtitles has more than two lines\n");
        }
    }

printf("Check last subtitle!\n");

fclose(quelle);
fclose(ziel);
return EXIT_SUCCESS;
}


text:
Q: AutoIT send() commands not working properly So I have a game client with 2 input fields: id pass and 1 button: login.
My login credentials are: $id=1234 and $pass=a_bCd.
I'm using AutoIT scripting to automate the login process (my script automatically inputs the id and pass in the login fields) and my AutoLogin() function looks like:
send($id + "{tab}")
Sleep(10)
send($pass + "{enter}")

Sometimes it works fine, but sometimes my script introduces 1234a- or 1234a_ in the ID field and the rest of the characters in the pass field. I tried many solutions like controlsend("Game","","","1234{tab}a_bCd{enter}"), or changing sleep() values, etc. but the input still goes wrong sometimes. Figured the send delay or sleep would have the problem, still don't know what to do.
Manually inserting the id and pass works properly. What would be a good solving of this problem? Thanks

A: I have had the same troubles with send. This post on autoitscript.com may help you with WinAPI_Keybd_Event() (documentation here):
#include <WinAPISys.au3>
_WinAPI_Keybd_Event(0x11, 0) # Push CTRL down
_WinAPI_Keybd_Event(0x11, 2) # Lift CTRL up again

This helped me with my problems.
NOTE: Sometimes, when your script breaks because of an error, it may happen that one of the keys on your keyboard is still pressed (i.e. pushed down but never lifted up). I use the on-screen keyboard that is integrated in Windows for these moments...

A: 2 Solutions:
You add Strings with &:
send($id & "{tab}")
send($pass & "{enter}")

If that does not work just separate it:
send($id)
send("{tab}")
send($pass)
send("{enter}")

And you don't need that sleep


text:
Q: Make a GET request to Parse API in Objective-C curl -X GET  -H "X-Parse-Application-Id: XYZ"   -H "X-Parse-REST-API-Key: XYZ" -G  --data-urlencode 'where={"col1":"val1", "col2":"val2"}' https://api.parse.com/1/classes/ClassName/

I tried to convert the above curl command to the following code in Objective-C, but to no avail.
responseData = [NSMutableData data];
NSString* classURL = @"https://api.parse.com/1/classes/ClassName/";
NSURL* url = [NSURL URLWithString:classURL];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:APP_ID forHTTPHeaderField:@"X-Parse-Application-Id"];
[request setValue:REST_API_KEY forHTTPHeaderField:@"X-Parse-REST-API-Key"];

NSString *qryString = [NSString stringWithFormat:@"where={\"col1\":\"%@\", \"col2\":\"%@\"}", val1, val2];
[request setHTTPBody:[qryString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
                                                             delegate:self];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;

NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

NSString* resp = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(resp);

A: I had made method for getting user specific images from parse. So you could use below method and modify as per your need.
//In below method I filtered object on objectID basis. So you have to change your filtering parameter
+(NSArray *)getObjectsWithObjectId:(NSString *)objectIdStr
{

  //Change below dictionary as per your need.
  NSDictionary *createdByDict = [[NSDictionary alloc] initWithObjectsAndKeys:objectIdStr,@"objectId",@"Pointer",@"__type",@"_User",@"className", nil];
 //In this above dict is added to create a final dict for sending as parameter for my result. So this depends upon ur parse db to change above and below dictionary.
 NSDictionary *paraDict = [[NSDictionary alloc] initWithObjectsAndKeys:createdByDict,@"createdBy", nil];

//Your dictionary would be like this one below, still check and change if needed.
//Also remove above to dictionary as they just your your reference. Might be useful for your further work in case of deeper filtering.
NSDictionary *paraDict = [[NSDictionary alloc]nitWithObjectsAndKeys:col1,val1,col2,val2, nil];

 NSError *error = nil;
 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:paraDict options:0 error:&error];

 if (!jsonData){
    //NSlog(@"NSJSONSerialization failed %@", error);
 }

 NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
 NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:json, @"where", nil];

 NSString *urlStr = @"YOUR_URL";
 NSString *resultStr = [Utilities addQueryStringToUrlString:urlStr withDictionary:parameters];     //Method to collaborate urlStr with parameter and encode it as per standard.

 NSURL *url = [NSURL URLWithString:resultStr];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

 [request setHTTPMethod:@"GET"];
 [request addValue:PARSE_APP_ID forHTTPHeaderField:@"X-Parse-Application-Id"];
 [request addValue:PARSE_REST_API_KEY forHTTPHeaderField:@"X-Parse-REST-API-Key"];
 [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

 NSURLResponse* response;

 //Capturing server response
 NSData* data = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:&error];

 NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

 NSArray *resultArray = [responseDictionary objectForKey:@"results"];

  if([responseDictionary objectForKey:@"error"]){
    [self showAlertWithTitle:@"ERROR" message:[responseDictionary objectForKey:@"error"]];
    return nil;
  }
 return resultArray;
}

//For parameter appending into url with encoding

+(NSString*)addQueryStringToUrlString:(NSString *)urlString withDictionary:(NSDictionary *)dictionary
{
  NSMutableString *urlWithQuerystring = [[NSMutableString alloc] initWithString:urlString];

 for (id key in dictionary) {
    NSString *keyString = [key description];
    NSString *valueString = [[dictionary objectForKey:key] description];

    if ([urlWithQuerystring rangeOfString:@"?"].location == NSNotFound) {
        [urlWithQuerystring appendFormat:@"?%@=%@", [self urlEscapeString:keyString], [self urlEscapeString:valueString]];
    } else {
        [urlWithQuerystring appendFormat:@"&%@=%@", [self urlEscapeString:keyString], [self urlEscapeString:valueString]];
    }
 }
 return urlWithQuerystring;
}

+(NSString*)urlEscapeString:(NSString *)unencodedString
{
  CFStringRef originalStringRef = (__bridge_retained CFStringRef)unencodedString;
  NSString *s = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,originalStringRef, NULL, NULL,kCFStringEncodingUTF8);
  CFRelease(originalStringRef);
 return s;
}

A: Thanks @walle84. I worked on it for a little while longer and figured out the curl equivalent in Objective-C.
responseData = [NSMutableData data];

NSString* qryString = [NSString stringWithFormat:@"{\"col1\":\"%@\", \"col2\":\"%@\"}",
                       val1, val2];
NSString* escapedString = [qryString
                           stringByAddingPercentEncodingWithAllowedCharacters:
                           [NSCharacterSet URLHostAllowedCharacterSet]];
NSString* classURL = [NSString  stringWithFormat: @"https://api.parse.com/1/classes/ClassName/?where=%@", escapedString];
NSURL* url = [NSURL URLWithString:classURL];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:APP_ID forHTTPHeaderField:@"X-Parse-Application-Id"];
[request setValue:REST_API_KEY forHTTPHeaderField:@"X-Parse-REST-API-Key"];

NSError* error = [[NSError alloc] init];
NSHTTPURLResponse* responseCode = nil;
NSData* oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200)
{
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

NSString* response = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];


text:
Q: Starting User script in Greasemonkey Is it possible to run a user script before the page and DOM loads?

A: Only if the user script runs on google chrome atm. Greasemonkey may support this too someday:
// ==UserScript==
// @name My script
// @description It's really neat
// @run-at document-start
// ==/UserScript==

A: As Erik Vold said, Greasemonkey cannot do this unless the browser is Chrome.
But, if this functionality is needed on any other browser, you can write an extension.


text:
Q: Support of a continuous distribution Suppose I have a continuous random variable $X$ on $\mathcal{R}^1$, with CDF $F(\cdot)$ and pdf $f(\cdot)$.
My understanding is that there are three equivalent definitions of the support of the random variable.

*

*$S=\{x :\Pr(X\in B(x,r))>0$ for all $r>0\}$, where $B(x,r)$ is the interval $(x-r,x+r)$.

*The smallest closed set $S$ such that $\Pr(X\in S)=1$.

*The closure of $\{x:f(x)>0\}$.

I have two questions about this.
Question 1: Is it true that these three definitions are indeed equivalent?
Question 2: Consider the following, $S_0\equiv S\cap\{x:f(x)=0\}$. That is, $S_0$ is the subset of the support at which $f(x)=0$. Is it true that $S_0$ has Lebesgue measure 0?

A: The most general definition that I am aware of takes support of any Borel measure $\mu$ on a topological space $X$ to be the the smallest closed set $A$ such that
$\mu(X\setminus A) = 0$ (cf. $\rm [I]). $
$\rm [II]$ rather elaborates the characterization (relevant to what OP is seeking through the three definitions) well:

Theorem 2.1. Let $X$ be a separable metric space and $\mu$ a (probability) measure in $X.$  Then there exists a unique closed set $C_\mu,$ satisfying $\rm{(i)}~ \mu(C_\mu) = 1,~\rm{ (ii)}$ if $D$ is any closed set such that $\mu(D) = 1,$ then $C_\mu\subseteq  D.$ Moreover, $C_\mu$ is the set of all points $x\in X$ having the property that $\mu(U) > 0$ for each open set $U$ containing $x.$

References:
$\rm [I]$ Real Analysis and Probability, R.M. Dudley, $2004, $ p. $227.$
$\rm [II]$ Probability Measures on Metric Spaces, K. R. Parthasarathy, Academic Press, $1967,$ sec. $2.2, $ pp. $27-28.$


text:
Q: Class With The Same Name Already Exists I've created a class named "Group" in my .NET C# web-application.
When I try to access this class within other classes I get into no troubles, however, in certain points within my code when I try to access the very same class, it refers me to a different built-in class named "Group" too under the the lib. Regular Expressions.
My question: How can I specify directly that I am trying to access a different class? If there were 2 classes under different libs. named the same way, I would of just typed X.Group and Y.Group in order to specify the difference, but I'm not sure what I need to type in order to access my manually created class within my code.
EDIT: I have no namespace for my web-application as far as I know. I am using WebForms in order to develop my website, hence no namespace is created as far as I'm concerned.
Thanks in advance.

A: The first layer of protection against this problem is to be careful about giving your types such general names. That's the best solution.
Barring that, then you can do one of two things:

*

*Fully qualify the type name where you use it. E.g. MyNamespace.Group

*Declare a type alias via using. E.g. using MySpecialGroup = MyNamespace.Group;

A:
How can I specify directly that I am trying to access a different class

You could:

*

*Use the fully-qualified name, e.g.
MyNamespace.Group x = new MyNamespace.Group();

*Avoid adding a using directive for System.Text.RegularExpressions unless you really need it (maybe fully-qualifying uses of that instead)

*Use an alias via a using directive:
using MyGroup = MyNamespace.Group;
...
MyGroup x = new MyGroup();

If you don't have a namespace declaration, you can just refer to global::Group instead of MyNamespace.Group... but I suspect you do have a namespace, and I'd urge you to create one if you don't already have one.

A: You can use using directive:
using Group = X.Group;

var group = new Group(); \\ default Group class comes from X namespace;
var group2 = new Y.Group();  \\ if  you want other class, specify full namespace.

A: If you only want to access your own class in the code, you can create an alias for it with the using keyword:
using Group = My.Namespace.Group;

(at the top of your class, besides the normal using directives).
Otherwise it's always possible to use the fully qualified name in the code
var Group = new My.Namespace.Group;


text:
Q: Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.validation.Validator' available I have a project on spring boot + spring data + hibernate. I have a bean of org.springframework.validation.beanvalidation.LocalValidatorFactoryBean witch is implemented org.springframework.validation.Validator. So I needed to include in the project webMvc and I used annotation @EnableWebMvc and extened my configuration from org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter. But WebMvcConfigurerAdapter provided it's own implementation of org.springframework.validation.Validator so I marked my bean with @Primary, but it doesn't help.
@Configuration
@EnableWebMvc
public class WebConfiguration  extends WebMvcConfigurerAdapter {

  @Override
  public Validator getValidator() {
    return myValidationBean();
  }

  @Bean
  @Primary
  public LocalValidatorFactoryBean myValidationBean() {
    return new LocalValidatorFactoryBean();
  }
}

Exception:
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.validation.Validator' available: expected single matching bean but found 2: mvcValidator, myValidationBean

Full stackTrace:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.validation.Validator' available: expected single matching bean but found 2: mvcValidator,myValidationBean

    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:160)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
    at com.myProject.ApiControllerTest.getEmployees_byUserId(ApiControllerTest.java:339)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.validation.Validator' available: expected single matching bean but found 2: mvcValidator,myValidationBean
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
    at org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver$1.getTarget(ContextAnnotationAutowireCandidateResolver.java:88)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:192)
    at com.sun.proxy.$Proxy128.forExecutables(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:201)
    at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:121)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at com.myProject.ApiController$$EnhancerBySpringCGLIB$$24c340c2.getEmployees(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)

A: You should not use EnableWebMvc in Spring Boot. That disables all the spring boot autoconfiguration of MVC. Define a WebMvcConfigurer, but don't use EnableWebMvc.


text:
Q: How to save contacts locally on iPhone Is it possible to save contacts (selectively, eventually) locally on an iPhone, without them being synced to iCloud? (A.k.a. the "All on My Mac" option present on the Mac.) And if yes, how can I do this?

A: Turn off iCloud for contacts in Settings → iCloud, Contacts. Select "Keep on my iPhone" when asked about previously synced contacts.


text:
Q: Socketio - flask server and c# client Hey I'm trying to create a messaging app using SocketIO. I have a server written in flask and a client written in C#. I'm using SocketIoClientDotNetfor the client (https://github.com/Quobject/SocketIoClientDotNet).
This is my code:
Flask: routes.py
from flask import Flask
from flask.ext.socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def home():
    return "hello"

@socketio.on('connect')
def connect():
    print("CONNECTED")

@socketio.on("message")
def test():
    print("TEST WORKS")

if __name__ == '__main__':
    socketio.run(app)

C# :
public static class EnvConnections {

    public static IO.Options CreateOptions() {
        var options = new IO.Options();
        options.Port = 5000;
        options.Hostname = "127.0.0.1";
        options.ForceNew = true;

        return options;
    }

public static void Connect() {
    Uri uri = new Uri("http://127.0.0.1:5000");
    var socket = IO.Socket(uri, CreateOptions()); //also tried to create the socket only with url IO.Socket("http://127.0.0.1:5000")

    socket.On(Socket.EVENT_CONNECT, () => {
        Console.Write("EVENT_CONNECT");
        socket.Disconnect();
    });

    socket.Connect(); //tried to remove this
    Console.ReadLine();
}

On both platforms nothing is printed. It looks like a connection is created between them (on flask this line is printed infinitely once the connection is establish : 127.0.0.1 - - [20/Jan/2016 11:23:43] "GET /socket.io/?EIO=3&transport=polling&t=635888858234059292-4049&b64=1 HTTP/1.1" 200 -)
What am I doing wrong?
Edit: after I installed gevent I started receiving connect events. The problem is that its stuck on it and no other function is called. Looking at the flask console it looks like it uses pulling instead of webSocket (some kind of fullback mechanism) so I tried to change the c# socket option:
    IO.Options options  = new IO.Options();
    //options.Transports = ImmutableList.Create<string>(Polling.NAME);
    options.Upgrade = true;
    var socket = IO.Socket("http://127.0.0.1:5000", options);

But it keeps printing transport=polling
Edit2:
fb0f4c189334468dba90255880b528a4: Sending packet MESSAGE with 0
127.0.0.1 - - [20/Jan/2016 17:49:13] "GET /socket.io/?EIO=3&transport=polling&t=635889089536079075-2035&b64=1 HTTP/1.1" 200 355 0.002000
5cea6ce4dd8b47d79e79dd96747c26e4: Sending packet OPEN with {'pingTimeout': 60000, 'sid': '5cea6ce4dd8b47d79e79dd96747c26e4', 'upgrades': ['websocket'], 'pingInterval': 25000}
5cea6ce4dd8b47d79e79dd96747c26e4: Sending packet MESSAGE with 0
127.0.0.1 - - [20/Jan/2016 17:49:13] "GET /socket.io/?EIO=3&transport=polling&t=635889089536109077-2036&b64=1 HTTP/1.1" 200 355 0.003000
f768281808204af995421b4dbb2cda1c: Sending packet OPEN with {'pingTimeout': 60000, 'sid': 'f768281808204af995421b4dbb2cda1c', 'upgrades': ['websocket'], 'pingInterval': 25000}
CONNECTED
CONNECTED
f768281808204af995421b4dbb2cda1c: Sending packet MESSAGE with 0
127.0.0.1 - - [20/Jan/2016 17:49:13] "GET /socket.io/?EIO=3&transport=polling&t=635889089536149079-2037&b64=1 HTTP/1.1" 200 355 0.002000
e4eb16fcd12f41898ba58a309014b85c: Sending packet OPEN with {'pingTimeout': 60000, 'sid': 'e4eb16fcd12f41898ba58a309014b85c', 'upgrades': ['websocket'], 'pingInterval': 25000}
e4eb16fcd12f41898ba58a309014b85c: Sending packet MESSAGE with 0
127.0.0.1 - - [20/Jan/2016 17:49:13] "GET /socket.io/?EIO=3&transport=polling&t=635889089536179081-2038&b64=1 HTTP/1.1" 200 355 0.002000
70f45826d89b42bba3842e41b8ae8b08: Sending packet OPEN with {'pingTimeout': 60000, 'sid': '70f45826d89b42bba3842e41b8ae8b08', 'upgrades': ['websocket'], 'pingInterval': 25000}
70f45826d89b42bba3842e41b8ae8b08: Sending packet MESSAGE with 0
127.0.0.1 - - [20/Jan/2016 17:49:13] "GET /socket.io/?EIO=3&transport=polling&t=635889089536219083-2039&b64=1 HTTP/1.1" 200 355 0.002000
CONNECTED
CONNECTED

A: To turn my comment into a proper answer:
The problem appears to be that the upgrading mechanism from long-polling to WebSockets does not work between these particular socket.io implementations. By configuring the client to directly use WebSockets, I got it to work. Here an example:
var socket = IO.Socket("http://127.0.0.1:5000/data", new IO.Options
{
    // The protocol upgrading does not properly work between Flask-SocketIO and SocketIOClientDotNet
    Transports = ImmutableList<string>.Empty.Add(WebSocket.NAME)
});

A: The problem is related to the encoding sent back by the server. Flask Socket IO is not returning text/plain which is what is meant to return when a base64 parameter is included in the request (b64=1). Instead it returns an octet-stream.
The C# library adds b64=1 to the request automatically and changing the ForceBase64 property doesn't change that unfortunately.
Currently the only way I have found to fix this is to adjust the source for EngineIoClientDotNet, editing Polling.cs and removing query.Add("b64","1").
This may have untoward effects if the library doesn't support binary but so far it is now connecting successfully.


text:
Q: Rename folder according to mp3/flac tag information I would like all folders in my music collection to be renamed with a date, which is tagged in the music files inside them. Basically, change
Dire Straits - Money For Nothing

in
Dire Straits - 1988 - Money For Nothing

Which soft or script can achieve that ?
Thanks !

A: I've used various software for this type of thing in the past and have had fairly good luck with MP3 Rename.  It is extremely flexible in the number of types of rules that you can use for the rename and can include any of info from the ID3 tags.

A: You can use MediaMonkey or MusicBrainz Picard which is what I use to catalog my collection it analyzes your music and tags them based on the song so you can tag items that have no information in the metadata. I dont see it on the page but it does do renaming based on tag information.

A: Easytag is a nice cross-platform tool that can rename files per their ID3 tags.

*

*View, edit, write tags of MP3, MP2 files (ID3 tag with pictures), FLAC files (FLAC Vorbis tag), Ogg Vorbis files (Ogg Vorbis tag), MP4/AAC (MP4/AAC tag), MusePack, Monkey's Audio files and WavPack files (APE tag)

*Auto tagging: parse filename and directory to complete automatically the fields (using masks)

*Ability to rename files and directories from the tag (using masks) or by loading a text file

Get it from http://easytag.sourceforge.net/
Direct windows download link here


text:
Q: Determine flux using Gauss's theorem Here's the task I'm a bit confused with:

Find using Gauss's theorem the outward flux seen from the point $\left(\begin{matrix}0\\0\\1\end{matrix}\right)$ of the vector field $$\mathbf{v}=\left(\begin{matrix}x^2yz\\xy^2z\\z\end{matrix}\right)$$
  through the area $M$ defined by
  $$M:=\left\{ (x,y,z)\in\mathbb{R}^3:x^2+y^2=z,\;0\leq z \leq 1\right\}$$

I don't understand the meaning of the "seen from the point". Does it influence somehow the solution?
Here's how I do this.
At first I find divergence of $\mathbf{v}$:
$$\operatorname{div}(\mathbf{v})=2xyz+2xyz+1=4xyz+1$$
To find the volume integral I make the following transformations:
$$-1\leq x\leq 1\\ -\sqrt{1-x^2}\leq y \leq \sqrt{1-x^2}\\0\leq z \leq 1$$
Applying divergence theorem we obtain
$$\int_{\partial V}\mathbf{v}\cdot\mathbf{n}\operatorname{do}=\int_V\operatorname{div}(\mathbf{v})d\mu=\int_{-1}^1dx\int_{-\sqrt{1-x^2}}^{\sqrt{1-x^2}}dy\int_{0}^14xyz+1dz\\=\dots\\=\pi$$
I skipped the routine calculation of the volume integral which I've done on the paper.
Does it seem to be correct? Is there anything to be done with this additional "seen from the point" condition?

A: It seems that your boundaries of integration are incorrect.
The domain ${M = \{(x,y,z) \,|\, x^{2} + y^{2} = z , 0 \leq z \leq 1 \}}$ corresponds qualitatively to the surface of a cone of height $1$ oriented along the $z-axis$, without its top-hat. Indeed, one should note that the top of this cone, which corresponds to the surface $\{(x,y,1) \,|\, x^{2} + y^{2} \leq 1 \}$ does not belong to the domain $M$.
If we want to determine the flux of the vector field $\boldsymbol{v}$ through the surface $M$ using Gauss's Theorem one may proceed as follows
$$ \begin{aligned}
\int_{\rm M} \boldsymbol{v} \cdot \boldsymbol{n} \, d S & = \int_{\partial \rm Cone}  \boldsymbol{v} \cdot \boldsymbol{n} \, d S - \int_{\rm Top} \boldsymbol{v} \cdot \boldsymbol{n} \, d S
\\
& = \int_{\rm Cone} \text{div} (\boldsymbol{v}) \, d V - \int_{\rm Top} \boldsymbol{v} \cdot \boldsymbol{n} \, d S \, ,
\end{aligned}$$
where $\int_{M} d S$ corresponds to the outgoing flux through the surface $M$, $\int_{\partial \rm Cone} d S $ corresponds to the flux through the surface of the entire cone with its top, and $\int_{\rm Top} d S$ corresponds to the flux through the top of the cone.
The integration $\int_{\partial \rm Cone} d S$ can be estimated thanks to Gauss's Theorem as follows. The domain of integration is given by
$$\begin{cases}
0 \leq z \leq 1 \, ,
\\
-\sqrt{z} \leq x \leq \sqrt{z} \, ,
\\
- \sqrt{z - x^{2}} \leq y \leq \sqrt{z - x^{2}} \, .
\end{cases} $$
(The boundaries are different than yours, since you are integrating on the entire cylinder) so that it becomes
$$ \begin{aligned}
\int_{\rm Cone} \text{div} (\boldsymbol{v}) \, d V & = \int_{0}^{1} d z \int_{-\sqrt{z}}^{\sqrt{z}} dx \, \int_{-\sqrt{z - x^{2}}}^{\sqrt{z - x^{2}}} d y \, (4 x y z + 1)
\\
& = \frac{\pi}{2}
\end{aligned}$$
On the other hand, the flux through the top $\int_{\rm Top} d S$ is given by
$$ \begin{aligned}
\int_{\rm Top} \boldsymbol{v} \cdot \boldsymbol{n} \, d S & = \int_{-1}^{1} d x \, \int_{- \sqrt{1 - x^{2}}}^{\sqrt{1-x^{2}}} d y \, \, (x^{2} y \,,\, x y^{2} \,,\, 1) \cdot (0,0,1)
\\
& = \int_{-1}^{1} d x \, \int_{- \sqrt{1 - x^{2}}}^{\sqrt{1-x^{2}}} d y \, 1
\\
& = \pi
\end{aligned} $$
(Note the fact that on the top, the outgoing normal is  given by $(0,0,+1)$)
As a conclusion, we obtain that $\int_{M} \boldsymbol{v} \cdot \boldsymbol{n} \, dS = - \frac{\pi }{2}$


text:
Q: JScrollPane Zoom view with components inside Are there any methods which i want to zoom the view of the viewport but the
location of the components inside does not change. The setting is that i have a big jpanel
inside a jscrollpane in which i only want to only change the view into zoomed mode. the
objects can be dragged and drop anywhere inside the panel so that is why it is important that its xy position remains.
here's my present zoom code, what i do is i use the graphics 2d scale to zoom the view. the problem is that the position is a mess. I also want to zoom it out so that the whole panel fits the jscrollpane.
//zoom in draw method using scale
g2.translate(zoomX, zoomY);

g2.scale(zoomScale, zoomScale);

g2.translate(-zoomX, -zoomY);

Im also thinking of manipulating the viewport. here is my viewport initialization.
the 2000 by 1000 dimension is the panel and the 750 by 698 is the extentsize of my viewport. any suggestion on how will i zoom without messing the position of the components?
Maybe moving the setviewposition is part of the solution?
 view = new JViewport();

 view.setViewSize(new Dimension(2000,1000));

 view.setExtentSize(new Dimension(750,698));

 view.setViewPosition(new Point(view.getExtentSize().width/2,view.getExtentSize().height/2));

A: Use two buttons which increase/decrease the zoom factor. Override the paintComponent method of the panel in the JScrollPane like this.
@Override
public void paintComponent(Graphics g)
{
    g.scale(zoomFactor, zoomFactor);
    // Change the size of the panel
    setSize(origWidth * zoomFactor, origHeight * zoomFactor);
    // Re-Layout the panel
    validate();
    super.paintComponent(g);
}

Hope it works.


text:
Q: Google app: domain verification for Oauth is successful, but status remains "Pending developer action" I'm working on getting a Google app verified, and although I have completed the domain verification, the Oauth consent screen says that it is waiting on me to "comply with domain verification requirements." What does this mean?
1. I've confirmed that I completed domain verification at https://www.google.com/webmasters/verification/home. (With my personal google account, I verified the domain with a DNS TXT record, then delegated it to my work account.)

2. ...and I've set that domain as the sole authorised domain for my app...

3. Nevertheless, the Oauth consent screen says that I still need to comply with the domain verification requirements. Why would this be?

A: Once you have completed the actions specified under "Pending developer action", you will need to reach back out to the Google verification team to inform them that you've taken action for your app verification to proceed. See https://support.google.com/cloud/answer/10311615#zippy=%2Cpending-developer-action.


text:
Q: Install VS Code on Windows through Powershell / command prompt? Is there a way to install Install VS Code on Windows through Powershell / command prompt commands ? as in linux with "sudo apt install ..."
Thank you

A: Complementing @Mohammed El Sayed great answer that uses Choco, the now Microsoft official package manager WinGet can let you do this as well
winget install -e --id Microsoft.VisualStudioCode

Note -e matches exact string (instead of substring) and --id limits usage to ID of application. More on args here
For more info on customising the installation see this GitHub discussion.

A: You can use Choco
choco install vscode.install

Ref:
https://community.chocolatey.org/packages/vscode.install


text:
Q: How to run Abaqus Macro (.py) script I am new to python. I generated a macro which is a .py script using Abaqus Macro manager. I realised that this script works only when run from the Abaqus manager and does not run by itself.
Please does anyone know how to modify this script so i can run it without using the Abaqus. Thank you in advance for your help
Adroit

A: to run a python script that relies on abaqus cae from the command line and without opening up the gui window you do:
 abaqus cae noGUI=script.py

As mentioned if all the script does is define a macro, well that's all it does is define the macro and quit. Typically you need to add code to open an odb, do something, write output, etc.

A: In general, Python scripts can be run in Abaqus via 'File > Run script'. However, as is a case for all Python scripts, if all your code is contained inside of a function (and in case of Abaqus macro, it is), and that function is never called explicitly inside the script, the code will not be executed.
You file probably looks something like this:
from abaqus import *
# some other imports, if any

def macro_function():
    # code defining the macro's behavior

You should edit the script by calling the function at the end of the script.
If you want some more concrete help, post your actual code.
EDIT: To call the defined function, you just write macro_function() at the end of the file, so that the script looks something like this:
from abaqus import *
# some other imports, if any

def macro_function():
    # code defining the macro's behavior

macro_function()

Maybe it would be easier if you just had the code outside of the function and remove the function completely. For anything more than this, you really should learn some Python.

A: According to my moderate experience, if you need loop computations, you have to launch the script inside CAE, since when starting it in command line, only one cycle is computed. An example of the script intended for loop computations and visualisation, you can find at researchgate, search text "How to write scripts for Abaqus"