text:
Q: Scala by name versus function parameters This is a named parameter:
def foo(bar: => Boolean): Boolean = bar

And this is a function parameter:
def foo(bar: () => Boolean): Boolean = bar()

How do the two declarations differ? Both will be evaluated lazily and each time the parameter is accessed?  Is there an advantage to one syntax or the other?  Would the former connote a pure function versus one with side effects for the latter?


text:
Q: Graphite/Grafana query wildcard for unknown level Is it possible to write a query to match all of these metrics:
foo.bar.something1.ending_word
foo.bar.something1.something2.ending_word
foo.bar.something1.something_else.ending_word
foo.bar.something1.something2.something3.something4.ending_word
foo.bar.ending_word

Something like this:
foo.bar[*].ending_word

?
I am trying to use this to query data in Grafana:

A: If your metrics are not tagged metrics, then you have to use the normal target expression syntax, in which case wildcards cannot cover indeterminite levels.  Reference the graphite doc on this:

All wildcards apply only within a single path element. In other words,
they do not include or cross dots (.). Therefore, servers.* will not
match servers.ix02ehssvc04v.cpu.total.user, while servers....
will.

If your metrics are tagged metrics, then you must use seriesByTag() and in this case the name may be treated as "just another" tag called "name" in the seriesByTag() function.  You may use regular expressions in seriesByTag() by using "name=~regEx", which means you can use .* to cover as many levels as you want. See the graphite docs on querying by tags for additional information.
If you can't control the metric naming such that you can use tagging, I don't see a way to do what you want.  Be warned that switching a metric to being tagged means that you'll have to change all existing references to it (as well as migrate the data).
There may be some way to do this in Grafana, but I don't know Grafana.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Print Notifications How can I print every single notification on my system in obj-C?
[[NSNotificationCenter defaultCenter] addObserver:self ...];

what does in "..."? Should I use NSDistributedNotificationCenter?
let's say I have a function called logfunc which will do NSLog(@"ok");
thank you

A: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethod:) name:nil object:nil];

You can then define a method that matches your selector, like this:
- (void)myMethod:(NSNotification *)notification {
    NSLog(@"notification received: %@", notification);
}


text:
Q: SQL Server 2008 - what is the fastest way to see if rows from one table exist in another, with grouping? I am trying to find the quickest way to locate all Projects in @Table2 that contain ALL rows in @Table1.  For example, given the following data the answer should only be Project ID = 1, as it contains ALL rows in @Table1.  Project 2 should be excluded as it does not contain Manchester.
declare @Table1 table (country varchar(50), city varchar(50))
insert into @Table1 (country, city) values ('United Kingdom', 'London');
insert into @Table1 (country, city) values ('United Kingdom', 'Birmingham');
insert into @Table1 (country, city) values ('United Kingdom', 'Manchester');

declare @Table2 table (projectid int, country varchar(50), city varchar(50))
insert into @Table2 (projectid, country, city) values (1, 'United Kingdom', 'London');
insert into @Table2 (projectid, country, city) values (1, 'United Kingdom', 'Birmingham');
insert into @Table2 (projectid, country, city) values (1, 'United Kingdom', 'Manchester');
insert into @Table2 (projectid, country, city) values (1, 'United Kingdom', 'Liverpool');
insert into @Table2 (projectid, country, city) values (2, 'United Kingdom', 'London');
insert into @Table2 (projectid, country, city) values (2, 'United Kingdom', 'Birmingham');
insert into @Table2 (projectid, country, city) values (2, 'United Kingdom', 'Liverpool');

select * from @Table1
select * from @Table2

I've looked a little into EXCEPT (this post was helpful) but can only get this working without using the Project ID.  Is there some clean SQL code that can help?  In my database I expect to have up to 100,000 rows.
Many thanks

A: According to what I think I understand the requirements to be this is one way to do this.
select t2.projectid
from @Table1 t1
join @Table2 t2 on t1.country = t2.country
    and t1.city = t2.city
group by t2.projectid
having count(distinct t2.country + t2.city) = (select count(*) from @Table1)


text:
Q: Macbook Air 13" Mid 2011 battery drain issue I own a Mid 2011 Macbook Air 13".  It is running macOS Mojave 10.14.6.
I replaced the battery once with a battery purchased from Amazon.
coconutBattery is reporting, as of right now, as having:

*

*Full Charge Capacity: 7121 mAh

*Design Capacity: 7200 mAh

*Manufacture Date: 12/12/2016

*Cycle Count: 68

*battery status: Good

The problem is that it drains extremely fast. I have tried Ubuntu on it as well, no luck. Even the previous version of macOS on this system (High Sierra).  I did a full battery drain, charged to 100% and still no luck.
While turned off, I held down Shift + Control + Option + power button. I held it for about 10+ seconds, I release and the MagSafe LED turned from orange to green for a few seconds, then back to orange.
I thought it was the battery, so I ordered another battery from Amazon. The same issue.
This is making me believe that maybe some kind of connection is bad on the battery, or the Mac is having some strange issue. I know it's an old laptop, but it's been one of my favorites and I carry it around whenever I am in an area where it could be stolen. The replacement battery from iFixit is about $70, but I don't want to deal with it if it's the Mac.
Any ideas what I can try?  I remember the battery life was amazing way back when I bought it.

A: The tell-tale here is that a brand new battery behaves in the same way. Even a cheap 'imitation' Apple battery should work correctly on day 1, at least.
That suggests that it's a hardware problem. You'll need to take it to an Apple Store or other repair shop.


text:
Q: Custom UIViewController animations WITHOUT A UINAVIGATIONCONTROLLER I have a camera view controller. I want to push it. But I want it to fade in while I push it. How do I do this. I'm not using a UINavigationController.

A: You "push" a view controller onto a navigation stack. But when you present a view controller without navigation controller, you name it "present" (not "push"). Means the term "pushing" a view controller is hardly connected to UINavigationController.
So you could just google for something like "UIViewController custom transition" or anything similar.
I did great success following a this great article by Teehan+Lax. Just read it, it should lead you the right way.
EDIT Okay. I gonna add some info to provide a better answer for you.
First of all, you'll create a new subclass of NSObject and conform to the UIViewControllerAnimatedTransitioning protocol:
@interface JWTransitionAnimator <UIViewControllerAnimatedTransitioning>
+ (JWTransitionAnimator *)transitionAnimatorForPresentation;
+ (JWTransitionAnimator *)transitionAnimatorForDismissal;
@end

Then you let the magic happen in your implementation:
@interface JWTransitionAnimator ()
@property (atomic, assign, getter=isPresenting) BOOL presenting;
@end

@implementation JWTransitionAnimator
+ (JWTransitionAnimator *)transitionAnimatorForPresentation {
    JWTransitionAnimator *animator = [[self alloc] init];
    [animator setPresenting:YES];

    return animator;
}
+ (JWTransitionAnimator *)transitionAnimatorForDismissal {
    return [[self alloc] init];
}

// implement the protocol:
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitioningContext {
    return 0.3;    // or any other duration.
}
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitioningContext {
    UIViewController *fromViewController = [transitioningContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toViewController = [transitionContext UITransitionContextToViewController];

    UIView *fromView = [fromViewController view];
    UIView *toView = [toViewController view];

    if ([self isPresenting]) {
        [fromView setUserInteractionEnabled:NO];

        [[transitionContext containerView] addSubview:fromView];
        [[transitionContext containerView] addSubview:toView];

        [toView setAlpha:0.0];
        [toView setTransform:CGAffineTransformScale([fromView transform], 0.3, 0.3)];

        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            [fromView setTintAdjustmentMode:UIViewTintAdjustmentModeDimmed];

            [toView setAlpha:1.0];
            [toView setTransform:CGAffineTransformScale([toView transform], 1.0, 1.0)];
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:finished];
        }];
    }
    else {
        // reverse your animation here (change "fromView" for "toView" and vice-versa)
    }
}

Your presenting viewController must conform to the UIViewControllerTransitionDelegate protocol. Implement it as follows:
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    return [JWTransitionAnimator transitionAnimatorForPresentation];
}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    return [JWTransitionAnimator transitionAnimatorForDismissal];
}

The you present the view controller like this:
- (IBAction)presentViewController:(id)sender {
    UIViewController *yourVC = [[UIViewController alloc] init];    // however you create it
    [yourVC setModalPresentationStyle:UIModalPresentationStyleCustom];
    [yourVC setTransitionDelegate:self];

    [self presentViewController:yourVC animated:YES completion:NULL];
}


text:
Q: Is "whining" really a serious enough concern to justify not implementing useful features? "Whining" seems to be a significant concern for the Stack Exchange team that is often a strong reason for opposition against various feature-request's.  For example:
Show all of my question/answers to me even if they are deleted

@hendrik it would lead to unbelievable amounts of whining. Will not get implemented as long as I am still alive to prevent it from happening. – Jeff Atwood♦

Make the FAQ clear on how a question can be reopened

@yannis I am strongly opposed to such a page, as I believe it is a recipe for endless whining and a manifesto for "I done been wronged" attitudes. – Jeff Atwood♦

Is "whining" really a serious problem?  I understand that we don't want moderators and the community to be flooded with all sorts of complaints from users (mostly new users), but is this really an overriding concern that justifies not implementing features that can improve the Stack Exchange user experience?

A: Just replace the word "whining" with "complaining that would have little value in improving the situation".
Sure, it's rarely productive to tell an adult they're whining, as they never think they are, and so they tend to assume you just don't get or like their position.
(Note that @Jeff Atwood did not accuse anyone specific of whining in the quotes above.)
But if you reframe the quotes as,

I'm against that, as I fear it would lead to a lot more complaining that would have little value in improving the situation...

I think you get the same effective meaning, without getting hung up on the pejorative connotations of "whining".

A: Whining is reactive.  Whining is negative.  Whining does not make the world, the web or the StackExchange network a better place.
Posting helpful questions and answers is proactive.  Posting helpful questions and answers is positive.  Posting helpful questions and answers makes the world, the web and the StackExchange network a better place.
Is whining itself a really big deal?  Probably not.  Is posting helpful questions and answers a really big deal?  Probably not.  Is making a conscious choice to perpetuate an attitude that causes millions of users to favor a positive mode of being over its negative counterpart a really big deal?  Maybe.

A: Yes. Yes, whining is a serious concern. People whine when they're unhappy about something and can't think of anything productive to do about it. There are other places for that; nowhere in the site description will you find the phrase "...where there will be wailing and gnashing of teeth."
The goal of the system should always be to give folks the tools to fix problems they encounter. Not to rub their faces in problems they can't do anything about.
Bad
Unreadably long enumeration of everything that might possibly result in a question being closed.
Good
Instructions on how to fix a question and vote to re-open.
Bad
Constant reminders of deleted posts that you can't do anything about.
Good
Targeted notifications of problems on posts that you might be able to salvage.

Focus on features that solve specific problems, not those that create new ones.

A: I think that the Stack Exchange model has succeeded because its designers do their best to maximize the ratio of productive to unproductive activity. But we have to keep in mind that a site maximizing that ratio may not maximize other ratios:
friendly:unfriendly
welcoming:unwelcoming
playful:serious
... and so on

