text:
Q: Predicting multiple forecast values using timeseries ARIMA model -> We are trying to build a timeseries model using ARIMA.
-> The goal is to predict multiple forcast values.
On the basis of history data I want to predict the next 3 data values.
-> In my use case I am using pmdarima for automatically finding the p,d,q values.
code:
import pmdarima as pm
model = pm.auto_arima(df[data_column])
hyperparameter = model.fit(df[data_column])
-> I have one dataset of 4000 rows. In one case I am considering first 100 rows of dataset and in second case I am considering all 4000 rows of the dataset.
-> ARIMA on 100 row dataset

*

*Here I am considering first 97 values as lag and trying to predict last 3 values.

*p,d,q values from pmdarima are (1,0,0)

*In this case we are able to successfully predict three different values.

*code is as follows

considering first 100 values of the dataset and getting p,d,q as 1,0,0 using pmdarima
 import pmdarima as pm
 model = pm.auto_arima(df[col_name])
 hyperparameter = model.fit(df[col_name])
 hyperparameter
 Output: ARIMA(order=(1, 0, 0), scoring_args={}, suppress_warnings=True)

 p=1
 d=0
 q=0

 X = df[col_name].values # converting data to ndarray

 number_of_moving_data_for_model=97
 train, test = X[:number_of_moving_data_for_model],X[number_of_moving_data_for_model:]

 # fit model
 model = ARIMA(train, order=(p,d,q))
 model_fit = model.fit()
 # multi-step out-of-sample forecast
 forecast = model_fit.forecast(steps=3)
 print('forcast =', forecast)
 Output: forcast = [55135502.82729979 55133836.2767516  55132494.00564519]

-> ARIMA on 4000 row dataset

*

*Here I am considering first 3997 values as lag and trying to predict last 3 values.

*p,d,q values from pmdarima are (0,1,0)

*In this case we are NOT able to successfully predict three different values.

*Code is as follows
considering first 4000 values of the dataset and getting p,d,q as 0,1,0 using pmdarima
import pmdarima as pm
model = pm.auto_arima(df[col_name])
hyperparameter = model.fit(df[col_name])
hyperparameter
Output: ARIMA(order=(0, 1, 0), scoring_args={}, suppress_warnings=True)
p=0
d=1
q=0
X = df[col_name].values # converting data to ndarray
number_of_moving_data_for_model=3997
train, test = X[:number_of_moving_data_for_model],X[number_of_moving_data_for_model:]
fit model
model = ARIMA(train, order=(p,d,q))
model_fit = model.fit()
multi-step out-of-sample forecast
forecast = model_fit.forecast(steps=3)
print('forcast =', forecast)
Output: forcast = [57531824. 57531824. 57531824.]
-> But when we are changing the p,d,q parameter values to (1,0,0) then it is predicting different three future values.

*

*Code is as follows
considering first 4000 values of the dataset and getting p,d,q as 0,1,0 using pmdarima
import pmdarima as pm
model = pm.auto_arima(df[col_name])
hyperparameter = model.fit(df[col_name])
hyperparameter
Output: ARIMA(order=(0, 1, 0), scoring_args={}, suppress_warnings=True)
p=1
d=0
q=0
X = df[col_name].values # converting data to ndarray
number_of_moving_data_for_model=3997
train, test = X[:number_of_moving_data_for_model],X[number_of_moving_data_for_model:]
fit model
model = ARIMA(train, order=(p,d,q))
model_fit = model.fit()
multi-step out-of-sample forecast
forecast = model_fit.forecast(steps=3)
print('forcast =', forecast)
Output: forcast = [57531509.23896821 57531194.56251951 57530879.97063115]
-> How by changing the p,d,q parameter values from (1,0,0) to (0,1,0) ARIMA is working correctly?


text:
Q: Laravel policy always denies access I registered policy
protected $policies = [
         'App\Grade' => 'App\Policies\GradesPolicy'

    ];

Thi is my route for this resource:
Route::get('/grades', 'GradesController@showGrades');

Controler method
public function showGrades()
    {

        $this->authorize('viewAny');

        switch(Auth::user()->role)
        {
            case 'teacher':
               return view('teacher');
            break;

            case 'parent':
              return view('parent');
            break;

            default:
             abort(400);
            break;
        }
    }

And policy method
public function viewAny(User $user)
    {

         return $user->check();
    }

Yes I know there are related topics here. I read them. I know this is something with model binding. The viewAny method is never invoked. I usedd dd inside of it and it shows nothing. But how am I supposed to bind model here? Any ideas?

A: you didn't specify the relevant model to the authorize method when calling the action "viewAny", so what you need to do is:
$this->authorize('viewAny',Grade::class);

or add it directly to the middleware and delete the authorize call from your controller
Route::get('/grades','GradesController@showGrades')
->middleware('can:viewAny,App\Grade');

redpajama_set_name: RedPajamaStackExchange


text:
Q: Group Function is not allowed here SQL I have tables like this:
Attendance(offering_id,visitor_id, regstr_date,amount_paid)
   Offer(offering_id,teacher_id)
   Teacher(teacher_id,teacher_firstname,teacher_lastname,start_date)
It is possible that one  visitor may attend twice or more. I want to retrieve visitor_id, regstr_date,total amount_paid,average amount_paid  from attendance where offering id is 30,40 or 50 and teacher's start date is less than any  visitor's latest regstr_date    and    average amount_paid by per visitor is less than 600. My code is as follows:
select
    distinct(a.visitor_id) as v_id ,
    max(a.regstr_date) as reg_date,
    sum(a.amount_paid) as total_pay,
    count(a.regstr_date) as attendance_count,
    avg(a.amount_paid) as average_paid
from
    attendance a, teacher t, offer o
where
    a.offering_id = o.offering_id
    and o.teacher_id = t.teacher_id
    and a.offering_id in ('30', '40', '50')
    and max(a.regstr_date) > t.start_date
group by
    a.visitor_id
having
    avg (a.amount_paid) <= 600;

But it shows group function is not allowed here. If possible could you help me with this please?

A: This query written for MS-SQL server
select  a.visitor_id as v_id ,
max(a.regstr_date) as reg_date,
sum(a.amount_paid) as total_pay,
count(a.regstr_date) as attendance_count,
avg(a.amount_paid) as average_paid
from attendance a Inner Join  offer o   on a.offering_id = o.offering_id
inner join  teacher t on t.teacher_id = o.teacher_id
where a.offering_id in('30','40','50')
group by a.visitor_id,t.start_date
having avg (a.amount_paid)<=600 and  max(a.regstr_date)>t.start_date;


text:
Q: Why does a function declaration override non-writable properties of the global object? Setting a property descriptor like this:
Object.defineProperty(window, 'someFunction', {
    value: function() { alert('safe'); },
    writable: false,
    enumerable: false,
    configurable: false
});

...should, as far as I know, make the someFunction property of window non-writable. It works for function expressions as I expect, whether the function is directly assigned to the object property... fiddle
window.someFunction = function() { alert('boom!'); }
someFunction(); // safe

...or assigned to a global variable: fiddle
var someFunction = function() { alert('boom!'); }
someFunction(); // safe

However, it doesn't seem to work with function declarations: fiddle
function someFunction() { alert('boom!'); }
someFunction(); // boom!

Is this behavior intentional? What is the reasoning behind it? Is this documented anywhere? Or am I just making some kind of silly mistake?

By the way, I'm using Chromium 17 to test this. Strict mode doesn't seem to make any difference.

