text:
Q: How to set position of suggestion list in AutoSuggestBox? I have a UWP application with a number of AutoSuggestBox controls.
When the suggestion lists open, the drop-down is often positioned at the end of the list or at some random location in the middle. I'd like it to either open to the currently selected item, or open at the top of the list if nothing is selected.
I can't figure out how to control this.

A:
How to set position of suggestion list in AutoSuggestBox?

The position was automatically controlled by the available display area, If the bottom area is not enough for dropdown rendering space, it will render top or middle. And it's by design. Currently, we have no such api that use to set the drop-down's placement, if you do want this feature please feel free post your requirement with Windows FeedBackHub app.


text:
Q: Opencv Image stitching blending (Multiband blending) I am trying to blend out the seams in images I have just stitched together using the blender from OpenCV 3.2 in cv::detail::MultiBandBlender found in #include "opencv2/stitching/detail/blenders.hpp". There is not a lot of documentation and even less coding examples from what I could find but I managed to find a good blog that helped explain the steps here.
When I run the code I have I get the following error:/opencv/modules/core/src/copy.cpp:1176: error: (-215) top >= 0 && bottom >= 0 && left >= 0 && right >= 0 in function copyMakeBorder
Here is the code to for the blending (assume stitching, warpPerspective and homographies found are correct)
//Mask of iamge to be combined so you can get resulting mask
Mat mask1(image1.size(), CV_8UC1, Scalar::all(255));
Mat mask2(image2.size(), CV_8UC1, Scalar::all(255));
Mat image1Updated, image2Updated;
//Warp the masks and the images to their new posistions so their are of all the same  size to be overlayed and blended
warpPerspective(image1, image1Updated, (translation*homography), result.size(), INTER_LINEAR, BORDER_CONSTANT,(0));
warpPerspective(image2, image2Updated, translation, result.size(), INTER_LINEAR, BORDER_TRANSPARENT,   (0));
warpPerspective(mask1, mask1, (translation*homography), result.size(), INTER_LINEAR, BORDER_CONSTANT,(0));
warpPerspective(mask2, mask2, translation, result.size(), INTER_LINEAR, BORDER_TRANSPARENT,   (0));

//create blender
detail::MultiBandBlender blender(false, 5);
//feed images and the mask areas to blend
blender.feed(image1Updated, mask1, Point2f (0,0));
blender.feed(image2Updated, mask2, Point2f (0,0));
//prepare resulting size of image
blender.prepare(Rect(0, 0, result.size().width, result.size().height));
Mat result_s, result_mask;
//blend
blender.blend(result_s, result_mask);

The error occurs when I try to do blender.feed
On a little side note; When making the masks for the blender should the mask be the entire images or just the be the area of the images that overlap one another during the stitch?
Thanks for any help in advance
EDIT
I have it working but am now getting this resulting blended imaged.

Here is the stitched image without blending for reference.
Any ideas on how to improve?

A: *

*Use blender.prepare before blender.feed

*Redesign your mask (half 255 and a half 0)

//Mask of the image to be combined so you can get resulting mask
Mat mask1, mask2;
mask1 = optimalSeamMask(energy, path);
mask2 = ones(mask1.rows, mask1.cols)*255-mask1

Mat image1Updated, image2Updated;
//Warp the masks and the images to their new posistions so their are of all the same  size to be overlayed and blended
warpPerspective(image1, image1Updated, (translation*homography), result.size(), INTER_LINEAR, BORDER_CONSTANT,(0));
warpPerspective(image2, image2Updated, translation, result.size(), INTER_LINEAR, BORDER_TRANSPARENT,   (0));
warpPerspective(mask1, mask1, (translation*homography), result.size(), INTER_LINEAR, BORDER_CONSTANT,(0));
warpPerspective(mask2, mask2, translation, result.size(), INTER_LINEAR, BORDER_TRANSPARENT,   (0));

//create blender
detail::MultiBandBlender blender(false, 5);
//feed images and the mask areas to blend
blender.prepare(Rect(0, 0, result.size().width, result.size().height));
blender.feed(image1Updated, mask1, Point2f (0,0));
blender.feed(image2Updated, mask2, Point2f (0,0));
//prepare resulting size of image
Mat result_s, result_mask;
//blend
blender.blend(result_s, result_mask);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access asynchronous services from a web site how do i use a website to connect to asynchronous services. What do i need to consider when connecting to asynchronous services from a web site. As there are multiple users if more than one user sends the request at same time to asynchronous services will it create an exception. What is the best approach i need to use.
Any explanation please


text:
Q: Sum or Percentage of a word in the results / column I have a report that in part is providing: Job Date, Job Target Date and Completion date.
I have a column at the end that works out whether or not the job was completed within the target time our outside of returning true or false.
As mentioned, I have created a column to work out whether a job is completed on time and I have tried googling many different solutions and trying them out.
The expression I've used to work out whether the job was completed on time is:
=IIF(Fields!CompletedDate.Value <= Fields!Target.Value, "True", "False")
Now I need an expression to work out the percentage that are within the target. So, let's say there are 80 jobs and 67 are completed in time. It would be 'True' (67) / 80 *100 = 83%.
The expression I've used to work out whether the job was completed on time is:
=IIF(Fields!CompletedDate.Value <= Fields!Target.Value, "True", "False")
Now I need an expression to work out the percentage that are within the target. So, let's say there are 80 jobs and 67 are completed in time. It would be 'True' (67) / 80 *100 = 83%.

A: I figured this one out myself, again..
If anyone is interested I kept the same IF statement in the original cell. I then created 2 additional cells underneath one containing the text 'Percentage of jobs completed on target' and the other cell I added a new expression that included the original one above;
=SUM(IIF(Fields!CompletedDate.Value <= Fields!Target.Value, 1, 0)) / count(Fields!PropertyCode.Value)
All I had to keep in mind was that I am already showing the results as true and false so in my seconds expression I change the values to numbers so I can calculate. True is '1' so I know that it will not be calculating on 0 as it cannot divide by zero.
So, I did a sum on the number true represented as 1 divided by number of results. Rather than times this by 100 ( 5/19*100 = percentage), I simply left out the times and changed the format of that cell to percentage so it takes the value in the cell and returns the percentage.
Thanks,
Jordan


text:
Q: preg_replace first match pattern include slash How to remove first pattern match when string content "/"
$a = "abc/def";
$b = "abc/def/ghi/abc/def";

$result = "/ghi/abc/def"; when replace with "abc/def" only look for the fist match

I try this but is not work.
$x  = preg_replace('/'.$a.'/', '', $b, 1);

A: You have to keep in mind that first argument of preg_replace is a RegEx pattern, so you can't pass just any string to it.
First you need to escape all regex characters with function preg_quote
Try:
$a = "abc/def";
$b = "abc/def/ghi/abc/def";

$pattern = preg_quote($a, '/'); // second argument allows us to escape delimiter chars, too

$x  = preg_replace("/$pattern/", '', $b, 1);


text:
Q: Android Json parsing string cannot be converted to json object error I want to send parameters such as username and password.
I got an error like String cannot be converted to jsonobject.
I dont know what this happening.Anyone pls help me my code is:
        JSONObject obj=new JSONObject();
            try{
            obj.put("username","test");
                obj.put("password","test");
            } catch (JSONException e) {
            }

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                urlJsonObj, obj, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                } catch (JSONException e) {
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }

        });
        // Adding request to request queue
      AppController.getInstance().addToRequestQueue(jsonObjReq,json_obj_req);
    }

A: It looks like your response is actually a string and not a json object i.e. {"object":"value"} but rather "object:value". You need to sniff your response via either Stetho, Fiddler or reenact your request via Postman (or Fiddler)
======================
This doesn't answer your question, but this will help you tremendously and make your life easier.
Highly recommend using Gson and Retrofit to make HTTP requests and parse Gson objects easily.
https://github.com/google/gson
http://square.github.io/retrofit/

A: There is nothing wrong with the way you are creating JSONObject and putting values in it. Make sure the response received is Json, because your onResponse method accepts JSONObject. You could be receiving String value as response, which could not be converted to JSONObject.


text:
Q: how to throwError in switchMap in the ngrx effect I am using ngrx8, rxjs6 and angular 9
After login I need to call another service. when that service is throwing error I want to catchError part of my effect to handle it, the issue is I catch the error in try catch and I see the log, but catchError is not triggered.
Simplified code
    login$ = createEffect(() => {
        return this.actions$.pipe(

            ofType(AuthActions.login),
            switchMap((action) =>
                this.userService.login(action.userName, action.password)
                    .pipe(
                        switchMap((token) => {
                            return throwError(new Error('hello'));
                        }),
                        map((token) => AuthActions.loginSuccess()),
                        catchError((error) => {
                            console.error('error', error); // I don't see this in console

                            return of(AppError({ error }));
                        })),
            ),
            catchError((error) => {
                console.error('error 2', error);

                return of(AppError({ error }));
            }),
        );
    });

My real code
    login$ = createEffect(() => {
        return this.actions$.pipe(

            ofType(AuthActions.login),
            switchMap((action) =>
                this.userService.login(action.userName, action.password)
                    .pipe(
                        switchMap(async (token) => {
                            try {
                                await this.matrixService.initClient(action.userName, action.password);

                                return of(token);
                            }
                            catch (error) {
                                console.log('catch error', error); // I see this in console

                                return throwError(error);
                            }
                        }),
                        map((token) => AuthActions.loginSuccess()),
                        catchError((error) => {
                            console.error('error', error); // I don't see this in console

                            return of(AppError({ error }));
                        })),
            ),
            catchError((error) => {
                console.error('error 2', error);

                return of(AppError({ error }));
            }),
        );
    });

console output

