text:
Q: Touching MKMapView causes pins to move slightly I add a pin where a user touches with this code:
func addPin(tap: UITapGestureRecognizer) {
        if (tap.state == UIGestureRecognizerState.Ended) {

            var coordinate = mapView.convertPoint(tap.locationInView(mapView), toCoordinateFromView: mapView)

            let address = addressAnnotationLogic.createWithCoordinate(coordinate)
            mapView.addAnnotation(address)
            routeLogic.addAddressAnnotation(address, toRoute: currentRoute!)

            // reverse geocode
            let pinLocation = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
            let geocoder = CLGeocoder()

            geocoder.reverseGeocodeLocation(pinLocation!, completionHandler: {
                (placemarks, error) -> Void in

                if error != nil {
                    println("Reverse geocoder failed with error " + error.localizedDescription)
                }

                if placemarks.count > 0 {
                    let topResult = placemarks[0] as? CLPlacemark
                    self.addressAnnotationLogic.updateAnnotation(address, withPlacemark: topResult!)
                }
            })
        }
}

My addressAnnotationLogic just creates a backing NSManagedObjectModel to save it, and my routeLogic just adds it to a route which is another NSManagedObjectModel.  My delegate methods are pretty standard.
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    if annotation is AddressAnnotation {
        var annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "SimplePinIdentifier")
        annotationView.enabled = true
        annotationView.animatesDrop = true
        annotationView.draggable = false
        annotationView.pinColor = MKPinAnnotationColor.Red
        annotationView.canShowCallout = true

        return annotationView
    }
    return nil
}

After my first pin is added, if I touch the screen again, for some reason the initial pin moves just the slightest bit which doesn't seem right.  It's more frustrating because later I draw an MKPolyline between points and then the pin will move just ever so slightly making the poly line look incorrect. What is this about?  Why the pins move just a little bit after already being added to the MKMapView?

A: You should probably make the coordinate property in your AddressAnnotation class dynamic.
class AddressAnnotation: NSObject, MKAnnotation {
    var title = ""

    // this works
    dynamic var coordinate: CLLocationCoordinate2D

    // this doesn't
    // var coordinate: CLLocationCoordinate2D

    init(_ coord:CLLocationCoordinate2D)
    {
        coordinate = coord
    }
}

If this doesn't work, please post your code for the AddressAnnotation class and the updateAnnotation method.
Here's what I think happens:
Your annotation first gets the coordinate that is translated from the screen coordinates of your first tap.
Then, in the asynchronous completion handler of your geocoder invocation, your updateAnnotation() method is called.
I assume that you update the coordinate of your AddressAnnotation to the coordinate of the nearest Placemark in there.
Unfortunately, the Map View has probably already drawn your Pin at the original location when that update happens.
When the coordinate is updated asynchronously, the Map View does not notice it.
Only when it redraws the annotation (prompted by the next tap), it picks up the updated coordinate (so you see the move from the first tap coordinate to the nearest place mark's coordinate).
Now, the Map View is actually trying to be notified of changes in its annotation's coordinates so that it can automatically redraw at the new coordinates.
For that it uses a technology called Key-Value-Observing. "Normal" Swift properties don't support that, however. Making them dynamic does.


text:
Q: Elastic Search Kibana PDF Report 0
I am trying to generate PDF reports and download them using a script. I followed below instructions.
https://github.com/elastic/kibana/blob/master/docs/user/reporting/automating-report-generation.asciidoc
I am able to queue the report and i also got a download url /api/.../download/xyzdrfd but when i am trying WGET on the url, It's not working. I have no idea how to download that report using APIs so just tried with WGET.
Any-idea how to download the reports using API call or programmatically?

A: Next step for downloading the report (after successfuly queued & processed):
Call GET request with basic auth and kbn-xsrf header, example:
curl -O -XGET -u elastic -H 'kbn-xsrf: true' 'https://your-elastic-host/api/reporting/jobs/download/l7q4xw77000z7a3357gfmdex'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Looping through a filtered Excel excel table For demonstration purposes, I have simplified my excel-formatted table to only 3 columns and 4 rows. What I need to do is loop through this simple table when it is filtered and on few occasions loop through the unfiltered table. I have looked all over the internet, and the closest thing I've gotten to my solution (in a rather cumbersome way) is through the use of the .SpecialCells(xlCellType).Areas property. But ironically, this solution didn't work when the table happens to be unfiltered.
Here's my entire, unfiltered table:

As a proof of concept, I'm just filtering to where Gender = "M". So here's how my filtered data looks like.

Now I just want to loop through this table and reference the cells that contain information, so in this table, I want to be able to print the following in the Debug.Print

I can't quite get the outputs that I want and the following code shows the three iterations that I have that serve to illustrate the point. What am I going wrong? This is is driving me nuts. Any help is greatly appreciated.
Sub filter_loop()
Dim people_table As ListObject

Set people_table = Worksheets("Sheet1").ListObjects("Table13")
Set people_table_visible = people_table.DataBodyRange.SpecialCells(xlCellTypeVisible)

' Set of iterations

' Iteration 1
For Each rngArea In people_table_visible.Areas
    For rngRow = 1 To rngArea.Rows.Count
        Debug.Print rngArea.Cells(1, 1) & " is " & rngArea.Cells(1, 2)
    Next rngRow
Next
' PROBLEM here is that it doesn't work when the table is not filtered

' Iteration 2

filtered_rows_r = people_table.DataBodyRange.SpecialCells(xlCellTypeVisible).Rows.Count

For r = 1 To filtered_rows_r
    Debug.Print people_table.DataBodyRange.SpecialCells(xlCellTypeVisible).Cells(r, 1) & " is " & people_table.DataBodyRange.SpecialCells(xlCellTypeVisible).Cells(r, 2)
Next r
'PROBLEM here is I get back "Diego is 23" and that's it, because filtered_rows_r returns 1 when it should return 2

' Iteration 3
filtered_rows_r2 = people_table.DataBodyRange.SpecialCells(xlCellTypeVisible).Rows.Count + 1

For r2 = 1 To filtered_rows_r2
    Debug.Print people_table.DataBodyRange.SpecialCells(xlCellTypeVisible).Cells(r2, 1) & " is " & people_table.DataBodyRange.SpecialCells(xlCellTypeVisible).Cells(r2, 2)
Next r2
'PROBLEM here is I get back "Diego is 23" and "Maria is 12", so it's not respecting the filtering

End Sub

A: Discontinuous (multi-area) ranges can't be looped through using (eg)
For x = 1 to rng.[Areas/Cells/Rows].Count
    'do something with  [Areas/Cells/Rows](x)
Next

A For Each approach is the most robust way to do it.
This works whether or not the table is filtered (as long as all table columns are visible):
Sub filter_loop()
    Dim people_table As ListObject, rngVis As Range, c As Range, rw As Range

    Set people_table = Worksheets("Sheet1").ListObjects("Table13")

    On Error Resume Next 'ignore error in cases where there are no visible rows
    Set rngVis = people_table.DataBodyRange.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0      'stop ignoring errors

    If rngVis Is Nothing Then Exit Sub

    For Each rw In rngVis.Rows
        Debug.Print rw.Cells(1).Value & " is " & rw.Cells(2).Value
    Next rw
End Sub


text:
Q: HTML5 video - onclick play to fullscreen I have a simple HTML5 video player. I would like it so when the user clicks a div on the site, this then opens the video up to fullscreen.
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <div class="top-video">
        <video controls="" muted="" autoplay="" playsinline="" id="topVideo">
          <source src="https://player.vimeo.com/external/419906207.hd.mp4?s=7c6f9edf7137540923b2931ac0359420124e5d6e&profile_id=174&loop=0&autoplay=1" type="video/mp4">
        </video>
    </div>

I have tried using jQuery to target this but cannot, does anyone have a solution?

A: According to the MDN documentation, an Element.requestFullscreen() could help you with that
$('#div-you-need-to-click').click((e) => {
  $('#topVideo')[0].requestFullscreen();
})


text:
Q: iOS 5/Lion Core Data ordered relationships: specify order? I am trying to use Core Data and it's ordered relationships feature, and I just can't find how would I actually specify ordering. I marked my relationship as 'ordered', but don't see where I set, say, 'order by attribute XXX descending'.

A: An ordered relationship only means that ordered in a arbitrary manner. (Ordered by the user for example.)
If you want to have an order related to your attributes, add a sort descriptor to your fetch request :
NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray* sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];


text:
Q: How to Write below SQL Query in Spring Data JPA? SELECT * FROM vnfconfigdetails where vnfid='1234' and (creationdate >= '2018-07-12' and creationdate <= '2018-07-15');

I have try bellow JPA query but empty result coming.
@Query(value= " SELECT * FROM vnfconfigdetails where (creationdate >= :startDate AND creationdate <= :endDate ) AND vnfid =:vnfid", nativeQuery = true)
List<VnfConfigDetailsDB> findByVnfidAndCreationdate(@Param("vnfid") String vnfid,@Param("startDate") Date startDate, @Param("endDate")Date endDate);

ShowSQL Query-
@Entity
@Table(name = "vnfconfigdetails", schema = "testreports")
public class VnfConfigDetailsDB {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private int id;

    @Column(name = "vnfid")
    private String vnfid;

    @Column(name = "vnfversion")
    private String vnfversion;

    @Column(name = "vnfname")
    private String vnfname;

    @Column(name = "configinfo")
    @Lob
    private String configinfo;

    @Column(name = "creationdate")
    private Date creationdate;

    @Column(name = "lastupdated")
    private Date lastupdated;

    @Column(name = "status")
    private String status;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getVnfid() {
        return vnfid;
    }

    public void setVnfid(String vnfid) {
        this.vnfid = vnfid;
    }

    public String getVnfversion() {
        return vnfversion;
    }

    public void setVnfversion(String vnfversion) {
        this.vnfversion = vnfversion;
    }

    public String getVnfname() {
        return vnfname;
    }

    public void setVnfname(String vnfname) {
        this.vnfname = vnfname;
    }

    public String getConfiginfo() {
        return configinfo;
    }

    public void setConfiginfo(String configinfo) {
        this.configinfo = configinfo;
    }

