text:
Q: How to correct a large number of duplicate records I am trying to correct a large number of duplicate records in SQL Server, is there a way I can do this as a bulk update, rather than running an update script for each row?
The data looks like this:
client | voucher_no | sequence_no | id
-------+------------+-------------+------
AA     | 11111111   | 1           | 0001
AA     | 11111111   | 1           | 0002
AA     | 11111111   | 1           | 0003
AA     | 11111112   | 13          | 0004
AA     | 11111112   | 13          | 0004
AA     | 11111113   | 28          | 0005
AA     | 11111113   | 28          | 0006
AA     | 11111114   | 17          | 0007
AA     | 11111114   | 17          | 0008
AA     | 11111115   | 23          | 0009
AA     | 11111115   | 23          | 0010

I am have been trying to find a way to update the records in one go, so that the results of the script would be:
client | voucher_no | sequence_no | id
-------+------------+-------------+------
AA     | 11111111   | 1           | 0001
AA     | 11111111   | 2           | 0002
AA     | 11111111   | 3           | 0003
AA     | 11111112   | 13          | 0004
AA     | 11111112   | 14          | 0005
AA     | 11111113   | 28          | 0006
AA     | 11111113   | 29          | 0007
AA     | 11111114   | 17          | 0008
AA     | 11111114   | 18          | 0009
AA     | 11111115   | 23          | 0010
AA     | 11111115   | 24          | 0011

UPDATE table_a
SET sequence_no = (SELECT ROW_NUMBER() OVER (PARTITION BY sequence_no ORDER BY t.client, t.voucher_no, t.sequence_no ))
                   FROM table_a AS t
                   WHERE t.id IN (0002, 0003, 0005, 0007, 0009, 0011)

The above works fine for the first id in the list, but it updates the remaining records with the same sequence_no as the first.
So I end up with:
client | voucher_no | sequence_no | id
-------+------------+-------------+------
AA     | 11111111   | 2           | 0002
AA     | 11111111   | 2           | 0003
AA     | 11111112   | 2           | 0005
AA     | 11111113   | 2           | 0007
AA     | 11111114   | 2           | 0009
AA     | 11111115   | 2           | 0011

Which can cause further issues if the sequence number is updated to one that already exists for that client and voucher_no combination.
I have also tried wrapping the above in a cursor, thinking that the query isn't getting the chance to update with the correct sequence_no for the next id number, but that hasn't worked either

A: I managed to solve this issue, by using the following code:
DECLARE @client VARCHAR(2)
DECLARE @voucher_no INT
DECLARE @sequence_no INT
DECLARE @id INT

DECLARE cursor_results CURSOR FOR
WITH T AS
(
    SELECT *, COUNT(*) OVER (PARTITION BY client, voucher_no, sequence_no) AS cnt
      FROM table_a
)

  SELECT t.client, t.voucher_no, t.sequence_no,t.id
    FROM T AS t
   WHERE t.cnt > 1
   AND agrtid IN (0002, 0003, 0005, 0007, 0009, 0011)
ORDER BY t.client, t.voucher_no, t.sequence_no DESC

OPEN cursor_results
FETCH NEXT FROM cursor_results INTO @client, @voucher_no, @sequence_no, @id
WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE @new_sequence_no INT = (SELECT MAX(sequence_no) + 1 FROM table_a WHERE client = @client AND voucher_no = @voucher_no)
    UPDATE table_a
       SET sequence_no = @new_sequence_no,
           last_update = GETDATE(),
           user_id = 'USR'
     WHERE id = @id
       AND client = @client
       AND voucher_no = @voucher_no

FETCH NEXT FROM cursor_results INTO @client, @voucher_no, @sequence_no, @id
END

CLOSE cursor_results
DEALLOCATE cursor_results

While this probably isn't the best way to approach this problem using the cursor allows me to step through the records and update them individually, before moving onto the next.
Setting @new_sequence_no in this manner also ensured I was getting the correct MAX(sequence_no) + 1 for the record I was on at that time, rather than all of the duplicates being given the MAX(sequence_no) + 1 for the first record.


text:
Q: How to count one to many i have two tables one Job Category with the structure | id | name | and the other one jobs with the structure | id | job_name | job_category |
How to count how many jobs are in each category?

A: select c.name, count(j.id)
from job_category c
left join jobs j on j.job_category = c.name
group by c.name

A: Why do you need join at all? Is it not
select job_category, count(*)
from jobs
group by job_category

If not, do post your own query (and, possibly, some sample data which might help us help you).
[EDIT, after reading comments]
It appears that my (over)simplified "solution" lacks in some details. True, it shows categories with no jobs, while the OP asked that those should also be displayed having "0" as a result.
Outer join with appropriate COUNT function would fix that; here's an example.
SQL> with job_category(id, name) as
  2    (select 1, 'categ 1' from dual union
  3     select 2, 'categ 2' from dual
  4    ),
  5  job (id, job_name, job_category) as
  6    (select 100, 'job 1', 1 from dual union
  7     select 200, 'job 2', 1 from dual
  8    )
  9  select c.name, count(j.id)
 10  from job_category c left join job j on j.job_category = c.id
 11  group by c.name
 12  order by c.name;

NAME    COUNT(J.ID)
------- -----------
categ 1           2
categ 2           0

SQL>

A: You can do it with a left join (see other answers) or with a subquery:
SELECT
    c.Name
,   (SELECT COUNT(*) FROM jobs j WHERE j.category_id=c.id) AS Count
FROM job_category c

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flex cancel a change event on a Tree Brief details: I'm using Flex 3.5.
I have a Tree component that's used as a navigation menu between different 'pages'.
When the user clicks a certain option in the menu, I switch the 'page' by switching between State components in my application.
The thing is that when the user indeed clicks an option in the menu, I want to perform a validation of some of the information in a certain component. If the validation fails, I show an alert, and I'd like to prevent the navigation to the other page. One part of this is simply not changing the currentState of the document, but the tree component still goes on with the change event, and the result is page A still being shown on the screen, whereas the selected option in the tree is page B (to which the user wanted to navigate, but failed since some of the information wasn't valid).
I tried to figure out how I can cancel the change event on the tree component itself.
The thoughts I had didn't quite fit nicely:
I searched for a slightly different event (such as 'changing' or 'startChange') on which I can call the stopPropagation() method (since the regular 'change' event is not cancelable), but none exists for the Tree component.
I also thought about always saving the current option that's selected in the Tree component by myself, and when the validation fails, I will set the Tree's selectedItem to that saved option. That's also ugly because such an action will raise another change event on the Tree, thus another change to the States components, and another population of the page in which I'm already at. That's something I really don't want to do.
I also though about using a different component, such as Menu (and I also found an implementation of a vertical Menu), but that doesn't even seem to help. The same problem will exist there.
Is there a proper way to do this?
There must be a best-practice for preventing a change process to commit!

A: <?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:local="*">

    <mx:Script>
    <![CDATA[
        import mx.controls.Alert;
        import mx.events.ListEvent;

        private function tree_changeHandler(event:ListEvent):void
        {
            trace("Change, selectedItem.label is: " + tree.selectedItem.label);
        }

        protected function tree_itemClickHandler(event:ListEvent):void
        {
            var data:Object = event.itemRenderer.data;
            if (!tree.isItemSelectable(data))
                Alert.show("Item \"" + data.label + "\" is not selectable");
        }

    ]]>
    </mx:Script>

    <local:MyTree id="tree" change="tree_changeHandler(event)" itemClick="tree_itemClickHandler(event)">
        <local:dataProvider>
            <mx:ArrayCollection>
                <mx:Object label="Label 1"/>
                <mx:Object label="Label 2"/>
                <mx:Object label="Label 3 (non-selectable)"/>
                <mx:Object label="Label 4"/>
            </mx:ArrayCollection>
        </local:dataProvider>
    </local:MyTree>

</mx:Application>

Source for MyTree.as:
package
{
import mx.controls.Tree;

public class MyTree extends Tree
{

    override public function isItemSelectable(data:Object):Boolean
    {
        if (!super.isItemSelectable(data))
            return false;

        var label:String = data.label;
        if (label.indexOf("non-selectable") >= 0)
            return false;

        return true;
    }

}
}

A: Eventually I found the place to put the code that determines each item's selectability: when the information that should be validated is changed, I perform the validation, and according to its result I set a property to all of the items in the Tree component, indicating whether they can be navigated to or not. If the validation was successful, the property is set to allow navigation, and if unsuccessful, it is set not to allow navigation.
Like Maxim, I extend the Tree component and overrode the isItemSelectable() method to check this property of the specified item, this way preventing the change process.
The access between the view that holds the information to-be-validated, and the view that holds the Tree component (they are not necessarily the same view) is done via a presentor class that holds both views (I use the MVP mechanism). This is not the most elegant design, but it is much better than anything else I could have thought of. The alleged problem with the design is the coupling between the views and the complexity of the presentor, that has to deal with more than one view and have methods that are related to the interaction between the views (instead of methods that represent actions of a specific view). The thing is that business-wise, the two views are coupled (since the information in one affects the navigation tree in the other), thus the presentor couples between them. The coupling is also done through the interface of the presentor, so that each view doesn't really "know" the other view.
I hope it might help other people.
Thanks,
Daniel


text:
Q: Java converting pixel to dp I have a pixel input and i want to convert it to DP using Java.
what formula should i use? or there is an external library than i can use!?
This code is common in android sdk. Is there a way to use it outside of Android?
public static float convertPixelsToDp(float px){
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        float dp = px / (metrics.densityDpi / 160f);
        return Math.round(dp);
    }

Iam not using it for android i use it in a java application so i want to know how to do it in java not android.


text:
Q: fluxbox keyboard switch german, greek (modern) and polytonic greek Where can i find a list of keyboard-layout codes to switch between german, greek (modern) and polytonic greek in fluxbox menu?
vim ~/.fluxbox/menu

[begin] (fluxbox)
[include] (/etc/X11/fluxbox/fluxbox-menu)
[submenu] (Keyboards)
[exec] (de) {setxkbmap de}
[exec] (greek) {setxkbmap greek}
[exec] (polytonic greek) {setxkbmap polytonic greek}
[end]

A: /usr/share/X11/xkb/rules/xorg.lst has all options and variants for xkbmap
polytonic is a variant so would use setxkbmap gr -variant 'polytonic'.
Fluxbox menu look correct.


text:
Q: Create an array of object in localStorage This code is about storing data in localStorage. If localStorage is yet empty I want to create an array of such type:
(Key:)Events (Value:)[{Date: "", Event: "", Participants: "", Description: ""}]

If there's yet some data in localStorage then runs the code else if...
if (tdAttr) {

    var fastDate = tdAttr.getAttribute('data-cell');
    var fastEvent = fastAddEvent.value;

    var events = JSON.parse(localStorage.getItem('events')) || [];
    localStorage.setItem('events', JSON.stringify(events));

    var addFastEvent = function () {

        if (events.length == 0) {
            //JS doesn't see the "events" variable inside this scope
        } else if (events.length > 0) {

            for (var i = 0; i < events.length; i++) {

                if (events[i].Date == fastDate) {

                    events[i].Event = fastEvent;
                    events[i].Participants = "";
                    events[i].Description = "";

                };

                break;

            };

        };

        localStorage.setItem('events', JSON.stringify(events));

    };

    addFastEvent();

};

