text:
Q: How to find min value of grouped data on column A and min of the other column B when duplicate values exist on A I am trying to analyse a dataframe using Pandas. My question is similar to the question:
How to get rows with min values in one column, grouped by other column, while keeping other columns?
In addition to that question (which is very important in my case), I also need to find the min value of the other columns if there are multiple min values for grouped column. If not, I need to see the corresponding values.
Here is a basic example;
df = pd.DataFrame({'id' : [1,1,1,2,2],
                   'A' : [8,6,6,8,9],
                   'B' : [1,2,4,5,4]})

When this dataframe is grouped by 'id' and aggregated (first on 'A', then on 'B') as I want, here is the output I want to see:
id  A   B
1   6   2
2   8   5

Note that, there are multiple rows having min value for the column 'A' when id is 1. The corresponding 'B' column values are 2 and 4. Thus, the min of them is returned as the result for the 'B' column.
I do not know R, so, I did not understand the answer from the link above. Anyway, this is a different version of it.

A: IIUC, using idxmin after sorting by B

df.loc[df.sort_values('B').groupby('id')['A'].idxmin()]

   id  A  B
1   1  6  2
3   2  8  5

A: Another way is taking advantage of groupby sorts group_keys by default. So, groupby 'id,  A' will push groups of min A per ID to the top. After that, call min on B, reset_index and drop_duplicate
df.groupby(['id', 'A'])['B'].min().reset_index().drop_duplicates(subset='id')

Out[298]:
   id  A  B
0   1  6  2
2   2  8  5


text:
Q: How do I find in which table Data has my given value in SQL What I need is to find out which tables have certain column data. It doesn't matter which column it belongs in, I just don't know which table to look at since there are a lot of tables.
Please let me know if you have ideas. Thanks.
Note: I should search in XML columns as well.
This is what I have tried. It did not work, please suggest better ideas for me to try.
    USE DATABASE_NAME
DECLARE @SearchStr nvarchar(100) = 'SEARCH_TEXT'
DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL

BEGIN
    SET @ColumnName = ''
    SET @TableName =
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL

        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END
END

SELECT ColumnName, ColumnValue FROM @Results

A: I made changes to the code you already had to include the XML datatype and cast the XML into NVARCHAR (MAX) in the WHERE clause and in the table variable.
USE DATABASE_NAME
DECLARE @SearchStr nvarchar(100) = 'SEARCH_TEXT'
DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(max))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL

