text:
Q: Haskell Data "Error - Control stack overflow" I'm a newbie in Haskell and I am writing my first data structure.
 data Nat = Null | N Nat

For example:   5 is N (N (N (N (N Null))))
I have to create instances from Show, Eq, Ord, Num, Enum
I wrote Eq already and it works.
instance Eq Nat where
    (==) Null Null = True
    (==) (N Null) (N Null) = True
    (==) Null (N Null) = False
    (==) Null (N xs) = False
    (==) (N xs) (N xs2) = xs == xs2

But when I try this in hugs it gives me an error ("Error- Control stack overflow").
And I can't go on.
(N (N Null)) :: Nat

What am I missing?

A: You are not covering all the cases. Also, you can simplify your definition by making a last "catch all the rest" case as follows:
instance Eq Nat where
    (==) Null   Null    = True
    (==) (N xs) (N xs2) = xs == xs2
    (==) _      _       = False

I have no idea, though, about why your code gave you a stack overflow. It should have given you a non-exhaustive match error, possibly.
Anyway, note that Hugs is now obsolete -- it went 10+ years without updates. You should switch to GHC and use ghci instead of Hugs.

If you still get stack overflows, it's likely that the issue is in the Show instance, where you could have defined an infinite recursion, as Willem Van Onsem points out above.
You should use something like
instance Show Nat where
   show Null = "Null"
   show (N x) = "(N " ++ show x ++ ")"

By the way, note that some standard instances can be automatically generated, in a correct way. For instance,
data Nat = Null | N Nat deriving (Show, Eq, Ord)

should just work as intended. It is a nice learning exercise to define these on your own, though.


text:
Q: How to start a Windows program from a remote system? I have Windows 7 (x64) running in VMware Fusion on my Mac. To make debugging apps on the Windows side from the Java side easier, I'd like to be able to start the app in Windows from the Mac side.
I'm open to running an ssh server (if that's the only solution), but the links from this question seem old and possibly out-of-date. An answer to another question recommended winexe, but I'm not sure if that'll work on windows 7.

A: After a bit of further research the session software looks promising for running commands on remote Windows PCs from a Mac using the winexe command.

A: It's possible to start programs on a remote PC using psexec under Windows. So, it may be possible to run that from Wine on the Mac, but that's a blatant piece of speculation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to add up values before and after a slash Hi I have a question related to slash.
the data I'm working on is like:
X Y Z
12/22 14/32 22/34

I would like to get the mean of the values before and after the slash.
X Y Z
17 18 28

How can I do this?

A: To get the mean of each cell even if there are more than one row in the data.frame:
as.data.frame(
  apply(dat, 1:2, function(x) {
      mean(as.integer(unlist(strsplit(x,"/"))))
    }
  )
)

A: Another solution:
as.data.frame(lapply(dat, function(x) mean(c(as.integer(sub("/.+", "", x)),
                                             as.integer(sub(".+/", "", x))))))

where dat is the name of your data frame.

A: values<-c("12/22","14/32","22/34")

> unlist(lapply(strsplit(values,"/"),function(values2){mean(as.numeric(values2))}))
[1] 17 23 28


text:
Q: .net application causing memory fragmentation I understand that only way a .NET application ( that does not use any unamanged code) can cause memory fragmentation is by large object heap. Are there any ways of detecting if your application is fragmenting memory and anyways of avoiding it?

A: *

*Keep objects small.

*Keep objects short-lived.

*Trust the GC

1 and 2 might be tough in practice but honestly, you'd be talking about BIG objects and the GC really does a good job with all this.


text:
Q: List of Strongly typed objects to list of dynamic OK. I'm trying to take a List<Product> and pass it into a method that takes a generic List<object> and loops over them to create a List<dynamic> via reflection. This method needs to be able to handle lists of other objects (ie: Item, Customer, Package, etc).
The idea is then so that I'll have a generic list of dynamic that I could send via JSON across the wire.
How can I make this happen?

A: The simplest approach is to just use LINQ to build a new list. Given that you're using .NET 4, you've got covariance available to you, so you can use:
List<object> foo = products.ToList<object>();

Or even just:
List<object> foo = new List<object>(products);

You can't pass the existing list because a List<Product> simply isn't a List<object>.
Of course if you could change your method to accept an IEnumerable<object> instead, that would work fine due to covariance. That may be feasible if you're only trying to read from the parameter collection.
Mind you, it's not clear why you need to then use reflection to create a List<dynamic> - what's your method actually doing? Why can't you just use:
List<dynamic> foo = new List<dynamic>(products);


text:
Q: How to organize C++ test apps and related files? I'm working on a C++ library that (among other stuff) has functions to read config files; and I want to add tests for this. So far, this has lead me to create lots of valid and invalid config files, each with only a few lines that test one specific functionality. But it has now got very unwieldy, as there are so many files, and also lots of small C++ test apps. Somehow this seems wrong to me :-) so do you have hints how to organise all these tests, the test apps, and the test data?
Note: the library's public API itself is not easily testable (it requires a config file as parameter). The juicy, bug-prone methods for actually reading and interpreting config values are private, so I don't see a way to test them directly?
So: would you stick with testing against real files; and if so, how would you organise all these files and apps so that they are still maintainable?

A: Perhaps the library could accept some kind of stream input, so you could pass in a string-like object and avoid all the input files? Or depending on the type of configuration, you could provide "get/setAttribute()" functions to directly, publicy, fiddle the parameters. If that is not really a design goal, then never mind. Data-driven unit tests are frowned upon in some places, but it is definitely better than nothing! I would probably lay out the code like this:
  project/
          src/
          tests/
                test1/
                      input/
                test2
                      input/

In each testN directory you would have a cpp file associated to the config files in the input directory.
Then, assuming you are using an xUnit-style test library (cppunit, googletest, unittest++, or whatever) you can add various testXXX() functions to a single class to test out associated groups of functionality. That way you could cut out part of the lots-of-little-programs problem by grouping at least some tests together.
The only problem with this is if the library expects the config file to be called something specific, or to be in a specific place. That shouldn't be the case, but if it is would have to be worked around by copying your test file to the expected location.
And don't worry about lots of tests cluttering your project up, if they are tucked away in a tests directory then they won't bother anyone.

A: Part 1.
As Richard suggested, I'd take a look at the CPPUnit test framework. That will drive the location of your test framework to a certain extent.
Your tests could be in a parallel directory located at a high-level, as per Richard's example, or in test subdirectories or test directories parallel with the area you want to test.
Either way, please be consistent in the directory structure across the project! Especially in the case of tests being contained in a single high-level directory.
There's nothing worse than having to maintain a mental mapping of source code in a location such as:
/project/src/component_a/piece_2/this_bit

and having the test(s) located somewhere such as:
/project/test/the_first_components/connection_tests/test_a

And I've worked on projects where someone did that!
What a waste of wetware cycles! 8-O Talk about violating the Alexander's concept of Quality Without a Name.
Much better is having your tests consistently located w.r.t. location of the source code under test:
/project/test/component_a/piece_2/this_bit/test_a

Part 2
As for the API config files, make local copies of a reference config in each local test area as a part of the test env. setup that is run before executing a test. Don't sprinkle copies of config's (or data) all through your test tree.
HTH.
cheers,
Rob
BTW Really glad to see you asking this now when setting things up!

A: In some tests I have done, I have actually used the test code to write the configuration files and then delete them after the test had made use of the file. It pads out the code somewhat and I have no idea if it is good practice, but it worked. If you happen to be using boost, then its filesystem module is useful for creating directories, navigating directories, and removing the files.

A: I agree with what @Richard Quirk said, but also you might want to make your test suite class a friend of the class you're testing and test its private functions.

A: For things like this I always have a small utility class that will load a config into a memory buffer and from there it gets fed into the actually config class. This means the real source doesn't matter - it could be a file or a db. For the unit-test it is hard coded one in a std::string that is then passed to the class for testing. You can simulate currup!pte3d data easily for testing failure paths.
I use UnitTest++. I have the tests as part of the src tree. So:
solution/project1/src <-- source code
solution/project1/src/tests <-- unit test code
solution/project2/src <-- source code
solution/project2/src/tests <-- unit test code

A: Assuming that you have control over the design of the library, I would expect that you'd be able to refactor such that you separate the concerns of actual file reading from interpreting it as a configuration file:

*

*class FileReader reads the file and produces a input stream,

*class ConfigFileInterpreter validates/interprets etc. the contents of the input stream

Now to test FileReader you'd need a very small number of actual files (empty, binary, plain text etc.), and for ConfigFileInterpreter you would use a stub of the FileReader class that returns an input stream to read from. Now you can prepare all your various config situations as strings and you would not have to read so many files.

A: You will not find a unit testing framework worse than CppUnit. Seriously, anybody who recommends CppUnit has not really taken a look at any of the competing frameworks.
So yes, go for a unit testing franework, but do not use CppUnit.


text:
Q: Raspberry Pi - linux-headers directory missing at the moment I'm trying to install a new driver for my PS3Eye to use it under my raspberry pi 1(The new driver is necessary for my use!). Following the instructions at http://kaswy.free.fr/?q=en/node/53 i realized that there is no linux-headers folder in /usr/src. I already tried sudo apt-get install linux headers-4.4.14 - Couldn't find any package by regex 'linux-headers-4.4.14'; sudo apt-get install linux-headers-4.4.14 - with the same error; sudo apt-get install linux-headers but the newest listed header was 3.6 version(Also did sudo apt-get update & upgrade & sudo rpi-update before) I have no clue how i could get the linux headers folder. I would be really greatful if someone of you could give me the right instructions to get this thing installed as my whole project relies on these.

A: try using apt-cache search to find the headers you need. If you are on the newest version of raspbian you can use apt search .


text:
Q: Retrieving friend's likes from the Facebook Graph API Howdy- I have been tooling around with the Facebook Graph API and successfully retrieved back a list of my likes, and a list of my friends (once I authenticated using OAuth). But what I really want to achieve is pulling back my friend's likes. When I try and do that, obviously using the same URL that I use to pull back my own likes but subbing the friend's user id for "me", I don't get anything back, unless they have installed the app as well. Then I get them no problem. To be clear, I can only see the likes of friends who have installed my application. So clearly I am running into a security/rights issue of some sort.
I could see where this would be the case; you simply aren't allowed to see your friend's likes unless they have installed the same app. Fair enough, but then how is blekko.com doing it? I even tried using FQL without much luck. I suspect I am missing something totally obvious. Anyone had any luck with this? Maybe with the Javascript API or one of the other access methods? Thanks in advance for any guidance.