So, issue #1: Why doesn't JS define the events variable inside the firts if condition (console.log:
Uncaught TypeError: Cannot read property 'length' of undefined)?
Though after else if... it does.
Issue #2:
How do I create my array
(Key:)Events (Value:)[{Date: "", Event: "", Participants: "", Description: ""}]

inside the first if condition?
I tried
if (events.length == 0) {
    var events = [];
    arr.push({
        Date: fastDate,
        Event: fastEvent,
        Participants: "",
        Description: ""
    });

}

But it still doesn't see the variable events (even inside the if condition) and shows me the error.
UPD I managed to solve the issue #2:
       if (events.length == 0) {

                            localStorage['events'] = events.push({

                              Date: fastDate,
                              Event: fastEvent,
                              Participants: "",
                              Description: ""

                            });
                        }

Though, still can't understand why the variable is "invisible" inside the first if condition. Let's say, there's no stored items when the condition starts to check, but I understand my variable
     var events = JSON.parse(localStorage.getItem('events')) || [];

like this - We get stored items, if there are no stored items, we create an array.
It seems like JS understands it like - We get stored items or an existing yet array


text:
Q: Binary Bayesian Network complexity Imagine a Bayesian Network with binary random variables, with the structure of a binary tree of arbitrary height:

I want to find the minimum number of probabilities that I must store at depth k to describe the entire tree up to that point (i.e. the joint distribution)

*

* Starting at depth 0 (the root node A), I only need to store 1 probability, i.e. $P(A = True) = P(a)$ because I get $P(\bar{a}) = 1 - P(a)$ for free.

* At depth 1, I need to store $P(ABC) = \sum_{ABC} P(A)P(B|A)P(C|A)$.

*
*I need to only store $P(a), P(b|a), P(b|\bar{a}), P(c|a), P(c|\bar{a})$ = 5 probabilities. This is because from $P(b|a)$ I get $P(\bar{b}|a) = 1 - P(b|a)$, and $P(\bar{c}|a)$ similarly.

*At depth 2, using similar logic, I store 1 + 4 + 8 = 13 probabilities

*And so on.

So at depth k, I store $\sum_{i=0}^{k} 2^{i+1}-1$ probabilities.
Is this correct?

A: I'm no expert in this field, but I think your reasoning is correct. (I found this pdf helpful in writing the answer.)
Your network is a directed acyclic graph (DAG), which means that the probabilities you need at a particular node are the conditional probability of that node (say, $X$), given every combination of its ancestors (say, $Y_i$, where $i = 1...n$). So, in the general case of a node with $n$ ancestors, you'd need to store $2^n$ probabilities for that particular node (since the "truth table" would have $2^n$ rows).
In your case, each node has only one ancestor. So, you need $2^1 = 2$ probabilities ($P(X|Y)$ and $P(X|\bar{Y})$) for every node that has an ancestor. So, for the overall tree, with $N$ nodes with ancestors and 1 node without an ancestor, you'd need $2*N$ probabilities for the former + 1 probability for the latter.
I think this works out to be the same as your formula (which, by the way, you can simplify to $2^{k+2} - 3$), since a complete binary tree at level $k$ (in your notation) has $2^{k+1} - 1$ total nodes and therefore $2^{k+1} - 2$ nodes with ancestors and 1 without.

A: From the law of total probability, the state of node $n_j$ given the state of the input node $n_i$ can be expressed as,
(1) $P(n_j) = P(n_j|n_i)P(n_i) + P(n_j|\bar n_i)P(\bar n_i),  \forall j>0$,
Now if we can assume,
(2) $P({n_j=1}|n_i)P(n_i)+P({n_j=1}|\bar n_i)P(\bar n_i) = 1$,
that is, $n_j$ is entirely determined by the state of the input node $n_i$, then for the $N-1$ non-root nodes we will only need $N-1$ probabilities.
If we can't assume (2) above then we will need to store the behavior of each node for both input states. For the $N-1$ non-root nodes with binary input this will be $2(N-1)$ PDFs. The total number of PDFs including the root that has no binary input, would be,
(3) Total Quantity of PDFs = $2N-1$, where N = total number of nodes.
EDIT: If you want this total in terms of specific depths, then for depth k we have $2^{k+1}, k>0$.


text:
Q: How to use sed ssh to change value i need to change value in file with ssh command sed.
<serverport>SOMERANDOMNUMBER</serverport>

I need to change '22127' to '22222'.

A: Try doing this :
sed -i.bak 's@<serverport>[0-9]\+</serverport>@<serverport>22222</serverport>@' file

But if it's XML, better use xmlstarlet


text:
Q: ajax antiforgery token json I am securing my application against cross-site scripting using anti forgery token
Development environment is VS 2012, MVC4, knockout
I have placed anti-forgery token as follows
<form id="__AjaxAntiForgeryForm" action="#" method="post"><%= Html.AntiForgeryToken()%></form>

In my ajax call I also want to send data. My ajax call is as follows
            $.ajax({
                url: VirtualDir + '/Tasks/StartTask/',
                asynch: false,
                type: 'POST',
                data: { "__RequestVerificationToken": token, oTaskData: JSON.stringify(item), whichTab: self.CurrentTab },
                success: function (data) {
                    InitializeData(data);
                    self.LoadData(data);
                }
            })
        };

My controller code is as follows
    [ValidateAntiForgeryToken]
    [Authorize]
    public JsonResult StartTask(TaskData oTaskData, string whichTab)
    {
        int TaskID = oTaskData.TaskID;
        int LoggedInEmployeeID = Convert.ToInt32(System.Web.HttpContext.Current.Session["EmployeeID"]);
        TaskRepository oTaskRepository = new TaskRepository();
        return Json(oTaskRepository.TaskChangeStatus(TaskID, LoggedInEmployeeID, TaskConstants.IN_PROGRESS, whichTab), JsonRequestBehavior.AllowGet);
    }

In controller, value of whichTab parameter is received but oTaskData is null
If I remove anti-forgery token then data is received properly in controller
How can I use antiforgery token along with JSON data?

A: When sending multiple values in JSON. You have stringify like this:
I am separating JSON string from the Ajax Request to make it clear.
    var sData = JSON.stringify({
       __RequestVerificationToken : token,
       oTaskData: item,
       whichTab: self.CurrentTab
    });

In Ajax Request Add this: contentType: 'application/json',
To show you are sending Json data.
and you are returning Json, so also dataType: 'json'
 $.ajax({
      url: VirtualDir + '/Tasks/StartTask/',
      asynch: false,
      type: 'POST',
      data: sData,
      contentType: 'application/json',
      dataType: 'json'
                success: function (data) {
                    InitializeData(data);
                    self.LoadData(data);
                }
            });

EDIT:
If the Above doesn't work then use Answer here:
Use the HEADER of Ajax request.
https://stackoverflow.com/a/24394578/1910735
var headers = {};
headers['__RequestVerificationToken'] = token;

$.ajax({
    type: 'POST',
    url: '/MyTestMethod',
    contentType: 'application/json; charset=utf-8',
    headers: headers,
    data: JSON.stringify({
         oTaskData: item,
           whichTab: self.CurrentTab
    }),
    dataType: "json",
    success: function () {},
    error: function (xhr) {}
});

You will have to create this Attribute Class : ValidateJsonAntiForgeryTokenAttribute, You can see in the answer: https://stackoverflow.com/a/24394578/1910735


text:
Q: Cannot modify custom tableview cell properties I have tried everything and a UIActivityMonitorView wont spin when I set in in didSelectRowForIndexPath. I access the custom tableview cell with
CustomCell *cell = (CustomCell *) [tableview cellForRowAtIndexPath];
I can see the cell and its properties initialized in the debugger but when I try modifying anything on the cell nothing changes. I set the cells activityMonitor IBOutlet to start spinning in a performSelectorAfterDelay woth no luck. When I try to set the cells alpha to 0 nothing happens either.
If, however I set the spinner to spin via IB it works when the cell loads up.
I also tried to access it via the tag, but it didnt work.
How does one set the properties on a custom tableview cell?

A: Check out Customizing Cells in the Table View Programming Guide. The specifics, though, vary between Storyboards, NIBs, or programmatically created UITableViewCell cells. You have to share your tableView:cellForRowAtIndexPath: and your tableView:didSelectRowAtIndexPath: for us to diagnose what's going on. Below, I'll show you an example of using the spinning activity indicator, but there's nothing special going on here. I suspect that there's something simple going on with your app, but not something we can help you with unless we can see your code.
But, to show you an example, assuming you've subclassed UITableViewCell with an interface defined in Interface Builder. Here is a sample didSelectRowAtIndexPath that starts the spinning activity indicator, and turns it off 15 seconds later.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TestCell *cell = (TestCell *)[tableView cellForRowAtIndexPath:indexPath];

    // I have a model in my app for the sections of the tableview, as well as the rows,
    // so let's get the pointer to the appropriate model information. Your implementation
    // may differ, but hopefully you get the idea.

    Section *section = self.sections[indexPath.section];
    Row *row = section.rows[indexPath.row];

    // because we selected this row, start the activity indicator

    [cell addActivityIndicator];

    // let's flag the row in our model to indicate that we're busy here (so if and when
    // we represent this row, we'll know if we're busy or not)

    row.loading = YES;

    // and let's asynchronously dispatch a "stop activity indicator" in 15 seconds

    int64_t delayInSeconds = 15.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        // because this is happening asynchronously, let's re-retrieve the cell
        // pointer, just in case it might have scrolled off of the visible screen
        // as is no longer visible or the pointer to the cell might have changed

        TestCell *currentCell = (TestCell *)[tableView cellForRowAtIndexPath:indexPath];

        // let's remove the activity indicator

        [currentCell removeActivityIndicator];

        // let's flag our model to indicate that this row is no longer loading

        row.loading = NO;
    });
}

And in this scenario, I need to make sure that my tableView:cellForRowAtIndexPath: looks at the model data to figure out whether it needs to present the spinning activity indicator, too:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"TestCell";
    TestCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // if I'm using storyboards, the following isn't needed, but if not, I might use something
    // like the following to load the custom cell from a NIB

    //if (cell == nil)
    //{
    //    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TestCell" owner:self options:nil];
    //    cell = (TestCell *)[nib objectAtIndex:0];
    //}

    // this happens to be my model structure, where I have an array of sections,
    // and each section has its array of Row objects for that section

    Section *section = self.sections[indexPath.section];
    Row *row = section.rows[indexPath.row];

    // each "Row" object has two text fields, which I use to update the
    // two labels in my TestCell subclass of UITableViewCell

    cell.label1.text = row.text1;
    cell.label2.text = row.text2;

    // for this row of this section, figure out whether I need to start animating
    // the UIActivityIndicator

    if (row.loading)
        [cell addActivityIndicator];
    else
        [cell removeActivityIndicator];

    return cell;
}