A: This is a bug (see Bug #115452), which I also encountered when answering this question.
Compatibility check: Test case

*

*In Firefox 4+, it works fine.

*In Chrome 16, it works fine.

*In Chrome 17, it does not work.

*IE8- doesn't have Object.defineProperty, so it doesn't work

*In IE9, it does not work.

*In Safari 5, it does not work.


text:
Q: Remove unwanted characters in a string using regex I have a string like this in my column:

[img ret872154ftu] fileaddress [/img ret872154ftu]

[img fd68721cvn] fileaddress [/img fd68721cvn]

[img xdfh654t] fileaddress [/img xdfh654t]

Now i wish to remove unwanted chars inside [img] and [/img].
I have already used this query but does not work:
UPDATE `table` SET `content` = replace(`content`, '[img [^]*]', '[img]');

Any suggestion?

A: UPDATE table SET
 column=REPLACE(column,SUBSTRING_INDEX(SUBSTRING_INDEX(column,'/img ',-1),']',1),'');

UPDATE table SET
 column=REPLACE(column,SUBSTRING_INDEX(SUBSTRING_INDEX(column,'[img ',-1),']',1),'');

SQL Fiddle
2 updates,with different delimiters because the texts might be different.


text:
Q: WFH: reach local network while VPN blocks it While WFH, my work laptop (macOS big sur 11.6) uses a VPN (cisco anyconnect) that effectively disables its 192.168.1.xxx IP address, which would otherwise let it see and be seen by the other hosts and the printer on my 192.168.1.xxx LAN.
Is there a way to move data between the laptop and the LAN without relying on an intermediate outside service such as dropbox, pastebin, web email, scp to/from a cloud host, or even copypasting to/from a chat service?
(The VPN's Preferences checkbox "Allow LAN access when using VPN (if configured)" is checked, but the laptop doesn't see the LAN.  So the build I got must have that unconfigured.  Its Statistics page also says "Tunnel All Traffic" through the VPN, i.e., even packets sent to 192.168.  So split tunnelling is unavailable.)
There's no wifi at home, because reasons, but bluetooth is available.
If there isn't a software solution:
Back in the day, you'd use an RS232 null modem cable.  Could a similar cable work between the laptop's USB-C and something on the LAN?  This is just to move the occasional megabyte file or hundred-byte command, so latency and bandwidth hardly matter.

A: A related question directed me to an answer that worked.
brew update && brew install openconnect (Just once.)
sudo openconnect -u myusername --authgroup=mygroupname hostname.mydomain.com
Type my password and my 2FA password.
To stop the VPN, type Ctrl+C.


text:
Q: unexpected allocation request that exceeds 2GB error I have a system with 32GB ram and 200GB of swap partition with Debian Linux (Jessie) and working with ABAQUS software to simulate complex phenomena. I've tested many test cases and they run without any error but now I want to run a test case which should need about 100GB of ram (or more or less). The problem id that it fills the RAM totally and even about 10GB of swap space but then it returns an error "unexpected allocation request that exceeds 2GB". the system is obviously 64bit and the software package is also 64bit. I checked that the same error will occur when about 50GB of RAM was filled.
I don't know what is limiting the process and why the error message tells 2GB as it already have about 40GB allocated?


text:
Q: A jQuery "double" swipe and styles issue After trying several ways to solve the issues, I couldn't so I decided to ask for help.
I'm doing a small app for phonegap and using jQuery mobile. http://jsfiddle.net/tronne/vh4266mu/1/
The problems are:

*

*When you swipe in the mobile it's ok, but from a desktop once you swipe the box, the panel also appear. I've found a possible solution, not sure if it's the proper one but it's working:
$(document).on("swipeleft swiperight", "#mouseSwipe1", function (e) {
    e.stopPropagation();
});

*Another with styles, I'm, not sure why I can't see the panel "test 3" inline with test 1 and test 2, I've tried changing all widths but still no luck

*And another style issue, when you swipe to see the panels, the first time you see the panel is working correctly but in the second there's a black big row at the bottom.


text:
Q: CSS Submenu bar This is my css code of menu bar which is having an error and not working fine.
ul.semiopaquemenu li a:hover, ul.semiopaquemenu li a.selected{
color: black;
-moz-box-shadow: 0 0 2px #595959; /* CSS3 box shadows */
-webkit-box-shadow: 0 0 5px #595959;
box-shadow: 0 0 5px #595959;
padding-top: 10px; /* large padding to get menu item to protrude upwards */
padding-bottom: 10px; /* large padding to get menu item to protrude downwards */
}
ul.semiopaquemenu li {
    position: relative;
}
/*sub menu*/
ul.semiopaquemenu li ul.sub-menu {
    display:none;
    position: absolute;
    LEFT:-22PX;
    top:25px;
    background-color:#99CCFF;
    width:130px;
    padding:10px;

    border-left: 2px solid #4b6c9e;
    border-right: 2px solid #4b6c9e;
    border-bottom: 2px solid #4b6c9e;
     border-bottom-left-radius: 10px;
  -webkit-border-bottom-left-radius: 10px;
  -moz-border-radius-bottomleft: 10px;
  border-bottom-right-radius: 10px;
  -webkit-border-bottom-right-radius: 10px;
  -moz-border-radius-bottomright: 10px;
    text-decoration:italic;
    text-transform:uppercase;
}
ul.semiopaquemenu li:hover ul.sub-menu {
    display:block;
}
</style>

This my Html code of menu Bar:

<asp:LinkButton ID="lbFAQ" runat="server" PostBackUrl="~/FAQ.aspx">Department</asp:LinkButton>

                    Sub Menu 1

                    Sub Menu 2

                    Sub Menu 3

                    Sub Menu 4

In this I'm not able to make boxes in sub menu items, so please help with this.

JSFiddle Demo

A: change css class ul.semiopaquemenu li ul.sub-menu of attributes to border-bottom: 0px solid #4b6c9e;. The lines are appeared due to mention of px in 2px change it to 0px.

A: We are not clear what is actually required but what I understood  is you need a box on sub menu item as well
try this  JS fiddle
Add this Css
.sub-menu a{
    border-bottom: 1px solid #000;
    padding: 10px;
    display: block;

}

Remove Extra Br in between
 tags
Also Remove Margin padding form submenu

ul.semiopaquemenu li ul.sub-menu {
    padding:0px;
    margin:0px;
    list-style:none;

}


text:
Q: ESLII confusion about splines regression In elements of statistical learning, beginning of chapter 5.2 they state 'we assume X is one dimensional'.
I understand this as meaning X has one feature and N samples.
However in chapter 5.2.2(extract below)

they present an example where, to my understanding, X is no more one dimensional since there are X1, X2,...
Am I correct or not?
Then in chapter 5.7 (extract below)

they present how to handle splines to handle multidimensional X. But isn't it exactly what has already been done in Chapter 5.2.2 using other notations?

A: No, there is a difference that is not merely notational.
In the first case we are dealing with $p$ one-dimensional $X_i$, each expanded into its own spline basis $h_i(X_i)$.  From the point of view of the spline, each input is one-dimensional ($X_i$ is one-dimensional); we don't need any other $X_j, j\neq i$ in order to calculate the spline basis $h_i(\cdot)$ for $X_i$.
Somewhat confusingly, each of these $X_i$ in this section corresponds to $X$ in the "we assume $X$ is one-dimensional" statement.  The upside is that when describing the algorithm the notation is simpler, because you don't need to carry around subscripts all the time that might needlessly add to subscript complexity when combined with subscripts used within the algorithm and cause confusion that way.
In the second case we are dealing with a multi-dimensional $X$ expanded into a single, joint spline basis.  With respect to the specific example, the tensor product basis, each basis function of the joint spline is the product of two basis functions of $X_i$-specific splines (two because we are assuming that $X$ is two-dimensional, i.e., that $p=2$.)  From the point of view of the spline calculation, we need both $X_1$ and $X_2$ as inputs in order to calculate the basis functions $g_{jk}(X)$.
From an application perspective, the former does not allow for interactions between the various $X_i$, but the latter does.
You sometimes have to be a little careful about when $X$ refers to all the data, e.g., $X = [X_1 | X_2 | \dots | X_p]$ or when $X$ is just being used as a placeholder for purposes of explaining a particular algorithm, in which case there's sort of a "local" definition of $X$ and a "global" definition of $X$ to keep track of.  I've fallen into that particular trap myself!


text:
Q: How to pass a KeyValuePair to web api I'm trying to pass a List of KeyValuePairs from my angular service to my web api controller like so:
web Api controller:
    [HttpGet]
    [Route("")]
    public IHttpActionResult Users([FromUri] List<KeyValuePair<string, object>> filters)
    { }

Angular service:
return $http.get(url, {
            params: {
                filters: [{ Key: "UserName", Value: "A.Lincoln" }]
            }
        });

I have tried lots of different ways to pass the params by changing the format of the json, but I always end up with the same result in te controller. filters = [0]{[,]}. So it knows I am passing it something but the key/value are always null. When I send a List of strings instead of keyvaluepairs it gets the values just fine. Can anybody help me with what is going wrong?

A: I think using JSON.stringify() for your data property should suffice.
var jsonString = [
    {
        "Key": "UserName",
        "Value": "A.Lincoln"
    }
]

$http.get(url, data: JSON.stringify(jsonString))
  .then(successCallback, errorCallback);

A: I have already found the answer.
Is now deserialize the JSON string in the controller like so:
public IHttpActionResult Users([FromUri] string jsonFilters)
    {
        var filters = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonFilters);}

If anybody knows a nicer solution please let me know :)

A: Try adding the $resource service routes to a factory and use it in the controller through its methods, this will help you work more efficiently:
.factory('yourResource', ['$resource', function ($resource) {
      return $resource(url/:key/:value, { Key: '@key', Value: '@value' } {
        'get': {
          method: 'GET',
          headers: {"Content-Type": "application/json"}
        }
      });
    }]);