A: Your application needs the permission "friends_likes".
Check http://developers.facebook.com/docs/authentication/permissions for more info on the different permissions.
This SO answer might help if you're having trouble with the authentication / permission request process.


text:
Q: How can prevent to save 2 same object in same time in my data base? and how I can test this version works correctly? We hava a gate that every vehicle submit his card and then we reduce his account.
Some times when gate officer open tow tab , two exchange save in our data base and vehicleAccount reduce twice and two same AccountExchange save in our data base .
Please help me to know how I can prevent to save 2 same Exchange in my data base.
how I can test this  version works correctly ?
I use version in my program like :
@Version private Long version = 0l
but this version doesnt increase when i change accounts in ui . all the version remain zero in all condition . I dont know why this problem occure?

A: Maybe save a timestamp when writing to the database. Everytime before you change the record you can check if the last change is longer ago than 10 seconds - or whatever time difference is reasonable for your application.

A: You can put an extra field in your table called "version". By default it is 0. Everytime you get an object you increment this version by one on your local object. When you want to save it you replace the object with ID = xxx and version = localversion-1. If you cannot find any object with this criteria someone else had saved it and therefor the version is incremented by 1 already.
Maybe Hibernate does include this already, but do not quote me on that.
Edit:
I use a @version annotation to make Hibernate handle it. But I don't know if any further configuration is necessary.


text:
Q: In Numpy, how to enforce a view to an array remain as a view? I created a view (x1) to a slice of a NumPy array.
x = np.arange(12).reshape((3,4))
x1 = x[0,:]

If I apply += operator, for example, it modifies the data of the original array x (x1 is the same view to x)
x1 += 10

However, if I apply something more complicated:
x1 = x1**2 + 10

A new array is assigned to x1 and x1 is no longer a view to x, which is not what I want.
I am wondering if there's a Pythonic way to enforce to x1 remain as a view?

A: In these cases, you should use the arr[:] syntax.
In this way, you refer to the x1 value. It can be considered as a pointer (kind of).
x1[:] = x1**2 + 10

x1
> array([10, 11, 14, 19])

x
> array([[10, 11, 14, 19],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])


text:
Q: Delete 30 days older files based on the date in the filename I received files with names in the csv format
Example:
     I want to remove the files which are older than 30 days based on the date in the filename
doesn't seem to help me much .
Do not want to use find mtime +30 days as i want to schedule every 30 days file needs to be removed based on the date in file name.