And in my subclassed UITableViewCell here is the code to add an activity indicator and to remove it:
@interface TestCell ()

@property (strong, nonatomic) UIActivityIndicatorView *activity;

@end

@implementation TestCell

- (void)addActivityIndicator
{
    if (!self.activity)
    {
        self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.activity.center = self.contentView.center;
    }
    [self.contentView addSubview:self.activity];
    [self.activity startAnimating];
}

- (void)removeActivityIndicator
{
    if (self.activity)
    {
        [self.activity stopAnimating];
        [self.activity removeFromSuperview];
        self.activity = nil;
    }
}

@end

This is all just a simple example of how it could work, but implementations may vary greatly (depending upon NIBs, storyboards, creating controls programmatically, the nature of your app's model, etc.). Rather than trying to retrofit the above code for your app, it will probably be easier for you to share your code with us and we'll hopefully be able to spot the problem pretty quickly. The problem is probably something simple.


text:
Q: No such module "CreateMLUI" I am using macOS Mojave Beta (10.14 18A293u) and Xcode 10.0 Beta (10L176w). I created a Swift Playground and I am unable to import CreateMLUI framework in order to use it. I keep getting an import error.

I have tried creating both an iOS Playground and a macOS Playground
Anyone knows what I am doing wrong?
Thanks in advance.

A: While macOS Mojave and Xcode 10 are in beta you may experience bugs while trying to use CreateML.
@Koen from one of the comments in my question found a topic in Apple  Developer Forums with some workarounds. What I did was:

*

*Create a new single view Mac OS (NOT iOS) playground

*Use a completely different name if already created a buggy playground (this is important)

*Add the import CreateMLUI line

*Remove all the other boilerplate code

A: I found the answer to this problem in the apple developers forum (Can't find the exact link to the post).
You simply have to select the macOS tab when creating a playground.

A: When you create the playground make sure you select "macOS" tab instead of. "iOS".

A: This feature is no longer supported in this environment. You can complete this task in the Create ML app. Follow these steps:

Xcode -> Toolbar -> Open Developer Tool -> Create ML -> New Document

A: *

*Open Xcode menu

*Choose Open Developer Tool > Create ML

*Press New Document

*Select Image Classification

*Specify name and a place where the project will be saved

A: In new versions of macOS, the CreateMLUI library has been deprecated and removed.  Instead, create models in CreateML, a developer application inside Xcode.


text:
Q: NSWindow display alert when attempt to close How can I display an NSAlert when an NSWindow attempts to close?  This will also have to be turned on and off.

A: NSWindow's delegate has a windowShouldClose: method that will allow you to customize this. There's also NSWindow's documentEdited methods that let you mark a document as having unsaved changes, which might interest you.


text:
Q: iOS - UIView subview has different size than super view I'm creating an UIViewController with a subview that has the same width as the super view and half the height of the super view.
Here is how it looks in the storyboard:

These are the constraints I added vor the View Punkte:

Plus I added the "Equal Height" constraint.
The constraints work correctly. The subview stays the same when I rotate the device.
But the problem are the frame sizes.
When I print the sizes of both views, that's what Xcode returns (The code is inside ViewDidLoad:
print(self.view.bounds) // returns --> (0.0, 0.0, 375.0, 667.0)
print(viewPunkte.bounds) // returns --> (0.0, 0.0, 600.0, 300.0)

Why is this happening? The width of the viewPunkte is not correct!
What is the solution to this problem?
Thanks.

A: If you are inspecting the frame of a view during viewDidLoad then you are probably doing so after the views have been initialized but before they have ever completed a layout pass. Your controller's view has not yet been added to the window and you should not assume that the frames of any of your views reflect what their final sizes will be.
Consider why you think you need to inspect view frames at this point in time.

A: Usually, the size of view controller's view in storyboard is not equal to simulator.It's square in storyboard but iOS devices are not in square shape.
It seems that you run your project in an iPhone/iPhone simulator
therefore:
self.view.bounds = iPhone screen size(pt) = (375.0, 667.0)
and you set up the height and width constraint of your 'viewPunkte', which are equal to the constant 300 & 600.
thats why the size of viewPunkte is constantly equal to (600.0, 300.0)

A: You can use
-(void) viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    //NSLog dimensions.
}

This should give you the correct dimensions since this event means  its view has just laid out its subviews.
This is fired after viewdidload and before viewDidAppear. Orientation change can also fire viewDidLayoutSubview.


text:
Q: Implementing a single class with different set of arguments I am working on a data parser for a project. I have to parse a file that may contain two different types of objects:
Type-1:
sb0 hardrectilinear 4 (0, 0) (0, 82) (199, 82) (199, 0)
Type-1 has to be stored as a class block, with the following attributes: BlockID, BlockType, number_of_edges, lowerleft, lowerright, upperleft, upperright.
Type-2:
sb1 softrectangular 24045 0.300 3.000
Type-2 also has to be stored as a class block, with the following attributes: BlockID, BlockType, area, min_aspectRatio, max_aspectRatio.
Is it possible to build a single class called "block", with a different set of arguments depending on the attribute "BlockType"? I have built a parser but I used two different classes for each BlockType using sstream.
I have shown my implementation of the parser when the text file to be parsed contains only type-2. Any ideas on how I can do this using a single class?
SoftBlock.h:
#ifndef SOFTBLOCKLIST_H_
#define SOFTBLOCKLIST_H_
#include <string>
#include <vector>
#include "SoftBlock.h"
#include <fstream>

class SoftBlockList {
public:
    SoftBlockList(std::string input_file);

    std::vector<SoftBlock> get_softblocklist();

private:
    std::vector<SoftBlock> softblocklist;

};

#endif /* SOFTBLOCKLIST_H_ */

SoftBlock.cpp:

#include "SoftBlockList.h"
using namespace std;

SoftBlockList::SoftBlockList(string input_file) {
    ifstream filehandle;
    filehandle.open(input_file.c_str());
    string temp;
    while(filehandle.good()){
        getline(filehandle, temp);
        SoftBlock block(temp);
        softblocklist.push_back(block);
    }
    filehandle.close();
}

vector<SoftBlock> SoftBlockList::get_softblocklist(){return
softblocklist;}

A: A simple way to do this would be to use a union. The union can only have 1 active member at a time, and only occupies a size equal to the biggest member.
#include <iostream>
using namespace std;

class Block {
    public:
    struct Type1 {
        int number_of_edges;
        float lowerleft, lowerright, upperleft, upperright;
    };
    struct Type2 {
        double area;
        float min_aspectRatio, max_aspectRatio;
    };

    union combinedData {
        Type1 t1;
        Type2 t2;
    };

    int BlockID;
    int BlockType;

    combinedData data;
};

int main() {
    Block block;
    block.BlockType = 1;
    block.data.t1.number_of_edges = 1; // Type1 is now active
    cout << block.data.t1.number_of_edges << endl;
    block.BlockType = 2;
    block.data.t2.area = 1.5678; // Switched to Type2 being the active member
    cout << block.data.t2.area << endl;
}

You can then use the value of BlockType to determine which member is active.


text:
Q: A confuse about Cyclic subspace I have asked such a question before:

problem:Let $V$ be a linear space,$\mathscr A $ is a linear translation on $V$.choose $0≠α∈V$.let $S=\{\mathscr A^k(α):k≥0\}$ and $U=span(S)$, prove that:
(i) $U$ is stable under $\mathscr A$.
(ii) assume $dim(U)=r$,then ${α,\mathscr A(α),\cdots,\mathscr A^{r-1}(α)}$ is a basis of $U$ and find out the metric of  $\mathscr A|_U$ under basis ${α,\mathscr A(α),\cdots,\mathscr A^{r-1}(α)}$

And I gave the answer myself:

lemma: if ${α_1,α_2,\cdots,α_n}$ is linear independent,${α_1,α_2,\cdots,α_n,β}$ is linear dependent,then $β$ can be linear expression by ${α_1,α_2,\cdots,α_n}$,but $α_i$ can't be linear expression by the other.

From the comment:we know${α,\mathscr A(α),\cdots,\mathscr A^{r-1}(α)}$ is linear dependent and ${α,\mathscr A(α),\cdots,\mathscr A^{r-1}(α),\mathscr A^r(α)}$ is linear dependent.
We write $\mathscr A^r(α)=x_0α+\cdots+x_{r-1}\mathscr A^{r-1}(α)$.
We have$(\mathscr A(α),\cdots,\mathscr A^r(α))⊆ (α,\cdots,\mathscr A^{r-1}(α))$. If ${\mathscr A(α),\cdots,\mathscr A^r(α)}$ is independent,then $α$ can be linear expression by ${\mathscr A(α),\cdots,\mathscr A^r(α)}$,by lemma,it is impossible, so ${\mathscr A(α),\cdots,\mathscr A^r(α)}$ is linear dependent,thus $\mathscr A^r(α)$ can be expression by ${\mathscr A(α),\cdots,\mathscr A^{r-1}(α)}$,so $x_0=0$.
we know${\mathscr A(α),\cdots,\mathscr A^{r-1}(α)}$ is linear dependent and ${\mathscr A(α),\cdots,\mathscr A^{r-1}(α),\mathscr A^r(α)}$ is linear dependent. Use similarly way with above,we can get $x_1=0$,this  process can continues. So $x_0=\cdots=x_{r-1}=0$.
So $\mathscr A^r(α)=0$.
Remark:$(\mathscr A(α),\cdots,\mathscr A^r(α))$ is subspace generated by${\mathscr A(α),\cdots,\mathscr A^r(α)}$.

we say set $S$ is linear independent if for any finite subset $\{α_1,\cdots,α_n\} $,if $x_1α_1+\cdots+x_nα_n=0$,then we have $x_1=\cdots=x_n=0$.if exist some finite subset $\{α_1,\cdots,α_n\} $ and Numbers that are not all zeros $x_1,\cdots,x_n$ such that $x_1α_1+\cdots+x_nα_n=0$,we say $S$ is linear dependent.

We say $α$ can be linear expression by $α_1,\cdots,α_n$ if extist $x_1,\cdots,x_n$ such that $α=x_1α_1+\cdots+x_nα_n $
Let $V$ linear space with dimension $n$
Definition: (i)let $α∈V$ the cylic subspace $C_α$ of is the smallest stable subpace  under $\mathscr A$(is: the intersection of stable subpace contain $α$)
(ii) Minimum polynomial $d_α(λ)$ of $α$ relative to to $\mathscr A$ is Polynomial with minimum degree and first term coefficient of 1 such that $d_α(\mathscr A)(α)=0$.
Here is some relatively theorem:
$C_α$ is generated by $\{α,\cdots,\mathscr A^{r}(α),\cdots \}$
My confuse comes from the following theorem :
theorem:assume $d_α(λ)=λ^r+a_{r-1}λ^{r-1}+\cdots+a_o$.then $dim C_α=r$ and
$\mathscr A^r(α)=-a_0α+\cdots-a_{r-1}\mathscr A^{r-1}(α)$.
but from my "proof" above:we have $a_0=\cdots=a_{r-1}=0$. It is seem to impossible,so Where did I go wrong?

A: Let $r'$ be the smallest number such that $\alpha, A(\alpha),\dots,A^{r'}(\alpha)$ is linearly dependent.
Then $\alpha,\dots,A^{r'-1}(\alpha)$ are independent, so we can apply the lemma to express
$$A^{r'}(\alpha)=\sum_{i<r'}a_iA^i(\alpha)\,.$$
It doesn't follow that $a_i$ must be $0$.
But, by induction we can clearly see that $A^k(\alpha)\in{\rm span}(\alpha,\dots,A^{r'-1}(\alpha))$ for every $k\in\Bbb N$, hence $U={\rm span}(\alpha,\dots,A^{r'-1}(\alpha))$, so $r=\dim U=r'$.
Also observe that
$$A^r(\alpha)-a_{r-1}A^{r-1}(\alpha)-\dots -a_1A(\alpha)-a_0\alpha=0\,,$$
and that this polynomial $d_\alpha$ is a factor of the minimal polynomial of $A$.


text:
Q: Check for Inactivity in a React Native App How do I check for inactivity globally in react native i.e touch events. I tried using https://www.npmjs.com/package/react-native-user-inactivity but it doesn't register touch events. I would prefer pure javascript solutions as apposed to linking native code. A solution for just iOS is fine.

A: You can use the PanResponder from react-native package.
Here you can see a working example, using expo toolkit.


text:
Q: What is the source of the quote: "The universe doesn't care?" I was reading an article in Time magazine about Interstellar and it opened with a quote that was never attributed:

There is no reason at all you should care about the universe. For one thing, it doesn't care a whit about you.

Since the article was on page 42 and titled Life, the Universe and Everything, I expected it to be a Douglas Adams quote, but couldn't find any reference.
Although it could just as easily be a physicist or cosmologist.
Does anyone know the source?

A: I found this article opening with the quote, but it has a different title than the one you mentioned.
In any case, based on a Google search it appears that Jeffrey Kluger (The author of that article) made it up. Pretty much every attempt to search for the phrase directs me to Kluger's article in one form or another, except for this article posted on Bernstein & Andriulli's website last week:

We are very, very small. In the context of even our Solar System, human beings are such a minute part of the total planetary existence that we're hardly worth mentioning. Put that into the context of the universe, and we wouldn't be a footnote. As TIME Magazine reporter Jeffrey Kluger puts it, "There is no reason at all you should care about the universe. For one thing, it doesn't care a whit about you."

Emphasis mine. Although it does kind of sound like it belongs in a Douglas Adams book, it seems to be an original creation.

A: The 'uncaring universe' quote may be derived from Niven's third law: "Mother Nature doesn't care if you're having fun."

A: Here's an older one...Pre 1900

"A Man Said to the Universe
A man said to the universe:
"Sir, I exist!"
"However," replied the universe,
"The fact has not created in me
A sense of obligation."
― Stephen Crane, War Is Kind and Other Poems

A: The earliest source I am aware of is Michael Moorcock's The Black Corridor, a portion of which was subsequently used by Hawkwind for a song of the same name.
The Moorcock book dates to 1969, the Hawkwind song to 1972.

Space does not care, space does not threaten
  Space does not comfort
  It does not speak, it does not wake
  It does not dream
  It does not know, it does not fear
  It does not love, it does not hate
  It does not encourage any of these qualities

Despite this, the concept of the universe not caring does seem to be quite a common trope, so it's unlikely that you're ever going to get a definite source for the article itself.


text:
Q: How can I pass a list as a parameter to a dialog? Y must pass a list of data to a dialog to fill a combobox.
In other part of the code I passed a string to dialogs, but, using the same method for this case, It didn´t work.
Here is my js code:
$scope.addPartido = function () {
    if ($scope.dataProv.locationsProv.provincias) {
        $modal.open({
            templateUrl: '../../secure/addPartido/addPartidoDialog.html',
            controller: function ($scope, $modalInstance) {
                $scope.close = function () {
                    $modalInstance.close();
                };
            }
        });
    }
};

Inside my controler I have the variable $scope.dataProv.locationsProv.provincias fill with de data.
And here is my html code:

            Provincia*

                <select ng-options="item.name for item in dataProv.locationsProv.provincias| orderBy:'name'"
                        ng-id="mySelProvincia" class="form-control" required="required"
                        ng-model="selectedProv">
                </select>

            <button type="button" class="btn btn-default" ng-click="close()">
                Cerrar
            </button>

A: It is easy!
This code works perfectly:
$scope.addPartido = function () {
    if ($scope.dataProv.locationsProv.provincias) {
        $modal.open({
            templateUrl: '../../secure/addPartido/addPartidoDialog.html',
            controller: function ($scope, $modalInstance, listProv) {
                $scope.statusProv = 'loading...';
                    $scope.provincia = "Select provincias";
                    $scope.dataProv = {
                        "locationsProv": {}
                    };

                    $scope.dataProv.locationsProv.provincias = listProv;
                $scope.close = function () {
                    $modalInstance.close();
                };
            },
            resolve: {
                    listProv: function () {
                        return $scope.dataProv.locationsProv.provincias;
                    }
                }
        });
    }
};


text:
Q: In Xamarin Forms, how can I show a web image in the same way as a image in the resource folder? I have a Xamarin forms image where I want to show images from the web, kind of like in a facebook style feed. Due to bandwidth concerns, I do not want to serve high resolution images from my web server.
Now if I add a Image with the Source attribute set to my image url, I cannot get the image to display larger than what it is in native resolution (at least on iOS where I am testing now). This means that to display the image at full width on the later iPhones I need to have a image wider than 1000px.
Is there any way I can make the web images behave more like the images loaded from the resource directory, that are scaled up on higher resolution devices?
Not sure how to explain this in a good way, this repo (not mine) addresses the same problem: https://github.com/williamwilling/xamarin-forms-image-size . Probably not a bug in Xamarin forms I would guess, more a behavior.
Note: I only need this to work on iOS and Android.

A: You really should consider using the library FFimageLoading.
Here is the example from their wiki. And the images behave similar when loading from a Source  / URL. It also allows caching, which is extremely useful.
<ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
        WidthRequest="300" HeightRequest="300"
        DownsampleToViewSize="true"
        Source = "http://loremflickr.com/600/600/nature?filename=simple.jpg">
</ffimageloading:CachedImage>


text:
Q: Doesn't this LED created by MIT violate the second law of thermodynamics? Here is the article I am referring to: http://www.wired.co.uk/news/archive/2012-03/09/230-percent-efficient-leds
In their own words (or at least the article writer's), "it appears to draw in heat energy from its surroundings ... it begins to cool down, stealing energy from its environment to convert into more photons."
Well, there we have it. In the simplest case, you could use this device to pump heat from cold to hot, by simply aiming the light from the LEDs onto a dark surface. This obviously shouldn't be possible.
What am I missing?


text:
Q: Spark se queda sin memoria leyendo desde JDBC (MySQL) Estoy ejecutando un job de Spark dentro de AWS Glue, usando multi threading y leyendo una tabla de MySql (particionada). Básicamente, tengo un thread por día de un mes específico, y cada día es una Task (numPartitions = 1). La configuración del clúster es G2, es decir, 5 workers (1 es el Driver) con 12,6 GB de MEM y 16 núcleos. Estoy usando el modo FAIR.
En este caso, estoy leyendo enero / 2021 desde la tabla. Entonces puedo ver en Spark History Server 31 subprocesos, cada uno de ellos con una tarea. El driver está distribuyendo 16 tareas (16 días) en un worker (executor) y las otras 15 tareas (15 días) en otro worker (executor). Si hago un dump de la tabla desde MySql, el archivo de salida es de aproximadamente 10 GB.
Entonces, si sabemos que cada día (es una tabla con transacciones y estoy leyendo las transacciones por día) tiene casi el mismo número de filas, puedo asumir que 15 días ~ 5 GB.
Mi pregunta aquí es:
¿Por qué Spark se queda sin memoria si está tratando de leer ~ 5GB en un worker con casi 13GB?
¡Gracias de antemano por la respuesta!


text: Q: Вкладное приложение aka Safari или MDI на Swift Недавно начал изучать Swift, до этого учил С# и вполне успешно. Так вот, в C# есть такая технология как MDI, когда мы можем запускать экземпляры окон в конкретном окне. На "шарике" это делается достаточно просто, а как это делается на Swift? Если говорить конкретно, то в целях обучения языка я хочу создать простую рисовалку, где каждый новый файл будет открываться в новой вкладке одного окна приложения.


text:
Q: Taylor Expansions in Spherical Coordinates (Generator of Rotations) We can expand a smooth function $f:\mathbb{R}^3\to \mathbb{R}$ in a Taylor series:
$$f((x^1,x^2,x^3)+(h^1,h^2,h^3))=f(x^1,x^2,x^3)+h_i\frac{\partial f}{\partial x^i}+h_ih_j\frac{\partial^2 f}{\partial x^i\,\partial x^j}+\cdots$$
Now suppose we write the same function in spherical coordinates: $\hat f\equiv f\circ g$, where $g:R_\theta^3\to \mathbb{R}^3$ is the spherical coordinate mapping. Why can't we then write
$$\hat f((\theta^1,\theta^2,\theta^3)+(\phi^1,\phi^2,\phi^3))=\hat f(\theta^1,\theta^2,\theta^3)+\phi_i\frac{\partial \hat f}{\partial \theta^i}+\phi_i\phi_j\frac{\partial^2 \hat f}{\partial \theta^i\,\partial \theta^j}+\cdots\tag{1}$$
What's going on here? Perhaps it's the periodicity, but then shouldn't the formula be valid if $(\phi^1,\phi^2,\phi^3)$ is sufficiently small?
What I'm really after is for a valid version of (1).


text:
Q: I don't know how to output files and create additional programs I wanted to make the following program, so I made it halfway, but I don't know how to make it from there. I will give you the result you want to execute and the result of the current execution. Where should I edit?
want to execute.
Please enter three values:
5.0 9.0 -6.5
Average: 2.500
Original data: +5.000 +9.000 -6.500
Data after average deduction: +2.500 +6.500 -9.000

now to execute.
Please enter three values:
5.0 9.0 -6.5
Average:2.500
Original data:5.000 9.000 -6.500
Data after average deduction:2.500 6.500 -9.000

source
#include <stdio.h>

double ave3 (double, double, double);
double subave3 (double *, double *, double *);

int main ()
{
   double a, b, c, ave;

   printf ("Please enter three values: \n");
   scanf ("%lf%lf%lf", &a, &b, &c);

   ave = ave3 (a, b, c); /* Function call */

   printf ("Average:%.3f \n", ave);
   printf ("Original data:%.3f %.3f %.3f \n", a, b, c);

   subave3 (&a, &b, &c);

   printf ("Data after average deduction:%.3f %.3f %.3f \n", a, b, c);

   return 0;
}

/* A function that calculates the average. It also subtracts the average value from the data. */
double subave3 (double *x, double *y, double *z)
{
    double ave = ave3(*x,*y,*z);
   *x-= ave; /* Subtract the average from each data */
   *y-= ave;
   *z-= ave;
}

double ave3 (double x, double y, double z) {
   double ave = (x +  y + z) / 3.0;
   return ave;
}

A: I think you can add + like this:
printf ("Original data:%+.3f %+.3f %+.3f \n", a, b, c);
...
printf ("Data after average deduction:%+.3f %+.3f %+.3f \n", a, b, c);

When you'd run this, you would get this output:
src : $ ./a.out
Please enter three values:
5.0 9.0 -6.5
Average:2.500
Original data:+5.000 +9.000 -6.500
Data after average deduction:+2.500 +6.500 -9.000


text:
Q: Selecting only rows with certain number from data table So... Probably my title is missleading but...
What my code currently does..
SELECT TOP 12
    *,
    r.user_name
FROM
    something p
INNER JOIN users r ON p.fk_user_id = r.user_id
ORDER BY
    something_id DESC

It pretty much only takes things from bottom and sorting it by id...
But what I need additionally is somehow add WHERE something_season = number and select only those things with fixed number, not everything.
Any suggestion? I guess that I can't even put WHERE in there.

A: You can put where as following:
SELECT TOP 12 *,r.user_name
FROM something p
INNER JOIN users r ON p.fk_user_id = r.user_id
WHERE something_season = number
ORDER BY something_id DESC


text:
Q: database diagram i want to see a diagram (erd) of a database system which has been designed for cms. would you lpease show me a complete on? tanks

A: How about n2cms

A: The best place to look for ER diagrams of typical database applications is Database Answers .org.  Click Here
I didn't see anything for CMS, but maybe it's there under a different name.


text:
Q: Loop, iterate with unexpected results, Propertie package javaapplication43;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import java.io.FileInputStream;

public class JavaApplication43 {

    int totalResults = 45; //
    int itemsperPage = 10;
    int i = 0;
    int j = 0;
    int count = 0;

    FileOutputStream output = null;
    Properties prop = new Properties();
    FileInputStream input=null;

    public JavaApplication43() throws FileNotFoundException, IOException {

        output = new FileOutputStream("config.properties");

        // set the properties value
        prop.setProperty("totalResults", "45");
        prop.setProperty("itemsperPage", "10");
        prop.setProperty("?", "?");

        // save properties to project root folder
        prop.store(output, null);

        input = new FileInputStream("config.properties");

        // load a properties file
        prop.load(input);

        // get the property value and print it out
        System.out.println(prop.getProperty("totalResults"));
        System.out.println(prop.getProperty("itemsperPage"));
        System.out.println(prop.getProperty("?"));

    }

    public void makeLoop() {
        for (i = 1; i <= (totalResults / itemsperPage) + 1; i++) {
            System.out.println("nextPage " + i);
            for (; j < i * itemsperPage; j++) {
                if (j > totalResults) {
                    break;
                }
                System.out.println("Filenumber " + (j + 1));
            }
        }
    }

    public static void main(String[] args) throws IOException {
        JavaApplication43 myTest = new JavaApplication43();
        myTest.makeLoop();
    }
}

*This Code gives the Result:

*

*nextPage1: Filnumber1, Filnumber2...Filenumber10

*nextPage2: Filenumber11, Filenumber12.., Filenumber20

*nextPage5: Filenumber41, Filenumber42.., Filenumber46

And so on. I expect the result so, if i start the next time with a sheduller it should start
with the nextpage2 and print the files from 11-20,
if i start again the programm it should start with the nextpage 3 and print the files from 21-30 and so on depends on the value wich i have for totalResults.
The Solution is may to save the value in the Property to make it Persistent, so that
if i  run the Programm again, it will read the Property config.properties to start on the right index, but i dont know how to iterate, through the loop. ?

A: import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import java.io.FileInputStream;

public class JavaApplication43_with_Main_3 {

    public static void main(String[] args) throws IOException {
        int totalResults = 45; //
        int itemsperPage = 10;
        int i = 0;
        int j = 0;
        FileOutputStream output = null;
        Properties prop = new Properties();
        FileInputStream input = null;
        input = new FileInputStream("config.properties");

        // load a properties file
        prop.load(input);

        // get the property value and print it out
        System.out.println("nextPage Prop " + prop.getProperty("nextPage"));

        String nextPage = prop.getProperty("nextPage");
        int intNextPage = Integer.parseInt(nextPage);
        System.out.println("intNextPage " + intNextPage);

        for (i = intNextPage; i <= (totalResults / itemsperPage) + 1; i++) {
            int jNextPage=intNextPage-1;
            System.out.println("nextPage here " + i);
            for (j=jNextPage*itemsperPage; j < i * itemsperPage; j++) {
               // System.out.println("j ist "+j);
                if (j > totalResults) {
                    break;
                }
                System.out.println("Filenumber " + (j + 1));
            }
            String strI = "" + (i + 1);
            System.out.println("hello " + strI);
            output = new FileOutputStream("config.properties");
            prop.setProperty("nextPage", strI);
            prop.store(output, null);
            break;
        }
    }
}

This is the does make loop and printing out

*

*nextPage 1, Filenumber1,Filenumber2,..,Filenumber10

then it saves the nextPage value into the Property File.
If you start again, it does printing out

*

*nextPage 2, Filenumber11,Filenumber12,...,Filenumber20

You should have e Propertiy File with the Name, config.properties
and but the key nextPage and the value 1, nextPage=1;--->config.properties


text:
Q: How to prove that $\frac{d}{dx}\sin(x)=\cos(x)$ I have to prove that $\dfrac{d}{dx}\sin(x)=\cos(x)$. I used the definition of a derivative:
$$\dfrac{d}{dx}f(x)=\lim\limits_{h\to 0} \dfrac{f(x+h)-f(x)}{h}$$
$$\dfrac{d}{dx}\sin(x)=\lim\limits_{h\to 0} \dfrac{\sin(x+h)-\sin(x)}{h}$$
Using angle sum formula:
$$\dfrac{d}{dx}\sin(x)=\lim\limits_{h\to 0} \dfrac{\sin (x)\cos (h)+\cos (x)\sin (h)-\sin (x)}{h}$$
Rearranging the terms:
$$\dfrac{d}{dx}\sin(x)=\lim\limits_{h\to 0} \dfrac{\cos (h)\sin(h)-\sin(x)+\sin(x)\cos(h)}{h}$$
Factoring out $\sin(x)$ from the last two terms:
$$\dfrac{d}{dx}\sin(x)=\lim\limits_{h\to 0} \dfrac{\cos(x)\sin(h)-\sin(x)[1-\cos(h)]}{h}$$
Separating the fraction:
$$\dfrac{d}{dx}\sin(x)=\lim\limits_{h\to 0} \dfrac{\cos(x)\sin(h)}{h}-\lim\limits_{h\to 0} \dfrac{\sin(x)[1-\cos(h)]}{h}$$
Now I am stuck. Can anyone please tell me what to do next, or give me a hint? Thanks

A: Now it depends on what you know.  Do you have $\lim_{h \to 0} \frac {\sin h}h=1$?  And $\lim_{h \to 0} \frac {1-\cos h}h=0$?  Then insert them and you are done.  These usually come before what you are doing.  The Taylor series are another route, but usually come later.

A: See this answer for a geometric proof that
$$
\lim_{x\to0}\frac{\sin(x)}{x}=1
$$
You might also find the following useful:
$$
\frac{1-\cos(x)}{x}=\frac{\sin(x)}{x}\frac{\sin(x)}{1+\cos(x)}
$$


text:
Q: Is it possible to stop the color of the 'remaining disk-space bar' from changing to red when there isn't a lot of space remaining in Win7?
Possible Duplicate:
How to change the disk space left warning in Windows 7?

For example, if on drive C:, which has total space of 465 GB, I have something like 50 GB of space remaining, the color of the bar below the drive icon in My Computer changes from blue to red.
I'd like to stop this from happening; I end up deleting stuff just to free some space -- even though I feel I'm not running out, as 50 GB is adequate -- so the color would change back to blue, but often later regret deleting what I then considered as unnecessary junk.


text:
Q: How can I share a variable within a Meteor template? Suppose I have a click event that calls a server method to query and return a product code stored in a variable a. I then want to use the variable a in another click event. Is there a way I can do this? If I just use a in the other click event, I get an undefined message.

A: Session works pretty effectively.
Meteor.call("someServerMethod", anArgument, function(err, res){
  if !(err) {
    Session.set("variableName", res);
  }
});

Then you can use:
Session.get("variableName");


text:
Q: Pass-through of Marvell 88SE9230 to Xen guest with AMD-V iommu I have a Gigabyte GA-970A-DS3P board with a AMD FX(tm)-8350 cpu. I have IOMMU enabled in the BIOS.
For the non-XEN linux boot I pass iommu=pt amd_iommu_dump as a kernel argument and can verify that AMD-V is loaded via dmsg | grep AMD-V.
When running a QEMU/KVM guest I can passthrough the Marvell 88SE9230 card to the guest and everything works fine.
I want to get this pass-through working with a XEN setup as well.
However from the 4 SATA 0-3 ports that the 88SE9230 card supplies only the last port is actually discovering a disk (i.e. if port 0 and 1 are connected, then disk on port 1 is discovered, while port 0 remains empty).
I now run Xen 4.9 via apt-get install xen-hypervisor-4.9-amd64 in an Ubuntu-18.04 dom0. Kernel is 4.15.0-29-generic. I rebind my device (in my case 0000:01:00.0) via pciback.sh as described here and rebind via pciback.sh "0000:01:00.0". Then I can attach 0000:01:00.0 to the Xen guest.
Inside the guest 0000:01:00.0 appears and lspci and pciconf (in my case the XEN guest is FreBSD FreeNAS) works correctly. However only the disk on the last connected port is detected. All other ports seems to be empty even if I have a disk connected. In the KVM version these disks are recognized.
I was wondering where the AMD iommu handling is implemented in the Xen case. The Ubuntu 18.04 dom0 doesnt have any iommu entries in sysfs and the AMD-V debug messages are not printed. So I guess there is a baremetal XEN hypervisor that implements the iommu initialization. Is there some option I need to add to enable AMD iommu handling in the hypervisor (equivalent to the linux iommu=pt option) and how is this done?

A: The standard Xen emulated IDE will appear as ada0 while the passthrough SATA device will also appear as ada0. This results in one disk shadowing the other. In /dev/ only one ada0 entry will be seen.


text:
Q: Injecting IOptions<> into ApiKeyAuthorizeAttribute I am using options pattern that stores different configurations, including API keys for different environments. So far I have been using it fine and injecting my values into classes as needed.
However, I faced a little challenge while trying to setup authorization in the controller and run validation against my ApiKey that is unique per environment, because I was not able to inject IOptions into ApiKeyAuthorizeAttribute class to perform validation.
Here is how my controller looks like now:
[ApiKeyAuthorize]
public class NotificationSettingsController : Controller
{
    //some endpoints here
}

ApiKeyAuthorize Class:
public class ApiKeyAuthorizeAttribute : Attribute, IAuthorizationFilter
{
    //////This...
    private readonly IOptions<MyConfig> _config;

    public ApiKeyAuthorizeAttribute(IOptions<MyConfig> config)
    {
        _config = config;
    }
    /////////...is what I am trying to accomplish
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var request = context.HttpContext.Request;

        var foundApiKeys = request.Headers.TryGetValue("ReplaceWithOptionsApiKeyName", out var requestApiKeys);

        if (!foundApiKeys || requestApiKeys[0] != "ReplaceWithOptionsApiKeyValue")
        {
            context.Result = new UnauthorizedResult();
        }
    }
}

My problem is that injecting here isn't possible, but I need to get a value from IOptions<> to run ApiKey validation.

A: Attributes are constructed in-place, so it's not possible to inject dependencies into them. However, ASP.NET Core provides a workaround. Instead of applying the attribute directly, you can use the ServiceFilter attribute instead and pass it the type of the filter you want to apply:
[ServiceFilter(typeof(ApiAuthorizeAttribute))]

This will dynamically apply the filter to the controller/action while instantiating it with any dependencies it requires at the same time. However, it does limit you in the other direction. For example, if you need to do something like:
[ApiAuthorizeAttribute(Roles = "Admin")]

It would not be possible to achieve this with the ServiceFilter attribute, because you cannot pass property values, like Roles here, along with the type.


text:
Q: Send json array and passing json array in spring mvc controller I'm trying pass Json data such bellow
for (var t = 0; t < files.length; t ++ ){
    contents.push({"name":files[t].name,"selected":true,"url":files[t].url});
}

Controller
@RequestMapping(value = "/ajax/candidate/onboarding/multidownload",method = RequestMethod.POST,consumes = "application/json")
public @ResponseBody RequestTTT downloadCandidateDoc(HttpServletResponse res,@RequestBody List<DownloadItem> files) {
    requestttt.setFiles(files);
    return requestttt;
}

Class RequestTTT
class RequestTTT {
    Long candidateId;
    List<DownloadItem> files;
}

Class DownloadItem
public class DownloadItem {
    private String name;
    private boolean selected;
}

Result i have is :

400 Bad request with function

$.ajax({
  type : "POST",
  url : "${contextPath}/ajax/candidate/onboarding/multidownload",
  data : JSON.stringify(data),
  dataType: 'json',
  headers : {
    'Accept' : 'application/json',
    'Content-Type' : 'application/json'
  },
  cache: false,
  timeout: 100000,
  success: function (data) {
    console.log("SUCCESS : ", data);
  },
  error: function (e) {
    console.log("ERROR : ", e);
  }
})

A: Sorry for late response.
Request List item Class:
public class DownloadItem {

    private String name;
    private String selected;
    private String url;

    /*{
        "name": "logo.png",
            "selected": true,
            "url": "192.168.84.30/static/candidate/india/1/120170623163651logo.png"
    }*/

    // Getter
    // Setter
}

Response Class:
import java.util.List;

public class Response {
    private Long candidateId;
    private List<DownloadItem> files;

    // Getter
    // Setter
}

Your controller code will be bellow:
@PostMapping("ajax/candidate/onboarding/multidownload")
public ResponseEntity<Response> downloadCandidateDoc(@RequestBody List<DownloadItem> request) {

    Response response=new Response();
    response.setCandidateId(11L);
    response.setFiles(request);

    return new ResponseEntity<>(response, HttpStatus.OK);

}

Here is imports:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

Edit:
I checked this in postman. Here is the sample input output.
http://IP:PORT/YOUR_CONTEXT_PATH/ajax/candidate/onboarding/multidownload
Request Json
[
  {
    "name": "logo.png",
    "selected": true,
    "url": "192.168.84.30/static/candidate/india/1/120170623163651logo.png"
  },
  {
    "name": "Chrysanthemum.jpg",
    "selected": true,
    "url": "192.168.84.30/static/candidate/india/1/…"
  }
]

Response:
{
    "candidateId": 11,
    "files": [
        {
            "name": "logo.png",
            "selected": "true",
            "url": "192.168.84.30/static/candidate/india/1/120170623163651logo.png"
        },
        {
            "name": "Chrysanthemum.jpg",
            "selected": "true",
            "url": "192.168.84.30/static/candidate/india/1/…"
        }
    ]
}


text:
Q: How to include document history in a document? When updating a document in alfresco's repository, it gets versioned on each check in, am looking for a way to dynamically include a version history table into one of my document's pages.
Exactly like the 'Version history' shown in the document details inside Share, is there any way to let alfresco automatically update my document to insert that part ? or in a simpler way, is there anyway to automatically put the version history table inside my deliverable documents ?

A: Oke for this to work you'll need JAVA knowledge to inject content in a document.
BTW this is a very old implementation so there could be nicer/faster ways to do this.
What we did was the following:
All the code is already in the Openoffice libraries within Alfresco. e.g. take a look at this library; openoffice-unoil-3.1.0.jar
Created a custom Action which takes as input a node.

*

*Use XComponentLoader to get the current connection

*Use XComponent to get the file (we copied the content to a JAVA
tempFile)

*Use XBookmarksSupplier to get the current bookmarks in Word (so in
this case, set a bookmark for the version history table)

*When looping through the bookmarks, get the Anchor. Within this object you can setString and then set your table string. I'm not sure how to set a table in this String. But it won't be fun if everything is known ;). Here is a bit Java code.

