text:
Q: "View Document" Event for Document Library? I'm trying to capture the View document "event" of when a user clicks on a document in a document library and it opens up the document in Word or Excel...
There is not such an event receiver and using ItemUpdated or ItemUpdating wouldn't work since those are only triggered when a user edits the properties of that document.
I know there is an audit log which I can access via the object model to get the view count, but the idea is to have a "View Count" column in that document library that displays how many times that document has been viewed or opened. If i use the audit log's view count, I would have to implement some type of timer job that would periodically poll the log and update the "View Count" column.
How do I capture the event when a user opens a document in a document library?

A: As you've found, there is no such event. In my opinion you've described the best solution - a timer job that periodically queries the audit log and updates the "View Count" column.
Another option is to use an HTTP module to capture the request.


text:
Q: Testing Rx & TcpClient After quite some thought and rummaging around on the interwebs, I've come up with (what I think is) quite a nifty encapsulation of turning TcpIp into an Observable stream of data:
public static IObservable<string> CreateFromTcpIp(IPAddress ip, int port)
{
    return
        Observable.Using(
            () => new TcpClient(),                               //create client
            client => client.ConnectObservable(ip, port)         //connect async
                      .Select(_ => client.GetStream())            // get stream
                      .Select(stream => new BinaryReader(stream)) // get reader
                      .SelectMany(reader => reader.ToObservable()) // see below
                      .Retry()                                // if error, retry
            )
            .Publish().RefCount(); //only subscribe once for all subscribers
}

Where ConnectObservable is just client.ConnectAsync(host, port).ToObservable(), and reader.ToObservable looks like this:
private static IObservable<string> ToObservable(this BinaryReader source)
{
   return Observable.Create<string>(
       observer =>
       {
           return Observable.Generate(
               source,
               reader => true, //just keep on going
               reader => reader,
               reader => reader.ReadString())
           .Subscribe(observer);
       });
}

The problem I'm facing is how to go about testing this. I don't want to implement/wrap interfaces all the way down that call stack.
I've been trying to create a 'server' using TcpListener inside my test class, but am coming up against various (possibly unrelated) problems getting the subscribing and serving to co-exist (Subscribing to the the results of my CreateFromTcpIp never seems to return the IDisposable, inserting delays in my tests seem to end up locking the assembly so I can't rebuild).
Is there an alternative approach that I'm missing?
EDIT The problem of Subscribe not returning is related to doing a Retry on a faulting Observable. I've asked another question here.

A: I suppose you could test the BinaryReader ToObservable like this (if you make it accessible). The fact that this expects an exception possibly highlights some issues, although I wrote it to pass the code as written (uses nunit):
[Test]
public void TestStreamToObservable()
{

    var expectedText = new List<string>
    {
        "A good test is simple.",
        "A rolling stone gathers no moss.",
        "Test properly"
    };

    var stream = new MemoryStream();
    var writer = new BinaryWriter(stream);
    expectedText.ForEach(writer.Write);
    writer.Flush();

    stream.Seek(0, SeekOrigin.Begin);
    var reader = new BinaryReader(stream);

    var resultText = new List<string>();

    Assert.Throws<EndOfStreamException>(
        () => reader.ToObservable().Subscribe(resultText.Add));

    CollectionAssert.AreEquivalent(expectedText, resultText);
}

As for the rest, you've kind of scuppered yourself for anything but integration testing by creating a new TcpClient(). A new of anything concrete like that will always spell trouble for testing. You could refactor and pull the Retry().Publish().RefCount() out into a separate method that operates on IObservable<string>. Then leave the TcpClient bits to integration testing only.

A: OK, for posterity, here are some of the things I've learnt while working through this problem.
 Mostly it's about the subtleties of using Rx:

*

*If you don't observe OnError, it will throw as an exception.

*On top of that, if you've done a ToObservable on a Task and you don't observe OnError, it will only throw when you unsubscribe

*Also, there's no point doing a Retry downstream from a Task: once it's thrown an exception, that's the Result, and it won't try again (too me a while to work that out!).

*In the case where my subscription was never returning, I needed to SubscribeOn a different thread (Scheduler.Default).

*Another bug was hinted at in James' answer: the ToObservable on the BinaryReader throws an exception. What is important here is that it is an Exception, not an OnError. So there's no Retry possible.

(Little code snippet to prove this to ourselves):
Observable.Generate(0, i => i < 4, i => i + 1,
                    i => { if(i > 2) throw new Exception("sorry"); return i; })
          .Subscribe(i => Console.WriteLine(i),
                     ex => Console.WriteLine(ex.Message));

Given this, I've recoded my ToObservable to use this (not so pretty):
return Observable.Create<string>(obs =>
{
    var subscribed = true;
    var errored = false;
    string result = String.Empty;
    while(subscribed && !errored)
    {
        try
        {
            result = source.ReadString();
        }
        catch(Exception ex)
        {
            errored = true;
            obs.OnError(ex);
        }
        obs.OnNext(result);
    }
    return Disposable.Create(() => subscribed = false);
});

*

*For further development, I wanted a Retry that was slightly less aggressive. This led me to this excellent answer. (It seems that not matter what I manage to write in Rx, there is always a more elegant way to do it)

*James' Spy extension method was very helpful. Thoroughly recommended.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it any reason why 'map' in jQuery works differently as static and instance method? I'm learning jQuery right now and was surprised that map method has different order for same parameters in callback if it's called on jQuery object or on generic iterable. If i call map on jQuery object, callback will be passed object index first and object value second:
$( 'div:lt(5)' ).map( function( i, j ) { console.log( index, object ); } );

But if i call map for a list or dict, callback arguments are reversed! Object goes first and index second:
$.map( [ 'a', 'b', 'c' ], function( i, j ) { console.log( object, index ); } );

Is it any architectural reason for such inconsistency, or just a random hacking and no one cares?

A: The jQuery.map() function was available in version 1.0, whereas the .map() function was added in jQuery 1.2. I assume one order was chosen for jQuery.map() (value, index), and then when .map() was added in jQuery 1.2 it was made consistent with .each() - and other similar functions - which which was available in 1.0 and used the (index, value) order.
This is purely speculation, though, and there may not have been any decision behind it at all. It also doesn't begin to address why jQuery.map() isn't consistent with jQuery.each(), which uses the same order (index,value) as its instance-based equivalent, and was also available in version 1.0.

A: I like @AnthonyGrists's answer but here's another angle.
I agree the different order of arguments is confusing but there is a kind of logic.

*

*With jQueryCollection.map(), you are more likely to want to specify the index as a solo argument because this is available as a reference to the collection element.

*With jQuery.map(), on the other hand, this refers to the global namespace so you are (kind of) more likely to want to specify the element as a solo argument than the index.
Unfortunately, the question now becomes, why do the two methods not use this in the same way? And maybe that's as big a question as the one we're trying to answer.
Totally rational - no. Underlying rationality - possibly.


text:
Q: object that contains 2dimensional double array-user input I am fairly new to java and I have a problem with following program:
 import java.util.Scanner;

public class Matrix2D {

private double[][] matrix;
private int dimX;
private int dimY;

public Matrix2D(int row , int col ){
    Scanner scanner=new Scanner(System.in);
    dimX=col;
    dimY=row;
    matrix=new double[row][col];
    int i ,j;
    for( i=0;i<matrix[row].length;i++)
    {
        for( j=0;j<matrix[col].length;j++)
        {
            System.out.println("Please enter double at position"+" "+ row +" "+ col);
            double input=scanner.nextDouble();
            matrix[row][col]=input;  }
    }

}

public static void main(String[] args) {
    Matrix2D test=new Matrix2D(3 ,3 );

}

}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Matrix2D.<init>(Matrix2D.java:17)
    at Matrix2D.main(Matrix2D.java:31)

The program lets me give the first user input , but immediately after it throws the exception above.
Any help would be much appreciated.

A: You got the indices of your loops mixed up. martix has row rows, with indices 0 to row-1, so matrix[row] is out of bounds.
It should be :
matrix=new double[row][col];
for(int i=0;i<row;i++) {
    for(int j=0;j<col;j++) {
        System.out.println("Please enter double at position"+" "+ i +" "+ j);
        double input=scanner.nextDouble();
        matrix[i][j]=input;
    }
}

or
matrix=new double[row][col];
for(int i=0;i<matrix.length;i++) {
    for(int j=0;j<matrix[i].length;j++) {
        System.out.println("Please enter double at position"+" "+ i +" "+ j);
        double input=scanner.nextDouble();
        matrix[i][j]=input;
    }
}


text:
Q: Redux props are being received in Redux DevTools but not in the React component I am passing down a Redux prop to a component that is sourced from a fetch payload. The payload successfully changes state in my reducer and according to my Redux DevTools the component that I am trying to pass the state down to as a prop successfully receives the prop (an array of objects that is fetched in the action) yet when I console.log the prop or try to do anything with it it shows up as an empty array.
My index reducer:
export default combineReducers({
  cart: cartitemReducer,
  products: productReducer,
})

The fetch action:
export const fetchCart = () => dispatch => {
  fetch('http://localhost:3000/api/v1/cartitems/')
    .then(res => res.json())
    .then(cartjson =>
      dispatch({
        type: 'FETCH_CART',
        payload: cartjson
    }))
}

The reducer:
const initialState = {
  userCart: [],
  cartItem: {}
}