I'm not saying that Stack Overflow isn't friendly, welcoming, or playful, and I'm not saying that it shouldn't be. But I think we chose to be friendly, welcoming, or playful to the degree that those behaviors maximize productive activity.
Whining -- actually, I'll start with the more neutral term complaining -- is one of those behaviors that sometimes forces us to chose between friendliness and productivity. Time spent complaining and time spent addressing complaints is time not spent solving problems.  Of course, sometimes it's necessary to complain and address complaints to fix problems with the site, so that we can boost productive activity. But other times, complaints are too narrow or selfish to be helpful to the site as a whole. Sometimes complaining is just whining.
So I think Jeff Atwood is absolutely right that if a feature will lead to more whining -- defined here as "unproductive complaining" -- without adding significantly to the site's productive activity, then that feature doesn't belong here.
However, I do sometimes wonder whether a given feature really would lead to more whining if implemented. It would be nice if there were a convenient "whining metric," so that declarations like "it is a recipe for endless whining" could actually be tested.


text:
Q: jackson2 - unexpected field in JSON I'm trying to write a JSON from a java object. Everything works fine until I write the values to a String using the ObjectMapper. The String shows an unexpected field in the JSON document called "map".
I want this:
{
  "name": [
    {
        "a": "1",
        "b": "2",
        "c": "3",
        "d": "4",
        "e": "5",
        "f": "6"
    }
  ]
}