*In the end use XStorable to store the file by using it's url

Good luck!


text:
Q: Selecting foreign keys in Django REST Framework's Browsable API I have a simple ForeignKey relationship between two models:
class Ticket(models.Model):
    description = models.CharField(max_length=1000)
    created_by = models.ForeignKey(User, related_name="created_ticket")

class User(models.Model):
    username = models.CharField(max_length=64, unique=True, primary_key=True)
    email = models.CharField(max_length=255)

I have a serialiser for each, with the user serialized within the ticket as a nested serialiser. What I would ideally like is

*

*in an update view of Tickets on the Browsable API, being able to choose from a dropdown list of extant users, and

*when entering a username and an e-mail, the application should check if users exist with those parameters, and if so, assign them to the ticket, and if not, raise a validation error (the validation part I got working, the rest... not so much).

So far, I've tried to follow overriding the update/create methods, but when I enter a code, the application always tries to create a new object, then complains that an object with the same username (the pkey) already exists. I have tried getting some sense out of the documentation on the subject, but with not much luck.
EDIT: My update method is
def update(self, instance, validated_data):
    usr_data = validated_data.pop('created_by')
    instance.created_by_id = usr_data.id
    return instance


text:
Q: jquery footable $('#classes').trigger('footable_redraw'); return hidden table this is my first Question, may be hard to understand.
calling $('#classes').trigger('footable_redraw'); , it return the data but hide the table heading and data rows,but when i used $('#classes').trigger('footable_initialize'); its work fine but reduplicate the data .
Ajax method is called on submitting form.
  $.ajax({
url : baseurl+'index.php/settings/classes/viewclasses',
success : function(data) {
$('.classestbody').append(data);
$('#classes').trigger('footable_redraw'); }
});