export default function(state = initialState, action) {
  switch(action.type) {
    case FETCH_CART:
      return {
        ...state,
        userCart: action.payload
      };

mapping state to props:
const mapStateToProps = state => ({
  cart: state.cart.userCart
})

When I console.log(this.props.cart) it returns an empty array. Yet my DevTools correctly show the contents of the array under cart.userCart

A: It all depends on where you are console.log()-ing. If you run that in componentDidMount(), then you would just get an empty-array because console.log() runs before you complete the fetch-request and update your reducers. componentDidMount() will not trigger again.
However, your code looks to be set-up correctly. You should be able to print your results in componentDidUpdate(), which is triggered anytime you get updated props or state.
componentDidUpdate(prevProps){
  if(prevProps.cart.length !== this.props.cart.length){
    console.log(this.props.cart)
 }
}


text:
Q: Word meaning not knowing when to stop Is there a word that means "not knowing when to stop"? I haven't been able to think of one as of yet.

A: It does rather depend on context. Reckless will often fit, but so might unrestrained, undisciplined, careless, and several others.
Personally I think the best "single-word" answer is intemperate - having or showing a lack of self-control; immoderate. It's particularly associated with not knowing when to stop drinking alcohol, but that doesn't prevent its use in other contexts.
Note that temper has many meanings; in "intemperate" it's the verb to moderate, or tone down.

A: Depending on context, you may use unrestrained or unbridled.

A: Incessant.
continuing without interruption; ceaseless; unending

A: Compulsive might do what you want.

A: Some possibilities: blithe, sense 2, "Indifferent, careless, showing a lack of concern";
uncurbed, "Unlimited; unrestricted"; gung ho, "Very enthusiastic or energetic"; high-handed, "Using power or authority without proper consideration for the feelings or rights of others"; and perhaps manic, speed demon, overboard, over the top, heavy-handed, lead-footed, roughshod, heedless.
Some facetious suggestions: unbrakeable; brakeless; brake-challenged.


text:
Q: Fitting a distribution to match known points on the CDF I've recently run into a situation where I know a few probability points in the tail of a distribution and I want to "fit" a distribution that goes through these points in the tail. I realize this is messy and not overly accurate, and plagued with conceptual issues. However, trust me that I really want to do this.
So effectively I know some points in the tail of the CDF with x being the values and y being the probability of that value or smaller. Here's R code to illustrate my data:
x <- c(0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85)
y <- c(0.0666666666666667, 0.0625, 0.0659340659340659, 0.0563106796116505,
       0.0305676855895196, 0.0436953807740325, 0.0267459138187221)

Then I create a function to minimize error between my data and a beta distribution CDF using pbeta. I use SSE as a fit metric then minimize that with -sum. I throw in an initial guess as the first param to optim of (9, .8) although I've tried this with different guesses and I always get the same result. The starting point guess I use comes from manually cooking up parameters by hand that seem close.
# function to optomize with optim
beta_func <- function(par, x) -sum( (pbeta( x, par[1], par[2]) - y)**2 )
out <- optim(c(9,.8), beta_func, lower=c(1,.5), upper=c(200,200), method="L-BFGS-B", x=x)

out <- out$par
print(out)
#> [1]  0.90000 23.40294

Below I graph the 'optimized' beta distribution in red, my actual data in blue, and a hand tweaked starting guess of the beta parameters in black.
plot(function(x) pbeta(x, shape1=out[1], shape2=out[2] ), 0, 1.5, col='red')
plot(function(x) pbeta(x, 9,.8), 0, 1.5, col='black', add=TRUE)
lines(x,y, col='blue')

I can't grok what's going on with optim to give a solution that's worse than my starting guess. I calculated the SSE for my starting guess vs the optim solution and it looks like my guess has a much larger -SSE:
# my guess
-sum( (pbeta( x, 9, .8) - y)**2)
#> [1] -0.03493344

# optim's output
-sum( (pbeta( x, .9, 23) - y)**2)
#> [1] -6.314587

Using past history as my Bayesian prior, my guess is that I'm misunderstanding optim or feeding it improper inputs. However, I can't grok what's going on. Any tips would be greatly appreciated.
I've tried using the CG optimization method, but the results are not meaningfully different and still don't seem near as good as my starting guess.
out <- optim(c(9,.8), beta_func, method="CG", x=x)
out <- out$par
print(out)
#> [1]  2.287611 11.124736

A: I think you are accidentally trying to maximize the squared errors.  The default for optim() is to minimize the function, so the negative sign in your beta_func() results in searching for a max.
If you modify your function like so you get values closer to your guess:
beta_func2 <- function(par, x) sum( (pbeta( x, par[1], par[2]) - y)**2 )
out2 <- optim(c(9,.8), beta_func2, lower=c(1,.5), upper=c(200,200), method="L-BFGS-B", x=x)
out2 <- out2$par
print(out2)
[1] 11.04296  0.50000

You can check the new function against your observations (where out, x, and y are defined as in your example):
plot(x,(pbeta(x,out[1],out[2])), ylim=c(-.1,1), col="red", type="l")
points(x, (pbeta(x,9,0.8)), col="black", type="l")
points(x,(pbeta(x,out2[1],out2[2])), col="orange", type="l")
lines(x,y, col='blue')
title(main="Blue observed CDF, black guesstimate, gold optimized")


text:
Q: Error socket: Error: bind EADDRINUSE 0.0.0.0:2361 in NODEJS I have a problem with the node server.
When I try to establish a WebRTC connection with the browser I get this error:
Error socket: Error: bind EADDRINUSE 0.0.0.0:2361
Error socket: Error: bind EADDRINUSE 0.0.0.0:1236
node:events:381
throw err; // Unhandled 'error' event
^
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({
ts: 1636713359395,
pid: 2560,
level: 'error',
msg: [ 'Error socket: Error: bind EADDRINUSE 0.0.0.0:2361' ]
})
at new NodeError (node:internal/errors:371:5)
at process.emit (node:events:379:17)
at /opt/WebAppCOM4/node_modules/simple-node-logger/lib/Logger.js:46:25
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
code: 'ERR_UNHANDLED_ERROR',
context: {
ts: 1636713359395,
pid: 2560,
level: 'error',
msg: [ 'Error socket: Error: bind EADDRINUSE 0.0.0.0:2361' ]
}
}
Do you have any ideas to solve this problem?
Thanks for the replies.
Michele


text:
Q: Is there a way to simulate gestures for non-touchscreen users? How are users able to actually use features such as pinching if they don't have touchscreen monitors?
I ask this because:

*

*I plan to use Windows 8 on my desktop, and I want to get the full use of any applications I download.

*I want to ensure that if I ever release any application I develop to the windows store that there is a way for my users to get around this situation (no touchscreen for multitouch events).

A:
How are users able to actually use features such as pinching if they don't have touchscreen monitors?

There are keyboard and mouse equivalents for most of the features, they've kept in mind that the applications need to be able to be navigated using keyboard and mouse as well. For instance, you can use mouse scrolling to replicate the pinching (to zoom).
These are documented in the Help and Support which is in the charm at the right side as well as when you press F1. I can't remember the category but it wasn't hard to reach; however, they're quite trivial.

I plan to use Windows 8 on my desktop, and I want to get the full use of any applications I download.

Yes, you will be possible to make full use of most of them, the only feature that lacks on a mouse is rotation but that shouldn't really matter as professional applications will probably include an on-screen control allowing you to rotate.

I want to ensure that if I ever release any application I develop to the windows store that there is a way for my users to get around this situation (no touchscreen for multitouch events).

By default both work in an equivalent way, you can however assign specific actions to specific events, although it would be stupid for an app developer to ignore a part of the users and explicitly make them behave different.

Have used quite some Metro apps when I tried myself and I never found an occasion that I was lacking functionality, so this will most likely rarely be a problem. And if it is, you can probably raise it to the developer that went wrong which might be happy to fix it.

A: Windows 8 Simulator lets you simulate touch. This is not a perfect alternative but if you just want to test an app or check some functionality while you're building your own app, the Simulator could be adequate.

A: Logitech Touchpad
Above looks like a good start to what you are after. It will allow you to simulate gestures and will be a fully functional mouse.

A: You can try and develop Mouse based gestures for non touch screen based devices. For Visually challenged people you can help them with Keyboard gestures(Multi-key combination based) would do better.


text:
Q: Upgrade shared data source from data source of Report Builder (DataSourceReference) I have old report built by Report Builder 18 years ago that needs to be migrated to a new Report Server Project.
I donwloaded MineDataSource.rsds (not rds) deployed by third party choco from server side.
    <?xml version="1.0" encoding="UTF-8"?>
    <DataSourceDefinition>
     <Extension>ODBC</Extension>
     <ConnectString>Dsn=mydsnsdsn=SQLEngine_Kerberos;hst=myhs;prt=19990</ConnectString>
     <UseOriginalConnectString>False</UseOriginalConnectString>
     <OriginalConnectStringExpressionBased>False</OriginalConnectStringExpressionBased>
     <CredentialRetrieval>Integrated</CredentialRetrieval>
     <Enabled>True</Enabled>
    </DataSourceDefinition>

I don't want to change the shared data sources from reporting server since it may impact deployment process (from third party)+ domain account of SQLEngine_Kerberos security (set by third party).
I tried,

*

*Add Existing data source by http://localhost//DataSources/MineDataSource.rsds, but could not find it.

*merge following xml config to new .rds but not working either

    <DataSources>
    <DataSource Name="MineDataSource">
      <DataSourceReference>/DataSources/MineDataSource</DataSourceReference>
      <rd:SecurityType>None</rd:SecurityType>
      <rd:DataSourceID>3f352f12-279a-4b49-9083-1e7279bdce3e</rd:DataSourceID>
    </DataSource>
    </DataSources>

To
    <RptDataSource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="MineDataSource">
      <DataSourceReference>http://localhost/<ReportServer>/MineDataSource.rsds</DataSourceReference>
      <!--<DataSourceReference>/DataSources/MineDataSource</DataSourceReference>-->
      <SecurityType>None</SecurityType>
      <DataSourceID>d72617f8-1c7f-43d3-b9de-7dfc57d7afd6</DataSourceID>
    </RptDataSource>

Anything that I could try? or you have right rds file to handle DataSourceReference?
Thanks a lot


text:
Q: Can't center vertically a div on grid using bootstrap How Can I center vertically the card to the other right div content?

this is my code:
le="margin-bottom:100px">

I Agree With the terms and service
Request Code

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

Testing

Your Answer

        <textarea rows="10" placeholder="Description" class="form-control" id="upload-editor"></textarea >

        I Agree With the terms and service   <input type="checkbox" id="TOS" name="scales">
        <button style="float:right" onclick="upload()"  class="btn btn-primary mb-2">Request Code</button>

Card title

Card subtitle

Some quick example text to build on the card title and make up the bulk of the card's content.

        Card link
        Another link

A: I would first remove the margin-bottom: 100px; and then add the class  align-self-center to each div I have in the row. By doing that you can make sure your divs are always centered even if you add padding-top or bottom or margin to the div with the class col-lg.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">

Testing

Your Answer

          <textarea rows="10" placeholder="Description" class="form-control" id="upload-editor"></textarea>

          I Agree With the terms and service <input
                                type="checkbox" id="TOS" name="scales">
          <button style="float:right" onclick="upload()" class="btn btn-primary mb-2">Request
                            Code</button>

Card title

Card subtitle

Some quick example text to build on the card title and make up the bulk of the card's content.

          Card link
          Another link

If that doesn't help please let me know.

A:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

Testing

Your Answer

        <textarea rows="10" placeholder="Description" class="form-control" id="upload-editor"></textarea >

        I Agree With the terms and service   <input type="checkbox" id="TOS" name="scales">
        <button style="float:right" onclick="upload()"  class="btn btn-primary mb-2">Request Code</button>

Card title

Card subtitle

Some quick example text to build on the card title and make up the bulk of the card's content.

        Card link
        Another link


text:
Q: FluentNHibernate Many-To-One References where Foreign Key is not to Primary Key and column names are different I've been sitting here for an hour trying to figure this out...
I've got 2 tables (abbreviated):
CREATE TABLE TRUST
(
TRUSTID NUMBER NOT NULL,
ACCTNBR VARCHAR(25) NOT NULL
)
CONSTRAINT TRUST_PK PRIMARY KEY (TRUSTID)

CREATE TABLE ACCOUNTHISTORY
(
ID NUMBER NOT NULL,
ACCOUNTNUMBER VARCHAR(25) NOT NULL,
TRANSAMT NUMBER(38,2) NOT NULL
POSTINGDATE DATE NOT NULL
)
CONSTRAINT ACCOUNTHISTORY_PK PRIMARY KEY (ID)

I have 2 classes that essentially mirror these:
public class Trust
{
    public virtual int Id {get; set;}
    public virtual string AccountNumber { get; set; }

}

public class AccountHistory
{
    public virtual int Id { get; set; }
    public virtual Trust Trust {get; set;}
    public virtual DateTime PostingDate { get; set; }
    public virtual decimal IncomeAmount { get; set; }

}
How do I do the many-to-one mapping in FluentNHibernate to get the AccountHistory to have a Trust?  Specifically, since it is related on a different column than the Trust primary key of TRUSTID and the column it is referencing is also named differently (ACCTNBR vs. ACCOUNTNUMBER)????  Here's what I have so far - how do I do the References on the AccountHistoryMap to Trust???
public class TrustMap : ClassMap<Trust>
{
    public TrustMap()
    {
        Table("TRUST");
        Id(x => x.Id).Column("TRUSTID");
        Map(x => x.AccountNumber).Column("ACCTNBR");
    }
}

public class AccountHistoryMap : ClassMap<AccountHistory>
{
    public AccountHistoryMap()
    {
        Table("TRUSTACCTGHISTORY");
        Id (x=>x.Id).Column("ID");
        References<Trust>(x => x.Trust).Column("ACCOUNTNUMBER").ForeignKey("ACCTNBR").Fetch.Join();
        Map(x => x.PostingDate).Column("POSTINGDATE");
        );

I've tried a few different variations of the above line but can't get anything to work - it pulls back AccountHistory data and a proxy for the Trust; however it says no Trust row with given identifier.
This has to be something simple.  Anyone?
Thanks in advance.

A: You need to use property-ref:
public class AccountHistoryMap : ClassMap<AccountHistory>
{
    public AccountHistoryMap()
    {
        Table("TRUSTACCTGHISTORY");
        Id (x=>x.Id).Column("ID");
        References(x => x.Trust, "ACCOUNTNUMBER").PropertyRef("ACCTNBR").Fetch.Join();
        Map(x => x.PostingDate).Column("POSTINGDATE");
    }
}


text:
Q: Ways to handle losing track of which user ID requests a password reset after POSTing I'm writing a password reset page.
Logic:

*

*User requests pw

*It's sent to their email with a unique string (that expires) appended to the /reset/$string

*Once at the page in my controller I check if the string matches one in the db, if so then I match that to the userId

*If it does, I allow them to enter their new pass

*If they POST to the same controller and mess up and enter 2 incorrect passwords, I lose the original URL with the reset string
so now I don't know which user to update in the db

My options (that I can think of):

*

*Set the string and user ID in a session and look that up in the controller (and make sure to clear this out once the pass is successfully reset)

*On step 4 above, I'll add in the user's ID in a hidden input field in the form and POST with that to check which user it is

A: I would do this:

*

*The user provides his email in a form and requests password reset.

*You check the db for the uid (user id) that matches the email.

*If the user exists you make a url like this:
http://domain.com/password_reset.php?uid=xxxx&key=fdhgf5115d4f15dfdb5fdf5

*The key is generated by the this: $key = md5(uniqid())

*You store the key into a session with the uid:
$_SESSION['pass_res']['key'] = $key;
$_SESSION['pass_res']['uid'] = $uid;

*When user click on the url you check if:
$_SESSION['pass_res']['uid'] == $_GET['uid'] and if
$_SESSION['pass_res']['key'] == $_GET['key']

*If they match you allow the user to change his password

*And after this unset($_SESSION['pass_res'])

*Also if a user close his browser the session expires

By this way only the user with the session id that requested password reset can change his password

A: Your solution in option 2 (add token to a hidden input) makes sense or you could just post the form to the same URL (the one with the token in it so you don't lose it) and structure your logic to work based on whether or not the form was posted.
The logic could look like this:

*

*User hits site.com/password/reset/token_here as GET or POST

*Check token from URL in database to see if its valid and current

*If request method is POST, check for matching, secure passwords

*

*If passwords do not match, assign error message to HTML view

*If passwords match, change password, delete token, redirect to success page

*Display form to user - form posts back to same URL w/ the token


text:
Q: U-SQL Schema Discovery The Data Lake approach (according to slide 5 here) is:

*

*Ingest all data - regardless of requirements

*Store all data - in native format without schema definition

*Do analysis - using engines like Hadoop

But let's say we have loaded up many many datasets to our data lake, how do I go about schema discovery in an automated and scalable manner?  Does U-SQL support dynamic schema discovery or what would be a good way to go about it using ADLA or other toolset?

A: This is a good question but the answer somewhat depends on the schema you want to discover.
Let me explain:
If you have CSV type data, there are tools, including the latest version of the ADL Tools for VisualStudio that will try to detect your schema from the provided data (the tools actually will generate the EXTRACT statement for you).
Some interactive languages may also give you extractors that try to infer the schema as part of the query. We do not support this in U-SQL at the moment, because you do not want to have a batch job infer the schema wrongly and fail after spending possibly a lot of money to run the job. In an interactive setting, it is less costly and can be easily corrected/overwritten by the query author.
If you have however data such as images or text documents and even nested, semistructured documents like JSON or XML, often the schema that you want has to be provided. E.g., if you have a JPEG file, do you want the EXIF properties? If so which ones? Or some feature extraction? Or some color analysis? etc.
So I think one thing that is important when designing a data lake is to have some semantically meaningful organization of the native-format data into folder structures and either use Views/TVFs to provide the schematized view(s) in the meta data service to make them more easily discoverable, or use a service like Azure Data Catalog to describe the data.
If you have already data inside the lake's storage and you want to discover it, right now you would have to build some form of discovery with U-SQL and the SDKs or some tooling that goes against the WebHDFS APIs of the store.


text:
Q: DOM. Why the class won't remove after I click on again I tried to style some element by click on them by giving them a class. Only one that I click on will have the style. But if I click the element twice, the class won't remove. I use toggle, but still does not work

const lists = document.querySelectorAll('.list');
lists.forEach(list => {
  list.addEventListener('click', () => {

    // remove the previous class active
    lists.forEach(list => list.classList.remove("active"))
    list.classList.toggle('active');

  });
});
.list.active {
  color: crimson;
}

Lorem ipsum dolor sit.

Lorem ipsum dolor sit.

Lorem ipsum dolor sit.

Lorem ipsum dolor sit.

A: *

*your .classList.remove()  doesn't specify any class to remove.
Change to .classList.remove('active')

*list.classList.toggle('active'); will never toggle active class.  It will be the same as list.classList.add('active');
If you really want to toggle  active class  do

document.querySelectorAll('#list > li').forEach( (list_el,_,all) =>
  {
  list_el.onclick =_=>
    {
    if ( list_el.classList.toggle('active') )
      all.forEach( li => li.classList.toggle('active', list_el===li ))
    }
  })
#list > li {
  cursor : pointer;
  }
.active {
  color: crimson;
  }

Lorem ipsum dolor sit.

Lorem ipsum dolor sit.

Lorem ipsum dolor sit.

Lorem ipsum dolor sit.

A: lists.forEach(list => list.classList.remove("active"))
you don't need this part as toggle('active') will remove the class when you click twice

const lists = document.querySelectorAll('.list');
lists.forEach(list => {
  list.addEventListener('click', () => {

    // remove the previous class active

    list.classList.toggle('active');

  });
});
.list.active {
  color: crimson;
}

Lorem ipsum dolor sit.

Lorem ipsum dolor sit.

Lorem ipsum dolor sit.

Lorem ipsum dolor sit.


text:
Q: AJAX form script isn't executed I want to use a form via AJAX, so I got this Code Snippet from another post on stackoverflow. It didn't work, so I added an alert to check, if the script is even executed. That doesn't seem to be the case and I'm wondering why.
<head>
    <script src='jquery.js'></script>
    <script>
    var request;

    $("#foo").submit(function(event){

        alert("Hallu");

        if (request) {
            request.abort();
        }

        var $form = $(this);

        var $inputs = $form.find("input, textarea");

        var serializedData = $form.serialize();

        $inputs.prop("disabled", true);

        request = $.ajax({
            url: "/action.php",
            type: "post",
            data: serializedData
        });

        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it worked!");
        });

        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );
        });

        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        event.preventDefault();
    });

   </script>