A: Rather than using Async-Await syntax to wait for the Promise returned by matrixService.initClient to complete (which wouldn't work in the current context due to switchMap operator not waiting for async functions), consider returning it without waiting for it, as it would be converted into an Observable (thanks to switchMap operator accepting Promise) resulting in this.userService.login being awaited.
login$ = createEffect(() => this.actions$
  .pipe(
    ofType(AuthActions.login),
    switchMap(({ userName, password }) => this.userService.login(userName, password)
      .pipe(
        switchMap(() => this.matrixService.initClient(userName, password)),
        map((token) => AuthActions.loginSuccess()),
        catchError((error) => {
          console.error('error', error);
          return of(AppError({ error }));
        })
      )
    ),
    catchError((error) => {
      console.error('error 2', error);
      return of(AppError({ error }));
    })
  )
);

A: based on the comments i will modify the previous answers a little bit
login$ = createEffect(() => this.actions$
  .pipe(
    ofType(AuthActions.login),
    switchMap(({ userName, password }) => this.userService.login(userName, password)
      .pipe(
        map((token) => AuthActions.loginSuccess())
        tap(() => this.matrixService.initClient(userName, password)),
      )
    ),
    catchError((error) => {
      console.error('error 2', error);
      return of(AppError({ error }));
    })
  )
);

I switch the order, always firing AuthActions.loginSuccess() and then this.matrixService.initClient(userName, password).
catchError does not need to be called twice, any error generated from service call will be catch in the outermost catchError operator.


text:
Q: Is inline equals #define function? Does inline int GetNumber(int i) { return mNumbers[i]; }; equals to: #define GetNumber(i) mNumbers[i] from machine instruction perspective?
mNumbers defined this way: std::vector<int> mNumbers.

A: No.
inline has one guaranteed effect: it allows you to define the same function (identically) in more than one translation unit, and then requires the function to be defined in every translation unit where it's used.
inline also serves as a hint that calls of the function should be inlined at the machine code level, but

*

*that hint can be freely ignored, and in case of a recursive function logically must be ignored for some calls,

*machine code call inlining is not the same as macro expansion, in particular the macro doesn't respect scopes.
Perhaps the most important advice I can give you here is to stop fretting about micro-optimization. It's premature. And premature optimization is evil.

A: No. Preprocessor macros are replaced like a query-replace in a text editor, and before the code is passed to the compiler proper. Inline function may have their code inserted in place on the call-site. While they may seem similar, it's quite different.


text:
Q: Random Forest Prediction Consider the following problem.
You have a large simulated dataset of epidemic curves labels from the classes M1, M2, M4..M24.
where in the epidemic curves t1 t2 t3 t4... time in days and the observations are the counts of infected cases per day.
ID    t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13 t14 t15  Y

1328  1  2  2  1  0  1  0  0  1   0   1   0   0   1   1  M7
3564  1  2  3  2  2  1  2  3  1   1   0   0   1   0   0  M18
1601  1  1  3  3  1  2  1  2  1   1   0   0   0   1   0  M9
1897  1  0  0  0  0  0  0  0  0   0   0   0   0   0   0  M10
708   1  1  1  1  1  2  1  3  2   1   0   2   0   1   0  M4
1313  1  1  0  0  1  1  1  0  0   1   0   0   0   0   1 M 7
2283  1  8  0  0  0  0  0  0  0   0   0   0   0   0   0 M12
536   1  9  0  0  0  0  0  0  0   0   0   0   0   0   0 M 3
,
,
,

ONE epidemic curve obtained from a real dataset of which I would like to predict the unseen label "Y" using random forest in R.  Since the test set is based on real data, I can't generate multiple epidemic curves like I did with the train set.
The test set looks like this:
ID      t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13 t14 t15 Y
21000  1  1  2  7  6  1  3  4  2   2   4   3   3   1   1 ?

Questions:
1: what are good approaches one can take to this kind of problem since I only have one epidemic curve to predict? How I will be able to create confusion matrix for prediction one test set?
2: how to validate RF result of the predicted label since I originally don't know the true label of the test set? For example, if RF predict the label "Y" of the test set to be M7, how accurate this prediction is since I don't have an idea of the true labels of my tex set?


text:
Q: Suggestion in hierarchy and normalization in SQL server Brief:
We are going to pull over huge set of data from n number of different servers to one server. Its going to have a billion of records in one table.
Existing:
That table is having about 80 to 90 columns, for ex:
ID, ParentID, L1H1, L1H2,L1H3,L2H1,L2H2,L3H3......

As you can see, this is hierarchial data in which it self represent itself ie parent item is also in this table.
My Ideas:

*

*I'm going to use HierarchyID which is in-built in SQL server.

*Segregating data and save it across with a different table ie L1
values are separately, L2 values are separate etc..,
Could someone suggest whether am i going in correct way? Or is there something i can do better?
or keep the source table as it is and create views on top of it would be better?
I'm really concerned about the optimization of fetching data/ showing it another application.
Thanks

A: Consider Partition and I believe it's not supported all SQL Server editions ...Partitioning large tables can have lot of benefits, read here
 http://technet.microsoft.com/en-us/library/ms190787.aspx][1]


text:
Q: VBA Excel Xlookup refer to table column I have a code for my ComboBox2 which works properly. Now I want to change values in combobox2 and based on that in the textbox6 get a number which is in a column (Total) which is the 6th column of the table (Table1) in another sheet (sheet2).
Private Sub combobox2_Change()

Dim tbl As ListObject
Dim rng As Range

Set tbl = ActiveWorkbook.Worksheets("sheet2").ListObjects("Table1")

Set rng = tbl.ListColumns(6).DataBodyRange

Me.TextBox6.Value = Application.WorksheetFunction.XLookup(Me.ComboBox2.Value, Sheets("sheet2").Range("A2:A7"), Sheets("sheet2").Rng)

End Sub

Could you please tell me why my code does not work? Thanks
I tried the code but I dont now how to get the third variable in the XLOOKUP correct.

A: Assuming you want to lookup the combobox value in the 1st table column and return the value in the 6th.
Private Sub ComboBox2_Change()

    Dim rng As Range
    With ActiveWorkbook.Worksheets("sheet2")
        Set rng = .ListObjects("Table1").DataBodyRange
        Me.TextBox6.Value = Application.WorksheetFunction.XLookup _
              (Me.ComboBox2.Value, rng.Columns(1), rng.Columns(6))
    End With

End Sub

A: Your issue is that there is no Sheets("sheet2").Rng object, variable rng would suffice as 3rd argument in your XLookUp function.
Assuming range A2:A7 is part of your listobject, you might code as follows.
Private Sub combobox2_Change()

'a) reference Listobject in Sheet2
    Dim tbl As ListObject
    Set tbl = Sheet2.ListObjects("Table1")          ' referencing the worksheet's Code(Name) Sheet2
'b) reference listobject data ranges
    Dim lookupRng As Range
    Set lookupRng = tbl.ListColumns(1).DataBodyRange    ' or: identify column by its name string in bracket
    Dim returnRng As Range
    Set returnRng = tbl.ListColumns(6).DataBodyRange    ' or: identify column by its name string in bracket
'c) get result providing for non-finding
    Dim result
    result = Application.WorksheetFunction.XLookup(Me.ComboBox2.value, lookupRng, returnRng, "")
'd) write result
    If result <> vbNullString Then
        Me.TextBox6.value = result
    End If

End Sub

**Help reference XLookUp function


text:
Q: Can Azure Insights API be used for completely stand-alone custom metrics? I am hoping I can put in some simple API calls in legacy systems so I can capture point-in-time metrics "somewhere" in Azure, so that I can then take advantage of the Azure Portal dashboard and metrics graphing. I looked into Insights SDK but that seems to require that whatever I'm running be deployed somewhere in Azure cloud. I just want to run a simple powershell script or simple .net console app that connects to a legacy database in our internal network, pulls very basic point-in-time counts for message processing backlog... and then pushes that info with a timestamp out "somewhere" for visualization.
Any ideas what I can use for this in Azure?
Thanks,
Andres

A: You can use the TrackMetric API in Application Insights SDK.
https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics


text:
Q: How do you pull items from an array list and count them in order to create a map from the element and its total count (properly) in Java? I need to know how to properly iterate over an ArrayList of elements and count the number of an elements appearance in the list without before hand knowing the element. I have tried a couple of approaches and have one that currently works but I feel that it is ugly and improper.
To explain a little more in depth, I have a java web application, one of the pages will present a graph that displays the number of hits a site gets in a day/week/month. I am taking the dates that the site is hit and putting them in an array list, iterating over the array list grabbing an element and counting the number of times it appears, I then put the date as a string and its total count and putting it into a map as a key value pair of (String,int), I will then take this map and convert it to a JSON object and use it with the D3JS library to create a nice bar chart that depicts the information. Below is the code I have tried and the results it presents. The results are accurate, but rather than just working I would like to do it properly and elegant and I know I have not achieved that here. I will explain it as thoroughly as possible and look forward to feedback and ideas of a better approach.
test code main method:
public static void main(String[] args) {

    Map<String, Integer> compMap = new HashMap<String, Integer>();

    ArrayList<String> comp = new ArrayList<String>();
    comp.add("10-31-2014");
    comp.add("10-31-2014");
    comp.add("10-31-2014");
    comp.add("10-31-2014");
    comp.add("10-15-2014");
    comp.add("10-15-2014");
    comp.add("10-15-2014");
    comp.add("10-15-2014");
    comp.add("10-15-2014");
    comp.add("10-12-2014");
    comp.add("10-12-2014");
    comp.add("10-12-2014");
    comp.add("10-12-2014");
    comp.add("10-12-2014");
    comp.add("10-12-2014");
    comp.add("10-12-2014");
    comp.add("10-12-2014");
    comp.add("10-12-2014");
    comp.add("10-09-2014");
    comp.add("10-09-2014");
    comp.add("10-09-2014");
    comp.add("10-09-2014");
    comp.add("10-09-2014");
    comp.add("10-01-2014");
    comp.add("10-01-2014");
    comp.add("10-01-2014");
    comp.add("10-01-2014");
    comp.add("10-01-2014");
    comp.add("10-01-2014");
    comp.add("10-01-2014");

    // 01 = 7 : 09 = 5 : 12 = 9 : 15 = 5 : 31 = 4

    for (int i = 0; i < comp.size(); i++) {

        int counter = 0;
        String current = comp.get(i);

        for (int j = 0; j < comp.size(); j++){
            if (comp.get(j).equals(comp.get(i))){
                counter++;
            }
        }
        compMap.put(current, counter);
    }

    for (Map.Entry<String,Integer> entry : compMap.entrySet()) {

        System.out.println("Key Value Pair Is: " + entry.getKey() + " : " + entry.getValue());

    }

}

For testing purposes I created an array list and added multiple string dates to it (honestly I could have used an array and cut down on test code but I wanted to get as close to an actual case as possible). Afterwards I create a nested for loop, the outer for loop grabs the first item in the list and uses that as the current date for the key in the map, it is also tasked with starting the counter at 0. The inner for loop starts at zero regardless of where I is and grabs the elements of the list to compare them to element i if they are equal then counter is incremented by 1. Once the loop is completed just before exiting the outer loop the current date being worked with and the counter total is added into the map.
The results of the counter:
Key Value Pair Is: 10-15-2014 : 5
Key Value Pair Is: 10-12-2014 : 9
Key Value Pair Is: 10-31-2014 : 4
Key Value Pair Is: 10-01-2014 : 7
Key Value Pair Is: 10-09-2014 : 5

These were pulled from the console after the test ran. The results are correct. My question is more to see if there are more elegant or proper ways to perform this task?
Thank you!

A: Multiset
I would suggest the MultiSet collection in  Google Guava. It has nice abilities that can save you a lot of time.
com.google.common.collect.Multiset<String> multiset = com.google.common.collect.HashMultiset.create();
multiset.add("10-31-2014");
multiset.add("10-31-2014");
multiset.add("10-15-2014");
multiset.add("10-15-2014");
multiset.add("10-15-2014");
multiset.add("10-15-2014");
multiset.toString();

Print:

[10-31-2014 x 2, 10-15-2014 x 4]

A: Map
for(String arrayElement : comp) {
    if(!compMap.containsKey(arrayElement)) {
        compMap.put(arrayElement, 1);
    } else {
        int newCount = compMap.get(arrayElement) + 1;
        compMap.put(arrayElement, newCount);
    }
}

The whole benefit of the map is that you can do a lookup on it very fast.  This allows you to do the 'counting' while you scan through the array once.  This makes the running time of the algorithm significantly faster (theoretically speaking, we improve from O(n^2) to O(n)).
We also can use java's for-each loop (as I did here), rather than need to maintain a separate counter (i.e. the i variable) in the for loop.  This is just for aesthetics - it makes the code a bit easier to read, but doesn't fundamentally change the algorithm.

A: Your code is doing a lot of duplicate counting. I'd use a Set to avoid that. There's also the Collections.frequency() method to count the occurrences:
Set<String> compSet = new HashSet<String>(comp); // unique elements of comp
for (String s : compSet) {
    compMap.put(s, Collections.frequency(comp, s));
}


text:
Q: Не удаётся yстановить пакет из NuGet При попытке установки Json из NuGet в Visual Studio 2015 выдаёт следущее:

Не удалось инициализировать узел PowerShell. Если для политики
  выполнения PowerShell выбран режим AllSigned, откройте консоль
  диспетчера пакетов, чтобы сначала инициализировать узел

OC Windows 10 Home 64 битная.

A: Нужно запустить PowerShell (под правами администратора) и выполнить команду:
Set-ExecutionPolicy RemoteSigned

Будет предупреждение:

Политика выполнения защищает компьютер от ненадежных сценариев. Изменение политики выполнения может поставить под угрозу безопасность системы, бла бла...

Подтверждаем выполнение и перезапускаем Visual Studio

A: Столкнулся с той же проблемой.
В моем случае, когда я открыл npm console я увидел сообщение об ошибке инициализации npm. Там было, примерно, следующее:

Nuget Package Manager requires PowerShell 2.0 to be installed. Please
  follow the link to get PowerShell 2.0.

Ссылка ведет на сайт microsoft, где можно скачать PowerShell для версий Windows до 7.
В Windows 8-10 PowerShell 2.0 — это компонент системы, находится он в Windows Features.
После того, как я включил PS 2.0 и перезагрузил студию, проблема решилась.

A: Та же ошибка появлялась при создании веб-приложений Visual Studio 2017 (C#) на Windows 10.
Перезагрузки не помогли.
Set-ExecutionPolicy RemoteSigned - не помогло.
Обновил (установил) до последней версии Microsoft SQL Server с официального сайта и всё заработало.

A: Нужно, чтобы проект лежал на том же диске, что и студия. Не знаю, как это связано, но мне помогло.

A: Там что-то связано с разрядностью PowerShell (64bit) и VS (32bit). Получается (насколько я понял), NuGet использует 32-разрядную консоль PowerShell, а нам надо использовать 64-разрядную (по системе). Следовательно надо настроить политику безопасности (ну или что-то такое) в PowerShell и подключить 64-битную как 32-битную.
Что надо сделать (кстати, перезагрузка системы тоже помогает):

*

*Открыть Windows PowerShell, запустить под администратором.

*В PowerShell консоли запустите следующий скрипт:
start-job { Set-ExecutionPolicy RemoteSigned } -RunAs32 | wait-job | Receive-Job

*Перезапустите Visual Studio.


text:
Q: How to use existing DB with IdentityServer4 I want to use IdentityServer4 with my custom database. I've separate tables for admin and students and both entities have separate rights.
I want to know how to configure IdentityServer EF database to work with my existing DB?
Any help would highly appreciated.
Thanks.

A: I started with the IdentityServer4 Quick Start sample 7_JavaScriptClient.
First I created a UserManager class that could connect to my data source and validate a user by user name and password and return that user object.
public class UserManager
{
    private SecurityContext _context;

    public UserManager(SecurityContext context)
    {
        _context = context;
    }

    public  Task<User> Find(string username, string password)
    {
         ...Logic to query your custom user table(s)...
    }

    public Task<List<Claim>> GetClaimsAsync(User user)
    {
        var claims = new List<Claim>();

        //custom database call here to where you store your claims.
        var myClaims = ...Your Database call here...
        var claimGroupName = "SomeCustomName";

        if (security != null && security.Count() > 0)
        {
            foreach (var claim in security)
            {
                //Add the value from the field Security_Id from the database to the claim group "SomeCustomName".
                claims.Add(new Claim(claimGroupName , claim.SECURITY_ID));
            }
        }

        return Task.FromResult(claims);

    }
 }

User Object
public class User
{
    public string FIRST_NAME { get; set; }
    public string LAST_NAME { get; set; }
    public string EMAIL { get; set; }

    ...Other attributes/properties...
}

Second I used the UserManager Object from the AccountController in the sample.
private readonly UserManager _userManager;

public AccountController(
        IIdentityServerInteractionService interaction,
        IClientStore clientStore,
        IHttpContextAccessor httpContextAccessor,
        UserManager userManager
        )
{
    _userManager = userManager;
 }

Third in the AccountController.Login() HTTP Post method I called the UserManager.Find(username, password) to return a user.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model)
{
     // validate username/password
     var user = await _userManager.Find(model.Username, model.Password);

     //sign the user in with a subject[user_id] and name[web_id]
     await HttpContext.Authentication.SignInAsync(user.USER_ID, user.WEB_ID, props);
}

Fourth I implemented the IProfileService. [I used this article as a resource.]
public class ProfileService : IProfileService
{
     UserManager _myUserManager;
     private readonly ILogger<ProfileService> _logger;

     public ProfileService(ILogger<ProfileService> logger)
    {
        _logger = logger;
        _myUserManager = new UserManager(new SecurityContext());
    }

    //Called by IdentityServer Middleware.
     public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var sub = context.Subject.FindFirst("sub")?.Value;
        if (sub != null)
        {
            var user = await _myUserManager.FindByNameAsync(sub);

            //Call custom function to get the claims from the custom database.
            var cp = await   getClaims(user);

            var claims = cp.Claims;

            ...Optionaly remove any claims that don't need to be sent...

            context.IssuedClaims = claims.ToList();
        }
     }

     //Called by IdentityServer Middleware.
     public async Task IsActiveAsync(IsActiveContext context)
    {
        var sub = context.Subject.GetSubjectId();
        var user = await _myUserManager.FindByNameAsync(sub);
        context.IsActive = user != null;
        return;
    }

    //Custom function to get claims from database via the UserManager.GetClaimsAsync() method.
    private async Task<ClaimsPrincipal> getClaims(User user)
    {
       var id = new ClaimsIdentity();
       //set any standard claims
       id.AddClaim(new Claim(JwtClaimTypes.PreferredUserName, user.USER_ID));
       //get custom claims from database or other source.
       id.AddClaims(await _myUserManager.GetClaimsAsync(user));

       return new ClaimsPrincipal(id);
    }
}