A: The following, based on arithmetic comparison of timestamps, should work :
keep_ts=$(date --date="30 days ago" +%s)
for file in $yourDir/*.csv; do
    file_ts=$(date --date="$(echo $file | cut -d_ -f3 | cut -d. -f1)" +%s)
    if [ "$file_ts" -lt "$keep_ts" ]; then
        rm "$file"
    fi
done


text:
Q: Wait for thread loop to be done I want to make a method that safely stops a thread running in a loop, allowing for the last loop to finish before returning control to the stopper.
Right now, no matter what I try, I freeze. Possibly out of deadlocks or whatnot; Java is not my usual environment, hence why this may be yet-another wait/notify question.
boolean isRunning = true;

@Override
public void run() {
    super.run();

    while (isRunning) {
        // Do work...
    }

    synchronized(this) {
        this.notify();
    }
}

public void stopSafely() {
    isRunning = false;

    try {
        synchronized(this) {
            this.wait();
        }
    } catch (InterruptedException ex) {
        // Handle...
    }
}

The problem with this approach (apart from the fact that I synchronize on this, but it's for the sake of example simplicity), is that if notify gets called before wait, the caller will freeze.
I'm sure that playing with the blocks I surround in synchronized could fix the problem, but I can't seem to get the right combination.
Any idea?

A: I hope the second method is called from a different thread that the one with the run method. I bet so.
In this case, placing the isRunning=false inside the synchronized block could be enough. Only one thread can enter a block synchronized on a given monitor.
Btw, don't call super.run(), it's useless and not a good programming habit.

A: Just go for the real simple solution:
private volatile boolean isRunning = true;

@Override
public void run() {
    while (isRunning) {
        // Do work...
    }
}

public void stopThread() {
    isRunning = false;
}

that's basically what Thread.interrupted() does internally, so you can just use this as well:
@Override
public void run() {
    while (Thread.interrupted()) {
        // Do work...
    }
}

in which case you have to call interrupt() on the thread.

A: Found a much simpler solution, which simply prevents from checking isRunning when doing the change:
boolean isRunning = true;

@Override
public void run() {
    while (true) {
        synchronized(this) {
            if (!isRunning) break;
        }

        // Do work...
    }
}

public void stopSafely() {
    synchronized(this) {
        isRunning = false;
    }
}

A: First thing to start with make isRunning volatile.
volatile boolean isRunning = true;

The problem is that java runtime do some optimization and value is not reflected in the other thread even though first thread changed the value.


text:
Q: TFS 2013 Scrum Template, how to show Features on Sprint backlog We use TFS 2013 with the Scrum 2013.4 template. We have one single project defined in a single collection.
This project contains all the backlog items for all different subsystems and their features.
To manage this backlog, we us the Portfolio Management approach.
With witadmin.exe we created another category (backlog level), as explained in this article on MSDN about Portfolio Management, under the "Add another backlog level"-section.
Only instead of "Initiative", our new category is called "Subsystem". Everything is showing up fine in TFS.
We can now categorize backlog items like this:
MainProject
--->Subsystem
------>Feature
--------->Backlog Item / Bug
------------>Task
All works fine, including different views on the backlog, where all the relations are visible
(like subsystems to features, subsystems to backlogitems, backlogitems to tasks, etc.).
The problem is that if we select the backlog of the current sprint (or any other sprint), it shows only
backlogitems and tasks, so it is unclear to which feature or subsystem the backlogitem belongs.
Is there a way to change the default query or output, so that the Sprint Backlog will also show the Features
and Subsystems in addition to the backlog items?

A: There is not.
Things in the backlog are part of the time limited execution flow and that does not represent sub system well.
You would be better adding a picklist to PBI, bug, and feature that had a list of sub systems. You would them be able to see on the item where it was for.
I usually reflect sub system in the area path and move team to a separate field.
http://nakedalm.com/team-foundation-server-2012-teams-without-areas/


text:
Q: Neo4j v4 Driver Errors in .NET My VB.NET code was working wonderfully using Imports Neo4j.v1 and Neo4j 3.x
I've upgraded to Neo4j 4.01 server on my laptop (Community Editon) and can connect and query successfully in Neo4j Desktop. I used NUGet to remove the old Neo4j reference and add Neo4j 4.01 driver. The code no longer works.
    Imports Neo4j.Driver
    Dim D = GraphDatabase.Driver(uri:=Neo4Lib.Neo4ConnectionString, authToken:=AuthTokens.Basic(Neo4Lib.Neo4UserName, Neo4Lib.Neo4Pswd))
    Using session = D.Session()
    'query database
    Dim rslt = session.run(CQ)
       .... processing ...
    End Using

It crashes are the Using session=D.Session() line with an error of

Overload resolution failed because no accessible 'Session' accepts this number of arguments.

I've studied the background materials at https://neo4j.com/docs/driver-manual/current/session-api/simple/ but cannot see the problem. I've had similar issues with Neo4j v4 on Azure with Python code.
Would appreciate suggested fixes.

A: The original problem stems from the fact that the old code you were using had the Sync code in the Neo4j.Driver package, from 4.x onwards the Neo4j.Driver package contains only Async code.
There is a Neo4j.Driver.Simple package (https://www.nuget.org/packages/Neo4j.Driver.Simple/) which would act like the 1.7x versions did. As a quick side note - it's not possible to delete a package from Nuget - once it's been published it's always there - the 1.7.2 one is here: https://www.nuget.org/packages/Neo4j.Driver/1.7.2 - at the worst - it could be hidden - but in that case you would just have to ask for the version explicitly. So you shouldn't have to worry about keeping older versions around.
I've written 3 examples (below) which show using the new driver from VB from a selection of angles, using just the Neo4j.Driver package and using Neo4j.Driver.Simple package. All 3 of them need the following Import statements (and these are basic Console apps). Also - none of them need the ConfigBuilder parameter.
'The imports
Import System
Import Neo4j.Driver
Import System.Threading.Tasks

Neo4j.Driver.Simple version
As this is the closest to the 1.7.2 version - I'll put this first:
Sub Main
    SyncVersion()
End Sub

Sub SyncVersion()
    Dim query = "MATCH (m:Movie) RETURN m"

    'NB. Driver could be in a 'Using' on this.
    Dim driver = GraphDatabase.Driver(uri:="neo4j://localhost:7687", authToken:=AuthTokens.Basic("neo4j", "neo"))

    'Open the session
    Using session = driver.Session()
        Dim result As IResult = session.Run(query)
        For Each record As IRecord In result
            Console.WriteLine(record("m").Properties("title"))
        Next
    End Using

    'Close the driver
    driver.Dispose()
End Sub

The benefits of this are that it should closely match your codebase, with minimal changes for you.
Neo4j.Driver package - using Async
This route does need you to use Async / Await:
'Note - This is also declared as Async
Async Sub Main
    AsyncVersion()
End Sub

Async Function AsyncVersion() As Task
    Dim query = "MATCH (m:Movie) RETURN m"
    Dim driver = GraphDatabase.Driver(uri:="neo4j://localhost:7687", authToken:=AuthTokens.Basic("neo4j", "neo"))

    'Open the session
    Dim session = driver.AsyncSession()

    'Get the result cursor
    Dim result As IResultCursor = Await session.RunAsync(query)

    'Loop through it
    While Await result.FetchAsync()
        Console.WriteLine(result.Current("m").Properties("title"))
    End While

    'Close the session
    Await session.CloseAsync()
    'Close the driver
    Await driver.CloseAsync()
End Function

Downsides are that you have to control the lifecycle of the Session and Driver objects yourself - i.e. you can't just use a Using statement :/
Neo4j.Driver package - Async code in a Sync way
This is the worst case scenario, as it involves you basically sync-ifying async code, using .Wait() and some very clunky ForEaching - but I thought it would fill up the examples:
'Not Async this time
Sub Main
    SyncWithAsync()
End Sub

Sub SyncWithAsync()
    Dim query = "MATCH (m:Movie) RETURN m"
    Dim driver = GraphDatabase.Driver(uri:="neo4j://localhost:7687", authToken:=AuthTokens.Basic("neo4j", "neo"))

    'Open the session
    Dim session = driver.AsyncSession()

    'Get the result cursor
    Dim resultTask As Task(Of IResultCursor) = session.RunAsync(query)
    resultTask.Wait()

    'Loop through it, but as we're 'syncing' an async, we need to wait for 'fetch' to work.
    Dim fetchTask = resultTask.Result.FetchAsync()
    fetchTask.Wait()
    While fetchTask.Result
        Console.WriteLine(resultTask.Result.Current("m").Properties("title"))
        fetchTask = resultTask.Result.FetchAsync()
        fetchTask.Wait()
    End While

    'Close the session
    session.CloseAsync().Wait()

    'Close the driver
    driver.CloseAsync().Wait()
End Sub

You still have to manage the life cycle of the Session and Driver instances.
Hope that helps

A: The solution: the session was run asynch and, as Hursey suggested above, it did require a ConfigBuilder argument, even though it was "Nothing". The return is different than my code for Neo4j 3.x, so I need to write new parsing code ... but I now have something to work with!
    Imports Neo4j.Driver

    CQ={neo4j cypher query}
    Dim D = GraphDatabase.Driver(uri:=Neo4Lib.Neo4ConnectionString, authToken:=AuthTokens.Basic(Neo4Lib.Neo4UserName, Neo4Lib.Neo4Pswd))
    Dim cb As ConfigBuilder = Nothing

    Using session = D.AsyncSession(cb)
     'query database
        Dim rslt As System.Threading.Tasks.Task = session.RunAsync(CQ)
              {process IResultCursor}
    End Using


text:
Q: Concurrent deletion and field access Is it legal for a second thread to delete an object while a first thread is still potentially inside a member function of that object, if the deletion occurs after the last (explicit) field access inside that function?
This will probably be clearer with an example:
#include <thread>
#include <atomic>

struct handoff {
    std::atomic<int> flag{};

    void signal() { flag = 1; }
};

int main() {
    auto h = new handoff;

    auto t2 = std::thread([=]{
        while (!h->flag) {
        }
        delete h;
    });

    h->signal();

    t2.join();
}

Here, the handoff h object is used to communicate between T1 (the main thread) and T2. The flag field is initially zero, and T2 waits until it becomes non-zero then immediately deletes the h object. T1 calls h->signal() which sets the flag to non-zero. So the object will be deleted (by T2) while T1 is still potentially "inside" the signal() call. However, there are no further accesses to any fields of the handoff object in signal().
Is it defined behavior? I think it is clear that calling a member function (even an empty one) is UB after an object has been deleted, but how about returning from one?
TSAN thinks this is OK and I agree in practice this will work fine on sane architectures.

A: Your code is safe. There is no such concept of being "inside" an object. You either access (as in: read write) the object or not. Method or not, its just a function. However in your concrete case accessing this after flag = 1 line in signal method is not safe. So it is a matter of concrete code, not of being inside or not.
Also you are correct that calling a member function after delete is UB. But that's not the case. The "call" event already happened before delete, that is not UB.


text:
Q: For comprehension with Future[String] and Future[List[String]] Simplified code:
val one: Future[String] = Future("1")
val many: Future[List[String]] = Future({"1","2","3"})

for {
  a <- one
  b <- many
} yield {
  doSomething(a,b) // Type mismatch, expected String, actual: List[String]
}

What I want to happen is to call for each couple of one/many and get a list of the outputs
 {doSomething("1","1"),doSomething("1","2"),doSomething("1","3")}

Can I get this to work with for comprehensions even when one is a Future[String] and the other a Future[List[String]]?

A: Try
  val one: Future[String] = Future("1")
  val many: Future[List[String]] = Future(List("1","2","3"))

  def doSomething(a: String, b: String) = ???

  for {
    a <- one
    b <- many
  } yield {
    b.map(v => doSomething(a, v))
  }

Alternatively we could use scalaz ListT transformer like so
  import scalaz._
  import ListT._
  import scalaz.std.scalaFuture.futureInstance

  val one: Future[String] = Future("1")
  val many: Future[List[String]] = Future(List("1","2","3"))

  def doSomething(a: String, b: String) = ???

  for {
    a <- listT(one.map(v => List(v)))
    b <- listT(many)
  } yield {
    doSomething(a, b)
  }


text:
Q: Is it possible to fake Useragent in C#? I want to create a crawler with C#. The problem is that some websites have disabled black listed crawlers in their robots.txt file, using:
User-agent: *
Disallow: /

Is there a way I could fake my request to show that I'm for instance Googlebot?

A: HttpWebRequest has .UserAgent, however - I would simply say: don't.
Of course, your point re robots.txt is rather moot; that is for you to follow. If you write a badly behaved tool that ignores robots.txt regardless of what you claim as your user-agent, then you should expect to be blacklisted fairly quickly.
In particular, trying to impersonate any of the major players is very dubious. Frankly I'd expect most major sites to also check the incoming IP range.

A: Yes, the HttpWebRequest has a property for user agent. You can set that to anything.


text:
Q: how to validate firebase otp from api using php/laravel backend I have a flutter app that send opt using firebase . problem is that when I send OTP from flutter app there no way to store that OTP in backend database for confirming.

A: you can verify the otp from firebase directily by using below function
await _firebaseAuth!.verifyPhoneNumber(
    phoneNumber: "+91${widget.phoneNumber}",
    timeout: const Duration(seconds: 60),
    verificationCompleted: verificationCompleted,
    codeSent: codeSent,);

final PhoneVerificationCompleted verificationCompleted =
    (AuthCredential phoneAuthCredential) {
  Utility.showLoadingDialog();
      print("in phone verification");
  _firebaseAuth!.signInWithCredential(phoneAuthCredential)
      .then((value) async {
    handleNavigation(value);

  }).catchError((error) {
    print("in error");
    print(error);
    Get.back();
    // showErrorMessage("Try again in sometime");
  });
};

final PhoneCodeSent codeSent =
    (String verificationId, int? resendToken) async {
      Timer(
          const Duration(seconds: 15),
              () {
                // setState(() {
                  otpSendTimeOut = true;
                // });
              });
  // Update the UI - wait for the user to enter the SMS code
  String smsCode = 'xxxx';
  setState(() {
    _verificationId = verificationId;
  });
  utils.Utility().showSuccessMessage("OTP sent successfully");

};


text:
Q: What metrics are being considered for evaluating "success" of a site in public beta? Now that there are number of area51 sites in public beta, I was wondering what metrics were being considered to determine which (if any) of the sites would make it to non-beta stage. I understand that the beta period is 90 days, so the metrics might not be laid out yet, so this is more of a 'what are the SE overlords thinking' kind of question.

A: The thinking is don't publish some kind of crazy, convoluted "You must be THIS tall to ride" equation until you have sites and data to test it on. You can see from our current crop of sites that we haven't hit that "Oy! This has got to go, ASAP" scenario. So, anything we come up with today will probably make no sense a few weeks from now.
When you see that a site doesn't work, you look at it and ask "why?" "Can it be fixed or does it need to end?" "What other fail scenarios do we have to consider?" Then you look at whatever criteria you feel where that site falls short and set the bar just above that point.
Sites will vary widely in size and purpose. Two posts per day on a "Mesothelioma Treatment" site might be a block buster for that community. Two posts per day on a video game site would be an epic fail.

A: Not only is there very little experience in what makes a SE-type site successful, quantitative critera can be gamed.  In the pre-commitment phase, there's a temptation to only vote questions on- or off-topic if they seem likely to hit 20 net votes.  I don't think that's a big problem, but going from public beta to permanent is one of the most important decisions, and really shouldn't be easily gamable.


text:
Q: Java - read file line by line - with pagination I am trying to implement a simple log reader and for that I looking for a java framework (e.g. apache commons io) which does the following -

*

*reads a text file line by line

*provides a paging functionality - i.e. I should be able to mention the number of lines I need to read from file + get the lines from the next page start - say 50th line to 100 th line

Is there any standard framework which does this ? (dont want to reinvent the wheel here)

A: Enough to help you get started!
Scanner scanner = new Scanner(new FileReader("myFile.txt");

while(scanner.hasNext()) {
    String line = scanner.next();
    System.out.println(line);
}


text:
Q: npm install, can't type Y/n in cmd I am trying to setup a react-js website, and when I do npm install, it asks me:
Building the Webpack DLL...
[webpack-cli] For using 'build' command you need to install: 'webpack' package.
[webpack-cli] Would you like to install 'webpack' package? (That will run 'npm install -D webpack') (Y/n)

The problem is, it is impossible to type anything. I tried cmd, powershell, git bash. It does not allow me to type. Why is this happening?
When I run the actual command npm install -D webpack it executes. But when I run npm install to continue installing, the same thing happens again, again asking me to type Y/n as if webpack wasn't installed already.


text:
Q: How to allow certain characters in input field How can i allow only "A-Za-z0-9 &#$._-" along with "/" . I tried with jquery
$('.allow').bind('keyup blur',function(){

   $(this).val( $(this).val().replace(/[^A-Za-z0-9 &#$._-]/g,' ') ); }

);

Along with this i also need to allow forward slash "/".
Can anyone please help me out. It will be a great help.

A: Use ^ and $ outside of []. This will match only the allowed characters.
You need to escape the / and - in regex
/^[a-z0-9 &#$._\-\/]$/i

A:

$('.allow').bind('keyup blur',function(){

   $(this).val( $(this).val().replace(/[^A-Za-z0-9\\ &#$._-]/g,' ') ); }

);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="allow"/>


text:
Q: Google API key no response on Google+ API I took following code :
<?php

$url = "http://www.tomanthony.co.uk/";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p",
"params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer",
"groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

$curl_results = curl_exec ($ch);
curl_close ($ch);

$parsed_results = json_decode($curl_results, true);

echo $parsed_results[0]['result']['metadata']['globalCounts']['count'];

?>

From Here
And tried it in my test page , it works flawlessly.
Then i went to google developer console , registred new app , selected Google+ API and rendered new keys (browser,server, android) and tried to use each of them with this script. None work.
What am i doing wrong here ? Can someone point out ?
I tried playing around with keys , like giving them domain from which they should be invoked , etc. But that doesnt seem to be the problem. Apache is not generating any error logs, and in developer-console (networking) i am getting 200 , in response : NO RESPONSE
Can someone point out what am i doing wrong , is there something in google developer console that i am missing ?


text:
Q: VB Code to Close Open Subfolders in Outlook Outlook has an habit of opening sub-folders if an email has been sent to it automatically (through rules). There is no way to turn off this feature.
Does anyone have ideas for code that would periodically (say every 30 seconds), automatically collapse all subfolders within, say, the sent items folder?
Thx

A: The Outlook object model doesn't provide anything for collapsing folders in the navigation pane.
The Starting Outlook with all folders collapsed/expanded states the following:

To keep the mailbox collapsed even when a new message is being delivered, make sure that your Inbox and other folders that receive email (for instance by a rule) have been added to your Favorites list.


text:
Q: Smush.It Cron How to enable I have just installed a Magento extension for Smush.it and image optimization extension however when I go into the tool, it tells me that
The Magento CRON is not set up. Please set up your Magento CRON for Smush.it to function correctly.
Please can someone advise as to how I can enable cron for this module

A: you did not enable the cronjob for magento itself I think?
The cronjob runs tasks for magento in the background in a defined intervall.
To setup the magento cronjob, you need access to your server (via ssh) or contact your hosting provider.
You need to add the following entry in your crontab to run the magento cronjob every minute:
* * * * * /bin/sh /path/to/your/magento/root/cron.sh

To edit your crontab, you can run the following command:
crontab -e -u your-webservers-user


text:
Q: How to refactor adding properties to json through nvl2 to avoid repetition? We are creating json of tag names and respective tag values:
[
  "name": "bob",
  "surname": "dylan",
  ...
]

This is done through first creating a main select, and then through that including tens of nvl2 functions to call the appropriate procedures for getting the value of each tag:
select u_json_pck.JsonPropertyObject(null,
           nclob_tt(
                    nvl2(ExecuteSelectToCheckIfValueExists(),
                         U_JSON_PCK.JsonProperty('TAG_NAME', ExecuteAVerySimilarSelectToGetValue()),
                         decode(v_remove_empty_tags, 1,
                                U_JSON_PCK.JsonProperty('TAG_NAME', ''), null)),
                    nvl2(......),
                    nvl2(...)...

(1) check if any value exists (e.g., for a tag "meetingParticipants" no participants might exist)
(2) if it exists, then call the procedure that actually gets that value and forms it into necessary nclob, and add this and the tag to json
(3) if it doesn't exist, then check if empty tags should be added to json, and then either add an empty one or don't add one
Can this be refactored so that ExecuteSelectToCheckIfValueExists() isn't called at all? We could check v_remove_empty_tags in the ExecuteAVerySimilarSelectToGetValue() and then, if this function finds no results, return -1 or null. But how to form the appropriate json out of that result?

A: I don't know what your function u_json_pck and type nclob_tt do exactly, but why not do this with the built-in JSON syntax something like:
select json_object
         ( 'myobject' value json_arrayagg
                            ( json_object
                                ( 'tag_name1'  value value1
                                , 'tag_name2'  value value2
                                , 'tag_name3'  value value3
                                absent on null
                                )
                              returning clob
                             )
         ) json_data
  from
  ( select null value1, 'BBB' value2, 'CCC' value3 from dual
    union all
    select null value1, 'BBB' value2, null value3 from dual
    union all
    select 123 value1, null value2, 'DDD' value3 from dual
    union all
    select 456 value1, 'EEE' value2, null value3 from dual
  );

which returns:
{
  "myobject": [
    {
      "tag_name2": "BBB",
      "tag_name3": "CCC"
    },
    {
      "tag_name2": "BBB"
    },
    {
      "tag_name1": 123,
      "tag_name3": "DDD"
    },
    {
      "tag_name1": 456,
      "tag_name2": "EEE"
    }
  ]
}

You just need to change absent on null to null on null according to the value of v_remove_empty_tags - so either have a separate select statement for each, or construct the SQL dynamically to specify that.


text:
Q: SDK path is empty in Notepad++ plugin.net I'm trying to develop a Notepad++ plugin using a nppPlugin.netV0.6 template.
Downloaded from http://sourceforge.net/projects/sourcecookifier/files/other%20plugins/NppPlugin.NET.v0.6.zip/download
I got a build error [SDK path is empty.]
The same template is working in other system (XP also).
Can anyone give me an resolution for this issue?

A: The build process calls program ildasm.exe. The directory for that program may not have been added to the PATH environment variable. When I installed Visual Studio 2012 Express installer the directory was not added so I added it to the PATH and the build succeeded.
I tracked the problem down by increasing the amount of logging output written by the build process. (Via Tools => Options => Projects and Solutions => Build and run => MS Build ... verbosity.)
Not sure whether your error is identical. Before adding the directory to the PATH the errors below were generated:
1>------ Rebuild All started: Project: NppManagedPluginDemo.VS2010, Configuration: Debug Any CPU ------
1> NppManagedPluginDemo.VS2010 -> C:\Adrian\VS\NppPlugin.NET.v0.5\Demo Plugin\NppManagedPluginDemo\bin\Debug\Demo.dll
1> ILDasm: calling 'ildasm.exe' with /quoteallnames /unicode /nobar /linenum "/out:C:\Users\Adrian_2\AppData\Local\Temp\tmpAB1F\Demo.il" "C:\Adrian\VS\NppPlugin.NET.v0.5\Demo Plugin\NppManagedPluginDemo\bin\Debug\Demo.dll"
1>C:\Adrian\VS\NppPlugin.NET.v0.5\Demo Plugin\NppManagedPluginDemo\DllExport\NppPlugin.DllExport.targets(8,5): error : The system cannot find the file specified

There are several versions of ildasm.exe in sub directories of c:\Program Files (x86)\Microsoft SDKs\Windows\ of my current computer.


text:
Q: Вывести 5 самых популярных ингрдиентов Здравсвтуйте! У меня есть БД со списком коктейлей, в ней хранятся записи о коктейле и его ингредиентах. Мне нужно вывести 5 самых используемых игредиентов из бд, которые являются алкогольными. Пробовал сделать такой запрос в БД:
SELECT MAX(COUNT`component_id`)
FROM `cocktails`
WHERE `component_typeName`='alkohol' OR `component_typeName`='likier'
LIMIT (1,5)

Сама структура БД вот такая:

Суть в том, что у меня есть коктейль в нем ингрдиенты, и получается если у меня 5 ингрдиентов в коктейле у меня 5 записей, в которых будет отличаться id и информация о компоненте, если 2 ингредиента - 2 записи. Надеюсь, понятно все объяснил.
Заранее спасибо!


text:
Q: Custom UITableView - iOs I followed this tutorial on  creating a simple rss reader...
http://www.kieranmcgrady.com/blog/2012/4/25/tutorial-how-to-create-a-simple-rss-reader-for-ios.html
The problem is that I am having problem with design since everything is done programmatically.
How would i go about making each cell a square that takes up the page and if i scroll down, it will go down to a new page showing the next cell?

A: It sounds like you are attempting to replicate the functionality of Reeder. If that's the case, you may find this article and GitHub project helpful.

A: You'd be better off (I think) using your own UIViewControllers with their own text/images and adding their views to a UIScrollView with paging enabled. If you are looking for some tutorials on how to use UIScrollView to achieve this perhpas this will be useful. Chances are you won't find exactly what you are looking for, you just need to divide your problem and then look for solutions. i.e. Read RSS feed. Create UIScrollView with pages. Create custom ViewControllers.


text:
Q: How to checksum a CD/DVD? (to verify integrity of my Debian installation) So I'd like to checksum my Debian 9.0 installation DVD to be able to compare it to the respective .iso file's hashes and the published hashes to be able to verify my installation's integrity.

I burned the Debian installation .iso to DVD under Ubuntu. There it had a problem verifying the DVD's checksum as it didn't proceed anymore at around 50% with the time remaining only rising and rising. However this may due to the fact that I accidentally executed sha512 (it had an error and didn't seem to have modified the .iso) instead of sha512sum on the .iso file during burning or checksumming. (The sha512 hash of the .iso was correct.)

I'd like to use sha512 and it seems I need the blocksize in bytes of my DVD first.
These 2 questions help but do not solve this issue for me:

*

*Calculate md5sum of a CD/DVD

*How to verify a CD against an ISO image?
Edit: Related question / finding of mine

A: Install the package genisoimage like this:
apt-get install genisoimage

It will install a program isoinfo which will report the number of sectors in the disk (assuming the CD device is sr0):
$ isoinfo dev=/dev/sr0 -d
CD-ROM is in ISO 9660 format
System id: C@-RTKS C@-BRIDCE
Volume id: antartica
Volume set id:
Publisher id:
Data preparer id:
Application id: CAUAF File System - Adaptec
Copyright File id:
Abstract File id:
Bibliographic File id:
Volume set size is: 1
Volume set sequence number is: 1
Logical block size is: 2048
Volume size is: 297247
NO Joliet present
NO Rock Ridge present

And, if that command is succesful, you will get some details about the disk.
Read the "Logical block size" (usually 2048) and the "Volume size"
And execute the commands below:
$ a=2048                # Block size read above.
$ b=297247              # Volume size. Near 300.000 for a 600Mega disk
$ dd if=/dev/sr0 bs="$a" count="$b" | md5sum

That will give you the MD5 hash. If you need a sha512 hash, use:
$ dd if=/dev/sr0 bs="$a" count="$b" | sha512sum

Reading a whole disk will take some time, be patient.

A: There would be far easier burning new DVD with checksummed image then doing a checksum of burned image cause that will take a long time.
Also @arrow gave you the best option if you really need to check the status of your burned ISO.
Today people are more often doing dd to the USB drive and installing from there. There are a lot of laptops without internal CD/DVD drive and NAND memory is harder to corrupt, you can't really scratch it like the DVD.


text:
Q: Gradle root project with multiple applications How do I create a gradle root project with multiple applications that use the same library.  I'm wanting to end up with tar and zip files containing:
RootProject/
  bin/
    Command1
    Command2
    ...
  lib/
    Library.jar
    ..

I created a gradle root project, the library sub-project, and several application sub-projects:
RootProject/
  settings.gradle
  build.gradle
  common.gradle
  Library/
    build.gradle
    src/main/java/Library.java
  Command1/
    build.gradle
    src/main/java/Command1.java
  Command2/
    build.gradle
    src/main/java/Command2.java

My current root project's build.gradle:
apply plugin: 'base' // To add "clean" task to the root project.

allprojects {
    repositories {
        mavenCentral();
    }
}

subprojects {
    apply plugin: 'java'

    group = 'edu.csusb.ecs.gmailsettings'
    version = '1.0-SNAPSHOT'

    dependencies {
        testCompile group: 'junit', name: 'junit', version: '4.10'
    }
}

task build(type: Copy) {
    dependsOn subprojects.build
    from subprojects.collect { it.tasks.withType(Jar) }
    into project.rootProject.buildDir.toString() + "/libs"
}

task clean(group:project.rootProject.ext.group, type: Delete, description:"clean jars from subprojects") {
    delete fileTree(project.buildDir).include('**/*')
}