</head>
<body>
    <form id="foo">
        <input type="text" id="name" name="name" />
        <textarea id="msg" name="msg"></textarea>
        <input type="submit" value="Senden" />
    </form>
</body>

A: When the script runs, #foo does not exist, so there is nothing to bind the event hander to.
Move the script so it appears after the form, or convert it to a function and bind it as a ready or load event handler.

A: The reason is very simple. You do something to $('#foo') before it has been loaded. At this point of time JS does not know anything about an object with id="foo", because it is not loaded yet.
Wrap the whole code in $(document).ready(function() { ... });.
This should look like this:
var request;

$(document).ready(function() {

    $("#foo").submit(function(event){

        alert("Hallu");

        if (request) {
            request.abort();
        }

        var $form = $(this);

        var $inputs = $form.find("input, textarea");

        var serializedData = $form.serialize();

        $inputs.prop("disabled", true);

        request = $.ajax({
            url: "/action.php",
            type: "post",
            data: serializedData
        });

        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it worked!");
        });

        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );
        });

        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        event.preventDefault();
    });
});

Please consider using a good IDE, like NetBeans or Eclipse. It helps you to detect unclosed brackets and other stuff.


text:
Q: "There is no something" vs "no something" Is it correct in English to write:

No water
No apple
No dog

when there is no water/apple/dog?
Is there any rule when only one form is valid:

There is no water

vs

No water

Let's say I create a table and in one cell I want to write that there is no water in the pump:

Col1
Col2

11
red

12
blue

13
no water in the pump

In such context - is it correct just to say "no water in the pump"? Or do I have change it to "There is no water in the pump"?

A: If you are writing a narrative, you should normally use complete sentences. "There is no water in the pump." If you are putting labels on something or making entries in a table, it is not necessary to use full sentences, and "no water" or "no water in pump" is fine.


text:
Q: How to modify template params via database in joomla I want to modify the current template params via database outside joomla framework. I managed to set the 'preset' param, but I can't write it back to the database. Here is my code.
Thanks a lot
// Initialize The Joomla Framework
// -----------------------------------------------------------------------------------
define('_JEXEC', 1);

// this is relative to the current script, so change this according to your environment
define('JPATH_BASE', '/home/kristof/public_html/joomla1');
define('DS', DIRECTORY_SEPARATOR);

// Require Joomla libraries
require_once(JPATH_BASE . DS . 'includes' . DS . 'defines.php');
require_once(JPATH_BASE . DS . 'includes' . DS . 'framework.php');
require_once(JPATH_CONFIGURATION . DS . 'configuration.php');
require_once(JPATH_LIBRARIES . DS . 'joomla' . DS . 'database' . DS . 'database.php');
require_once(JPATH_LIBRARIES . DS . 'import.php');
// -----------------------------------------------------------------------------------