Lastly in the Startup.cs setup any Objects for Dependency Injection.
public void ConfigureServices(IServiceCollection services)
{
   builder.Services.AddTransient<IProfileService, ProfileService>();

   //This is the DbContext to our Database where the users and their claims are stored.
   services.AddTransient<SecurityContext>();
   services.AddTransient<UserManager>();

 }

Here is a similar question and anser as well.
Note that they also reference the IResourceOwnerPasswordValidator interface and implementation which is for authenticating OAuth 2.0 resource owner password credential grant (aka password). Used with GrantTypes.ResourceOwnerPasswordAndClientCredentials or GrantTypes.ResourceOwnerPassword.


text:
Q: Storyboarding for iOS and iPad I'm developing a simple app for the iPhone and was preparing to submit it for review from Apple.
I found out I needed to supply screenshots for the iPad and when I ran the simulator on the iPad nothing seems to display.
It looks like it's because my storyboarding height and width modes were set to Width: Compact, Height: Any.
First of all, to get it to render for iPad, do I need to re-storyboard for Height: Any, Width: Any.  Or do I have to do Height: Regular, Width: Regular?
Also will setting those mess up my current constraints and layout?
Finally do I have to use all new UILabels, Views, etc?  I'd like to use the old ones without messing up the positioning and constraints I've set, but I can't see anything when I change to Width/Height: Any.

A: If your app is just an iPhone app, you don't need to submit iPad screenshots, you can submit with just the iPhone screenshots.
If you wish to make your app universal, you will have to ensure the storyboard is changed to support regular width/height as well. Also take into consideration multi-tasking support if the app is not marked for full screen specifically.

A: If you are planning to make it support for iPad as well(Universal), Then probably you have to redo all the constraints you have considering the size classes you used at the moment. For iPad wRegular and hRegular recommended. Changing your size classes from wCompact, hAny to wRegular, hRegular will definitely mess up your existing constraints.
If your app is iPhone only, then you don't have to upload iPad screenshots at all.


text:
Q: How to correct sort domain class by an alphanumeric (String) property? When I'm sorting a Domain Class by an alphanumeric property, the sort order is not the expected when the value starts with numbers. Example:
class MyDomainClass {
  String descr
}

MyDomainClass.createCriteria().list() {
  order("descr", "asc")
}.each { it ->
  println it.descr
}

if the table constains this 3 values:

*

*AAA

*111

*BBB

The print result is:

*

*AAA

*BBB

*111

But what I want is (same as database query result):

*

*111

*AAA

*BBB

Is there any configuration where I can define this?