BEGIN
    SET @ColumnName = ''
    SET @TableName =
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' +
            QUOTENAME(TABLE_NAME) ), 'IsMSShipped' ) = 0 )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int',
                'decimal','xml') AND QUOTENAME(COLUMN_NAME) > @ColumnName )

    IF @ColumnName IS NOT NULL

    BEGIN
        INSERT INTO @Results
        EXEC
        (
            'SELECT ''' + @TableName + '.' + @ColumnName + ''','+
            'cast('+    @ColumnName+  ' as nvarchar(max))'
            +'FROM ' + @TableName + ' (NOLOCK) ' +
            ' WHERE cast( ' +  @ColumnName + ' as nvarchar(max)) LIKE ' + @SearchStr2
        )
    END
   END
END
SELECT ColumnName, ColumnValue FROM @Results

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exception has occurred: TclError can't use "icon.png" as iconphoto: not a photo image I've been trying to figure out why this doesn't work.
from tkinter import *
import webbrowser
import urllib
import base64
import os
window=Tk()
def browser(url):
   webbrowser.open_new_tab(url)
window.title("name")

if os.name == "nt":
   user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36"
   url = "https://redstoner.me/downloads/gigashitfiles/gigashit.ico"
   headers = {"User-Agent" : user_agent,}
   request = urllib.request.Request(url,None,headers)
   response = urllib.request.urlopen(request)
   b64pic = base64.encodebytes(response.read())
   response.close()
   icondata= base64.b64decode(b64pic)
   tempFile= "icon.ico"
   iconfile= open(tempFile,"wb")
   iconfile.write(icondata)
   iconfile.close()
   window.wm_iconbitmap(tempFile)
   os.remove(tempFile)
else:
   user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36"
   url = "https://redstoner.me/downloads/gigashitfiles/gigashit.png"
   headers = {"User-Agent" : user_agent,}
   request = urllib.request.Request(url,None,headers)
   response = urllib.request.urlopen(request)
   b64pic = base64.encodebytes(response.read())
   response.close()
   icondata= base64.b64decode(b64pic)
   tempFile= "icon.png"
   iconfile= open(tempFile,"wb")
   iconfile.write(icondata)
   iconfile.close()
   window.iconphoto(True, tempFile)
   os.remove(tempFile)

window.geometry("650x700")
window.mainloop()

First of all, I know I could of made this way cleaner but right now I really wanna find out how to get rid of the error.
I tried using tk.call but it didn't work also.
Error is at line 40, in
window.iconphoto(True, tempFile)


text:
Q: d3.js area graph with initial zoom I am trying ti implement a zoom and brush chart with D3.js with an initial zoom. The initial zoom covers only about 10% of the brushable extent - this works correctly. When I zoom on the chart the first time, the zoom does not take into account the initial state.
Here's the graph initially:

And after the first zoom:

Here's a plunkr, and the relevant code:
 svg.append("rect")
      .attr("class", "zoom")
      .attr("width", width)
      .attr("height", height)
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .call(zoom);

    //To set initial zoom level in graph
      var d0 = data[0].date,
      d1 = data[data.length-1].date;
     svg.call(zoom).transition()
    .duration(1500)
    .call(zoom.transform, d3.zoomIdentity
          .scale(width / (x(d1) - x(d0)))
          .translate(-x(d0), 0));

  function brushed() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
    var s = d3.event.selection || x2.range();
    x.domain(s.map(x2.invert, x2));
    focus.select(".area").attr("d", area);
    focus.select(".axis--x").call(xAxis);
    svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
        .scale(width / (s[1] - s[0]))
        .translate(-s[0], 0));
  }

  function zoomed() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
    var t = d3.event.transform;
    x.domain(t.rescaleX(x2).domain());
    focus.select(".area").attr("d", area);
    focus.select(".axis--x").call(xAxis);
    context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
  }

Why are zoom events not relative to the initial zoom state?

A: Your code works fine if, you don't zoom over the chart plot area: you can zoom on the axes or margins for example. This is a hint as to what is happening:
The zoom is applied to two elements:
svg.append("rect")
   ...
   .call(zoom);

And:
svg.call(zoom)

This means we are keeping track of two zoom states - but you only apply an initial state to one:
svg.call(zoom).transition()
  .duration(1500)
  .call(zoom.transform, d3.zoomIdentity
      .scale(width / (x(d1) - x(d0)))
      .translate(-x(d0), 0));

This is why you can zoom in the margins and the chart works as intended, but doesn't work if you zoom over the rect that covers the plot area. Let's just apply the zoom once on one element:
  var rect = svg.append("rect")
    ...
    .call(zoom);

  rect.transition()
   .duration(1500)
   .call(zoom.transform, d3.zoomIdentity
      .scale(width / (x(d1) - x(d0)))
      .translate(-x(d0), 0));

Here's an updated plunkr
I've removed the script.js file as it duplicated script in the index.html file.
I had issues with your original plunkr in Firefox, I have not addressed those, I used Chrome to view


text:
Q: "Later" vs "later on." What's the difference between the two?

Later the doctors found out that my case was a bit different.
Later on the doctors found out that my case was a bit different.

Is one more common than the other?

A: *

*"Later" is definitely more formal than "Later on"

*According to me the "on" is just a filler to make the sentence smoother.
For Example- Many times we use "in order to", even though "to" is sufficient.

A: "Later on" is more informal than just plain "later."

A: "later" and "later on" have the same meaning.  Sometimes "later on" is preferred because it has another, smoother rhythmical flow. You can consider "later on" as just a variant for "later".


text:
Q: Websphere classloader delegation mode We are using WebSphere 6.1 application server with default classloader delegation mode i.e. PARENT-FIRST. We think about changing it to PARENT-LAST to be able to choose our jsf implementation or our webservices stack.
As PARENT-FIRST is the default I wonder how many people switched to PARENT-LAST, and what was the reason to switch, and if your life became better since you switched :)
We have a lot of applications in production so I cannot just switch to see what happens, if we do it we will have a lot of testing so I'd like to have to some feedback if you have switched to PARENT-LAST.
Thanks

A: On projects that I'm assigned to, we actually do switching to PARENT-LAST for most of our applications. The reason for that is usually an app-specific implementation of something, or a need for app-specific property bundle that Websphere uses too (overriding the Websphere setup of commons-logging, for example).
If something breaks after the switch, it is usually because of somewhat wrong setup of the application that suddently starts to be used (while before the switch it was overriden by Websphere's resources).

A: Portlet applications (deployed on WebSphere Portal Server) always switch their configuration to parent last.  In my experience it is always better to switch to parent last, especially if you are using commons logging.  This is because WebSphere includes a truck load of stuff in its own classloaders which are often a different versions/configurations to the one that you want to use.
If you are doing it, I would recommend that you script up the deployment of the application because it can be one of those things that are missed when you do a deployment.


text:
Q: I am having a TypeError: Cannot read property 'GoogleAuthProvider' of undefined?(React JS) Firebase? Error
I am having an error contantly in my react app.Actually I want to integrate firebase prebuilt-ui with firebase auth of google,facebook,etc.Although I have tried to run npm i command after deleting npm modules but still I am getting the error.This is the tutorial I am following on pre-built react js ui
https://www.youtube.com/watch?v=zq0TuNqV0Ew&t=1254s.
This the package.json file.
{
  "name": "olxclone",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.32",
    "@fortawesome/free-brands-svg-icons": "^5.15.1",
    "@fortawesome/free-regular-svg-icons": "^5.15.1",
    "@fortawesome/free-solid-svg-icons": "^5.15.1",
    "@fortawesome/react-fontawesome": "^0.1.11",
    "@material-ui/core": "^4.11.0",
    "bootstrap": "^4.5.3",
    "cra-template": "1.0.3",
    "firebase": "^6.0.0",
    "firebase-admin": "^9.3.0",
    "firebase-functions": "^3.11.0",
    "firebaseui": "^3.1.1",
    "react": "^16.13.1",
    "react-bootstrap": "^1.4.0",
    "react-dom": "^16.13.1",
    "react-firebaseui": "^3.1.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

and the error which is coming from source file.The code is
import React from 'react';

// Import FirebaseAuth and firebase.

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faQuestionCircle, faBook, faCamera, faMapMarkerAlt, faCoffee, faSearch, faSearchPlus, faUserCircle, faComment } from '@fortawesome/free-solid-svg-icons';
import { Link } from "react-router-dom"
import "../App.css";

import firebase from 'firebase/app';
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';

import { Button, Modal } from 'react-bootstrap'

firebase.initializeApp({
    apiKey: "1:717565114992:web:971b1dd5199c57b04812b5",
    authDomain: "fastsellat.firebaseapp.com"
  })

class Login extends React.Component {
    constructor() {
        super()
        this.state = {
            show: false,

        }
    }
    handleModal = () => {
        this.setState({
            show: true
        })
    }
    closeModal = () => {
        this.setState({
            show: false
        })
    }
    state = { isSignedIn: false }
    uiConfig = {
        signInFlow: "popup",
        signInOptions: [
          firebase.auth.GoogleAuthProvider.PROVIDER_ID,
          firebase.auth.FacebookAuthProvider.PROVIDER_ID,
          firebase.auth.GithubAuthProvider.PROVIDER_ID,
          firebase.auth.EmailAuthProvider.PROVIDER_ID
        ],
        callbacks: {
          signInSuccess: () => false
        }
      }

      componentDidMount = () => {
        firebase.auth().onAuthStateChanged(user => {
          this.setState({ isSignedIn: !!user })
          console.log("user", user)
        })
      }
    render() {
        return (

                <Button  variant="outline-primary" onClick={() => { this.handleModal() }}>
                    Login
                    </Button>

                <Modal show={this.state.show}>
                    <Modal.Header>

Help make OLX safer place to buy and sell

Contact and close deals faster

Save all your favourite items in one place

                                    Previous

                                    Next

                    </Modal.Header>
                    <Modal.Body>
                    {
                        this.state.isSignedIn ? (

Signed In!

                            <button onClick={() => firebase.auth().signOut()}>Sign out!</button>

Welcome {firebase.auth().currentUser.displayName}

                        ):(


text:
Q: Microservices and the "single point of failure" concept One concept I don't entirely understand is the single point of failure. It seems to me that whenever you have multiple services, say A, B and C, involved in an entire system, then if any of them is down the system as a whole can't do anything that useful (If the system could be useful without B, then why is B even needed in the first place?).
For example, let's say we have a pipeline such that A publishes an event that is consumed by B and then B publishes a message that is consumed by C and this flow of data is how the whole system serves its purpose.
A ===> B ===> C

Maybe C is the service that processes credit card information: the business isn't really running if no money is coming in!
Since this is a messaging system, these services are "independent" in the sense that if one goes down it does not cause another to go down. Ok, but if B goes down then C won't receive any new messages and the entire system isn't serving it's purpose. So, what difference does it make having separate services A, B and C rather than one service ABC?

A: Slightly modify the system and add redundancy.
[(A)(A)(A)] ===> [(B)(B)(B)] ===> [(C)(C)(C)]
Now even if one of the replicated services say (B) goes down the user story would get completed due to the availability of clone (B) nodes.
This system (in this scope) doesn't have a single point of failure.
Point to note, your design used messaging or essentially "loose coupled" it was very easy to modify the system and remove failure points.
There are other aspects of microservices which would need a detailed discussion. A prespective which helped me to understand the concepts in aligned to microservices is the Scale cube model.

A: I think your question is rhetorical. Obviously, if the system depends on all services, then any service is a single point of failure. If a single service goes down, the system won't be "serving it's purpose". Embracing Microservices won't automatically liberate you from the problem of single point of failure.
Most proponents of Microservices will tell you that you should design your system in such a way that the whole system should not depend on any one service. But, such a system just sounds like a unicorn to me. It's the same thing as saying "if you delete a chunk of your code, the app should keep working"
In reality, you can design a system where there is some utility left if any one service goes down. But, I doubt that there is any system that can function properly when one of its important components is missing. When a system does function properly without one of its components, the amount of extra error checking and so on that's required is horrendous.
But the thing is, that's not what Microservices are designed for. That's just one of the supposed benefits that people tout. The benefit only comes if you design your system to allow for the failure. But, you don't need to use Microservices to do that anyway.
Making occasionally connected clients can be another way to avoid single point of failure. Git is a good example. If GitHub goes down, you don't have people sitting around saying "oh, looks like I won't have to do any work today then".
Note: a load balancer can be thrown in front of any service so that the physical machine doesn't become the single point of failure.

A: Think of a service ('B') as a collection of parallel roads, or processing channels. Once these roads are built to a design (the code) they will sit there operating. The design doesn't change, so the processing doesn't change, and it does as you say. However, consider a road develops a non-design fault - a hardware failure. The road surface is physically un-passable. Traffic cannot flow, but luckily we have many parallel roads which can absorb this traffic! If we were to only have 1 (wide) road, the whole road has been shut for resurfacing so no traffic can flow.
You can take this further. Imagine traffic on your parallel roads is increasing and the roads are at capacity. It is easy to build another single lane road. This isn't much, but once it is built you can allow it to operate at maximum capacity. But the land rent costs money! So when traffic is reduced, we can easily decommission the small road and not pay rent on it.
You can take this even further - say you come up with a new road design, so you build it next to the existing roads. You can allow traffic onto this road and test how it operates. If there is an unknown error in your design, some traffic might get lost. But most of the traffic can go through your existing good roads. Now we can either change the design, or keep it and slowly change each small road into the new design.

A: Different parts of the service have different online-capacity needs.  Failure mode analysis is critical to really understand where you need to separate services and make them more resilient.  For example, perhaps C is not useful to separate if it isn't optional to the workflow for ordering, but because it is so important, it should get it's own additional resiliency (multiple fail-over workers on multiple hosts).
If, on the other hand, C were a fulfillment system (sending the pick-ticket to the warehouse), it wouldn't need that level of resiliency, and could afford to go down.  It's about deciding where your failure points are, and how much it's worth to prevent those failures.
In addition to failure modes, there are capacity issues to consider.  Credit-card processing may have completely different scaling needs than an inventory listing service.  Perhaps customers are asking prices on a VERY frequent basis, and as such, you may need to support much more capacity than for the credit-card processing service.  As such you need to build more scaling capacity for that part of your service.  Also, a failure in that service may be more acceptable than a failure in an actual order processing service (revenue is likely vs speculative).  Regardless, you need to understand the value of each of these services, and find ways to split them that allow you to scale their capacity and resiliency independently.

A: Service composition is one of the most difficult parts of microservices. Without reading a few books on this, here are a few guidelines. If you are looking for some of the benefits below, breaking out into an independent service might make sense:

*

*Re-use logic. In your example, if service C is also called by other services: D -> E -> C. If you suspect your logic could or should be consumed by other services, creating service C as independent means you can serve customers of that logic even when A and B are down.

*De-couple teams. If you are a small team, you probably don't want hundreds of services. But, write your logic so that you can separate it later. It's good to have a "microservice" mindset even if you don't break your logic into independent running services in the beginning.

*Ensure logic separation. It's easy to cheat when your code is in a monolith. If you really need to force yourself or your team to think about two things as "separate" so that you can re-use it, another service can force this.

*Optimize for execution patterns. If your system has to respond synchronously, do work asynchronously, deal with huge surges of inbound floods of work (from 0 rps to 10,000 rps in minutes) you may want to separate out services. A lightweight service that only takes a REST API call and queues it for actual work might be exactly what you need to handle inbound floods of work where you can afford to process or respond asynchronously. The lightweight service can spin up in milliseconds providing quick response to erratic demand. If you have a 12GB Java beast, scaling up could take a while.

I would also recommend that you choose your datastore wisely. A lot of time can be spent optimizing reliability of the coded services and the accompanying infrastructure, but you can still have a single-point-of-failure in your database architecture (or network or load balancer or dns or...)


text:
Q: Adding .Renvrion to github repo hiding from public If it is a duplicate I am sorry, however I've read lots of threads and
none of them worked and only a few of them were related to R.
I want to automate an R script using github actions. So doing that
I need to pass some keys, tokens and etc.
However I want to hide them from public while my repo is still public.
What I have done so far is:
git add -A(.gitignore does not include .Renviron)
git commit -m 'message'
git push
(Now this works, but my .Renviron still viewable)
git add .gitignore(add .Renviron in .gitignore, while .Renviron is in github repo)
git commit -m 'message'
git push
(Now this works, but .Renviron is still visible publicly)
Then
git rm .Renviron
git commit -m 'message'
git push
 (This time as you can imagine required environment objects cant be found.)
Any help appreciated. I feel somehow near to the solution but I do something wrong or miss
something


text:
Q: Upgrading to Magento 2.0.5 gives Class 'cms/block' not found I just upgraded to 2.0.5 and get the following error in apache log.

PHP Fatal error:  Class 'cms/block' not found in
  /vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on
  line 97

A: Looks like you have custom modules or themes or widget that refer to old M1 block name. Remove it and error will gone


text:
Q: Ajax freezes page after data loaded I am working on C9 IDE on a django project using the django server. I need to update three sections with Ajax request. Mostly this works OK, but sometimes (1 in 10) after the new data is visible (so, request successful) the site completely freezes (not even F5 works). Freez affects all sections not only those updated by request. Browser throws no error, I see the data, so nothing went wrong. But besides scrolling nothing responds. Refresh works only when re-entering the url.
Not sure what to show you, as there is no error, so I load jquery like this on top of home.html:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<html>

Ajax request looks like this:
function get_sid(go2url) {
var wait_sid = document.getElementById('wait_sid');
wait_sid.style.display = "initial";

//$('#sidebar').fadeTo(250,0.25);
$.ajaxSetup({
 beforeSend: function(xhr, settings) {
     function getCookie(name) {
         var cookieValue = null;
         if (document.cookie && document.cookie != '') {
             var cookies = document.cookie.split(';');
             for (var i = 0; i < cookies.length; i++) {
                 var cookie = jQuery.trim(cookies[i]);
                 // Does this cookie string begin with the name we want?
             if (cookie.substring(0, name.length + 1) == (name + '=')) {
                 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                 break;
             }
         }
     }
     return cookieValue;
     }
     if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
         // Only send the token to relative URLs i.e. locally.
         xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
     }
 }
});
var currentRequest = null;
currentRequest = $.ajax({
    type: "GET",
    url: go2url,
    data: {},
    async:  true,
    timeout: 15000,
    beforeSend : function()    {
        if(currentRequest != null) {
            currentRequest.abort();
        }
    },
    success: function(data){
        $('#sidebar').load(go2url);
        //$('#sidebar').fadeTo(350,1);
        wait_sid.style.display = "none";
    },

    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert('Loading seems to have encoutered an error. Please try

again.'+textStatus);wait_sid.style.display = "none";//$('#sidebar').fadeTo(350,1);

    }
});
}

At first I've been thinking the fade function is broken, but the issue persist after removing it. If request is sync or async does not change freez occurence. Timeout is not helping either (I hoped it would break whatever is freezing the browser, it does not). I am no expert in ajax or jquery, from what I read about this, in last three days, searching for a solution - everything is setuped OK. It should work perfectly, shouldn't it?


text:
Q: Getting all Users and their Custom Permissions tl;dr
Want to make a SOQL to return all Users and there (custom) permissions

Hi there
I've just started using SF, so bare with me if this is very basic.
One of the usages of salesforce we're trying to do is to manage the permissions and policies of what some departments can do in our internal BO (backoffice).
So I manage to find that we can do that by making the PermissionSet with CustomPermissions, and it is going forward kindly of ok. But now from our BO we need to query SF for users and their permissions.
So, for those who know SQL, this was kind of what I wanted to do:
SELECT
  User.Id,
  User.Email,
  User.Username,
  PermissionSet.Id,
  CustomPermission.*
FROM User
  JOIN PermissionSetAssignment
    ON PermissionSetAssignment.AssigneeId = User.Id
  JOIN PermissionSet
    ON PermissionSet.Id = PermissionSetAssignment.PermissionSetId
  JOIN CustomPermission
    ON CustomPermission ON CustomPermission.??? = PermissionSet.Id

But on SF they use SOQL, which already understood that it takes an object way of querying.
Already did a couple of tests, and Docs#StandardObjets helped to understand the properties of each object, but failed of explaining how do the objects interact and which alias they have when interacting. I mean from the POV of PermissionSetAssignments, users are called Assignee.
Where can I find these alias?
Where can I find the object relations map?
But going back to the topic, I've manage to go till here:
SELECT Id, Email,
  (SELECT
    PermissionSet.Id
    PermissionSet.Label
  FROM PermissionSetAssignments)
FROM User

Which I already have Users, PermissionSetAssignments and PermissionSet, I was able to find this by some examples and the PermissionSet diagram (end of the page)
But I'm completely lost in going from there to CustomPermissions.
Any idea?

edit
With the help of @adrian-larson so far I've manage to get the users, their permission sets, and the SetupEntityAccessItems SetupEntityId and ParentId, however I still miss the DeveloperName from CustomPermissions that would need to be attached to  SetupEntityAccess.
The @adrian-larson answer would be correct if I wanted to do a query (in that case 3) per each user.
The idea is to map the CustomPermissions DeveloperName into our application specific policy, so I intend to from time to time to fetch that Users > PermissionSet > CustomPermissions and update all users permissions on our application.
what I have so far:

*

*get all users and their permission sets
SELECT Id, Email,
  (
    SELECT PermissionSet.Id, PermissionSet.Label
    FROM PermissionSetAssignments
  )
FROM User

*get all setup entity access items that are custom and the parent id (permission set)
SELECT Label, Name,
(
  SELECT
    Parent.Name,
    SetupEntityId,
    SetupEntityType
  FROM SetupEntityAccessItems
  WHERE
    SetupEntityType = 'CustomPermission'
)
FROM PermissionSet

*[STILL MISSING] a way to map setup entity access to the custom permission name

edit
Solution found.
On the CustomPermission docs doesn't mention an ID, but noticed that @adrian-larson made a match through the ID, so with the simple:
    SELECT Id, DeveloperName
    FROM CustomPermission

It was possible to get the missing data part.
Ideally 1 query would be the best, but this will work also.
Thanks @adrian-larson

A: You can get Object, Field, and SetupEntity permissions with the query outlined below. It gets you a lot of information...
static List<PermissionSet> getPermissions(Id userId)
{
    return [
        SELECT Name,
            (
                SELECT
                    SObjectType,
                    Field,
                    PermissionsRead,
                    PermissionsEdit
                FROM FieldPerms
            ),
            (
                SELECT
                    SObjectType,
                    PermissionsRead,
                    PermissionsCreate,
                    PermissionsEdit,
                    PermissionsDelete,
                    PermissionsViewAllRecords,
                    PermissionsModifyAllRecords
                FROM ObjectPerms
            ),
            (
                SELECT SetupEntityId, SetupEntityType
                FROM SetupEntityAccessItems
            )
        FROM PermissionSet WHERE Id IN (
            SELECT PermissionSetId
            FROM PermissionSetAssignment
            WHERE AssigneeId = :userId
        )
    ];
}

If you just care about CustomPermission, you could do something like:
static List<CustomPermission> getCustomPermissions(Id userId)
{
    Set<Id> assigned = new Map<Id, PermissionSet>([
        SELECT Id FROM PermissionSet
        WHERE Id IN (
            SELECT PermissionSetId
            FROM PermissionSetAssignment
            WHERE AssigneeId = :userId
        )
    ]).keySet();
    return [
        SELECT DeveloperName FROM CustomPermission
        WHERE Id IN (
            SELECT SetupEntityId
            FROM SetupEntityAccess
            WHERE SetupEntityType = 'CustomPermission'
            AND ParentId IN :assigned
        )
    ];
}

Or for all users:
static List<CustomPermission> getCustomPermissions()
{
    return [
        SELECT DeveloperName FROM CustomPermission
        WHERE Id IN (
            SELECT SetupEntityId
            FROM SetupEntityAccess
            WHERE SetupEntityType = 'CustomPermission'
        )
    ];
}

A: I managed to do it using 1 API request:
/services/data/v46.0/query/?q=SELECT Id, ParentId, SetupEntityId FROM SetupEntityAccess WHERE SetupEntityId IN (SELECT Id FROM CustomPermission WHERE NamespacePrefix = '{{NAMESPACE_PREFIX}}') AND ParentId IN (SELECT PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = '{{USER_ID}}')


text:
Q: Typescript pattern - dealing with awaits that can be return void or empty I'm curious if there is a tidy pattern approach I can use for this common scenario:
I have a function that gets a price from making an api call:
let currentPrice = await getCurrentPrice(prodId)

This getCurrentPrice() function in the ideal case makes the api call as usual and returns a string. Promise<string>.
async function getCurrentPrice(pId: string): Promise<string> {
    axios({ .... })
    .then(res => return res.data.price)
    .catch(err => return "")
}

But in the error case I then need to write more logic at the point I made the call like if currentPrice === "".
This doesn't seem very tidy (mostly returning empty strings) hence wondering if there is a clearer pattern better used.
Thanks.


text:
Q: convergence of the integral of sin(nx) and a test function and I am trying to show that the integral $\int_{\mathbb{R}}\sin(nx)fdx$ converges to $0$ for any test function $f$ while $\int_{\mathbb{R}}\sin^2(nx)f(x)dx$ does not go to 0.
For the first function, the symmetry of the $\sin(nx)$ is what gets you the "0 integral" I presume. As $n\to \infty$ the integral on any region is 0 for a constant test function but apart from this. I am not sure what to do.
For the second one, choose a constant test function on it's support. Since $\sin(nx)^2$ is always non-negative, we can find some sort of lower bound for the integral so that we don't have convergence.


text:
Q: Oozie Setup does not work Yet another problem with Apache Bigtop. This time it is oozie.
Whenever I want to do something with Oozie, I get the following exception:
java.lang.IllegalArgumentException: Oozie URL is not available neither in command option or in the environment

I did some google-fuu and came across the tutorial officially provided by them.
But hurray, next problem:
Whenever I enter
bin/oozie-setup.sh -hadoop 2.6.0 $HADOOP_HOME -extjs ext-2.2.zip

I get the following reply:
  setting OOZIE_DATA=/var/lib/oozie
  setting OOZIE_CATALINA_HOME=/usr/lib/bigtop-tomcat
  setting CATALINA_TMPDIR=/var/lib/oozie
  setting CATALINA_PID=/var/run/oozie/oozie.pid
  setting CATALINA_BASE=/var/lib/oozie/tomcat-deployment
  setting CATALINA_OPTS="$CATALINA_OPTS -Xmx1024m"
  setting OOZIE_CONFIG=/etc/oozie/conf
  setting OOZIE_LOG=/var/log/oozie
  setting OOZIE_DATA=/var/lib/oozie
  setting OOZIE_CATALINA_HOME=/usr/lib/bigtop-tomcat
  setting CATALINA_TMPDIR=/var/lib/oozie
  setting CATALINA_PID=/var/run/oozie/oozie.pid
  setting CATALINA_BASE=/var/lib/oozie/tomcat-deployment
  setting CATALINA_OPTS="$CATALINA_OPTS -Xmx1024m"
  setting OOZIE_CONFIG=/etc/oozie/conf
  setting OOZIE_LOG=/var/log/oozie

 Usage  : oozie-setup.sh <Command and OPTIONS>
          prepare-war [-d directory] [-secure] (-d identifies an alternative directory for processing jars
                                                -secure will configure the war file to use HTTPS (SSL))
          sharelib create -fs FS_URI [-locallib SHARED_LIBRARY] (create sharelib for oozie,
                                                                FS_URI is the fs.default.name
                                                                for hdfs uri; SHARED_LIBRARY, path to the
                                                                Oozie sharelib to install, it can be a tarball
                                                                or an expanded version of it. If ommited,
                                                                the Oozie sharelib tarball from the Oozie
                                                                installation directory will be used)
                                                                (action failes if sharelib is already installed
                                                                in HDFS)
          sharelib upgrade -fs FS_URI [-locallib SHARED_LIBRARY] (upgrade existing sharelib, fails if there
                                                                  is no existing sharelib installed in HDFS)
          db create|upgrade|postupgrade -run [-sqlfile <FILE>] (create, upgrade or postupgrade oozie db with an
                                                                optional sql File)
          (without options prints this usage information)

 EXTJS can be downloaded from http://www.extjs.com/learn/Ext_Version_Archives

I have tried quiet a lot of things. I downloaded a version of ext-2.2.zip from an archive. I downloaded the version 2.3.0. But no matter what I do, the reply stays the same. Please help me get Oozie to run. I desperately need it right now!

A: Few thing you have to check 1st, as per the link you have shared that is to enable the Oozie UI which required ext-2.2 jar.
So if you already have Oozie setup done then you have to make the oozie.war file, including DB Driver and ext-2.2.zip file
to do so steps you need to perform is

*

*download ext-2.2.zip file from source and place the same in OOZIE_HOME/libext folder.

*download mysql/oracle/postgress driver and place the same in OOZIE_HOME/libext folder.

*start the oozie-setup.sh scriptr by executing
$ ./oozie-setup.sh
these will update the oozie.war file with supported ext-2.2.zip file and other jars which you have place in OOZIE_HOME/libext location.

*once the above is done, you can go to next step by creating Sharedlib manually by simply coping the uncompress sharedlib.tar.gz file available in OOZIE_HOME location to hdfs://localhost:54310/user/hduser/share/lib

*Create Oozie DB by executing
OOZIE_HOME/bin/./ooziedb.sh create -sqlfile oozie.sql -run
NOTE: here oozie.sql is a blank file which you need to mention it could be any name but extension should be .sql, also the DB details need to update in oozie-site.xml under OOZIE_HOME/conf/oozie-site.xml file; if you have not set any DB configuration details the Oozie will Use defualt DB which is DERBY,

*Finally if all above points have been setup you can start oozie by
$OOZIE_HOME/./bin/oozied.sh start
and hit the oozie url and check the status.
Referecnce URL: Rohit Menon has mention some of the steps which can be done simply.

A: My Oozie binary (version 5.0.0) is in /home/hduser/oozie/oozie-5.0.0.
About the war file, the tutorial I've followed (https://acadgild.com/blog/beginners-guide-for-oozie-installation) gives this indication :
"Now after setting up the things, move into the bin folder of newly obtained oozie-4.1.0 in the path $HOME/oozie/oozie-4.1.0/" (for me is $HOME/oozie/oozie-5.0.0).
"Now prepare a war file by using the below command : sudo ./oozie-setup.sh prepare-war "
but, for my installation this command doesn't worked, because oozie-setup.sh give me the help indication about the usage :

My solution was simply to go one level up from the /bin directory and give this command : hduser@:~/oozie/oozie-5.0.0$ bin/oozie-setup.sh (without the string "prepare-war"). This worked for me.


text:
Q: LuaTeX: Wrong/missing italic correction in TeXLive 2015 vs 2014 Italic correction for OTF math fonts seems to be broken in LuaTeX in TL15.
MWE:
\documentclass{article}
\usepackage{unicode-math}
\setmathfont{Latin Modern Math}
\begin{document}
\begin{equation}
  V^* \quad T^6 \quad T) \quad VT
\end{equation}
\end{document}

Compiling with TL14 gives

and TL15:

There is no problem for upright letters (\mathup{T}).
Using the .otf font from 2014 with TL15 produced the same result as with the 2015 font.
I can remember having similar problems with TL11/12.
So the question is: what caused this change and how can I fix it?

A: The problem has a long history. It was brought up in 2011, as far as I know, with a message to the TeX Live mailing list; the thread went on also in the LuaTeX list.
The problem is that LuaTeX doesn't add the italic correction in math mode after characters having category code 11. Indeed, in TeX Live 2011, the output from your code would be the same as you get now.
See How can I enable italic correction for LuaTeX? for finding a workaround that applies also to the present version of LuaLaTeX:
\documentclass{article}

\usepackage{unicode-math}
\setmathfont{Latin Modern Math}
%\setmathfont{TeX Gyre Termes Math}

\everymath\expandafter{\the\everymath\luatexcatcodetable\CatcodeTableLaTeX}
\everydisplay\expandafter{\the\everydisplay\luatexcatcodetable\CatcodeTableLaTeX}

\begin{document}

\begin{equation}
  V^* \quad T^6 \quad T) \quad VT
\end{equation}
\end{document}

The problem was circumvented by changing the default category codes for math letters to 12. However, as suggested by Ulrike Fischer, the new release of LaTeX (2015/01/01) has changed back the category codes to 11 for every character that qualifies as a letter and so the problem has reappeared.
Quoting Joseph Wright in chat

That's a bit of a problem: we are for a start looking at fixing \CatcodeTableLaTeX so it has the right catcodes

so the workaround is not guaranteed to be valid in the future (but I hope some better remedy will be found in the meantime).


text:
Q: NSOperation and SetImage I need to use a thread in order to retrieve an image from the web and assign it into an image view.
I have subclassed NSOperation and called it from my view controller like:
NSOperation *operation = [[[GetImage alloc] init] autorelease];

[queue addOperation:operation];

I get the image fine but how do I go about assigning that image that is in my NSOperation class? I have the image stored in a UIImage called RetrievedImage:
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];

retrievedImage = [[UIImage alloc] initWithData:imageData];

[imageData release];

How do I now get that into the ImageView of my ViewController?
Thanks

A: you use delegation.
Your NSOperation:
- (void)main {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://sstatic.net/stackoverflow/img/apple-touch-icon.png"]];
    UIImage *image = [UIImage imageWithData:data];
    [delegate fetchedImage:image];
    [pool drain];
}

your delegate:
- (void)fetchedImage:(UIImage *)image {
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:_cmd withObject:image waitUntilDone:NO];
        return;
    }
    self.imageView.image = image;
}

the important part is the part where you check if you are running on the main thread.
You can't access interface elements from another thread. So if you aren't on main thread, you start the same method on the main thread

A: You have a few options here:

*

*You could hand a reference to your imageview to the GetImage operation, and assign to imageview.image when the operation gets the image.

*You could subclass UIImageView and have it listen to a notification, say GetImageFinishedNotification- the operation posts this notification with the image attached when it finishes, and the imageview receives it and displays the image.

*You could set up a model object that has a UIImage property. Your viewcontroller retains on this object and sets up Key-Value observing on its image property. The operation also retains on it and sets the image property when it gets the image. The viewcontroller is alerted to the change and sets the right imageview.

I personally prefer NSNotification for this sort of thing- it's actually pretty similar to foursquare's fully-loaded project.

A: Try using HJCache, its made for this kind of thing:
http://www.markj.net/hjcache-iphone-image-cache/

A: The ImageView has an image property, try accessing this.


text:
Q: Ubuntu Desktop shifted to right I am using Ubuntu 12.04 (precise) Kernel : 3.5.0-18-generic
I am encountering a strange problem, my whole desktop has shifted to right. This happened after I restored my system, I was getting a blank screen earlier.(something is better than nothing).
For some reason it also shows my display as laptop.
Running xrandr

xrandr: Failed to get size of gamma for
output default Screen 0: minimum 640 x 480, current 1024 x 768,
maximum 1024 x 768 default connected 1024x768+0+0 0mm x 0mm
1024x768        0.0*     800x600         0.0      640x480         0.0

Running lspci

lspci -nn | grep VGA
00:02.0 VGA compatible controller [0300]: Intel Corporation 2nd
Generation Core Processor Family Integrated Graphics Controller
[8086:0102] (rev 09)
My Display on window supports maximum of 1366*768.
I do not want to reinstall everything please help.

It is  cycled around as mentioned by  Eliah Kagan
For correcting my blank screen issue I edited my grub file I edited this line and added nomodeset, without it screen gets all grained up.

GRUB_CMDLINE_LINUX_DEFAULT="quiet splash nomodeset "

When I boot from live CD also I get the same shifted screen
Update 2
Tried booting from live CD with 11.04 same issue
Update 3
.xsession-errors file : http://pastebin.com/uveSgNa8
Update 4

xrandr -q | grep -w connected
xrandr: Failed to get size of gamma for output default
default connected 1024x768+0+0 0mm x 0mm

A: Did you try pressing "Auto Set" button on your monitor??
I once experienced the same problem.
But i got it solved just by pressing "Auto" button on my monitor...

A: The problem is resolved I was searching for why I was getting

Failed to get size of gamma for output default Screen

on running xrandr. I came across this post
http://ubuntuforums.org/showthread.php?t=1594308&page=2#16
and followed the steps mentioned there

The correct solution would be to set up an xorg.conf file with your
  resolution;could be done by Xorg -configure (little pain,because it
  includes the whole bunch of possible configuration options);so it
  might be worth to try an existing xorg.conf file from the web. Found
  this xorg.conf e.g. :

This was an interesting issue My desktop is normal now thanks to all who helped out.

A: Was your problem solved? If not...
I see from your xsession-errors that the issue is in the EDID file from your monitor:
"unable to get EDID for output"
FIRST SHOT
I had that when I tried to connect an external monitor from its VGA in to the HDMI port of my laptop using a VGA-to-HDMI conversor. It caused the problem.
Then I switched to the DVI-D in of the external monitor and used a DVI-to-HDMI conversor. That solved my problem with the EDID thing. Maybe because the both signals were digital now... I don't know.
After that I had to do some tweaking on the screen's resolution (Ubuntu 12.04) as shown here.
SECOND SHOT
Try deleting the /home/$USERNAME/.config/monitors.xml file.
Type:
$ rm ~/.config/monitors.xml

That's a long guess for your problem, but who knows. Don't worry, this file is rebuild every time you save your Display Preferences.
THIRD SHOT
Type:
$ xrandr -q | grep -w connected

It shows which display is in use (e.g. LVDS1 or VGA1).
Then you can type:
$ xrandr --output LVDS1 --primary --auto

Note that you should change "LVDS1" to the according display in use.
Hope it works!

A: Installing a proprietary video card driver might help by allowing you to move the area of the screen. At least the nvidia x-server settings app would allow you to do that if you have an nvidia card. Not sure about the AMD catalyst, though.

A: Do you have higher resolution settings available? If so try and set it to the highest settings you have... ↓

A: I have a NVIDIA card and I went into the DASH> NVIDIA X Server Settings > X Server Display Configuration.
Then I set the default video input 1920x1080 (for me) and change the ViewPortOut to 1768x992+80+40. That lets me have my resolution but not screw anything up, when my Ubuntu bugged out to scroll the desktop when I moused to the bottom or the right of my screen this had changed and was my problem.
Sorry if it doesn't appy.
///EDIT: Sorry to modify this value click the "Advanced" Button on the bottom

A: Check the vbios of your computer by restarting and entering bios. Check video display and reset, adjust.
Printout the vbios if you have questions.
Did you say you tried to adjust the screen in in the front controlls?


text:
Q: What is Scan-Move? From wikia:

Scan-Move is a command available to units without an attack, such as
  high templar and the medivac dropship. The hotkey used is A, the same
  as the attack command. Using scan-move "orders selected units to move
  to the target area or follow the target unit. Scan-Moving units will
  not engage enemies."

I don't understand this description. What's the difference between scan-move and normal move? If I scan-move a high templar ... what will he do when he runs into enemies?
Also, now that I think of it - assume I have a group of units selected, where some have an attack and some don't (e.g. Zealots and High Templars). What actually happens when I hit A-click, and they run into some enemies?

A: The tooltip for Scan Move:

Orders selected units to move to the target area or follow the target unit. Scan-moving units will not engage enemies.

Scan-move allows the use of auto-cast abilities. If using a regular move command, the unit will not use auto-cast abilities.
Also note that the default hotkey for both scan-move and attack is "A". If you have a regular unit with an attack, and a unit with scan-move as orders, and you group them together and use the hotkey "A", the game will try to execute the attack first. If that order is successful given, the scan-move is then executed.
E.g. If you have a marauder and medivac in one group, and you use the "a" hotkey and left click on a zealot
the marauderwill attack the zealot, and the medivac will scan-move to the zealot. If the zealot moves away, the medivac will follow it.
E.g. If you have a marauder and medivac in one group, and you use the "a" hotkey and left click on a mutalisk (remember marauders cannot attack air units), the game will display the error "Must target ground units", and the medivac will not scan-move to the mutalisk.
Here is a list of units, from melee maps, with Scan Move as an ability:

*

*Warp Prism

*High Templar

*Infestor

*Overlord

*Raven

*Medivac (only this unit has an auto-cast ability)


text:
Q: How can I express the Riemann tensor of the 4-metric in terms of quantities derived from the 3-metric and the normal to it? I want an expression for the Riemann tensor of the four metric in terms of extrinsic curvature, normal, lie derivative of the normal, etc.
The first Einstein-Codacci eq. gives the Riemann tensor of the three metric in terms of the contracted Riemann four tensor and the extrinsic curvature. So this is not the one I want.
Does anyone know a relation that I am looking for? And how to derive it?

A: See this reference
The formula is on Page 11 (Codazzi Equation) (The definition of the metrics $\gamma$ is on page 7).


text:
Q: autocomplete and remove default value I want to do 2 things as soon as the input-box gets focus:

*

*autocomplete (default dropdown)

*remove the default-value as
$(".keywordbox > input").autocomplete({"source":"/nl/video/show-keywords/3", "maxLength" : "10" });
$(".keywordbox > input").focus(function() {
    if ($(this).val() == $(this).prop("defaultValue")) {
        $(this).val('');
    }
    $(this).trigger('keydown.autocomplete');
});

The autocomplete on focus works fine, except when it is combined with
 $(this).val('');

Anyone suggestions to make this work?
** EDIT **
Seems that autocomplete does not work because the input is empty. Even when there is no placeholder-value set.
What I want is that de autocomplete sets of without giving a value, so that all options (without filtering) can be given.

A: Try to change like
$(".keywordbox > input").focus(function() {

to
$(".keywordbox > input").keydown(function() {

but it is optinal and for your question try like
if ($(this).val() == $(this).prop("defaultValue")) {
    $(this).val('');
    return false;
}

and better than to put default value add placeholder like
<input placeholder="default value">

SIMPLY GIVE LIKE THIS
$(".keywordbox > input").focus(function() {
    $(this).trigger('keydown.autocomplete');
});

A: The solutions is simple ... adding the following code
"minLength": "0"

Then it becomes
$(".keywordbox > input").autocomplete(
     {
     "source":"/nl/video/show-keywords/3",
     "maxLength" : "10",
     "minLength": "0"
 });


text:
Q: MKMapView not filling view (iOS) I am creating a view programmatically. The view is fairly simple as it only contains an MKMapView which I want to fill the screen (with the exception of the navigation bar at the top).
Here is what I am doing to setup the MKMapView:
- (void)setupMapView
{
    mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
    mapView.delegate = self;
    mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

    [self.view addSubview:mapView];
}

However, the MKMapView doesn't seem to fill the entire screen. If you look at the top of this screenshot there is a gap between the top of the map and the bottom of the navigation bar (which is added by the UINavigationController).

Please could someone suggest why this is happening and how I can fix it?

A: The frame of the view (self.view.frame) probably have an offset in the y position. This is to position it correctly in its superviews coordinate space. When you copy that frame onto your new view it is inappropriate because you are moving into a different coordinate space.
A cheap alternative that will work in 99.9% or cases is to use the view bounds instead:
mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];

Because this usually has an origin of zero and the full size of the view.


text:
Q: ¿Cómo puedo crear mi propia librería de interfaz gráfica sin necesidad de usar otras librerías de interfaz gráfica? Sé que esta pregunta tendrá un voto negativo, pero es que tengo es que he querido saber como se puede crear mi propia librería de interfaz gráfica.

A: Pues lo primero que tienes que hacer es estudiarte la API del sistema operativo (Windows) o la librería de escritorio (KDE, Gnome, ...) si estás en Linux.
Esto es imprescindible ya que tu librería no obrará magia, sino que tendrá que comunicarse con otras librerías más básicas para proveer la interfaz gráfica.
Dicho de otra forma: El Sistema Operativo será el que te avise ante los eventos que se produzcan (clicks del ratón, pulsación de teclas, ...) así como el que te provee los recursos que necesitas (el acceso al dispositivo de la pantalla).
Así, en Windows, que en temas de programación es más bien monolítico, te encontraás con la WinAPI, que te va a dar soporte para las operaciones más básicas:

*

*Crear una región en la pantalla que tendrá un comportamiento personalizado

*Controlar el movimiento del ratón

*Acceso a eventos de teclado

*...

En Linux la cosa cambia debido a la filosofía reinante en este otro Sistema Operativo. Aquí tienes diferentes capas gráficas y será esta capa gráfica la que te va a proveer la funcionalidad básica para que tu puedas desplegar tu propia interfaz gráfica.
En el fondo, las librerías gráficas que puedes encontrar hoy no son más que utilidades que, haciendo uso de estas funciones que te digo, proporcionan un mecanismo más cómo de cara a crear entornos gráficos para las aplicaciones.


text:
Q: How does Flask-login with multiple servers work I have been using Flask login module, which creates and maintains session on the server.
Since server maintains the session, I think it is not completely stateless. How does it work when application has more than one server. Should requests be sticky (i.e. given session should make subsequent requests to a particular server)?

A: This statement you've made is not completely correct:

... which creates and maintains session on the server.

Flask-Login uses the session facilities provided by Flask, so the data it stores in the session will be written by Flask using the configured session storage mechanism.
By default Flask writes user sessions as secure cookies in the client, but session on the server are also possible. For example, this snippet shows how to configure Flask to write sessions on a server-side Redis store.
When the user session is stored in a client side cookie it is pretty obvious that having multiple servers is not a problem. The cookie will be sent to the server handling each request, so everything will work just fine.
For server-side sessions this works as well. A server-side session is written under a unique identifier, and this unique identifier is then stored in a client side cookie. Each request then comes with the session ID, and Flask uses this ID to load the session data. If you configure all your web servers to use the same user session storage then multiple servers can handle requests from the same client without issue.


text:
Q: Modelica Reduction Method Pantelides error in electrical due to missing ground I'm posting this for anyone who runs into the same problem in the future.  I was running into a problem running the following simple electrical model:

It produces the following error:
[1] 16:14:41 Translation Error
Internal error Circular Equalities Detected for Variables:
----------------------------------

[2] 16:14:41 Translation Error
Internal error IndexReduction.pantelidesIndexReduction failed! Found empty set of continuous equations. Use -d=bltdump to get more information.

[3] 16:14:41 Translation Error
Internal error Transformation Module PFPlusExt index Reduction Method Pantelides failed!

A: Modelica references everything internally to ground, which is not defined here.  Every isolated electrical network will need to be referenced to ground.  To correct this problem I added a ground connection as follows:


text:
Q: Please tell me how many characters I have left in the comment flagging dialog Flagging comments, I ran into this:

I'd pasted-in a reasonable reason, but the Flag Comment button was disabled!  And, the dialog/UI didn't provide a clue as to why!
Eventually, I found this brilliant request for a reasonable number of characters for the field. (2047 characters would be a fine choice. (^_^) )

Meanwhile, there is an easy, immediate, UI fix... Merely add a single bit of static text to the dialog, like so:

IMPORTANT!
The comments shown are not the final comments I flagged with (obviously, since they were being rejected).  People commenting that those comments could have been condensed (after minutes of hindsight) are missing the bulk of the point of this question.
That is: that the UI should indicate why an input is being rejected.
I won't rehash the length argument anymore, since most people have already resoundingly supported that notion here.

A: Yes, that makes sense. It will be implemented in the next build.

A: I agree with the character counter, but not with the length of the flag comment (2047 character) you proposed in your original edit of this question.
I handle 100+ moderator flags daily.  Do you really expect me to read that much text on a single comment flag?  You need to keep the description brief.
In your example, all you have to do is flag both comments as obsolete.  I can figure the rest out.

A:
Identical comments, and in addition, they have been reposted as an answer by the OP (which is what they should be)

That's less "figur[ing] the rest out" for the moderator, with custom text, while still staying far underneath the limit. It's fairly easy, by the way, to figure out that two comments are identical.
The point I'm trying to make, by the way, is not that this specific comment can be reduced. It's that all comment flags that take up anywhere close to that amount of space are far, far too long.

A: Tackling the OP's central argument that the flagging dialog could be improved by giving the user feedback as to why the button is inactive, and ignoring for a second the sub-argument triggered by his verbose example flag, I agree with the OP.
Whether the comment field is 2 characters wide or 2000 characters wide, making the limit easily visible and intuitively-understandable is good UI design. There's nothing worse when filling in a form than exceeding a limit and not realising until you've finished typing.
We should either display the character limit, or prevent the flagger from being able to type more characters than are permitted.
(As an aside, my opinion is that the current limit is more than enough.)


text:
Q: Number of times all the numbers in an array are divisible by 2 I am trying to get the count of number of times all the integers in an array is divisible by 2 considering only one integer in each step.
For example, initially if I have the array : [2,4,2] and count = 0

Step 1

[1,4,2] , count=1

Step 2

[1,2,2] , count=2

Step 3

[1,1,2] , count=3

Step 4

[1,1,1] , count=4

My approach to the problem is given below :
Code
public static void main(String[] args) {
     int[] ar={2,4,2};
     int[] p=new int[ar.length];
     int count=0;
     for (int i=0;i<ar.length ;i++ ) {
        if(ar[i]>=1){
            ar[i]=ar[i]/2;
            count++;
        }
     }
     for (int x:ar) {
        System.out.println(x);
     }
     System.out.println("Count:"+count);

}

Output

1
2
1
Count:3

The problem in the code given above is that the array is scanned only one time and I want to scan the array until all the integers are no more divisible by 2

A: Note that you have two issues:

*

*You divide each element of the array by 2 at most one time.

*You divide elements of the array by 2 without checking first whether or not they are divisible by 2.

You need an inner loop that would divide each array element as long as it is divisible by 2:
public static void main(String[] args) {
     int[] ar={2,4,2};
     int[] p=new int[ar.length];
     int count=0;
     for (int i=0;i<ar.length ;i++ ) {
        while (ar[i] % 2 == 0 && ar[i] > 0) { // keep dividing ar[i] by 2 as long as
                                              // it is divisible by 2
            ar[i]=ar[i]/2;
            count++;
        }
     }
     for (int x:ar) {
        System.out.println(x);
     }
     System.out.println("Count:"+count);
}

A:      for (int i=0;i<ar.length ;i++ ) {
        while(ar[i]%2==0 && ar[i]>1){
            ar[i]=ar[i]/2;
            count++;
        }
     }

This will suffice.


text:
Q: Building a web-based iphone/ipad simulator/emulator I am tempted to ask you, what would it entail to build a web based iphone/ipad simulator/emulator that actually represents the way iphones and ipads display pages accurately?
It would require the webkit mobile engine, yes of course, or a copy of it - though that can get dead exhausting to replicate, if even possible.
So this brings me to the core of my question. Is it possible from a programming standpoint to 'port' the webkit mobile engine to a web-based environment/website so that users from all over the world, regardless of the browser they're using, can witness/experience/see the rendering of pages through the eyes of an iphone/ipad with the proper webkit mobile engine?
Cheers
G.Campos

A: I'm not sure, but maybe http://www.pieceable.com/viewer is what you want. It's a wev-viewer which allows you to see your iphone app in browser. For example http://three20.info/ uses it to demonstrate possibilities.

A: After non-stop searching and asking around, I was unable to find evidence that this would be easy let alone possible to implement. I guess this explains why it hasn't been done before.
bummer =(


text:
Q: celery flask PicklingError, attribute lookup  on flask_security.core failed I am using celery in flask to periodically execute task, and using demo from the doc, the debug message says sending task but I didn't see the output printed.
The broker I am using is redis, and I am using the method in the doc to create celery.
My manage.py file
import ...

app = create_app()
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
celery = make_celery(app)

@celery.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    # Calls test('hello') every 10 seconds.
    sender.add_periodic_task(10.0, test.s('hello'), name='add every 10')

    # Calls test('world') every 30 seconds
    sender.add_periodic_task(30.0, test.s('world'), expires=10)

    # Executes every Monday morning at 7:30 a.m.
    sender.add_periodic_task(
        crontab(hour=7, minute=30, day_of_week=1),
        test.s('Happy Mondays!'),
    )

@celery.task
def test(arg):
    print(arg)

And the function make_celery
def make_celery(app):
    celery = Celery(
        app.import_name,
        backend=app.config['CELERY_RESULT_BACKEND'],
        broker=app.config['CELERY_BROKER_URL']
    )
    celery.conf.update(app.config)

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask

    return celery

And I use this command to start celery beat
celery -A manage.celery beat --loglevel=DEBUG

create app function
def create_app():
    from apps.models import db
    from admin import admin, security, user_datastore

    app = Flask(__name__, static_folder=settings.ProductSetting.STATIC_FOLDER)
    app.register_blueprint(blueprint)
    app.config.from_object(settings.ProductSetting)
    db.init_app(app)
    ckeditor = CKEditor(app)
    security_ctx = security.init_app(app, user_datastore)
    login_manager = LoginManager(app)

    @login_manager.user_loader
    def load_user(user_id):
        return db.session.query(User).get(user_id)

    # define a context processor for merging flask-admin's template context into the
    # flask-security views.
    @security_ctx.context_processor
    def security_context_processor():
        return dict(
            admin_base_template=admin.base_template,
            admin_view=admin.index_view,
            h=admin_helpers,
            get_url=url_for
        )

    admin.init_app(app)

    def my_access_control_function():
        """
        :return: True if the user is allowed to access the filemanager, otherwise False
        """
        # You can do whatever permission check you need here
        if not current_user.is_active or not current_user.is_authenticated:
            return False

        if current_user.has_role('superuser'):
            return True

        return False

    flaskfilemanager.init(app, access_control_function=my_access_control_function)
    return app

The output:
Configuration ->
    . broker -> redis://localhost:6379/0
    . loader -> celery.loaders.app.AppLoader
    . scheduler -> celery.beat.PersistentScheduler
    . db -> celerybeat-schedule
    . logfile -> [stderr]@%DEBUG
    . maxinterval -> 5.00 minutes (300s)
[2019-02-12 11:27:41,800: DEBUG/MainProcess] Setting default socket timeout to 30
[2019-02-12 11:27:41,801: INFO/MainProcess] beat: Starting...
[2019-02-12 11:27:41,818: DEBUG/MainProcess] Current schedule:
<ScheduleEntry: manage.test('world') manage.test('world') <freq: 30.00 seconds>
<ScheduleEntry: add every 10 manage.test('hello') <freq: 10.00 seconds>
<ScheduleEntry: manage.test('Happy Mondays!') manage.test('Happy Mondays!') <crontab: 30 7 1 * * (m/h/d/dM/M
Y)>
[2019-02-12 11:27:41,818: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes
[2019-02-12 11:27:42,842: INFO/MainProcess] Scheduler: Sending due task add every 10 (manage.test)
[2019-02-12 11:27:44,900: DEBUG/MainProcess] beat: Synchronizing schedule...
[2019-02-12 11:27:44,911: DEBUG/MainProcess] manage.test sent. id->acc7f805-d8d5-4ae3-af35-1b5da1798749
[2019-02-12 11:27:44,912: DEBUG/MainProcess] beat: Waking up in 8.33 seconds.
[2019-02-12 11:27:53,256: INFO/MainProcess] Scheduler: Sending due task manage.test('world') (manage.test)
[2019-02-12 11:27:53,257: DEBUG/MainProcess] manage.test sent. id->1c691bd7-0ba1-4215-8c56-fbc59d5ca775
[2019-02-12 11:27:53,257: INFO/MainProcess] Scheduler: Sending due task add every 10 (manage.test)
[2019-02-12 11:27:53,258: DEBUG/MainProcess] manage.test sent. id->709fe5fd-83c8-4fca-a8e0-0c1ca8d25e84
[2019-02-12 11:27:53,258: DEBUG/MainProcess] beat: Waking up in 9.99 seconds.

out put after start worker
command
celery -A manage.celery worker -l info

- ** ---------- [config]
- ** ---------- .> app:         apps:0x27466765c88
- ** ---------- .> transport:   redis://localhost:6379/0
- ** ---------- .> results:     redis://localhost:6379/0
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]
  . manage.test

[2019-02-12 15:05:13,190: CRITICAL/MainProcess] Unrecoverable error: PicklingError("Can't pickle <function <
lambda> at 0x000002687E93EA60>: attribute lookup <lambda> on flask_security.core failed",)
Traceback (most recent call last):
  File "e:\env\games\lib\site-packages\celery\worker\worker.py", line 205, in start
    self.blueprint.start(self)
  File "e:\env\games\lib\site-packages\celery\bootsteps.py", line 119, in start
    step.start(parent)
  File "e:\env\games\lib\site-packages\celery\bootsteps.py", line 369, in start
    return self.obj.start()
  File "e:\env\games\lib\site-packages\celery\concurrency\base.py", line 131, in start
    self.on_start()
  File "e:\env\games\lib\site-packages\celery\concurrency\prefork.py", line 112, in on_start
    **self.options)
  File "e:\env\games\lib\site-packages\billiard\pool.py", line 1007, in __init__
    self._create_worker_process(i)
  File "e:\env\games\lib\site-packages\billiard\pool.py", line 1116, in _create_worker_process
    w.start()
  File "e:\env\games\lib\site-packages\billiard\process.py", line 124, in start
    self._popen = self._Popen(self)
  File "e:\env\games\lib\site-packages\billiard\context.py", line 383, in _Popen
    return Popen(process_obj)
  File "e:\env\games\lib\site-packages\billiard\popen_spawn_win32.py", line 79, in __init__
    reduction.dump(process_obj, to_child)
  File "e:\env\games\lib\site-packages\billiard\reduction.py", line 99, in dump
    ForkingPickler(file, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function <lambda> at 0x000002687E93EA60>: attribute lookup <lambda> on
flask_security.core failed

A: The issue is that the line:
celery.conf.update(app.config)

will take ALL flask (including flask-security) configurations and add them to celery config.
In flask-security some config variables are actually lambda's (as well as some localProxies). Those won't pickle of course - and some actually depend on being in a context. Why do you need all of these?


text:
Q: How to insert multiple rows of student records scores in a while loop in a database table? I want to create a table with input fields where student records can be inserted. The name of the students are in the first column of the table fetched from the database with a while loop. The other columns contain fields for inputing the student scores. The challenge I'm facing is how to insert the records of all the students in different row of a table called result_sec into the database. I've search for similar post but couldn't get a suitable answer. Below is the code. Thanks in advance.
<?php require('header.php'); ?>
<?php
$query_form = sprintf("SELECT * FROM regform LIMIT 2");
$form = mysqli_query($conn, $query_form) or die(mysqli_error($conn));
$formdata = mysqli_fetch_assoc($form);

if(isset($_POST['submit']))
{
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];

    foreach($exes as $key => $exe)
    {
            $sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam) VALUES ('$exe', '$asss[$key]', '$ca1s[$key]', '$ca2s[$key]', '$exams[$key]')";
    }
    $insert = mysqli_multi_query($conn, $sql);
}
?>
<form method="POST">

        Name
        Ass.
        Exe.
        1st C.A.
        2nd C.A.
        Exam

     <?php do { ?>

          <?php echo $formdata['surname']." ".$formdata['firstname']; ?>
          <input name="ass[]" size="1px"/>
          <input name="exe[]" size="1px" />
          <input name="ca1[]" size="1px" />
          <input name="ca2[]" size="1px" />
          <input name="exam[]" size="1px" />
          <input type="hidden" name="regformid[]" value="<?php echo $formdata['regformid'];?>" />

     <?php } while ($formdata = mysqli_fetch_assoc($form)); ?>

    <button type="submit">Insert Student Record</button>
    </form>
<?php require('footer.php'); ?>

A: See If this resolve your problem
if(isset($_POST['submit'])){
    $exes = $_POST['exe'];
    $asss = $_POST['ass'];
    $ca1s = $_POST['ca1'];
    $ca2s = $_POST['ca2'];
    $exams = $_POST['exam'];

    //You can use a foreach loop to loop over one of the repeated inputs, and then use the index to access the corresponding elements in the others:
    foreach ($exes as $i => $exe) {
        $exee = mysqli_real_escape_string($exe);
        $ass = mysqli_real_escape_string($asss[$i]);
        $ca1 = mysqli_real_escape_string($ca1s[$i]);
        $ca2 = mysqli_real_escape_string($ca2s[$i]);
        $exam = mysqli_real_escape_string($exams[$i]);

            $sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam)
            VALUES ('$exee', '$ass', '$ca1', '$ca2', '$exam')";
            $insert = mysqli_multi_query($conn, $sql);
    }
}


text:
Q: Storing Login Credentials for Command Line App I am writing a command line app in python using the click module that will SSH to Cisco network device and send configuration commands over the connection using the netmiko module. The problem I'm running into is that SSH-ing to the network device requires a hostname/IP, username, and password. I am trying to implement a way for a user of my script to login to a device once and keep the SSH connection open, allowing subcommands to be run without logging in each time. For example,
$ myapp ssh
hostname/IP: 10.10.110.10
username: user
password: ********

Connected to device 10.10.101.10

$ myapp command1
log output

$ myapp --option command2
log output

$ myapp disconnect
closing connection to 10.10.101.10

How would I go about storing/handling credentials to allow this functionality in my cli? I have seen recommendations of caching or OAuth in researching this issue, but I'm still not sure how to implement this or what the recommended and safe way to do this is.

A: Perhaps you are attempting something like this.
$ myapp ssh -u user -p password
(myapp) command1
(myapp) command2
(myapp) disconnect
$

Python has a standard library module cmd that may help:
https://docs.python.org/3.5/library/cmd.html


text:
Q: superclass mismatch for class HTTP on mac os X I'm having some troubles installing my Ruby on Rails environment on my Mac, I'm trying with this versions:

*

*ruby 1.8.7 (2011-06-30 patchlevel 352) [i686-darwin10.7.1]

*gem 1.8.6

*Snow Leopard 10.6.8
I think that XCode by default installs some ruby libraries that are in conflict with some of my gems. To install ruby I have used "rvm install 1.8.7"
This is the error's stack trace:
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/http.rb:278
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:596:in `new_constants_in'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/net/https.rb:101
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:596:in `new_constants_in'
activesupport (3.0.3) lib/active_support/dependencies.rb:225:in `load_dependency'
activesupport (3.0.3) lib/active_support/dependencies.rb:239:in `require'
activesupport (3.0.3) lib/active_support/dependencies.rb:454:in `load'
activesupport (3.0.3) lib/active_support/dependencies.rb:454:in `load_file'
activesupport (3.0.3) lib/active_support/dependencies.rb:596:in `new_constants_in'
activesupport (3.0.3) lib/active_support/dependencies.rb:453:in `load_file'
activesupport (3.0.3) lib/active_support/dependencies.rb:340:in `require_or_load'
activesupport (3.0.3) lib/active_support/dependencies.rb:491:in `load_missing_constant'
activesupport (3.0.3) lib/active_support/dependencies.rb:183:in `const_missing'
activesupport (3.0.3) lib/active_support/dependencies.rb:181:in `each'
activesupport (3.0.3) lib/active_support/dependencies.rb:181:in `const_missing'
activesupport (3.0.3) lib/active_support/inflector/methods.rb:113:in `constantize'
activesupport (3.0.3) lib/active_support/inflector/methods.rb:112:in `each'
activesupport (3.0.3) lib/active_support/inflector/methods.rb:112:in `constantize'
activesupport (3.0.3) lib/active_support/dependencies.rb:528
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `call'
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `default'
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `[]'
activesupport (3.0.3) lib/active_support/dependencies.rb:538:in `get'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:58:in `controller_reference'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:44:in `controller'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:23:in `call'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:148:in `call'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:93:in `recognize'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:68:in `optimized_each'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:92:in `recognize'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:139:in `call'
actionpack (3.0.3) lib/action_dispatch/routing/route_set.rb:492:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/head.rb:14:in `call'
rack (1.2.3) lib/rack/methodoverride.rb:24:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/flash.rb:182:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/cookies.rb:295:in `call'
activerecord (3.0.3) lib/active_record/query_cache.rb:32:in `call'
activerecord (3.0.3) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
activerecord (3.0.3) lib/active_record/query_cache.rb:12:in `cache'
activerecord (3.0.3) lib/active_record/query_cache.rb:31:in `call'
activerecord (3.0.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:353:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/callbacks.rb:46:in `call'
activesupport (3.0.3) lib/active_support/callbacks.rb:415:in `_run_call_callbacks'
actionpack (3.0.3) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
rack (1.2.3) lib/rack/sendfile.rb:107:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/show_exceptions.rb:46:in `call'
railties (3.0.3) lib/rails/rack/logger.rb:13:in `call'
rack (1.2.3) lib/rack/runtime.rb:17:in `call'
activesupport (3.0.3) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `synchronize'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
actionpack (3.0.3) lib/action_dispatch/middleware/static.rb:30:in `call'
railties (3.0.3) lib/rails/application.rb:168:in `call'
railties (3.0.3) lib/rails/application.rb:77:in `send'
railties (3.0.3) lib/rails/application.rb:77:in `method_missing'
railties (3.0.3) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.2.3) lib/rack/content_length.rb:13:in `call'
rack (1.2.3) lib/rack/handler/webrick.rb:52:in `service'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:162:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:95:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:92:in `each'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:92:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:23:in `start'
/Users/raimonbosch//.rvm/rubies/ruby-1.8.7-p352/lib/ruby/1.8/webrick/server.rb:82:in `start'
rack (1.2.3) lib/rack/handler/webrick.rb:13:in `run'
rack (1.2.3) lib/rack/server.rb:217:in `start'
railties (3.0.3) lib/rails/commands/server.rb:65:in `start'
railties (3.0.3) lib/rails/commands.rb:30
railties (3.0.3) lib/rails/commands.rb:27:in `tap'
railties (3.0.3) lib/rails/commands.rb:27
script/rails:6:in `require'
script/rails:6

Thanks in advance,
Raimon Bosch.

A: In the end we found another class in the repository with the same name:
cd $HOME/.rvm/gems
find . -name *.rb | xargs grep 'class HTTP'

Then we see an HTTP class on net.ssh-2.1.4
./ruby-1.8.7-p352/gems/net-ssh-2.1.4/lib/net/ssh/proxy/http.rb:  class HTTP

To solve the problem we forced the require 'net/http' and require 'net/https' at the beginning of the application. If the aplication requires the default gems is requiring first the HTTP class of net-ssh-2.1.4 and then we are not able to use Net:HTTP.


text:
Q: : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails in laravel migration In my migration file , I am adding organization id to the user's table , i tried all of the code below but not solved yet
class AddOrganizationIdToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
//            $table->foreignId('organization_id')->references('id')->on('organizations')->onDelete('cascade');
            $table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();
//            $table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }

A: I have data on my user's table so it is giving errors while migrating, to solve it I add the field as nullable
$table->foreignId('organization_id')->nullable()->references('id')->on('organizations')->onDelete('cascade');

A: if you write with foreignId need:
$table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();

or just foreign
$table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');

A: What could be the issue is that this migration is running before the organizations table migration, and when it tries to find it to create the constraint it fails.
What I would suggest is on the AddOrganizationIdToUsersTable :
Schema::table('users', function (Blueprint $table) {
            $table->foreignId('organization_id');
        });

And on the Organization creation migration:
Schema::table('users', function(Blueprint $table) {
            $table->foreign('organization_id')->references('id')->on('organizations');
        });

#2 solution:
Move the migration of Organization table to run before your AddOrganizationIdToUsersTable by changing the timestamp on the name of the file


text:
Q: Update all occurence of String in File using Java I have 1 file, which contains some String that need to be updated.
MY REPORT
REPORT RUN DATE : 27/08/2012 12:35:11 PAGE 1 of @TOTAL@
SUCCESSFUL AND UNSUCCESSFUL DAILY TRANSACTIONS REPORT
---record of data here----

MY REPORT
REPORT RUN DATE : 27/08/2012 12:35:11 PAGE 2 of @TOTAL@
SUCCESSFUL AND UNSUCCESSFUL DAILY TRANSACTIONS REPORT
---record of data here----

In case I just want to update all occurence of @TOTAL@ to some number, is there a quick and effecient way to do this?
I understand that I can also use BufferedReader+BufferedWriter to print to another file and use String.replace it along the way, but I wonder if there is a better and elegant way to solve this...
The file wont exceed 10MB, so there is no need to concern whether the file can be to big ( exceed 1 GB etc )

A: If you don't care about the file being too large, and think calling replace() on every line is inelegant, I guess you can just read the entire file into a single String, call replace() once, then write it to the file.

A:
... I wonder if there is a better and elegant way to solve this

It depends on what you mean by "better and elegant", but IMO the answer is no.

The file wont exceed 10MB, so there is no need to concern whether the file can be to big ( exceed 1 GB etc )

You are unlikely to exceed 1Gb.  However:

*

*You probably cannot be 100% sure that the file won't be bigger that 10Mb.  For any program that has a significant life-time, you can rarely know that the requirements and usage patterns won't change over time.

*In fact, a 10Mb text file may occupy up to 60Mb of memory if you load the entire lot into a StringBuilder.  Firstly, the bytes are inflated into characters.  Secondly, the algorithm used by StringBuilder to manage its backing array involves allocating a new array of double the size the original one.  So peak memory usage could be up to 6 times the number of bytes in the file you are reading.

*Note that 60Mb is greater than the default maximum heap size for some JVMs on some platforms.


text:
Q: Is there a way to simulate data in BigQuery as in SQL Server? In SQL Server 2016 there is database called wide-world-importers, where we can simulate data to generate millions of data by calling SQL Server's inbuilt stored procedures.
Is there a way to do the same thing in google-big query? Or is there a way to to simulate data in google-big query as my requirement? Or even is there a place to get sample data sets with millions of records like HR, Finance, Sales, etc for big-query; public data sets in big-query not satisfied my requirement?

A: just run below as is in BigQuery Standard SQL
CREATE TEMPORARY FUNCTION gender(num STRING)
RETURNS STRING
LANGUAGE js AS """
  var n = parseInt(num);
  if (Math.floor(Math.sin(n*n)) == 0) return "f"
  return "m";
  """;

CREATE TEMPORARY FUNCTION department(num STRING)
RETURNS STRING
LANGUAGE js AS """
  var n = parseInt(num);
  return Math.floor(Math.sin(n) * 3 + 3)
  """;

WITH sequence AS (
  SELECT FORMAT("%07d", ROW_NUMBER() OVER()) AS num
  FROM UNNEST((SELECT SPLIT(FORMAT("%1000000s", ""),"") AS h FROM (SELECT NULL))) AS pos
)
SELECT
  num AS id,
  CONCAT("FN ", num) AS first_name,
  CONCAT("LN ", num) AS last_name,
  gender(num) AS gender,
  CONCAT("Department ", department(num)) AS department
FROM sequence
ORDER BY num

be patient as it took few min to run - you can change 1000000 in %1000000s to lower number (it sets row count in result) to make it fast while playing with it
This is just super simple example of how to generate your own data for free
You can extend this example to whatever specific requirements you have
Endless opportunities here - like controlling distribution over different attributes, having nested data - records / repeated, etc.
You can see Standard SQL Reference if any questions on Syntax or Functions
Also note: I am using here recently introduced Scalar User-Defined Functions
Enjoy and Hope this helped!


text:
Q: express routing run from post to next get is not automatically I have following route defined:
router.post('/select', function(req, res, next){
    var sql = "SELECT metadocid, col1, col2, col3 FROM mdt1 where ";
    var metadocid = req.body.metadocid;
    var op1 = req.body.op1;
if (metadocid !== "") {
        var opm = req.body.op1;
        switch (opm){
               case "equals":
                   opm = "=";
                   break;
               }
        var sel1 = "metadocid "  + opm + " " + metadocid;
    }
    sql = sql + sel1;
    console. log('Send sql: ' + sql );
    async.waterfall(
    [
      function(callback) {
       fs.writeFile('message.txt', sql, callback);
      }
    ], function (err) {
        if(err) return console.log(err);
        console.log('Appended text!');
    });
    next();
  });

router.get('/documents', function(req,res){
    handleAllDepartments(1);
    res.sendFile(__dirname + '/docs.html');
});

app.use('/',router);
But from router.post('/select') it is not started the router.get('/documents'). If I type in browser the route /documents then
the programm continue to run.
I want the programm continue from router.post('/select') to router.get('/documents') automatically.
Please help!
Thank you in advance!

A: The point of routing in Express is that if you call e.g. POST /select, the router will call only functions assigned to this and ONLY this request. This means that use of next() won't pass execution to for example GET /select or POST /documents or GET /documents because those are different requests.
There is method called use in Express that allows you to catch EVERY request without caring about method and address. It allows also use of next() of course.
To sum up, you have to call 4 separate requests to each of those you described in comments (and that's a lot) or simply make one request that will handle all those operations you were about to conduct in 4 routers.

A: It's not really clear to me from your code why you're doing things this way.  It looks like you're trying to post some data to a file, and then send a separate document down to the client.  This is a slightly uncommon workflow, though certainly doable.
The more common way to handle POST in a RESTful architecture like Express is to take the POST in one handler, and respond with a redirect to the newly POST'ed resource, which the client would then separately request with a GET.
That said, if you do have a workflow where you first post some data and then want to call some other function to handle the response, then you can use multiple handlers on a route like so:
function receiveDocData(req,res,next){
  var sql = "SELECT metadocid, col1, col2, col3 FROM mdt1 where ";
    var metadocid = req.body.metadocid;
    var op1 = req.body.op1;

  if (metadocid !== "") {
        var opm = req.body.op1;
        switch (opm){
               case "equals":
                   opm = "=";
                   break;
               }
        var sel1 = "metadocid "  + opm + " " + metadocid;
    }
    sql = sql + sel1;
    console. log('Send sql: ' + sql );
    async.waterfall(
    [
      function(callback) {
       fs.writeFile('message.txt', sql, callback);
      }
    ], function (err) {
        if(err) return console.log(err);
        console.log('Appended text!');
    });

    next();
  }
}

function doTheNextThing(req,res){
  handleAllDepartments(1);
  res.sendFile(__dirname + '/docs.html');
}

router.post('/select', receiveDocData, doTheNextThing);
router.get('/documents', doTheNextThing);
app.use('/',router);

Note that I left the route for '/documents' on the assumption from your setup that you would want to get it independent of doing the actions in the original '/select' handler.


text:
Q: How should google crawl my blog? I was wondering how (or if) I should guide Googlebot through my blog. Should I only allow visiting pages with single entries or should it also crawl the main page (which also has full entries)? My concern is that the main page changes when I add a new post and google keeps the old version for some time. I also find directing people to the main page annoying - you have to look through all the post before you find the one you're interested in. So what is the proper way to solve this issue?

A: Why not submit a sitemap with the appropriate <changefreq> tags -- if you set that to "always" for the homepage, the crawler will know that your homepage is very volatile (and you can have accurate change freq for other URLs too, of course). You can also give a lower priority to your homepage and a higher one to the pages you prefer to see higher in the index.
I do not recommend telling crawlers to avoid indexing your homepage completely, as that would throw away any link juice you might be getting from links to it from other sites -- tweaking change freq and priority seems preferable.

A: Make a sitemap.xml and regenerate it periodically. Check out Google Webmaster Tools.


text:
Q: Setting a mock location programmatically in FusedLocationProviderClient I am trying to use mock locations in my app for testing. To receive location updates I used the latest android developer documentation here:
https://developer.android.com/training/location/receive-location-updates
This tutorial uses FusedLocationProviderClient and locationClient.requestLocationUpdates(createLocationRequest(), locationCallback, null) as example.
The issue is that I can no longer use permission:
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

because I get the error "Permission is only granted to system apps" (I tried also in debug mode)
So I tried the following code, but it doesn't work:
    locationClient.setMockMode(true);

    String[] tokens = location.split(",");
    Location newLocation = new Location(LocationManager.GPS_PROVIDER);
    newLocation.setLatitude(Float.parseFloat(tokens[0]));
    newLocation.setLongitude(Float.parseFloat(tokens[1]));

    newLocation.setAccuracy(3.0f);

    newLocation.setTime(System.currentTimeMillis());

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        newLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
    locationClient.setMockLocation(newLocation);

Does anyone have an idea how to solve this?

A: It seems that adding the
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

permission to debug android manifest works even though Android Studio says "Permission is only granted to system apps".
So the solution is that, after adding it, run the application, then go to Settings / Developer options / Select mock location app -> here my app appears and I can select it.
I hope others can confirm and use this!


text:
Q: Completely transparent UIButton with irregular hit area I know how to use a background image with alpha channel to create a UIButton with an irregular tap area. But with this solution, only the ignore-tap area is transparent; the tap area consists of the opaque.
What I want is a totally transparent UIButton, with an irregular tap area. (It triggers an animation behind the button.)
It seems that some sort of extra UILayer with some hit-testing could work, but I don't quite see how. Suggestions welcome.

A: Here's my solution. The problem: A UIImageView (call it the base view) to which I want to attach an irregularly-shaped tap area. The area corresponds to something in the image, let's call it a river. It could be a non-connected region.
In the Finder, duplicate the view's image, and make all the non-river pixels transparent, using your favorite graphics app. Call this the mask image.
When the base view is tapped, check to see if the corresponding pixel in the mask image is or is not transparent. (Solution left to reader; examples abound.)
So the mask image is never actually rendered, it is just used as a reference.
Note that if the base view gets resized or moved around (as it does in my app, via animating its constraints) then you have to "move" the mask image too, or in some other way manage the coordinate translation between view and mask. The easiest way to do this is to make the mask image a hidden subview of the base view, with its left, top, leading and trailing anchors constrained to be equal to those of the base view. Then they move around together, and the coord translation between the two is the identity.
I wrapped all this up in a subclass of UIImageView so that it manages its own mask, and calls a delegate if the "river" (or whatever) is tapped.