THEN IN THE CONTROLLER
  $scope.get= yourResource.get({Key: 'UserName', value: 'A.Lincoln'}, function (response) {
    alert(response);
  };


text:
Q: Getting JsonArray data from Jersey using Angular js I am writing simple application with REST in the backend and Angular as frontend. And now I cant make them talk properly.
My Jersey class gets some data from database make JSONArray from it and send it to response to get.
@GET
@Path("{userID}")
@Produces(MediaType.APPLICATION_JSON)
public String getLearningList(@PathParam("userID") int userId)
{
    SqlConnector con = new SqlConnector();
    List<String> list = con.getUsersLearningList(userId);
    JSONObject jObj = new JSONObject();
    jObj.put("list", list);
    JSONArray jArray = jObj.getJSONArray("list");
    return jArray.toString();
}

In Angular I am using angular-resourse to get data from REST and even I made isArray: true I am getting this error:
       Error in resource configuration for action `get`. Expected response to contain an object but got an array

Here is my angular
myApp.factory('GetDataService', ['$resource', function($resource){
    return {
        getData: function(url)
        {
            return $resource(url,{},{
                query: {
                    method: 'GET',
                    params: {},
                    isArray: true
                }
           })
       }
    }
}]);

SqlConnector is just my class which work with database.
I am completely new in Angular. Thank you in advance!


text:
Q: PHP Regex match four spaces but not five     This is a line indented with four spaces
        another one with eight spaces
    now the last with four

this is my string i want to preg_split on four spaces and not more, i am using,
preg_split('/^    /m', $str)

result:
array(4) {
  [0]=>
  string(0) ""
  [1]=>
  string(41) "This is a line indented with four spaces
"
  [2]=>
  string(34) "    another one with eight spaces
"
  [3]=>
  string(22) "now the last with four"
}

I want the line with more than four spaces to be part of the first split,  I have difficulty in understanding the non capture or negative lookahead regex.

A: To split on 4 spaces not on 5th you can use this negative lookahead:
$arr = preg_split('/^ {4}(?! )/m', $str);

where (?! ) is negative lookahead that will fail matching 4 spaces at start if there is a 5th space next to it.

EDIT: To avoid empty values in split array use:
 $arr = preg_split('/^ {4}(?! )/m', $str, -1, PREG_SPLIT_NO_EMPTY);


text:
Q: Duplicates using preceding data Hi I need to find duplicates, I have attached an image of the dataset and an example of a duplicate. Same id, and same result with preceding dates.
Any help would be really appreciated.
Dataset Screengrab

structure(list(id = c(1010001, 1010001, 1010001, 1010001, 1010001,
1010001, 1010001, 1010001, 1010001, 1010001, 1010001, 1010001,
1010001, 1010001, 1010001, 1010001, 1010001, 1010001, 1010001,
1010001, 1010001, 1010001, 1010001, 1010001, 1010001, 1010001,
1010001, 1010001, 1010001), DateCollected = structure(c(1145664000,
1145750400, 1145836800, 1145923200, 1146009600, 1146096000, 1146096000,
1146096000, 1146096000, 1146096000, 1146096000, 1146182400, 1146268800,
1146355200, 1146441600, 1146528000, 1146614400, 1146700800, 1146787200,
1146787200, 1146787200, 1146787200, 1146787200, 1146787200, 1146873600,
1146960000, 1147046400, 1147132800, 1147219200), class = c("POSIXct",
"POSIXt"), tzone = "UTC"), Test = c("Tacrolimus (FK506)", "Tacrolimus (FK506)",
"Tacrolimus (FK506)", "Tacrolimus (FK506)", "Tacrolimus (FK506)",
"Tacrolimus (FK506)", "Tacrolimus (FK506)", "Tacrolimus (FK506)",
"Tacrolimus (FK506)", "Tacrolimus (FK506)", "Tacrolimus (FK506)",
"Tacrolimus (FK506)", "Tacrolimus (FK506)", "Tacrolimus (FK506)",
"Tacrolimus (FK506)", "Tacrolimus (FK506)", "Tacrolimus (FK506)",
"Tacrolimus (FK506)", "Tacrolimus (FK506)", "Tacrolimus (FK506)",
"Tacrolimus (FK506)", "Tacrolimus (FK506)", "Tacrolimus (FK506)",
"Tacrolimus (FK506)", "Tacrolimus (FK506)", "Tacrolimus (FK506)",
"Tacrolimus (FK506)", "Tacrolimus (FK506)", "Tacrolimus (FK506)"
), Result = c(3, 4.1, 5.9, 8.1, 4.6, 7, 7.8, 11.2, 18.1, 18.4,
27, 4, 7.8, 8.4, 8.4, 6.1, 6.8, 5.4, 5.4, 6.5, 6.7, 8.1, 14.2,
32.4, 7.2, 8.6, 8.9, 7.2, 9.6), Units = c("ug/L", "ug/L", "ug/L",
"ug/L", "ug/L", "ug/L", "ug/L", "ug/L", "ug/L", "ug/L", "ug/L",
"ug/L", "ug/L", "ug/L", "ug/L", "ug/L", "ug/L", "ug/L", "ug/L",
"ug/L", "ug/L", "ug/L", "ug/L", "ug/L", "ug/L", "ug/L", "ug/L",
"ug/L", "ug/L")), row.names = c(NA, -29L), class = c("tbl_df",
"tbl", "data.frame"))

A: We can write a function to calculate difference between the value of Result and return row indices when a duplicate is found.
find_duplicates <- function(x) {
  inds <- which(diff(x) == 0)
  sort(unique(c(inds, inds + 1)))
}

We can apply this function by group.
To get duplicate rows we can do :
library(dplyr)
df %>% group_by(id) %>% slice(find_duplicates(Result))

#      id DateCollected       Test               Result Units
#    <dbl> <dttm>              <chr>               <dbl> <chr>
#1 1010001 2006-04-30 00:00:00 Tacrolimus (FK506)    8.4 ug/L
#2 1010001 2006-05-01 00:00:00 Tacrolimus (FK506)    8.4 ug/L
#3 1010001 2006-05-04 00:00:00 Tacrolimus (FK506)    5.4 ug/L
#4 1010001 2006-05-05 00:00:00 Tacrolimus (FK506)    5.4 ug/L

To get an additional flag column we can use :
df %>%
  group_by(id) %>%
  mutate(is_duplicate = row_number() %in% find_duplicates(Result))

A: We can group by 'id' and create a flag by checking the lag or lead of the adjacent 'Result'
library(dplyr)
df1 %>%
   group_by(id) %>%
   mutate(flag= Result == lag(Result)|Result == lead(Result)) %>%
   filter(flag)
# A tibble: 4 x 6
# Groups:   id [1]
#      id DateCollected       Test               Result Units flag
#    <dbl> <dttm>              <chr>               <dbl> <chr> <lgl>
#1 1010001 2006-04-30 00:00:00 Tacrolimus (FK506)    8.4 ug/L  TRUE
#2 1010001 2006-05-01 00:00:00 Tacrolimus (FK506)    8.4 ug/L  TRUE
#3 1010001 2006-05-04 00:00:00 Tacrolimus (FK506)    5.4 ug/L  TRUE
#4 1010001 2006-05-05 00:00:00 Tacrolimus (FK506)    5.4 ug/L  TRUE


text:
Q: Can OpenLayers 3 properly render KML? When I used the simple online Demo (http://openlayers.org/en/v3.6.0/examples/drag-and-drop.html), and dropped in a KML file, it got the colors right but it ignored all the placemarks. Using Ubuntu+Chrome.
My needs are pretty basic - I want to make a simple Web page, which allows the user to click one of a number of links, and then render KML corresponding to that link. I would love to use OL3 instead of Google My Maps + Maps, if only because Google appears to require a credit card # etc, for the privilege of using their Javascript API(s).
Thanks!

A: Have a look at this jsFiddle.
You should be able to drag and drop that example KML file which you provided.

The problem is not the placemarks. Placemarks are fine for OL3. My feeling is that you don't see that data in the other example because the styles are read from the KML. Reading styles from a KML and trying to put this into OL3 opens a whole can of worms.
So I recommend to first use:
formatKML = new ol.format.KML({extractStyles: false});


text:
Q: Mahapps.Flyouts - Content Binding I'm trying to dynamically bind a Flyout content to a view, like I would do to a TabControl, but when I load the view object the Flyout is empty. I tried loading the view directly below the Controls:FlyoutsControl and it worked, so I don't think the problem is with the view itself.
Also, I need to load this in a specific Flyout, so using the ItemSource property in the Controls:FlyoutsControl wouldn't work for me.
MainWindow.xml
<Controls:MetroWindow.Flyouts>
    <Controls:FlyoutsControl>
        <Controls:Flyout
            Content="{Binding FlyTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
            IsOpen="{Binding IsOpen, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
            Background="#91000000"/>
    </Controls:FlyoutsControl>
</Controls:MetroWindow.Flyouts>

UserControl1.xml - The View to be loaded
<controls:Flyout
    x:Class="TestApp.View.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
    Position="Right"
    MinWidth="380" MaxWidth="380"
    Header="Manufacturer Data">
    <Grid>
        <TextBox
            Text="Test Data"
            Grid.Row="0" Grid.Column="0"
            VerticalAlignment="Center"
            HorizontalAlignment="Right"/>

    </Grid>
</controls:Flyout>

MainWindowViewModel.cs
    private UserControl1 _flyTest;

    public UserControl1 FlyTest
    {
        get { return _flyTest; }
        set
        {
            _flyTest = value;
            RaisePropertyChanged("FlyTest");
        }
    }

    private void LoadTabs()
    {
        FlyTest = new UserControl1();
        IsOpen = true;
    }

A: I figured it out by changing the view object type from Flyout to UserControl


text:
Q: Azure B2C Xamarin Forms, clientId versus applicationId I followed this sample https://github.com/Azure-Samples/active-directory-b2c-xamarin-native to implement Azure B2C auth in Xamarin Forms.
There are two GUID in the sample
B2CConstants  ClientID = "e5737214-6372-472c-a85a-68e8fbe6cf3c";

AndroidManifest.xml
<data android:scheme="msale5737214-6372-472c-a85a-68e8fbe6cf3c"

and
MsalActivity.cs  DataScheme = "msal90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6")]

Info.plist
<string>msal90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6</string>

The first one is the clientId for the registered app in tenant, what about the second?
Some blogs called applicationId, so how can I get this from the Azure portal?

A: It's a Custom Redirect URI.You should make sure that your application has enabled the Native client setting and create it as shown in the following screenshot:

You could look at this.


text:
Q: How to strcat with intervals in C++? So here's my code:
#include <iostream>
#include <string.h>
using namespace std;

const int MAX_SIZE1 = 20;
const int MAX_SIZE2 = 10;

int main()
{
    char a[MAX_SIZE1][MAX_SIZE1][MAX_SIZE2];
    int n, i, j;
    cin >> n;
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            cin >> a[i][j];

    char s[MAX_SIZE1 * MAX_SIZE1 * (MAX_SIZE2 - 1) + 1];
    int hor = 0, vert = 0;
    while (hor < n / 2 && vert < n / 2)
    {
        for (i = vert; i < n - vert; i++)
            strcat(s, a[hor][i]);
        for (i = hor + 1; i < n - hor; i++)
            strcat(s, a[i][n - vert - 1]);
        for (i = n - vert - 2; i >= vert; i--)
            strcat(s, a[n - hor - 1][i]);
        for (i = n - hor - 2; i > hor; i--)
            strcat(s, a[i][vert]);
        hor++;
        vert++;
    }
    if (n % 2)
        for (i = vert; i < n - vert; i++)
            strcat(s, a[hor][i]);
    else
        for (i = hor; i < n - hor; i++)
            strcat(s, a[i][vert]);
    cout << s << endl;
    return 0;
}

I've got some questions. How to modify it in order to get intervals between the words in the outputted s string? And how to get rid of the awkward 50 rows (literally) long weird symbols in the beginning of my output?
EDIT: I'm sorry. Thought it didn't matter. The input should be a maximum of 20x20 array of words which do not exceed 9 characters each. The output should be an s string which represents a sentence formed by reading the array in a clockwise spiral beginning from the top left corner. Problem is.. I got weird symbols in the beginning of my output and get no intervals between the words.

A:  Use C++ instead of C
Since you are using C++, you should really write your code in a C++ way, using std::string. One of your problems (uninitialized string) can be fixed this way, since it is impossible to define an uninitialized string in C++.

Replace
#include <string.h>

by
#include <string>

Replace
char s[MAX_SIZE1 * MAX_SIZE1 * (MAX_SIZE2 - 1) + 1];

By
std::string s;

Replace
strcat(s, a[hor][i]);

by
s = s + a[hor][i];

 If you still want to use C