A: I realized the problem was happening due to NLS_SORT parameter on Oracle DB being changed to WEST_EUROPEAN when my application sets the locale to pt_BR (because this is the default sorting for this locale according Oracle's documentation). So I realized I can define a custom sorter using NLSSORT function when necessary:

select ret
  from ( select 'AAA' as ret from dual
          union
         select '111' as ret from dual
          union
         select 'BBB' as ret from dual)
 ORDER BY NLSSORT(ret, 'NLS_SORT = BINARY');

In grails:

println ' --- With WEST_EUROPEAN sort ---'
MyDomain.executeQuery("SELECT m FROM MyDomain as m ORDER BY NLSSORT(descr, 'NLS_SORT = WEST_EUROPEAN')").each {
    println it.descr
}

println ' -- With BINARY sort ---'
MyDomain.executeQuery("SELECT m FROM MyDomain as m ORDER BY NLSSORT(descr, 'NLS_SORT = BINARY')").each {
  println it.descr
}

Output:

--- With WEST_EUROPEAN sort ---
AAA
BBB
111
--- With BINARY sort ---
111
AAA
BBB


text:
Q: Rails: passing data from instance variable in 1 controller to instance variable in another controller I have a Rails app which has 2 databases.

*

*Legacy DB with table called : Businesses

*regular development DB that comes with the rails app.

I have data in the Businesses table that I want to put into the development DB. To accomplish this I have taken the following steps:

*

*Set up the app so that I can read from the Businesses DB and see the output in the browser.
I accomplished this by creating a model Business and a BusinessesController class which reads all the data from the businesses table and stores the entries in an instance variable @businesses

*Then I created a model called Listing and a ListingsController. I would like to read all the entries from @businesses in the BusinessesController and store them in @listings in the ListingsController.
Thus essentially all I need to do is take data stored in one instance variable and save it in another instance variable. I'm not sure how to do this in Rails.
So far I have the following classes:
Buisiness
class Business < ActiveRecord::Base
  establish_connection "Listings_development"
end

class BusinessesController < ApplicationController
  def get_all
    @businesses = Business.all
  end

  def index
    self.get_all
    respond_to do |format|
      format.html #index.html.erb
    end
  end
end

index.html.erb

Listing businesses

    Index
    Name
    Phone Number
    Suite
    Address
    City
    Province
    Postal Code
    Fax
    Latitude
    Longitude
    Website

  <% count = 0 %>
  <% @businesses.each do |business| %>

  <%count = count.to_i + 1 %>

    <%= business.bid %>
    <%= business.company_name %>
    <%= business.phone_number %>
    <%= business.suite_number %>
    <%= business.address %>
    <%= business.city %>
    <%= business.province %>
    <%= business.postal_code %>
    <%= business.fax_number %>
    <%= business.latitude %>
    <%= business.longitude %>
    <%= business.website %>
  <% end %>

<%= link_to 'New Business', new_business_path %>

Listings
class Listing < ActiveRecord::Base
  attr_accessor :name, :telephone

  def initialize(attributes = {})
    @name = attributes[:name]
    @telephone = attributes[:telephone]
    @latitude = attributes[:latitude]
    @longitude = attributes[:longitude]

    puts 'Created a new Listing'
  end
end

class ListingsController < ApplicationController
  def get_all
    @listings = @businesses
    # @listings = businesses_controller.get_all
  end

  def index
    self.get_all

    respond_to do |format|
      format.html #index.html.erb
    end
  end
end

index.html.erb

Listings

This is where all Listings will show up

<%= @listings.inspect %>

<%= @businesses.inspect %>

When I go to url
http://localhost:3000/businesses

I can see the table of all the entries in my legacy DB - businesses table in the browser
But when I go to url:
http://localhost:3000/listings

I just see the place holder text and for values of @businesses & @listings I see nil.
So clearly the @businesses variable is not accessible within the ListingsController class. I'm wondering how to best pass data between these 2 controllers.

A: You are doing it wrong! You never should need a controller to talk to another controller in a MVC pattern. Your model should be the only responsible to know how to get the data, and so you would use that model in both controllers. Business logic lives at models.
You should use Business model inside Listings controller
@listings = Business.all


text:
Q: Placing the label of the panel from the top of the plot to the top left when using facet_wrap() How could i place the label of the panel when using facet_wrap () in ggplot2 packages from the top of the plot to the top left of the plot?.
That is to change the position of the number 4, 5,6 and 8 from the top of the plot to the top left.

A: Try if adding this works:
+ theme(strip.text.x = element_text(hjust=0))


text:
Q: Como eu adiciono um hyperlink na Checkbox em flutter Bom dia, tudo bem pessoal?
Eu gostaria de adicionar um hyperlink no trecho "política de privacidade", e não estou conseguindo. É possível fazer isso?
Se alguém puder me auxiliar agradeço.
import 'package:flutter/material.dart';

class GetCheckValue extends StatefulWidget {
  @override
  GetCheckValueState createState() {
    return new GetCheckValueState();
  }
}

class GetCheckValueState extends State<GetCheckValue> {
  bool _isChecked = false;
  String _currText = '';

  List<String> text = [
    "Declaro que li e aceito os termos da Política de Privacidade."

  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: Column(
            children: text
                .map((t) => CheckboxListTile(
                      title: Text(
                        t,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 17.0,
                        ),
                      ),
                      value: _isChecked,
                      onChanged: (val) {
                        setState(() {
                          _isChecked = val;
                          if (val == true) {
                            _currText = t;
                          }
                        });
                      },
                      activeColor: Colors.lightBlueAccent,
                      checkColor: Colors.white,
                    ))
                .toList(),
          ),
        ),
      ],
    );
  }
}

A: Você consegue criar um hyperlink em um texto utilizando RichText e TextSpan, por exemplo:
  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
        text: 'Concordo com os ',
        children: <InlineSpan>[
          _buildLink(
            context: context,
            title: 'Termos de uso',
            onTap: () {
              print('Tap termos de uso');
            }
          ),
          const TextSpan(text: ' e a '),
          _buildLink(
            context: context,
            title: 'Política de Privacidade',
            onTap: () {
              print('Tap política de privacidade');
            }
          ),
        ],
      ),
    );
  }

  TextSpan _buildLink({
    BuildContext context,
    String title,
    VoidCallback onTap,
  }) {
    return TextSpan(
      text: title,
      style: Theme.of(context).textTheme.bodyText1.copyWith(
            fontSize: 14.0,
            color: Colors.pink,
          ),
      recognizer: TapGestureRecognizer()..onTap = onTap,
    );
  }

E dentro de um TextSpan utilizar o parâmetro recognizer para criar o hyperlink, deixando uma parte do texto como link.
Veja na prática no DartPad.

Com isso, adapte para o seu caso. Não é necessário um CheckboxListTile e sim apenas uma Row com um Checkbox e o RichText.


text:
Q: Problems with importing events from Facebook I am to import information about events from Facebook.
I've generated the token, downloaded all the needed libraries.
Here is my code (for example I wanted to download events linked to "Poetry"):
import urllib3
import facebook
import requests
token = 'xyz'
graph = facebook.GraphAPI(access_token = token, version = 2.7)
events = graph.request('/search?q=Poetry&type=event&limit=10000')

Unfortunately an error occurs

How can it be fixed?
I have one more question - how is it possible to download information over some events in a particular location?
I would appreciate any hints or tips.

A: You need to use apostrophes to enclose a string:
graph.request('/search?q=Poetry&type=event&limit=10000')


text:
Q: Pandas groupby day in range and category I have a dataframe in the following format and want to sum the weight column by category and by day (where day is in the start-end range)
i.e. from this:

batch
category
start_day
end_day
duration
weight

XX001
AAA
2022-01-06
2022-01-14
6
0.1250

XX002
BBB
2022-01-08
2022-01-12
4
0.2500

XX003
AAA
2022-01-07
2022-01-09
2
0.5000

to this:

day
AAA
BBB

2022-01-06
0.1250
0.0000

2022-01-07
0.6250
0.0000

2022-01-08
0.6250
0.2500

2022-01-09
0.1250
0.2500

2022-01-10
0.1250
0.2500

2022-01-11
0.1250
0.2500

2022-01-12
0.1250
0.0000

2022-01-13
0.1250
0.0000

I can foresee some ways of doing it inefficiently by e.g. generating a series of days from earliest to latest, then iterating over each entry in the individual table to increment the sum of weights in each category in each day, but I'm guessing there's a better way of doing it using groupby, but I just can't seem to figure it out.
EDIT: Here's a loop-heavy way of doing it:
import pandas as pd

batches_data = {
    "XX001": {"category": "AAA", "start_day": pd.Timestamp("2022-01-06"), "end_day": pd.Timestamp("2022-01-14")},
    "XX002": {"category": "BBB", "start_day": pd.Timestamp("2022-01-08"), "end_day": pd.Timestamp("2022-01-12")},
    "XX003": {"category": "AAA", "start_day": pd.Timestamp("2022-01-07"), "end_day": pd.Timestamp("2022-01-09")},
}
batches = pd.DataFrame.from_dict(batches_data, orient="index")
batches["duration"] = (batches["end_day"] - batches["start_day"]).dt.days
batches["weight"] = 1 / batches["duration"]

min_start = min(batches["start_day"])
max_end = max(batches["end_day"])

dates = pd.date_range(start=min_start, end=max_end, freq='D')
categories = sorted(batches["category"].unique())

daily_weights_by_category = pd.DataFrame(0, index=dates, columns=categories)
for _, batch in batches.iterrows():
    for date in dates:
        if date >= batch["start_day"] and date < batch["end_day"]:
            daily_weights_by_category.loc[date, batch["category"]] += batch["weight"]

print(daily_weights_by_category)

A: something like
df.groupby(["category","start_day"]).sum()["weight"]

*

*groupby - groups in to sub dfs and you can actually iterate these with

for grouped_df, name in df.groupby(["category","start_day"]):

    print(name)

*.sum() then sum the column

*["weight"] select the weight column
should work (not tested but pretty sure thats right - its been a while)