I get this:
 {
  "name": [
    {
      "map": {
        "a": "1",
        "b": "2",
        "c": "3",
        "d": "4",
        "e": "5",
        "f": "6"
      }
  ]
}

This is the class where I've defined the Object I want to convert to JSON:
public class SomeClass{
    private List<JSONObject> name;

//getters, setters
}

Can anyone help me?

A: Please notice that inside the class you are serializing you have a parameter called map if you called it bla you would have seen:
{
  "name": [
{
  "bla": {
    "a": "1",
    "b": "2",
    "c": "3",
    "d": "4",
    "e": "5",
    "f": "6"
  }
 ]
}

in order to get rid of the parameter name you should use the annotation: @JsonUnwrapped on top of the map parameter inside the class, like:
@JsonUnwrapped
private Map<String, String> map;

Another option is to create a getter function for map use the following:
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(map.getDataMap());

A: I've solved the problem. I just created an array of object and then I've serialized it with jackson.
private Bla[] bla;
// getters and setters

Class Bla:
private String a;
private String b;
private String c;
...
// getters and setters

Thank you for everything.
Jon


text:
Q: Checking the status of an IHostedService from another project? I'm currently working on a project which processes files via a Hosted Service background task, persists those files to a DB, then show the user that data via a webpage. The webpage and the background task are in different .NET projects: the background task in a Web API and the webpage in a MVC App. The task runs every 5 minutes.
My goal is to be able to, from the MVC Controller, reach out to the Hosted Service and ask if the task is running or if it isn't. I'm unsure if there's something within Hosted Services that I'm missing or if a 3rd-party library is the answer. I'm also unsure if there's a direct, programmatic property way to do this or if it'll have to be some sort of messaging system. I've seen things like Rabbit and Hangfire in my research, but I'm not sure if that's necessary.
The following code is all from the Hosted Service project. Here is the code for the Document Processor
public class DocProcessor: IHostedService
{
    private readonly ILogger<DocProcessor> _logger;
    private readonly IWorker _worker;

    public DocProcessor(ILogger<DocProcessor> logger, IWorker worker)
    {
        _logger = logger;
        _worker = worker;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        await _worker.DoWork(cancellationToken);
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Stopping task.");
        return Task.CompletedTask;
    }
}

Here is the IWorker interface:
public interface IWorker
{
    Task DoWork(CancellationToken cancellationToken);
}

Here is the DocProcessorWorker:
public class DocProcessorWorker: IWorker
{
    private readonly ILogger<DocProcessorWorker> _logger;

    public DocProcessorWorker(ILogger<DocProcessorWorker> logger)
    {
        _logger = logger;
    }

    public async Task DoWork(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            ... Work Being Done
            await Task.Delay(TimeSpan.FromMinutes(5), cancellationToken);
        }
    }
}

And the services portion of Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHostedService<DocProcessor>();
builder.Services.AddSingleton<IWorker, DocProcessorWorker>();
...Other stuff...
var app = builder.Build();


text:
Q: How do I change the scroll behaviour of TDrawGrid The TDrawGrid component has a standard way of determining how much to scroll when you scroll to the right and left for example.  I want the same behaviour as with a TScrollBox. The amount scrolled to the right and left is a lot less and you can control that. I was using a TScrollBox for this exact reason until I figured out that I can't have fixed Rows and Fixed Cols anymore because my ScrollBox determines the scrolling.
Is there a short way to do this without creating my own component?


text:
Q: how to print permutations of array of strings in c without recursion? Is anyone here who can explain me how to print the permutations of a array of strings in iterative method without using recursion. Please explain with code.

A: If the string is "abcd", put all of the "a" chars in position 0 for the first n-1! arrays, in position 1 for the next n-1! arrays, etc. Then put all of the "b" chars in position 1 for the first n-2! arrays, etc, all of the "c" chars in position 2 for the first n-3! arrays, etc, and all of the "d" chars in position 3 for the first n-4! arrays, etc, using modulo n arithmetic in each case to move from position 3 to position 0 as you are filling out the arrays.


text:
Q: Polynomial of prime degree: being irreducible or having a root!
Let $p$ be a prime number. Prove that for any field $K$ and any $a \in K$, the
  polynomial $x^p−a$ is either irreducible, or has a root.

it doesn't seem hard, but i have no idea.
any hint is welcomed!
thank you

A: This question is a duplicate, and has already been asked (and answered) several times:
Prove $f=x^p-a$ either irreducible or has a root. (arbitrary characteristic) (without using the field norm)
Irreducibility of a polynomial if it has no root (Capelli)
$x^p-c$ has no root in a field $F$ if and only if $x^p-c$ is irreducible?


text:
Q: How to group data in multiple rows in Excel? I need to group data from multiple rows into one row. The issue that I'm having is that I have inherited this data, thousands of rows, and Column A only contains a value when a new data row is started. For example, I have:

And I need to return:

Any ideas on how I can accomplish this?

A: Use this code:
Sub Merge()
Set d = CreateObject("Scripting.Dictionary")
arr = [a1].CurrentRegion
For i = 2 To UBound(arr)
    If Len(arr(i, 1)) = 0 Then arr(i, 1) = arr(i - 1, 1)
    If Not d.exists(arr(i, 1)) Then
        d(arr(i, 1)) = arr(i, 2)
    Else
        d(arr(i, 1)) = d(arr(i, 1)) & "," & arr(i, 2)
    End If
Next
[d2].Resize(d.Count, 2) = Application.Transpose(Array(d.keys, d.items))
End Sub


text:
Q: SQL Combine Multiple rows into Multiple Columns I have been looking at the other example here and across the web and I just cannot wrap my head around how to do this.
I have a site where I am pulling every piece of information on products into the one table to be viewed and then loaded into a csv/excel sheet.
It combines 7 tables and spits them out as below: (cut off the rest of the table to make easily readable)
ID  Filter     FilterValue  ParentItem  ItemTitle
---------------------------------------------------------------
7   15         B            LE0001      LB PALETTE WHITE 127MM
7   16         Yes          LE0001      LB PALETTE WHITE 127MM
7   18         Yes          LE0001      LB PALETTE WHITE 127MM
7   20         Std          LE0001      LB PALETTE WHITE 127MM
7   22         Yes          LE0001      LB PALETTE WHITE 127MM
7   23         Polyester    LE0001      LB PALETTE WHITE 127MM
7   25         White        LE0001      LB PALETTE WHITE 127MM
7   26         127mm        LE0001      LB PALETTE WHITE 127MM

Using this code (The current columns showing are tblprod.prodID, prodval.valueColumn, prodval.valueKey, tblprod.parentSKU, and tblprod.prodTitle )
SELECT
   tblprod.prodID as ID, prodval.valueColumn as Filter,
   prodval.valueKey as FilterValue, tblprod.prodSKU as Item,
   tblprod.parentSKU as ParentItem, tblprod.prodTitle as ItemTitle,
   tblprod.prodConsumerTitle as ConsumerTitle, tblprod.itemGroup as ItemGroup,
   tblprod.itemFamily as ItemFamily, tblprod.cutLengthCode as LengthCode,
   tblprod.prodPackSize as PackSize, tblprod.prodMultQty as MultipleQuantity,
   tblsu.ImportCode as SalesUnit, tblprod.prodPrice as SalesPrice ,
   tblprod.qtyDependent as QtyDep, tblprod.qtyTarget as Limit,
   tblprod.targetPrice as Price, tblprod.prodLegacyImage as MainImage,
   catprod.IsPrimary as SafetyinMind, featlists.prodList as NEWLimited
FROM
   [Eclipse].[dbo].[tbl_Product] AS tblprod
LEFT JOIN
   [Database].[dbo].[tbl_SalesUnit] AS tblsu ON tblsu.ID = tblprod.saleUnit
LEFT JOIN
   [Database].[dbo].[tbl_ProductFilter] AS prodfil ON prodfil.ProdID = tblprod.prodID
LEFT JOIN
   [Database].[dbo].[tbl_ProductFilterValues] AS prodval ON prodval.valueID = prodfil.valueID
LEFT JOIN
   [Database].[dbo].[tbl_ProductstoFeaturedLists] AS prodlists ON prodlists.prodID = tblprod.prodID
LEFT JOIN
   [Database].[dbo].[tbl_FeaturedLists] AS featlists ON featlists.ID = prodlists.listID
LEFT JOIN
   [Database].[dbo].[tbl_CategoryProducts] AS catprod ON catprod.prodID = tblprod.prodID

The important part is I want to combine the rows of the same ID, create column titles out of the Filter column (prodval.valueColumn) and fill them with their corresponding value (prodval.valueKey)
My issue is I just have no idea how to accomplish this and I am lost when reading the other answers, secondly there are 19 filters and not every product will have all of them (as you can see the above product has 8) I am unsure if this will cause me any issues when I do this. The filters range from 15 to 33, all of them are used but just by different products.
An example table would look like below.
ID  ParentItem  ItemTitle               Filter 15   Filter 16   Filter 17   Filter 18   Filter 19   Filter 20   Filter...
7   LE0001      LB PALETTE WHITE 127MM  B           YES                     YES                     Std

If anyone could offer any help I would seriously appreciate it, I just cannot get my head around it.
Sorry forgot to mention I am using SQL Server Management Studio

A: try below solution :
DECLARE @Columns VARCHAR(max)
;WITH cte
     AS (SELECT Min(Filter) minimum,
                Max(Filter) maximum
         FROM   yourtable)
SELECT @Columns = Stuff((SELECT ',' + '[ ' + CONVERT(VARCHAR(30), number, 121) + ']'
                         FROM   master..spt_values N
                         WHERE  EXISTS (SELECT 1
                                        FROM   cte
                                        WHERE  n.number BETWEEN cte.minimum AND cte.maximum)
                                AND type = 'P'
                         FOR XML PATH('')), 1, 1, '')

DECLARE @sql NVARCHAR(max)= 'select [ID],[ParentItem],[ItemTitle],' + @Columns +
                            ' from (select [ID],[ParentItem],[ItemTitle],[Filter],[FilterValue] from yourtable) t
                            pivot
                            (MAx(FilterValue)
                            FOR Filter in(' + @Columns + ')
                            )as pvt'

EXEC sp_executesql
  @sql

sqlfiddle

A: Use PIVOT to get the result. Fiddler Demo
CREATE TABLE #Sample
(
    ID INT,
    Filter INT,
    FilterValue VARCHAR(100),
    ParentItem VARCHAR(100),
    ItemTitle VARCHAR(100)
)

INSERT INTO #Sample VALUES(7,   15,'B',   'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   16,'Yes', 'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   18,'Yes', 'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   20,'Std', 'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   22,'Yes', 'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   23,'Polyester',    'LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   25,'White','LE0001','LB PALETTE WHITE 127MM')
INSERT INTO #Sample VALUES(7,   26,'127mm','LE0001','LB PALETTE WHITE 127MM')

SELECT P.ID,P.ParentItem, P.ItemTitle,
 Min(Filter15) Filter15,
 Min(Filter16) Filter16 ,
 Min(Filter17)Filter17,
 Min(Filter18)Filter18,
 Min(Filter19)Filter19,
 Min(Filter20)Filter20,
 Min(Filter21)Filter21,
 Min(Filter22)Filter22,
Min(Filter23)Filter23,
Min(Filter24)Filter24,
Min(Filter25)Filter25,
Min(Filter26)Filter26,
Min(Filter27)Filter27,
Min(Filter28)Filter28,
Min(Filter29)Filter29,
Min(Filter30)Filter30,
Min(Filter31)Filter31,
Min(Filter32)Filter32,
Min(Filter33)Filter33
FROM
 (SELECT *,
               'Filter' + CONVERT(VARCHAR(30), Filter)  AS Filter_A

        FROM   #Sample
 ) AS A

 PIVOT (Min(A.FilterValue) FOR Filter_A in
      (Filter15,Filter16,Filter17,Filter18,Filter19,
       Filter20,Filter21,Filter22,Filter23,Filter24,
       Filter25,Filter26,Filter27,Filter28,Filter29,
       Filter30,Filter31,Filter32,Filter33)) AS P
GROUP BY P.ID,P.ParentItem, P.ItemTitle


text:
Q: Unable to modify machine.config file I want to improve performance of my ASP.NET web application and want to change "processModel" tag in machine.config. But I am unable to modify "machine.config" file located at framework directory. Though I have disabled "readonly" permission for the file, still it is not working.

A: Open it using NotePad++ (or) NotePad. You have to run Notepad first in Administrator more (right click, select Run as administrator), then open machine.config
Ramkumar Thangavel.

A: You need to run the text editor that you are using to edit the machine.config file as Administrator.

A: For Visual Studio:

*

*Right click on Visual Studio icon

(If you are right clicking on a taskbar icon, then you'll need to right click on the Visual Studio icon in the list as well)

*Click Run as administrator

*Within Visual Studio, click File->Open->File... (shortcut is Ctrl + O)

*From here, navigate to your machine.config. For .net 4, it's probably here: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config


text:
Q: Aggregating a pandas data frame and deleting non required rows I have a data frame on which I want to perfom an aggregation and get rid of some rows that are not required basis a certain condition
ID  Type                     Band      Event            Date        Function       Title                Country
1   Lead  Jr                   L       Hire             07/06/2016  PM          Lead Product Specialist India
1   Lead  Jr                   L       Job Change       01/03/2019  PM          Lead Product Specialist India
1   Lead  Jr                   L       Job Change       01/03/2019  PM          Lead Product Specialist India
1   Lead  Sr                   S       Promotion        25/07/2019  PM          Lead Project Manager    India
2   Trainee                    P       Job Change       25/07/2016  AM          Trainee                 Australia
2   SW Developer               L       Promotion        25/07/2017  AM          Developer Lead          Australia
2   SW Developer               L       Job Change       25/07/2018  AM          Developer Lead          Australia
2   Lead  Specialist           S       Promotion        25/07/2019  AM          Lead Project Manager    Australia
3   Lead  Specialist           S       Promotion        25/10/2019  AM          Lead Project Manager    Australia
4   Sr  Specialist             S       Promotion        25/11/2019  AM          Lead Project Manager    Australia

and I want the following output from the data:
ID  Type                Band       Event            Date        Function       Title               Country
1   Lead  Jr             L         Job Change    01/03/2019     PM       Lead Product Specialist     India
1   Lead  Sr             S         Promotion     25/07/2019     PM       Lead Project Manager        India
2   Trainee              P         Job Change    25/07/2016     AM       Trainee                   Australia
2   SW Developer         L         Job Change    25/07/2018     AM       Developer Lead            Australia
2   Lead  Specialist     L         Promotion     25/07/2019     AM       Lead Project Manager      Australia
3   Lead  Specialist     S         Promotion     25/10/2019     AM       Lead Project Manager      Australia
4   Sr  Specialist       S         Promotion     25/11/2019     AM       Lead Project Manager      Australia

So essentially the logic is that I need to get the unique record basis the grouping at Type and band level and taking that record with the latest date, meaning the latest record. So if there are three records with Band = "L" and Type = "Lead Jr" with three different dates, then I need to take the latest record basis the date out of these three and so on.

A: *

*Use pandas.DataFrame.sort_values & pandas.DataFrame.drop_duplicates
# date to datetime
df.Date = pd.to_datetime(df.Date)

# depending on the data, optionally sort
df.sort_values(['ID', 'Type', 'Date'], inplace=True)

# drop_duplicates with keep='last'
df.drop_duplicates(['ID', 'Type', 'Band'], keep='last')  # optionally add .reset_index(drop=True)

sort and drop_duplicates as a single line
df.sort_values(['ID', 'Type', 'Date']).drop_duplicates(['ID', 'Type', 'Band'], keep='last')

Result
   ID              Type Band       Event       Date Function                    Title   Country
2   1          Lead  Jr    L  Job Change 2019-01-03       PM  Lead Product Specialist      India
3   1          Lead  Sr    S   Promotion 2019-07-25       PM     Lead Project Manager      India
7   2  Lead  Specialist    S   Promotion 2019-07-25       AM     Lead Project Manager  Australia
6   2      SW Developer    L  Job Change 2018-07-25       AM           Developer Lead  Australia
4   2           Trainee    P  Job Change 2016-07-25       AM                  Trainee  Australia
8   3  Lead  Specialist    S   Promotion 2019-10-25       AM     Lead Project Manager  Australia
9   4    Sr  Specialist    S   Promotion 2019-11-25       AM     Lead Project Manager  Australia

A: If you sort the dataframe inversely by Date, then within each group, the data is sorted in that way as well, so you can safely take the first one.
df.sort_values("Date", ascending=False).groupby(["Type", "Band"]).first()


text:
Q: Vs2011 beta display hangs I installed Visual Studio 2011 beta and it seemed to install fine apart from the display badly lags begind control input, the display doesnt refresh and I need to hover my mouse over the code editor window like an etch a sketch. I've tried to tweak all the display settings btw: i5/GeForce 415M,  single/dual monitor. refresh is 60hz.
Any ideas appreciated.
Edit:
Update: Here was the fix for me - Right Click VS launcher, Run using -> Integrated Graphics.


text:
Q: Prisma: Update using "where" with non-unique fields? When checking out the typings for the update method in Prisma ORM, I found that I can only include a where clause for unique fields:
return this.prisma.publication.update({
    data,
    where: {id},
});

I'd love to combine this with authentication and do something like:
return this.prisma.publication.update({
    data,
    where: {id, owner: user.id}, <-- Authorisation
});

Is this at all possible with Prisma or do I need a separate query for this that retrieves the instance?

A: In this case, you would need to use updateMany as you are using a non-unique field along with the unique one.

A: Apparently, as of Prisma version 4.5.0, there is a new feature allowing you to add non-unique fields to the unique where clause as long it contains at least one unique field.
Prisma realese 4.5.0
It's a preview feature so in order to enable it, add this to your shcema.prisma:
generator js {
  provider        = "prisma-client-js"
  previewFeatures = ["extendedWhereUnique"]
}

And then your code sample will work.
return this.prisma.publication.update({
  data,
  where: {id, owner: user.id},
});


text:
Q: please explain this definition of neighborhood in graphs? $$N(A) = \bigcup_{v\in A} N(v)$$
$v$ is a vertex in $G(V,E)$ graph. $A$ is a subset of $V$. In my book, it is defined as

"If $A$ is a subset of $V$, we denote by $N(A)$ the set of all vertices
  in $G$ that are adjacent to at least one vertex in $A$"
-Referenced from Discrete mathematics and its applications (7th ed.) by Rosen, K. (2012).

I can understand the definition of the sentence. But I cannot understand the equation. Please explain by breaking the equation down if it is possible.

A: $N(v)$ denotes the neighbors of a vertex $v$.
Each vertex $v$ in $A$ has its own set of neighbors $N(v)$.
If a vertex is a neighbor of at least one vertex $v$ in $A$, then it belongs to at least one of these $N(v)$. So we take the union of all these neighbor sets $N(v)$ over all vertices $v \in A$.
For example, if $A=\{v_1,v_2,v_3\}$, then the neighbor sets of each vertex are $N(v_1)$, $N(v_2)$ and $N(v_3)$, and we define $N(A)$ as $\bigcup_{v \in A} N(v) := N(v_1) \cup N(v_2) \cup N(v_3)$.

A: The equation is saying that the neighborhood of $A$ is just the union of all the neighborhoods of vertices in $A$. The index on the union symbol just means to take the union over all vertices in $A$.

A: The author is using $N(v)$ to denote the set of all vertices which are connected to $v$ by an edge (i.e., the set of all neighboring vertices).  In an equation:
$$ N(v)=\{w\in V\mid (v,w)\textrm{ is an edge}\}$$
From this, the validity of the equation is easy to see.


text:
Q: map multiple rows of first dataframe into list in another Hello I am mapping databases together and stuck on the following step of our workflow.
I have a main df:
name, id
'tree', 0
'foo', 1
'apple', 2
'table', 3

And another map_df for the codes
ID, id_for_map, Code
0, 0, 'aa'
1, 1, 'ab'
2, 1, 'ac'
3, 2, 'ba'
4, 2, 'bb'
5, 3, 'bb'

I would like to get every code in a list as a column of the main df after the id matching:
name, id, code
'tree', 0, ['aa']
'foo', 1,  ['ab','ac']
'apple', 2, ['ba','bb']
'table', 3, ['bb']

I tried to use temp dataframes, with a lot of inefficent work, but still couldn't figure it out.
Thank you for your help in advance!

A: You can try
df1['code'] = df1['id'].map(df2.groupby('id_for_map')['Code'].agg(list))

print(df1)

      name  id          code
0   'tree'   0        ['aa']
1    'foo'   1  ['ab', 'ac']
2  'apple'   2  ['ba', 'bb']
3  'table'   3        ['bb']


text:
Q: Android ActionbarSherlock - is it possible to place the share call to action right next to the List navigation? I just got the pulldown navigation to work with ActionbarSherlock. Here is how it looks like:

And what I am wondering is whether I can put the sharing widget right next to the pulldown on the same action bar?  If so, how can I do that?  Is it part of the layout xml that I have to add? Or where/what needs to be specified?
This is my values/arrays.xml file
<resources>
    <string-array name="locations">
        <item>Home</item>
        <item>Learn</item>
        <item>Services</item>
        <item>Next Steps</item>
    </string-array>
</resources>

And this is how I start the activity:
private TextView mSelected;
private String[] mLocations;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setTheme(R.style.Theme_Sherlock_Light);

But when I try to add both, the sharing and the list-navigation. It doesn't render one or the other. Here is what I try to do:
    Context context = getSupportActionBar().getThemedContext();
    ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(
            context, R.array.locations, R.layout.sherlock_spinner_item);
    list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);

    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    getSupportActionBar().setListNavigationCallbacks(list, this);

Thanks,
Alex
RUNTIME ERROR:
java.lang.ClassCastException: android.widget.ShareActionProvider cannot be cast to com.actionbarsherlock.view.ActionProvider
        at com.actionbarsherlock.view.MenuInflater$MenuState.readItem(MenuInflater.java:389)
        at com.actionbarsherlock.view.MenuInflater.parseMenu(MenuInflater.java:162)
        at com.actionbarsherlock.view.MenuInflater.inflate(MenuInflater.java:112)
        at com.marketing.MainActivity.onCreateOptionsMenu(MainActivity.java:880)
        at com.actionbarsherlock.app.SherlockActivity.onCreatePanelMenu(SherlockActivity.java:184)
        at com.actionbarsherlock.ActionBarSherlock.callbackCreateOptionsMenu(ActionBarSherlock.java:559)
        at com.actionbarsherlock.internal.ActionBarSherlockNative.dispatchCreateOptionsMenu(ActionBarSherlockNative.java:65)
        at com.actionbarsherlock.app.SherlockActivity.onCreateOptionsMenu(SherlockActivity.java:149)
        at android.app.Activity.onCreatePanelMenu(Activity.java:2444)
        at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:388)
        at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:739)
        at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:2833)
        at android.os.Handler.handleCallback(Handler.java:605)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4424)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)