$app = JFactory::getApplication('site');
$template = $app->getTemplate(true);
$param=$template->params->set('preset','preset3');

A: $template = JFactory::getApplication('site')->getTemplate();
    $db = JFactory::getDBO();
    $sql = "select params from #__template_styles where template = ".$db->quote($template);
    $db->setQuery($sql);
    $params = json_decode($db->loadResult());
    $params->PARAM_NAME= PARAM_VALUE;

    $sql = "update #__template_styles set params = ".$db->quote(json_encode($params))." where template = ".$db->quote($template);
    $db->setQuery($sql);
    return $db->query();


text:
Q: mysql check for records who have not posted since a while i have a table where i am trying to locate the users who are still idle and have not done any work since the last post they did, my table structure is below code
need to account for users who have gone the longest without a post invite
i tried using the date functionality but could not figure out how longest and what date
functions are needed to take this account.
but the catch is there are bunch of date fields and every column gets updated at some point, so i want to compare that the user has not been active or doing anything in last 60 dates considering all date fields
here is my code of mysql
SELECT
    tblcontact_desc.ContactID,
    COUNT(tblpost.PostID) AS NoPosts,
    tblpost.PostStatus_UpdatedDateTime,
    DATEDIFF(CURDATE(), (SELECT PostStatus_UpdatedDateTime FROM tblpost ORDER BY PostStatus_UpdatedDateTime DESC limit 1))
  FROM
    tblpost
    INNER JOIN tblcontact_desc ON (tblpost.ContactdescID = tblcontact_desc.ContactdescID)
        GROUP BY
    tblcontact_desc.ContactID
  ORDER BY NoPosts  DESC

but that seems to be bringing wrong results and showing nouser

A: try this, i think it should work
ill just help you with the logic
if you are checking from the column PostDate, And suppose table name is PostTbl
SELECT DATEDIFF(CURDATE(), (SELECT PostDate FROM PostTbl ORDER BY PostDate DESC limit 1));

If DATEDIFF is more than 60, you got your user,


text:
Q: Appending a Textarea not included in Form POST Is there a possible case where appending a textarea on page load won't be included inside the form post? however, hardcoding it in PHP works fine?
I would post the whole code, but I'm using PyroCMS fieldTypes and I'm not sure if many know it.
Here's the JS code:
$(function() {
      $(".list_field").append('
<textarea name="work_and_education[3]" class="item_input" placeholder="List item content..."></textarea>
+

-

');
});

UPDATE:
Here's how the html looks like after loading the page:
The textarea that contains values are done by php.

<textarea name="work_and_education[0]" class="item_input" placeholder="List item content...">testin1</textarea>
+

-

<textarea name="work_and_education[3]" class="item_input" placeholder="List item content..."></textarea>
+

-

<textarea name="work_and_education[2]" class="item_input" placeholder="List item content...">testing2</textarea>
+

-

A: This should work, however if you are using it to add many textareas, they should have unique names and possibly id's.


text:
Q: When using multivariate regression with a mix of binary and continuous predictors, is it necessary to still run a T Test for the binary predictors? When using multivariate regression with a mix of binary and continuous predictors, is it necessary to still run a T Test for the binary predictors or can that information be found in the regression?
Really, I'm wanting to know this for only one of the categorical variables. I want to know if there exist a significant difference between the means of these two groups (let's say it's gender).


text:
Q: UITableView height change when scrolling with animation I took UIViewController which have 2 UITableView.
How to use the method scrollViewDidloadScroll:(UIScrollView *)scrollView to do stretches to the Top Layout Guide?
Project on Objective C.

A: We can do it using tags. Need assign tag to tableview object,
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//Need to give tag value to table view
if(scrollView.tag == 100){
    //table1
}else if(scrollView.tag == 101){
    //table2
}}

Hope this will hep you


text:
Q: ELB and CloudFront: Can I keep some folders on CloudFront and others on EC2? I have a load balancer which balances some EC2 instances. The three major instances are:

*

*www.domain.com/blog – LAMP. This is on EC2 and I want to keep it there

*www.domain.com/forum – Lamp. This is on EC2 and I want to keep it there

*www.domain.com – Windows. Rest everything I can move to Cloudfront
Due to budgetary constraints I want to keep Blog and Forums on EC2.
Can I keep the load balancer (with my DNS provider) before the Cloudfront which will help me

*

*keep redirecting the forum and blog requests to EC2 instances and

*direct all other requests to Cloudfront
Load Balancer currently success directs users between various EC2 instances, some on linux and some on windows platform
Setup I need it:
Load Balancer Checks request type:
If the URL contains /forum direct them to EC2
If the URL contains /blog direct them to EC2
If the URL does not contain either direct them to Cloudfront
Forum is - Xenforo
Blog is Wordpress


text:
Q: Can't remove directory under Windows or Linux I installed a video game from the the Microsoft Store and all I want to do is uninstall it.
I've tried:

*

*Uninstalling through the Windows Store. (It won't open and just loads indefinitely)

*Removing the game through the "Add & Remove Programs" dialog. (It fails with an 0x80073cf6 error)

*"Taking ownership" of the directory and deleting it through the command prompt. (Still tells me permission denied).

I figured I could circumvent the Microsoft BS by deleting the folder under linux. Even though I have full permissions on the folder I still get "permission denied" when I try to remove the folder using rm -rf WindowsApps as root.
# ls -ld WindowsApps
drwxrwxrwx 1 root root 4096 Jun 27 14:09 WindowsApps

Am I missing something obvious? I just want to delete a folder. This is taking up 60GB+ on my hard drive and is quite a nuisance.


text:
Q: How to call method to main method (Program runs but does not print out questions) (Homework) Response to previous program, Simply placing new balance(); where public static void main is, does not work, and without that the program  runs but nerver prints out the user questions!
import java.io.*;

public class cInterest {

    public static void main(String[] args)   throws IOException
    {
       //new balance ;
    }
    public static  double balance(double principal, double rate, double years) throws IOException{

        double amount = 0;

        String input;
        BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));

        System.out.print("How much would you like to take out? ");
        input = myInput.readLine ();
        principal = Double.parseDouble (input);

        System.out.print("Enter the interest rate: ");
        input = myInput.readLine ();
        rate = Double.parseDouble (input);

        for (int i = 1; i < years; i++) {
            amount = principal * rate * years;
            amount += principal;
        }
        return amount; //- principal;
    }
}

A: balance is a method, not a class, so you can't use the new keyword. You want to call the method, instead, like this:
public static void main(String[] args)   throws IOException
{
    double balance = balance(0.0, 0.0, 1.0); // Awkward hard-coded variables! Ew!
    System.out.println(balance);
}

But why are you passing these variables to the method when the user's just going to overwrite them? Your balance method should only be responsible for calculating the balance, not gathering user input. You can do that in the main method:
public static void main(String[] args)   throws IOException
{
    // Gather user input.
    String input;
    BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));

    System.out.print("How much would you like to take out? ");
    input = myInput.readLine ();
    double principal = Double.parseDouble (input);

    System.out.print("Enter the interest rate: ");
    input = myInput.readLine ();
    double rate = Double.parseDouble (input);

    System.out.print("Enter the number of years: ");
    input = myInput.readLine ();
    double years = Double.parseDouble (input);

    // Now do the calculations...
    double balance = balance(principal, rate, years); // Much clearer!
    System.out.println(balance);
}

public static double balance(double principal, double rate, double years) {
    // Calculate the end balance based on the parameters, and return it.
}

Even better would be to put the gathering of user input into a dedicated method of its own, but I'm far enough off-topic as it is.

A: You should explicitly call the balance() method somewhere.

A: Use System.out.println instead of System.out.print, otherwise, your Stream will not be flushed. You can refer to the PrintStream javadoc for more informations.


text:
Q: A continuous function on a sphere attains the same value at some pair of antipodal points Let $S=\{x\in \mathbb R^n: \|x\|=1\}$ be the unit sphere in $\mathbb R^n$, and let $f: S\to \mathbb R$ be a real-valued continuous function on $S$. Prove that there is a point a belonging to $S$ such that $f(a)=f(-a)$.

A: Suppose, for the sake of a contradiction, there is no such $a\in S$. Define the function $g:S\to \mathbb{R}$ by $g(x)=f(x)-f(-x)$. Our assumption guarantees that $g$ is never zero. By the intermediate value theorem, this implies that $g$ is either always positive or always negative. Without loss of generality assume that $g(x)>0$ for every $x\in S$. But then for any point $x\in S$, we have $0<g(-x)=f(-x)-f(x)=-g(x)<0$, a contradiction.


text:
Q: How to force postfix to use smtp relay When I execute, the following line postfix uses my sendgrid relay server
echo "Subject: sendmail test" | sendmail -v test@test.nl

But when I execute the sendmail function via the PHP script it won't send it to the relay server. Look like it want to distribute it locally
Any thoughts on how to force postfix to use the smtp relay option

*

*Update

It looks like postfix is timing out on STARTTLS, I have added the log below. Could this be due to my LetsEncrypt certificate?
postfix/smtpd[29268]: > localhost[::1]: 250-www.example.com
postfix/smtpd[29268]: > localhost[::1]: 250-PIPELINING
postfix/smtpd[29268]: > localhost[::1]: 250-SIZE 10240000
postfix/smtpd[29268]: > localhost[::1]: 250-VRFY
postfix/smtpd[29268]: > localhost[::1]: 250-ETRN
postfix/smtpd[29268]: > localhost[::1]: 250-STARTTLS
postfix/cleanup[29279]: 8E2B520B98: message-id=<1635758129.617fb031bae3c@www.example.com>
postfix/smtpd[29268]: smtp_get: EOF

postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
config_directory = /etc/postfix
header_size_limit = 4096000
inet_interfaces = all
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
mydestination = $myhostname, localhost.$mydomain, localhost
mydomain = example.com
myhostname = www.example.com
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
myorigin = /etc/mailname
readme_directory = no
recipient_delimiter = +
relayhost = smtp.sendgrid.net:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = static:apikey:BLBAABLAABLAA
smtp_sasl_security_options = noanonymous
smtp_sasl_tls_security_options = noanonymous
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_tls_security_level = encrypt
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname E
SMTP $mail_name (Debian/GNU)
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_tls_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file = /etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_use_tls = yes

It seems to work perfectly when I write a python script but with the PHP swiftmailer it seems to fail and return an EOF
=============== UPDATE
The relay seems to work but now we are getting this error
Swift_IoException [ 0 ]: Connection to localhost:25 Timed Out

I am able to sendmails using sendmail, but when SwiftMailer is using sendmail its getting the earlier stated error

A: I managed to fix the issue. It turned out that the mail that the client send out was embedded with an unauthorised image. I removed the embedded image and everything works fine now!
I do find it odd that nothing would show in the verbose log of postfix