How can i only get my updated data in table after saving any Values by calling submitting for saving ?

A: Basically you need to check to see if the data is in the table already.  If the data is not in the table, add it; if it is in the table, don't.  You'll need some way to positively identify a row that matches the data.  If data is an array, you'll need to loop through the array and check each row.
Another option would be to use a data binding framework.  This would allow you to bind the data to the table, then you just add/update/delete rows from the data and the framework takes care of updating the table (view) for you.
I personally use Knockout.js.  They have a really good tutorial: http://learn.knockoutjs.com/.  Even if you don't end up using Knockout.js, I think the tutorial is pretty cool and it will only take you a couple of hours to go through all of them.

A: If your script on index.php/settings/classes/viewclasses always returns the hole table, and since you said the data gets duplicated this seems to be the case.
Then it is easier to delete all rows then add them all again, just add $('.classestbody').empty(); before $('.classestbody').append(data);. Your code would look like this:
$.ajax({
    url : baseurl+'index.php/settings/classes/viewclasses',
    success : function(data) {
        $('.classestbody').empty();
        $('.classestbody').append(data);
        $('#classes').trigger('footable_redraw');
        }
});


text:
Q: Application Request Routing on local machine I installed ARR on my local machine and setup a server farm with a single server in it (localhost). I added two redirect routing rules.  However, it doesn't do the redirect.  My Default Web Site has ab additional binding like this one: localhost.mycompany.com.  I tried putting that in the server farm and it still didn't work.  The redirect rules look like this.
Uses wildcards in the pattern
inbound pattern:  */path2/*/*/*/method*
Redirect URL: /path1/path2/api/item/method