You have to initialize your output string:
char s[MAX_SIZE1 * MAX_SIZE1 * (MAX_SIZE2 - 1) + 1] = "";

Uninitialized strings typically contain rubbish, and strcat adds to it, rather than removing it.
In addition, if you want delimiters, you should code that explicitly; strcat doesn't add any delimiters itself:
strcat(s, ",");


text:
Q: How to integrate D3@4.2.2 with Angular@2.0.0-rc5 and angular-cli@webpack I have been able to integrate D3@3.5.15 with Angular@2.0.0-rc5 and angular-cli@latest (the last version prior to webpack).
Shortly after the release of Angular@2.0.0-rc5, the angular-cli folks went all in up with a WEBPACK-centric release. I've spent quite a bit of time trying to get D3@4.2.2 to work in this environment with any success. Basically I have not been able to figure out how to expose D3 modules and functions in this environment.
Any help would be much appreciated.
Regards
Rodrigo

A: I followed this to install d3: https://github.com/angular/angular-cli#3rd-party-library-installation
Then in my chart component, I import d3 like this:

import * as d3 from 'd3';

d3 works; however, I am getting errors in the console:

Property 'axisBottom' does not exist on type 'typeof d3'.

I am curious to see if you will get the same error messages...


text:
Q: What is the best way to diagrammatically represent a system threading architecture? I am yet to find the perfect way to diagrammatically represent the overall threading architecture for a system (using UML or otherwise).
I am after a diagramming technique that would show all the threads in a given system and how they interact with each other. There are a few similar questions - Drawing Thread Interaction, UML Diagrams of Multithreaded Applications and Intuitive UML Approach to Depict Threads but they don't fully answer my question.
What are some of the techniques that you've found useful to depict the overall threading architecture for a system?

A:
What are some of the techniques that you've found useful to depict the overall threading architecture for a system?

By not treating it special. Elements in the architecture send messages to one another; if that's across a thread boundary (or even a system boundary) doesn't really matter from an architectural perspective.
As far as implementation goes, it doesn't matter. Implementation is done at the module level. Black Box A presents some interface and consumes some other Black Box. Make a note that the interface it consumes or provides is required to be (non)blocking and/or threadsafe and be on your way.
Otherwise, consider it a design smell if those threading details are leaking through your abstractions.


text:
Q: How to change the size of font appearing on the installer window in nsis ? I have developed my own language file for HINDI language and it's working fine. I have created two files in NSIS Contrib folder one is .nsh and second is .nlf. And its font size is default. But when I use my own language in installer, the font size of my language looks relatively small to the english languge. see below how it looks like-

In above image the second language font looks small relative to english and it's hard to read. Similar things happen on other pages like below-

Can anyone tell me how to increase this font size of my own language. where can I do this setting or what setting should I do in my language file so that the font size will look big??

A: Near the top of the .nlf file there should be a section that looks something like this:
# Font and size - dash (-) means default
-
-

You can replace the first line with a font name if you want to force a specific font and the second line is the font size.
For example, the Japanese .nlf looks like this:
# Font and size - dash (-) means default
MS Pゴシック
9

but it would also be legal to leave the name as - and just set the size.


text:
Q: Some websites not using an internet connection on Chrome It's been a while since I've had this problem. Whenever I connect to some websites on Chrome, it doesn't use the internet at all (there is zero data being transferred for Chrome). However, when I try connecting to the same website via Safari, it works just fine. I've tried clearing my browser history and cache, but it still doesn't work.
Also, for some web pages, I can't connect when I try to go to the page directly by typing the URL in the address bar, but I can load the page just fine if I connect via clicking the URL button on another page.
Is there some way I can diagnose this problem? I think there's something wrong internally with Chrome on my MacBook but I don't know how to monitor the Chrome processes.


text:
Q: How to use Django/Rest Framework to search a database table without specifying a column? Initial question:
Following the Django documentation, to get a QuerySet of blog entries from the year 2006, we can use filter() like so:
Entry.objects.filter(pub_date__year=2006)

Retrieving specific objects with filter, it is assumed that we know which column to search in.
How can we search for an object if we do not know which column it could be in?
For a small number of columns, we could chain the filters like so:
Entry.objects.filter(column1='foo').filter(column2='foo')

With +30 columns, this seems highly repetitive. What is a better way of doing this?
A follow up question:
Given that in urlpatterns we find the following path:
path('foo/bar/<str:object>/', views.ViewObject.as_view())

And ViewObject uses the Rest Framework generic views:
class ViewObject(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = ObjectSerializer
    ...
    queryset = ?

How can we construct the ViewObject view such that parameter <str:object> is used to search for a value in all columns of a database table?

A: For the first question as far as I understand you would like to create a searchbar or something similiar to that so it looks like what you are looking for is full text search in django. Example usage:
from django.contrib.postgres.search import SearchVector
>>> Entry.objects.annotate(
...     search=SearchVector('field_one', 'field_two'),
... ).filter(search='string')

SearchVector takes fields as args that will be looked in, and filter(search='string') actual string to look up and this will return a queryset.
You can create better queries and order results with SearchQuery and SearchRank.
Here is the documentation.
For the second question there is a 3rd party package called django-filter. DRF documentation mentions it in filter api tutorial but you can check out documentation from here

A: I could have commented but am not allowed. You can try the following link pass all fields of model in django filter backend
class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = [f.name for f in User._meta.get_fields()]


text:
Q: TextInputLayout: Is it possible to have different font between input field and hint text? I have a textInputLayout with a TextInputEditText.
I would like the hint text to be in Roboto and the edit field (the text that user is entering) to be of a custom font, but can't seem to get it working. Somehow if I try to set a font on the TextInputEditText it also affects the hint text's font.
Anyone know how to get this issue solved?
*** edit: Found some weird thing. When I set the inputType to textPassword on the TextInputeditText (and have my custom font set on same widget via fontFamily=".." then I do have two different fonts on hint and edit field?!! But unfortunately for any other input type and in my case I need inputType="textEmailAddress" the hint text changes to same font as TextInputEditText

A: I found the solution:
You need to set typeFace on the TextInputLayout programmatically for the font you want for the hint text.
The font for the TextInputEditText fields can be set directly in either xml or programatically.

A: Default EditText does not offer a method to set the Typeface of the hint only, but if you set a custom typeface to your EditText, all the text fields are affected.
To obtain what you want, you need to define a custom TypefaceSpan and a SpannableString, as suggested in this topic.
Please have a look at francisco_ssb answer.


text:
Q: How to geocode a phone number in the United States? I am looking for a way to get the latitude and longitude coordinates of any area code + prefix land line phone in the United States.  Does anyone know of a data provider or service that could be used to do this?
EDIT:  I understand that the location of cell phones or VOIP lines probably cannot be geocoded and this is fine by me.  I am only interested in POTS phone numbers.  Although, it would be nice to be able to identify the type of phone service based on the prefix (if this is even possible).

A: There are websites that do this, for example http://www.thedirectory.org [edit: link is no good now]. I have no idea if they have anything like a RESTful api you could use, although I guess you could always screenscrape them. Presumably the raw data that they're using should be something you could obtain yourself, possibly from the phone company.

A: I found a few options that do the trick for a reasonable price:
Option 1 (web service subscription):
Service Objects DOTS GeoPhone [edit: link is no good now] web service should do the trick nicely.  It even seems to provide the "telephone service type" information that I was hoping for.
Option 2 (database subscription):
AreaCodeWorld™ Platinum Edition [edit: link is no good now] is a database product that can be purchased on a one-time basis or via annual subscription.  The data spec includes all North American area codes and prefixes along with latitude & longitude coordinates.

A: Using the Google Geocoding API and the list on the side of allareacodes.com, I created this json for a hacker project:
http://pintweets.com/area_codes.json [edit: link is no good now]
Clearly, this is not court-admissible evidence, but it should work for certain purposes.

A: [EveryoneAPI][1] [edit: link now goes to a new site not related] will do exactly what you're looking for.
You can limit your query to location-only by adding "data=location" to your HTTP request, and you'll get back something like this:
"location": {
  "city": "Birmingham",
  "geo": {
    "latitude": "33.51685254860801",
    "longitude": "-86.81075983815001"
  },
  "state": "AL",
  "zip": "35203"
}

Disclaimer: I am the CEO of Telo.
[1]: https://www.everyoneapi.com/

A: There's publicly available geocode data for zipcodes (although the location they give is the geocode for the corresponding post office), so you might be able to build a correspondence that way (although you'd have to pick the specific zip more or less at random, as there are many more zips than area codes).
However there's going to be some built in error. Some numbers (e.g. 800 numbers) don't have a specific location by design. Same with cell numbers. In NY, in any case, there are cell #'s that start with the same areacode as NY-located phone #'s (e.g. 718, 212). I'm not sure if the carriers are required to provide those #'s in a way that corresponds with the customers billing address, either, so you might get a situation where most of the 212 #'s are NYC but some are cell phones in Wichita.


text:
Q: playframework, input disabled breaks play from passing the value? I have an input field that is filled in from a previous form(so the input is set to disabled on the second page) and we receive null for the value then. This works:
<input type="text" class="boxtpl" name="${field.name}" value="${user?.email}">

but this doesn't:
<input type="text" class="boxtpl" name="${field.name}" value="${user?.email}" disabled="disabled">

Is there a reason why this seems to break the framework?

A: Disabled controls shouldn't actually be submitted with the form, so what you're seeing is in fact normal behaviour. According to the HTML form specification:

When set, the disabled attribute has the following effects on an element:

*

*Disabled controls do not receive focus.

*Disabled controls are skipped in tabbing navigation.

*Disabled controls cannot be successful.

The definition of successful can be found in the same document. It's a bit nonsensical to suggest that Play is broken because of this.
If you want to have a form field that user cannot edit while it should still be sent along when the form is submitted, you can use the read-only attribute, or use JavaScript to disallow user input.
Update: as pointed out in the comments, the following points may also offer a solution:

*

*It's possible that Play still keeps the disabled control's form values in the request object, and just doesn't bind them (so you could retrieve them from the request if needed)

*Use a hidden field to keep the form value in case you still want to submit the value, but do not want the user(s) to see the control


text:
Q: Callback inside loop variable value resolved wrong Supose I've:
var items = {
  '1': {
    id: 1
  },
  '2': {
    id: 2
  },
}

for (var item in itemns) {
  var item = items[item];

  $(object).on('signal', function () {
    doSomethingElse(item.id);
  });
}

Always doSomethingElse is called with id = 2, I know why it happens, but how can I avoid this in other words how can i workaround this ?


text:
Q: Varchar to Datetime format I need to convert my Registrationdate(varchar)column in Table1 to Registrationdate(datetime)format in Table2. I need to use that in insertion code.
Insert Full_patient_reg (Patient_id,RegistrationDate,PatientName)
    select a.PATIENT_ID,a.REGISTRATIONDATE,a.PATIENTNAME from hinai_patient a
    where a.PATIENT_ID not in
    (select Patient_id from Full_patient_reg where a.PATIENT_ID=Patient_id)

It cause the error like 'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.'
Please suggest a code which act in insert code.
Dateformats (varchar)
2011-08-01 00:00:00
2000-11-16 07:39:44
2020-06-06 07:51:42.644
2020-05-26 06:55:38.08

A: Simple convert seems to be working fine:
select convert(datetime, RegistrationDate)

Please find the db<>fiddle here.


text:
Q: Laravel 5 - how to authenticate without email confirmation? I'm creating a simple authentication system in Laravel 5.  I have authentication code written in Laravel 4 that I'm using as a foundation.
My problem is,

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'confirmed' in
  'where clause' (SQL: select * from users where email =
  myemail@gmail.com and confirmed = 1 limit 1)

It looks like Laravel is looking to see if my email was verified.  But I do not need to implement a sign-up and verification process for this application.  My question is, how do I tell laravel not to worry about email confirmation?
My authentication code looks like this:
public function postAuthenticate()
{
    // Fetch posted credentials

    $email = \Request::input('email');
    $password = \Request::input('password');
    $remember = \Request::has('_remember');

    $credentials = [
        'email' => $email,
        'password' => $password,
        'confirmed' => 1
    ];

    // Attempt to log in user
    if (\Auth::attempt($credentials, $remember))
    {
        return \Redirect::intended('dashboard');
    }

    // If this code was reached, it means that the user failed to authenticated.
    // In this case, redirect back to the login page with errors.

    $messages = new Illuminate\Support\MessageBag;
    $messages->add('Authentication Error', 'Sign in failed.');

    return \Redirect::to('/login')
        ->withInput()
        ->with('errors', $messages);
}

And my user model looks like:
<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

}