text:
Q: Preventing sporadic coordinates using CoreLocation Basically I'm making an app that is supposed to record a path and data that someone travels along. I'm having some trouble with accuracy and determining inaccurate reports. Here is an image of the path that my iPhone recorded. The red line is the recorded path, the pink is how I actually walked (apologies for the huge screenshot):

My delegate for recording the data looks like this:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    if (newLocation.horizontalAccuracy < 0) return;
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
    // The "> 50.0f" is to hopefully throw out inaccurate points
    if (locationAge > 5.0 || [newLocation distanceFromLocation:oldLocation] > 50.0f) return;
    [[self locationPoints] addObject:newLocation];
    [self updateView];
}

Some advice that I've seen is to use filters to check if the data is appropriate for the projected path. Is this the best way to go?

A: You could add checking for newLocation.horizontalAccuracy:
if ((newLocation.horizontalAccuracy > 0.0) && (newLocation.horizontalAccuracy < 10.0))

Or, for your case:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    if (newLocation.horizontalAccuracy < 0) return;
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];

    if ((locationAge > 5.0)||(newLocation.horizontalAccuracy < 0.0)||(newLocation.horizontalAccuracy > 10.0)) return;
    [[self locationPoints] addObject:newLocation];
    [self updateView];
}

This (locationAge > 5.0) condition seems weird. Do you really want it? If you keep it in your app will stop updating if device looses proper GPS signal for >5.0s.
One more thing: did you remeber to setup your locationManager with:
locationManager.desiredAccuracy=kCLLocationAccuracyBest;

You should also know that this eats up quit a lot of battery, but for testing...


text:
Q: Import error with "import pyspark.pandas " This is part of new coursework I am doing.
I am trying to install pyspark and I intend to use pyspark.pandas .  I try to run a check on my package like this.
import pandas as pd
import numpy as np
import pyspark.pandas as ps
But as I run imports, I see the below error.
ImportError: cannot import name 'print_exec' from 'pyspark.cloudpickle' (C:\Users\smith\Anaconda3\lib\site-packages\pyspark\cloudpickle\__init__.py)
The pyspark version I am using is 3.1.3. I am not sure, I could be wrong at setting paths here. Is there a way I can verify the paths?? Or this could be any other issue please let me know.
Thanks

A: Pandas API is available only for PySpark version 3.2, or above.
To upgrade PySpark to its latest release execute the following command:
!pip install -U --upgrade pyspark

Remove the "!" if you're not executing the command on a Jupyter Notebook.

After restarting your kernel import pyspark.pandas as ps import should work.
Note
You can also check the PySpark version Python is importing like so:
import pyspark

print(pyspark.__version__)
# 3.3.0

Update
I've had a look at the history of changes made to broadcast.py (that I believe is where the import is failing), and it seems they've changed the location of print_exc from pyspark.cloudpickle to pyspark.util. Upgrading should really solve the issue.
Older version of broadcast.py module:
https://github.com/apache/spark/blob/75ea89ad94ca76646e4697cf98c78d14c6e2695f/python/pyspark/broadcast.py#L24
Newer versions:
https://github.com/apache/spark/blob/8f744783531d4f62abdf82643b5eb34d54a2820b/python/pyspark/broadcast.py#L42


text:
Q: How can I adjust scaling of W10 to match as closely as possible to W7 On Win7 I use scaling of 125% and that was enough to cover all my needs. However, on Win10, I had to up it to 135% to even barely match the scale factor. But the issue is that since it works differently it is partially broken for me. There are a few glaring issues at hand:

*

*Blurry text in old windows elements like MMC.

*Unscaled text in some cases, for example dialogue windows, like, when you import some .reg file and a warning pops-up - the text is INCREDIBLY small for 135% scale, but the window itself is scaled an there is plenty of space of bigger font size.
I could fix the blur of 1) by setting HDPIAWARE flag for specific applications, that's fine. But the problem is that it still wont be scaled at all and is really hard to read.
I could not find any way fix the 2). I tried using solutions that enable old Win8.1 scaling (like http://windows10-dpi-fix.xpexplorer.com) but still to no avail.
Is there some other aspects of scaling I'm missing that can help me bring it closer to Windows XP/7 style? My eyesight is incredibly poor.
EDIT: To clarify, I have no issues choosing custom scaling, I can make it 200% if needed, I know how this option works and where to set it. problem is, this will make elements bigger but barely affects the text. Notice dialogue window label text is unchanged:
https://www.screenshotcomparison.com/comparison/9475
This applies to 70% of the screen text, atually.


text:
Q: Feature detection when P/Invoking in C# and .NET i'm trying to find a good way to detect if a feature exists before P/Invoking. For example calling the native StrCmpLogicalW function:
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
   [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
   public static extern int StrCmpLogicalW(string psz1, string psz2);
}

will crash on some systems that do not have this feature.
i don't want to perform version checking, as that is bad practice, and can sometimes just be wrong (for example when functionality is back-ported, or when the functionality can be uninstalled).
The correct way, is to check for the presence of the export from shlwapi.dll:
private static _StrCmpLogicalW: function(String psz1, String psz2): Integer;
private Boolean _StrCmpLogicalWInitialized;

public int StrCmpLogicalW(String psz1, psz2)
{
    if (!_StrCmpLogialInitialized)
    {
        _StrCmpLogicalW = GetProcedure("shlwapi.dll", "StrCmpLogicalW");
        _StrCmpLogicalWInitialized = true;
    }

    if (_StrCmpLogicalW)
       return _StrCmpLogicalW(psz1, psz2)
    else
       return String.Compare(psz1, psz2, StringComparison.CurrentCultureIgnoreCase);
}

The problem, of course, is that C# doesn't support function pointers, i.e.:
_StrCmpLogicalW = GetProcedure("shlwapi.dll", "StrCmpLogicalW");

cannot be done.
So i'm trying to find alternative syntax to perform the same logic in .NET. i have the following pseudo-code so far, but i'm getting stymied:
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
   private Boolean IsSupported = false;
   private Boolean IsInitialized = false;

   [DllImport("shlwapi.dll", CharSet = CharSet.Unicode, Export="StrCmpLogicalW", CaseSensitivie=false, SetsLastError=true, IsNative=false, SupportsPeanutMandMs=true)]
   private static extern int UnsafeStrCmpLogicalW(string psz1, string psz2);

   public int StrCmpLogicalW(string s1, string s2)
   {
       if (!IsInitialized)
       {
          //todo: figure out how to loadLibrary in .net
          //todo: figure out how to getProcedureAddress in .net
          IsSupported = (result from getProcedureAddress is not null);
          IsInitialized = true;
       }

       if (IsSupported)
          return UnsafeStrCmpLogicalW(s1, s2);
       else
          return String.Compare(s1, s2, StringComparison.CurrentCultureIgnoreCase);
   }
}

and i need some help.

Another example of some exports that i want to detect presence of would be:

*

*dwmapi.dll::DwmIsCompositionEnabled

*dwmapi.dll::DwmExtendFrameIntoClientArea

*dwmapi.dll::DwmGetColorizationColor

*dwmapi.dll::DwmGetColorizationParameters (undocumented1, not yet exported by name, ordinal 127)

*dwmapi.dll::127 (undocumented1, DwmGetColorizationParameters)

1 as of Windows 7 SP1
There must already be a design pattern in .NET for checking the presence of OS features. Can anyone point me to an example of the preferred way in .NET to perform feature detection?

A: You could P/Invoke to LoadLibraryW to load shlwapi.dll and then P/Invoke to GetProcAddressW to find "StrCmpLogicalW". If NULL is returned, then it's not there.
You don't need the actual returned value from GetProcAddressW - as long as it's not NULL, you know you can use the P/Invoke declaration of your choice.
Note that GetProcAddressW also supports functions exported by ordinal value.
EDIT: If you want to follow some kind of pattern, then this might work:
First define a helper class NativeMethodResolver that tells you if a method exists in a library:
public static class NativeMethodResolver
{
    public static bool MethodExists(string libraryName, string methodName)
    {
        var libraryPtr = LoadLibrary(libraryName);
        var procPtr = GetProcAddress(libraryPtr, methodName);

        return libraryPtr != UIntPtr.Zero && procPtr != UIntPtr.Zero;
    }

    [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern UIntPtr LoadLibrary(string lpFileName);

    [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
    private static extern UIntPtr GetProcAddress(UIntPtr hModule, string lpProcName);
}

The above helper class can be consumed by derived classes of SafeNativeMethod that aids in boiler plating some common stuff:
public abstract class SafeNativeMethod
{
    private readonly string libraryName;
    private readonly string methodName;
    private bool resolved;
    private bool exists;

    protected SafeNativeMethod(string libraryName, string methodName)
    {
        this.libraryName = libraryName;
        this.methodName = methodName;
    }

    protected bool CanInvoke
    {
        get
        {
            if (!this.resolved)
            {
                this.exists = Resolve();
                this.resolved = true;
            }

            return this.exists;
        }
    }

    private bool Resolve()
    {
        return NativeMethodResolver.MethodExists(this.libraryName, this.methodName);
    }
}

A derived class that defines its own Invoke method can then call the base CanInvoke to see if a default value (or default implementation) should be returned in place of the return value of the sought native method. From your question, I'll take shlwapi.dll/StrCmpLogicalW and dwmapi.dll/DwmIsCompositionEnabled as example implementations for SafeNativeMethod:
public sealed class SafeStrCmpLogical : SafeNativeMethod
{
    public SafeStrCmpLogical()
        : base("shlwapi.dll", "StrCmpLogicalW")
    {
    }

    public int Invoke(string psz1, string psz2)
    {
        return CanInvoke ? StrCmpLogicalW(psz1, psz2) : 0;
    }

    [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern int StrCmpLogicalW(string psz1, string psz2);
}

public sealed class SafeDwmIsCompositionEnabled : SafeNativeMethod
{
    public SafeDwmIsCompositionEnabled()
        : base("dwmapi.dll", "DwmIsCompositionEnabled")
    {
    }

    public bool Invoke()
    {
        return CanInvoke ? DwmIsCompositionEnabled() : false;
    }

    [DllImport("dwmapi.dll", SetLastError = true, PreserveSig = false)]
    private static extern bool DwmIsCompositionEnabled();
}

Those two can then be used like this:
static void Main()
{
    var StrCmpLogical = new SafeStrCmpLogical();
    var relation = StrCmpLogical.Invoke("first", "second");

    var DwmIsCompositionEnabled = new SafeDwmIsCompositionEnabled();
    var enabled = DwmIsCompositionEnabled.Invoke();
}

A: Marshal.Prelink can be used to get the P/Invoke "not found" exception without actually calling the method. Here is how it could be used to complete your example:
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode, Export="StrCmpLogicalW", CaseSensitivie=false, SetsLastError=true, IsNative=false, SupportsPeanutMandMs=true)]
    private static extern int UnsafeStrCmpLogicalW(string psz1, string psz2);