EDIT: When I use the Test Pattern and enter one of the URLs against my rule it parses it successfully
Also tried putting the full hostname (e.g. http://localhost.mycompany.com/...) in the redirect rule as well as using the alias localServerFarm (which is the name of server farm).  Nothing worked.
The module is "working" in some respect because when I had a broken rule it sure told me about it when I tried to load any url on localhost.  Once I fixed the rule, I no longer got the error message but it doesn't do any redirection.

A: This was just a matter of getting the redirect rule correct.  In the rules list there is a column named Input and it's setting is URL Path.  So, the only input to the pattern match is the path part of the URL not including the / at the beginning.  All I had to do was change the */ at the beginning of my pattern to just *, e.g. */path2/*/*/*/method* changed to *path2/*/*/*/method*.
I don't know if there's any other setting for the Input field (it isn't settable in the rule definition screen) but for anyone creating rules remember that only the path without a leading / is what's used for evaluating the pattern match.   One note is that if you're matching from the beginning of the path, as I am, you don't need the * at the beginning of the pattern.  However, if you go into the test pattern screen and paste a full URL into the Input data it will not just grab the path part of that URL and feed it to the pattern match will use the entire string so it will require an * at the beginning of your pattern to work.


text:
Q: Como puedo ocultar el subitem de un item de un menuStrip en vb? Como puedo ocultar un subitem de un item de un menu (menuStrip) en vb
intente con este pero me dice que esta fuera de intervalo
MenuStrip1.Items.Item(1).Enabled = False

Intente con este codigo y me oculta es el menu completo
MenuStrip1.Items(0).Visible = False

A: Tu IDE te muestra el nombre de tu ítem en el área de propiedades

en este caso mi item se llama
ToolStripMenuItem6

ahora solo accede a su propiedad visible:
ToolStripMenuItem6.Visible = False

A:
Los Menus y submenus tienen su propiedad Name y puedes acceder a ellos directamente. Pongamos que tienes un Menu llamado Menu1 y debajo un submenu llamado Submenu1. Para ocultar el submenú simplemente tienes que hacer:
Submenu1ToolStripMenuItem.Visible=false

Normalmente por defecto el nombre es el texto del menu + ToolStripMenuItem, pero puedes modificarlo a lo que quieras.
Edit
Te doy un par de opciones mas por si lo que quieres es ocultar un submenu con respecto al menu padre:
'Oculta el primer submenu con respecto al menu llamado Menu1ToolStripMenuItem
CType(Me.MenuStrip1.Items("Menu1ToolStripMenuItem"), ToolStripMenuItem).DropDownItems.Cast(Of ToolStripMenuItem).ElementAt(0).Visible = False

'Oculta el submenu llamado Submenu1ToolStripMenuItem del Menu1ToolStripMenuItem
CType(Me.MenuStrip1.Items("Menu1ToolStripMenuItem"), ToolStripMenuItem).DropDownItems.Cast(Of ToolStripMenuItem).Where(Function(s) s.Name = "Submenu1ToolStripMenuItem").FirstOrDefault().Visible = False


text:
Q: How to input into DataTable quickly? Or save data permanently into DataTable? I am inputting a text file into a DataTable and then using SqlBulkCopy to copy to a Database. While BulkCopy is fast, inserting 50000+ lines into DataTable is not (around 5 mins). How do I make it efficient?
Can I insert data into the DataTable quickly?
If not, is there a way to save the inserted data permanently into the DataTable so I don't have to insert it every time I run the program?
    for (; i < fares.Length; )
            {
                k = i;
                Console.WriteLine("Inserting " + k + " out of " + (fares.Length));
                for (; i <= (k + 3); i++)
                {
                    if (i % 4 == 0)
                    {
                        for (int j = 0; j < fares.Length - 1; j++)
                        {
                            {
                                int space = fares[i].IndexOf(" ");
                                startStation = fares[i].Substring(0, space);

                                endStation = fares[i].Substring(space + 1, fares[i].Length - space - 1);

                            }
                        }
                    }

                    else if (i % 4 == 1)
                    {
                        valueFare = fares[i];
                    }
                    else if (i % 4 == 2)
                    {
                        standardFare = fares[i];

                    }
                    else if (i % 4 == 3)
                    {
                        time = int.Parse(fares[i]);
                    }

                }

                faresDT.Rows.Add(startStation, endStation, valueFare, standardFare, time);

A: If what you want is to optimize your load to the database, I suggest that you get rid of the DataTable completely. By making use of Marc Gravell's FastMember (and anyone who's using SqlBulkCopy should be using FastMember IMHO) you can get a DataReader directly from any IEnumerable.
I would use some variation of the below code whenever writing from a file directly to a database. The below code will stream the contents of the file directly to the SqlBulkCopy operation thru the clever use of yield returns and lazy load of IEnumerable.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using FastMember;

namespace BulkCopyTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            const string filePath = "SOME FILE THAT YOU WANT TO LOAD TO A DB";

            WriteData(GetData<dynamic>(filePath));
        }

        private static void WriteData<T>(IEnumerable<T> data)
        {
            using (var bcp = new SqlBulkCopy(GetConnection(), SqlBulkCopyOptions.TableLock, null))
            using (var reader = ObjectReader.Create(data))
            {
                SetColumnMappings<T>(bcp.ColumnMappings);
                bcp.BulkCopyTimeout = 300;
                bcp.BatchSize = 150000;
                bcp.DestinationTableName = ""; //TODO: Set correct TableName
                bcp.WriteToServer(reader);
            }
        }

        private static void SetColumnMappings<T>(SqlBulkCopyColumnMappingCollection mappings)
        {
            //Setup your column mappings
        }

        private static IEnumerable<T> GetData<T>(string filePath)
        {
            using (var fileStream = File.OpenRead(filePath))
            using (var reader = new StreamReader(fileStream, Encoding.UTF8))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    //TODO: Add actual parsing logic and whatever else is needed to create an instance of T
                    yield return Activator.CreateInstance<T>();
                }
            }
        }

        private static SqlConnection GetConnection()
        {
            return new SqlConnection(new SqlConnectionStringBuilder
            {
                //TODO: Set Connection information here
            }.ConnectionString);
        }
    }
}