results in an error

org.gradle.tooling.BuildException: Could not run build action using
  Gradle distribution
  'https://services.gradle.org/distributions/gradle-4.5.1-bin.zip'.     at
  org.gradle.tooling.internal.consumer.ExceptionTransformer.transform(ExceptionTransformer.java:51)
    at
  org.gradle.tooling.internal.consumer.ExceptionTransformer.transform(ExceptionTransformer.java:29)
    at
  org.gradle.tooling.internal.consumer.ResultHandlerAdapter.onFailure(ResultHandlerAdapter.java:41)
    at
  org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:57)
    at
  org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at
  org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at
  org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)    at
  org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
    at
  org.gradle.tooling.internal.consumer.DefaultBuildActionExecuter.run(DefaultBuildActionExecuter.java:60)
    at
  org.netbeans.gradle.model.GenericModelFetcher.getModels(GenericModelFetcher.java:168)
    at
  org.netbeans.gradle.project.model.NbGradle18ModelLoader$ProjectModelFetcher.getModels(NbGradle18ModelLoader.java:379)
    at
  org.netbeans.gradle.project.model.NbGradle18ModelLoader.loadModels(NbGradle18ModelLoader.java:68)
    at
  org.netbeans.gradle.project.model.DefaultGradleModelLoader.loadModelWithProgress(DefaultGradleModelLoader.java:559)
    at
  org.netbeans.gradle.project.model.DefaultGradleModelLoader.access$1600(DefaultGradleModelLoader.java:64)
    at
  org.netbeans.gradle.project.model.DefaultGradleModelLoader$6.run(DefaultGradleModelLoader.java:419)
    at
  org.netbeans.gradle.project.tasks.GradleDaemonManager.runNonBlockingGradleTask(GradleDaemonManager.java:35)
    at
  org.netbeans.gradle.project.tasks.GradleDaemonManager.access$100(GradleDaemonManager.java:22)
    at
  org.netbeans.gradle.project.tasks.GradleDaemonManager$2.execute(GradleDaemonManager.java:125)
    at
  org.jtrim.concurrent.AbstractTaskExecutorService$FunctionWrapper.execute(AbstractTaskExecutorService.java:270)
    at
  org.jtrim.concurrent.AbstractTaskExecutorService$TaskOfAbstractExecutor.execute(AbstractTaskExecutorService.java:340)
    at
  org.jtrim.concurrent.Tasks$RunOnceCancelableTask.execute(Tasks.java:342)
    at
  org.jtrim.concurrent.SingleThreadedExecutor$QueuedItem.runTask(SingleThreadedExecutor.java:919)
    at
  org.jtrim.concurrent.SingleThreadedExecutor$QueuedItem.access$1200(SingleThreadedExecutor.java:898)
    at
  org.jtrim.concurrent.SingleThreadedExecutor$Impl$Worker.executeTask(SingleThreadedExecutor.java:815)
    at
  org.jtrim.concurrent.SingleThreadedExecutor$Impl$Worker.processQueue(SingleThreadedExecutor.java:827)
    at
  org.jtrim.concurrent.SingleThreadedExecutor$Impl$Worker.run(SingleThreadedExecutor.java:861)
    at
  org.jtrim.concurrent.SingleThreadedExecutor$Impl$1.run(SingleThreadedExecutor.java:453)
    at java.lang.Thread.run(Thread.java:748) Caused by:
  org.gradle.internal.exceptions.LocationAwareException: Build file
  '/Users/000017913/Development/GmailSettings/build.gradle' line: 20 A
  problem occurred evaluating root project 'GmailSettings'.     at
  org.gradle.initialization.DefaultExceptionAnalyser.transform(DefaultExceptionAnalyser.java:74)
    at
  org.gradle.initialization.MultipleBuildFailuresExceptionAnalyser.transform(MultipleBuildFailuresExceptionAnalyser.java:47)
    at
  org.gradle.initialization.StackTraceSanitizingExceptionAnalyser.transform(StackTraceSanitizingExceptionAnalyser.java:30)
    at
  org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:137)
    at
  org.gradle.initialization.DefaultGradleLauncher.getConfiguredBuild(DefaultGradleLauncher.java:104)
    at
  org.gradle.internal.invocation.GradleBuildController$2.call(GradleBuildController.java:87)
    at
  org.gradle.internal.invocation.GradleBuildController$2.call(GradleBuildController.java:84)
    at
  org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
    at
  org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
    at
  org.gradle.internal.invocation.GradleBuildController.configure(GradleBuildController.java:84)
    at
  org.gradle.tooling.internal.provider.runner.ClientProvidedBuildActionRunner.run(ClientProvidedBuildActionRunner.java:64)
    at
  org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at
  org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at
  org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at
  org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at
  org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at
  org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at
  org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:49)
    at
  org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:32)
    at
  org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at
  org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at
  org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at
  org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at
  org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
    at
  org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
    at
  org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at
  org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at
  org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at
  org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at
  org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
    at
  org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
    at
  org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at
  org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at
  org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
    at
  org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at
  org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at
  org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at
  org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at
  org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at
  org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at
  org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at
  org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at
  org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at
  org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at
  org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at
  org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)    at
  org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at
  org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at
  org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at
  org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at
  org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at
  org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at
  org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at
  org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
    at
  org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at
  org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at
  org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at
  org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at
  org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at
  org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at
  org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
  Caused by: org.gradle.api.GradleScriptException: A problem occurred
  evaluating root project 'GmailSettings'.  at
  org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
    at
  org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:204)
    at
  org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:77)
    at
  org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:209)
    at
  org.gradle.configuration.BuildOperationScriptPlugin$1.run(BuildOperationScriptPlugin.java:61)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at
  org.gradle.configuration.BuildOperationScriptPlugin.apply(BuildOperationScriptPlugin.java:58)
    at
  org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:41)
    at
  org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
    at
  org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
    at
  org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:64)
    at
  org.gradle.configuration.project.LifecycleProjectEvaluator.access$100(LifecycleProjectEvaluator.java:34)
    at
  org.gradle.configuration.project.LifecycleProjectEvaluator$ConfigureProject.run(LifecycleProjectEvaluator.java:110)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at
  org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:50)
    at
  org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:667)
    at
  org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:136)
    at
  org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
    at
  org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:60)
    at
  org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:38)
    at
  org.gradle.initialization.DefaultGradleLauncher$ConfigureBuild.run(DefaultGradleLauncher.java:249)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at
  org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at
  org.gradle.initialization.DefaultGradleLauncher.configureBuild(DefaultGradleLauncher.java:167)
    at
  org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:126)
    ... 62 more Caused by: org.gradle.api.InvalidUserDataException:
  Declaring custom 'build' task when using the standard Gradle lifecycle
  plugins is not allowed.   at
  org.gradle.language.base.plugins.LifecycleBasePlugin$7.execute(LifecycleBasePlugin.java:142)
    at
  org.gradle.language.base.plugins.LifecycleBasePlugin$7.execute(LifecycleBasePlugin.java:138)
    at
  org.gradle.internal.ImmutableActionSet$CompositeSet.execute(ImmutableActionSet.java:196)
    at
  org.gradle.internal.MutableActionSet.execute(MutableActionSet.java:35)
    at
  org.gradle.api.internal.DefaultDomainObjectCollection.doAdd(DefaultDomainObjectCollection.java:204)
    at
  org.gradle.api.internal.DefaultDomainObjectCollection.add(DefaultDomainObjectCollection.java:198)
    at
  org.gradle.api.internal.DefaultNamedDomainObjectCollection.add(DefaultNamedDomainObjectCollection.java:93)
    at
  org.gradle.api.internal.tasks.DefaultTaskContainer.addTask(DefaultTaskContainer.java:101)
    at
  org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:81)
    at
  org.gradle.api.internal.project.DefaultProject.task(DefaultProject.java:1209)
    at
  org.gradle.internal.metaobject.BeanDynamicObject$MetaClassAdapter.invokeMethod(BeanDynamicObject.java:479)
    at
  org.gradle.internal.metaobject.BeanDynamicObject.tryInvokeMethod(BeanDynamicObject.java:191)
    at
  org.gradle.internal.metaobject.CompositeDynamicObject.tryInvokeMethod(CompositeDynamicObject.java:98)
    at
  org.gradle.internal.metaobject.MixInClosurePropertiesAsMethodsDynamicObject.tryInvokeMethod(MixInClosurePropertiesAsMethodsDynamicObject.java:30)
    at
  org.gradle.groovy.scripts.BasicScript$ScriptDynamicObject.tryInvokeMethod(BasicScript.java:134)
    at
  org.gradle.internal.metaobject.AbstractDynamicObject.invokeMethod(AbstractDynamicObject.java:160)
    at
  org.gradle.groovy.scripts.BasicScript.invokeMethod(BasicScript.java:83)
    at
  build_dycfbq39lcq7wcyu7h089vex6.run(/Users/000017913/Development/GmailSettings/build.gradle:20)
    at
  org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
    ... 94 more