    static bool? _UnsafeStrCmpLogicalWIsSupported;
    static bool UnsafeStrCmpLogicalWIsSupported => _UnsafeStrCmpLogicalWIsSupported ?? IsSupported("UnsafeStrCmpLogicalW", out _UnsafeStrCmpLogicalWIsSupported);

    public static int StrCmpLogicalW(string s1, string s2)
    {
        if (UnsafeStrCmpLogicalWIsSupported)
            return UnsafeStrCmpLogicalW(s1, s2);
        else
            return String.Compare(s1, s2, StringComparison.CurrentCultureIgnoreCase);
    }

    static bool IsSupported(string method, out bool? field)
    {
        var result = IsSupported(method);
        field = result;
        return result;
    }
    static bool IsSupported(string method)
    {
        var methods = typeof(SafeNativeMethods).GetMethods().Where(m => m.Name == method).ToList();
        if (methods.Count == 0)
            throw new ArgumentException("Method not found: "+method, nameof(method));
        try
        {
            foreach (var m in methods)
                Marshal.Prelink(m);
            return true;
        }
        catch { return false; }
    }
}


text:
Q: C# Downloading Image with same name as in URL I've got a method to save an image from requested website url, but it saves image as wallpaper.jpg. Is there a possiblity to save an image with the same name as in given url (for example https://i.imgur.com/l7s8uDA.png as a l7s8uDA.jpg?
Here's the code:
private void DownloadImage(string uri)
{
    string fileName = Environment.CurrentDirectory + "\\Wallpapers\\wallpaper.jpg";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK ||
        response.StatusCode == HttpStatusCode.Moved ||
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
    {
        // if the remote file was found, download oit
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
    }
}

A: You can get the file name from uri this way:
var uri = new Uri("https://i.imgur.com/l7s8uDA.png");
var name= System.IO.Path.GetFileName(uri.LocalPath);

Also if you need file name without extension:
var name = System.IO.Path.GetFileNameWithoutExtension(uri.LocalPath)


text:
Q: How many github ssh keys do I need for a small dev team? I'm confused by the concept of SSH keys when it comes to using a remote repository hosted by GitHub. I generated the keys as instructed in http://help.github.com/win-set-up-git/ , but now that I have multiple devs pushing into the repo, I'm not clear if we're all to share one single SSH key or if we all need to generate an individual key per-machine and use that?
Could someone kindly clarify that for me?

A: Use a key per developer - each dev should generate their own key. This gives you a better indication of who is committing to the repo, and means that you can revoke a developer's commit rights if/when they leave the company. Otherwise they could just copy the shared key, and you would have to re-issue a new one every time you needed to change access rights.

A: An SSH key is used for the user to be authenticated and identified into GitHub.
It is common that, for every different device a user uses to access GitHub, he generates a different ssh-key and register/link it to his GitHub's account.
When you control a project, you control access and permissions based on users, and not SSH keys.
So, when you (as a user) setup your git environment you can create only one ssh-key for each machine you would like to give permission to your GitHub's account.

Update:
Github now recommends using HTTPS instead of SSH keys but everything in this answer remains valid if you replace all SSH key references above by Github's Personal Access Tokens


text:
Q: Why the final output of the recursive function is 5? Why the output of the above code is 5 as the function should go to first 5-4-3-2 (since no output) loop decrements to 1 so return 12 so at last 12+1..... so the answer must not be 5 i guess ?
using namespace std;
int  x()
{
}
int reee(int n)
{
  for(int i=n; i>0; i--)
  {
  if(i==2)
  {
    return x();
  }
  else if(n==1)
  {
    return 12;
  }
  else
  {
     return reee(i-1)+1;
  }
}
}
int main()
{
  cout << reee(5) << " ";
}

A: There is no need for a for loop in this case as your function is already a recursive function so it keeps running the function until it is 2. When it is 2, it returns x making it empty body + 3. If you want it to get to 1, in the if statement of i==2, you should make it return(i-1)
Therefore, your code should be like this:
using namespace std;

int reee(int n)
{
  if(n==2) {
    return reee(--n);
  } else if(n==1) {
    return (n+12);
  } else {
     return reee(--n)+1;
  }
}
int main()
{
  cout << reee(5) << " ";
}

That should help you with what you are trying to achieve.

A: int  x()
{
}

Calling this function results in Undefined Behavior because your function declared to return int doesn't return anything.
Crank up the compiler warning and while you are in learning stages treat warnings as errors.


text:
Q: How can I hide the keyboard in the UI in Swift Playgrounds (on Xcode) that appears in the Live View when I create a UITextView? I have created a UITextView object and when I interact with it in the Live View, the keyboard appears in the UI and the only way to enter text seems to be from that keyboard. Is this a recent change in Swift Playgrounds? Is there any way users can enter text from their physical keyboards?
Code:
let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 1024, height: 768))
textView.textColor = .green
textView.font = UIFont(name: "Courier", size: 22)
textView.backgroundColor = .black
mainView.addSubview(textView)

A: You can add gesture recognizer to a superview, assign action with custom close keyboard method and call textField.resignFirstResponder() inside it.
Here is a quick example:
import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

    private var textView: UITextView?

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        textView = UITextView()

        if let textView = textView {
            textView.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
            textView.text = "Hello World!"
            textView.textColor = .black

            view.addSubview(textView)
        }
        self.view = view
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
        self.view.addGestureRecognizer(tapGesture)
    }

    @objc func hideKeyboard() {
        textView?.resignFirstResponder()
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()


text:
Q: Numpy mask from cylinder coordinates I generated the coordinates of a cylinder. Its two faces connect two arbitrary points already given.

Is it possible to build a 3D numpy mask of the filled cylinder from the coordinates with standard Python libraries? Creating a 2D mask seems simple enough, but I'm encountering some difficulties with 3D.
Here the code for generating the cylinder, taken from here and here:
import scipy
import scipy.linalg
import numpy as np
import nibabel as nib
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# defining mask
shape = (100, 100, 100)
image = np.zeros(shape=shape)

# set radius and centres values
r = 3
start = [30, 45, 60]
end = [40, 58, 70]
p1 = np.array(start)
p2 = np.array(end)

# # calculate p2-p1 distance
# dx = p2[0] - p1[0]
# dy = p2[1] - p1[1]
# dz = p2[2] - p1[2]
# dist = math.sqrt(dx**2 + dy**2 + dz**2)

# vector in direction of axis
v = p2 - p1
# find magnitude of vector
mag = scipy.linalg.norm(v)
# unit vector in direction of axis
v = v / mag
# make some vector not in the same direction as v
not_v = np.array([1, 0, 0])
if (v == not_v).all():
    not_v = np.array([0, 1, 0])
# make vector perpendicular to v
n1 = np.cross(v, not_v)
# normalize n1
n1 /= scipy.linalg.norm(n1)
# make unit vector perpendicular to v and n1
n2 = np.cross(v, n1)
#surface ranges over t from 0 to length of axis and 0 to 2*pi
t = np.linspace(0, mag, 100)
theta = np.linspace(0, 2 * np.pi, 100)
rsample = np.linspace(0, r, 2)

#use meshgrid to make 2d arrays
t, theta2 = np.meshgrid(t, theta)
rsample, theta = np.meshgrid(rsample, theta)

# generate coordinates for surface
# "Tube"
X, Y, Z = [p1[i] + v[i] * t + r * np.sin(theta2) * n1[i] + r * np.cos(theta2) * n2[i] for i in [0, 1, 2]]
# "Bottom"
X2, Y2, Z2 = [p1[i] + rsample[i] * np.sin(theta) * n1[i] + rsample[i] * np.cos(theta) * n2[i] for i in [0, 1, 2]]
# "Top"
X3, Y3, Z3 = [p1[i] + v[i] * mag + rsample[i] * np.sin(theta) * n1[i] + rsample[i] * np.cos(theta) * n2[i] for i in [0, 1, 2]]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
ax.plot_surface(X2, Y2, Z2)
ax.plot_surface(X3, Y3, Z3)

plt.show()

I need the 3D numpy mask to select all the values inside the cylinder of a 3D image. The shape of mask and image is the same.

A: In the end I looped through the coordinates of tube and faces.
I got the coordinates following this link: 3D points from Numpy meshgrid coordinates
tube = np.stack((X.ravel(), Y.ravel(), Z.ravel()), axis=1)
face1 = np.stack((X2.ravel(), Y2.ravel(), Z2.ravel()), axis=1)
face2 = np.stack((X3.ravel(), Y3.ravel(), Z3.ravel()), axis=1)

# filling numpy mask

for i in range(len(tube)):
    image[int(tube[i][0]), int(tube[i][1]), int(tube[i][2])] = 255

for j in range(len(face1)):
    image[int(face1[j][0]), int(face1[j][1]), int(face1[j][2])] = 255

for k in range(len(face2)):
    image[int(face2[k][0]), int(face2[k][1]), int(face2[k][2])] = 255

mask_new = nib.Nifti1Image(image.astype(np.float32), ctsurg_file.affine)

nib.save(mask_new, os.path.join(currdir, 'mask_cyl.nii.gz'))


text:
Q: Trouble getting a valid token in Web Api 2, even after Cors is enabled So I've installed the NuGet package Microsoft.AspNet.WebApi.Cors.5.2.3 in my VS2015 solution, and also have enabled CORS in my Web Api project.
I have successfully used Fidder to test my /token POST request, and my GET request to API controller \api\values.
If I use the token I received back in Fiddler, and hard code it into my JavaScript GET request - I can indeed make a successful request to \api\values from my Single Page Application.
PROBLEM: I cannot make a successful POST request to http://localhost:17883/token in my local dev environment.
The error in Chrome is:
XMLHttpRequest cannot load http://localhost:17883//token.
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
XHR failed loading: POST "http://localhost:17883//token".

I've enabled CORS in WebApiConfig.cs -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;

namespace API
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            // *** ENABLE CORS ***
            var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

In my Angular authService, I coded up an API test function hooked up to a button on my Login page (this request is successful):

var _apitest = function ()
    {
        var deferred = $q.defer();

        var tkn='cbJZpiF-rEdi_WgWzuFOAxPZ0lBiqivEnOmpSYMPu_fuvu37cpLFzHhzc119GfwIc6dnDivYhhH2a1O2bMa6EExRGa3lvPfzZJHiDDaH6klIU2NFEG5FMxFl_-Z_jBQvPkPyW_31iP6P_oVNZZpXzkQfkwA4zilzKLE7If2Dko6MNNID1lscVfkZ4emJXWpalSXCS4A7qmO-ceIchMfrcbZHgVqBjZC_YHz-DxAfg2lTksUdn8NBir_cDOH5Ymsrzj_bKP1H6WJULDfZEPuh0PpB2DlJEXOV63KWUf7Eubp_FYfni5czD1Z-lh2a2RPRfpRxlMQVBUCCp03_Ul5a6lzOFHSJCJlynidw2DV_InK-oFZEuvQK2Xiy_7wq0JVmx-Nej1bQRN7b2eWK25jjdrTfCNyMdtmDZ7qOSmX3dWuyQhCbp_15ciFhmr7wfIYPzsFssbg-XHtDi2lw87KkJ0IhNmtnsoNyKCrM5ibJG5O5t_gxr3l52JN54Jj2mbeY';

        var req={
            "method": "GET",
            "url": "http://localhost:17883/api/values",
            "headers": {
                "Authorization": "Bearer " + tkn
            }
        };
        $http(req).then(function (data)
        {
            deferred.resolve(data);
        });

        return deferred.promise;
    };

This POST request to \token is NOT successful:

var _loginUserPost = function (loginData)
    {
        var controllerpath = "/token";
        var url = serviceBase + controllerpath;
        var body = "username=" + loginData.userName + "&password=" + loginData.password + "&grant_type=password";

        var deferred = $q.defer();
        deferred.notify("Logging in user...");

        // POST REQUEST !!
        var req = {
            method: 'POST',
            encoding: 'JSON',
            headers: {
                'Content-Type': 'application;x-www-form-urlencoded'
            },
            url: url,
            data: body
        };

        $http(req).then(function (data)
        {
            deferred.resolve(data);
        }, function (err)
        {
            deferred.reject("Failed to login user via api call.");
            console.log("Failed to login user via api call. Errors details: " + err);
        });

        return deferred.promise;
    }

I also tried to decorate the ApplicationOAuthProvide class with the EnableCors attribute, but it still doesn't work:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
     ...
}