A: In this case I think you should take advantage of the BeginLoadData, LoadDataRow and EndLoadData methods provided in the DataTable class, you could use them like this:
try
{
    faresDT.BeginLoadData();

    // Your for loop...
    {
        // Logic defining the value of startStation, endStation, valueFare, standardFare and time removed for briefness.
        faresDT.LoadDataRow(new object[] {startStation, endStation, valueFare, standardFare, time}, true);
    }
}
finally
{
    faresDT.EndLoadData();
}

What BeginLoadData() does is turning off some processing that happens every time you add a row, and only does it once when you are done loading data by calling EndLoadData().
You can find more details about these APIs here:
https://learn.microsoft.com/en-us/dotnet/api/system.data.datatable.loaddatarow?view=netframework-4.7.2


text:
Q: Angular 2 end to end tests with Protractor ci I've made a project using the angular2-seed. I wanted to write some e2e tests for it. Successfully got them running locally, however with e2e testing in Travis-C there is an issue that it cannot find the elements the test uses.
For example I have a sidebar-menu component:
import {Component} from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
    selector: 'sidebar-menu',
    directives: [ ROUTER_DIRECTIVES ],
    templateUrl: 'app/shared/sidebar-menu/sidebar-menu.html'
})

export class SidebarMenuComponent {}

Using the sidebar-menu html:

Algemeen

 Home

And the e2e test that I wrote:
describe('Sidebar', () => {
  beforeEach( () => {
      browser.get('/');
  });

  it('Side menu should have the right title', () => {
      expect(element(by.css('#sidebar-menu h3')).getText()).toEqual('ALGEMEEN');
  });
});

When I run this locally using npm run e2e.ci it works and the test passes. However on travis-ci the test does not pass and it simply says "expected '' to equal 'ALGEMEEN'". Don't know what I'm doing wrong.
I'm using Angular 2 RC1 and travis uses NodeJS 5/6.
Travis-ci output:
1) Sidebar Side menu should have the right title
  Message:
    Expected '' to equal 'ALGEMEEN'.
  Stack:
    Error: Failed expectation
        at Object.<anonymous> (app/shared/sidebar-menu/sidebar-menu.component.e2e-spec.ts:11:60)
        at /home/travis/build/node_modules/jasminewd2/index.js:96:23
        at new Promise (/home/travis/build/node_modules/selenium-webdriver/lib/promise.js:1043:7)
        at controlFlowExecute (/home/travis/build/node_modules/jasminewd2/index.js:82:18)
        at TaskQueue.execute_ (/home/travis/build/node_modules/selenium-webdriver/lib/promise.js:2790:14)
        at TaskQueue.executeNext_ (/home/travis/build/node_modules/selenium-webdriver/lib/promise.js:2773:21)
        at /home/travis/build/node_modules/selenium-webdriver/lib/promise.js:2697:25
        at /home/travis/build/node_modules/selenium-webdriver/lib/promise.js:639:7
        at process._tickCallback (internal/process/next_tick.js:103:7)

Travis.yml:
language: node_js
node_js:
  - 5
  - 6

sudo: false

before_install:
  - export CHROME_BIN=chromium-browser  # Karma CI
  - export DISPLAY=:99.0

before_script:
  - sh -e /etc/init.d/xvfb start
  - nohup bash -c webdriver-manager start 2>&1 &  # Protractor CI
  - sleep 1  # give server time to start

after_failure:
  - cat /home/travis/build/mgechev/angular2-seed/npm-debug.log

cache:
  directories: node_modules

script:
  - npm run tests.all

Protractor.conf.js:
const config = {
  baseUrl: 'http://localhost:5555/',
  restartBrowserBetweenTests: false,

  specs: [
    './dist/dev/**/*.e2e-spec.js'
  ],

  exclude: [],

  // 'jasmine' by default will use the latest jasmine framework
  framework: 'jasmine2',

  // allScriptsTimeout: 110000,

  jasmineNodeOpts: {
    // showTiming: true,
    showColors: true,
    isVerbose: false,
    includeStackTrace: false,
    // defaultTimeoutInterval: 400000
  },

  directConnect: true,

  capabilities: {
    browserName: 'chrome'
  },

  onPrepare: function() {
    const SpecReporter = require('jasmine-spec-reporter');
    // add jasmine spec reporter
    jasmine.getEnv().addReporter(new SpecReporter({ displayStacktrace: true }));

    browser.ignoreSynchronization = false;
  },

  /**
   * Angular 2 configuration
   *
   * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching
   * `rootEl`
   */
  useAllAngular2AppRoots: true
};

if (process.env.TRAVIS) {
  config.capabilities = {
    browserName: 'firefox'
  };
}

exports.config = config;


text:
Q: Adding UIWindow breaks autolayout from background I'm trying to add UIAlertController in a new window on top of all other views. Works fine except it's trying to break autolayout each time window appears.
    let topWindow = UIApplication.sharedApplication().keyWindow!

    let alertWin = UIWindow(frame: UIScreen.mainScreen().bounds)
    alertWin.rootViewController = UIViewController()
    alertWin.tintColor = UIApplication.sharedApplication().keyWindow!.tintColor
    alertWin.windowLevel = topWindow.windowLevel + 1
    alertWin.makeKeyAndVisible()

    let alert = UIAlertController(title: "TITLE", message: text, preferredStyle: .Alert)
    let OKAction = UIAlertAction(title: "OK", style: .Default) { _ in
       alertWin.rootViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
       alertWin.hidden = true
       alertWin.rootViewController = nil
       alertWin.removeFromSuperview()
    }
    alert.addAction(OKAction)
    alertWin.rootViewController?.presentViewController(alert, animated: true, completion: nil)

I have already tried to put both this snippet and action closure content into main thread, but no luck
This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.  This will cause an exception in a future release.
 Stack:(
    0   CoreFoundation                      0x000000010ed36d85 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010e0aedeb objc_exception_throw + 48
    2   CoreFoundation                      0x000000010ed36cbd +[NSException raise:format:] + 205
    3   Foundation                          0x000000010de22b6b _AssertAutolayoutOnMainThreadOnly + 79
    4   Foundation                          0x000000010dc82357 -[NSISEngine withBehaviors:performModifications:] + 31
    5   UIKit                               0x0000000111292adb -[UIView(AdditionalLayoutSupport) _withAutomaticEngineOptimizationDisabledIfEngineExists:] + 58
    6   UIKit                               0x000000011129361e -[UIView(AdditionalLayoutSupport) updateConstraintsIfNeeded] + 254
    7   UIKit                               0x0000000111283c47 -[UIWindow(UIConstraintBasedLayout) updateConstraintsIfNeeded] + 108
    8   UIKit                               0x0000000111294333 -[UIView(AdditionalLayoutSupport) _updateConstraintsAtEngineLevelIfNeeded] + 272
    9   UIKit                               0x0000000110a48a96 -[UIView(Hierarchy) _updateConstraintsAsNecessaryAndApplyLayoutFromEngine] + 159
    10  UIKit                               0x0000000110a256f6 -[UIWindow layoutSubviews] + 43
    11  UIKit                               0x0000000110a58980 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 703
    12  QuartzCore                          0x0000000110585c00 -[CALayer layoutSublayers] + 146
    13  QuartzCore                          0x000000011057a08e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
    14  QuartzCore                          0x0000000110579f0c _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    15  QuartzCore                          0x000000011056e3c9 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277
    16  QuartzCore                          0x000000011059c086 _ZN2CA11Transaction6commitEv + 486
    17  QuartzCore                          0x000000011059c378 _ZN2CA11Transaction14release_threadEPv + 224
    18  libsystem_pthread.dylib             0x00000001139c8387 _pthread_tsd_cleanup + 470
    19  libsystem_pthread.dylib             0x00000001139c7f63 _pthread_exit + 117
    20  libsystem_pthread.dylib             0x00000001139c6582 pthread_attr_getschedpolicy + 0
    21  libsystem_pthread.dylib             0x00000001139c4341 start_wqthread + 13
)