And finally, my user table migration is:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

}

Thanks!

A: You have to remove 'confirmed' => 1 from $credentials.
For example:
$credentials = [
        'email' => $email,
        'password' => $password
];


text:
Q: Topmost window focus I have a very strange issue.
I have two application.
For example:
Process1.exe launching Process2.exe. (This is done using Process.WaitForExit(), Process1 will wait till Process2 gets closed.)
Sample code for this case.
Process p = new Process();
p.StartInfo.FileName = strFilePath;
string strDirectory = System.IO.Path.GetDirectoryName(strFilePath);
p.StartInfo.WorkingDirectory = strDirectory;
p.Start();
p.WaitForExit();

Here assume that Process2.exe launching multile windows. (Assuming 3 windows)
Now from the 3rd window in the Process2.exe, we are launching remote desktop using a pre-configured RDP(Remote Desktop Protocal) file.
This is done by using the below code.
System.Diagnostics.Process remoteWindow = new System.Diagnostics.Process();
remoteWindow.StartInfo.FileName = MSTSC_PROCESS_NAME;
remoteWindow.StartInfo.Arguments = strUrl;
remoteWindow.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
result = remoteWindow.Start();

Now the issue is when we close the remote desktop window, focus is moving to Process1.exe. Actually windows should retain focus on Process2.exe
Also, this issue is not occuring in all kind of PC's. This issue is occurring specifically in Panasonic CF-C1 laptop.
OS: Windows 7
Is this a windows related issue?  or Any suggestions will help.


text:
Q: Paste an HTTP request directly into postman to send By an http request, I mean something like:
POST /service/controller.asmx/endpoint HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: ...

xmlFile=string&xmlFile=string

Is there a way to paste a request in this format into postman to send, like I can paste into the Body tab?
I can go the other way around and get a string like this by going to the Code button and selecting HTTP from the dropdown, but pasting into that box seems not to take.
I want to do this to avoid going to each tab seperately and configuring each thing individually, including the URL and request type.

A: No, you cannot paste that string into Postman.
You should consider pasting the cURL version of the code into your terminal (if you use Linux).
It's enough for quick one-offs.


text:
Q: Symbol raised to the power of asterix raise to the power of asterix in regex To describe the regex (a*+b+a)* in plain English you would simplify it to (a*)* + (b)* + (a)* . How would you describe (a*)* in English as the rest is just any number of bs or any number of as?

A: In your first step you distributed the Kleene star over $+$, but note that that does not hold in general. The string $aaaba$ is a member of the first language but not the second.
What you are allowed to do is observe that having the $a^*$ inside the brackets is redundant, since we can already take an arbitrary number of powers of $a$ using the outside Kleene star. So this language is the same as $(a+b)^*$. The second language is equivalent to $a^*+b^*$, which as I noted before is not equal to $(a+b)^*$.
To answer your second question, $(a^*)^*$ is simply the same as $a^*$; both include any number of $a$s.


text:
Q: Recover Apple CoreStorage Volume, LVG, Logical Volume Group -container / partition / volume I wasn't able to mount the disk on my MacBook (I had removed both hard drives from iMac, since it's logic board went bad and I thought not to put more money on Apple products due to such bad hardware performances that I recently experienced for 2015 iMac and 2018 MacBook Pro).
So for data recovery from Harddrive and make it mountable after I connected both on my MacBook Pro from thunderbolt ports using their apdaters:

*

*I create a coreStorage named FUSION using "diskutil coreStorage create FUSION /dev/disk2 /dev/disk3". i.e. disk2 - 128GB and disk3 - 2TB

*It looked good, So I thought of shortcut by simply trying "First Aid" on diskutil for the drive to be able to make Drive mountable.

*It ran without error but  it created an empty new volume of total 2TB and I wasn't able to see any of my old files in it.

*So upon try to undo this FUSION volume, I accidentally ran "diskutil cs deleteLVG [Logical volume Group guid id]".

*Now I do not want to perform any thing unless I make sure I am right and restore the container and partitions that existed.
Anyone can please help me with good suggestion to restore my partition and make my disk mountable?


text:
Q: Grammar matters - explanation of example I just stumbled over this from http://braythwayt.com/2015/05/04/grammar-matters.html :

*

*"I'd like to thank the employees of FormerCo, who made me feel that my contribution mattered."

*"I'd like to thank the employees of FormerCo who made me feel that my contribution mattered."
One is a lovely tribute to a good company's people. The other is a passive-aggressive criticism of a flawed company's toxic culture.
Grammar. Matters.

I am not an English native speaker and I do not get how that comma would discriminate a passive-aggressive tweet from a employee-praising tweet.
Can somebody explain?

A: It's a bit of a stretch, but I can see the point.

I'd like to thank the employees of FormerCo, who made me feel that my contribution mattered.

With the comma, the second clause applies to all the employees of FormerCo, implying that they're all good people.

I'd like to thank the employees of FormerCo who made me feel that my contribution mattered.

Without the comma, the second clause implies that only some of the employees of FormerCo had this effect and that most (or at least some) of them did not.


text:
Q: Use SYS_REFCURSOR with CTE (includes Update statement) I am using CTE to fetch some values and then using UPDATE statement to clear the returned values from database table.
This is happening inside a stored procedure.
UPDATE TABLE1
   SET AA = NULL, BB = NULL
 WHERE EXISTS
          (WITH T1 AS (SELECT AA, BB, CC FROM TABLEABC)
               ,T2
                AS (SELECT AA, BB, CB
                      FROM T1
                     WHERE T1.AA > 100)
           SELECT *
             FROM T2
            WHERE TABLE1.CC = T2.CC

My column BB has some identification data which I want to capture before it is cleared by the Update statement. Can anyone guide me on how I can capture this column data and return as Procedure output.
OPEN SYS_REFCURSOR FOR

A: Unfortunately, the RETURNING INTO clause of an UPDATE statement will give you the values after the update, not the prior values.
So, if you want to save off the old values, you must do so before the UPDATE statement.  Take care to lock the rows and only actually update rows that you've saved, because it is possible that your table could be modified between the time you save off the data and the time to update it.
Then, return the saved data in a ref cursor.
Here is code that puts that all together:
CREATE TABLE TABLE1 ( AA number, BB number );

CREATE OR REPLACE PACKAGE so_test AS

  TYPE TABLE1_LIST_TAB IS TABLE OF TABLE1%ROWTYPE;

  FUNCTION do_it return sys_refcursor;

END so_test;

CREATE OR REPLACE PACKAGE BODY so_test AS

  FUNCTION do_it RETURN SYS_REFCURSOR IS
    l_old_data TABLE1_LIST_TAB;
    l_rc SYS_REFCURSOR;
  BEGIN

    SELECT AA, BB
    BULK COLLECT INTO l_old_data
    FROM table1
    WHERE -- put your conditions here of what you intend to update
    FOR UPDATE;

    UPDATE TABLE1
      SET AA = NULL, BB = NULL
    WHERE EXISTS ( SELECT 'record old data is captured'
                 FROM   TABLE(l_old_data) od
                 WHERE  od.aa = table1.aa   -- Assuming AA is a primary key
               )
    RETURNING AA, BB BULK COLLECT INTO l_old_data;

    OPEN l_rc FOR SELECT * FROM TABLE(l_old_data);

    RETURN l_rc;

  END do_it;
END so_test;

NOTE: if you are not on 12c, you will need to define TABLE1_LIST_TAB as an OBJECT type in the database instead of in the package spec, or else the package body won't compile.


text:
Q: Move Files That Do Not Exist I need copy files from my local hard drive to an external hard drive.  My thought is, I only want to copy the files that do not currently exist.  I am sure there is a much easier way to do as such, but this is where my mind went first.
My thoughts on how to accomplish this:
1) Get a list of all files on my C: drive and write to a text file
2) Get a list of all files on my L: drive (backup) and write to a text file
3) Compare C: drive text file to L: drive text file to find the files that do not exist
4) Write results of the files that do not exist to an array
5) Iterate through the newly created array and copy the files to the L: drive
Is there a more effective/time efficient way to accomplish this task?