I really need to know what I'm missing. I have been searching and trying different things - but to no avail.
Advice is appreciated.
Bob
********* UPDATE - What I've tried so far ************
Still, request to \token is kicked back with CORS exception in Chrome.
I've tried unsuccessfully to add Headers (search "Step 10:" in this article: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/ ):
   public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });   // BM:

    ...
   }

A: Make sure you have an Options() Action in your controller. It's probably making a preflight Options request before the post and not finding a matching action.

public HttpResponseMessage Options()
{
    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

Depending on how IIS is configured, you may also need to allow the options request in your web.config

<system.webServer>
    <security>
      <requestFiltering>
        <verbs applyToWebDAV="false">
          <add verb="OPTIONS" allowed="true" />
        </verbs>
      </requestFiltering>
    </security>
<system.webServer>

Also make sure the Content-Type you're specifying in Angular is the same as what's being expected by Web Api

var req = {
    // ...
    headers:
        'Content-Type': 'application;x-www-form-urlencoded'
    },
    // ..
};


text:
Q: How to display only unique messages when using flash in flask When using the flash functionality in flask, I have a couple of functions. I call f1, which calls f2 x times, which calls f3 y times. I get a inconsistency in f3, so I want to flash it in f3. However, I don't want to pass the inconsistency all the way down to f1 again, which results in the fact that the message in currently being flashed multiple times because the inconsistency occurs multiple times. Letting the user know 1 time is enough to determine the cause of it.
So I want to only display unique messages.
Minimal example:
from flask import Flask, flash, render_template_string

app = Flask(__name__)
app.secret_key = 'arstarst'

@app.route('/')
def index():
    flash('banana', 'red')
    flash('apple', 'green')
    flash('banana', 'red')
    flash('pear', 'blue')
    return render_template_string('''
      {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
          {% for category, message in messages %}

{{message}}

          {% endfor %}
      {% endif %}
    {% endwith %}
    ''')

A: Solution:

*

*Make an emtpy dict in jinja

*Loop over messages

*Check if the message is in the dict

*If not, add to the dict and print the message

*If so, do nothing

Example:
from flask import Flask, flash, render_template_string
app = Flask(__name__)
app.secret_key = 'arstarst'

@app.route('/')
def index():
    flash('banana', 'red')
    flash('apple', 'green')
    flash('banana', 'red')
    flash('pear', 'blue')
    return render_template_string('''
      {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
          {% set printed_messages = dict() %}
          {% for category, message in messages %}
            {% if message not in printed_messages %}

{{message}}

              {% set x = printed_messages.__setitem__(message, "value")  %}
            {% endif %}
          {% endfor %}
      {% endif %}
    {% endwith %}
    ''')


text:
Q: how to make slide animation? css part
 body
{
background-color:black;
padding:0;
margin:0;
overflow:hidden;
}
  #accordion {
   display:none;
       position:absolute;
   left:89%;
       margin-top:400px;
       width:174px;
   height:150px;
   list-style:none;

  }

 #logpop
{
 display:none;
 position:absolute;
 left:91%;
 margin-top:400px;
 width:174px;
 height:150px;

}

    <input class="input_box" name="email" type="text" placeholder="aaa"/>

    <input class="input_box" name="pass" type="password" placeholder="*****"/>

    <button id="btn1">Login</button>

Jae Jung

there is video running in the background and I want to make login box slice from right out of screen to left and when user clicks on button it slides to right out of screen and accordion menu slide in right out of screen to left. I wonder css for login box and accordion has right position(positioning on right screen middle) and how to implement Jquery to make sliding animation effect.

A: jQuery provides the .slideDown & .slideUp functions to slide an elements from bottom-to-top or vice versa, but it doesn't provide one to slide ltr or rtl.
But this is a short tutorial that covers how you can do it with minimal code.

A: Check this fiddle
HTML
<input id="btnStart" type="button" value="Start" />

Login

First header

First content

Second header

Second content

CSS
body{
    overflow: hidden;
}
#slider{
    width: 100px;
    background-color: rgb(200,200,200);
    text-align: center;
    position: absolute;
    z-index: 100;
    top: 50px;
    right: -100px;
}
#accordion{
    position: absolute;
    z-index: 100;
    top: 20px;
    left: -100px;
}
input{
    padding: 3px;
}

JavaScript
$("#accordion").accordion();
$("#btnStart").click(function(e) {
    $("#slider").animate({
        "right": "+=" + $(window).width() / 2 + "px"
    }, "1000");
});
$("#slider").click(function(e) {
    $("#slider").animate({
        "right": "-=" + $(window).width() / 2 + "px"
    }, "1000");
    $("#accordion").animate({
        "left": "+=" + $(window).width() / 2 + "px"
    }, "1000");
});

Hope this helps you.


text:
Q: Safari bug .position() I'm not sure if this is a bug with my code, or with Safari, but when using the code:
cx = $('.cart').position().top;

to trigger an alert on the page; it will trigger (work correctly) in all browsers but Safari. I am unsure why.
Here is the page I am having the problem with!
I'm using Safari version 3.2.2 by the way.

A: I'm not sure what the alert dialog is supposed to do but I got it to display fine in both Safari 5.1.7 and Chrome 22. I did however notice a discrepancy in the position returned. Below is the output of the dialog in each browser:
Output in Safari 5.1.7:
http://partytime.v5.cloudsvr.com.au
Cart is loaded: 1, X position: 1274px;

Output in Chrome 22:
Cart is loaded: 1, X position: 1260.5px;

Not sure if this is what you wanted/intended but it appears to be working correctly.


text:
Q: Java 8 cannot force TLS for sslcontext creation? I'd like to use TLS/TLSv1.2 for an ssl context:
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(new KeyManager[] { km }, new TrustManager[] { new MyTrustStore(keyStore) }, new SecureRandom());
System.out.println("PROTOCOL: "+SSLContext.getDefault().getSupportedSSLParameters().getProtocols()[0]);

We're using custom Truststores and keymanagers, just ignore that here, but we do need those.
Now this prints "SSLv2Hello" every time.
I have tried both
SSLContext context = SSLContext.getInstance("TLSv1.2");

and
SSLContext context = SSLContext.getInstance("TLS");

And neither worked.
For reference this runs on JDK 1.8.0_171
Thank you for your help

A: You can try a custom way. Below is a kotlin sample
    val sslContext = SSLContexts.custom().setProtocol("TLSv1.2").build()

Reference : How to fix 'SSLHandshakeException: Received fatal alert: decode_error'?


text:
Q: How to validate input within a bool to begin with two 0's using substring I am real stumped regarding a specific validation, I need to validate that the user has inputted two 0's before their user ID. This is what I have tried so far:
if (txtID.Text.Substring(0, 2) != "00")
{
    DisplayMessage("Your ID must begin with two zeros.");
    txtID.Focus();
    return false;
}

A: You can simply do this:
if (txtID.Text.Length >= 2 && txtID.Trim().StartsWith("00", true, null))
{
    DisplayMessage("Your ID must begin with two zeros.");
    txtID.Focus();
    return false;
}

Although not relevant in this case, StartsWith comes with multiple overloads (case sensitive, case insensitive, culture specific)..

A: Anyone with User Experience would tell you that if they have to enter 00, don't make them enter it at all, it's a bad user experience.  Instead make it easy on your user and do it for them:


text:
Q: Using parent data as the zerotext of a nested repeater If my nested repeater returns no results, I want the zerotext result to be from the parent item. I can't figure it out; I've read around the issue but nothing seems to cover this specifically. I'm using Kentico EMS v6.
Is it even possible? Thanks, Oli.

A: it is not possible unless you modify the code of the web part. Reason: you can use only plain text or macro in the 'No record found text' field and macro can not be evaluated to such thing as parent's 'No record found text'.


text:
Q: Why compare $s_n:=\sum_{k=1}^n\frac{1}{k}$ to $\int_{1}^{n+1}\frac{1}{x}dx$, instead of $\int_1^{n}\frac1{x}dx$, when proving divergence of $s_n$? I've seen an example in which the limit of the sequence $s_n = \sum_{k=1}^n \frac{1}{k}$ is proved to be divergent because:
$$s_n \geq \int_{1}^{n+1}\frac{1}{x} dx$$
and $\log(n+1)=+\infty$ as $n\to +\infty$. I'm confused about the following: Why $n+1$ instead of $n$? I've been trying to think but found no (convincent) reason for it, I guess it would work with $n$ too.
I guess I got confused because in the previous example, he proved that $s_n=\sum_{k=1}^{n}\frac{1}{k^2}$ is convergent because:
$$s_n\leq 1+\int_1^{n}\frac{1}{x^2}dx$$

A: $\int_1^{n+1}\frac 1 x dx=\sum_{k=1}^{n} \int_k^{k+1} \frac 1 x dx \leq \sum_{k=1}^{n} \frac 1 k$ because $\frac 1 x \leq \frac  1k$ when  $x$ is between $k$ and $k+1$.

A: Actually it is OK to use $\int_1^n{1\over x}\,dx=\ln n$ for the comparison, it just requires the extra step of noting that, since the integrand $1\over x$ is non-negative for $x\gt0$, we have $\int_1^{n+1}{1\over x}\,dx\ge\int_1^n{1\over x}\,dx$. Alternatively, one can use the non-negativity of the terms in the series to say $\sum_{k=1}^n{1\over k}\ge\sum_{k=1}^{n-1}\ge\int_1^n{1\over x}\,dx$.
The point is, the key comparison interprets each each term in the series as the area beneath a single step in a step function, each step being of width $1$, so the natural comparison for a sum of $n$ terms is an integral over an interval of length $n$.