A: You can read how to add ShareActionProvider to SherlockActionBar here /simple tutorial/

A: Look here for information on how to add an easy share action widget. Yes, in your layout menu xml you would add it as another item. It looks as if there is little room for an icon, so you might want to push the current "Learn" menu into overflow.
Edit:
I think it would be simpler to do this by inflating your entire menu from xml. Examples can be found here, but
basically you override onCreateOptionsMenu:
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}

menu/main_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="Share"         android:actionProviderClass="android.widget.ShareActionProvider" />

<item
android:id="@+id/menuSort"
android:showAsAction="ifRoom"
android:actionLayout="@layout/action_sort"  />

</menu>

layout/action_sort.xml:
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:entries="@array/locations" />


text:
Q: Using Angular.js to access php array data I've already asked a question like this but i'm getting issues. I'm using angular.js to send data to a php file. This php file is gathering a list of data and storing this in an array. I'm then encoding this array and sending it back to angular on a success function. I need to display each array one after the other on each other.
Any suggestions ?
if($result){
 while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){

  $Participants = array(
            firstname => $row['firstname'],
            lastname => $row['lastname'],
            amount => $row['longitude']
        );

 }

}

echo json_encode($Participants);

My angular
     angular.forEach(response.data, function(value, key){

        var Participants = {};

        Participants = {

          firstname: value['firstname'],
          lastname: value['lastname'],
          amount: value['amount'],
        };

        console.log(Participants);

        });

A: Your array will only ever hold one participant.  Declare it above the loop, and append to it within:
$Participants = array();

if($result) {
    while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){

        $Participants[] = array(
            firstname => $row['firstname'],
            lastname => $row['lastname'],
            amount => $row['longitude']
        );
}

A similar issue exists in your client-side angular code:
// Note this is now an array instead of plain object
var Participants = [];
angular.forEach(response.data, function(value, key){
    Participants.push({
        firstname: value['firstname'],
        lastname: value['lastname'],
        amount: value['amount'],
    });
});

console.log(Participants);


text:
Q: PSSH private key issue I'm new to PSSH. I followed the PSSH document to write the script. When I use Private key, it returns with the error "ImportError: No module named ecdsakey"
I tried downloading that module but there is no "ecdsakey" modul,the module available is "ecdsa" and it's already installed. Searched everywhere but couldn't find the relevant answer.I'm using ubuntu14.04 OS
from __future__ import print_function
from pprint import pprint
import paramiko
from pssh.pssh_client import ParallelSSHClient
from pssh.exceptions import AuthenticationException,UnknownHostException,ConnectionErrorException
client_key = paramiko.RSAKey.from_private_key_file('/home/ubuntu/Downloads/pssh.txt')
client=ParallelSSHClient(['ip1','ip2'],pkey=client_key)
try:
    output=client.run_command('ls /',sudo=True)
except(AuthenticationException,UnknownHostException,ConnectionErrorException):
    pass