text:
Q: Converting error to boxed when inside a collection I have a function that reads a file line by line and parses. Right now to i32 but really I'd like this to be templated. Just keeping things simple for now.
I can get it sorted out using explicit for-loops, but not using iterators.
The below code complains that the error type can't be converted to the Box<dyn Error> type and I'm not sure what to do about that. Aren't the parse errors part of the standard library and thus implement the Error trait, and doesn't Box do automatic conversion of errors (because it's such a common idiom?)
Playground link
use std::error::Error;
use std::fs;

pub fn read_file_to_list(filename: &str) -> Result<Vec<i32>, Box<dyn Error>> {
    let file_as_string = fs::read_to_string(filename)?;
    file_as_string.lines().map(|line| line.parse()).collect()
}

Error is in the parse:
   Compiling playground v0.0.1 (/playground)
error[E0271]: type mismatch resolving `<i32 as FromStr>::Err == Box<dyn std::error::Error>`
 --> src/lib.rs:6:44
  |
6 |     file_as_string.lines().map(|line| line.parse()).collect()
  |                                            ^^^^^ expected struct `ParseIntError`, found struct `Box`
  |
  = note: expected struct `ParseIntError`
             found struct `Box<dyn std::error::Error>`

I assume I'll need to do some sort of map_err but I can't figure out what and how.

A: Luckily, conversion from ParseIntError to Box<dyn Error> can be done using the Into trait as there is a blanket impl for that in the stdlib. So we can  replace line.parse() with
line.parse().map_err(|e| e.into())

or:
line.parse().map_err(Into::into)

A common trick to make this more ergonomic is abusing the fact that ? automatically calls .into() on the error type:
Ok(line.parse()?)

It looks a bit silly to use ? only to wrap in Ok, but it's actually a common idiom precisely for this purpose. So this compiles:
pub fn read_file_to_list(filename: &str) -> Result<Vec<i32>, Box<dyn Error>> {
    let file_as_string = fs::read_to_string(filename)?;
    file_as_string.lines().map(|line| Ok(line.parse()?)).collect()
}


text:
Q: Latest Chromecast (21.0.1) produces crash from Android 12: ForegroundServiceStartNotAllowedException Precondition

*

*targetSdkVersion and compileSdkVersion 31.

*com.google.android.gms:play-services-cast:21.0.1 and com.google.android.gms:play-services-cast-framework:21.0.1
Crash
Fatal Exception: android.app.ForegroundServiceStartNotAllowedException: startForegroundService() not allowed due to mAllowStartForeground false: service com.ondemandkorea.android/com.google.android.gms.cast.framework.media.MediaNotificationService
       at android.app.ForegroundServiceStartNotAllowedException$1.createFromParcel(ForegroundServiceStartNotAllowedException.java:54)
       at android.app.ForegroundServiceStartNotAllowedException$1.createFromParcel(ForegroundServiceStartNotAllowedException.java:50)
       at android.os.Parcel.readParcelable(Parcel.java:3345)
       at android.os.Parcel.createExceptionOrNull(Parcel.java:2432)
       at android.os.Parcel.createException(Parcel.java:2421)
       at android.os.Parcel.readException(Parcel.java:2404)
       at android.os.Parcel.readException(Parcel.java:2346)
       at android.app.IActivityManager$Stub$Proxy.startService(IActivityManager.java:6897)
       at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1926)
       at android.app.ContextImpl.startForegroundService(ContextImpl.java:1892)
       at android.content.ContextWrapper.startForegroundService(ContextWrapper.java:796)
       at com.google.android.gms.cast.framework.media.internal.zzp.zzg(com.google.android.gms:play-services-cast-framework@@20.1.0:33)
       at com.google.android.gms.cast.framework.media.internal.zzp.onStatusUpdated(com.google.android.gms:play-services-cast-framework@@20.1.0:1)
       at com.google.android.gms.cast.framework.media.zzbo.zzm(com.google.android.gms:play-services-cast-framework@@20.1.0:4)
       at com.google.android.gms.cast.internal.zzap.zzaa(com.google.android.gms:play-services-cast@@20.1.0:1)
       at com.google.android.gms.cast.internal.zzap.zzQ(com.google.android.gms:play-services-cast@@20.1.0:65)
       at com.google.android.gms.cast.framework.media.RemoteMediaClient.onMessageReceived(com.google.android.gms:play-services-cast-framework@@20.1.0:1)
       at com.google.android.gms.cast.zzbn.run(com.google.android.gms:play-services-cast@@20.1.0:4)
       at android.os.Handler.handleCallback(Handler.java:938)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loopOnce(Looper.java:226)
       at android.os.Looper.loop(Looper.java:313)
       at android.app.ActivityThread.main(ActivityThread.java:8582)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:563)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1133)

I have seen similar SO posts like this or this, but those were caused by starting some foreground service manually.
As you can see in the stack trace, I'm not really starting any services myself. In fact, I don't even have startForegroundService() call in my codebase.
It looks like Chromecast is doing the service implementation, but I don't know where to start to debug this. Someone reported an issue in the Chromecast github, but no one has replied.
If anyone experienced similar issue, please help me debug this (or reproduce the issue).
Thank you.


text:
Q: Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.2:generate I using
mvn archetype:generate -DarchetypeGroupId=$archetype_groupId -DarchetypeArtifactId=$archetype_artifactId -DarchetypeVersion=$archetype_version -Dpackage=$package -DgroupId=$groupId -DartifactId=$artifactId -Dversion=$version  -DinteractiveMode=false

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.2:generate (default-cli) on project standalone-pom: java.io.IOException: 没有那个文件或目录 -> [Help 1]

[DEBUG]   - found resource (archetype-resources/)service/src/test/resources/scf_local.config
[DEBUG]   - ignored resource META-INF/maven/archetype-metadata.xml
[DEBUG] Processing complete archetype zzdealdemo
[DEBUG] Processing module hook
[DEBUG] Processing module rootArtifactId hook
[DEBUG] Processing module pom /etc/hook/pom.xml
[DEBUG] Processing module moduleOffset
[DEBUG] Processing module outputDirectoryFile /etc/hook
[DEBUG] Processing fileset project moduleId hook
[DEBUG] Processing fileset project pom /etc/hook/pom.xml
[DEBUG] Processing fileset project moduleOffset
[DEBUG] Processing fileset project outputDirectoryFile /etc/hook
[DEBUG] Processing fileset project basedirPom /etc/pom.xml
[DEBUG] Processing pom /etc/hook/pom.xml
[DEBUG] Processing template archetype-resources/pom.xml
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.950s
[INFO] Finished at: Mon Sep 16 11:25:56 CST 2019
[INFO] Final Memory: 15M/150M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.2:generate (default-cli) on project standalone-pom: java.io.IOException: 没有那个文件或目录 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.2:generate (default-cli) on project standalone-pom: java.io.IOException: 没有那个文件或目录
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoFailureException: java.io.IOException: 没有那个文件或目录
        at org.apache.maven.archetype.mojos.CreateProjectFromArchetypeMojo.execute(CreateProjectFromArchetypeMojo.java:207)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)

A: Try this below command to create maven project through CMD mode and let me know if any issue is there...
mvn archetype:generate -DgroupId=TestCases -DartifactId=FrameworkProject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false -DarchetypeVersion=1.1