text:
Q: remove null keys by regex I'm trying to remove null values for some key, I tried with this REGEX but it's not working. please your advice...
private static final String REMOVE_NULL_VALS_REGEX = ",\"([^\"]+)\":null|\"([^\"]+)\":null,|\"([^\"]+)\":null";

{
  "event": "111e0d4a",
  "type": "business",
  "eventProducerId": "Billing",
  "eventVersion": "1.0",
  "headerReference": {
    "activityId": "999",
  },
  "payload": {
    "trans": "Line",
    "details": {
      "plan": {
        "features": [
          {
            "featureName": "GSM",
          }
        ],
        "planName": "null"
      },
      "number": {
        "mobileNumber": "111111111"
      },
      "lineType": "GSM"
    },
    "dea": "0000002",
    "sourceBan": "null",
    "financialAccount": {
      "financialAccountNumber": "212121"
    },
    "reasonCode": "null"
  }
}

I did the convert to string and I'm trying to remove those null values with regex.

A: I recommend to you use GSON, is very easy library
You can create a pojo with this page: http://www.jsonschema2pojo.org/
And you can create a pojo (java class)
if some value is null then the value of the class be null to.
if you want see a tutorial you can see the following link: https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

A: So as Carlos Heuberger pointed out, you were looking for a colon inside the quotes and that was not matching anything. Here (between the quotation marks) is a regex suitable for replaceAll with "" in your context.
"\"[^\"]*\"[^\"]*\"null\""

The logic is like this. You look for a quote followed by some stuff besides a quote, then another quote, some stuff besides (the colon  and space typically) then "null". You replace with the empty string. The only downside, is you may leave some commas that are not needed. Assuming none of your strings have commas inside, cleaning them up is achieved by a few more lines of code (as it happens, for the example in the question it also cleans up a couple of other fishy jsons).
So the following would achieve your goal with RegEx (and the other comments and answers here may be right that it's not the best way to go -- I'm just going with your idea).
// examples from question or later comment, your choice
//public static String jStr = "{\r\n  \"event\": \"111e0d4a\",\r\n  \"type\": \"business\",\r\n  \"eventProducerId\": \"Billing\",\r\n  \"eventVersion\": \"1.0\",\r\n  \"headerReference\": {\r\n    \"activityId\": \"999\",\r\n  },\r\n  \"payload\": {\r\n    \"trans\": \"Line\",\r\n    \"details\": {\r\n      \"plan\": {\r\n        \"features\": [\r\n          {\r\n            \"featureName\": \"GSM\",\r\n          }\r\n        ],\r\n        \"planName\": \"null\"\r\n      },\r\n      \"number\": {\r\n        \"mobileNumber\": \"111111111\"\r\n      },\r\n      \"lineType\": \"GSM\"\r\n    },\r\n    \"dea\": \"0000002\",\r\n    \"sourceBan\": \"null\",\r\n    \"financialAccount\": {\r\n      \"financialAccountNumber\": \"212121\"\r\n    },\r\n    \"reasonCode\": \"null\"\r\n  }\r\n}";
public static String jStr = "{\"transactionType\":\"UCCLineAct\",\"dealerCode\":\"0000002\",\"financialAccount\":{\"financialAccountNumber\":\"110885364\"},\"lineOfServiceDetails\":{\"lineType\":\"GSM\",\"number\":{\"mobileNumber\":\"4079232335\"},\"ratePlan\":{\"planName\":\"null\",\"features\":[{\"featureId\":\"UCCGSM\",\"featureName\":\"UCC GSM\"}]}},\"reasonCode\":\"null\",\"sourceBan\":\"null\"} ";
public static void main(String args[]) {
  System.out.println(jStr);  // show before we mess with it
  jStr=jStr.replaceAll("\"[^\"]*\"[^\"]*\"null\"",""); //replace "blah" :"null"
  jStr=jStr.replaceAll("(,[ \t\r\n\f]*,)+",","); //cut repeated commas separated by at most whitespace, to a single comma
  jStr=jStr.replaceAll("\\{[ \t\r\n\f]*,","\\{"); // remove comma appearing immediately (possibly with whitespace between) after {
  jStr=jStr.replaceAll("\\[[ \t\r\n\f]*,","\\["); // remove comma appearing immediately after [
  jStr=jStr.replaceAll(",[ \t\r\n\f]*\\}","\\}"); // remove comma immediately before }
  jStr=jStr.replaceAll(",[ \t\r\n\f]*\\]","\\]"); // remove comma immediately before ]
  System.out.println(jStr); // show after
}

There may be some slicker way to include the possible commas within the regex, but it was getting too hard for me to cover all the cases. Also, in theory [ \t\r\n\f] should be replaceable with [\s], but jdoodle balked at that.


text:
Q: How to connect postgresql with LDAP user? I have a server with postgresql-9.4 fresh install and I have another server with LDAP already installed. I want to connect postgresql with LDAP user that already exists.
What's the basic configuration that I should change in /var/lib/pgsql/9.4/data/pg_hba.conf and what else I should do?

A: Thanks everyone, I just made a change in /var/lib/pgsql/9.4/data/pg_hba.conf with :
local   all         all                               ldap ldapserver=ldap.server ldapport=389 ldaptls=0 ldapprefix="uid=" ldapsuffix=",ou=People,dc=domain,dc=com"

And the authentication works!

A: *

*Read the Friendly Manual:

http://www.postgresql.org/docs/9.5/static/auth-methods.html

*You probably want to use https://github.com/larskanis/pg-ldap-sync to sync your LDAP users and groups to PostgreSQL


text:
Q: How do I find partial duplicate on first element of a delimited string? I have a pipe delimited text file that I read into a string array.  The text file will have 2 elements, and the first element could possibly have one or more duplicates.  If there are any duplicates, I want to concatenate the values into 1.
Example Text File:
ABC|111
DEF|222
GHI|333
ABC|444
JKL|555
ABC|666

In this example, "ABC" is duplicated 3 times.  I would like to concatenate the values into a single line separated with a '~' sign.
New string array values:
ABC|111~444~666
DEF|222
GHI|333
JKL|555

The order of the list is not important.  I know how to find duplicate values of an entire line using .Distinct(), but I am not sure how to do this with only the first element of the string array.  I would provide some code of my attempt, but I honestly have no idea how to even begin to achieve the desired results.  Any help is appreciated!  Thanks.
(Apologies if this post is duplicated.  I had to refresh the page.)
Edit
The text file can contain anywhere from 10,000 - 100,000 values.

A: Say for example you had parsed your input file's rows into an enumerable list of objects with Key (eg ABC) and Value (eg 111) you could sim[ply use some LINQ GroupBy to do what you want:
 var result = table.GroupBy(x => x.Key, v => v.Value)
                   .Select( g => g.Key + "|" + String.Join("~",g));

Where table is your enumerable list.
Live working code: https://rextester.com/HGP1385

var input = @"ABC|111
DEF|222
GHI|333
ABC|444
JKL|555
ABC|666";

var table = input.Split(new[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries)
    .Select(x => {
      var values = x.Split('|');
        return new { Key = values[0], Value = values[1] };
    });

var result = table.GroupBy(x => x.Key, v => v.Value)
                  .Select( g => g.Key + "|" + String.Join("~",g));

foreach(var r in result)
    Console.WriteLine(r);

A: Here's a quick one that can perhaps get you started:
Dictionary<string,List<string>> unDupe = new Dictionary<string, List<string>>();

for (int i = 0; i < yourArray.Length; i++)
{
    string[] split = yourArray[i].Split('|');
    if (unDupe.ContainsKey(split[0]))
    {
        unDupe[split[0]].Add(split[1]);
    }
    else
    {
        unDupe.Add(split[0], new List<string>() { split[1] });
    }
}

List<string> undupinated = new List<string>();

foreach (var keyValuePair in unDupe)
{
    undupinated.Add(string.Concat(keyValuePair.Key, "|", string.Join("~", keyValuePair.Value)));
}


text:
Q: Onclick animate and jump to section I have this jquery:
$('.tbl-link').click(function(){
    $('.tbl-content').animate({
        opacity: 'show',
        //height: '+=300px',
        marginTop: '330px'
    }, 1200).css({
        'display': 'block'
    });
});

$( '#info div:not(:first)' ).hide();

$('#info-nav li').click(function(e) {
    $('#info div').hide();
    $('#info-nav .current').removeClass("current");
    $(this).addClass('current');

    var clicked = $(this).find('a:first').attr('href');
    $('#info ' + clicked).fadeIn('fast');
    e.preventDefault();
}).eq(0).addClass('current');

it all works however i want to go a step further i have multiple links on a page and onclick the menu comes down and there is a section which has tabs, in that section i have 3 tabs one for each link, what i want is for if the user clicks on link 2 the menu comes down and shows section 2 for link 2, the same for link 3 but to show section 3 etc.
here is the link to the site: http://www.butterflybuns.com/area51/prices-ordering
what do i need to adjust or add to make it so?
thanks

A: One way you could do this is simply to call click on the appropriate tab.  For instance, if you click on the link related to tab 2:
$('#info-nav li').eq(1).click();


text:
Q: Using Counters in cassandra for multiple java instances Hi I am planning to use Counters  for getting a human readable unique number  in Cassandra .I have my java application running on two servers (2 instances).How can i ensure that any request at anytime fetches me a unique counter value?

A: Counters are not sequences.  Use UUIDs to generate unique identifiers instead: http://www.datastax.com/documentation/cql/3.0/webhelp/cql/cql_reference/cql_data_types_c.html

A: Implementing counters i.e (read & write) are atomic job, so  you need not have to fetch the column and then increment or decrement.
e.g update #CF set cnt1=cnt+1, cnt2=cnt2+10 where field='SOMETHING';


text:
Q: Programmatically add several buttons to an Excel worksheet with VBA I managed to programmatically add a button to a worksheet with an associated macro, but I'm having a problem when I try to add more buttons with associated macros, here is the code I use :
'Adding the first button
 With newWorkBook.Worksheets(1).Buttons
    .Add 350, 15, 173.25, 41.25
    .Caption = "Exporter"
    .OnAction = "'" & ThisWorkbook.FullName & "'!export_Click_FCM"
 End With

 'Adding the second button
 With newWorkBook.Worksheets(1).Buttons
    .Add 350, 66.25, 173.25, 41.25
    .Caption = "Ouvrir le fichier Export"
    .OnAction = "'" & ThisWorkbook.FullName & "'!open_export_FCM"
 End With

When using this code, the first button appears with the caption of the second one and with its macro associated, and the second button appears with the default caption "button2" and with no macro associated, how can I solve this problem?

A: Your first two lines of each block should be one:
With newWorkBook.Worksheets(1).Buttons.Add(350, 15, 173.25, 41.25)

so you get a reference to the added Button, not to the Buttons collection.