A: For sure you don't want to create text files listing file names, and then compare them. That will be inefficient and clunky. The way to do this is to walk through the source directories looking for all the files. As you go, you'll be creating a matching destination path for each file. Just before you copy the file you need to decide whether or not to copy it. If a file exists at the destination path, skip copying.
Some enhancements on that might include skipping copying only if the file exists and the last modified date/time and file size match. And so on, I'm sure you can imagine variants on this.
One thing that you might not want to do is build a list of all the files first, and then start copying. It may very well be more efficient to copy files as you are iterating over the source directory. For example you could use Directory.EnumerateFiles to do this in an efficient way.
Of course, you don't need to write a program to do this. Thousands already exist, some of which are quite effective.


text:
Q: Proper use of prolonged I have seen examples of using prolonged with negative connotations. If a relationship between two countries is cordial and last for more than five centuries is it correct to use the phrase " prolonged relationship"?

A: Prolonged definition:
Cambridge: continuing for a long time.
Oxford: continuing for a long time or longer than usual; lengthy.
Example usage:

*

*Prolonged use of the drug is known to have harmful side-effects. (negative connotation)

*With proper care prolonged battery life can be ensured. (Positive connotation)
Its evident that "Prolonged" is an adjective that is used to define the lengthy duration of something irrespective of the positive/negative meaning of the context.
So yes, It is correct to use "Prolonged relationship".
However, in this particular case "Prolonged" may not be the best option. As suggested by Kris, you may go for sustained, lasting, long lasting etc.

A: As 'prolonged' simply means longer than expected, or longer than initially planned, it has no inherent negative connotations, so in this example you could use 'prolonged relationship.'
As Kris comments, though, there are some words which have a definitely positive connotations. 'Enduring,' does imply being strong enough to hold through challenge,  so it may be more appropriate here.


text:
Q: Angular 10 on IIS - cannot open link (component) in new tab, always redirected to index/404.0 error displayed In my Angular application deployed on IIS I want to open link 'Contact' in new tab via the following link:
<a [routerLink]="['/contact']">Contact</a>

The problem is that in the new tab I find index page. Previously I had a problem with refreshing page which I solved by this given to web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/index.html" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

</configuration>

After reading many inputs on stackoverflow and elsewhere I suspect this setting to be responsible for this behavior, but am not sure.
Is there a way to combine correct behavior of refresh and ability to open link in new tab in Angular app deployed to IIS?
EDIT
Now I understand the construction. It means if I try to access anything except file or directory, my request is redirected to index.html.
I added (prepended) another rule to avoid redirecting:
<rule name="Contact link" stopProcessing="true">
  <match url="contact" />
  <action type="None" />
</rule>

This ensures that any request to contact page is not redirected. But at the same time, for obvious reason, I get a 404.0 error, because no index file is found at that location.
So new question is: Is there any way how to open angular component in new tab?


text:
Q: Scalatest from Maven: How to tag and filter out an entire Suite? I have a Maven project and I'm using the scalatest-maven-plugin to configure scalatest. I'm using scalatest 3.0.0 however I can't manage to tag and filter out an entire Suite.
As reference, I have used the blog Tag a whole ScalaTest suite (update for Java 8) but this doesn't seem to work from Maven.
I created a new Skip tag defined as follows:
package tags;

import java.lang.annotation.*;

@org.scalatest.TagAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Skip {}

Then I tag my test Suite like this:
@tags.Skip
class AcceptanceTest extends FeatureSpec { ...

I then configure my scalatest-maven-plugin like this:
<plugin>
    <groupId>org.scalatest</groupId>
    <artifactId>scalatest-maven-plugin</artifactId>
    <configuration>
        <tagsToExclude>tags.Skip</tagsToExclude>
    </configuration>
    <executions>
        <execution>
            <id>test</id>
            <goals>
                <goal>test</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Then running mvn clean install -X I see (which correctly passes the -l Tag exclusion CLI argument to Scalatest):
[DEBUG] Forking ScalaTest via: cmd.exe /X /C "java -Dbasedir=mydir
        org.scalatest.tools.Runner -R -l tags.Skip ...

but the AcceptanceTest Suite gets nevertheless executed. I have also tried tagging the Suite like this without success:
class AcceptanceTest extends Tag("tags.Skip") with FeatureSpecLike { ...

A: To separate execution of integration tests I used maven profiles:
    <profiles>
    <profile>
        <id>default-test</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>net.alchim31.maven</groupId>
                    <artifactId>scala-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>org.scalatest</groupId>
                    <artifactId>scalatest-maven-plugin</artifactId>
                    <version>1.0</version>
                    <configuration>
                        <reportsDirectory>${project.build.directory}/surefire-reports</reportsDirectory>
                        <junitxml>.</junitxml>
                        <filereports>WDF TestSuite.txt</filereports>
                        <tagsToExclude>org.example.testkit.annotations.IntegrationTestSuite</tagsToExclude>
                    </configuration>
                    <executions>
                        <execution>
                            <id>test</id>
                            <goals>
                                <goal>test</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
    <profile>
        <id>integration-test</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>net.alchim31.maven</groupId>
                    <artifactId>scala-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>org.scalatest</groupId>
                    <artifactId>scalatest-maven-plugin</artifactId>
                    <version>1.0</version>
                    <configuration>
                        <reportsDirectory>${project.build.directory}/surefire-reports</reportsDirectory>
                        <junitxml>.</junitxml>
                        <filereports>WDF TestSuite.txt</filereports>
                        <tagsToInclude>org.example.testkit.annotations.IntegrationTestSuite</tagsToInclude>
                    </configuration>
                    <executions>
                        <execution>
                            <id>test</id>
                            <goals>
                                <goal>test</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

Then I marked integration tests accordingly
@IntegrationTestSuite
class ExampleTest extends PropSpec with MockitoSugar with BeforeAndAfterAll with EndpointTestHelper {

to run unit tests I run
mvn test

for integration tests
mvn test -Pintegration-test

UPD:
package org.example.testkit.annotations;

import org.scalatest.TagAnnotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@TagAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface IntegrationTestSuite {}

We use scala 2.11, scalatest 2.2.6, maven 2, java 8.

A: You can pass tags that you need dynamically without creating new profiles:
<plugin>
    <groupId>org.scalatest</groupId>
    <artifactId>scalatest-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>test</id>
            <goals>
                <goal>test</goal>
            </goals>
            <configuration>
                <tagsToInclude>${tagsToInclude}</tagsToInclude>
                <tagsToExclude>${tagsToExclude}</tagsToExclude>
            </configuration>
        </execution>
    </executions>
</plugin>

Some tag definition example:
package com.foo.tags;

import org.scalatest.TagAnnotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@TagAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Skip {}

And finally you can pass your tags from CLI dynamically in the following way:
mvn -DtagsToExclude=com.foo.tags.Skip test


text:
Q: Can receive messages using cli, but not getting messages from kafka python I am using AWS MSK Kafka managed streaming service and all of a sudden I am not receiving any messages through my consumer. I am using kafka-python and the weird thing is that when I open up my cli and create a new consumer with the exact same code, I receive the messages just fine. If I restart the kafka broker, only then will I get messages. Any idea what the issue could be?
>>> consumer = KafkaConsumer(
...                 bootstrap_servers=[...],
...                 auto_offset_reset='earliest',
...                 enable_auto_commit=True,
...                 group_id='my-client-id',
...                 api_version=(2, 2, 1))
>>> consumer.subscribe(['hello_world', 'foo_bar'])
>>> for message in consumer:
...     print(message)


text:
Q: $\mathbb{Q}[x,y]/(y)$ is isomorphic to $\mathbb{Q}[x]$ How can I show that $\mathbb{Q}[x,y]/(y)$ is isomorphic to $\mathbb{Q}[x]$ as rings?

I know that first isomorphism theorem is required here but I could not find the proper homomorphism.

A: $\mathbb Q[x,y]\to\mathbb Q[x]$, $f(x,y)\mapsto f(x,0)$ is a homomorphism that is onto and has precisely $(y)$ as kernel.

A: And to see what this map does in a slightly different way: note that $(y)$ consists of all polynomials with the shape $y p(x,y)$. When we reduce an element $f(x,y) \in \mathbb{Q}[x,y]$ modulo $(y)$, we're free to throw away any part of it that's in $(y)$. So any term in $f$ with a $y$ in front of it is redundant in the quotient. Thus we end up with a unique representative that only has $x$ terms, and moreover there is essentially no other restriction. The most succinct way to do this is as rendered in the other answer.


text:
Q: Is there another way to cut the numbers after the 10th decimal without callig round()? I wanted to create a function that whatever the number received as input, it would cut-off (not round, which could take some decimal higher) every number after the 10th one. It normally works fine, but if I call the function with a number like this:
1234567.123456789123456789
It returns: 1234567.1234567892
And not 1234567.1234567891, as expected.
def cut_to_10(number):
    number = str(number)
    j = 0
    if "." in number:
        for i in number:
            j += 1
            if i == ".":
                before_dot = number[:j - 1]
                after_dot = number[j:]
                if len(after_dot) > 10:
                    after_dot = after_dot[:10]

                return float(before_dot + "." + after_dot)