Error:
Traceback (most recent call last):
File "pssh1.py", line 4, in <module>
from pssh.utils import load_private_key
File "/usr/local/lib/python2.7/dist-packages/pssh/__init__.py", line 33, in <module>
from .pssh_client import ParallelSSHClient
File "/usr/local/lib/python2.7/dist-packages/pssh/pssh_client.py", line 36, in <module>
from .ssh_client import SSHClient
File "/usr/local/lib/python2.7/dist-packages/gevent/builtins.py", line 93, in __import__
result = _import(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pssh/ssh_client.py", line 32, in <module>
from .utils import read_openssh_config
File "/usr/local/lib/python2.7/dist-packages/gevent/builtins.py", line 93, in __import__
result = _import(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pssh/utils.py", line 27, in <module>
from paramiko.ecdsakey import ECDSAKey
File "/usr/local/lib/python2.7/dist-packages/gevent/builtins.py", line 93, in __import__
result = _import(*args, **kwargs)
ImportError: No module named ecdsakey

A: Try these commands:
sudo pip install ecdsa

If you are on Python 3.x you might have to use pip3 instead of pip:
sudo pip3 install ecdsa


text:
Q: How to use JSON between PHP and javascript I have made an application requesting data to a PHP and javascript receives the data and displays it.
At first I did it by getting the data separated by ',' and it works fine, but I want to do it with JSON and this is where I have the problem.
I receive the data and try to decode them but it gives me the following error:
Uncaught SyntaxError: Unexpected token <in JSON at position 0
     At JSON.parse (<anonymous>)
     At XMLHttpRequest.xmlhttp.onreadystatechange

In the received variable I have:
"<meta charset="utf-8"/>
↵  {"rastro":"entrada:inicio-inicio-comprobarPerfil-conectar-","mensaje":"si","usuario":"Invitado47","password":"","email":""} "

My code is:
PHP
$jsondata = array();
$jsondata["rastro"] = $rastro;
$jsondata["mensaje"] = $mensaje;
$jsondata["usuario"] = $usuario;
$jsondata["password"] = $password;
$jsondata["email"] = $email;

echo '' . json_encode($jsondata) . '';

javascript
var xmlhttp;

xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {

    if (xmlhttp.readyState==4 && xmlhttp.status==200) {

         var contenidosRecibidos = JSON.parse(xmlhttp.responseText);

I have looked at google for many examples and it seems all very simple but there is no way it works.
Thank you for your help

A: I don't know if this is the best solution but this is what I use to use JSON in Javascript via PHP.
PHP:
    <script>
           var datavalue= <?php echo json_encode($answers) ?>;
    </script>

The data is a JSON object. I also recommend to have a look at jQuery, which provides excellent ways to call PHP pages and have JSON as a result.

A: It looks like your PHP page is throwing some error/warning.
Try to print response like this.
    echo json_encode($jsondata);

That might not be the cause for your proble. But I strongly suspect that your PHP page is throwing some warning.
And are you sure $password is not "Undefined" ?
Try
    console.log(xmlhttp.responseText)

before parsing it. You'll get the warning/error.

A: Thank you. The problem was in the beginning of PHP, in the first line had:
<meta charset="utf-8"/>


text:
Q: Exporting a Greenplum data base to Amazon S3 as a .csv Hypothetical scenario - I have a 10 node Greenplum cluster with 100 TB of data in 1000 tables that needs to be offloaded to S3 for reasons. Ideally, the final result is a .csv file that corresponds to each table in the database.
I have three possible approaches, each with positives and negatives.
COPY - There is a question that already answers the how, but the problem with psql COPY in a distributed architecture, is it all has to go through the master, creating a bottleneck for the movement of 100TB of data.
gpcrondump - This would create 10 files per table and the format is TAB Delimited, which would require some post-gpcrondump ETL to unite the files into a single .csv, but it takes full advantage of the distributed architecture and automatically logs successful/failed transfers.
EWT - Takes advantage of the distributed architecture and writes each table to a single file without holding it in local memory until the full file is built, yet will probably be the most complicated of the scripts to write because you need to implement the ETL, you can't do it separately, after the dump.
All the options are going to have different issues with table locks as we move through the database and figuring out which tables failed so we can re-address them for a complete data transfer.
Which approach would you use and why?

A: I suggest you use the S3 protocol.
http://www.pivotalguru.com/?p=1503
http://gpdb.docs.pivotal.io/43160/admin_guide/load/topics/g-s3-protocol.html


text:
Q: Connection to a PostgreSQL through PHP It just stays at the ... or die ("Can't Connect"); and nothing else happens, but I know that everything is right on the Connection String
<?php
    header('Content-Type: text/html; charset=utf-8');

    echo "Teste Inicio"; //To see if it can reach this part of code

    $conn_string = "host='localhost' port='5432' dbname='name_db' user='user_pgsql' password='passuser_pgsql'"; //Connection String
    $db_conn = pg_connect($conn_string) or die("Can't Connect");

    echo "Teste Depois Conexão"; //To see if it can reach this part of code

    $stat = pg_connection_status($db_conn);
    echo $stat;

    if ($db_conn)
    {
        echo "Teste Conectou"; //Echo to see if it has connected
            $query = "SELECT idgestores FROM gestores"; //Query
            echo "
"."Conexão bem sucedida"; //Connection Successfully
            $result = pg_query($db_conn, $query);
            while($row = pg_fetch_row($result))
            {
                echo "
"."ID: $row[0]   Nome: $row[1]";
                echo "
";
            }
    }
    else
    {
        echo "Teste Erro"; //Error
        echo "Erro de Ligação"; //Error
    }
?>


text:
Q: Accumulate sum of all element in list having integers I'm trying to get the sum of all numbers for each list through itertool accumulate function:
This is the code:
from itertools import *
import operator

list_numbers = [[45,43,56,67],[41,423,526,627,897],[545,453,656,667]]

Iterable_list = iter(list_numbers)

while(True):
    try:
        print(list(accumulate(next(Iterable_list),operator.add))[-1])
    except StopIteration as ex:
        print(ex)
        break

The above works well.
if I try to take out the max of each list:
while(True):
    try:
        print(list(accumulate(next(Iterable_list),func=max))[-1])
    except StopIteration as ex:
        print(ex)
        break

this also works well.
My interpretation was, if I use func = sum, it will do the sum of each list like I tried below but it prompts error
message:
'int' object is not iterable

while(True):
    try:
        print(list(accumulate(next(Iterable_list),func=sum))[-1])
    except StopIteration as ex:
        print(ex)
        break

Why it doesn't it work and in which scenario can we use func = sum?

A: You could understand better the behavior of itertools.accumulate if you use a lambda function to explore the inputs that func will receive.
Let's use lambda x: print(x) instead of sum first, to print the values:
TypeError: <lambda>() takes 1 positional argument but 2 were given

Ok, so func will receive two values. Let's try lambda x, y: print(x, y):
45 43
None 56
None 67
None
41 423
None 526
None 627
None 897
None
545 453
None 656
None 667
None

Why are we seeing None? Because print() does not return any value, so it returns a None.

This means that func should receive two values from the iterator (L1 and L2), apply an operation on both values and return a single value C. Then, apply the same operation on the previous result (C) with the next value in the iterator (L3).

Why sum() fails?
Well, because it expects a single argument, an iterable, and optionally accepts a second (start). Now, itertools.accumulate is passing two values and Python assumes you're trying to use sum(L1, start=L2), but L1 is not iterable since its just a number... TypeError: 'int' object is not iterable.
In which scenario can we use func=sum?
sum() could help us if it could receive two values and return a single one, which is possible (sum(iterable, start=start)). Now, consider that the output of sum will be used as the first input of sum with the next element in the iterable, something like: sum(sum(L1, start=L2), start=L3) and so on. This means that sum(L1, start=L2) should return an iterable for us to be able to use sum. It's hard to find an example for this, meaning that sum might not be the best option for any particular case when using itertools.accumulate, but this doesn't mean that sum is not useful by itself.

A: This can be done using Zip() or map() method or using numpy.
Using zip():
def nested_sum(lst):

 return [sum(i) for i in zip(*lst)]

lst = [[2, 4, 6], [2, 2, 1], [1, 2, 3]] # A Sample List
print(nested_sum(lst))

#Output
[12,5,6]


text:
Q: use functions exported in dll While creating a dll using MSVC(Microsoft Visual C++), one should explicitly export the names that are supposed to be used by others.
Should I explicitly import names that I used in my files?
Example:
/*Math.c  will be compiled to a dll*/
__declspec(dllexport) double Sub( double a, double b )
{
    return a - b;
}

and compile Math.c to a dll
cl /LDd Math.c

this generates 4 files Math.dll Math.obj Math.lib Math.exp
I want to use Sub() in my programs and Should I IMPORT Sub like this or not??
/*TestMath.c*/
#include <stdio.h>

__declspec(dllimport) double Sub( double a, double b );
//or can I just ignore the __declspec(dllimport) ?
//I can compile TestMath.c to TestMath.exe without it in Win7 MSVC 2010
//but some books mentioned that you should EXPLICT IMPORT this name like above
int main()
{
    double result = Sub ( 3.0, 2.0 );
    printf( "Result = %f\n", result);
    return 0;
}

and I compile it with Math.lib to TestMath.exe as:
cl /c TestMath.c //TestMath.c->TestMath.obj
link TestMath.obj Math.lib // TestMath.obj->TestMath.exe

__decclspec(dllexport) or some .def files to explicit declare export name is necessary, TestMath.exe will run error if there is no export declaration.
And My Question is:
Is IMPORT declaration necessary? Some books say yes, but without it, I can run my demo correctly.


text:
Q: Pass Parameter for Lazy Instantiation Given the following code snippet, how can I pass the member variable _tenantContext into the Lazy<CloudBlobContainer> constructor?
public class BlobStorage : IStorage
{
    private readonly ITenantContext _tenantContext;

    public BlobStorage(ITenantContext tenantContext)
    {
        _tenantContext = tenantContext;
    }

    private readonly Lazy<CloudBlobContainer> _blobcontainer = new Lazy<CloudBlobContainer>(() =>
    {
        var connectionString = ConfigurationManager.ConnectionStrings["FileStorage"].ConnectionString;
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer blobContainer = blobClient.GetContainerReference("attachments");
        blobContainer.CreateIfNotExists();

        return blobContainer;
    });

A: I believe this will work:
public class Foo
{
    private readonly object _bar;
    private readonly Lazy<int> _lazyInt;

    public Foo(object bar)
    {
        _bar = bar;
        _lazyInt = new Lazy<int>(() => GetLazyObject(_bar));
    }

    private static int GetLazyObject(object init)
    {
        return init.GetHashCode();
    }
}


text:
Q: Fitting 3D surface to lines I'm trying to fit a 3D surface to about a dozen lines that I have, and am not sure how to do this. Here is what I have so far:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

healths = [80, 55, 17, 74, 57, 31, 22, 27, 87, 18, 43]
models = [np.poly1d([  4.28223697e+08,  -3.83982829e+09,   1.54420366e+10,
        -3.68735527e+10,   5.82979362e+10,  -6.43887895e+10,
         5.10598512e+10,  -2.94075941e+10,   1.22979001e+10,
        -3.69415039e+09,   7.80163678e+08,  -1.12121998e+08,
         1.05309654e+07,  -6.30329783e+05,   2.62939411e+04,
         2.78341012e+03]),
          np.poly1d([ -5.03569457e+08,   4.13162720e+09,  -1.53435594e+10,
         3.41117449e+10,  -5.05920921e+10,   5.27923363e+10,
        -3.98217265e+10,   2.19550281e+10,  -8.83588557e+09,
         2.56102119e+09,  -5.19347600e+08,   6.97912073e+07,
        -5.55518569e+06,   1.81867166e+05,   6.20639376e+03,
         2.98402109e+03]),
          np.poly1d([ -3.11228639e+08,   2.54546572e+09,  -9.38149455e+09,
         2.05935433e+10,  -2.99744015e+10,   3.04666739e+10,
        -2.21712463e+10,   1.16419022e+10,  -4.38122091e+09,
         1.15421540e+09,  -2.02321433e+08,   2.09660556e+07,
        -7.91107187e+05,  -7.20219187e+04,   1.09687645e+04,
         3.03857181e+03]),
          np.poly1d([  4.06376109e+08,  -3.40876838e+09,   1.29871912e+10,
        -2.97061518e+10,   4.54326091e+10,  -4.89753710e+10,
         3.82216169e+10,  -2.18390890e+10,   9.13394309e+09,
        -2.76751311e+09,   5.95043272e+08,  -8.79507913e+07,
         8.57795062e+06,  -5.35644516e+05,   2.33340505e+04,
         2.84100399e+03]),
          np.poly1d([  5.85452053e+08,  -4.32915850e+09,   1.44085701e+10,
        -2.85267351e+10,   3.74193127e+10,  -3.42989241e+10,
         2.26027183e+10,  -1.08749153e+10,   3.85568236e+09,
        -1.01690647e+09,   2.02670602e+08,  -3.11739277e+07,
         3.71627668e+06,  -3.28017937e+05,   2.02386281e+04,
         2.86613920e+03]),
          np.poly1d([  9.67869416e+07,  -7.20947000e+08,   2.42488924e+09,
        -4.85195211e+09,   6.39741251e+09,  -5.80880723e+09,
         3.67879424e+09,  -1.60522563e+09,   4.62972701e+08,
        -8.12821951e+07,   8.28251991e+06,  -1.33038835e+06,
         5.02616864e+05,  -1.06915704e+05,   1.18577216e+04,
         2.95626138e+03]),
          np.poly1d([ -8.21965398e+07,   6.66113115e+08,  -2.43997814e+09,
         5.35210028e+09,  -7.84838350e+09,   8.12834471e+09,
        -6.11475052e+09,   3.37560830e+09,  -1.35904117e+09,
         3.88270096e+08,  -7.36513971e+07,   7.69475814e+06,
        -4.68518014e+04,  -9.39497975e+04,   1.19806651e+04,
         2.94753388e+03]),
          np.poly1d([  4.44955719e+06,  -4.77598603e+07,   2.22221359e+08,
        -6.00377966e+08,   1.05765733e+09,  -1.28774804e+09,
         1.11742436e+09,  -7.01168814e+08,   3.19423895e+08,
        -1.05427538e+08,   2.51936455e+07,  -4.42976358e+06,
         6.05534885e+05,  -7.03349132e+04,   7.68758833e+03,
         3.07576987e+03]),
          np.poly1d([  1.86261524e+09,  -1.48587084e+10,   5.35778935e+10,
        -1.15449514e+11,   1.65600547e+11,  -1.66711318e+11,
         1.21000328e+11,  -6.40359773e+10,   2.47042057e+10,
        -6.87497940e+09,   1.35135140e+09,  -1.81534762e+08,
         1.59351750e+07,  -8.74063407e+05,   3.12551420e+04,
         2.78842491e+03]),
          np.poly1d([ -5.18981082e+08,   4.15882351e+09,  -1.50353149e+10,
         3.24186114e+10,  -4.64249139e+10,   4.65234117e+10,
        -3.34717498e+10,   1.74414418e+10,  -6.54853332e+09,
         1.73539847e+09,  -3.10545763e+08,   3.40774866e+07,
        -1.68331576e+06,  -5.34555987e+04,   1.21777897e+04,
         2.98675915e+03]),
          np.poly1d([ -2.06268790e+08,   1.62871951e+09,  -5.84473299e+09,
         1.26039508e+10,  -1.81881671e+10,   1.84965039e+10,
        -1.35835529e+10,   7.25000855e+09,  -2.78509188e+09,
         7.47231759e+08,  -1.30834535e+08,   1.24172387e+07,
        -7.93649306e+04,  -1.15924911e+05,   1.29540492e+04,
         2.97883998e+03])]

x = np.linspace(0,1,1000)
y = [[health]*1000 for health in healths]
z = [model(x) for model in models]

# Plot all the lines I want to fit a surface to
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, projection='3d')
for yy, zz in zip(y, z):
    ax1.plot(x, yy, zz)

ax1.set_xlabel('SoC')
ax1.set_ylabel('SoH')
ax1.set_zlabel('OCV')

#Create many small surfaces (FOUND ON SO)
def fun(x, y):
  return models[healths.index(y)](x) # Select the model for the correct health, and evaluate at all x points

y = healths
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
# end of what was found on SO

# Plot the surface
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, projection='3d')

ax2.plot_surface(X, Y, Z)

ax2.set_xlabel('SoC')
ax2.set_ylabel('SoH')
ax2.set_zlabel('OCV')

plt.show()

which gives the following plots:

But there are some problems with this.

*

*This appears to just be a group of small surfaces being plotted, not 1 single surface that was fit to all the liens

*I do not get an equation I can use to reproduce the surface(s) (unlike np.poly1d)

The reason I am trying to do this is because I want to be able to input just the health value (SoH on the plots) and then output a 2d line similar to the ones I am trying to fit.
In order to do this, I believe I need to fit a 3D surface to the lines. So, my question is, how can I fit a 3D surface to the lines and get the surfaces equation?
Thanks, let me know if anyone needs more details or if this has been answered. I was looking online for a while and could not find an answer that I could make work.


text:
Q: How to make cocoapods build for device only? I'm trying to create a cocoa pod out of my Cocoa Touch Framework project. The project is not intended to support iOS simulator, only devices. It doesn't even compile for simulator. And it becomes a problem, because cocoapods tries (at least I think so) to build it for simulator and fails.
When I run the following command:
pod spec lint --verbose

it failes and the part of the output is the following:
The following build commands failed:
CompileC /var/folders/_w/9b4kyb8x2lzb9hvpn94jtrh00000gp/T/CocoaPods/Lint/build/Pods.build/Release-iphonesimulator/jsoncpp.build/Objects-normal/i386/jsoncpp.o jsoncpp/dist/jsoncpp.cpp normal i386 c++ com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)
-> RevSDK (0.1.0)
- ERROR | [iOS] xcodebuild: Returned an unsuccessful exit code.
- NOTE  | xcodebuild:  Headers/Public/RevSDK/time.h:62:10: fatal error: 'base/base_export.h' file not found

Analyzed 1 podspec.

[!] The spec did not pass validation, due to 1 error.

I'm not really good at understanding how the whole process goes and what exactly is wrong, but this line in the output:
CompileC /var/folders/_w/9b4kyb8x2lzb9hvpn94jtrh00000gp/T/CocoaPods/Lint/build/Pods.build/Release-iphonesimulator/jsoncpp.build/Objects-normal/i386/jsoncpp.o jsoncpp/dist/jsoncpp.cpp normal i386 c++ com.apple.compilers.llvm.clang.1_0.compiler

makes me think that cocoapods is trying to compile my project for the simulator. So I need to exclude it somehow. I need to let it know that it should compile for device only. What I tried was adding the following into my .podspec file:
s.xcconfig     = {
'VALID_ARCHS' => ['armv7', 'armv7s', 'arm64']
}

but unfortunately it produced no effect. And I literally don't know what to do. Can anyone help me?

A: This is probably the same or similar issue around VALID_ARCHS being deprecated in Xcode 12 and EXCLUDED_ARCHS needed.
s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }

A: Try this:
s.pod_target_xcconfig = { 'VALID_ARCHS' => 'armv7', 'armv7s', 'arm64' }


text:
Q: Laravel share variable to views in custom middleware group I need to put $page variable into views in some group of routes. I found one solution to put routes in middleware group and in middleware use View::share. But if I place any function in middleware will this code run for
How does view composer work? Does it try to run function on each view? I'm just thinking about performance if one page is from multiple views....
Middleware:
public function handle(Request $request, Closure $next)
{
     View::share('page', Page::get());

     return $next($request);
}

Will query for getting Pages get called once for multiple views?


text:
Q: data not deleted from DB when removing items in RIA Services I have a Silverlight3 client consuming an unmodified/code-generated DomainService through RIA Services with a Linq-to-SQL back end.  Is this the correct way to delete a row from the database?
this.context.Albums.Remove(this.context.Albums[0]);
this.context.SubmitChanges();

The SubmitOperation comes back with no errors, but no rows are ever deleted from the database.  Inserts work just fine.

A: What does your corresponding DomainService have on the server?
Does it have a DeleteAlbum method, that attaches the Album to the Linq-to-SQL DataContext, and then calls DeleteOnSubmit?
Couple of things to try -
Override SubmitChanges on the server, and add a try/catch to see if you're hitting some exception.
Alternatively on the client, pass in a callback into SubmitChanges (i.e. use the other overload), and see if the SubmitOperation passed into the callback has its HasError property true, along with what the Error is.
Hope that helps narrow down the problem...


text:
Q: Android Studio - "Unmappable character for encoding UTF-8" All was working fine and dandy with Eclipse in Windows until I switched to Mac OS X Yosemite, using Android Studio V1.0. I imported the project as a Non-Android Studio project since it was created with Eclipse, the import went fine and then Android Studio started showing this error all over the files :
error : unmappable character for encoding UTF-8

EDIT: Opening files directly into Sublime Text show no errors in foreign characters. Using view.encoding() inside ST's console I was able to see the file encoding, which was Western (Windows 1252). I went to Android Studio and changed the encoding of the file to windows-1252 and it's now working fine !
Is there a way to tell Android Studio to read the files in windows-1252 and then convert them to UTF-8 to keep the standard encoding format ?

A: Adding the following to build.gradle solves the problem :
android {
    ...
    compileOptions.encoding = 'ISO-8859-1'

A: I have encountered this problem, too.
The reason for my problem is that I copy a file which is not encoded UTF-8 from Eclipse to Android Studio.
A solution to this problem is that:

*

*Make sure the default file encoding of your Android Studio is UTF-8:
Settings --> File Encodings, set  IDE Encoding, Project Encoding and Default encoding for properties files to UTF-8.

*Copy your error file to a txt file and delete the error file.

*Create a new file, its name is as the same as the deleted file.

*Copy the content from the txt file to the new file.

A: For Android Studio 2.2 you have To add compile option in gradle file of your project:
android {
    ...
    compileOptions {
        encoding "ISO-8859-1"
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}


text:
Q: Laravel Controller acrescentar conteudo? Sou novato e gostaria de uma ajuda, tenho um controller que realiza uma consulta.
Controller
$user = $this->user->find('1');
view('index', compact('user'));

View
@forelse ($user as $u)

{{ $u->name }}

@endforeach

Na View precisaria colocar algum campo extra exemplo: ativo, mais não gostaria de mexer no banco de dados apenas colocar um campo e acessar no
{{ $u->ativo }}

Espero que tenha sido claro.

Para esclarecer melhor...
o user foi apenas um exemplo, ao invés de passar mais um objeto para View no Controller gostaria de mudar esse objeto e incluir itens nele, vamos dizer que passo um user e um post ao invés de fazer um novo foreach.
Em invés:
view('index', compact('user'),compact('post'));

gostaria
view('index', compact('user'));

Observação: user ou outro nome apenas exemplo.
Ao invés:
View

{{ $user->name }}

@forelse ($post as $u)

{{ $u->name }}

@endforeach

isso:
@forelse ($user as $u)

{{ $u->name }}

{{ $u->Postname }}

@endforeach

Espero que fique melhor a explicação.


text:
Q: Hello World jQuery DataTable example. Sort icons are a bit off I would imagine this could be easily reproduced in a few steps:
Using Visual Studio 2015, I created a new web project using the ASP.NET MVC template. I then installed jquery.datatables into my ASP.NET MVC project.
Install-Package jquery.datatables
1.10.11

And modified the generated index.cshtml in the Home view folder to see if I could get the Data Table to work.
@{
    ViewBag.Title = "Home Page";
}

            Col 1
            Col 1

            A
            2

            5
            4

            X
            7

            A
            2

            5
            4

            6
            7

            A
            2

            5
            4

            6
            7

            X
            7

            A
            2

            5
            4

            6
            7

            A
            2

            5
            4

            6
            7

@section scripts{

}

I added the needed css and js references to my master page
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <link href="~/Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
    <link href="~/Content/DataTables/css/dataTables.bootstrap.css" rel="stylesheet" />

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("About", "About", "Home")

@Html.ActionLink("Contact", "Contact", "Home")

                @Html.Partial("_LoginPartial")

        @RenderBody()

© @DateTime.Now.Year - My ASP.NET Application

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

The HTML table turns into a DataTable, but the sort icons look kind of weird. This is how they should look. I found this:

But instead mine look off:

I have this big semi transparent "down arrow with 3 lines to the right" next to the up down arrows that I expected.
I can't seem to make sense of the CSS.

A: What is happening here is that /3/dataTables.bootstrap.css (only v3) is adding extra ::content of type Glyphicons Halflings on top of the "native" arrows. This gives the effect with for example a black glyphicon-indent-left (I believe it is in unicode \e150) next to a blue indicator.
Personally I dislike it, it took some time to figure out (I am using angular) but cannot understand why it should be necessary to enrich the bootstrap styling with something completely new.
You can neutralize the extra icons by adding this CSS after your inclusion of dataTables.bootstrap.css :
table.dataTable thead .sorting_asc:after {
    content: "";
}
table.dataTable thead .sorting:after {
    content: "";
}
table.dataTable thead .sorting_desc:after {
    content: "";
}

Then the good old sorting icons appears, and only them.
You could also leave out dataTables.bootstrap.css completely (but not dataTables.bootstrap.js and bootstrap.min.css) I do that myself in some projects, and it does not really make that difference. Many of the tweaks in dataTables.bootstrap.css is what most people would already have in their CSS - like giving headers a pointer cursor, disabling bootstraps exaggarated margins and so on.


text:
Q: Не могу сделать ORDER BY перед GROUP BY Подскажите почему два запроса выдают разные результаты?
1-ый запрос:
SELECT date, text, topic_id
FROM forum_msgs
ORDER BY topic_id,date DESC

и 2-ой запрос:
SELECT *
FROM (SELECT date, text, topic_id
      FROM forum_msgs
      ORDER BY topic_id,date DESC
    ) t1

2-ой запрос выдаёт неотсортированную таблицу и поэтому запрос, который приведен ниже уже не имеет смысла.
SELECT *
FROM (SELECT date, text, topic_id
      FROM forum_msgs
      ORDER BY topic_id,date DESC
    ) t1
GROUP BY topic_id

A: Спасибо Mike - подсказал то что и было нужно. Итоговый запрос конечно немного сложнее, но основа легла на ура.
SELECT t1.parent_id, t1.id id,
                   t1.name,
                   t2.*
            FROM forum_dirs t1 LEFT JOIN (
                SELECT
                    forum_topics.title,
                    forum_topics.dir_id,
                    forum_topics.id topic_id,
                    forum_topics.date topic_date,
                    forum_topics.user_id topic_user_id,
                    users.logo topic_user_logo,
                    users.name topic_user_name,
                    users.login topic_user_login,
                    t3.*
                FROM forum_topics LEFT JOIN users ON users.id=forum_topics.user_id
                LEFT JOIN (
                    SELECT
                        forum_msgs.text,
                        forum_msgs.user_id msg_user_id,
                        forum_msgs.date msg_date,
                        forum_msgs.topic_id msg_topic_id,
                        users.logo msg_user_logo,
                        users.name msg_user_name,
                        users.login msg_user_login
                    FROM forum_msgs
                    LEFT JOIN users ON users.id=forum_msgs.user_id
                    WHERE (topic_id, date) IN (SELECT topic_id, max(date) FROM forum_msgs GROUP BY topic_id)
                ) t3 ON t3.msg_topic_id=forum_topics.id
                WHERE (dir_id, date) IN (SELECT dir_id, max(date) FROM forum_topics GROUP BY dir_id)
            ) t2 ON t2.dir_id=t1.id

A: Наверное потому, что во втором случае вы делаете выборку из выборки. выборка идет опять в том порядке, как удобно оптимизатору.
А почему не использовать group by в том же выражении, что и order by? Они вполне могут сосуществовать в одной выборке.


text:
Q: How to add a new element to a specific cell inside a table? <?php session_start() ;
include 'databaseConnection.php' ;
$sqlCommand3 = "SELECT * FROM posts ;" ;
        $result3 = mysqli_query($conn , $sqlCommand3);
        $resultCheck = mysqli_num_rows($result3);
        while ($row = mysqli_fetch_array($result3)) { ?>

    <?php echo $row['poster']; ?>

    <?php echo $row['post_destination']; ?>

    <?php echo $row['post_readyTime']; ?>

    <?php  echo $row['post_numberOfPassenger'];?>

    <?php echo $row['post_submitTime']; ?>

    <form action="riderJoin.php" method="post">
      <input type ="hidden" name ="id" value="<?php echo $row['post_id']; ?>" >
      <input type =submit  class="edit_btn"  name = submit value = "Join">

    </form>

<?php } ?>

How to add a new input (type = "submit" value="delete") with a new action (before the "join" button) whenever the $_POST['submit'] is set? I don't want to add a new input before each "join" button. Instead, I just want to add after a specific "join" button inside a cell when that specific "join" button is clicked. Also, if I click another 'join' button in other cell, a similar effect would happen too. So in the end, after clicking two "join" button, there should be only two delete button each added before the specific clicked "join" buttons. How to solve it ?
Thanks a lot :)


text:
Q: Rest API aggregate I'd like rest  API from left aggregate using MongoDB, but not show any information. I'm using nosqlbooster for try my schema and it's working, but don't get pass infomation using middleware, someone can help me, any information that can one direction me.
Follow code:
Model

 const userSchema = mongoose.Schema ({
      name: {
        type: String
      },
      email: {
        type: String,
        required: true
      },
      username: {
        type: String,
        required: true
      },
      course:[{type: Schema.Types.ObjectId, ref: 'course'}],
      password: {
        type: String,
        required: true
      }
    });

     const courseSchema = new Schema({
       title: { type: String },
       createdBy: { type: String },
      createdAt: { type: Date, default: Date.now() }
    });

Controller
router.get('/getCourseUsers', passport.authenticate('jwt', {session:false}), (req, res)=>{
  const user =  User.aggregate([
    {
      $lookup:
        {
          from: "courses",
          localField: "course",
          foreignField: "_id",
          as: "user"
        }
   },
   {
       $unwind: "$course"
   }

]).cursor({})
.exec((users) => {
  console.log('users', users);
}, (err) => {
  console.log('err', err);
});
})

I using nosqlbooster, the $lookup i got this information:
{
    "_id" : ObjectId("5b38e3bc9dbf9113560a2d4c"),
    "email" : "marcos@marcos.com.br",
    "username" : "marcos",
    "course" : ObjectId("59ef4fcf941e450ccc132f13"),
    "password" : "$2a$10$ZwtV9drpSEF7y8swFsTM3..DCT80AFMib0EAnJgFXhJmgUR5.tHH.",
    "__v" : 0,
    "user" : {
        "course" : [
            {
                "_id" : ObjectId("59ef4fcf941e450ccc132f13"),
                "title" : "Course Club ",
                "createdAt" : ISODate("2017-10-24T11:35:17.562-03:00"),
                "__v" : 0
            }
        ]
    }
}

A: Your .exec callback method is not structured correctly. The callback usually has 2 parameters
.exec((err, data) => {})

Your code should therefore look like this.
router.get('/getCourseUsers', passport.authenticate('jwt', {session:false}), (req, res)=>{
  const user =  User.aggregate([
    {
      $lookup:
        {
          from: "courses",
          localField: "course",
          foreignField: "_id",
          as: "user"
        }
   },
   {
       $unwind: "$course"
   }

]).exec((err, users) => {
    if (err) {
      console.log(err)
    }
    console.log('users', users);
  })
})

A: About cusors give erros for this don't working. I updated my mongoose and change some informations for this: .then(function (users ) { res.json(users); console.log('users', users[0]); })


text:
Q: XOR reversibility operation question I have heard somewhere that using XOR is not reversible (they spoke about encryption) but I do not understand how it was meant? AFAIK even with OR operation you cannot find out which of the two bits was 1. Please, could anyone who knows how it was meant explain it to me?
Thank you

A: I think you have probably misquoted them slightly.
They probably meant that using a one-time pad is unbreakable because unless you have a copy of the one time pad there is absolutely no information in the ciphertext that you can use to recover the plaintext. You cannot use statistical analysis or even a brute-force search because all inputs could give the output with equal probability and there's no way to know which input is the right one.
One-time pads are typically implemented using XOR, but the irreversibility is because it is a one time pad, not because of the XOR operation.

A: You probably mean "XOR encryption is unbreakable without the key"

If the key is random and is as long as
  the message (so it never repeats), the
  XOR cipher is more secure. With a
  keystream is generated by a
  pseudo-random number generator, the
  result is a stream cipher. With a key
  that is truly random, the result is a
  one-time pad, which is unbreakable
  even in theory.

A: They probably meant XOR is reversible, unlike either AND or OR. For encryption, this is interesting primarily with respect to Vernam ciphers -- ones where your cipher produces a key stream, which you XOR with the data stream. On the receiving end, you can XOR the encrypted stream with the same key stream, and get the plaintext back.
It's also interesting from a viewpoint of cryptanalysis. For example, if two streams were enciphered with the same key stream, XORing them with each other gives you the XOR of the two plaintext streams, with all effects of the key stream removed. At this point, you can use a "sliding window" technique: XOR something you think is likely to be in one message at various points with that stream, and if it's there, the result will be the intelligible text of the other message.

A: if you do
z = x XOR y
then
x = z XOR y
so yes its reversible


text:
Q: Remove div tags in HTML in C# My aim is to store the binary format of HTML code in an iframe. I want to convert the tab into HTML. In JavaScript I converted the div content into HTML and through a hidden field I am getting the HTML content.
In that page I have an ajax HTML editor so I am getting big empty space. I am trying to remove it using regex like:
Regex.Replace(htmlformat,"divID",'')

But it's removing only the id like div id=""style... So it removes the space but it's not in the HTML format. So iframe webservice is not able to convert it into pdf.
I want to remove the div content with its tags in HTML using C#.

A: You will also want to allow for other things before class in the div tag

]*class="footer"[^>]*>(.*?)

Also, go case-insensitive. You may need to escape things like the quotes, or the slash in the closing tag. What context are you doing this in?
Also note that HTML parsing with regular expressions can be very nasty, depending on the input. A good point is brought up in an answer below - suppose you have a structure like:

Hi!

Trying to build a regex for that is a recipe for disaster. Your best bet is to load the document into a DOM, and perform manipulations on that.
Pseudocode that should map closely to XML::DOM:
document = //load document
divs = document.getElementsByTagName("div");
for(div in divs) {
    if(div.getAttributes["class"] == "footer") {
        parent = div.getParent();
        for(child in div.getChildren()) {
            // filter attribute types?
            parent.insertBefore(div, child);
        }
        parent.removeChild(div);
    }
}


text:
Q: Function/dom calls in javascript library I'm trying to create a javascript library like jquery. I get how to create a normal library like so:
 var lib=lib||(function () {
       function privateFunction (alert ("hi");){};
       return {
          exampleAlert: function(input){
          alert(input);
       }
     }
    })();

Calling it like so:
lib.exampleAlert ("test");

This is like jquery
 $.ajax(stuffhere);

My question revolves around jquery. It can call the dom like $('.class').hide() and have functions like $.ajax(stuffhere); in the same library. How can I do dom calls and a regular function call like the ajax one in the above example library?
Thanks in advance!! Have searched more days than I would like to admit.

A: DOM has nothing to do here, it is just up to jQuery implementation.
If you ask about having both lib() and lib.func() calls, then you can do the following to support both function types at the same time:
var lib = function(sel) {
    return {
        object: document.querySelector(sel),
        text: function(val) {
           if (val === undefined) {
               return this.object.innerText;
           } else {
               this.object.innerText = val;
           }
        }
    };
};

lib.ajax = function() {
    console.log("AJAX imitation");
};

Now, you can do both:
lib("body").text("hi"); // jQuery-style setter
var text = lib("body").text(); // jQuery-style getter, returns "hi"

and
lib.ajax();

jQuery works exactly in the same way, but hundred times more complex.


text:
Q: Cannot get jQuery to recognize mouse hover over image I am trying to animate a picture when the mouse cursor hovers over it. I am using jQuery to accomplish this. I cannot figure out why it does not work for the current state of my code. Apologies in advance, I just started my endeavour into web development.
Thanks!
HTML
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="CSS/stylesheet_test.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="CSS/animate.css">
    <link href="https://fonts.googleapis.com/css?family=Work+Sans:500&subset=latin-ext" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">

    <title>Daryl N.</title>

HomeArchive

Hi, I'm Daryl

This is my personal website

jQuery
$(document).mousemove(function() {
    if($('#me-pic').is(':hover')
    {
        alert("Hello");
    }
});

UPDATE
The source of my problem came from setting the z-index of my image div to -1. Changing this solved my problem, as well as changing the script.

A: Well, I'm not sure if your method should work or not, but there's a better way to handle this, designed for the original purpose:
$(document).ready(function() {
  $('#me-pic').hover(function() {
    alert("Hello");
  });
});

A: With jQuery you can attach the hover event directly onto the selector, try this:
$(document).ready(function() {
    $('#me-pic').hover(function(){
        alert("Hello");
    })
});

A: The solution is to use hover jquery method.
$('#me-pic').hover(function(){
    alert("Hello");
})

View reference here.
Further more,I recommend you remove $(document).mousemove() event.In this situation, it is inefficient method.


text:
Q: Authentication between microservices in Kubernetes We have several microservices implemented in Java/Kotlin and Spring MVC, running in Tomcat docker images. These services provide public APIs which are authenticated by user's cookies/sessions. These work correctly.
Now, we would like to create an internal endpoint, which wouldn't be accessible either outside of GKE or via some kind of internal authentication.
What would be the good way to go especially for Spring MVC and GKE?
EDIT:
I would like to achieve to authenticate different endpoints on one service. For instance:

*

*/public/ - no auth

*/private/ - user must be logged in

*/internal/ - only other microservices can access

I would prefer to implement such auth on the application level, but I am not sure what would be the best way. IP range of internal Google IPs? Some other way of securely identifying the caller?
Maybe my idea is bad, if so, I will be happy to change my mind.

A: Your question isn't GKE specific. It's broadly a Kubernetes question.
I encourage you to search Kubernetes service authentication.
There are many ways to do this, including rolling your own auth model. One feature that can help here is Kubernetes NetworkPolicy resource (it's like firewalls), you can learn more about it here https://kubernetes.io/docs/concepts/services-networking/network-policies/ and see here for some examples: https://github.com/ahmetb/kubernetes-network-policy-recipes (Keep in mind that this is a firewall, not authentication.)
If you want to get this automatically, you can use Istio (https://istio.io) which allows you to automatically set up mutual TLS between all your services without any code changes. Istio also gives a strong identity to each workload. You can use Istio's authentication policies to set up auth between your microservices without changing your application code which is really cool: https://istio.io/docs/tasks/security/authn-policy/


text:
Q: Controls added by VSTO working without Add-In Suppose you have an Excel VSTO add-in that creates a control. Is there a way to make that control work in an instance of Excel that doesn't have the add-in?
Simplification of the problem: an add-in creates a button..
private void Sheet1_Startup(object sender, System.EventArgs e)
 {
    var button = this.Controls.AddButton(10, 10, 50, 50, "My Button");
    button.Text = "My Button";
    button.Click += new EventHandler(button_Click);
 }

 void button_Click(object sender, EventArgs e)
 {
    MessageBox.Show("I was clicked!");
 }

the document is then saved with that button and emailed to another user. When the other user opens the document and clicks that button, nothing happens.
How do you make the button work on everyone else's computer?

A: I develop on Word, not Excel, but as I see it, your options are:

*

*Create a document/template-level VSTO Add-In. Every workbook created based on a template (xltm) can have the same button, and it can call a macro or just run code. It's fairly straightforward, but your recipient would need to have the Add-In as well.

*Essentially the same as #1 but it's application-level, so it still has to be installed on your recipient's computers, but the button is always there, they don't have to make it themselves. You can conditionally show it, if you want it only in certain workbooks.

*Create a macro in a workbook, save it and remove the VSTO customizations from the workbook, and tell your recipients to run the macro. They can add a button to run it, on a custom ribbon tab, but you can't create the button automatically because changing the ribbon through code is not supported. It's also shared across all documents so it would show up in every excel document, depending on how it's created (you'd want to make it in the Excel equivalent of the Normal.dotm template). They can't make it only show up sometimes.

*This is pretty similar to #3 but the way the macro is delivered may make more sense to you. Word has a way to create a macro in a document and place it in the startup folder, and all documents opened by that user on that system would have the macro available. Excel has something similar, a personal workbook. You can probably find a way to provide this personal workbook to your recipients with your macro already in it. They would still need to create any ribbon buttons themselves.

It seems like you really don't want your users to have the Add-In, so #3 or #4 seem like the best options.


text:
Q: MS Graph C# .Net Create Calendar Event for user with RSVP enabled We are currently integrating Microsoft Graph api into a website to create calendar events generated from our system, where users can rsvp to the event.
We are currently using the Auth code flow for authorization for the users.
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
Where the frontend is a react app, and the backend is a .Net 4.8 C# project.
For our google solution, we create events for every integrated user individually and assign the organizer to be a service email account tied to our site. This allows the users to RSVP to it, and we can track what their status is based on their response. This also allows us to track and delete the individual events on a per user basis when necessary.
When searching and testing for a MS Graph solution, changing the organizer does not work based on the answer here.
Are the organizer and isOrganizer Attributes in MS-Graph event working?
As when the event is created, the individual that the event was created for is considered the organizer of the event. This is causing the RSVP to not show in outlook.
Is there a way to create an event for a user where the organizer is a generic email account (not an outlook account), while also keeping track of that event Id so we can track the RSVP status, and make any updates when necessary?


text:
Q: Tkinter: Calling function when button is pressed import tkinter as tk

def load(event):
    file = open(textField.GetValue())
    txt.SetValue(file.read())
    file.close()

def save(event):
    file = open(textField.GetValue(), 'w')
    file.write(txt.GetValue())
    file.close()

win = tk.Tk()
win.title('Text Editor')
win.geometry('500x500')

# create text field
textField = tk.Entry(win, width = 50)
textField.pack(fill = tk.NONE, side = tk.TOP)

# create button to open file
openBtn = tk.Button(win, text = 'Open', command = load())
openBtn.pack(expand = tk.FALSE, fill = tk.X, side = tk.TOP)

# create button to save file
saveBtn = tk.Button(win, text = 'Save', command = save())
saveBtn.pack(expand = tk.FALSE, fill = tk.X, side = tk.TOP)

I get the error that load and save are missing a position argument: event. I understand the error, but don't understand how to resolve it.

A: Here's a runnable answer. In addition to changing the commmand= keyword argument so it doesn't call the function when the tk.Buttons are created, I also removed the event argument from the corresponding function definitions since tkinter doesn't pass any arguments to widget command functions (and your function don't need it, anyway).
You seem to be confusing event handlers with widget command function handlers. The former do have an event argument passed to them when they're called, but the latter typically don't (unless you do additional stuff to make it happen—it's a fairly common thing to need/want to do and is sometimes referred to as theThe extra arguments trick).
import tkinter as tk

# added only to define required global variable "txt"
class Txt(object):
    def SetValue(data): pass
    def GetValue(): pass
txt = Txt()
####

def load():
    with open(textField.get()) as file:
        txt.SetValue(file.read())

def save():
    with open(textField.get(), 'w') as file:
        file.write(txt.GetValue())

win = tk.Tk()
win.title('Text Editor')
win.geometry('500x500')

# create text field
textField = tk.Entry(win, width=50)
textField.pack(fill=tk.NONE, side=tk.TOP)

# create button to open file
openBtn = tk.Button(win, text='Open', command=load)
openBtn.pack(expand=tk.FALSE, fill=tk.X, side=tk.TOP)

# create button to save file
saveBtn = tk.Button(win, text='Save', command=save)
saveBtn.pack(expand=tk.FALSE, fill=tk.X, side=tk.TOP)

win.mainloop()

A: Remove the 'event' arguments from both function defs and remove brackets from your commands.

A: Use button.bind() mehtod and pass 'Button-1' in first argument and function name in second argument
def functionname(event):
  #your code
button = tk.Button(win, text="Login", bg="green")#, command=attempt_log_in)
button.grid(row=5, column=2)
button.bind('<Button-1>', functionname)

A: You have functions save and load that takes 1 argument : event but when you called
# create button to open file
openBtn = tk.Button(win, text = 'Open', command = **load()**) <<<--- no argument in load
                                                       <<<---should be load(someEvent)
openBtn.pack(expand = tk.FALSE, fill = tk.X, side = tk.TOP)
# create button to save file
saveBtn = tk.Button(win, text = 'Save', command = **save()**)<<< ---- same for the save
saveBtn.pack(expand = tk.FALSE, fill = tk.X, side = tk.TOP)

But in your function save and load the argument : event you don't do nothing with it so you can just delete the event argument and this problem shouldn't appear. Like this :
def load():
    file = open(textField.GetValue())
    txt.SetValue(file.read())
    file.close()

def save():
    file = open(textField.GetValue(), 'w')
    file.write(txt.GetValue())
    file.close()


text:
Q: Drive API know when file is send to trash I'm trying to know when a certain file is sent to the drive trash. I've tried the following but nothing seems to work:
@POST
@Path("/webhook")
public void webhook(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
    Credential credential = initFlow().loadCredential("user");
    Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();

    String pageToken = GDrive.savedPageToken;
    Logger log = Logger.getLogger("thread");
    log.setLevel(Level.INFO);

    while (pageToken != null) {
        ChangeList changes = service.changes().list(pageToken).execute();

        for (Change change : changes.getChanges()) {

            if  ( change.getFile() == null ) {
                log.info("IGNORE: "+change.getFileId());

            }
            else if (!change.getFile().getMimeType().equalsIgnoreCase("application/vnd.google-apps.folder")) {
                log.info("TRASHED REMOVE DIGITAL INPUT: "+change.getFile().getTrashed());
                log.info("TRASHED REMOVE DIGITAL INPUT: "+change.getRemoved());
                log.info("TRASHED REMOVE DIGITAL INPUT: "+change.getFile().getExplicitlyTrashed());
                log.info("TRASHED REMOVE DIGITAL INPUT: "+change.getFile().getName());
            }
        }
        if (changes.getNewStartPageToken() != null) {
            GDrive.savedPageToken = changes.getNewStartPageToken();
        }
        pageToken = changes.getNextPageToken();
    }
    response.setStatus(200);
}

The first condicion change.getFile() == null is for when file is completely removed from drive.
On the second one I try to see when a file is send to trash, but these functions getTrashed(), getRemoved(), getExplicityTrashed() are always null or false.
How I could know when a file is removed?


text:
Q: Asterisk/TrixBox and Predictive Dialing/Outbound Call Center Is anyone out there running predictive dialers or Call Center type products on Asterisk/Trixbox.  I'm looking for vicidial type functionality.  The best way to characterize it would be political campaigning or marketing surveys.
Also, I really am just trolling for good or bad news either way on the product.
As I don't really have a problem per se, this might need to be marked Community Wiki.
Thanks for the help

A: We looked into this about 18 months ago. We ended up going with a different provider (not Asterisk) but from memory the choices were mostly fairly poor, especially for highly customised environments. And their interfaces were all clearly an afterthought designed by someone with only basic HTML skills.
In the end we went with a VoIP provider called Swyx, and then wrote our own predictive dialling code using their extensive and well documented ActiveX API (integrated it into the Do Not Call register, automatic callback requests when calls failed or went to answering machine, etc).

A: We use Vicidial for as much as 220 seats at a time with a multi-server Asterisk setup. It performs very well. We have in-house programmers that do the customization of the CRM, etc. for us so it's also very cost-effective.
You could contact a consultant from their webpage:
http://www.vicidial.com/


text:
Q: Combining arrays element wise to form an array of coordinates I am struggling to figure out this code.
Essentially, I want to create two arrays, N-1 by 1, of which contain random numbers between -2 and 2. I then want to combine these arrays element-wise, to form a new array of pairs of coordinates.
Here is the code I have so far, but I am not sure how to finish it (I am using numpy).
def x0x1Array(N):

    x0x1 = np.zeros([N-1, 1])
    x0 = np.zeros([N-1, 1])
    x1 = np.zeros([N-1, 1])

    x1 = np.zeros([1, N-1])

    for i in range(0, len(x0)):
        for j in range(0, len(x1)):
                x0[i] = np.random.uniform(-2,2)
                x1[j] = np.random.uniform(-2,2)

    x0x1 = np.array((x0,x1)).T

    print(x0x1)

Hope you guys can help!
O it worked, i just took a transpose!

A: There is a way to make this more efficient just by using the fact that np.random.uniform can generate entire arrays at a time, not just one element at a time:
x0x1 = np.random.uniform(-2, 2, size = (N,2))

You can then, if you need to, access each column with:
x0 = x0x1[:,0]
x1 = x0x1[:,1]