    public Date getCreationdate() {
        return creationdate;
    }

    public void setCreationdate(Date creationdate) {
        this.creationdate = creationdate;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Date getLastupdated() {
        return lastupdated;
    }

    public void setLastupdated(Date lastupdated) {
        this.lastupdated = lastupdated;
    }

}

A: This should work.
 List<VnfConfigDetailsDB> findByVnfidAndCreationdateBetween(String vnfid, Date startDate, Date endDate)

You don't need @Query. When you say Between, sping-data will formulate the query correctly.

A: In your case you use native query. This is not JPQL so you have to do some changes.

*

*Do not use @Param infront of parameters in the method: Please remove @Param("vnfid"), @Param("startDate") and @Param("endDate").

*Replace all :paramName with ?. For example replace :startDate with ?NumberOfParam and so on inside of the query:
@Query(value= " SELECT * FROM vnfconfigdetails where (creationdate >= ?2 AND   creationdate <= ?3 ) AND vnfid =?1", nativeQuery = true)
List<VnfConfigDetailsDB> findByVnfidAndCreationdate(String vnfid,Date startDate, Date endDate);

If you want to use JPQL then you have to remove nativeQuery = true and your query will look something like that:
@Query(value= " SELECT v FROM VnfConfigDetailsDB v where (v.creationdate >= :startDate AND v.creationdate <= :endDate ) AND v.vnfid =:vnfid")
List<VnfConfigDetailsDB> findByVnfidAndCreationdate(@Param("vnfid") String vnfid,@Param("startDate") Date startDate, @Param("endDate")Date endDate);

A: Remove @Param
@Query(value = "SELECT * FROM vnfconfigdetails where (creationdate >= ?2 AND   creationdate <= ?3 ) AND vnfid =?1", nativeQuery = true)
List<VnfConfigDetailsDB> findByVnfidAndCreationdateBetween(String vnfid, Date startDate, Date endDate);

In the entity class add the temporal annotation. This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "creationdate", columnDefinition = "DATETIME")
private Date creationdate;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "lastupdated", columnDefinition = "DATETIME")
private Date lastupdated;


text:
Q: String into multiple string in an array I have not been coding for long and ran into my first issue I just can not seem to figure out.
I have a string "XX|Y1234$ZT|QW4567" I need to remove both $ and | and push it into an array like this ['XX', 'Y1234', 'ZT', 'QW4567'].
I have tried using .replace and .split in every way I could like of
 var array = "XX|Y1234$ZT|QW4567"
 var array2 = [];

 array = array.split("$");

 for(i = o; i <array.length; i++)
   var loopedArray = array[i].split("|")
   loopedArray.push(array2);
 }

I have tried several other things but would take me awhile to put them all down.

A: You can pass Regex into .split(). https://regexr.com/ is a great tool for messing with Regex.
// Below line returns this array ["XX", "Y1234", "ZT", "QW4567"]
// Splits by $ and |
"XX|Y1234$ZT|QW4567".split(/\$|\|/g);

A: Your code snippet is close, but you've messed up your variables in the push statement.

var array = "XX|Y1234$ZT|QW4567"
var array2 = [];

array = array.split("$");

for (i = 0; i < array.length; i++) {
  var loopedArray = array[i].split("|")
  array2.push(loopedArray);
}
array2 = array2.flat();

console.log(array2);

However, this can be rewritten much cleaner using flatMap. Also note the use of let instead of var and single quotes ' instead of double quotes ".

let array = 'XX|Y1234$ZT|QW4567'
let array2 = array
  .split('$')
  .flatMap(arrayI => arrayI.split('|'));

console.log(array2);

And lastly, split already supports multiple delimiters when using regex:

let array = 'XX|Y1234$ZT|QW4567'
let array2 = array.split(/[$|]/);

console.log(array2);

A: You can do this as follows:
"XX|Y1234$ZT|QW4567".replace('$','|').split('|')

It will produce the output of:
["XX", "Y1234", "ZT", "QW4567"]

A: If you call the split with two parameters | and the $ you will get an strong array which is splittend by the given characters.
var array = "XX|Y1234$ZT|QW4567";
var splittedStrings = array.Split('|','$');
foreach(var singelString in splittedStrings){
   Console.WriteLine(singleString);
}

the output is:
XX
Y1234
ZT
QW4567


text:
Q: Importing component library on Kicad I'd like to import a component library that I downloaded into my Kicad. I am running the latest Kicad for Windows as shown below. I have added the directory containing the library into the library search path. I even copied the library in to the global library directory within the installation location. And the component does not show up in my library browser!!
The answer on a similar question does not seem to work with this version of Kicad.
Application: kicad Version: (2015-01-16 BZR 5376)-product Release build wxWidgets: Version 3.0.0 (debug,wchar_t,compiler with C++ ABI 1002,GCC 4.8.2,wx containers,compatible with 2.8) Platform: Windows 7 (build 7601, Service Pack 1), 64-bit edition, 64 bit, Little endian, wxMSW Boost version: 1.54.0
         USE_WX_GRAPHICS_CONTEXT=OFF
         USE_WX_OVERLAY=OFF
         KICAD_SCRIPTING=ON
         KICAD_SCRIPTING_MODULES=ON
         KICAD_SCRIPTING_WXPYTHON=ON
         USE_FP_LIB_TABLE=HARD_CODED_ON
         BUILD_GITHUB_PLUGIN=ON
         KICAD_USE_WEBKIT=OFF

A: It turns out I have to activate the library I want to use. Merely adding the library to my search path is not sufficient [1].
[1] https://forum.kicad.info/t/importing-component-library/574


text:
Q: Find $X$ and $U$ for projectiles. A projectile is fired from horizontal ground at an angle of $X$ above the horizontal and speed of $u$ m/s and lands a distance of 100m away. Another projectile is fired with the same initial speed but at an angle of $2X$ above the horizontal and lands a distance of 150m. What are $X$ and $u$? I have tried to use the projectiles equation I have, but I feel like it's not going well. Any assistance would be great, thanks.

A: The range of a projectile, launched from the horizontal, with speed $u$ at an angle $\theta$ is $$d=\frac{u^2}{g}\sin(2\theta)$$
You are given $d_1=100$m, for an angle $X$ and $d_2=150$m for an angle $2X$By dividing the equation for the two cases you get $$\frac{d_1}{d_2}=\frac{100}{150}=\frac{\sin(2X)}{\sin(4X)}$$
You can use $\sin(2a)=2\sin(a)\cos(a)$ to write $\sin(4a)=2\sin(2a)\cos(2a)$. Plug it into the above equation and you get a formula for $\cos(2X)$. Calculate $X$ and plug it into the first equation


text:
Q: How to match column value to column name? I am trying get value from shipping_charge table. I have two tables one is pincode table and second is shipping_charge table. When user enter pincode, I fetch data from pincode table to check zone. So, I cant understand how to match fetched 'zone' value to get shipping charge from shipping_charge table. Shipping charges include in city and metro column. I provide table for example.
Here is my pincode table:
______________________
|id|pincode|cod|zone |
----------------------
|1 |100001 | Y |city |

|2 |100002 | N |City |

|3 |100003 | N |metro|

|4 |100004 | Y |City |

|5 |100005 | Y |City |

----------------------

Here is my shipping_charge table:
________________________
|id|pro_code|city|metro|
------------------------
|1 |pro0001 |100 |150  |

|2 |pro0002 |50  |100  |

|3 |pro0003 |150 |200  |

|4 |pro0004 |100 |120  |

------------------------