text:
Q: How to do imports in python? I did some websearch, but all I found was frustration.
I have a project in a directory (lets call it) "projectdir", in which I have "main.py".
In projectdir I have a subdirectory called "otherstuff", In which I have "foo.py".
How do I import foo.py, so I can use its contents in main.py, without doing much of the work that python designers/implementors should have, and without relying on boilerplate files?
Or is that impossible in python?

A: you need to include __init__.py in your otherstuff directory.  This is to tell python to search there for imports.
The python documentation explains how the module/package import works.  And is def worth the time reading it, despite its kind of long length

A: You need to put a __init__.py file in otherstuff subdirectory, to mark it as a package. After, you can import your module using:
import subdirectory.foo

or
from subdirectory import foo

The __init__.py file can be empty. There is no other "clean" way to achieve that in python.


text:
Q: un-loading https I'm using this code in functions.php to load https on my events-manager pages:
function my_em_force_ssl( $template ) {
    if ( ! is_ssl() && em_is_event_page() ) {
        wp_redirect( str_replace( 'http:', 'https:', get_permalink() ) );
        die();
    }

    return $template;
}

add_filter( 'template_redirect', 'my_em_force_ssl', 10 );

Is there a way to unload or revert back to http when leaving those pages?

A: Not tested, but give it a shot:
function my_em_force_ssl() {
    if ( ! is_ssl() && em_is_event_page() ) {
        wp_redirect( str_replace( 'http:', 'https:', get_permalink() ) );
        exit;
    } elseif ( is_ssl() && ! em_is_event_page() && $_SERVER['REQUEST_METHOD'] === 'GET' ) {
        wp_redirect(
            str_replace( 'https:', 'http:',
                add_query_arg(
                    $_GET, site_url( $GLOBALS['wp']->request )
                )
            )
        );
        exit;
    }
}

add_action( 'template_redirect', 'my_em_force_ssl', 10 );

And a heads up, template_redirect is an action, so no need to accept & pass back params :)


text:
Q: Accessing run-time generated HTML with AHK script How do you access HTML generated at run-time on AHK?
I'm trying to access the content of the drop down box after the postcode is pasted into the search box (at this website - http://www.postcodeanywhere.co.uk/demos/address-finder/)

For 2 entries, the web page code is as follows:

        MK10 0AA, A C R Logistics, Standing Way, Brinklow, Milton Keynes

    MK10 0AA, Waitrose, A C R Logistics, Standing Way, Brinklow, Milton
    Keynes

For 2+ entries, the web page code is as follows:

        MK13 7NA, 1, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 2, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 3, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 4, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 5, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 6, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 7, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 8, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 9, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 10, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 11, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 12, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 13, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 14, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 15, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 16, Bleasdale, Heelands, Milton Keynes

        MK13 7NA, 17, Bleasdale, Heelands, Milton Keynes

This is my code so far - it only returns a list of countries when run and not the actual addresses, I suspect that it is pointing to another pcaitem class in the document...
;// Fileread, test, somefilename
fileread, AddressList, mk-data-000001-1.csv

IE := ComObjCreate("InternetExplorer.Application")
IE.Navigate("http://www.postcodeanywhere.co.uk/demos/address-finder/")
ComObjError(false)
IE.Visible := true

loop 14
{
Send {Tab down}{Tab up}
Sleep 200
}

loop, parse, AddressList, `n, `r
{
    Clipboard = %A_LoopField%
    Send, ^v

Name_Elements := IE.document.getElementsByClassName("pcaitem")
loop, % Name_Elements.length
{
Addr_text := Name_Elements[A_Index-1].innertext
}
}

Sample content of mk-data-000001-1.csv
MK1 1AS
MK1 1AX
MK1 1BA
MK1 1BB
MK1 1BE
MK1 1BG
MK1 1BH
MK1 1BJ
MK1 1BL
MK1 1BN
MK1 1BP
MK1 1BQ
MK1 1BU
MK1 1BW
MK1 1BX

A: I believe your assumption was right.
I don't think it hurts to be a little bit more precise?
I used the following:
IE.document.getElementsByClassName("pcalist")[0].getElementsByClassName("pcaitem")

Here's a test example
SetTitleMatchMode,2

IE := ComObjCreate("InternetExplorer.Application")
IE.Navigate("http://www.postcodeanywhere.co.uk/demos/address-finder/")
ComObjError(false)
IE.Visible := true
MsgBox Press OK when the page has been fully loaded.
Sleep 200
WinMaximize, Internet Explorer
Sleep 1000

;click the search input field
send {PGDN}
Sleep 200
x:=A_ScreenWidth//2
Click, %x% 250
Sleep 200

;search text
Send, MK1 1AS
Sleep 200

Data:=""
ResultsList := IE.document.getElementsByClassName("pcalist")[0].getElementsByClassName("pcaitem")
Loop % ResultsList.Length
    Data .= ResultsList[A_Index-1].innerHTML
StringReplace,Data,Data,,`n,All
Data:=RegExReplace(Data,"<span[^<>]+>",", ")
MsgBox % Data

Screenshot


text:
Q: Pandas - reindex so I can keep values Long story short
I have a nested dictionary. When I turn it into a dataframe.
import pandas
pdf = pandas.DataFrame(nested_dict)

 95     96     97     98     99    100   101   102   103    104    105  \
A  70019    102   4243   3083   3540  6311  4851  5938  4140   4659   3100
C      0    185    427    433   1190   910  3898  3869  2861   2149   3065
D      8      9  23463   1237   2574  4174  3640  4747  3557   4582   5934
E    141     89   5034   1576   2303  3416  2377  1252  1204   1703    718
F      7     12   1937   2246   1687  1154  1317  3473  1881   2221   3060
G    343   1550  13497  10659  12343  8213  9251  7341  6354   9058   9022
H      1   1978   1829   1394   1945  1003  1382  1489  4182    932    556
I      5    772   1361   3914   3255  3242  2808  3765  3284   2127   3120
K      3  10353    540   2364   1196   882  3439  2107   803    743    621
L      6     14   1599  11759   4571  4821  3450  5071  4364   1891   3677
M      1      6    158    211    524  2738   686   443   612    509   1721
N      6    186    299   2971    791  1440  2028  1163  1689   4296   1535
P     54     31    726   6208   7160  5494  6184  4282  3587   3727   3821
Q     10     87   1228   2233   1016  1801  1768  1693  3414    515    563
R      7  53939   3030   8904   6712  6134  5127  3223  4764   3768   6429
S     76   5213   3676   7480   9831  7666  5410  8185  7508  11237   8298
T   4369   1253   3087   2487   6559  4572  6863  3184  7352   6068   4756
V    732      5   7595   4331   5216  5444  5187  6013  4245   4545   4761
W      0      6    103   1225    598   888   601   713  1298   1323    908
Y     12      9   1968   1085   2787  5489  5529  7840  8691   9745  10136

Eventually I want to melt down this data frame to look like the following.
residue residue_num count
A       95          70019
A       96          102
A       97          4243
....

The residue column is being marked as the index so I don't know how to make it an arbitrary index like 0,1,2,3 and call "A C D E F.." another name.
EDIT
Answered myself as per suggestion

A: Answered from here and here
import pandas
pdf = pandas.DataFrame(the_matrix)
pdf = pdf.reset_index()
pdf.rename(columns={'index':'aa'},inplace=True)
pandas.melt(pdf,id_vars='aa',var_name="position",value_name="counts")

     aa position counts
0    A   95  70019
1    C   95  0
2    D   95  8
3    E   95  141
4    F   95  7
5    G   95  343
6    H   95  1
7    I   95  5
8    K   95  3

A: Your pdf looks like a pivot table. Let's assume we have a dataframe with three columns. We can pivot it with a single function like this:
pivoted = df.pivot(index='col1',columns='col2',values='col3')

Unpivoting it back without losing the index requires a reset_index dance:
pivoted.reset_index().melt(id_vars=pivoted.index.name)

To get the exact original df:
pivoted.reset_index().melt(id_vars=pivoted.index.name, var_name='col2', value_name='col3')

PS. To my surprise, melt does not get a kwarg like keep_index=True. Enhancement suggestion is still open: https://github.com/pandas-dev/pandas/issues/17440


text:
Q: Facebook Login with Trigger.io and Parse So I'm trying to implement Facebook login for my Trigger.io app but I can't figure out which method to use from the Parse SDK.
Currently I use Trigger.io's method in my login function and a Parse method that doesn't work:
function login() {
  forge.facebook.authorize(function (success) {
    Parse.FacebookUtils.logIn({
      authData: success
    });
  });
}

What I get in the success callback variable is the Facebook access token and when the access expires. They're accessed like this:
success.access_token
success.access_expires

Does anyone know the proper method and parameters I need to call to login/store a User in Parse?


text:
Q: Trying to download ~200 files using ThreadPoolExecutor -> some files are skipped I need to download ~200 files. If I run code below for the 1st time, the code downloads ~100 files. Then I need to run this code few more times in order to download the rest files (ie. if I run the code 2nd time - I can get +20-30 new files, if 3rd time - again +20-30, and so on). Why does this happen\how to fix? Maybe this is important - server may generate some files up to 10 sec.
import os
import concurrent.futures
import urllib.request
import shutil

def get_cities(osm_id, file_name, place_type):
    file_folder = os.path.join(os.getcwd(), place_type)
    file_name = file_name + '_' + place_type
    file_path = os.path.join(file_folder, file_name)

    if not os.path.exists(file_folder):
        os.makedirs(file_folder)

    if not os.path.exists(file_path):
        area_id = str(3600000000 + osm_id)

        url = 'http://overpass-api.de/api/interpreter?data=(node["place"="city"](area:'+area_id+'););out;'

        with urllib.request.urlopen(url) as response, open(file_path, 'wb') as out_file:
            shutil.copyfileobj(response, out_file)

def cities_controller(place_type='cities'):
    countries = Countries.objects.filter(status=1).exclude(osm_id=None)
    en_group_inst = Languages.objects.filter(iso_code='en').first().group

    with concurrent.futures.ThreadPoolExecutor(max_workers=multiprocessing.cpu_count()) as executor:
        for country in countries:
            osm_id = country.osm_id
            file_name = CountriesTranslations.objects.get(
                country=country, lang_group=en_group_inst).common_name.lower().replace(' ', '_')

            executor.submit(get_cities, osm_id, file_name, place_type)

cities_controller()