    if "." not in number:
        return round(float(number), 10)

EDIT 1:
Also tried this, and the same unexpected result returned.
import numpy as np

def cut_to_10(number):
    return np.floor(number * 1e10) / 1e10

EDIT 2:
Considering the amazing explanation given by ShadowRanger, but, considering also that I need more a ceiling precision than a floor one, and given the fact that I still had to work with float, I just decided to change
return float(before_dot + "." + after_dot)
to
return float(before_dot + "." + after_dot) - 2e-10
and it worked fine. 1e-10 didn't work.

A: 1234567.123456789123456789 is not an actual float. You can type it, but it becomes 1234567.1234567892, the closest representable float value; the rounding is occurring before you actually call round.
>>> 1234567.123456789123456789
1234567.1234567892

If you need that much precision, you need to move to decimal.Decimal, which will work just fine:
>>> decimal.Decimal('1234567.123456789123456789')
Decimal('1234567.123456789123456789')

>>> round(_, 10)
Decimal('1234567.1234567891')

Just don't convert back to float, because 1234567.1234567891 doesn't exist (if it did, that's what 1234567.123456789123456789 would have produced), and you'll be back where you started with 1234567.1234567892.

A: See the other answer for the correct solution. Leaving this one up just because it seems like a more straightforward approach to doing the truncation once you work past the floating point limitation.
import numpy as np

def cut_to_10(number):
    return np.floor(number * 1e10) / 1e10


text:
Q: Chrome Extension : How do I get previous entries and list them on the pop-up? / FIXED I've been trying to learn how to code a Chrome Extension with Javascript and I am stuck now so I would like your help please :)
What am I trying to do is to list comments/memos inside the extension popup.
The comment (input value) is store in localStorage.

    function hello()
            {
            var greetings = "";

            if(localStorage['comment']){
                    var addComment = localStorage['comment'];
                }else{
                    addComment = "";
                };

            greetings = 'Your post : ' + addComment;

            return greetings;
            };

    function createIntro(){
        var content = document.createElement("div");
        content.style.width = '220px';
        content.appendChild(document.createTextNode("Hello, " + hello()));
        container.appendChild(content);

        return content;
    }

    var container = document.getElementById("intro");

    document.getElementById("submit").addEventListener("click",function(e){
        localStorage['comment'] = document.getElementById('comment').value;
    var commentList = createIntro();
    container.insertBefore(commentList, container.firstChild);
    e.preventDefault();
    });
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>extension</title>

    <input type="text" name="comment" id="comment" placeholder="Write anything"/>
    <input type="button" value="save" id="submit"/>

So far I've only managed to get the last entry displayed but it's not what I want.
Now I can list them when I click on the save button but when I close the popup and open it again they aren't here :(
Is there anyone who can point me to the right direction and tell me what I'm missing please ?
Thank you ! :)


text:
Q: Paypal sandbox exchange rate is two times the real one Paypal sandbox acts weirdly:
I make payment of 700 RUB(Russian currency) to USD Seller account.
700 RUB in the real world is something around 10 USD, but when I make this payment in sandbox I got the conversion to 22.55 USD. I would understand difference +/-10%, but this is more than double the real price. Unfortunately I can't test such conversion on the real paypal accounts now, but paypal guy says that "the currency conversion you see in Sandbox accurately reflects our rates at that time." - https://www.paypal-community.com/t5/Selling-on-your-website/Completely-inaccurate-currency-conversion/td-p/184328?profile.language=en-gb
So how is it possible and what is the problem? Did anyone have this issue?

A: There's an API you can use to get the real time conversion rate that PayPal uses https://developer.paypal.com/webapps/developer/docs/classic/api/adaptive-payments/ConvertCurrency_API_Operation/


text:
Q: I am trying to upload my data to php my admin using a modal but unable to do. I don`t know which error I am getting . Help me this I am trying to submit data but data is not updated in php my admin. Can anyone help e with this where I am getting Error.
I have tried many ways but unable to locate my error.
Below is my function I want to submit a form :
    function add_ip() {

if(isset($_POST['add_ip'])) {

$name           = escape_string($_POST['name']);
$gender         = escape_string($_POST['gender']);
$age            = escape_string($_POST['age']);
$diagnosis      = escape_string($_POST['diagnosis']);
$date           = escape_string($_POST['date']);
$room           = escape_string($_POST['room']);
$doctor         = escape_string($_POST['doctor']);
$nurse          = escape_string($_POST['nurse']);

$query = query("INSERT INTO ipd(name,gender,age,diagnosis,date,room,doctor,nurse) VALUES('{$name}','{$gender}','{$age}'),'{$diagnosis}','{$date}','{$room}','{$doctor}','{$nurse}'");
confirm($query);

set_message("Patient Added");

redirect("ipd.php");

}

}

FORM:

                        <?php add_ip(); ?>

                                <input type="text" class="form-control" name="name" placeholder="Patient Name" required autofocus>

                            <input type="radio" name="gender" id="male" class="with-gap">

                            Male

                            <input type="radio" name="gender" id="female" class="with-gap">

                            Female

                                <input type="text" class="form-control" name="age" required>

                                Age

                                <input type="text" class="form-control" name="diagnosis" required>

                                Probable Diagnosis

                                <input type="text" class="form-control" name="date" required>

                                Date of Admission

YYYY-MM-DD format

                                <input type="text" class="form-control" name="room" required>

                                Room Number

                                <input type="text" class="form-control" name="doctor" required>

                                Reporting Doctor

                                <input type="text" class="form-control" name="nurse" required>

                                Assigned Nurses

                        <input type="submit" name="submit" class="btn btn-primary" >

                    </form>

I am trying to submit data but data is not updated in php my admin. Can anyone help e with this where I am getting Error.
I have tried many ways but unable to locate my error.

A: You need to remove paranthesis after '{$age}' and add it after the '{$nurse}'
VALUES('{$name}','{$gender}','{$age}','{$diagnosis}','{$date}','{$room}','{$doctor}','{$nurse}')

A: First print the POST data , in your function so that you will get to know that whether you are getting data correctly or no,
once you get the data.
There is one error in your Sql query
  ,'{$age}'),'{$diagnosis}',

here you have added UN-necessary ")" please remove it, and check

A: You recieve $_POST('add_ip') in function but you haven't send anything like add_ip in form
and try to print your sql query and check in mysql/phpmyadmin whether your query works proper or not.


text:
Q: Jmeter test failed with only 5 thread I am new into Jmeter and trying to do my first load test, When I get my data from website it is always come in .txt form and when this data I try to run my test it fails,

A: It's hard to say what is wrong without seeing the "Sampler result" tab screenshot for at least one failed sampler.
Going forward consider providing as much information as you can, i.e.:

*

*Screenshot of the HTTP Request sampler

*Screenshot of the View Results Tree listener demonstrating Sampler result, request data and headers and response data

*At least relevant parts of the jmeter.log file, better with the debug logging for the test elements involved enabled


text:
Q: Flow finish behavior - flow called by custom URL button I have a Visual Flow that is triggered by a Button on a record.  The flow sends an email notification and posts to chatter (without requiring any user input).  When the flow is finished I just want the user to end up back on the same record they started from, but using retURL is giving me some extra page reloads
the button URL is
/flow/Send_email_notification_to_merchandiser?MerchWorkOrderID={!Merchandiser_Work_Order__c.Id}&retURL=/lightning/r/Merchandiser_Work_Order__c/{!Merchandiser_Work_Order__c.Id}/view

and the syntax of the retURL is
/lightning/r/Merchandiser_Work_Order__c/{!Merchandiser_Work_Order__c.Id}/view

Ultimately, the user does end up on the correct Record page, but I'm hoping to avoid all of the "screen flashes".  Any tips?

A: I think you just need to you Id of your record. See below
/flow/Send_email_notification_to_merchandiser?MerchWorkOrderID={!Merchandiser_Work_Order__c.Id}&retURL={!Merchandiser_Work_Order__c.Id}


text:
Q: Why Do I need default value in WithMockCustomUser? I made a test Using @WithMockCustomUser annotation.
Since My Service Logic needs User's email, I needed to make CustomSecurirtyContextFactory.
So I made it and Use it in WithMockCustomUser
What I'm wondering is that why should I need default value in WithMockCustomUser?
I've already set values in CustomUserDetails in WithMockCustomUserSecurityContextFactory..
I've checked values and find out that default values are not used..
Test is using values in CustomUserDetails
so those default values looks meaningless to me.
Let me show you my code
Service I'm trying to test
public class CommentService {

    private final CommentRepository commentRepository;
    private final PostsRepository postsRepository;
    private final UserDetailService userDetailService;

    @Transactional
    public Long commentSave(CommentSaveRequestDto requestDto, Long id) {
        Posts post = postsRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("해당 게시글이 존재하지 않습니다"));
        requestDto.setPosts(post);

        User user = userDetailService.returnUser();
        requestDto.setUser(user);

        return commentRepository.save(requestDto.toEntity()).getId();
    }

UserDetailService used In above service
@RequiredArgsConstructor
@Service
public class UserDetailService implements UserDetailsService {

    private final UserRepository userRepository;

    public User returnUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName;

        if (principal instanceof UserDetails) {
            userName = ((UserDetails) principal).getUsername();
        } else {
            userName = principal.toString();
        }

        System.out.println("유저 : " + userName);

        int start = userName.indexOf("email")+6;
        int end = userName.indexOf(".com,")+4;
        String email = userName.substring(start, end);

        System.out.println("이메일 : " + email);

        User user = userRepository.findByEmail(email).orElse(null);

        return user;
    }

    public Principal returnPrincipal() {
        return (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}

WithMockCustomUser
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class, setupBefore = TestExecutionEvent.TEST_EXECUTION)
public @interface WithMockCustomUser {
    String name() default "testName";

    String email() default "testEmail@naver.com";

    Role role() default Role.USER;
}

WithMockCustomUserSecurityContextFactory used with WithMockCustomUser
class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<CommentsApiControllerTest.WithMockCustomUser> {
    @Override
    public SecurityContext createSecurityContext(CommentsApiControllerTest.WithMockCustomUser customUser) {
        SecurityContext context = SecurityContextHolder.createEmptyContext();

        CustomUserDetails principal = new CustomUserDetails();
        Authentication auth =
                new UsernamePasswordAuthenticationToken(principal, "password", principal.getAuthorities());
        context.setAuthentication(auth);
        return context;
    }
}

CustomUserDetails used in WithMockCustomUserSecurityContextFactory above
@Getter
class CustomUserDetails implements UserDetails {

    public  String name = "ㅇㅇ";
    public String email = "1park5@naver.com";

    public String role  = Role.USER.toString();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        ArrayList<GrantedAuthority> auth = new ArrayList<GrantedAuthority>();
        auth.add(new SimpleGrantedAuthority((role)));

        return auth;
    }

    @Override
    public String getPassword() {
        return null;
    }

    @Override
    public String getUsername() {
        return "email="+email+",";
    }

    @Override
    public boolean isAccountNonExpired() {
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    @Override
    public boolean isEnabled() {
        return false;
    }
}

Test Code
@Test
    @WithMockCustomUser
    @Transactional // 프록시 객체에 실제 데이터를 불러올 수 있게 영속성 컨텍스트에서 관리
    public void comment_등록() throws Exception {
        // given
        String title = "title";
        String content = "content";
        User user = userRepository.save(User.builder()
                .name("name")
                .email("fake@naver.com")
                .picture("fakePic.com")
                .role(Role.USER)
                .build());

        PostsSaveRequestDto requestDto = PostsSaveRequestDto.builder()
                .title(title)
                .content(content)
                .user(user)
                .build();
        postsRepository.save(requestDto.toEntity());

        String comment = "comment";
        Posts posts = postsRepository.findAll().get(0);

        CommentSaveRequestDto saveRequestDto = CommentSaveRequestDto.builder()
                .comment(comment)
                .posts(posts)
                .build();

        Long id = posts.getId();

        String url = "http://localhost:"+ port + "/api/posts/" + id + "/comments";

        //when

        mvc.perform(post(url)
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .content(objectMapper.writeValueAsString(saveRequestDto)))
                .andDo(print())
                .andExpect(status().isOk());

    }

This doc helped me made this test
At least this test is successfully passed, I'm not Sure I made it correctly.
Any comments would be very helpful.
Thank you in advance.


text:
Q: The compilation of an array of conditions with numba.jit takes a long time If I try to compile a function, containing an array of conditions, with numba's jit-compiler, it takes very long. The program looks essentially like
from numba import jit
import numpy as np

@jit(nopython=True)
def foo(a, b):
    valid = [
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0),
        (a - 1 >= 0) and (b - 1 >= 0)
    ]

foo(1, 1)

where I have excluded everything that will not alter the compilation time significantly. The problem arises if I use more than 20 elements.
| elements | time |
-------------------
|    21    | 2.7s |
|    22    | 5.1s |
|    23    |  10s |
|   ...    |  ... |
-------------------

Despite that, the function workes well. Does anybody know, why it takes so long, to compile such function with numba? Creating arrays in a similar way with combinations of integers or floats causes no problem.

A: *

*You may want to report this on the numba issue tracker, feels like something is going awry in the compiler for it to scale so poorly.

*You may also consider if you really need a large number of array statements like this and if problem could be more clear refactored.  E.g. instead of array of booleans, could valid be a function called as needed?

*That all said, a workaround in the current version of numba is unrolling the conditions.
For your example:
# "codegen"
for i in range(23):
    print(f'    valid[{i}] = (a - 1 >= 0) and (b - 1 >= 0)')

@jit(nopython=True)
def foo(a, b):
    valid = np.empty(23, dtype=np.bool_)
    valid[0] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[1] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[2] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[3] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[4] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[5] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[6] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[7] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[8] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[9] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[10] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[11] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[12] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[13] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[14] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[15] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[16] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[17] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[18] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[19] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[20] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[21] = (a - 1 >= 0) and (b - 1 >= 0)
    valid[22] = (a - 1 >= 0) and (b - 1 >= 0)

%time foo(1,1)
Wall time: 274 ms


text:
Q: Equivalent of LocalBroadcastManager without Android support library There are lots of examples on StackOverflow and elsewhere that use the class LocalBroadcastManager to avoid broadcasting events outside of an app.
However, this class uses the Android support library as shown in the package name: android.support.v4.content.LocalBroadcastManager.
Is there an equivalent of LocalBroadcastManager in the standard SDK that does not use the Android support library?
It does not seem that the sendBroadcast method in android.content.Context has this kind of security granularity.

A: No it doesn't exist, If you want to recreate this class you can read the source code to implement yourself without using the support lib.
Anyway, what's the problem using the support lib? it's lightweight.
A bit workaround could be using the normal BroadCastReceiver and put <android:exported="false"> on your manifest, inside this receiver, this avoid to other apps send you intents, so you are faking a local receiver.
Note: I said faking, because the LocalBroadcastManager has optimizations, by not spread the intent to the system...
Hope this helps.


text:
Q: Can we use arrays for multiple publish topics in ros? So i was working on some ros based UAV simulation and it just struck me when I had to initialize separate publishers for each UAV. Is it possible to make an array of such publishers and then reference them by just using their index number? I know I should just do it and try it, but I guessed asking here would be a faster option:)

A: Yes this is possible by collecting multiple ros::Publishers in containers. Here is a small example  using an array:
#include <ros/ros.h>

#include <std_msgs/String.h>

int main(int argc, char *argv[])
{
  ros::init(argc, argv, "test_node");
  ros::NodeHandle nh;
  ros::WallTimer timer;

  //Create publishers
  std::array<ros::Publisher, 3> publishers;
  for (size_t i = 0; i < publishers.size(); i++)
  {
    std::stringstream topic_name;
    topic_name << "topic" << i;
    publishers[i] = nh.advertise<std_msgs::String>(topic_name.str(), 0);
  }

  //Publish
  ros::Rate r(1);
  std_msgs::String msg;
  while (nh.ok())
  {
    std::stringstream message;
    message << "Hello World " << ros::Time::now();
    msg.data = message.str();
    for (size_t i = 0; i < publishers.size(); i++)
    {
      publishers[i].publish(msg);
    }

    ros::spinOnce();
    r.sleep();
  }

  return 0;
}

The node advertises the three topics

*

*/topic0

*/topic1

*/topic2

and publishes a simple string like Hello World 1562571209.130936883 with a rate of 1 Hz.


text:
Q: Converting string into list of every two numbers in string A string = 1 2 3 4
Program should return = [[1,2],[3,4]]
in python
I want the string to be converted into a list of every two element from string

A: You could go for something very simple such as:
s = "10 2 3 4 5 6 7 8"
l = []
i = 0
list_split_str = s.split()  # splitting the string according to spaces
while i < len(s) - 1:
    l.append([s[i], s[i + 1]])
    i += 2

This should output:
[['10', '2'], ['3', '4'], ['5', '6'], ['7', '8']]

You could also do something a little more complex like this in a two-liner:
list_split = s.split()  # stripping spaces from the string
l = [[a, b] for a, b in zip(list_split[0::2], list_split[1::2])]

The slice here means that the first list starts at index zero and has a step of two and so is equal to [10, 3, 5, ...]. The second means it starts at index 1 and has a step of two and so is equal to [2, 4, 6, ...]. So we iterate over the first list for the values of a and the second for those of b.
zip returns a list of tuples of the elements of each list. In this case, [('10', '2'), ('3', '4'), ('5', '6'), ...]. It allows us to group the elements of the lists two by two and iterate over them as such.
This also works on lists with odd lengths.
For example, with s = "10 2 3 4 5 6 7 ", the above code would output:
[['10', '2'], ['3', '4'], ['5', '6']]

disregarding the 7 since it doesn't have a buddy.

A: here is the solution if the numbers exact length is divisible by 2
def every_two_number(number_string):
    num = number_string.split(' ')
    templist = []
    if len(num) % 2 == 0:
        for i in range(0,len(num),2):
            templist.append([int(num[i]),int(num[i+1])])
    return templist

print(every_two_number('1 2 3 4'))

you can remove the if condition and enclosed the code in try and except if you want your string to still be convert even if the number of your list is not divisible by 2
def every_two_number(number_string):
    num = number_string.split(' ')
    templist = []
    try:
        for i in range(0,len(num),2):
            templist.append([int(num[i]),int(num[i+1])])
    except:
        pass
    return templist

print(every_two_number('1 2 3 4 5'))


text:
Q: Apache : Map one virtualhost to a subdirectory of another virtualhost I'm trying to map one virtual host to a subdirectory of another virtual host, something like this http://host2.com -> http://host1.com/host2. At this moment, whenever I go to http://host2.com it maps to http://host1.com instead of http://host1.com/host2
My default site file is this
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName "host1.com"

 <Directory /srv/www/host1>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order deny,allow
    Allow from all
 </Directory>

 DocumentRoot /srv/www/host1
 WSGIScriptAlias / /srv/www/host1/apache/django.wsgi

 </VirtualHost>

<VirtualHost *:80>

    ServerAdmin webmaster@localhost
    ServerName "host2.com"
    DocumentRoot /srv/www/host1

    <Proxy *>
    Order deny,allow
    Allow from all
    </Proxy>

    ProxyPass / http://host1.com/host2
    ProxyPassReverse / http://host1.com/host2

</VirtualHost>

What am I missing? I'm not sure if it should matter, but I'm using Django with wsgi.

A: This can actually be accomplished using a single <VirualHost />, by using the ServerAlias directive.  You can then use the RewriteRule to pass those requests to the proper directory, and by leaving off [R] you will just be rewriting the request, leaving the URL intact.
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName host1.com
    ServerAlias host2.com

    <Directory /srv/www/host1>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order deny,allow
        Allow from all
    </Directory>

    DocumentRoot /srv/www/host1
    WSGIScriptAlias / /srv/www/host1/apache/django.wsgi

    RewriteEngine On
    RewriteCond %{HTTP_HOST} host2\.com [NC]
    RewriteRule (.*) /host2$1 [L]
</VirtualHost>

Hope this helps.

A: Here's another post that might help:
Redir
I haven't tested this below but you get the idea.
You could use redirecting:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.host2\.com [NC]
RewriteRule ^(.*)$ http://host1\.com\host2 [L,R=301]