A: in my root projects build.gradle I defined a task to copy all subprojects jar files into the /build/libs folder of the root project like this:
task build(type: Copy) {
    dependsOn subprojects.build
        // from subprojects.collect { it.tasks.withType(AbstractArchiveTask) }
        from subprojects.collect { it.tasks.withType(Jar) }
        into project.rootProject.buildDir.toString() + "/libs"
}

task clean(group:project.rootProject.ext.group, type: Delete, description:"clean jars from subprojects") {
    delete fileTree(project.buildDir).include('**/*')
}

you should be able to copy any other build artefacts to the root project in a similar way.

A: Thanks for your help all. The following, derrived from your input seems to work.
task copyJars(type: Copy) {
    dependsOn subprojects.build
    from subprojects.collect { it.tasks.withType(Jar) }
    into project.rootProject.buildDir.toString() + "/libs"
}

task copyDependencies(type: Copy) {
    from subprojects.collect { it.configurations.runtime }
    into project.rootProject.buildDir.toString() + "/libs"
}

task copyStartScripts(type: Copy) {
    dependsOn copyJars
    from subprojects.collect { it.tasks.withType(CreateStartScripts) }
    into project.rootProject.buildDir.toString() + "/scripts"
}

task createDistribution() {
    apply plugin: 'distribution'

    distributions {
        main {
            contents {
                from(copyStartScripts) {
                    into "bin"
                    fileMode = 0755
                }
                from(copyJars) {
                    into "lib"
                }
                from(copyDependencies) {
                    into "lib"
                }
            }
        }
    }
}