I tryed only this code to get zone
$result= $this->connect()->query("SELECT * FROM wm_pincode WHERE
pincode='$pincode'");
    if($result->num_rows>0){
        $row=$result->fetch_assoc();
        $zone =$row['zone'];
    }

If user enter pro_code= pro0002 and pincode=100003 then get zone=metro and shipping charge=100.
So how is it.

A: If you want to use two queries:
$result= $this->connect()->query("SELECT * FROM wm_pincode WHERE
pincode='$pincode'");
    if($result->num_rows>0){
        $row=$result->fetch_assoc();
        $zone =strtolower($row['zone']);
        $result= $this->connect()->query("SELECT $zone as shipping_charge_value FROM shipping_charge WHERE
pro_code='$procode'");
        if($result->num_rows>0){
            $row=$result->fetch_assoc();
            $shipping_charge =$row['shipping_charge_value'];
        }
    }

A: you can use union all
select charge,zone from (
select metro as charge,'metro' as namezone,pro_code from shipping_charge
  union all
select city as charge,'city' as namezone,pro_code from shipping_charge)
as DD,pincode sc where DD.pro_code='pro0002' and DD.namezone=sc.zone and sc.pincode=100003


text:
Q: What's wrong with Android-Studio imports Apparently Google no longer supports the Eclipse Android IDE, and I've been having some odd problems with imports in Android studio. When I pasted a code snipped with ContextMenu menu, it wouldn't import it, even with alt+enter it would not show the appropriate android.view.ContextMenu.
Now I pasted an example with LAYOUT_INFLATER_SERVICE, and unfortunately it won't recognize it at all - alt+enter suggests creating a constant, class, field, or renaming. I don't remember having this problem in Eclipse.
Where do I find these constants, or more importantly, how do I get Android-studio to get the right imports without memorizing where these classes/constants are?

A:
What's wrong with Android-Studio imports?

Not much, I'm using it (resp. Intellij Idea) for years now.

When I pasted a code snipped with ContextMenu menu, it wouldn't import
  it, even with alt+enter it would not show the appropriate
  android.view.ContextMenu.

This definitely works for me, so it's certainly not a missing feature. I would suspect something in your project / module setup being funny. If you're really serious about it I would try to reproduce the issue on a vanilla project.

Now I pasted an example with LAYOUT_INFLATER_SERVICE, and
  unfortunately it won't recognize it at all - alt+enter suggests
  creating a constant, class, field, or renaming.

I can confirm that one. Annoys me too. But then: How should the IDE know about a single String matching some constant definition? I would be surprised if Eclipse did any better...
Try "Symbol-Search" (Ctrl Alt Shift N) or "Search everywhere" (Shift Shift), this should mitigate the problem.


text:
Q: Viewstate, have I understood this correctly? Say I have 5 buttons on a page, numbered 1-5.
When one is clicked, a value with a viewtate getter/setter assigns this the value of the button clicked.
If I am checking for a value in Page_Init() / OnInit(), after the postback has occured, the value will always be empty/null.
Is this correct?
If so, is there anything else I can do that doesnt require an architectural change? Or something similar I can use to persist changes across post backs (Session[] no good unfortunately).

A: ViewState stores the state of the page (page and control settings + custom values stored in ViewState) between post backs. It is just hidden field with serialized (and encrypted) state data. When you set something to ViewState in code behind it is transfered with page markup to the client and posted back to the sever in the next Postback. The page life cycle (between InitComplete and PreLoad) deserializes state from ViewState. That is the reason why you can't access data from ViewState in OnInit.

A: refer to :http://code.google.com/p/citiport2/wiki/All_Events
Page: AddParsedSubObject
Page: CreateControlCollection
Page: AddedControl
Page: AddParsedSubObject
Page: AddedControl
Page: ResolveAdapter
Page: DeterminePostBackMode
Page: PreInit
Control: ResolveAdapter
Control: Init
Control: TrackViewState
Page: Init
Page: TrackViewState
Page: InitComplete
Page: LoadPageStateFromPersistenceMedium
Control: LoadViewState
Page: EnsureChildControls
Page: CreateChildControls
Page: PreLoad
Page: Load
Control: DataBind
Control: Load
Page: EnsureChildControls
Page: LoadComplete
Page: EnsureChildControls
Page: PreRender
Control: EnsureChildControls
Control: PreRender
Page: PreRenderComplete
Page: SaveViewState
Control: SaveViewState
Page: SaveViewState
Control: SaveViewState
Page: SavePageStateToPersistenceMedium
Page: SaveStateComplete
Page: CreateHtmlTextWriter
Page: RenderControl
Page: Render
Page: RenderChildren
Control: RenderControl
Page: VerifyRenderingInServerForm
Page: CreateHtmlTextWriter
Control: Unload
Control: Dispose
Page: Unload
Page: Dispose

Page: Init is earlier

A: I'm not 100% sure what you're asking here, but it sounds like a problem with the ASP.NET Page Lifecycle. It trips up everyone!
Basically, what happens is that a developer expects to be able to do some work in Page_Init (or more commonly Page_Load), but the click event for whatever triggered the postback hasn't happened yet.
In fact, iirc ViewState hasn't even been deserialized when Page_Init fires.
I can't tell you where the right place to do whatever work needs done is without knowing more, but you probably want to move some of that code that's in Page_Init into an event handler later in the lifecycle.
You can see this for yourself: Pop a breakpoint at the start of Page_Init, and another one at the start of MyButton_Click, you'll see that Page_Init fires first.

A: You can use Request.Form["idofbutton"] to get the posted value. This happens as part of the http protocol. Inspect the http request/ response in something like firebug to see what is getting posted.


text:
Q: android.content.res.Resources$NotFoundException on support_simple_spinner_dropdown_item I am without ideas of what is causing this problem,
Problem:
android.content.res.Resources$NotFoundException: Resource ID #0x7f040028

R.java reports this ResID as:
public static final int support_simple_spinner_dropdown_item=0x7f040028;

Full Stacktrace
06-14 17:29:32.685 9541-9541/com.cynetstudios.frequencyselector E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.cynetstudios.frequencyselector, PID: 9541
        android.content.res.Resources$NotFoundException: Resource ID #0x7f040028
            at android.content.res.Resources.getValue(Resources.java:1266)
            at android.content.res.Resources.loadXmlResourceParser(Resources.java:2654)
            at android.content.res.Resources.getLayout(Resources.java:1082)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:412)
            at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:371)
            at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
            at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:197)
            at android.widget.Spinner.onMeasure(Spinner.java:507)
            at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:418)
            at android.view.View.measure(View.java:17555)
            at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
            at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
            at android.view.View.measure(View.java:17555)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
            at android.view.View.measure(View.java:17555)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
            at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
            at android.view.View.measure(View.java:17555)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:17555)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17555)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2625)
            at android.view.View.measure(View.java:17555)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5891)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5291)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:412)
                                                                                at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:371)
                                                                                at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
                                                                                at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:197)
                                                                                at android.widget.Spinner.onMeasure(Spinner.java:507)
                                                                                at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:418)
                                                                                at android.view.View.measure(View.java:17555)
                                                                                at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
                                                                                at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
                                                                                at android.view.View.measure(View.java:17555)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                                at android.view.View.measure(View.java:17555)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
                                                                                at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
                                                                                at android.view.View.measure(View.java:17555)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                at android.view.View.measure(View.java:17555)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                                                at android.view.View.measure(View.java:17555)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2625)
                                                                                at android.view.View.measure(View.java:17555)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5891)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:550)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5291)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

The only code relating to this Spinner is:
//Initialise Frequency Drop Down Spinner
        spinFreqSelector = (Spinner) findViewById(R.id.spinFreqSelector);
        ArrayList<String> FreqList = new ArrayList<>(Arrays.asList("2.4/5Ghz", "2.4Ghz", "5Ghz"));
        //R.layout.support_simple_spinner_dropdown_item is only a template
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, FreqList);
        spinFreqSelector.setAdapter(arrayAdapter);

This error occurs when protected void onCreate(Bundle savedInstanceState) finishes,
Cleaning and rebuilding does not fix this.

*

*Build and compile SDK = 23

*Minimum build sdk = 19

Solutions?

A: ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, FreqList);

Try android.R.layout.simple_spinner_item or android.R.layout.support_simple_spinner_dropdown_item


text:
Q: Running CMD as admin to uninstall driver I am trying to run an uninstall command for several remote computers. Is there a way to run CMD as admin to run a script that uninstalls the driver I need it to?
I was using PSEXEC and i can connect to all the computers but I it won't run the batch file i have to uninstall the driver as admin.
Any help would be great!

A: You can do this by pressing windows key x and selecting open command prompt as administrator


text:
Q: Ao compilar o código, tanto o numero1 quanto o numero2 exibem o mesmo valor mesmo tendo um incremento public class IncrementoDecremento{

    public static void main(String[] args) {

        Integer numero1 = 10;
        Integer numero2 = ++numero1;

        System.out.println("numero: " + numero1 + ", numero2: " + numero2);

    }

}

Como funciona esse Incremento?