text:
Q: Dll Private method throw "not accesible due to access level" WITHIN owner class I'm an amateur and not English native speaker. I'm trying to do mapper for use it with Dapper's dynamic results, I need it for a personal project and I couldn't adapt self Dapper mapper either Automapper to my needs (probably due to my lack of knowledge), so I decided to make mine.
It works flawlessly when I add the mapper code with "Add -> Existing Item", but if I try to use it as a DLL it throws the "not accessible due to access level" exception, pointing this part of the code:
    public T Map(IEnumerable<dynamic> dapperResult, bool cleanResult = false)
    {
        var parser = new PrePostFixesParser(this);
        T mapped = this.NewObject(dapperResult.First()); <------//EXCEPTION HERE
        if (_OnlyConstructor.Contains(this.TType)) return mapped;
        //... Other things

The method NewObject:
    private T NewObject(dynamic dyn)
    {
        Type t = typeof(T);
        bool IsInterfaceNotIEnumerable = t.IsInterface
            && !typeof(IDictionary).IsAssignableFrom(t)
            && !(typeof(IEnumerable).IsAssignableFrom(t) && !typeof(string).IsAssignableFrom(t));
        if (IsInterfaceNotIEnumerable)
            throw new CustomException_DapperMapper(
                @"DapperMapper.NewObject: Exception trying to instantiate an interface that isn't an IEnumerable. This is a BUG.");

        T newObj;
        //if there are a constructor configurated
        if (_Constructors.ContainsKey(this.TType))
        {
            //object[] constructorParams = GetConstructorParams();
            try
            {
                Func<dynamic, T> constDelegate = (Func<dynamic, T>)_Constructors[this.TType];
                newObj = constDelegate(dyn);
            }
            catch (Exception err)
            {
                throw new CustomException_DapperMapper(
                    $@"DapperMapper.NewObject: Exception using constructor to create object of type {TType.Name} with delegate {_Constructors[TType]}.", err);
            }
        }
        //if there are no constructor configurated, use parameterless constructor
        else newObj = Activator.CreateInstance<T>();

        return newObj;
    }

Both methods are part of the same class called DapperMapper. I've read the page always want all the possible code in the same question, so I'm posting the entire class here, but it's a large one, so I'm posting too the link to Github where I have all the solution... just in case:
public class DapperMapper<T> : DMStatic_Mapper, iDapperMapper
{
    public DapperMapper(MapperStore store)
    {
        this.TType = typeof(T);
        this.MappersStore = store;
        this.MappersStore.StoreMapper(this.TType, this);
    }

    #region properties
    public MapperStore MappersStore { get; private set; }
    public Dictionary<MemberInfo, MemberTypeInfo> mtInfos { get { return _mtInfos[this.TType]; } }
    public Type TType { get; private set; }
    public IEnumerable<string> NamesList { get { return _NamesList[this.TType]; } }
    public Tuple<string[], bool> Prefixes { get { return _Prefixes.ContainsKey(this.TType) ? _Prefixes[this.TType] : null; } }
    public Tuple<string[], bool> Postfixes { get { return _Postfixes.ContainsKey(this.TType) ? _Postfixes[this.TType] : null; } }
    #endregion

    #region helpers
    private T NewObject(dynamic dyn)
    {
        Type t = typeof(T);
        bool IsInterfaceNotIEnumerable = t.IsInterface
            && !typeof(IDictionary).IsAssignableFrom(t)
            && !(typeof(IEnumerable).IsAssignableFrom(t) && !typeof(string).IsAssignableFrom(t));
        if (IsInterfaceNotIEnumerable)
            throw new CustomException_DapperMapper(
                @"DapperMapper.NewObject: Exception trying to instantiate an interface that isn't an IEnumerable. This is a BUG.");

        T newObj;
        //if there are a constructor configurated
        if (_Constructors.ContainsKey(this.TType))
        {
            //object[] constructorParams = GetConstructorParams();
            try
            {
                Func<dynamic, T> constDelegate = (Func<dynamic, T>)_Constructors[this.TType];
                newObj = constDelegate(dyn);
            }
            catch (Exception err)
            {
                throw new CustomException_DapperMapper(
                    $@"DapperMapper.NewObject: Exception using constructor to create object of type {TType.Name}
with delegate {_Constructors[TType]}.", err);
            }
        }
        //if there are no constructor configurated, use parameterless constructor
        else newObj = Activator.CreateInstance<T>();

        return newObj;
    }
    #endregion

    #region public methods
    /// <summary>
    /// Remove duplicated results due to JOINs.
    /// </summary>
    /// <param name="origDapperResult"></param>
    /// <param name="cleanResult"></param>
    /// <returns></returns>
    public IEnumerable<dynamic> GetDistinctDapperResult(IEnumerable<dynamic> origDapperResult, bool cleanResult)
    {
        PrePostFixesParser parser = new PrePostFixesParser(this);
        IEnumerable<string> names = this.NamesList;
        List<dynamic> result = new List<dynamic>();

        foreach(dynamic dyn in origDapperResult)
        {
            IDictionary<string, object> dict =
                (!cleanResult ? parser.GetTypeMembersWithoutPrePostFixes(dyn, names) : dyn)
                as IDictionary<string, object>;

            bool distinct = true;
            foreach(dynamic resultDyn in result)
            {
                IDictionary<string, object> resDict = resultDyn as IDictionary<string, object>;

                if(dict.Keys.SequenceEqual(resDict.Keys) && dict.Values.SequenceEqual(resDict.Values))
                {
                    distinct = false;
                    break;
                }
            }

            if (distinct) result.Add(dyn);
        }
        return result;
    }
    /// <summary>
    /// Check if the dynamic object have all the members needed to map a new T object, except those setted as IEnumerable,
    /// which should be provided in others dynamic.
    /// </summary>
    /// <param name="dyn"></param>
    /// <returns></returns>
    public bool CheckIfDynamicHasAllTypeMembersByName(dynamic dyn)
    {
        IDictionary<string, object> membersDict = dyn as IDictionary<string, object>;
        IEnumerable<string> dynList = membersDict.Select(kvp => kvp.Key);
        PrePostFixesParser parser = new PrePostFixesParser(this);
        IEnumerable<string> list = parser.GetCleanNamesList(this.NamesList);

        return !dynList.Except(list).Any() && !list.Except(dynList).Any();
    }
    /// <summary>
    /// Check if the dynamic object have all the members needed to map a new T object, except those setted as IEnumerable,
    /// which should be provided in others dynamic.
    /// </summary>
    /// <param name="membersDict"></param>
    /// <returns></returns>
    public bool CheckIfDynamicHasAllTypeMembersByName(IDictionary<string, object> membersDict)
    {
        IEnumerable<string> dynList = membersDict.Select(kvp => kvp.Key);
        PrePostFixesParser parser = new PrePostFixesParser(this);

        return dynList.SequenceEqual(parser.GetCleanNamesList(this.NamesList));
    }
    /// <summary>
    /// Generic Map.
    /// </summary>
    /// <param name="dapperResult"></param>
    /// <returns></returns>
    public T Map(IEnumerable<dynamic> dapperResult, bool cleanResult = false)
    {
        var parser = new PrePostFixesParser(this);
        T mapped = this.NewObject(dapperResult.First());
        if (_OnlyConstructor.Contains(this.TType)) return mapped;

        //TODO: divide el siguiente foreach en dos con dos nuevos diccionarios estáticos, uno para pInfos y otro para fInfos,
        //aunque se repita código: hacer métodos para cada parte del código del tipo:
        //private T PreMapCreator(KeyValuePair<PropertyInfo, MemberTypeInfo> kvp, IEnumerable<dynamic> dapperResult, bool cleanResult = false)
        //private T PreMapIEnumerable(KeyValuePair<PropertyInfo, MemberTypeInfo> kvp, IEnumerable<dynamic> dapperResult, bool cleanResult = false)
        //...

        //Loop through all members
        foreach (KeyValuePair<MemberInfo, MemberTypeInfo> kvp in mtInfos)
        {
            if (kvp.Value == MemberTypeInfo.Ignore)
                continue;
            //Member have a creator
            else if ((kvp.Value & MemberTypeInfo.Creator) == MemberTypeInfo.Creator)
            {
                //MemberDelegate mDel = (MemberDelegate)_MembersCreators[this.TType][kvp.Key.Name];
                Func<dynamic, object> mDel = (Func<dynamic, object>)_MembersCreators[this.TType][kvp.Key.Name];

                if (kvp.Key.MemberType == MemberTypes.Property) ((PropertyInfo)kvp.Key).SetValue(mapped, mDel(dapperResult));
                else ((FieldInfo)kvp.Key).SetValue(mapped, mDel(dapperResult));
            }
            //Member is IDictionary or IEnumerable
            else if ((kvp.Value & MemberTypeInfo.IEnumerable) == MemberTypeInfo.IEnumerable)
            {
                Type t = GetMemberType(kvp.Key);
                //if ((kvp.Value & MemberTypeInfo.Interface) == MemberTypeInfo.Interface) t = ResolveInterface(kvp.Key, dapperResult);
                //else t = GetMemberType(kvp.Key);
                /*
                {
                    //Type of property or field
                    if (kvp.Key.MemberType == MemberTypes.Property) t = ((PropertyInfo)kvp.Key).PropertyType;
                    else t = ((FieldInfo)kvp.Key).FieldType;
                }*/
                bool isAnInterface = (kvp.Value & MemberTypeInfo.Interface) == MemberTypeInfo.Interface;
                bool isNested = (kvp.Value & MemberTypeInfo.Nested) == MemberTypeInfo.Nested;

                //If member is a dictionary
                if (typeof(IDictionary).IsAssignableFrom(t))
                {
                    //Create a dummy dictionary with the dapper's dynamic result which should be equal to the final one
                    DictionaryMapper dictMapper = new DictionaryMapper(dapperResult, kvp.Key.Name, isNested, isAnInterface, cleanResult, t, this);

                    try
                    {
                        if (kvp.Key.MemberType == MemberTypes.Property) ((PropertyInfo)kvp.Key).SetValue(mapped, dictMapper.DummyDictionary);
                        else ((FieldInfo)kvp.Key).SetValue(mapped, dictMapper.DummyDictionary);
                    }
                    catch (Exception err)
                    {
                        throw new CustomException_DapperMapper(
                            $@"DapperMapper.Map: Couldn't map IDictionary member {kvp.Key.Name} with value contained by dynamic object.
Incorrect type of value?: {kvp.Value.ToString()}",
                            err);
                    }
                }
                //Rest of enumerables
                else
                {
                    IEnumerable<dynamic> iEnumDapperResult;
                    //Select current member's values from dynamic
                    if (isNested && !cleanResult)
                    {
                        //Type mType = t; // GetMemberType(kvp.Key);//IEnumerable<T>
                        Type genericType = t.GenericTypeArguments[0];//mType.GenericTypeArguments[0];//T
                        if ((kvp.Value & MemberTypeInfo.Interface) == MemberTypeInfo.Interface)
                        {
                            bool genericIsInterfaceNotIEnumerable =
                                genericType.IsInterface &&
                                !typeof(IDictionary).IsAssignableFrom(genericType) &&
                                !(typeof(IEnumerable).IsAssignableFrom(genericType) && !typeof(string).IsAssignableFrom(genericType));

                            if (genericIsInterfaceNotIEnumerable) genericType = ResolveInterface(genericType, dapperResult);
                        }

                        iDapperMapper nestedMapper = MappersStore.GetMapper(genericType);
                        var nestedParser = new PrePostFixesParser(nestedMapper);

                        iEnumDapperResult = dapperResult
                            .Select(dyn => nestedParser.GetTypeMembersWithoutPrePostFixes(dyn, nestedMapper.NamesList));
                    }
                    else if (!cleanResult) iEnumDapperResult = dapperResult.Select(dyn => parser.RemovePrePostFixesFromDictionary(dyn));
                    else iEnumDapperResult = dapperResult;

                    //Create dummy IEnumerable
                    EnumerableMapper enumMapper = new EnumerableMapper(iEnumDapperResult, kvp.Key.Name, isNested, t, this.TType); ;
                    var dummy = Activator.CreateInstance(t, enumMapper.DummyEnumerable);

                    try
                    {
                        if (kvp.Key.MemberType == MemberTypes.Property) ((PropertyInfo)kvp.Key).SetValue(mapped, dummy);
                        else ((FieldInfo)kvp.Key).SetValue(mapped, dummy);
                    }
                    catch (Exception err)
                    {
                        throw new CustomException_DapperMapper(
                            $@"DapperMapper.Map: Couldn't map IEnumerable member {kvp.Key.Name} with value contained by dynamic object.
Incorrect type of value?: {kvp.Value.ToString()}",
                            err);
                    }
                }
            }//End IDictionary/IEnumerable
            //If Built-in
            else if ((kvp.Value & MemberTypeInfo.BuiltIn) == MemberTypeInfo.BuiltIn)
            {
                string name = parser.RemoveFieldsUnderscore(kvp.Key.Name);
                IDictionary<string, object> dapperDict;
                if (!cleanResult)
                    dapperDict = parser.GetTypeMembersWithoutPrePostFixes(dapperResult.First(), NamesList) as IDictionary<string, object>;
                else
                    dapperDict = dapperResult.First() as IDictionary<string, object>;

                if (!dapperDict.ContainsKey(name))
                    throw new CustomException_DapperMapper(
                        $@"DapperMapper.Map: There's no member in dynamic dapper result with name {kvp.Key.Name}. Cannot Map object.");

                try
                {
                    if (kvp.Key.MemberType == MemberTypes.Property) ((PropertyInfo)kvp.Key).SetValue(mapped, dapperDict[name]);
                    else ((FieldInfo)kvp.Key).SetValue(mapped, dapperDict[name]);
                }
                catch (Exception err)
                {
                    throw new CustomException_DapperMapper(
                        $@"DapperMapper.Map: Couldn't map BuiltIn-type member {kvp.Key.Name} with value contained by dynamic object.
Incorrect type of value?: {kvp.Value.ToString()}",
                        err);
                }
            }
            //if nested
            else if ((kvp.Value & MemberTypeInfo.Nested) == MemberTypeInfo.Nested)
            {
                Type mType = GetMemberType(kvp.Key);

                if ((kvp.Value & MemberTypeInfo.Interface) == MemberTypeInfo.Interface)
                    mType = ResolveInterface(mType, dapperResult);

                //access generic Map method through nongeneric interface method
                iDapperMapper nestedMapper = MappersStore.GetMapper(mType);

                if (nestedMapper == null)
                    throw new CustomException_DapperMapper(
                        $@"DapperMapper.Map: No Mapper found at store for property {kvp.Key.Name} of type {mType.ToString()}.
If you want to map a nested property you have to create a mapper for that property type.");

                if (kvp.Key.MemberType == MemberTypes.Property)
                    ((PropertyInfo)kvp.Key).SetValue(mapped, nestedMapper.NoGenericMap(dapperResult, cleanResult));
                else ((FieldInfo)kvp.Key).SetValue(mapped, nestedMapper.NoGenericMap(dapperResult, cleanResult));
            }
        }

        return mapped;
    }
    /// <summary>
    /// Generic map to IEnumerables. Result HAVE to be ordered by the splitOn column.
    /// </summary>
    /// <typeparam name="R"></typeparam>
    /// <param name="dapperResult"></param>
    /// <param name="splitOn"></param>
    /// <param name="cleanResult"></param>
    /// <returns></returns>
    public R Map<R>(IEnumerable<dynamic> dapperResult, string splitOn = "Id", bool cleanResult = false)
        where R : IEnumerable<T>
    {
        R result;
        Type r = typeof(R);
        List<dynamic> singleObjectDynamic = new List<dynamic>();
        object splitObject = (dapperResult.First() as IDictionary<string, object>)[splitOn];

        if (typeof(IList).IsAssignableFrom(r))
        {
            result = (R)Activator.CreateInstance(typeof(List<>).MakeGenericType(this.TType));

            foreach (dynamic dyn in dapperResult)
            {
                IDictionary<string, object> dict = dyn as IDictionary<string, object>;
                if (!dict.ContainsKey(splitOn))
                    throw new CustomException_DapperMapper(
                        $@"DapperMapper.Map(IEnumerable): Dapper result doesn't have a member with name equals to splitOn parameter.
SplitOn = {splitOn}");

                if (!object.Equals(splitObject, dict[splitOn]) || dapperResult.Last() == dyn)
                {
                    ((IList)result).Add(Map(singleObjectDynamic));
                    singleObjectDynamic.Clear();
                    splitObject = dict[splitOn];
                }
                else
                    singleObjectDynamic.Add(dyn);
            }
        }
        else
        {
            //http://stackoverflow.com/questions/18251587/assign-any-ienumerable-to-object-property
            var addMethod = r.GetMethod("Add", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

            // Property doesn't support Adding
            if (addMethod == null)
                throw new CustomException_DapperMapper(
                    $@"DapperMapper.Map(IEnumerable): Method Add doesn't exist in enumerable type to map.
enumType: {r.Name}.");

            if (r.IsGenericTypeDefinition) result = (R)Activator.CreateInstance(r.MakeGenericType(this.TType));
            else result = (R)Activator.CreateInstance(r);

            foreach (dynamic dyn in dapperResult)
            {
                IDictionary<string, object> dict = dyn as IDictionary<string, object>;
                if (!dict.ContainsKey(splitOn))
                    throw new CustomException_DapperMapper(
                        $@"DapperMapper.Map(IEnumerable): Dapper result doesn't have a member with name equals to splitOn parameter.
SplitOn = {splitOn}");

                if (!object.Equals(splitObject, dict[splitOn]) || dapperResult.Last() == dyn)
                {
                    addMethod.Invoke(result, new object[] { NoGenericMap(dyn) });
                    singleObjectDynamic.Clear();
                    splitObject = dict[splitOn];
                }
                else
                    singleObjectDynamic.Add(dyn);
            }
        }

        return result;
    }
    /// <summary>
    /// Non-generic Map.
    /// </summary>
    /// <param name="dapperResult"></param>
    /// <returns></returns>
    public object NoGenericMap(dynamic dapperResult, bool cleanResult = false)
    {
        IEnumerable<dynamic> ienum = new List<dynamic>() { dapperResult } as IEnumerable<dynamic>;
        return this.Map(ienum, cleanResult);
    }
    /// <summary>
    /// Non-generic Map.
    /// </summary>
    /// <param name="dapperResult"></param>
    /// <param name="cleanResult"></param>
    /// <returns></returns>
    public object NoGenericMap(IEnumerable<dynamic> dapperResult, bool cleanResult = false)
    {
        return this.Map(dapperResult, cleanResult);
    }
    #endregion
}

QUESTION
So, what's happening?
I'm astonished by this one. Am I terribly wrong or class's methods should be able to see same class private methods?
For the DLL I just began it with a new Class Library project in visual studio 2015 community, and when done build it with the typical release configuration, then I went to a console project I'm using to testing it (I just made a simple database there, to have direct Dapper's dynamic results objects to test it) and added reference to the DLL. Could it be that I build the DLL wrong? Do I have to do something more in the testing project apart from referencing the DLL and add the corresponding using namespace?
I've tried searching for private methods, DLLs, private methods in DLLs, private methods in the public class in DLLs, but it seems I'm not able to find anything that solves it. Apart from checking the class and method have the proper access keywords (c# default access is private if no other is specified, right?), and clean, build, rebuild again both solutions, I don't see anymore.
I'm afraid I'm just forgetting something stupid, but it works if I copy-paste the code (or add it with "Add->Existing Item" as I said before") instead of using the DLL, therefore the code is correct, right?
EDIT:
Due to comment of GSerg I'm adding the way I call DapperMapper in the testing project after adding the reference to the DLL:
MapperStore store = new MapperStore();
DapperMapper<Persons> mapper = (DapperMapper<Persons>)store.GetMapper(typeof(Persons));
Persons p = mapper.Map(result);

EDIT2:
As can be seen in the comments, as suggested by GSerg I created a new console project for testing, add the reference to the DLL, copy-paste ONLY the test (mock classes, database), hit F5 and got the same result. I double checked that I builded the DLL and the test project at release mode, and use windows explorer to confirm that there were no DLL's .cs files at the testing project.


text:
Q: Get back the mongo ObjectID when using $http POST in Angular I have a MEAN stack application where I am using $http.post to add objects to a Mongo database that I am persisting in a local array.  Is there a way of returning the generated ObjectID (._id) attribute when I post it?
I am trying to keep "pointers" in the local array so I can GET them later.

A: I don't know how MEAN stack mongo driver is working but in many cases, when you call insert by passing the javascript object, driver after successful insert modify the object with the new generated ObjectId or _v field. The generation of ObjectId in most cases is done by driver and not MongoDB server.
So in many cases returning the same object from post call does give you the ObjectId.
Maybe you can print the object after insert on the console to see if the driver is doing the work for you or not. If it's doing you can just return the same object as a response.
If it isn't doing so, bad luck.


text:
Q: BAD ACCESS error even though property is set to retain I hope someone can tell me why I'm wrong. Here is a snippet of my code:
TimeLogAppDelegate *appDelegate = (TimeLogAppDelegate *)[[UIApplication sharedApplication] delegate];

PickFromListViewController * pl = [[PickFromListViewController alloc] initWithNibName:@"PickList" bundle:nil];
pickList = pl;
[pickList setSearchItems:[appDelegate tableListMutableArray:type ] :NSLocalizedString(type,nil)];
pickList.callingViewController = self;
[pl release];
pickList.responseSelector = [[type lowercaseString] stringByAppendingString: @"Selected:"];
pickList.includeNone = YES;
pickList.includeNew = YES;
[self.navigationController pushViewController:pickList animated:YES];

As you can see, I am releasing pl half-way through, just to create the problem. 'pickList' is obviously a PickFromListViewController and is declared in the Header. I set it up as a property (@property (nonatomic, retain) PickFromListViewController *pickList;) and I @synthesize it.
My problem is:
after pl is release I get a BAD ACCESS error accessing pickList indicating that the pointer is no longer available, but I thought the fact that pickList is synthesized, it would be retained until I release it at dealloc?
Can someone tell me why I am wrong?
Many thanks

A: Setting up your pickList property as (nonatomic, retain) only applies if you access the property via a property accessor, as follows:
self.pickList = P1;

or
[self setPickList:P1];

If you simply assign a value to the member variable:
pickList = P1;

You are bypassing the property accessor methods, so no retain message is sent.


text:
Q: Error Parsing File:LazyUserDataModel.java on Simtay SimpleCRUD I recently downloaded this SimpleCRUD  application by Simtay. I loaded the project on Netbeans 8.0.1 and added the necessary libraries. I get this error:

@Override
      public List load(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) on the class
LazyUserDataModel.java

Below is the class.
package com.nz.simplecrud.controller;

import com.nz.simplecrud.entity.User;
import com.nz.simplecrud.service.DataAccessService;
import com.nz.simplecrud.util.LazySorter;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

/**
 *
 * Custom Lazy User DataModel which extends PrimeFaces LazyDataModel.
 * For more information please visit http://www.primefaces.org/showcase-labs/ui/datatableLazy.jsf
 */

public class LazyUserDataModel extends LazyDataModel<User> implements Serializable{

    // Data Source for binding data to the DataTable
    private List<User> datasource;
    // Selected Page size in the DataTable
    private int pageSize;
    // Current row index number
    private int rowIndex;
    // Total row number
    private int rowCount;
    // Data Access Service for create read update delete operations
    private DataAccessService crudService;

    /**
     *
     * @param crudService
     */
    public LazyUserDataModel(DataAccessService crudService) {
        this.crudService = crudService;
    }

    /**
     * Lazy loading user list with sorting ability
     * @param first
     * @param pageSize
     * @param sortField
     * @param sortOrder
     * @param filters
     * @return List<User>
     */
    @Override
    public List<User> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
        datasource = crudService.findWithNamedQuery(User.ALL, first, first + pageSize);
        // if sort field is not null then we sort the field according to sortfield and sortOrder parameter
        if(sortField != null) {
            Collections.sort(datasource, new LazySorter(sortField, sortOrder));
        }
        setRowCount(crudService.countTotalRecord(User.TOTAL));
        return datasource;
    }

    /**
     * Checks if the row is available
     * @return boolean
     */
    @Override
    public boolean isRowAvailable() {
        if(datasource == null)
            return false;
        int index = rowIndex % pageSize ;
        return index >= 0 && index < datasource.size();
    }

    /**
     * Gets the user object's primary key
     * @param user
     * @return Object
     */
    @Override
    public Object getRowKey(User user) {
        return user.getId().toString();
    }

    /**
     * Returns the user object at the specified position in datasource.
     * @return
     */
    @Override
    public User getRowData() {
        if(datasource == null)
            return null;
        int index =  rowIndex % pageSize;
        if(index > datasource.size()){
            return null;
        }
        return datasource.get(index);
    }

    /**
     * Returns the user object that has the row key.
     * @param rowKey
     * @return
     */
    @Override
    public User getRowData(String rowKey) {
        if(datasource == null)
            return null;
       for(User user : datasource) {
           if(user.getId().toString().equals(rowKey))
           return user;
       }
       return null;
    }

    /*
     * ===== Getters and Setters of LazyUserDataModel fields
     */

    /**
     *
     * @param pageSize
     */
    @Override
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    /**
     * Returns page size
     * @return int
     */
    @Override
    public int getPageSize() {
        return pageSize;
    }

    /**
     * Returns current row index
     * @return int
     */
    @Override
    public int getRowIndex() {
        return this.rowIndex;
    }

    /**
     * Sets row index
     * @param rowIndex
     */
    @Override
    public void setRowIndex(int rowIndex) {
        this.rowIndex = rowIndex;
    }

    /**
     * Sets row count
     * @param rowCount
     */
    @Override
    public void setRowCount(int rowCount) {
        this.rowCount = rowCount;
    }

    /**
     * Returns row count
     * @return int
     */
    @Override
    public int getRowCount() {
        return this.rowCount;
    }

    /**
     * Sets wrapped data
     * @param list
     */
    @Override
    public void setWrappedData(Object list) {
        this.datasource = (List<User>) list;
    }

    /**
     * Returns wrapped data
     * @return
     */
    @Override
    public Object getWrappedData() {
        return datasource;
    }
}

Any help please??

A: Rules for overriding

The argument list should be exactly the same as that of the overridden
  method. The return type should be the same or a subtype of the return
  type declared in the original overridden method in the super class.

LazyDataModel class has the method called load (Primefaces 5)
public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
throw new UnsupportedOperationException("Lazy loading is not implemented.");
 }

You can only Override the above method in LazyUserDataModel if you are using Primefaces 5.
Since the method
load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters)

does not present in the LazyDataModel (PF5) it is normal to have the error.
So how to resolve?
Change Map<String,String> filters to  Map<String, Object> filters (In order to override need to have Same Signature)
Note: Simtay project was written using PF3.4, with LazyDataModel.


text:
Q: powershell reg ex replace whole string with part of string I'm rubbish at reg ex's anyway and been trying all day with no success.
input string:

"fred XY-C4569-32 (Bloggs) 24 acacia (revision 1) road"

I just want to extract

"fred XY-C4569-32"

fred may be shorter or longer e.g. (ted or william) so i cant just sub string in on an index to do it.
I have been trying stuff like
-replace "^([a-z0-9 -]*) ([a-z0-9 \\(\\) -])" , '$1'

but no joy so far
thanks

A: Almost there, just add + or * next to the second character class.
-replace "^([A-Za-z0-9 -]*\\b) [A-Za-z0-9() -]+" , '$1'

DEMO


text:
Q: highstocks align ticks cross multiple charts I'm trying to reinvent the wheel apparently >.>
But issues I'm having is lining up the two axis,
Any help with lining up the multiple charts would be appreciated, I'm drawing a blank.
JSFiddle - http://jsfiddle.net/ah8p3581/1/
Please Follow Link - http://jsfiddle.net/ah8p3581/1/


text:
Q: ag-grid-angular not displaying data in a tabular format I am using ag-grid-angular to display data in a tabular format but all the data gets cluttered into one column.
I am using raw data to populate the ag-grid.

My component.ts file
import { Component, OnInit } from '@angular/core';
import {AgGridModule} from 'ag-grid-angular/main';
import {GridOptions} from 'ag-grid';

@Component({
 selector: 'app-main',
 templateUrl: './main.component.html',
 styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
gridOptions: GridOptions;
columnDefs= [
   {headerName: 'Pokemon', field: 'name'},
   {headerName: 'Type', field: 'type'},
   {headerName: 'Price', field: 'price'},

];
rowData = [
{name : 'Bulbasaur', type: 'plant', price: 1000},
{name : 'Bulbasaur', type: 'plant', price: 1000},
{name : 'Bulbasaur', type: 'plant', price: 1000},
{name : 'Bulbasaur', type: 'plant', price: 1000},
{name : 'Bulbasaur', type: 'plant', price: 1000},
{name : 'Bulbasaur', type: 'plant', price: 1000},
{name : 'Bulbasaur', type: 'plant', price: 1000},
{name : 'Bulbasaur', type: 'plant', price: 1000},
{name : 'Bulbasaur', type: 'plant', price: 1000},
{name : 'Bulbasaur', type: 'plant', price: 1000},
{name : 'Bulbasaur', type: 'plant', price: 1000}
];
constructor() {
this.gridOptions = <GridOptions>{
  rowCount: 10
};
}

ngOnInit() {
}

}

the rowData and colDefs are declared in the above code
My component.html code:

Grid example

<ag-grid-angular class = "ag-fresh"
            [rowData]="rowData"
            [columnDefs]="columnDefs"
             [gridOptions]="gridOptions"
            >
 </ag-grid-angular>

My app.module.ts file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { MainComponent } from './main/main.component';
import {AgGridModule} from 'ag-grid-angular';

@NgModule({
 declarations: [
 AppComponent,
 MainComponent
],
imports: [
BrowserModule,
AgGridModule.withComponents(MainComponent)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

A: Add the following into styles  section of .angular-cli.json
"../node_modules/ag-grid/dist/styles/ag-grid.css",
"../node_modules/ag-grid/dist/styles/theme-fresh.css",

A: In the tutorial on building an ag-Grid with Angular CLI (https://www.ag-grid.com/ag-grid-angular-angularcli/#creating-a-angular-project-with-ag-grid) on the bottom, they tell you to put the style sheets for ag-Grid into the angular-cli.json file. Like ishabi described.
To complete the answer and not just post the link:
Add the following two lines to your .angular-cli.json file:
 "../node_modules/ag-grid/dist/styles/ag-grid.css",
 "../node_modules/ag-grid/dist/styles/ag-theme-balham.css"

Change the second line according to the theme you are using.


text:
Q: TYPO3 8.7 - Link Target ist missing in navigation for page typ external URL After update from TYPO3 7.6.16 to 8.7 in my navigation (TMENU) the target _blank is no longer output for pages of typ external URL. In page properties the target flag _blank is entered. Any hints?

A: Try this, working for me:
lib.mainmenuu = HMENU
lib.mainmenuu {
    special = directory
    special.value = 1
    1=TMENU
    1.wrap=
|

    1.NO {
        # do not create a link here else there are double  tags
        doNotLinkIt = 1
        wrapItemAndSub=
|

        stdWrap.cObject = CASE
        stdWrap.cObject {
        key.field = doktype
        default = TEXT
        default {
            field = title
            typolink.parameter.field = uid
            stdWrap.htmlSpecialChars = 1
        }
       # 3 = external url
       3 = TEXT
       3 {
           field = title
           typolink.parameter.field = url
           typolink.extTarget = _blank
        }
      }
   }
}

Here, use your news detail page id instead of 27. this will override default page title with current detail news title.


text:
Q: Is there a ui-component for vaadin that I can use for text highlighting? I am new to Javascript and Vaadin. I am looking for a text component that allows highlighting and annotation. This is what I have in mind.
I want to display a couple of paragraphs on my web-page and then the user should be able to select certain sections of text and add a highlight. When the user clicks on the highlighted section, I want to show a context-menu with some operations.
Is there a vaadin component or some other javascript component I can use or modify to achieve what I am looking for?
If there do not exist any components, can you suggest the steps that I need to do to create such a component.

A: Some options:
Rich text area: https://vaadin.com/book/-/page/components.richtextarea.html
Context menu: https://vaadin.com/directory#!addon/69
I made a quick demo project with a rich text area & a context text area.
In the bottom text area I have right clicked & you can see a context menu appears with "Insert" & "Clean". This is customisable & just needs some css styles.

You could use a rich text area to edit your text, similar to wikipedia? Maybe by having an edit tab or an edit option in your context menu?

Or you could edit the text in a pop up panel, activated on a double click? Might look cool!
See http://demo.vaadin.com/sampler/#ui/structure/popup-view
(You can put any layout with components on this)
Or you could put your text in a read only text area & could even use the context menu to change the background color of your highlighted text?
I'll keep looking...


text:
Q: Drop down list inside a pop up window (comes up when button is pressed) Currently I'm trying to create a button which creates a popup box which in turn has a drop down list, like in here. However, I'm having trouble figuring out how to put the drop down list inside the pop up window. Can anyone help?
I currently have a pop up window with a form, but I want to change this form into a drop down list. refer this jsfiddle

Do you have an agreement or a conflict?

<button onclick="myFunction()">Try it</button>

A: Here's a possible demo solution.

$('#dialog').hide();
$('#target').click(function() {
  $('#dialog').show();
  $('#dialog').dialog();
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>

  <select>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>

<input type="button" id="target" value="click" />

A: You are using prompt which is default for all browser having input.
If you want popup with select dropdown you have to create custom popup.
Here is DEMO using BootStrap model.

A: when dropbox change event fires catch selected item and do your work or just use this

  <select id="dd">  <option value="Select Cars...">Select Cars...</option>   <option value="volvo">Volvo</option>   <option value="saab">Saab</option>   <option value="mercedes">Mercedes</option>   <option value="audi">Audi</option> </select>

$( "#dialog" ).hide();
$( "#dd" ).change(function() {
$('#dropdownselectitem').html($('#dd').val());
      $( "#dialog" ).show();
    $( "#dialog" ).dialog();
});


text:
Q: Использование БД "HP Vertica" через dbplyr(R) в Win10 Поскольку Vertica работает только в Linux, установил Vertica 10-Dev  в виртуальной машине. Как ее можно использовать в Win10 через dbplyr(R)? Перейти полностью в Линукс не вариант. Может у кого то есть опыт в аналогичной ситуации.

A: Подключиться к Verica можно через ODBC драйвер. Для есть несколько реализаций ODBC: RODBC, RJDBC, odbc. dbplyr может использовать любое подключение, класс которого унаследован от DBIConecction.
Пример с использованием RJDBC:
library(RJDBC)
drv <- JDBC(driverClass="com.vertica.jdbc.Driver", classPath="full\path\to\driver\vertica_jdbc_VERSION.jar")
con <- dbConnect(drv, "jdbc:vertica://host:5433/db", "username", "password")
tbl(con)

jar необходимо скачать с официального сайта. Там же можно найти и ODBC драйвер для Linux/Windows и использовать его с пакетом odbc.


text:
Q: What are Django swappable models? What are swappable models in Django? And Why sometimes when we do a migration a swappable dependency appears in Django migration files?
I have searched for this concept in Django but I did not understand what it really does?! Give me an example of the usage and functionality of this feature in Django.


text:
Q: What is the correct way to alter timestamp values in a tablerow for MariaDB On a MariaDB Server Version 10.1.34-MariaDB I have a database d with table timestamp_manipulation_experiments and each row in t contains a field called timestamp of type timestamp(6). Values in those fields look something like '2012-04-21 10:09:20.000000'.
How can one correctly alter the field in a way that refers to the old value? Let's say one would like to de/increase the timestamp of the row with id = 2 by x minutes and y seconds or even a week.
Trying something like
UPDATE d.timestamp_manipulation_experiments
SET `timestamp` = `timestamp` + '0001-01-01 01:01:01' WHERE id = 2;

and then looking at the result
SELECT * FROM d.timestamp_manipulation_experiments;

caused some mistakes and did not work.

A: Two functions from https://mariadb.com/kb/en/library/date-time-functions/
have been pointed out to me.
Both of them work fine.

*

*DATE_ADD see https://mariadb.com/kb/en/library/date_add/
For Example:
-- add 2 Minutes and 1 Second to the current timestamp and look at the result
UPDATE d.timestamp_manipulation_experiments
SET `timestamp` = DATE_ADD(`timestamp`, INTERVAL '2:1' MINUTE_SECOND) WHERE id = 2;
SELECT * FROM d.timestamp_manipulation_experiments WHERE id = 2;

*

*TIMESTAMPADD see https://mariadb.com/kb/en/library/timestampadd/
For Example:
-- add 1 week to the current timestamp and look at the result
UPDATE d.timestamp_manipulation_experiments
SET `timestamp` = TIMESTAMPADD(WEEK,1,`timestamp`) WHERE id = 2;
SELECT * FROM d.timestamp_manipulation_experiments WHERE id = 2;


text:
Q: How does webserver handle multiple connections on the same port TCP connection is defined by [client IP address:outgoing port - server IP address:incoming port]. Web server listens on one port but handles multiple tcp connections on the same port - how is that achieved? Is one connection somehow transferred to other incoming port to be able to listen to new connection?

A: Even if the server IP and server port are the same, the client IP or client port are different. So there is no problem, from the TCP point of view.
If you want more details, in the server code there is a socket destined to accept connections, that will be the listening socket and it will be bound to the server port (and optionally to the IP). When a client connects to this port the listening socket accepts it and a new connected socket is returned.
Even if all the server sockets use the same port, only one of them is actually listening, so there is no problem.