text:
Q: Is it true that $\sigma(X_1,X_1+X_2)=\sigma(X_1,X_2)$? Given a sequence $(X_k)_{k\in\mathbb{N}}$ of real centered r.v.'s, and a sequence $(Y_n)_{n\in\mathbb{N}}$ defined by
$$Y_n = X_1 + ..+X_n$$
it is stated, in a chapter on martingales of the book I'm studying, that
$$\sigma(Y_1,..,Y_m)=\sigma(X_1,...X_m)$$
without any hint for a proof, as if it were trivial.
All I know, in general, is that $\sigma(X_n+X_m)\subseteq\sigma(X_n,X_m)$, which should imply that  $\sigma(X_n,X_n+X_m)\subseteq\sigma(X_n,X_m)$. But how to go from here?
The source is: P. Baldi, Stochastic Calculus - An Introduction Through Theory and Exercises, Springer, Section 5.1, page 109.

A: Elaborating on my comment:
For a measurable function $f$,
$$\sigma(f(X)) \subseteq \sigma(X),$$
since a set $\{\omega : f(X(\omega)) \in B\}$ can be expressed as $\{\omega : X(\omega) \in f^{-1}(B)\}$. This also holds if $X$ is a random vector $X=(X_1, \ldots, X_m)$.

Since $Y_i = X_1 + \cdots + X_i$, we therefore have $\sigma(Y_i) \subseteq \sigma(X_1, \ldots, X_m)$ for $i \le m$. Consequently, $\sigma(Y_1, \ldots, Y_m) \subseteq \sigma(X_1, \ldots, X_m)$.
Conversely, since $X_1 = Y_1$ and $X_i = Y_i - Y_{i-1}$ for $i \ge 2$, we have $\sigma(X_i) \subseteq \sigma(Y_1, \ldots, Y_m)$ for $i \le m$, and thus $\sigma(X_1, \ldots, X_m) \subseteq \sigma(Y_1, \ldots, Y_m)$.


text:
Q: redirect landing without changing url I'm working with Apache and Joomla. I would like to have some URIs that land to the same landing page, but avoiding the URL changes.
So, for example:
examplecom/luggage/delay/iberia
examplecom/luggage/delay/aireuropa
examplecom/luggage/delay/ryanair
Need to point to examplecom/luggage/delay but the address bar must show the different airline companies.
I've been messing arround with mod_rewrite with the following codes:
1:
RewriteCond %{REQUEST_URI}  /equipaje/problemas-de-equipaje/perdida-equipaje-iberia [NC,OR]
RewriteCond %{REQUEST_URI}  /equipaje/problemas-de-equipaje/perdida-equipaje-vueling [NC,OR]
RewriteCond %{REQUEST_URI}  /equipaje/problemas-de-equipaje/perdida-equipaje-ryanair [NC,OR]
RewriteCond %{REQUEST_URI}  /equipaje/problemas-de-equipaje/perdida-equipaje-aireuropa [NC,OR]
RewriteRule ^(.*)$  /equipaje/problemas-de-equipaje/perdida-equipaje [P]

2:
RewriteRule ^equipaje/problemas-de-equipaje/perdida-equipaje-iberia equipaje/problemas-de-equipaje/perdida-equipaje [NC,L]
RewriteRule ^equipaje/problemas-de-equipaje/perdida-equipaje-vueling equipaje/problemas-de-equipaje/perdida-equipaje [NC,L]
RewriteRule ^equipaje/problemas-de-equipaje/perdida-equipaje-ryanair equipaje/problemas-de-equipaje/perdida-equipaje [NC,L]
RewriteRule ^equipaje/problemas-de-equipaje/perdida-equipaje-aireuropa equipaje/problemas-de-equipaje/perdida-equipaje [NC,L]

The idea is to have different urls for AdWords but then I'll avoid the indexing of that company landpages to avoid replicated content.
I've been searching for several examples and trying to understand how the module works, but until now I haven't acomplished with that...
Is it possible to do that with mod_rewrite?
Many thanks!

A: You can't use two localpaths using flag [P], but if you take your first try and change the rewrite rule to use the full url, it should work:
RewriteCond %{REQUEST_URI}  /equipaje/problemas-de-equipaje/perdida-equipaje-iberia [NC,OR]
RewriteCond %{REQUEST_URI}  /equipaje/problemas-de-equipaje/perdida-equipaje-vueling [NC,OR]
RewriteCond %{REQUEST_URI}  /equipaje/problemas-de-equipaje/perdida-equipaje-ryanair [NC,OR]
RewriteCond %{REQUEST_URI}  /equipaje/problemas-de-equipaje/perdida-equipaje-aireuropa [NC,OR]
RewriteRule ^(.*)$  http://tudominio.es/equipaje/problemas-de-equipaje/perdida-equipaje [P]


text:
Q: Backtest using yahoo finance and backtest I'm getting an error message when I try to run the code below. How can I change my code to provide comprehensive daily and monthly returns? I want to use this code in particular for BIST30 and BIST100. Should I modify my code for a few details?
\#%%
import yfinance as yf
import backtrader as bt

# Download historical data for the asset

ticker = "SASA.IS"
data = yf.download(ticker, period="max", start="2020-01-02")

# Create a Backtrader data feed from the Pandas dataframe

data = bt.feeds.PandasData(dataname=data)

# Create a Backtrader strategy

class MyStrategy(bt.Strategy):
def __init__(self):
self.data_close = self.datas\[0\].close
self.sma = bt.indicators.SimpleMovingAverage(self.datas\[0\], period=200)
self.order = None

    def next(self):
        if self.order:
            # If an order is pending, do nothing
            return

        if self.data_close > self.sma:
            # If the price crosses above the moving average, buy the asset
            self.order = self.buy()

# Create a Backtrader cerebro object

cerebro = bt.Cerebro()

# Add the data feed to the cerebro object

cerebro.adddata(data)

# Add the strategy to the cerebro object

cerebro.addstrategy(MyStrategy)

# Run the backtest

result = cerebro.run()

# Get the Returns analyzer

returns_analyzer = result\[0\].analyzers.returns

# Get the detailed returns

returns = returns_analyzer.get_analysis()

# Print the detailed returns

print(returns)

I'm attempting to use this code to view daily and monthly returns.

\[***100%***\*\*\]  1 of 1 completed
-

AttributeError                            Traceback (most recent call last)
\<ipython-input-15-b254cc0d9b5a\> in \<module\>
39
40 # Get the Returns analyzer
\---\> 41 returns_analyzer = result\[0\].analyzers.returns
42
43 # Get the detailed returns

AttributeError: 'ItemCollection' object has no attribute 'returns'