A: Ele é chamado pré incremento então ele pega o valor da variável em que ele opera e muda seu valor adicionando 1 ao que já existia. E como o operador resulta em uma expressão o resultado disso pode ser usado em qualquer lugar que espera uma expressão, então nesse exemplo esse novo valor é atribuído para a nova variável.
O compilador acabará fazendo o mesmo que este código:
public class Main {
    public static void main(String[] args) {
        Integer numero1 = 10;
        numero1++;
        Integer numero2 = numero1;
        System.out.println("numero: " + numero1 + ", numero2: " + numero2);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Isso é diferente do pós incremento em que o valor da variável é usado na expressão antes de aplicar a operação, então o valor de numero1 acabaria sendo o mesmo, mas numero2 daria um resultado diferente. Que ficaria assim:
public class Main {
    public static void main(String[] args) {
        Integer numero1 = 10;
        Integer numero2 = numero1;
        numero1++;
        System.out.println("numero: " + numero1 + ", numero2: " + numero2);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
A recomendação é não usar operações que causa efeito colateral (muda o estado) em um lugar que espera uma expressão, então toda vez que o operador faz uma atribuição na própria variável faça isso em uma linha separada. Outra forma é usar parenteses para conter a expressão, mas na prática isso transformaria até o pós incremento em pré incremento, o que pode não ser o desejado, então só evite por tudo na mesma linha dois operadores que fazem atribuição.
Também não é muito interessante o uso do tipo Integer (é uma pena até que ele exista), prefira o int sempre que possível.

A: É simplesmente uma questão de onde esta o ++
Integer numero2 = ++numero1;

Isso se transforma nisso:
numero1 = numero1 + 1;
Integer numero2 = numero1;

Agora se você colocar:
Integer numero2 = numero1++;

Vira isso:
Interger numero2 = numero1;
numero1 = numero1 + 1;


text:
Q: Reinitializing Simulators in XCode My Simulators are destroyed somehow after installing different Xcode Versions on my machine, moved and renamed them etc. . Is it possible to remove all current Simulators listed inside the Devices Manager and do a clean reinstall or do i have to remove and add them manually ? I tried to reinstall Xcode with no success.

A: Yes, it is possible to remove / Add all of them, or whatever type you want. Go to
Xcode > Window > Devices

From here, scroll to the bottom, where you will see header saying "Simulators". Those are all simulators that you created (or system created), you can right-click and delete them. There is also button "+" at the bottom, where you can readd them.
Here is screenshot of how it looks:

Hope it helps!
EDIT: If you want to delete them all at once, please use following script, as it is not possible to remove them all at once from the UI:
https://gist.github.com/cabeca/cbaacbeb6a1cc4683aa5


text:
Q: Inaccuracy/randomness in scipy.signal.detrend Why does scipy.signal.detrend give slightly different results on the same data? Also, it seems to give different results depending on whether the keyword "linear" is included (by default, the detrend is linear anyway)
Edit: I know the inaccuracy is very small, and some inaccuracy is expected due to floating point arithmetic. What is strange is that the results are different for the same data + function.
from scipy.signal import detrend as scipy_detrend
from pylab import *

x = arange(10)
y = arange(10, dtype='int64')

subplot(211)
plot(x, scipy_detrend(y, type="linear"), label='scipy detrend linear')
plot(x, scipy_detrend(y), label='scipy detrend')
plot(x, detrend(y, "linear"), label='pylab detrend')

subplot(212)
plot(x, scipy_detrend(y, type="linear"), label='scipy detrend linear')
plot(x, scipy_detrend(y), label='scipy detrend')
plot(x, detrend(y, "linear"), label='pylab detrend')

show()

Note: the red line is pylab.detrend, blue line is scipy.signal.detrend with linear keyword and green is just scipy.signal.detrend .

A: Your data is arange(10), and your detrended result is of the order 1e-15, that means the difference is due to floating point accuracy. (Your detrended result is 15 orders of magnitude smaller than your input already)

A: It is floating point rounding error. In the general case, floating point error is not necessarily reproducible across runs on the same CPU, same data, and same code, as it can be affected by events outside the program (unless special care is taken):
Consistency of Floating-Point  Results using the Intel® Compiler or Why doesn't my application always give the same answer? - Dr. Martyn J. Corden, David Kreitzer
This seems to be a FAQ


text:
Q: reactJS application with navbar does not right justify dropdown menu items I have a reactJS application which incorporates navbar for navigation.  The initial view shows the 3 line menu icon in the top right hand corner which is what I want.  It looks like this:

When I click on the menu icon, the drop down appears like this:

I am trying to get the dropdown to align the menu items to the right, not to the left.  This is the code that generates the navbar:

            Basic Account Information

            Contributions

            Investment Elections

            Beneficiary Information

            Transfers

             Loans

             Transaction History

             Documents

             Logout

I thought putting the pullRight in the  classname would pull the items to the right.  I guess not.
Any suggestions?
Thank you.

A:
I am trying to get the dropdown to align the menu items to the right,
  not to the left.

You can use flexbox to achieve that layout.
Something like this should work:
.pullRight .nav-item {
   display: flex;
   justify-content: flex-end;
}


text:
Q: Which definition of putExtra is used when a Messenger is packed into an Intent I am starting a Service from an Activity by passing an Intent like this:
intent.putExtra("MESSENGER", new Messenger(handler));

The above line works correctly, but I would like to understand how it works since I have not converted the Messenger into a Parcel. Is this definition of putExtra being used?
putExtra(String name, Serializable value)

-Amit

A: Messenger does not implement Serializable  but it implements Parcelable (docs):
public final class
Messenger
  extends Object
  implements Parcelable

so it is:
public Intent putExtra (String name, Parcelable value)

docs here.


text:
Q: Password to Modify Prompt Disappearing I have an excel file which prompts the user for a password, or otherwise opens the file as Read-Only.
Only myself and one supervisor have the password.
Last week, went to open the file, and instead of the pw prompt, I was greeted with a "File.xlsm is locked for editing by 'another user'." message instead.
We changed the pw, thinking perhaps someone figured it out somehow... But the problem re-occurred, three times now. There is no owner file (~File.xlsm) and I have my folder settings set to show all.
When I go back to the General Options, where the pw is entered, the box is blank. Not sure what happened to the pw...
I've been scouring the net, but no one else seems to have had this issue - are you aware of anything that could be causing this?
I should note that this file is over two years old at this point, and we've never had any issues before.


text:
Q: Remote validation on action with dateTime don't get proper value (Asp.Net Core 3.1)
Model:
[Remote(action: "isDateOfTimeInUse", controller: "Contentpanel")]
public DateTime DateOfBirth { get; set; }

Action:
[AcceptVerbs("Get", "Post")]
public IActionResult isDateOfTimeInUse(DateTime dateOfBirth)
{

    var currentDate = DateTime.Now.Date.Year;

    if (currentDate - dateOfBirth.Date.Year <= 18)
    {

        return Json($"Date of birth " + dateOfBirth + " less then 18");
    }
    else
    {
        return Json(true);
    }
}


text:
Q: Slickgrid Custom MultiSelectEditor Working Only with FireFox 17.0.1 I've extend SlickGrid's Editor, tu support html Select and MultiSelect. Here is the MultiSelectEditor source:
function PickListEditor(args) {

      var $select;
      var defaultValue ;
      var scope = this;

      this.init = function() {
          console.log("PickListEditor...  SelectValues");
          console.log(args.column.columnSelectItems);
          option_str = ""
          var length =  args.column.columnSelectItems.length;
          for(var i = 0; i< length ; i++){
              var selectOption = args.column.columnSelectItems[i];
              if(selectOption["disable"]==true) disable = "disable";
              option_str += "<OPTION value='"+selectOption["stringValue"]+"'>"+selectOption["label"]+"</OPTION>";
          }
          $select = $("<select tabIndex='0' multiple='multiple'>"+ option_str +"</select>");
          console.log(args.container);
          $select.appendTo(args.container);
          $(args.container).append($select[0]);
          console.log($select);
          console.log($select[0]);
          $select.focus();
      };

      this.destroy = function() {
          $select.remove();
      };

      this.focus = function() {
          $select.focus();
      };

      this.loadValue = function(item) {
          console.log("loaded Item  : ");
          console.log(item);
          defaultValue = item[args.column.field];
          $select.val(defaultValue);
      };

      this.serializeValue = function() {
          if(args.column.columnSelectItems){
            return $select.val();
          }else{
            return "";
          }
      };

      this.applyValue = function(item,state) {
          item[args.column.field] = state;
      };

      this.isValueChanged = function() {
          return ($select.val() != defaultValue);
      };

      this.validate = function() {
          return {
              valid: true,
              msg: null
          };
      };

      this.init();
}

The multi select work fine on firefox 17.0 . But on chrome 23.0.1271.95 or safari  6.0.2 , I the multiselect is displayed, but I can't select Items.
Do someone have any Idea ?
Cheers,
Boris.

A: Try this one:

function SelectsEditor(args) {
    var $select;
    var defaultValue;
    var scope = this;

    this.init = function () {
        var option_str = "";
        for (key in args.column.options) {
            option_str += "<OPTION value='" + key + "'>" + args.column.options[key] + "</OPTION>";
        }
        $select = $("<SELECT tabIndex='0' class='editor-select' multiple='multiple'>" + option_str + "</SELECT>");
        $select.appendTo(args.container);
        $select.focus();
    };

    this.destroy = function () {
        $select.remove();
    };

    this.focus = function () {
        $select.focus();
    };

    this.loadValue = function (item) {
        defaultValue = item[args.column.field];
        $select.val(defaultValue);
    };

    this.serializeValue = function () {
        return $select.val();
    };

    this.applyValue = function (item, state) {
        item[args.column.field] = state;
    };

    this.isValueChanged = function () {
        return ($select.val() != defaultValue);
    };

    this.validate = function () {
        return {
            valid: true,
            msg: null
        };
    };

    this.init();
}


text: Q: Var overflow in JS and mongo I am working in javascript and mongo. I have to store and work with very large integers e.g. pow(10,30) maybe even more. I am concerned about overflowing, does this happen in mongo or in javascript if I use var ? I know that JS function toPrecision() works up to 20 digits, but what happens if I have more ? And what about mongo, when does the stored number overflow ?


text:
Q: How to print column in python array? I have an array of 3 numbers per row, 4 columns deep.
I am struggling to figure out how I can write the code to print all numbers from a specified column rather than from a row.
I have searched for tutorials that explain this easily and just cannot find any that have helped.
Can anyone point me in the right direction?

A: If you're thinking of python lists as rows and columns, probably better to use numpy arrays (if you're not already). Then you can print the various rows and columns easily, E.g.
import numpy as np
a = np.array([[1,2,6],[4,5,8],[8,3,5],[6,5,4]])
#Print first column
print(a[:,0])
#Print second row
print(a[1,:])

Note that otherwise you have a list of lists and you'd need to use something like,
b = [[1,2,6],[4,5,8],[8,3,5],[6,5,4]]
print([i[0] for i in b])

A: You can do this:
>>> a = [[1,2,3],[1,1,1],[2,1,1],[4,1,2]]
>>> print [row[0] for row in a]
[1, 1, 2, 4]


text:
Q: Relative Position in PHP between 2 points (Lat/Long) I have a database of airports with Latitude and Longitude for each point.  I want to run a PHP script to find all airports that are nearby a given airport, with their distance and relative direction.
I.e.  for Airport KLDJ (40-37-02.810N   074-14-40.539W)
Airport Nearby
KJFK - John F Kennedy Airport (21.2 nm NE) (40-38-23.104N   073-46-44.132W)
I have used code from http://www.movable-type.co.uk/scripts/latlong.html to find distance, and tried to use it to find bearing, which might not be right.
//BEARING RHUMB LINE
$phi = log(tan($lat2/2+pi/4)/tan($lat1/2+pi/4));
$distance['bearing'] = (rad2deg(atan2($theta, $phi)) +180) % 360;

I basically want to run all points through this script and find the distance, which I have already, but then the direction.  (i.e. N, S, W, E, NW, SW, NE, SE)

A: Heavily borrowing from the techniques here and using data from here, I put together this example
<?php

$chicago = array(
    'lat' => 41.9
  , 'lng' => 87.65
);

$dallas = array(
    'lat' => 32.73
  , 'lng' => 96.97
);

$ftworth = array(
    'lat' => 32.82
  , 'lng' => 97.35
);

$bearing = getBearingBetweenPoints( $dallas, $chicago );

echo "Bearing: $bearing°<br>";
echo "Direction: " . getCompassDirection( $bearing );

function getBearingBetweenPoints( $point1, $point2 )
{
  return getRhumbLineBearing( $point1['lat'], $point2['lng'], $point2['lat'], $point1['lng'] );
}

function getRhumbLineBearing($lat1, $lon1, $lat2, $lon2) {
  //difference in longitudinal coordinates
  $dLon = deg2rad($lon2) - deg2rad($lon1);

  //difference in the phi of latitudinal coordinates
  $dPhi = log(tan(deg2rad($lat2) / 2 + pi() / 4) / tan(deg2rad($lat1) / 2 + pi() / 4));

  //we need to recalculate $dLon if it is greater than pi
  if(abs($dLon) > pi()) {
    if($dLon > 0) {
      $dLon = (2 * pi() - $dLon) * -1;
    }
    else {
      $dLon = 2 * pi() + $dLon;
    }
  }
  //return the angle, normalized
  return (rad2deg(atan2($dLon, $dPhi)) + 360) % 360;
}

function getCompassDirection( $bearing )
{
  static $cardinals = array( 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N' );
  return $cardinals[round( $bearing / 45 )];
}

A: You can check, if the latitude of position B is larger or smaller than the latitude of position A to determine if it's in the east or in the west. Same thing with the longitude for north and south. Finally you need a threshold, to detect, in which case the drift is large enough to switch to an intermediate direction.

A: Looking at another page from the same website:
$lat = 0;  // latitude of centre of bounding circle in degrees
$lon = 0;  // longitude of centre of bounding circle in degrees
$rad = 0;  // radius of bounding circle in chosen units

// Choose your unit of measure...
$r = 6371;  // earth's radius in km
$r = 3959;  // earth's radius in miles
// or
$r = 3440;  // earth's radius in nautical miles

// convert point of origin to radians
$lat = deg2rad($lat);
$lon = deg2rad($lon);

// first-cut bounding box (in radians)
$maxLat = $lat + $rad / $r;
$minLat = $lat - $rad / $r;
// compensate for longitude getting smaller with increasing latitude
$maxLon = ( $lon + $rad / $r ) / cos( $lat );
$minLon = ( $lon - $rad / $r ) / cos( $lat );

combined with the query:
$query = 'SELECT
  id
, lat
, lon
, ACOS(SIN('.$lat.') * SIN(RADIANS(lat)) + COS('.$lat.') * COS(RADIANS(lat)) * COS(RADIANS(lon) - '. $lon.')) * '.$r.' AS distance
FROM (
   SELECT
     id
   , lat
   , lon
   FROM MyTable
   WHERE
     RADIANS(lat) > $minLat AND RADIANS(lat) < '.$maxLat.'
    AND
     RADIANS(lon) > $minLon AND RADIANS(lon) < '.$maxLon.'
) AS FirstCut
WHERE ACOS(SIN('.$lat.') * SIN(RADIANS(lat)) + COS('.$lat.') * COS(RADIANS(lat)) * COS(RADIANS(lon) - '. $lon.')) * '.$r.' < '.$rad;

Selects you a list of locations (and their distance from the origin of your circle) within the bounding circle you specified.
The only thing left to do is calculate a bearing for the locations returned. Which can be done with your rhumb line formula.
The above assumes you have your database filled with coordinates in degrees.
If you had you locations stored as geometry objects, you could use MySQL's inbuilt spatial functions. Although I'm quite sure MySQL does only include bounding rectangles.


text:
Q: Consume webservices - Return async json I currently have a search engine that calls a bunch of webservices and APIs and returns puts everything into a database.
What I want to do, is to make a async json service, that searches all the webservices and APIs and returns partial results.
The idea is, that the frontend code keeps pinging the service each second, until a "completed: true" is returned in the header.
Example pseudo-code:
Pull 1:
completed: false;
results, count: 2;

Pull 2:
completed: false;
results, count: 9;

Pull 3:
completed: true;
results, count: 15;

How do I create this the best way?
I have all my integrations as class-library projects.
My thinking was to create an ashx handler, with the IHttpAsyncHandler, but I can't seem to find anything that does what I need.
Hopefully someone can point me in the right direction.
I use VS2013 and .NET 4.5.1, so I have all the async-await goodies to my using, if needed.
EDIT:
The server is to handle multiple request, based on a search ID, so - If the search ID is 721, it's getting the results from the 721 search, the 812 gets the ones from 812 and so on.


text:
Q: How to display record into drop down Menu I have a problem is it possible to or is there any code when I open the form , the field example : i have a 4 fields namely
 id,
name,
age
gender
i want to display the field "name" into the combo box so if the record is more than 1 automatically it adds the items in the combo box.
hope someone can understand my problem newbie in using LINQ..
thank you


text:
Q: python string differences I am seeing that a string comparison of two identical strings ('fraiser') in Python is failing. When using repr(str1) and repr(str2) I get different results, but I don't know how to interpret them or why they return different things. Any help?
>>> repr(list(lowerAndMakeSet(fileChunks))[3])

"'frasier'"

>>> repr(list(lowerAndMakeSet(c))[2])

"['f', 'r', 'a', 'i', 's', 'e', 'r']"

A: Your second "string" that you are repring is actually a list and not a string. You can see this if you do type(list(lowerAndMakeSet(c))[2]).


text:
Q: Plotly bar chart showing % of total AND % of sub-group I'm trying to think of a way to most effectively display the following analysis. I'm using Python and Plotly for other analysis and would like to stick with that.
Say I have a number of newspapers. Each newspaper has a different amount of circulation worldwide. Within that, some percentage of the circulation is from the US. And within that, some percentage is from a given state, say, California.
I'd like to have a bar graph that shows, for one journal:

*

*Total circulation (say, 1M)

*Of that, how much is US circluation (say, 500k)

*Of that, how much is from California (say 100k)

So I want a compact way to show

*

*What percentage of total is from US (50%)

*What percentage of US is from CA (20%)

*What percentage of total is from CA (10%)

Then repeat for each journal and look for trends.
Plotly has a stacked bar chart which looks close, but I want to customize to specifically call out the three percentages. Each newspaper has a different total number, so a stacked bar chart normalized to 100% won't tell me the magnitude of each different newspaper.
I was thinking total %'s on the left of the bar, and US-specific %'s on the right of the bar. Or different colors?
Any advice is appreciated.
---Edit to add MWE---
import pandas as pd
import plotly.express as px

data = {'Name':['Paper A', 'Paper B'],
     'Total circ':[1000000, 800000],
      'US circ':[500000, 200000],
      'CA':[100000, 100000]
     }
df = pd.DataFrame.from_dict(data)
df['not CA'] = df['US circ'] - df['CA']
df['not US'] = df['Total circ'] - df['US circ']

fig = px.bar(df, x='Name', y=['not US', 'not CA', 'CA'], text_auto=True)

(https://ibb.co/D5123xk)

A: I have created code to add the composition ratios as labels assuming the bar chart you have created. Convert the presented data frame from wide format to long format. It then calculates the composition ratios for each group. Next, with the data frame extracted to only the regions you need, use the graph object to create a stacked bar chart, extracted by region. Labels are created from a dedicated list of the number of copies and composition ratios. The labels are specified in the loop process.
df = df.melt(id_vars='Name', value_vars=df.columns[1:], var_name='Region', value_name='Volume')
df['percentage'] = df.groupby(['Name'])['Volume'].apply(lambda x: 100 * x / float(x.head(1))).values
df = df[(df['Region'] != 'Total circ') & (df['Region'] != 'US circ')]

new_labels = ['{}k({}%)'.format(int(v/1000),p) for v, p in zip(df.Volume,df.percentage)]

import plotly.graph_objects as go

fig = go.Figure()

for i,r in enumerate(df['Region'].unique()):
    dff = df.query('Region == @r')
    #print(dff)
    fig.add_trace(go.Bar(x=dff['Name'], y=dff['Volume'], text=[new_labels[i+i*1],new_labels[1+i*2]], name=r))

fig.update_layout(barmode='stack', autosize=True, height=450)

fig.show()


text:
Q: What is "puck" in coffee brewing? I am reading the instructions of a trimming tool that came with my new espresso machine which say:

The twist blade that trims down the puck to the right level to keep a consistent extraction.

This is not about ice hockey, so I have no idea what puck means here. I tried googling, to no avail.

A: Particularly when put in an espresso machine, the coffee is ground very fine and compressed with a coffee tamper into a semi-solid mass that's the same basic shape and color as a hockey puck.  People who are really into espresso actually call this disc of coffee grounds a puck, especially after it has gotten wet and stuck together.
If you go to google and search for "coffee puck", you'll find thousands of baristas obsessing over various details of puck consistency and moisture levels, trying to correlate those attributes to the quality of the espresso shot that was produced.


text:
Q: How to implement Pace with ASP.Net MVC applications I have implemented pace.js with my ASP.NEt application so that I can display loading while my program performs ajax calls.
I have the following in my main layout view:
<script data-pace-options='{ "ajax": true, "elements": false, "document": false }' src="~/Scripts/pace.min.js"></script>

Unfortunately,
The loader keeps loading no matter what I do, sometimes it just goes on for ages. All I want it to do is load during my ajax calls. And it still loads even on pages that don't have ajax calls.
How do I do that?


text:
Q: How to get index and the range of a div element from a group of divs using jQuery If I have a group of tokenized divs like the following.
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<div> Barrack </div>
<div> Obama </div>
<div> was </div>
<div> the </div>
<div> president </div>
<div> of </div>
<div> the </div>
<div> United </div>
<div> States </div>
<div> from </div>
<div> the </div>
<div> year </div>
<div> 2012 </div>
<div> to </div>
<div> 2016 </div>
<div> . </div>

<button id="btnClick"> Click me </button>

<script>
$(function(){

$('#btnClick').click(function(){
var selection = window.getSelection();
alert(selection);
});

});
</script>

I have tried the above
1) I want to get the index of divs when I click on multiple divs on mouse click event.
Example is if I click on div which contains Barrack and 2012, I am not able to get the selected div's index.
2) If I select the div which contains both Barrack and Obama
I want the range of the div, something like:
startIndex -> 0 and length -> 2.
Where startIndex = "Barrack" is the 0th div and it ranges 2 divs Barrack and Obama.

A: Something like this should do the trick. Is this what you want?
  var selectedDiv = [];

  $("div").click(function() {
    selectedDiv.push($(this).text());
  });

EDIT
Get the index of div
 var indexNo = $("div").index($(this));

$(function() {
  var selectedDiv = [];

  $("div").click(function() {
    $(this).addClass("selected");
    var indexNo = $("div").index($(this));
    selectedDiv.push(indexNo);
    // selectedDiv.push($(this).text());
  });

  $('#btnClick').click(function() {
    // var selection = window.getSelection();
    alert(selectedDiv);
  });

});
div {
  width: 100px;
  background: #00f;
  color: #fff;
  margin: 3px;
  cursor: pointer;
}
div.selected {
  background: #f0f;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<div> Barrack </div>
<div> Obama </div>
<div> was </div>
<div> the </div>
<div> president </div>
<div> of </div>
<div> the </div>
<div> United </div>
<div> States </div>
<div> from </div>
<div> the </div>
<div> year </div>
<div> 2012 </div>
<div> to </div>
<div> 2016 </div>
<div> . </div>

<button id="btnClick"> Click me </button>

A: Use the slice function of jQuery.
.slice( start [, end ] )

start ➡ An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.
end ➡ An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from
  the end of the set. If omitted, the range continues until the end of
  the set.

For your case, to select only Barack & Obama from multiple div elements, I would write something like:
$( "div" ).slice(0, 1).css( "background-color", "red" );

jQuery.slice() method

A: Here you go
<div class="findIndex">
  <div> the </div>
  <div> United </div>
  <div> States </div>
  <div> from </div>
  <div> the </div>
  <div> year </div>
  <div> 2012 </div>
  <div> to </div>
  <div> 2016 </div>
  <div> . </div>
</div>
<button id="btnClick"> Click me </button>

var indexRange = [];
$(".findIndex div").on("click",function(){
  if(indexRange.length == 0){
      indexRange[0] = $(this).index();
  }else{
    indexRange[1] = $(this).index();
  }
})

$("#btnClick").on("click",function(){
    if(indexRange.length == 2){
        alert("Start Index:" + indexRange[0] + "\n" + "End Index:" + indexRange[1] + "\n" + "Length:" + ((indexRange[1] - indexRange[0]) + 1));
    }else{
        alert("Please select start and end first.");
    }
    indexRange = Array();
})

Here is the fiddle :
https://jsfiddle.net/vsmdcc3L/

A: You can try $.each() or $(selector).each()
<script>
    $(document).ready(function(){
        var lastIdx = 0;
        $("div").each(function(idx, item){
            $(this).click(function(){
                if (idx > lastIdx) {
                    console.log("start:" + lastIdx);
                    console.log("length:" + (idx - lastIdx + 1));
                }
                lastIdx = idx;
            });
        });
    });
</script>


text:
Q: Printing from a preview (PrintPreviewDialog) without calling PrintPageEventHandler again, and recreating the PrintDocument I'm certain I'm missing something here...
I create a PrintDocument (which is very time consuming 600-1200 pages), and then allow the user to preview it with PrintPreviewDialog.
However, when the user chooses to print the document (from the preview dialog) the print document gets created again. I just want the document that has been created, previewed, accepted by the user, to be printed. How do I print the created document directly?
The code is simply this...
            PageSettings pageSettings = new PageSettings();
            pageSettings.Margins.Top = 40;
            pageSettings.Margins.Bottom = 40;
            pageSettings.Margins.Left = 40;
            pageSettings.Margins.Right = 40;

            LoadChartsBook chartsBook = new LoadChartsBook(chartsData);
            PrintDocument docToPrint = chartsBook.CreatePrintDocument();
            docToPrint.DefaultPageSettings = pageSettings;

            PrintPreviewDialog previewDialog = new PrintPreviewDialog();
            previewDialog.Document = docToPrint;
            previewDialog.ShowDialog();

Then the called code for CreatePrintDocument()
    public PrintDocument CreatePrintDocument()
    {
        index.resetCounter();
        coverPagePrinted = false;
        currentChartIndex = 0;
        pageNumber = 0;
        PrintDocument printDocument = new PrintDocument();
        printDocument.DocumentName = (index.totalEntries()+1).ToString() + ", of Load Charts Book: " + chartBookID;
        printDocument.PrintPage += new PrintPageEventHandler(PrintLoadChartsBookEventHandler);
        return printDocument;
    }

Each chart is very processor intensive and hence time consuming to create, I need to avoid this apparent second call to CreatePrintDocument() but can't see why it's being called in again anyway.
Am I missing a setting in the preview dialog?
Any help appreciated.


text:
Q: C# List hides properties?
Possible Duplicate:
How does List<T> make IsReadOnly private when IsReadOnly is an interface member?

Okay, this is driving me nuts. List<T> implements IList<T>.  However,
IList<int> list = new List<int>();
bool b = list.IsReadOnly;
bool c = ((List<int>)list).IsReadOnly;    // Error

The error is:

'System.Collections.Generic.List' does not contain a definition for 'IsReadOnly' and no extension method 'IsReadOnly' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?)

How can this be? Doesn't this violate the very rule that we tell everyone, about not hiding members?  What is the implementation detail here?

A: Because the implementation is via an explicit interface implementation.
Meaning that it's defined as
bool IList<T>.IsReadOnly { get; set; //etc }

http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx
And that is why it's not off of List.

A: List<T> implements IList<T> explicitly so you have to cast the object to the interface before being able to access IsReadOnly . From MSDN:

A class that implements an interface can explicitly implement a member
  of that interface. When a member is explicitly implemented, it cannot
  be accessed through a class instance, but only through an instance of
  the interface

A: If you look at the List class, you'll see this:
 bool IList.IsReadOnly { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
        get; }

All that's really relevant is that IsReadOnly is declared using the explicit implementation which means that property can only be seen if the object is declared as that of IList.

A: Explicit interface implementation, something like:
bool IList<T>.IsReadOnly { get; }


text:
Q: Zend GData YouTube API errors Greetings,
Having quite a bit of difficulty with the YouTube API. I added the Zend Gdata folder to my include_path and all of the API tests run fine, but when I try to load the YouTube API Demo App, I get the following error:
Warning: include_once(Zend/Gdata/YouTube.php) [function.include-once]: failed to open stream: No such file or directory in /home/tappess1/public_html/includes/ZendGdata/library/Zend/Loader.php on line 146

Warning: include_once() [function.include]: Failed opening 'Zend/Gdata/YouTube.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/tappess1/public_html/includes/ZendGdata/library/Zend/Loader.php on line 146

Warning: require_once(Zend/Exception.php) [function.require-once]: failed to open stream: No such file or directory in /home/tappess1/public_html/includes/ZendGdata/library/Zend/Loader.php on line 98

Fatal error: require_once() [function.require]: Failed opening required 'Zend/Exception.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/tappess1/public_html/includes/ZendGdata/library/Zend/Loader.php on line 98

The PHP include_path seems to be set correctly, the tests run.. the issue seems to be either in operations.php in the YouTube API's demo or in Loader.php. The default directory for Loader.php was simply Zend/Loader.php, I generally use $_SERVER['DOCUMENT_ROOT'] . '/path/to/dir'; due to listing restrictions on my host.
Any idea why this will not work? It occurs when I click on the Authenticate link within the demo.
Thanks

A: Urgh, I had exactly the same errors. My solution was to totally scrap using the Zend GData API and use the REST interface. This way you're writing more code, but it's all under your control.


text:
Q: asymptotic form of divisor bound Let $d(n)$ denote the divisor function, the number of divisors of $n$. Following this post of Tao, https://terrytao.wordpress.com/2008/09/23/the-divisor-bound/ I have managed to show that $d(n) \leq C_{\epsilon}n^{\epsilon}$ for any $\epsilon > 0$.
I want to show this is equivalent to $d(n)=n^{o(1)}$ but am not sure how to do so.
I know that $f(x)=o(g(x))$ means that $\lim_{x \to \infty}\frac{f(x)}{g(x)}=0$. I'm not sure how to proceed because in the above the "little oh" is an exponent.
I did think about taking logs but I don't know if this is allowed with asymptotic notation or if that then helps as I'd then having to show $\frac{\log(d(n))}{1} = 0$ (I've assumed I could "absorb" the $\log(n)$ into the "little-oh").


text:
Q: How do I retrieve data from database using cursor? (Android, SQLite) I am stuck. I can't find out what I do wrong, so please help anybody.
Though it's quite simple task, I don't understand how actually database looks like.
Here's the code I use to insert data into table in database:
EditText title = (EditText)findViewById(R.id.Title);
String Title = title.getText().toString();

EditText d = (EditText)findViewById(R.id.director);
String Director = d.getText().toString();

SQLiteDatabase db = openOrCreateDatabase("Films", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS MyFilms (idFilm INTEGER PRIMARY KEY AUTOINCREMENT, Title VARCHAR, Director VARCHAR, Year INTEGER, Rating INTEGER);");
db.execSQL("INSERT INTO MyFilms (Title) VALUES('" + Title + "');");
db.execSQL("INSERT INTO MyFilms (Director) VALUES('" + Director + "');");
db.close();

Does this code gives me a table with columns idfilm, Title, Director, Year, Rating?
If it's so, there's still a problem when I try to retrieve all the titles from Title column using this code:
SQLiteDatabase db = openOrCreateDatabase("Films", MODE_PRIVATE, null);
Cursor c = db.rawQuery("SELECT * FROM MyFilms",null);
c.moveToFirst();

while (c.isAfterLast() == false) {
  String Title = c.getString(c.getColumnIndex("Director"));
  stringList.add(Title); //This I use to create listlayout dynamically and show all the Titles in it
  c.moveToNext();
}

The error log:
05-21 17:50:14.666: E/AndroidRuntime(27045): FATAL EXCEPTION: main
05-21 17:50:14.666: E/AndroidRuntime(27045): java.lang.NullPointerException
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:355)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.widget.AbsListView.obtainView(AbsListView.java:1409)
 05-21 17:50:14.666: E/AndroidRuntime(27045):   at android.widget.ListView.measureHeightOfChildren(ListView.java:1216)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.widget.ListView.onMeasure(ListView.java:1127)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.view.View.measure(View.java:8313)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.widget.RelativeLayout.measureChild(RelativeLayout.java:566)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:381)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.view.View.measure(View.java:8313)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.view.View.measure(View.java:8313)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.view.View.measure(View.java:8313)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.view.View.measure(View.java:8313)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.view.ViewRoot.performTraversals(ViewRoot.java:839)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.os.Looper.loop(Looper.java:123)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at android.app.ActivityThread.main(ActivityThread.java:3683)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at java.lang.reflect.Method.invokeNative(Native Method)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at java.lang.reflect.Method.invoke(Method.java:507)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-21 17:50:14.666: E/AndroidRuntime(27045):    at dalvik.system.NativeStart.main(Native Method)

Why does DDMS throw NullPointerException? How should I get the data from "Title"? I tried to use c.getString(), but when I ask for c.getString(1) there's still NullPointerException though it returns "Director" when I set c.getString(2). Please, help!

A: if your properly inserted values from edittext box. then do these steps .
     Retrieve values
Cursor c = db.rawQuery("SELECT * FROM MyFilms",null);

if (c != null ) {
        if  (c.moveToFirst()) {
              do {
              String dir = c.getString(c.getColumnIndex("Director"));
              test.add("" + dir );
              }while (c.moveToNext());
        }
   }

Display the values as a list
    this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,test));

The statement displays it as a list as the class extends a ListActivity.

A: Your problem happens when you populate the database (your first code segment).
You need to combine the INSERT statements:
db.execSQL("INSERT INTO MyFilms (Title, Director, Year) VALUES('"
    + title + "','" + director + "'," + year + ");");

Otherwise, you wind up with rows that contain a null value for Title or Director.
(Note: Don't use the SQL notation above, because it may leave you vulnerable to SQL injection. I only wrote it this way for the sake of simplicity. In production code, you should use parameters or sanitize your values. Don't become a victim of Little Bobby Tables).
EDIT
Here are some threads regarding prepared statements:

*

*How do I use prepared statements in SQlite in Android?

*Queries with prepared statements in Android?

A: Use this code.
c.moveToFirst();
        if (c != null) {
            do {
                for (int i = 0; i < c.getColumnCount(); i++) {

                    Log.e("", "" + c.getString(i));
                }
            }while (c.moveToNext());
        }


text:
Q: Django- Clear user cache when user logged out I am using django.core.cache to store user roles related data in the cache. The user roles are stored as keys roles_<user.id> in the cache.
I want to delete the roles_<user.id> key from the cache whenever theuser logs out from the system.
I used the user_logged_out auth signal for this but somehow this signal is not working(not deleting the cache data).
I have created a receiver in signals.py as:
def clear_user_cache(sender, user, request, **kwargs):
    cache.delete('roles_{}'.format(user.id))

user_logged_out.connect(clear_user_cache)

My logout url is:
url(r'^accounts/logout/', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='auth_logout'),

Logout in template:
{% trans 'Logout' %}

When I hit the logout button, the user is logged out but the cache is not being cleared. If I try printing some statements in the signal receiver, they are not getting printed.
I though the url in the template might have caused this problem so I tried changing it to:
{% trans 'Logout' %}

But still nothing happened.
How can I make the logout signal to fire when the user is logged out?
I am using Django==1.8.18 and python2.7

A: Sounds like your signals haven't been registered. If the signals.py file is in the user app then you need to modify user/apps.py and user/__init__.py
You could also register them by importing in your models but I think this way is a bit cleaner.
# apps.py

from django.apps import AppConfig

class UserConfig(AppConfig):
    name = 'user'

    def ready(self):
        from . import signals

# __init__.py

default_app_config = 'user.apps.UserConfig'

A: As @bdoubleu suggested in his answer that my signals might have not been registered, I tried defining my receiver function inside the users/__init__.py file instead of signals.py.
This caused the signal to be activated whenever user logs out from the system and the user cache for respective user is cleared.
This approach was easy to implement and indeed solved my query. I am open to any other suggestions that are better than this approach.


text:
Q: Failed to find Build Tools revision 27.1.1. When I try to download, says it has no download link: This is my build.gradle file:
buildscript {
repositories {
    google()
    maven { url 'https://maven.fabric.io/public' }
    maven { url 'https://maven.google.com' }
    maven { url 'http://dl.bintray.com/amulyakhare/maven' }
    maven { url 'https://jcenter.bintray.com/' }
    maven { url "https://jitpack.io" }
    mavenCentral()
}

dependencies {
    classpath 'io.fabric.tools:gradle:1.+'
    classpath "io.realm:realm-gradle-plugin:3.2.0"
    classpath 'com.google.gms:google-services:3.1.0' // google-services plugin
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'realm-android'

repositories {
google()
maven { url 'https://maven.fabric.io/public' }
maven { url 'http://dl.bintray.com/amulyakhare/maven' }
maven { url 'https://jcenter.bintray.com/' }
maven { url "https://jitpack.io" }
maven {
    url 'https://maven.google.com'
}
}

android {
compileSdkVersion 27
buildToolsVersion '27.1.1'
defaultConfig {
    applicationId "nl.hgrams.passenger"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 905
    versionName '3.2'
    multiDexEnabled true
}
sourceSets {
    main {
        java {
            exclude 'nl.hgrams.passenger.activities.PSSimilarTripsGroupActivity'
            exclude 'nl.hgrams.passenger.activities.PSTripStatsActivity'
        }
    }
}
lintOptions {
    checkReleaseBuilds false
    abortOnError false
}
dexOptions {
    preDexLibraries = false
    javaMaxHeapSize "4g"
}
packagingOptions {
    exclude 'META-INF/services/javax.annotation.processing.Processor'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE'
}
buildTypes {
    release {
        minifyEnabled false
        shrinkResources false
        ext.enableCrashlytics = true
        ext.betaDistributionReleaseNotesFilePath = "/Users/gopublic/bamboo-home/xml-data/build-dir/131073/PAS-PAD-VRANDROID/changelog.txt"
        ext.betaDistributionEmails = "alin.rosu@100grams.nl, pedro.amanhui@100grams.nl, 100gramstest@gmail.com"
        ext.betaDistributionGroupAliases = "passenger-android-beta"

    }

    debug {
        minifyEnabled false
        shrinkResources false
        ext.enableCrashlytics = true
        ext.betaDistributionEmails = "alin.rosu@100grams.nl, pedro.amanhui@100grams.nl, 100gramstest@gmail.com"
        ext.betaDistributionReleaseNotesFilePath = "/Users/gopublic/bamboo-home/xml-data/build-dir/131073/PAS-PAD-VRANDROID/changelog.txt"
        ext.betaDistributionGroupAliases = "passenger-android-beta"

    }
}
}

dependencies {
implementation 'com.android.support:multidex:1.0.0'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:percent:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:transition:27.1.1'
implementation 'com.google.code.gson:gson:2+'
implementation 'com.android.volley:volley:1+'
implementation 'com.squareup.okhttp:okhttp:2.0.0+'
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation 'com.google.android.gms:play-services-maps:11.8.0'
implementation 'com.google.android.gms:play-services-location:11.8.0'
implementation 'com.google.android.gms:play-services-gcm:11.8.0'
implementation 'com.google.android.gms:play-services-analytics:11.8.0'
implementation 'com.google.android.gms:play-services-auth:11.8.0'
implementation 'com.google.firebase:firebase-core:11.8.0'
implementation 'com.google.firebase:firebase-storage:11.8.0'
implementation 'com.google.firebase:firebase-auth:11.8.0'
implementation 'com.google.firebase:firebase-messaging:11.8.0'
implementation files('libs/nineoldandroids-2.4.0.jar')
implementation files('libs/okhttp-urlconnection-2.0.0.jar')
implementation 'com.edmodo:cropper:1.0.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.makeramen:roundedimageview:2.3.0'
implementation 'com.google.maps.android:android-maps-utils:0.4+'
implementation 'com.instabug.library:instabug:4.2.6'
implementation 'io.reactivex:rxjava:1.1.0'
implementation 'com.plattysoft.leonids:LeonidsLib:1.3.1'
implementation 'io.smooch:core:latest.release'
implementation 'io.smooch:ui:latest.release'
implementation "com.daimajia.swipelayout:library:1.2.0@aar"
implementation 'com.squareup.okhttp3:okhttp:3.2.0'
implementation 'com.squareup.retrofit:retrofit:1.9.0'
implementation 'com.bartoszlipinski:recyclerviewheader2:2.0.1'
implementation 'io.branch.sdk.android:library:2.+'
implementation 'com.github.2359media:EasyAndroidAnimations:0.8'
implementation 'me.grantland:autofittextview:0.2.+'
implementation 'com.github.kaknazaveshtakipishi:PermissionEverywhere:1.0.2'
implementation('com.crashlytics.sdk.android:crashlytics:2.8.0@aar') {
    transitive = true;
}
implementation(
        [group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1'],
        [group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.4.1'],
        [group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.4.1']
)
implementation 'devlight.io:navigationtabbar:1.2.5'
implementation 'org.apache.commons:commons-lang3:3.4'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.yahoo.mobile.client.android.util.rangeseekbar:rangeseekbar-library:0.1.0'
implementation 'commons-io:commons-io:2.4'
implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
}

apply plugin: 'com.google.gms.google-services'

I get this error:
Failed to find Build Tools revision 27.1.1
Install Build Tools 27.1.1 and sync project

If I press to install build tools 27.1.1. I get an not able to download error:
https://s3.amazonaws.com/uploads.hipchat.com/39260/829560/ECeAJ5Gi0GQnjoZ/upload.png
Why is this happening? It used to work with 26.1.1 but now that I updated to Android Studio 3.1, it doesn't allow me to use that version, saying 27.0.3 is the minimum which works. but tried with 27.0.3 and 27.1.1 and I always get compilation errors

A: According to the Android SDK manager, the latest version of build tools are 27.0.3 and 28.0.0-rc1.
27.1.1 is the support libraries version.

A: Referring the official documentation, the actual release is:
android {
    buildToolsVersion "27.0.3"
    ...
}

and not 27.1.1
so, fix your android node with
android {
  compileSdkVersion 27
  buildToolsVersion '27.0.3'
   .....


text:
Q: Encrypting and decrypting a zip file in Android? I am using this code: http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des for encrypting my zip files used in android app .It is working really fine with the zip files when I tried it using java code ,But when I tried same methods in Android app - It decrypts the file but file I get is corrupted and unable to open it.
Log:
         04-19 10:58:25.711: W/System.err(6752): net.lingala.zip4j.exception.ZipException: zip headers not found. probably not a zip file
         04-19 10:58:25.721: W/System.err(6752):    at net.lingala.zip4j.core.HeaderReader.readEndOfCentralDirectoryRecord(HeaderReader.java:122)

And when I  try to open the same file on Windows with winzip it displays:
   Does not appear to be a valid archive file.

Update::
public class EncryptDecryptFileStreamWithDES {

private static Cipher ecipher;
private static Cipher dcipher;

// 8-byte initialization vector
private static byte[] iv = {
    (byte)0xB2, (byte)0x12, (byte)0xD5, (byte)0xB2,
    (byte)0x44, (byte)0x21, (byte)0xC3, (byte)0xC3
};

public static void call() {

    try {

        SecretKey key = KeyGenerator.getInstance("DES").generateKey();

        AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);

        ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        dcipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

    //    encrypt(new FileInputStream("C:\\Users\\Admin\\Desktop\\zipped\\4.zip"), new FileOutputStream("C:\\Users\\Admin\\Desktop\\zipped\\4.dat"));
      //  decrypt(new FileInputStream("C:\\Users\\Admin\\Desktop\\zipped\\4.dat"), new FileOutputStream("C:\\Users\\Admin\\Desktop\\zipped\\4new.zip"));

    //}
    //catch (FileNotFoundException e) {
        //System.out.println("File Not Found:" + e.getMessage());
        //return;
    }
    catch (InvalidAlgorithmParameterException e) {
        System.out.println("Invalid Alogorithm Parameter:" + e.getMessage());
        return;
    }
    catch (NoSuchAlgorithmException e) {
        System.out.println("No Such Algorithm:" + e.getMessage());
        return;
    }
    catch (NoSuchPaddingException e) {
        System.out.println("No Such Padding:" + e.getMessage());
        return;
    }
    catch (InvalidKeyException e) {
        System.out.println("Invalid Key:" + e.getMessage());
        return;
    }

}

public static void encrypt(InputStream is, OutputStream os) {

    try {

        call();

        byte[] buf = new byte[1024];

        // bytes at this stream are first encoded
        os = new CipherOutputStream(os, ecipher);

        // read in the clear text and write to out to encrypt
        int numRead = 0;
        while ((numRead = is.read(buf)) >= 0) {
            os.write(buf, 0, numRead);
        }

        // close all streams
        os.close();

    }
    catch (IOException e) {
        System.out.println("I/O Error:" + e.getMessage());
    }

}

public static void decrypt(InputStream is, OutputStream os) {

    try {

        call();

        byte[] buf = new byte[1024];

        // bytes read from stream will be decrypted
        CipherInputStream cis = new CipherInputStream(is, dcipher);

        // read in the decrypted bytes and write the clear text to out
        int numRead = 0;
        while ((numRead = cis.read(buf)) > 0) {
            os.write(buf, 0, numRead);
        }

        // close all streams
        cis.close();
        is.close();
        os.close();

    }
    catch (IOException e) {
        System.out.println("I/O Error:" + e.getMessage());
    }

}

}

This is the Class which I am using:

A: The problem is that you use different keys to encrypt and decrypt the file:
1) You call encrypt(..) from somewhere outside the EncryptDecryptFileStreamWithDES, which in its turn calls your call() method, which initializes new key:
SecretKey key = KeyGenerator.getInstance("DES").generateKey();

2) Then you call decrypt(..), which calls your call() method again and you get new SecretKey.
There is no such a problem in the example you used, there is an opposite order of these methods invocations.
To extend this example you need to hold the key between invocation of encrypt(..) and decrypt(..) and then initialize SecretKeySpec with the key stored:
byte[] keyBytes = KeyGenerator.getInstance("AES").getEncoded();

...

SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);

Here is a little bit more real-life example.
P.S. As it was mentioned, using DES algorithm is not the best idea, use AES instead.


text:
Q: Algorithm: How to evenly distribute different colored balls? Let's say I have some number of different colored balls. For the sake of an example, let's assume 4 red balls, 4 blue balls and 2 green balls. If I want to evenly distribute these balls so that the most consistent distance between two balls of the same color is maintained I could have the following sequence:
R-B-G-R-B-R-B-G-R-B
Even though Blue and Red Balls aren't always the same distance from their counterparts, they are arranged in such a way that keeps their distances consistent while also maintaining consistency for the Green Balls
In the case of 6 red balls, 5 blue balls, and 3 green balls, I could have something like:
R-B-R-G-B-R-B-G-R-B-R-G-R
I'm not exactly sure what the criteria for "most consistent distance between two balls of the same color" would be but is there some kind of algorithm or generalized solution that would solve this? What is the formal name of this problem, if this is the case?

A: This problem is similar to drawing of line in nD-space (here 3D). So you can use Bresenham/DDA-like algorithms to generate sequence with fair item distribution (instead of fair distribution of pixel shifts in ever dimension). Arbitrary found example
(I have not checked its correctness - perhaps division dm/2 might produce worse results than error doubling):
void plotLine3d(int x0, int y0, int z0, int x1, int y1, int z1)
{
   int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1;
   int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1;
   int dz = abs(z1-z0), sz = z0<z1 ? 1 : -1;
   int dm = max(dx,dy,dz), i = dm; /* maximum difference */
   x1 = y1 = z1 = dm/2; /* error offset */

   for(;;) {  /* loop */
      setPixel(x0,y0,z0);
      if (i-- == 0) break;
      x1 -= dx; if (x1 < 0) { x1 += dm; x0 += sx; }
      y1 -= dy; if (y1 < 0) { y1 += dm; y0 += sy; }
      z1 -= dz; if (z1 < 0) { z1 += dm; z0 += sz; }
   }
}

Replace x1-x0 by  the first color count, y1-y0 by the second and so on. Output corresponding color in successful if-conditions:
{x1 -= dx; if (x1 < 0) { x1 += dm; x0 += sx;HERE}


text:
Q: Google Cloud Run Liveness Probe with Terraform I'm willing to make sure that my Google Cloud Run instances that crash are known as crashed and taken care of by spawning new instances. It doesn't seem to be the case right now with my configuration.
I've read in the official Cloud Run doc 1 that it was possible to configure a liveness probe to know when my container is down and then auto-heal in case of problem.
The liveness probe doesn't seem to be configurable from terraform.
Had you have any case where you had to configure it from terraform?
Thanks a lot for your answers and advice!
PS: if my question seems odd, please do not hesitate to tell me if there's another way to get auto-healing on a google cloud run instance.
PS2: what I'm thinking now right now is setting up a cloud function that will check every 10 seconds if my /health endpoint is ok, and if not, will redeploy. Let me know what you think about it.

A: It's not possible to configure health/live probes with Terraform right now.
There is a open issue here: https://github.com/hashicorp/terraform-provider-google/issues/12532


text:
Q: Invariant of a localized divergenceless vector field Assume $V$ is a 3D smooth divergenceless ($\nabla \cdot V = 0$) vector field which vanishes outside some finite region $\mathcal{R}$. We can intuitively imagine such a field as a bunch of integral curves looping around one another. Is there an invariant associated to such a field which tells us "how many" integral curves of $V$ there are in $\mathcal{R}$.
For example, if $\mathcal{R}$ has the topology of a torus, and all the integral curves of $V$ circle inside the tube, we can calculate the flux of $V$ at any cross section of the torus and this would give us "the number of integral curves of $V$". Can this be generalized for an arbitrary, but well-behaved, region $\mathcal{R}$ and divergence-less vector field $V$?


text:
Q: Luigi passing small data between tasks Using Luigi I want to do a query on my postgres DB to get a lat/lng coordinate pair then pass that pair onto another task.
I have a task QueryPostgres() that takes a SQL string as an input and performs the query. Is there a more concise way of passing the query result onto the next task rather than writing it to a local file? After all it is only two numbers I need to pass.
Thanks!

A: You could write the result out into another table in the database, redis, etc. Check the luigi.contrib package for a wide variety of output target types. http://luigi.readthedocs.io/en/stable/api/luigi.contrib.html


text:
Q: Lagrange's Theorem Group theory proof I am reading DF's proof of Lagrange's theorem that the order of a subgroup divides the order of a group.
The part where I cannot follow is when they say that :
The set of left cosets of H in G partition G (I can see this).
Bythe definition of a left coset the map:
$H \rightarrow gH$ defined by $h \mapsto gh$ is a surjection from H to the left coset gH (this I cannot see clearly) but I know the definition of a left coset is that you take all elements of G and multiply on the subgroup H on the left side
Injective since $gh_{1}=gh_{2} \implies h_{1}=h_{2}$
Then they conclude that H and gH have the same order I guess this is because we can see now it is  bijective?
My question here is about the Surjectiveness, how can I see that? and my other question is what excatly are they doing when showing injectiveness are they just looking on the element map? \mapsto

A: Having looked at your post and flipped to the proof from Dummit and Foote that you're talking about, I have a hunch that you're getting hung up on the notation.  That being said, perhaps it will help to rephrase the major points.
For any element $g \in G$, we can define the left-coset map
$$
\phi_g : H \to gH\\
\phi_g(h) = gh
$$
The image of this map is
$$
\phi_g(H) = \{\phi_g(h) : h \in H\} =  \{gh: h \in H\}
$$
so that, by the definition of a left coset, $\phi_g(H) = gH$.  In other words, the map $\phi_g$ is surjective.
Now, try to use the left-cancellation law to show that $\phi_g$ is injective.

A: I think misunderstanding is in statement "the definition of a left coset is that you take all elements of G".
No, definition if coset is that you take one element of G and multiply it by all element of $G$ (although different elements $g_1$ and $g_2$ can generate same coset). By taking all element of $G$ you create all cosets and $H$ itself (if $g \in H$).
So, function $H \rightarrow gH$ is surjective because for every $h$ exist element in $gH$ (it is $gh$), and as was mentioned by you injective


text:
Q: Facebook: FQL get all checkins me() is tagged in I want to get all the checkins a user is tagged in (note: I am not interested in his own checkins). I tried the following, which is a little illogical and of course does not work, but you'll get what I am trying to do:
SELECT message FROM checkin WHERE tagged_uids IN
(SELECT uid FROM user WHERE uid = me())

Any ideas?

A: You're thinking of IN backwards. The query you're looking for is:
SELECT message FROM checkin WHERE me() IN tagged_uids

However, tagged_uids is not indexable, so you'll need to know more information before you can run this query (like who is actually recording the checkin). One thing you could try is:
SELECT message FROM checkin
WHERE author_uid IN (SELECT uid2 FROM friend WHERE uid1 = me())
    AND me() IN tagged_uids

This will find all checkins in which your user is tagged that are by friends of the user (probably the only people who can check in that user anyway).