text:
Q: degeneration of reductive group If $A$ is a mixed characteristic complete DVR (I'm only actually interested in $\mathbf{Z}_p$) and $G/A$ is a closed subgroup scheme of $GL(n)$ whose generic fibre is connected reductive and split, is the identity component of the special fibre also connected reductive and split?
Oh dear I'm getting very confused about this question. Is there a closed subgroup scheme of $GL(2)$ over $A$ whose generic fibre is trivial but whose special fibre is a Borel subgroup of $GL(2)$? Is life really as bad as that?

A: This may also be SGA3's example, since I am too lazy to go check, but my standard example of a reductive group degenerating to something solvable is to define a multiplication $\ast_t$ on $2 \times 2$ matrices by
$$\begin{pmatrix} x_{11} & x_{12} \\ x_{21} & x_{22} \end{pmatrix} \ast_t \begin{pmatrix} y_{11} & y_{12} \\ y_{21} & y_{22} \end{pmatrix} = \begin{pmatrix} x_{11} y_{11} + t x_{12} y_{21} & x_{11} y_{12} + x_{12} y_{22} \\
x_{21} y_{11} + x_{22} y_{21} & t x_{21} y_{12} + x_{22} y_{22} \end{pmatrix}.$$
For $t \neq 0$, this is simply the ordinary $2 \times 2$ matrices under the change of coordinates $\left( \begin{smallmatrix} z_{11} & z_{12} \\ t z_{21} & z_{22} \end{smallmatrix} \right)$, so it is associative, and it gives a group when restricted to the open set $z_{11} z_{22} - t z_{21} z_{12} \neq 0$. I hope this shows you that there is nothing mysterious in the given formulas.
In the limit $t=0$, the above formulas still define an associative multiplication, which forms a group $G_0$ on the open set $z_{11} z_{22} \neq 0$. Explicitly,
$$\begin{pmatrix} x_{11} & x_{12} \\ x_{21} & x_{22} \end{pmatrix} \ast_0 \begin{pmatrix} y_{11} & y_{12} \\ y_{21} & y_{22} \end{pmatrix} = \begin{pmatrix} x_{11} y_{11} & x_{11} y_{12} + x_{12} y_{22} \\
x_{21} y_{11} + x_{22} y_{21} &  x_{22} y_{22} \end{pmatrix}.$$
Clearly, there is a map $G_0 \to \mathbb{G}_m^2$ projecting a matrix onto its diagonal entries. The kernel, matrices of the form $\left( \begin{smallmatrix} 1 & x_{12} \\ x_{21} & 1 \end{smallmatrix} \right)$, is clearly a copy of $\mathbb{G}_a^2$. So we have a short exact sequence $1 \to \mathbb{G}_a^2 \to G_0 \to \mathbb{G}_m^2 \to 1$ and $G_0$ is solvable.
As grghxy points out, every flat affine group scheme of finite type over a dvr embeds in some $GL_N$, so you are not adding anything with that condition.
This example can be modified to suit many tastes: Replace $z_{11} z_{22} - t z_{12} z_{21} \neq 0$ by $z_{11} z_{22} - t z_{12} z_{21} = 1$ if you like simple Lie groups better than reductive ones; quotient by $\pm \mathrm{Id}$ if you like your groups in adjoint form; work with $2 \times 2$ matrices and $\ast_t$ commutator if you like Lie algebras. Replace $t$ by $p$ in the above formulas to work over $\mathbb{Z}_p$.

A: SGA3 XIX section 5 has a terrifying example of $PGL(2)$ degenerating into something solvable. Thanks to grghxy.


text:
Q: Default button in Window created with CreateWindowEx() I've created a window using CreateWindowEx which functions as a wizard dialog using the following code;
DWORD dwStyle = WS_DLGFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_OVERLAPPEDWINDOW;
m_hWnd = CreateWindowEx(WS_EX_APPWINDOW, _T("WIZARD"), _T("SETUP"), dwStyle, CW_USEDEFAULT, CW_USEDEFAULT, WIZARD_WIDTH, WIZARD_HEIGHT, NULL, NULL, g_hInstance, this);

In the WM_CREATE handler I create the bottom 'Next', 'Back' and 'Cancel' buttons, on the Next' button I set the style BS_DEFPUSHBUTTON and I send the DM_SETDEFID to the window with the ID of the next button. The button displays like a next button but hitting return on any of the input fields does nothing (None have ES_WANTRETURN set).
What am I doing wrong? I can post more code if I've missed anything vital out.
Thanks,
J

A: The DM_SETDEFID message is normally processed by DefDlgProc. If you're calling DefWindowProc instead, then you need to handle that message yourself so that when IsDialogMessage sends your window a DM_GETDEFID message, you'll know how to respond.


text:
Q: AWS Elastic Beanstalk health check issue My web application is Django and web server use Nginx, use Docker image and Elastic Beanstalk for deployment.
Normally there was no problem, but as the load balancer expands EC2, my web server becomes 502 Bad Gateway.
I checked Elastic Beanstalk application logs, about 16% of the requests returned 5xx errors, at which time the load balancer expands EC2, causing the web server to transition to the 502 Bad Gateway state and the Elastic Beanstalk application to the Degraded state.
Is this a common problem when the load balancer performs a health check? If not, how to turn off the Health Check?
I am attaching a captured image for reference.

A: As far as I know, 502 Bad Gateway error can be mitigated only by manually checking the major links you have on your websites and if they are accessible through a simple GET request.
In case of my website, I had some issue with the login page and an about page, (and it was about 33% of my website sadly) which is why after uploading to EC2 i got a 5xx error on health check. I solved the problem by simply making the links work on the server (there were some functionalities which were only running on localhost and not on AWS so I fixed that and got OK status in Health Check)
I don't think there is a point in removing health check as it gives vital information about your website and you probably don't want your website to have inaccessible pages.
Keep track of logs to narrow down to the problem.
I hope you find the solution.

A: While your code is being deployed, you will get 502 because the EC2 instance fails the health check call. You need to adjust the load balance health check default settings to allow enough time for your deployment to complete. Allow more time for a deployment if you also restart the server after each deployment.
The AWS load balancer sends a health check request to each registered instance every N seconds using the path you specify. The default interval seconds is 30 seconds. If the health check fails N number of times (default is 2) for any of the instances you have running, health changes to Degraded or Severe depending on the percentage of your instances that are not responding.

*

*Send a request that should return a 200 response code. Default is '/index.html'

*Wait for N seconds before time out (default 5 seconds)

*Try again after N interval seconds (default 30 seconds)

*If N consecutive calls fail, change the health state to warning or severe (default unhealthy threshold is 2)

*After N consecutive successful calls, return the health state to OK (default is 10).

With the default settings, if any web server instance is down for more than a minute (2 tries of 30 seconds each), it is considered an outage. It will take 5 minutes (10 tries every 30 seconds) to get back to Ok status.
For a detailed explanation and configuration options please check AWS documentation:  Configure Health Checks for Elastic Load Balancing


text:
Q: xpages hiding/showing fields based on a combobox value I'm using a <xe:djTabContainer> with 10 <xe:djTabPane> containing numerous fields components.
There is a principal combobox whose value will determine which fields to be showed or not and in this way the document structure will be achieved.
If I will use this approach, then for all my >50 fields which I want to show/hide, I will use only the onChange event of the combobox?
Considering the fact that there are >50 fields which enter in this category < showing&hiding them >, should I use another approach / method? Thanks for your time.
<xp:comboBox value="#{Contr.txt_tipcontractcv}" id="comboBox4">                                 <xp:selectItems id="selectItems1">
     <xp:this.value><![CDATA[#{javascript:return ""}]]></xp:this.value>
</xp:selectItems>
<xp:selectItems id="selectItems2">
    <xp:this.value><![CDATA[#{javascript:@DbColumn(@DbName(),"SetupvwTipuriContracteC",1);}]]>           </xp:this.value>
</xp:selectItems>
<xp:eventHandler event="onchange" submit="false">                                       <xp:this.script><![CDATA[XSP.partialRefreshPost("#{id:FisaP}", {
});
]]></xp:this.script>                                    </xp:eventHandler>                          </xp:comboBox>

and the panel:
<xp:panel id="FisaP">
        <xp:label id="label4"
            style="color:rgb(128,0,0);font-family:verdana;font-size:9pt;font-weight:bold">
            <xp:this.value><![CDATA[#{javascript:"Fisa contract "+ Contr.getItemValueString("txt_tipcontractcv")}]]></xp:this.value>
            <xp:this.rendered><![CDATA[#{javascript:
            Contr.getItemValueString("txt_tipcontractcv") != ""
         }]]></xp:this.rendered>

        </xp:label>

    </xp:panel>

A: I would turn it around. Let the labels and fields ask the combobox if they should be rendered or not. Let the combobox's onchange event initiate a partial refresh of a panel which includes all fields you want to show/hide.
If your >50 fields are all on one place you can frame them with a panel and set the rendered property there.
If your combobox is bound to a viewScope variable the rendered property of fields/labels would be
rendered="#{javascript:viewScope.tipcontractcv1 == 'Vanzare-Cumparare'}"

or if it is bound to a document field then
rendered="#{javascript:document1.getItemValueString('txt_tipcontractcv1') === 'Vanzare-Cumparare'}"

Update:
Based on your code in your answer https://stackoverflow.com/a/25636661/2065611 take the following steps so get it to work with the Dojo Tab Container:
1.
Put the labels and fields in panels which do have an id but don't have a rendered attribute
<xp:panel id="panel1">
    <xp:label value="Persoane spre informare" ... id="label2">
         <xp:this.rendered><![CDATA[#{javascript:
            Contr.getItemValueString("txt_tipcontractcv1") == "Vanzare-Cumparare"
         }]]></xp:this.rendered>
    </xp:label>
    ... other label and fields ...
</xp:panel>

You can create other panels "panel2", "panel3", ... too. They can be placed in different djTabPanes.
2.
Change the onchange event of your combobox and execute client side code to refresh the panels
            <xp:eventHandler
                event="onchange"
                submit="false">
                <xp:this.script><![CDATA[
                    XSP.partialRefreshPost("#{id:panel1}", {
                        onComplete: function() {
                            XSP.partialRefreshPost("#{id:panel2}");
                        }
                    });
                ]]></xp:this.script>
            </xp:eventHandler>

3.
You can optimize your code if you put labels and fields with the same rendered attribute together into an additional panel
<xp:panel id="panel1">
    <xp:panel id="panelRendered1"
         <xp:this.rendered><![CDATA[#{javascript:
            Contr.getItemValueString("txt_tipcontractcv1") == "Vanzare-Cumparare"
         }]]></xp:this.rendered>
        <xp:label value="Persoane spre informare" ... id="label2" />
        ... other label and fields ...
    </xp:panel>
</xp:panel>

A: First...  never do this:
if (comboVal == "Vanzare-Cumparare")

Even though it's called "SSJS"..  it's really not "JavaScript"... you're pretty much working with Java.  In Java everything is an object.  Even a literal string.  So by entering "Vanzare-Cumparare" you're pretty much creating a new Object.  You can see this in the typeahead of the SSJS editor.  Try typing "anything".   <-- Note you NEED to type in that period.
The way to do that if statement is:
if ("Vanzare-Cumparare".equalsIgnoreCase(comboVal)

you could reverse it I think:
if (comboVal.equalsIgnoreCase("Vanzare-Cumparare")

Should give you the same result.  I think sometimes you can get away with using the == but mostly likely it's going to bite you at some point no matter what.  So I recommend never doing that.
I'm not sure I'm following your approach here.  I guess it makes some sense but if it were me I'd do it differently.  I know that personally I've NEVER tried to grab the component in SSJS like this:  var combo:javax.faces.component.UIComponent  - I've never seen the need.
I'd prefer to use a scoped variable and then in the label's rendering property grab that scoped variable and use that to determine your rendering value - true or false.

A: I see a real problem. If the component is not currently rendered, you cannot get a handle to it with getComponent. If you simply change the display value, then the component is always there, even if it's not displayed.
Something like this:
var combo:javax.faces.component.UIComponent = getComponent("txt_tipcontractcv1");
var comboVal = combo.getValue();
if (comboVal.equalsIgnoreCase("Vanzare-Cumparare")) {
    document.getElementById("#{id:label2}").style.display = "block"; // or "inline"
} else {
    document.getElementById("#{id:label2}").style.display = "none";
}

You need to ensure that the label2 element is always rendered, so that the style indicates whether it is visible.


text:
Q: Selenium 2.0 and findBy - Custom properties or Expando Properties Anyone have a suggestion for finding elements on a page by a custom property, like an expando property?
Problem: Site uses alot of JSP and dynamic images for buttons. They do not have static names or IDs. (Think of a registration or checkout process where every page has a "next" or "continue" button, but it dynamically takes you somewhere depending upon current context)
Suggested Solution: My repeated requests that these are not automate-able have recently been answered with a custom expando property of "btn-tag-title".
If every element on a page has a unique (but custom) property named btn-tag-title=, can selenium 2.0 find it reliable every time?
Other Suggested Solutions?
    log.info(driver.getCurrentUrl());
    assertTrue(selenium.isElementPresent("btn-tag-title=Sign In"));
    selenium.type("name=username", "demo");
    selenium.type("name=password", "tester");
    selenium.click("btn-tag-title=Sign In");
    log.info(driver.getCurrentUrl());

A: Sure.  You can refer to any attribute of the element in either an XPath or CSS locator.  For example:
assertTrue(selenium.isElementPresent("//*[@btn-tag-title='Sign In']"));
...
selenium.click("//*[@btn-tag-title='Sign In']");

or
assertTrue(selenium.isElementPresent("css=*[btn-tag-title='Sign In']"));
...
selenium.click("css=*[btn-tag-title='Sign In']");

For what it's worth, if your developers can put a custom property with a guaranteed-unique value on every interesting element, you should ask them why they won't put that value in the id= attribute instead.  Because element IDs are special in HTML, DOM, and Selenium, and elements can be located much more quickly by their ID than by any other technique.


text:
Q: Access ElastiCache memcache instance from local development environment Is there any way to access cache nodes from local development environment? Although the same cache nodes are accessible from EC2 instance.
I'm using Enyim memcache client library with C#. I found few article saying this is not possible then what should be best approach. Should i need to setup memcache locally for  development work?

A: According to Amazon, there is no accessing elasticache clusters from outside AWS:

...an Amazon ElastiCache Cluster, inside or outside a VPC, is never allowed to be accessed from the Internet.

From http://aws.amazon.com/elasticache/faqs/#Can_I_access_Amazon_ElastiCache_from_outside_AWS
Also see this question:
Can you connect to Amazon Elasticache Redis outside of Amazon

A: When you create your Elastic Cache cluster, you have to define a Security Group. A Security group is a set of rules that define what IP addresses are authorised to connect to your cluster.
Should you want to connect to your cache cluster from your local machine, be sure to add a rule to authorise your local IP address to connect to the cluster (beware if you're behind a NATing gateway or a proxy, you need to use your external IP address and not your internal IP address)
Details are available at :
http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/GettingStarted.CreateCacheCluster.html
Security Group is explained at : http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html
--Seb

A: You can create ssh tunnel:
$ ssh -nNT -L 11211:<elasticache instance public dns name>:11211 ubuntu@<ec2 instance> -i <path to your pem file>

*

*-L means local port forwarding

*-nNT means no tty allocated and no commands executed on remote side

for example:
$ ssh -nNT -L 11211:blah-blah.cfg.use1.cache.amazonaws.com:11211 ubuntu@ec2-54-254-254.compute-1.amazonaws.com -i ~/.ssh/mykey.pem

And in another console you can connect to localhost:
telnet localhost 11211
Trying ::1...
Connected to localhost.
Escape character is '^]'.


text:
Q: my sql field sum using another field to differentiate and then sort it I would like to ask something about query using mysql
I have this table called video_stat, and here's the field
CREATE TABLE IF NOT EXISTS `video_stat` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `video_id` int(10) NOT NULL,
  `member_id` int(10) NOT NULL,
  `counter` int(11) NOT NULL,
  `daydate` varchar(15) NOT NULL,
  `monthdate` varchar(10) NOT NULL,
  `epochtime` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1

the 'counter' field will be updated per day
and my question is that, I would like to sort this field, by sum-ing the counter as total per video_id and then sort them by total per video_id to then display the list on a popular video page. how can I do that?
I thought that it would work using this query:
SELECT SUM( counter ) AS total_viewed, member_id, video_id
FROM member_video_stat

but it will only sums up everything on the counter field and return a single row since the SUM(counter) part did not count for each and particular video_id
illustration:
current table
+--------------+-----------+---------+
| id| video_id | member_id | counter |
+---+----------+-----------+---------+
| 4 |      6   |       2   |       1 |
| 5 |      9   |       6   |       1 |
| 6 |      12  |       2   |       1 |
| 7 |      6   |       2   |       1 |
| 8 |      12  |       2   |       1 |
+--------------+-----------+---------+

to something like
    +----------+-----------+---------+
    | video_id | member_id | total   |
    +----------+-----------+---------+
    |      6   |       2   |       2 |
    |      9   |       6   |       1 |
    |      12  |       2   |       2 |
    +----------+-----------+---------+

A: Give this a try
SELECT SUM(counter) AS total_viewed, member_id, video_id
FROM member_video_stat
GROUP BY video_id
ORDER BY total_viewed DESC

Hoa


text:
Q: How to normalize location names in Python? I am working on a dataset of user comments in which they mention locations. I am using nltk (StanfordNERTagger) and spacy to pull out the locations. The problem is that they are in many different forms. Ex: (nyc vs New York City,  ga vs Georgia, etc). Additionally, I wish to retrieve the state for a given city. Is there a library or way to normalize these in Python? A library that for instance worked like this:
g = geo_classify('New York City')
g.cities() => ['New York City']
g.states() => ['New York']
g.countries() => ['United States']

I tried using Geograpy3 but it didn't detect some cities, any abbreviations, and didn't give me the state for a given city. Any suggestions?

A: @Big_Mac - I am one of the committers of Geograpy. Thank you for trying Geograpy3. You might want to use the locator interface and the newest release of geograpy3 which is due these days. There is now a CityLookup, RegionLookup and CountryLookup  which takes different labels of according to wikidata into account.
Here is a "preview" of what to expect. Internally the following SQL database query will be used:
NY example
query
select * from cityLookup where label='New York City'

result

label
level
locationKind
wikidataid
name
geoNameId
regionId
countryId
pop
lat
lon
partOfRegionId
gndId
regionName
regionIso
regionPop
regionLat
regionLon
countryName
countryIso
CountryLat
CountryLon

New York City
5
City
Q60
New York City
5128581
Q1384
Q30
8398748
41
-74
Q1384
4042011-5
New York
US-NY
19795791
43
-75
United States of America
US
40
-99

Here is some example code i am currently using to test the current state of geograpy3:
'''
Created on 2021-08-11

@author: wf
'''
#from lodstorage.entity import EntityManager
from geograpy.locator import LocationContext
import OSMPythonTools
from OSMPythonTools.nominatim import Nominatim
import os
import logging

class LocationLookup:
    '''
    lookup locations
    '''
    preDefinedLocations={
        "Not Known": None,
        "Online": None,
    }
    other={
        "Washington, DC, USA": "Q61",
        "Bangalore": "Q1355",
        "Bangalore, India": "Q1355",
        "Xi'an": "Q5826",
        "Xi'an, China": "Q5826",
        "Virtual Event USA": "Q30",
        "Virtual USA": "Q30",
        "London United Kingdom": "Q84",
        "Brno":"Q14960",
        "Cancun":"Q8969",
        "St. Petersburg": "Q656",
        "Gothenburg Sweden": "Q25287",
        "Los Angeles California": "Q65",
        "Zurich, Switzerland": "Q72",
        "Barcelona Spain": "Q1492",
        "Vienna Austria": "Q1741",
        "Seoul Republic of Korea": "Q8684",
        "Seattle WA USA": "Q5083",
        "Singapore Singapore":"Q334",
        "Tokyo Japan": "Q1490",
        "Vancouver BC Canada": "Q24639",
        "Vancouver British Columbia Canada": "Q24639",
        "Amsterdam Netherlands":"Q727",
        "Paris France": "Q90",
        "Nagoya": "Q11751",
        "Marrakech":"Q101625",
        "Austin Texas":"Q16559",
        "Chicago IL USA":"Q1297",
        "Bangkok Thailand":"Q1861",
        "Firenze, Italy":"Q2044",
        "Florence Italy":"Q2044",
        "Timisoara":"Q83404",
        "Langkawi":"Q273303",
        "Beijing China":"Q956",
        "Berlin Germany": "Q64",
        "Prague Czech Republic":"Q1085",
        "Portland Oregon USA":"Q6106",
        "Portland OR USA":"Q6106",
        "Pittsburgh PA USA":"Q1342",
        "Новосибирск":"Q883",
        "Los Angeles CA USA":"Q65",
        "Kyoto Japan": "Q34600"
    }

    def __init__(self):
        '''
        Constructor
        '''
        self.locationContext=LocationContext.fromCache()
        cacheRootDir=LocationContext.getDefaultConfig().cacheRootDir
        cacheDir=f"{cacheRootDir}/.nominatim"
        if not os.path.exists(cacheDir):
            os.makedirs(cacheDir)

        self.nominatim = Nominatim(cacheDir=cacheDir)
        logging.getLogger('OSMPythonTools').setLevel(logging.ERROR)

    def getCityByWikiDataId(self,wikidataID:str):
        '''
        get the city for the given wikidataID
        '''
        citiesGen=self.locationContext.cityManager.getLocationsByWikidataId(wikidataID)
        if citiesGen is not None:
            cities=list(citiesGen)
            if len(cities)>0:
                return cities[0]
        else:
            return None

    def lookupNominatim(self,locationText:str):
        location=None
        nresult=self.nominatim.query(locationText,params={"extratags":"1"})
        nlod=nresult._json
        if len(nlod)>0:
            nrecord=nlod[0]
            if "extratags" in nrecord:
                extratags=nrecord["extratags"]
                if "wikidata" in extratags:
                    wikidataID=extratags["wikidata"]
                    location=self.getCityByWikiDataId(wikidataID)
        return location

    def lookup(self,locationText:str):
        lg=self.lookupGeograpy(locationText)
        ln=self.lookupNominatim(locationText)
        if ln is not None and lg is not None and not ln.wikidataid==lg.wikidataid:
            print(f"❌{locationText}→{lg}!={ln}")
            return None
        return lg

    def lookupGeograpy(self,locationText:str):
        '''
        lookup the given location by the given locationText
        '''
        if locationText in LocationLookup.preDefinedLocations:
            locationId=LocationLookup.preDefinedLocations[locationText]
            if locationId is None:
                return None
            else:
                location=self.getCityByWikiDataId(locationId)
                return location
        locations=self.locationContext.locateLocation(locationText)
        if len(locations)>0:
            return locations[0]
        else:
            return None


text:
Q: Vagrantfile for configuring vm in vagrant having forward_port 80, 8080 is throwing error I have the following in my Vagrantfile.
config.vm.forward_port 80, 8080

And when I do Vagrant up, I get this error. My intent is port mapping from guest to host.
Bringing machine 'default' up with 'virtualbox' provider...
There are errors in the configuration of this machine. Please fix
the following errors and try again:

vm:
* The following settings shouldn't exist: forward_port

A: The member variable for the config object in that block should be forwarded_port, with symbol type arguments of guest and host, and a member method of network, so your line should appear like:
config.vm.network 'forwarded_port', guest: 80, host: 8080