text:
Q: DirectShow-IMediaDet only extracts the first frame I experienced a weird effect concerning DirectShow and splitters.
I was not able to track it, so maybe somebody can help?
In my application I extract a few frames from movies.
I do this by DirectShow's IMediaDet interface.
(BTW: It's XP SP3, DirectShow 9.0).
Everything works fine, as long as there is no media splitter involved
(this is the case for mp4, mkv, flv, ...).
Concerning codecs I use the K-Lite distribution.
Since some time there are two splitters: LAV and Haali.
The Gabest splitter has been removed since some time.
But only with the latter activated everything worked fine!
OK - the effect:
It's about IMediaDet.GetBitmapBits:
Some (most) medias that uses splitters always extract the very first frame.
And with some other medias with splitters this effect is only when I
used get_StreamLength before. (Although GetBitmapBits should switch
back to BitmapGrab mode, as the docu says.).
As said - everything works fine as far as no splitter is involved (mpg, wmv, ...).
Does someone experienced a similar effect?
Where may be the bug: In DShow, in the splitters, in my code?
Any help appreciated ... :-)

A: Your assumption is not quite correct. IMediaDet::GetBitmapBits builds a filter graph internally, and attempts to navigate playback to position of interest. Then starts streaming to get a valid image onto its Sample Grabber filter "BitBucket".
It does not matter if splitter is a separate filter or it is combined with source. Important part is the ability of the graph to seek, a faulty filter might be an obstacle there, even though the snapshot is taken. This is the symptom you are describing.
For instance the internal graph might be like this:

There is a dedicated multiplexer there, and snapshot is taken from correct position.


text:
Q: Recursion Tree with Python Turtle I created the following tree:

But now I want it to be vertical like this:

For creating the horizontal one I used the following code:
from turtle import *

def tree(length,order):
    if length < (length/order):
           return
    forward(length)
    left(45)
    tree(length * 0.5,length/order)
    right(90)
    tree(length * 0.5,length/order)
    left(45)
    backward(length)
    return
tree (200, 5)

Now, I am trying the following code to create it vertically but it stuck (I think) at line right(45) line:
def tree(length,order):
    if length < (length/order):
           return
    rt(-90)
    forward (length)
    right(45)
    tree(length * 0.5,length/order)
    left(225)
    tree(length * 0.5,length/order)
    left(90)
    backward(length)
    return

tree (200,5)

A: import turtle

def tree(t,length,order):
    if length < (length/order):
           return
    t.forward(length)
    t.left(45)
    tree(t,length * 0.5,length/order)
    t.right(90)
    tree(t,length * 0.5,length/order)
    t.left(45)
    t.backward(length)
    return

screen = turtle.Screen ( )
tip = turtle.Turtle()
tip.shape ("turtle")
tip.speed (1)

tip.left(90)  # vertical start
tree (tip, 200, 5)

A: This can be as simple as a one-line fix:
mode('logo')

Among other things, 'logo' mode changes 0 degrees to be towards the top of the screen insted of the right:
from turtle import *

def tree(length, order):
    if length >= length / order:
        forward(length)
        left(45)
        tree(length / 2, length / order)
        right(90)
        tree(length / 2, length / order)
        left(45)
        backward(length)

mode('logo')

tree(200, 5)

A: Hey, look! Here is a Recursion Tree program built into the built-in turtle package:
#!/usr/bin/env python3
"""      turtle-example-suite:

             tdemo_tree.py

Displays a 'breadth-first-tree' - in contrast
to the classical Logo tree drawing programs,
which use a depth-first-algorithm.

Uses:
(1) a tree-generator, where the drawing is
quasi the side-effect, whereas the generator
always yields None.
(2) Turtle-cloning: At each branching point
the current pen is cloned. So in the end
there are 1024 turtles.
"""
from turtle import Turtle, mainloop
from time import clock

def tree(plist, l, a, f):
    """ plist is list of pens
    l is length of branch
    a is half of the angle between 2 branches
    f is factor by which branch is shortened
    from level to level."""
    if l > 3:
        lst = []
        for p in plist:
            p.forward(l)
            q = p.clone()
            p.left(a)
            q.right(a)
            lst.append(p)
            lst.append(q)
        for x in tree(lst, l*f, a, f):
            yield None

def maketree():
    p = Turtle()
    p.setundobuffer(None)
    p.hideturtle()
    p.speed(0)
    p.getscreen().tracer(30,0)
    p.left(90)
    p.penup()
    p.forward(-210)
    p.pendown()
    t = tree([p], 200, 65, 0.6375)
    for x in t:
        pass
    print(len(p.getscreen().turtles()))

def main():
    a=clock()
    maketree()
    b=clock()
    return "done: %.2f sec." % (b-a)

if __name__ == "__main__":
    msg = main()
    print(msg)
    mainloop()

Now, focus on the make_tree function:
def maketree():
    p = Turtle()
    p.setundobuffer(None)
    p.hideturtle()
    p.speed(0)
    p.getscreen().tracer(30,0)
    p.left(90) # HERE! They turned left by 90 degrees!
    p.penup()
    p.forward(-210)
    p.pendown()
    t = tree([p], 200, 65, 0.6375)
    for x in t:
        pass
    print(len(p.getscreen().turtles()))

From that built-in tree.py file, simply removing some code without adding any can get you:
from turtle import Turtle

def tree(plist, l, a, f):
    if l > 3:
        lst = []
        for p in plist:
            p.forward(l)
            q = p.clone()
            p.left(a)
            q.right(a)
            lst.append(p)
            lst.append(q)
        for x in tree(lst, l * f, a, f):
            yield None

p = Turtle()
p.hideturtle()
p.getscreen().tracer(30,0)
p.left(90)
for x in tree([p], 120, 65, 0.6375):
    pass

Output:

What's different from the above method and your current method is that we get to see each level of branches grow altogether, instead of waiting for a single route to finish every time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring Boot 2.2.1 suffix pattern issues I have some tests that test PUTting a resource to an endpoint.  We support using path extensions to determine the content type of the request.  The tests that do not include the file suffix in the path pass fine; the test that does include the suffix fails with a 406.  The suffix is registered in ContentNegotationConfigurer and I've tried every combination of spring.mvc.pathmatch.use-suffix-pattern, spring.mvc.pathmatch.use-registered-suffix-pattern, spring.mvc.contentnegotiation.favor-path-extension, and spring.mvc.contentnegotiation.favor-parameter to no avail.
The request mapping in question accepts all values and produces html, xml, and json.
Debugging into the DispatcherServlet, I noticed in RequestMappingInfo.getMatchingCondition, the consumes condition properly matches, but the produces condition returns null.  Stepping in further, I see the ContentNegotiationManager has 4 strategies, one of them being ServletPathExtensionContentNegotationStrategy.  This class has a method resolveMediaTypeKey, which basically tries to look up the extension from registered media types.  Because my file extension and media type are registered, it matches and returns the media type for that extension (which is not html, xml or json) and in turn, the ContentNegotationManager returns that value to the ProducesRequestCondition.  At this point, the returned media type is compared to the declared produces values.  Since the value being returned does not match any of the declared produces values from the controller, the condition fails.
This seems problematic to me.  It seems like the behavior implies that if you PUT/POST/whatever a resource to a controller and it uses the file suffix to determine the content type of the request, it also attempts to force it as the return type when attempting to determine the handler mapping, which is not the case.
This was not an issue in Spring Boot 2.1.x.  Curious if this is a legitimate issue or if there is something I'm missing.


text:
Q: how to pass a dynamic variable to the OS path to be checked i am trying to write a few checks which check for the ownership,permissions of a few directories.
Here i need to create the directories if they are not present.However the path needs to be dynamic.
For example in /local/backup/DBNAME the DBNAME would be a variable defined by user input.
So if the user provides the DBNAME as ORACLE_DB1 we would check for:
if (os.path.isdir("/local/backup/ORACLE_DB1/log")):
    print('log directory exists')

Also 'local' needs be another dynamic variable dependent on server type.
For example if server is type-1 then it is '/local/backup/DBNAME' and if it is type-2 then '/share/backup/DBNAME'.

A: You can compose the path with os.path.join() like so:
server_path = 'local' if....
db_name = <get the database name from wherever you get it>
filepath = os.path.join(server_path, 'backup', db_name, 'log')

You can then check for the path existence and create it if needed.


text:
Q: Interruption of process in critical section In Priority based scheduling, I came across the problem of Priority inversion which is a higher priority process is forced to wait for the lower priority task.
One possible scenario is, consider three process L,M,H with order of priority L < M < H .
L is running in CS ; H also needs to run in CS ; H waits for L to come out of CS ; M interrupts L and starts running ; M runs till completion and relinquishes control ; L resumes and starts running till the end of CS ; H enters CS and starts running.
Here, my question is, regarding the statement M interrupts L and starts running i.e., can a process executing in Critical section be interrupted or pre-empted.

A:
Here, my question is, regarding the statement M interrupts L and starts running i.e., can a process executing in Critical section be interrupted or pre-empted.

It depends on how the critical section is implemented.
In operating system code you will frequently find critical sections implemented where interrupts are blocked. In this kind of implementation, a process will always execute the entire critical section without interruption.
In user code that uses critical sections implemented through system services, the process invariably can be interrupted. If the were not the case a process could take over the system by putting all its code in a critical section.
You are describing one of the reasons process priorities should be consistent. Unless you are doing real time processing or background batch processing, all processes should generally have the same base priority.
The old DECUS tapes used to be filled with "fair share" applications that would lower the priory of processes with high CPU usage and that would wreak havoc with system scheduling.

A: The answer is simple and yes.
If someother process with a higher priority in a preemptive system doesn't need to run in critical section, i.e. doesn't need to aquire a lock which is held by a lower priority process, then it can preempt the lower priority process regardless of what it is executing.
Even if M needs the CS, it will preempt L, run, get blocked and switched out for L to continue execution.


text:
Q: Software development process for a part time University project for 1 developer? I will be doing a part time University project soon and the time frame for it is around 8 months with approximately 10-15 hours a week spent working on it, with a review by a tutor each quarter.
My question is what software development process would you recommend using when the course requires you to work on your own in order to manage yourself as well as the project?
I wanted to use a weekly or bi-weekly iterative approach to my work but a lot of the processes seem tailored to teams of people.
I am looking at XP (Extreme Programming) OR Scrum as something that is less than the norm for University work but again Scrum I don't know a lot about yet, and a question I have is; can you say you are doing XP without pair-programming? because my tutor seems to think that I have to stick to all the practices otherwise I can't do it (nevermind if I am working alone).
We can have external user input as well but due to the small timescales with part time work it may be more beneficial for myself to be the user as well, which is not what I prefer considering how I can get lost in the design.

A: The first principle of the Agile Manifesto is to have a preference for team colaboration over processes.  What this means for you is don't get caught up with XP or Scrum or some other named process, but do something for your specific needs.  Some approaches that can really help:

*

*User stories to track requirements/features and estimation (story points).  It provides enough structure to figure out the high level design without getting too bogged down in the details.

*BDD or TDD, all the more important because you are working by yourself.  Without a dedicated testor, you have two hats to wear.  If you code your tests, they will help you discover when you accidentally break something.

*Version control.  Use it, it will save your hide--even if you are only one person.  Better yet, use an externally hosted solution that has regular backups.  There's several options like GitHub or some equivalent that allow you to have private repositories.  Nothing worse than the sinking feeling before d-day (delivery day) and you just realized you went down a rabit hole that had a bottomless pit.  The repository will let you go back to a sane version and choose a different route.

*Short iterations.  No more often than one a week, but no less often than once every two weeks.  You need constant feedback, and the weekly iteration can work really well.  At every iteration you should have something that works, albeit with more features.  If you iterate too often you will be spinning your wheels and not getting enough done.  If you don't iterate often enough it will be too long without feedback (i.e. your testing cycle) and the problems become more troublesome to fix.

A: There's nothing to stop you using an agile process with only one developer, though some like XP require pair programming so you'd have to use a different methodology.
It has been argued that XP is a particularly fragile form of Agile development. In XP Refactored the authors point out that if you don't adopt just one of the features of XP the whole thing can fail quite badly.
You can't do daily standups - unless your tutor/supervisor is available at the same time every day. So you will have to pick and choose the features you use.
The short iteration cycles will help and you can use your weekly(?) tutorials to discuss the progress made in the last week and what you hope to achieve in the next week.

A: For my personal projects I use Personal Kanban for overall process visualization.

...Unlike other personal productivity tools, Personal Kanban is a pattern – it is not an edict. You can mold it into whatever shape or form works best for you at the time. Personal Kanban is also scalable – it can work with just you, or with your family, or even with work groups.
There are only two real rules with Personal Kanban:

*

*Visualize your work

*Limit your work-in-progress
It's just that simple.  After you've used this "introductory' kanban for a little while, your understanding of the nature of  your work will evolve. As it does, your kanban will likewise evolve...


text:
Q: how can I make sure that the edit text field (android) is not locked by any other thread? I have an activity to search in some remote database there is an edit text field to put your search key words. when the search complete for the first time and results retrived successfully I couldn't write in that text field as in this pic screenshot.
My guess is that text field is locked by another thread so I need to verify that guess.
If any one have other thought please share it with me
thanks in advance.

A: Only the UI thread (main thread) of the app can manipulate UI elements.  That appears as though something has disabled the view and not re-enabled it.

A: As @Larry Schiefer mentioned, only the UI thread can access UI elements. That being said, there are multiple ways to access the UI thread, such as using runOnUiThread or the onPostExecute method of an AsyncTask, so it is valuable to ensure that the UI is only being accessed from one source at a time. One way to do this is to implement a Handler for the UI, which means that all request to update the UI are posted to the Handler such that only the Handler is directly accessing the UI. You can find alot of valuable information on how to communicate with the UI here: https://developer.android.com/training/multiple-threads/communicate-ui.html
As a side note, it is valuable to remember that, since Java supports concurrency, any given resource could potentially be accessed by multiple sources at the same time if you are not careful with your programming. While there are a variety of strategies for protecting resources one valuable tool is to use a Semaphore, which essentially act like a key - no key means no access. The simple code snipped below can be used to protect a resource which may be accessed from multiple sources to ensure that it is not accessed at the same time:
Semaphore mySemaphore = new Semaphore(1);
mySemaphore.acquire();
// Access resource
mySemaphore.release();

The above snipped declares a Semaphore with one permit, meaning only one caller can hold it at a time, and then tries to acquire the Semaphore in order to access the resource; after the resource is accessed, the Semaphore is released. You can find more information about the Semaphore here: http://developer.android.com/reference/java/util/concurrent/Semaphore.html


text:
Q: Force Windows 10 to have a second screen I have an Eurolite Pixel 64 Mesh LED Screen that works like a desktop extended second screen on Windows. I just have to connect the DVI output of my graphic card to the Eurolite sending card :

My problem is Windows 10 doesn't recognize the sending card like a real screen. I still have only one screen in the resolution control panel.
With my preceding ATI graphic card and Windows 7, i could force  to send ouput signal without screen detection. But with Windows 10 and my basic Intel(R) HD graphics 530, i can't.

*

*My first idea is to create a c# application or service that emulate a second screen and control pixel by pixel the DVI output signal but I doesn't found any help on the web for this.

*My second idea is to create a dummy dvi plug using a DVI Y with 3 resistances on the first plug and the sending card in the second plug. Does anybody has already done this ?
Thanks. If it's not the good exchange site, please tell me where, i'll change it

A: What you need is an EDID/DDC Emulator
It will emulate an attached screen, you just put it between your computer and the sender.
.


text:
Q: Removing edit within switch statements I am working on creating a poker odds calculator, I have 8 players set around a table with a JComboBox with the selected amount of players. What I am looking to do is to "repaint" the GUI after I make multiple selections. For example, if I click 4 players, 4 players become editable. This currently works but when I select 3 players after, player 4 is still editable.
I have tried to set the visibility, I tired to remove the player panes, I tried remove(addPlayer4), I have tried a few other odd things but the closest I can get is removing the player entirely.
addPlayer1.addActionListener((ActionEvent e) -> {
        player1.removeAll();
        player1.add(playerPanelFactory("Player1",1));
        //welcomeScreen.get
        repaint();
        validate();
    });
    addPlayer2.addActionListener((ActionEvent e) -> {
        player2.removeAll();
        player2.add(playerPanelFactory("Player2",2));
        getParent().repaint();
 //       contentPane.repaint();
        validate();
    });
    addPlayer3.addActionListener((ActionEvent e) -> {
        player3.removeAll();
        player3.add(playerPanelFactory("Player3",3));
        getParent().repaint();
//        contentPane.repaint();
        validate();
    });
    addPlayer4.addActionListener((ActionEvent e) -> {
        player4.removeAll();
        player4.add(playerPanelFactory("Player4",4));
        repaint();
        validate();
    });

.....
playerBox.addActionListener((ActionEvent e)-> {
        numberOfPlayers = playerBox.getSelectedItem().toString();
        int numPlayers = Integer.parseInt(numberOfPlayers);
        switch(numPlayers){
            case 1:
                addPlayer1.doClick();
                break;
            case 2:
                addPlayer1.doClick();
                addPlayer2.doClick();
                break;
            case 3:
                addPlayer1.doClick();
                addPlayer2.doClick();
                addPlayer3.doClick();
                break;
            case 4:
                addPlayer1.doClick();
                addPlayer2.doClick();
                addPlayer3.doClick();
                addPlayer4.doClick();
                break;
            case 5:
                addPlayer1.doClick();
                addPlayer2.doClick();
                addPlayer3.doClick();
                addPlayer4.doClick();
                addPlayer5.doClick();
                break;
            case 6:
                addPlayer1.doClick();
                addPlayer2.doClick();
                addPlayer3.doClick();
                addPlayer4.doClick();
                addPlayer5.doClick();
                addPlayer6.doClick();
                break;
            case 7:
                addPlayer1.doClick();
                addPlayer2.doClick();
                addPlayer3.doClick();
                addPlayer4.doClick();
                addPlayer5.doClick();
                addPlayer6.doClick();
                addPlayer7.doClick();
                break;
            case 8:
                addPlayer1.doClick();
                addPlayer2.doClick();
                addPlayer3.doClick();
                addPlayer4.doClick();
                addPlayer5.doClick();
                addPlayer6.doClick();
                addPlayer7.doClick();
                addPlayer8.doClick();

                break;
            default:
                return;
        }
    });

I didn't want to link all of the code since it is almost 700 lines but I believe this is where the issues could be. The goal I am looking to get is to have the players pane editable when they are selected and not editable when not selected.
https://imgur.com/a/ssgXSXW?
I hope this makes sense

A: Hopefully this adaptation will help fix your problem. Essentially you are adding a number of players every time you change the counter, re-adding them on every change, e.g. when 1 player is selected, you spawn player 1. Then when two players are selected, you spawn player 1 again and player 2. Perhaps adding in a check of some sorts so that you aren't re-creating the same players again would be good, then you wouldn't have to clear the players every time they are added, though only a minor thought.
With this suggestion, the aim is to basically compare the current number of player to the previous number. If we are adding more players or staying the same, continue as normal and update our variables. If we are however removing one or more players, remove the player in between our current number of players, and our target number of players, before re-drawing.
Example case: going from 7 players to 5 players. Therefore we want to delete new number of player (5) + 1, so player 6. Then loop round and delete the last player, player 7. Then redraw.
I haven't been able to test it without the code, but I hope my brainstorm helps, or that it sparks some thoughts to either yourself or someone else :) Hopefully it is implementable as well. If anyone know of a better way of doing this, I'm all ears as well and eager to learn where I may have gone wrong! :)
int lastNumPlayers;

/*
*   SOME CODE
*/

playerBox.addActionListener((ActionEvent e)-> {
        numberOfPlayers = playerBox.getSelectedItem().toString();
        int numPlayers = Integer.parseInt(numberOfPlayers);

        if(numPlayers >= lastNumPlayers) {
            switch(numPlayers){
                case 1:
                    addPlayer1.doClick();
                    break;
                case 2:
                    addPlayer1.doClick();
                    addPlayer2.doClick();
                    break;
                case 3:
                    addPlayer1.doClick();
                    addPlayer2.doClick();
                    addPlayer3.doClick();
                    break;
                case 4:
                    addPlayer1.doClick();
                    addPlayer2.doClick();
                    addPlayer3.doClick();
                    addPlayer4.doClick();
                    break;
                case 5:
                    addPlayer1.doClick();
                    addPlayer2.doClick();
                    addPlayer3.doClick();
                    addPlayer4.doClick();
                    addPlayer5.doClick();
                    break;
                case 6:
                    addPlayer1.doClick();
                    addPlayer2.doClick();
                    addPlayer3.doClick();
                    addPlayer4.doClick();
                    addPlayer5.doClick();
                    addPlayer6.doClick();
                    break;
                case 7:
                    addPlayer1.doClick();
                    addPlayer2.doClick();
                    addPlayer3.doClick();
                    addPlayer4.doClick();
                    addPlayer5.doClick();
                    addPlayer6.doClick();
                    addPlayer7.doClick();
                    break;
                case 8:
                    addPlayer1.doClick();
                    addPlayer2.doClick();
                    addPlayer3.doClick();
                    addPlayer4.doClick();
                    addPlayer5.doClick();
                    addPlayer6.doClick();
                    addPlayer7.doClick();
                    addPlayer8.doClick();

                    break;
                default:
                    return;
        }

        lastNumPlayers = numPlayers;
    } else {
        //Loop through all players between the last number and the new number
        for(int i = numPlayers + 1; i <= lastNumPlayers; i++) {
            switch(i) {
                //Lowest number of players is 1, so lowest check is at 2 (1+1 = 2)
                case 2:
                    player2.removeAll();
                    break;
                case 3:
                    player3.removeAll();
                    break;
                case 4:
                    player4.removeAll();
                    break;
                case 5:
                    player5.removeAll();
                    break;
                case 6:
                    player6.removeAll();
                    break;
                case 7:
                    player7.removeAll();
                    break;
                case 8:
                    player8.removeAll();
            }
        }

        //After removing unused players, redraw screen
        repaint();
        lastNumPlayers = numPlayers;
    }

});


text:
Q: Somehow UI font looks skinny in 15.10 http://i.imgur.com/n3HUrjP.png
http://i.imgur.com/NLXuK8G.png
Fonts looks weird in menu bar and dash and normal in other places.
How can i solve this problem?

A: The best option would probably be to install unity-tweak-tool using apt-get. From there you can change the settings of the fonts used, including the thickness.


text:
Q: How to overlap navigation bar Anyone had this problem before ?
I  had set my navigation bar to be transparent .When i push to a new view controller the view does not overlap the navigation bar . It leaves a white spaces which i don't want to . I want the uiview to be full to the top of the screen rather than below the navigation bar because i want it to be transparent so that it show the transparent navigation bar with image view  .
Here some example
https://www.dropbox.com/s/teuhsdt6u4agr6e/Screen%20Shot%202016-02-25%20at%205.21.14%20PM.png?dl=0

A: Navigation bar is not there on the image you put as example. It looks like an image view positioned an appropriate amount of space below the top.
Navigation bar will always be visible if there is one. If you don't want the navigation bar to be displayed, present the view controller instead of pushing it onto the navigation stack.


text:
Q: cURL get url from redirect I'm currently using cURL to try and get the URL from a redirect for a website scraper. I only need the url from the website. I've researched on stackoverflow and other sites for the past couple days and have been unsuccessful. The code I'm currently using is from this website:
  $url = "http://www.someredirect.com";
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HEADER, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
  curl_setopt($ch, CURLOPT_NOBODY, true);
  $response = curl_exec($ch);
  preg_match_all('/^Location:(.*)$/mi', $response, $matches);
  curl_close($ch);
  echo !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';

Any help would be greatly appreciated!

A: In your particular case, the server is checking for certain user-agent strings.
When a server checks the user-agent string, it will only respond with a 302 redirect status code when the server sees a "valid" (according to the server) user-agent. Any "invalid" user-agents will not receive the 302 redirect status code response or Location: header.
In your particular case, when the server receives a request from an "invalid" user-agent it responds with a 200 OK status code with no text in the response body.
(Note: in the code below, the actual URLs provided have been replaced with examples.)
Let's say that http://www.example.com's server checks the User-Agent string and that http://www.example.com/product/123/ redirects to http://www.example.org/abc.
In PHP your solution would be:
<?php

$url = 'http://www.example.com/product/123/';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64; rv:21.0) Gecko/20100101 Firefox/21.0"); // Necessary. The server checks for a valid User-Agent.
curl_exec($ch);

$response = curl_exec($ch);
preg_match_all('/^Location:(.*)$/mi', $response, $matches);
curl_close($ch);

echo !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';

And, the output of this script would be: http://www.example.org/abc.

A: Try using this code:
function curl_last_url(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
$mr = $maxredirect === null ? 5 : intval($maxredirect);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    if ($mr > 0) {
        echo $mr;
        echo $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

        $rch = curl_copy_handle($ch);
        curl_setopt($rch, CURLOPT_HEADER, true);
        curl_setopt($rch, CURLOPT_NOBODY, true);
        curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
        curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
        do {
            curl_setopt($rch, CURLOPT_URL, $newurl);
            $header = curl_exec($rch);
            if (curl_errno($rch)) {
                $code = 0;
            } else {
                $code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
                echo $code;
                if ($code == 301 || $code == 302) {
                    preg_match('/Location:(.*?)\n/', $header, $matches);
                    $newurl = trim(array_pop($matches));
                } else {
                    $code = 0;
                }
            }
        } while ($code && --$mr);
        curl_close($rch);
        if (!$mr) {
            if ($maxredirect === null) {
                trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
            } else {
                $maxredirect = 0;
            }
            return false;
        }
        curl_setopt($ch, CURLOPT_URL, $newurl);
    }
return $newurl;

}


text:
Q: Firbase orderbychild not snowing all data I am making a project that is send friend request show pending request this is my project.
In my script it shows the names of those who accepted the friend request and the others show addfriends and the names of those who have given friend requests but did not accept do not show all the names but show 2 to 1. I tried a lot but couldn't help anyone.
Firebase json database

{
  "notifications": {
    "-N964r-hlIFTn5i14bx9": {
      "dateTime": "10/08/2022, 15:30:36",
      "name": "Joseph Woody",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmk_mfI1qcVtlSQzB952yWUODl-Ur_2TUxCdEcd2=s96-c",
      "sendFrom": "-N9640stAoDzUjqmghtf",
      "sendTo": "-N8rnaIorXRyiQ1Fe0xD",
      "status": "Accept"
    },
    "-N964v7XylvFfGhMQ5gp": {
      "dateTime": "10/08/2022, 15:30:52",
      "name": "ABIR gaming",
      "photo": "https://lh3.googleusercontent.com/a-/AFdZucqY1wofPZNptkjPuF210noURTHlRVp420JnVYp2=s96-c",
      "sendFrom": "-N8rnWikyHCym4bb-RbW",
      "sendTo": "-N8rnaIorXRyiQ1Fe0xD",
      "status": "Accept"
    },
    "-N965-HmgGNRLYKinhLq": {
      "dateTime": "10/08/2022, 15:31:13",
      "name": "Abir Abir",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmlukAObU-2T4ZWTxb_euiT5h-fCtRGlT1JE52u4=s96-c",
      "sendFrom": "-N963am1cYtt60eGAciU",
      "sendTo": "-N8rnaIorXRyiQ1Fe0xD",
      "status": "Accept"
    },
    "-N9653z8w6DPHMUMGZWm": {
      "dateTime": "10/08/2022, 15:31:33",
      "name": "ABIR ABIR",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmkgujGQC2_a_VB-7jS8QFLngjuTGmbJfQzOvbPC=s96-c",
      "sendFrom": "-N8roNhXRcZEdQSkmU-Z",
      "sendTo": "-N8rnaIorXRyiQ1Fe0xD",
      "status": "Accept"
    },
    "-N9654nVjBPG7su1Moc_": {
      "dateTime": "10/08/2022, 15:31:36",
      "name": "ABIR ABIR",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmkgujGQC2_a_VB-7jS8QFLngjuTGmbJfQzOvbPC=s96-c",
      "sendFrom": "-N8roNhXRcZEdQSkmU-Z",
      "sendTo": "-N9640stAoDzUjqmghtf",
      "status": "Accept"
    },
    "-N965_2LkLZHmvDJwrLu": {
      "dateTime": "10/08/2022, 15:33:44",
      "name": "ABIR ABIR",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmkgujGQC2_a_VB-7jS8QFLngjuTGmbJfQzOvbPC=s96-c",
      "sendFrom": "-N8roNhXRcZEdQSkmU-Z",
      "sendTo": "-N963am1cYtt60eGAciU",
      "status": "Pending"
    },
    "-N965_96c7ZBC_8PA2BY": {
      "dateTime": "10/08/2022, 15:33:45",
      "name": "ABIR ABIR",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmkgujGQC2_a_VB-7jS8QFLngjuTGmbJfQzOvbPC=s96-c",
      "sendFrom": "-N8roNhXRcZEdQSkmU-Z",
      "sendTo": "-N8roD7WBYMrfguNZooD",
      "status": "Pending"
    },
    "-N965_F9NYr7J7Edgfqw": {
      "dateTime": "10/08/2022, 15:33:45",
      "name": "ABIR ABIR",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmkgujGQC2_a_VB-7jS8QFLngjuTGmbJfQzOvbPC=s96-c",
      "sendFrom": "-N8roNhXRcZEdQSkmU-Z",
      "sendTo": "-N8rnWikyHCym4bb-RbW",
      "status": "Pending"
    },
    "-N965_KKUC0R6ULkVN6o": {
      "dateTime": "10/08/2022, 15:33:46",
      "name": "ABIR ABIR",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmkgujGQC2_a_VB-7jS8QFLngjuTGmbJfQzOvbPC=s96-c",
      "sendFrom": "-N8roNhXRcZEdQSkmU-Z",
      "sendTo": "-N8rnNEE96tLpae7w9V5",
      "status": "Pending"
    },
    "-N965dcYJ_UpOux7UGG-": {
      "dateTime": "10/08/2022, 15:34:03",
      "name": "Joseph Woody",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmk_mfI1qcVtlSQzB952yWUODl-Ur_2TUxCdEcd2=s96-c",
      "sendFrom": "-N9640stAoDzUjqmghtf",
      "sendTo": "-N8rnNEE96tLpae7w9V5",
      "status": "Pending"
    },
    "-N965duKm3qFUQvIxtsb": {
      "dateTime": "10/08/2022, 15:34:04",
      "name": "Joseph Woody",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmk_mfI1qcVtlSQzB952yWUODl-Ur_2TUxCdEcd2=s96-c",
      "sendFrom": "-N9640stAoDzUjqmghtf",
      "sendTo": "-N8roD7WBYMrfguNZooD",
      "status": "Pending"
    },
    "-N965e0bwTpC-3CMPJDM": {
      "dateTime": "10/08/2022, 15:34:04",
      "name": "Joseph Woody",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmk_mfI1qcVtlSQzB952yWUODl-Ur_2TUxCdEcd2=s96-c",
      "sendFrom": "-N9640stAoDzUjqmghtf",
      "sendTo": "-N8roNhXRcZEdQSkmU-Z",
      "status": "Pending"
    },
    "-N965ePvNVI6vK3gOu-R": {
      "dateTime": "10/08/2022, 15:34:06",
      "name": "Joseph Woody",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmk_mfI1qcVtlSQzB952yWUODl-Ur_2TUxCdEcd2=s96-c",
      "sendFrom": "-N9640stAoDzUjqmghtf",
      "sendTo": "-N963am1cYtt60eGAciU",
      "status": "Pending"
    },
    "-N965eh0nSilf9HL3va8": {
      "dateTime": "10/08/2022, 15:34:07",
      "name": "Joseph Woody",
      "photo": "https://lh3.googleusercontent.com/a/AItbvmk_mfI1qcVtlSQzB952yWUODl-Ur_2TUxCdEcd2=s96-c",
      "sendFrom": "-N9640stAoDzUjqmghtf",
      "sendTo": "-N8rnWikyHCym4bb-RbW",
      "status": "Pending"
    }
  },
  "users": {
    "-N8rnNEE96tLpae7w9V5": {
      "email": "abirhossain6033@gmail.com",
      "name": "ABIR Hossain",
      "photoURL": "https://lh3.googleusercontent.com/a-/AFdZucpdSqIvGmMKroiKFaapilpL6oF4WjbawEY4oMo=s96-c",
      "status": 1660123605643
    },
    "-N8rnWikyHCym4bb-RbW": {
      "email": "abirhossain200019@gmail.com",
      "name": "ABIR gaming",
      "photoURL": "https://lh3.googleusercontent.com/a-/AFdZucqY1wofPZNptkjPuF210noURTHlRVp420JnVYp2=s96-c",
      "status": 1660123944618
    },
    "-N8rnaIorXRyiQ1Fe0xD": {
      "email": "sfaada878@gmail.com",
      "name": "Sfa Ada",
      "photoURL": "https://lh3.googleusercontent.com/a/AItbvmkVE_Sqeb693wTxAmPviHcRqDreThs_Xw5CHzqE=s96-c",
      "status": 1660123922624
    },
    "-N8roD7WBYMrfguNZooD": {
      "email": "hhhahhhaa90@gmail.com",
      "name": "Hhha Hhhaa",
      "photoURL": "https://lh3.googleusercontent.com/a/AItbvmkxV6rxwb5ozhhC5rpYjL68Lri5kEYlQhkXyxA=s96-c",
      "status": 1659867583892
    },
    "-N8roNhXRcZEdQSkmU-Z": {
      "email": "mridul1320@gmail.com",
      "name": "ABIR ABIR",
      "photoURL": "https://lh3.googleusercontent.com/a/AItbvmkgujGQC2_a_VB-7jS8QFLngjuTGmbJfQzOvbPC=s96-c",
      "status": 1660124028462
    },
    "-N963am1cYtt60eGAciU": {
      "email": "abirabut42@gmail.com",
      "name": "Abir Abir",
      "photoURL": "https://lh3.googleusercontent.com/a/AItbvmlukAObU-2T4ZWTxb_euiT5h-fCtRGlT1JE52u4=s96-c",
      "status": 1660123878040
    },
    "-N9640stAoDzUjqmghtf": {
      "email": "formuqeb473@gmail.com",
      "name": "Joseph Woody",
      "photoURL": "https://lh3.googleusercontent.com/a/AItbvmk_mfI1qcVtlSQzB952yWUODl-Ur_2TUxCdEcd2=s96-c",
      "status": 1660124482110
    }
  }
}

<link href="/sdcard/site/plugin/bootstrap.min.css" rel="stylesheet " >


text:
Q: Entity Framework will not work with MySql I have visual studio community 2015 and I have a class library project. I have added the Entity Framework 6, Mysql.Data, MySql.Data.Entity and MySql.Net(not even sure this is needed) package through nuGet.
However when I go through adding an ADO.Net Entity Model to the project via the wizard I get as far as "Choose your version" but I get an error stating that "Your project references the latest version of Entity Framework; However, an Entity Framework database provider compatible with this version could not be found for your data connection......."
My App.config is as follows
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="MyContext" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=hapangodb;uid=root;password=********" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
      </provider></providers>
  </entityFramework>

<system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.6.4.0" newVersion="6.6.4.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

I have tried uninstalling and reinstalling all the mysql components but still get the same issue. I have been using Entity framework with mysql for years with no issues but since getting a new laptop I cant seem to get it to work......
What on earth is going on?

A: Configuration looks correct to me. Just for testing purpose, have you tried adding the below config to your machine.config file and see if that picks up?
<DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>

A: I have solved the issue (Why does it always seem like as soon as you start telling people about code issues you suddenly find them yourself?)
For some reason I had two mysql providers in the App.config. One was simply EF6 the other as you can see is more targeted to 6.9.7.0.
I removed the EF6 one along with the sql server provider (as I will not need it anyway) and now everything works.
I hazard a guess that if the two mysql providers had been the other way around then it would have worked too as it seems to have been trying the first one it came across.


text:
Q: Existence of solution to a system of linear PDEs with boundary conditions I am looking to find a solution, or even just prove the existence of one, to the following system of linear PDEs. They come up in a construction I am trying to work out in symplectic geometry. Here $(r_1, \theta_1, r_2, \theta_2)$ are the polar coordinates on $\mathbb{R}^4$, and $\beta$ and $\gamma$ are smooth functions in terms of those coordinates, that I would like to solve for:
$$2\gamma + r_2\frac{\partial \gamma}{\partial r_2} = 1$$
$$\frac{\partial \beta}{\partial \theta_2}(r_1^2-1) - r_2^2\frac{\partial \gamma}{\partial \theta_1} = 0$$
$$2\beta r_1 + \frac{\partial \beta}{\partial r_1}(r_1^2-1) = r_1$$,
and I need the conditions that $\beta = \gamma = 1$ when $r_1^2 \geq \delta > 0$, and $\beta = r_1$ when $r_1 = 0$ and $\theta_2 = 0, 0.5$. For certain reasons, I know that a solution (i.e. functions $\beta$ and $\gamma$) will not exist if I want $\beta = r_1$ whenever $r_1 = 0$, but I want to know if they might exist around two values of $\theta_2$.

A: The general solution of your equations in a simply connected domain on which $r_2\not=0$ and $r_1\not=\pm1$ is
$$
\beta = \frac12 + \frac1{{(r_1}^2{-}1)}\,
\left(\frac{\partial a}{\partial\theta_1}+b(\theta_1,r_2)\right)
\quad\text{and}\quad
\gamma= \frac12 + \frac1{{r_2}^2}\,
\left(\frac{\partial a}{\partial\theta_2}+c(\theta_2,r_1)\right),
$$
where $a = a(\theta_1,\theta_2)$ is a function of $\theta_1$ and $\theta_2$ only, $b$ is a function of $\theta_1$ and $r_2$ only, and $c$ is a function of $\theta_2$ and $r_1$ only.
To see this, set $\bar\beta = ({r_1}^2{-}1)\bigl(\beta-\tfrac12\bigr)$ and $\bar\gamma = {r_2}^2\bigl(\gamma-\tfrac12\bigr)$ and note that the given equations imply the constant coefficient linear equations
$$
\frac{\partial\bar\beta}{\partial r_1}
= \frac{\partial\bar\gamma}{\partial r_2}
= \frac{\partial\bar\beta}{\partial\theta_2}-\frac{\partial\bar\gamma}{\partial\theta_1} = 0,
$$
which are easily solved.
I do not see how you can choose $a$, $b$, and $c$ so that your 'boundary conditions' are satisfied.  Because the general solution depends on three functions of two variables, one would expect to be able to specify (initial) conditions along a surface in the domain, but not along a hypersurface (which is what boundaries generally are).


text:
Q: Can i start .Net Console Application under custom user? I have a console application that i would like to run as 'MySpecificUser'. Can i specify this user in app.config?

A: No, you can't. By the time the config file is read by the CLR it is too late to specify the user the process runs under. On the other hand you could write a launcher console application in whose config file you specify a username and password which are used to run the actual application using for example this Process.Start overload.

A: You can use the runas utility in order to execute any program as a specific user.
This is not something you could specify in a config, however, not directly.

A: I don't think this is possible by editing the app.config.
You should rather use Process.Start in order to run the process under another user. You will need to provide a password for the user account otherwise it will not work.


text:
Q: How to compare 2 strings in conditional_format in xlsxwriter? I want to compare 2 strings in conditional_format in xlsxwriter. For example, if cell W2 is not equal to neither "Bullish" nor "Bearish", the color of W2 changes to gray color.
My code is like this;
  gray_cell_format = workbook.add_format()
  gray_cell_format.set_font_color('#808080')
  worksheet.conditional_format(f'W2:W{size_dataframe}', {'type': 'formula',
                                                               'criteria': '=IF(ISNA(MATCH($W2, {"Bullish","Bearish"}, 0)),"YES","NO")',
                                                               'format': gray_cell_format})

However, it doesn't work.


text:
Q: How to release resources if a program crashes I have a program that uses services from others. If the program crashes, what is the best way to close those services? At server side, I would define some checkers that monitor if a client is invalid periodically. But can we do any thing at client? I am not the sure if the normal RAII still works at this case. My code is written in C and C++.

A: If your application experiences a hard crash, then no, your carefully crafted cleanup code will not run, whether it is part of an RAII paradigm or a method you call at the end of main. None of an application's cleanup code runs after a crash that causes the application to be terminated.
Of course, this is not true for exceptions. Although those might eventually cause the application to be terminated, they still trigger this termination in a controlled way. Generally, the runtime library will catch an unhandled exception and trigger termination. Along the way, your RAII-based cleanup code will be executed, unless it also throws an exception. Then you're back to being unceremoniously ripped out of memory.
But even if your application's cleanup code can't run, the operating system will still attempt to clean up after you. This solves the problem of unreleased memory, handles, and other system objects. In general, if you crash, you need not worry about releasing these things. Your application's state is inconsistent, so trying to execute a bunch of cleanup code will just lead to unpredictable and potentially erroneous behavior, not to mention wasting a bunch of time. Just crash and let the system deal with your mess. As Raymond Chen puts it:

The building is being demolished. Don't bother sweeping the floor and emptying the trash cans and erasing the whiteboards. And don't line up at the exit to the building so everybody can move their in/out magnet to out. All you're doing is making the demolition team wait for you to finish these pointless housecleaning tasks.

Do what you must; skip everything else.
The only problem with this approach is, as you suggest in this question, when you're managing resources that are not controlled by the operating system, such as a remote resource on another system. In that case, there is very little you can do. The best scenario is to make your application as robust as possible so that it doesn't crash, but even that is not a perfect solution. Consider what happens when the power is lost, e.g. because a user's cat pulled the cord from the wall. No cleanup code could possibly run then, so even if your application never crashes, there may be termination events that are outside of your control. Therefore, your external resources must be robust in the event of failure. Time-outs are a standard method, and a much better solution than polling.
Another possible solution, depending on the particular use case, is to run consistency-checking and cleanup code at application initialization. This might be something that you would do for a service that is intended to run continuously and will be restarted promptly after termination. The next time it restarts, it checks its data and/or external resources for consistency, releases and/or re-initializes them as necessary, and then continues on as normal. Obviously this is a bad solution for a typical application, because there is no guarantee that the user will relaunch it in a timely manner.

A: As the other answers make clear, hoping to clean up after an uncontrolled crash (i.e., a failure which doesn't trigger the C++ exception unwind mechanism) is probably a path to nowhere. Even if you cover some cases, there will be other cases that fail and you are building in a serious vulnerability to those cases.
You mention that the source of the crashes is that you are "us[ing] services from others". I take this to mean that you are running untrusted code in-process, which is the potential source of crashes. In this case, you might consider running the untrusted code "out of process" and communicating back to your main process through a pipe or shared memory or whatever. Then you isolate the crashes this child process, and can do controlled cleanup in your main process. A separate process is really the lightest weight thing you can do that gives you the strong isolation you need to avoid corruption in the calling code.
If forking a process per-call is performance-prohibitive, you can try to keep the child process alive for multiple calls.

A: One approach would be for your program to have two modes: normal operation and monitoring.
When started in a usual way, it would :

*

*Act as a background monitor.

*Launch a subprocess of itself, passing it an internal argument (something that wouldn't clash with normal arguments passed to it, if any).

*When the subprocess exists, it would release any resources held at the server.

When started with the internal argument, it would:

*

*Expose the user interface and "act normally", using the resources of the server.

A: You might look into atexit, which may give you the functionality you need to release resources upon program termination. I don't believe it is infallible, though.
Having said that, however, you should really be focusing on making sure your program doesn't crash; if you're hitting an error that is "unrecoverable", you should still invest in some error-handling code. If the error is caused by a Seg-Fault or some other similar OS-related error, you can either enable SEH exceptions (not sure if this is Windows-specific or not) to enable you to catch them with a normal try-catch block, or write some Signal Handlers to intercept those errors and deal with them.


text:
Q: How to create a Stage by nativeHandle (hwnd) in JavaFX I use JNA and connected an external dll. Library function creates a window and returns nativeHandle (windowHandle, hWnd).
How to create a Stage by nativeHandle?


text:
Q: Master Theorem - $T(n)=2T(\frac{n}{4})+1$ Hello Mathematics Community,
I tried to solve
$T(n)=2T(\frac{n}{4})+1$
with the Master-Theorem.
$Case$ $3:$
$a=2$ ; $b=4$ ; $f(n)=1$
$n^{log_b\,a}$ $=$ $n^{log_42}=n^{0.5}$
Condition: $ f(n)\in \Omega(n^{log_ba+\epsilon)} \, for \, \epsilon>0 $
$= 1\in\Omega(n^{0.5+\epsilon}) $
$Let \, \epsilon>0$ ; $ \epsilon=0.5 $
$ 1\in \Omega(n) \ with \, \epsilon=0.5 $
$Condition\, 2:$
$af(\frac{n}{b})\leq cf(n)$
$= 2(\frac{n}{4})^1 \leq cn $
true for $c=1$
$\Rightarrow T(n) = \Theta(n) $
Is this true or is there a mistake ?
sincerely,
M.Hisoka

A: $1$ isn't in $\Omega(n^{1/2+\varepsilon})$, it's in $O(n^{1/2-\varepsilon})$. Also $af(n/b) \le cf(n)$ is equivalent to $a \le c$ since $f(n) = 1$.


text:
Q: My sudoku solving program always returning unsolved grid My program uses backtracking for solving sudoku puzzles. Below is my full code of the class. In this puzzle I am expecting two results. In the solve() function there I print the grid just to verify it works, which works and all fields are correctly used. The problems begin, where I need my program to save the grid at that point into the solvedGrids list. Where I then just in the solveSudoku() function (which is run from Main()) just print every grid in the list, but it returns the unsolved grid. I don't know why it does that, because where I first print the grid it does it correctly. (print() and print2() are the same, the print2() looks better). But when I try to add it in a list all progress goes to a loss. Below will also be an example of what I get after running the program and the Program.cs file
Solver.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SudokuConsole
{
    public class Solver
    {
        private int[][] grid;
        private int[][] grid2;
        private List<int[][]> solvedGrids;

        public Solver()
        {
            grid = new int[9][];
            grid[0] = new int[] { 5, 3, 0, 0, 7, 0, 0, 0, 0 };
            grid[1] = new int[] { 6, 0, 0, 1, 9, 5, 0, 0, 0 };
            grid[2] = new int[] { 0, 9, 8, 0, 0, 0, 0, 6, 0 };
            grid[3] = new int[] { 8, 0, 0, 0, 6, 0, 0, 0, 3 };
            grid[4] = new int[] { 4, 0, 0, 8, 0, 3, 0, 0, 1 };
            grid[5] = new int[] { 7, 0, 0, 0, 2, 0, 0, 0, 6 };
            grid[6] = new int[] { 0, 6, 0, 0, 0, 0, 2, 8, 0 };
            grid[7] = new int[] { 0, 0, 0, 4, 1, 9, 0, 0, 5 };
            //grid[8] = new int[] { 0, 0, 0, 0, 8, 0, 0, 7, 9 };
            grid[8] = new int[] { 0, 0, 0, 0, 8, 0, 0, 0, 0 };
            solvedGrids = new List<int[][]>();
        }

        public void print()
        {
            Console.Write("[");
            for (int x = 0; x < grid.Length; x++)
            {
                Console.Write("[");
                for (int y = 0; y < grid[x].Length; y++)
                {
                    Console.Write(grid[x][y]);
                    if (y + 1 < grid[x].Length)
                        Console.Write(", ");
                }
                Console.Write("]");
                if (x + 1 < grid.Length)
                    Console.Write(", ");
            }
            Console.Write("]\n");
        }

        public void print2(int[][] grid2)
        {
            Console.Write("[");
            for (int x = 0; x < grid2.Length; x++)
            {
                if (x != 0)
                    Console.Write(" ");
                Console.Write("[");
                for (int y = 0; y < grid2[x].Length; y++)
                {
                    Console.Write(grid2[x][y]);
                    if (y + 1 < grid2[x].Length)
                        Console.Write(" ");
                }
                Console.Write("]");
                if (x + 1 < grid2.Length)
                    Console.Write("\n");
            }
            Console.Write("]\n");
        }

        public bool possible(int y, int x, int n)
        {
            for (int i = 0; i < 9; i++)
            {
                if (grid[y][i] == n)
                    return false;
            }
            for (int i = 0; i < 9; i++)
            {
                if (grid[i][x] == n)
                    return false;
            }
            double x0d = x / 3;
            double y0d = y / 3;
            int x0 = (Convert.ToInt32(Math.Floor(x0d))) * 3;
            int y0 = (Convert.ToInt32(Math.Floor(y0d))) * 3;
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    if (grid[y0 + i][x0 + j] == n)
                        return false;
                }
            }
            return true;
        }

        public void solve()
        {
            for (int y = 0; y < 9; y++)
            {
                for (int x = 0; x < 9; x++)
                {
                    if (grid[y][x] == 0)
                    {
                        for (int n = 1; n < 10; n++)
                        {
                            if (possible(y, x, n))
                            {
                                grid[y][x] = n;
                                solve();
                                grid[y][x] = 0;
                            }
                        }
                        return;
                    }
                }
            }
            print(); //Here I print, just to see that it works.
            solvedGrids.Add(grid); //Adding the solved grid to the list
        }

        public void solveSudoku()
        {
            solve();
            foreach (int[][] x in solvedGrids)
            {
                print2(x); //Printing out the solved grid.
            }
        }

    }
}

Program.cs
using System;

namespace SudokuConsole
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Solver solver = new Solver();
            solver.solveSudoku();
        }
    }
}

And here is what I get:
[[5, 3, 4, 6, 7, 8, 1, 9, 2], [6, 7, 2, 1, 9, 5, 3, 4, 8], [1, 9, 8, 3, 4, 2, 5, 6, 7], [8, 5, 9, 7, 6, 1, 4, 2, 3], [4, 2, 6, 8, 5, 3, 9, 7, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 6, 1, 5, 3, 7, 2, 8, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 4, 5, 2, 8, 6, 7, 1, 9]]
[[5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 5, 3, 4, 8], [1, 9, 8, 3, 4, 2, 5, 6, 7], [8, 5, 9, 7, 6, 1, 4, 2, 3], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 6, 1, 5, 3, 7, 2, 8, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 4, 5, 2, 8, 6, 1, 7, 9]]
[[5 3 0 0 7 0 0 0 0]
 [6 0 0 1 9 5 0 0 0]
 [0 9 8 0 0 0 0 6 0]
 [8 0 0 0 6 0 0 0 3]
 [4 0 0 8 0 3 0 0 1]
 [7 0 0 0 2 0 0 0 6]
 [0 6 0 0 0 0 2 8 0]
 [0 0 0 4 1 9 0 0 5]
 [0 0 0 0 8 0 0 0 0]]
[[5 3 0 0 7 0 0 0 0]
 [6 0 0 1 9 5 0 0 0]
 [0 9 8 0 0 0 0 6 0]
 [8 0 0 0 6 0 0 0 3]
 [4 0 0 8 0 3 0 0 1]
 [7 0 0 0 2 0 0 0 6]
 [0 6 0 0 0 0 2 8 0]
 [0 0 0 4 1 9 0 0 5]
 [0 0 0 0 8 0 0 0 0]]


text:
Q: How to serialize/deserialize a JS observable? If I have an observable stream, using RxJS or similar, like this (marble diagram):
----1------2------3--4---|

How can I serialize that to a format like NDJSON so I can save it in a database? Once it's saved, how can I reconstitute it as an observable?
For context, I want to capture a stream of user actions in the DOM (like mouse drags, etc.) and then replay them at a later time exactly the same as the user initially performed it.

A: If time is of the importance, you might want to store the time value along with the events themselves.
Little POC:
import { fromEvent, Observable, of, timer } from "rxjs";
import {
  map,
  tap,
  mergeMap,
  concatMap,
  takeUntil,
  mapTo
} from "rxjs/operators";

let latestCache: Array<{ time: number; event: MouseEvent }>;

fromEvent(document.getElementById("start-cache"), "click")
  .pipe(
    concatMap(() => {

      const source = fromEvent(window, "mousemove").pipe(
        tap((x: MouseEvent) => console.log(x.clientX, x.clientY)),
        takeUntil(timer(1000)),
        store( newCache => (latestCache = newCache))
      );

      function store(
        onCacheCreated: (
          cache: Array<{ time: number; event: MouseEvent }>
        ) => void
      ) {
        const cache = [];
        let lastTime = Date.now();
        return tap({
          next: (x: MouseEvent) => {
            cache.push({ time: Date.now() - lastTime, event: x });
            lastTime = Date.now();
          },
          complete: () => onCacheCreated(cache)
        });
      }

      return source;
    })
  )
  .subscribe();

fromEvent(document.getElementById("replay-cache"), "click")
  .pipe(
    concatMap(() => {
      if (!latestCache) {
        console.error("no cache yet");
      }
      return of(...latestCache).pipe(
        concatMap(x => timer(x.time).pipe(mapTo(x.event))),
        tap((x: MouseEvent) => console.log(x.clientX, x.clientY))
      );
    })
  )
  .subscribe();

RxJS playground

Open the console below to see results

<button id="start-cache">Start Cache </button>
<button id="replay-cache">Replay Cache </button>

https://stackblitz.com/edit/rxjs-vxwurq?file=index.ts
From here on, you can store the array however you want, using the onCacheCreated function.


text:
Q: How to open UITextView web links in a UIWebView instead of Safari? I'm developing and iPhone 3.0 application. And I'm trying to open web links in a UITextView into a UIWebView instead of Safari. But still no luck.
The UITextView is not editable, and it perfectly detects web links and open them in Safari.
How to avoid that? How to grab that url so i can use with my own UIWebView?

A: With Swift 3, UITextViewDelegate provides a textView(_:shouldInteractWith:in:interaction:) method. textView(_:shouldInteractWith:in:interaction:) has the following declaration:

Asks the delegate if the specified text view should allow the specified type of user interaction with the given URL in the given range of text.

optional func textView(_ textView: UITextView,  shouldInteractWith URL: URL,  in characterRange: NSRange,  interaction: UITextItemInteraction) -> Bool

The following code shows how to open UITextView web links in a SFSafariViewController instead of opening them in Safari app:
import UIKit
import SafariServices

class ViewController: UIViewController, UITextViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set textView
        let textView = UITextView()
        textView.text = "http://www.yahoo.fr http://www.google.fr"
        textView.isUserInteractionEnabled = true
        textView.isEditable = false
        textView.isSelectable = true
        textView.dataDetectorTypes = UIDataDetectorTypes.link

        // Add view controller as the textView's delegate
        textView.delegate = self

        // auto layout
        view.addSubview(textView)
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        textView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        textView.heightAnchor.constraint(equalToConstant: 300).isActive = true
        textView.widthAnchor.constraint(equalToConstant: 300).isActive = true
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        // Open links with a SFSafariViewController instance and return false to prevent the system to open Safari app
        let safariViewController = SFSafariViewController(url: URL)
        present(safariViewController, animated: true, completion: nil)

        return false
    }

}

A: The simplest way is to override the webView:decidePolicyForNavigationAction:request:frame:decisionListener: method on UITextView like so:
@interface UITextView (Override)
@end

@class WebView, WebFrame;
@protocol WebPolicyDecisionListener;

@implementation UITextView (Override)

- (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener
{
    NSLog(@"request: %@", request);
}
@end

This will affect all UITextViews in your application. If you only require this on a single view, create a subclass and override the method on that.
Note: this is technically a private API and could be removed at any time. There is no way to do this via the public API.
edit: as of iOS 7.0 a new method has been introduced on UITextViewDelegate to support this. See nihad's answer for details.

A: This is an old question but incase anyone is looking for an updated way of doing this.
Assign your viewController that holds the UITextView as a delegate in your viewController's .m file and just add:
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{

    //Do something with the URL
    NSLog(@"%@", URL);

    return NO;
}


text:
Q: Django - selectively query models using pk_url_kwarg Consider the these two models and view:
models.py
class BHA_List(models.Model):
    well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list')
    bha_number = models.CharField(max_length=100)

class BHA_overall(models.Model):
    bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall')
    drill_str_name = models.CharField(max_length=111)
    depth_in = models.CharField(max_length=111)

views.py
class BHA_UpdateView(UpdateView):
    model = BHA_overall
    pk_url_kwarg = 'pk_alt'
    form_class = BHA_overall_Form

To my understanding, pk_url_kwarg = 'pk_alt' will query and return instances of model = BHA_overall.
Let's say that I use a different CBV other than UpdateView, and want to implement two models. So something like this:
model = (BHA_overall, BHA_List). Is there any way that I force my pk_url_kwarg = 'pk_alt' to query and return instances only in BHA_List, but force my get_object() return objects in BHA_overall?? What CBV should I use?

A: you can use just 'View' and define methods post and get.
about like this:
class SomeView(View):
      model = BHA_List
      template_name = 'some.html'
      def get(request, **kwargs):
          overall = BHA_overall.objects.all()
          return render(request,
                        self.template_name,
                        locals())
      def get(request, **kwargs):
          return render(request, self.template_name, {})


text:
Q: MongoDB - Assertion failure isOk() db/pdfile.h I've used mongodb a few days, it has been working fine until today.
I got a error when querying a database.
Wed Nov  2 17:56:44 [initandlisten] connection accepted from 127.0.0.1:49234 #1
Wed Nov  2 17:56:45 [conn1] command admin.$cmd command: { listDatabases: 1 } ntoreturn:1 reslen:338 813ms
Wed Nov  2 17:56:46 [conn1]  admin.system.namespaces Assertion failure isOk() db/pdfile.h 300
0x10007d703 0x100087eec 0x1004165e4 0x10040774b 0x100410823 0x100437df9 0x1004b3006 0x100426693 0x100426b53 0x100429f45 0x10042d8f0 0x10043109e 0x10043353b 0x10043662a 0x1004a13ca 0x1003d5e0f 0x1003e298a 0x100603394 0x100148d8c 0x10060a554
 0   mongod                              0x000000010007d703 _ZN5mongo12sayDbContextEPKc + 195
 1   mongod                              0x0000000100087eec _ZN5mongo8assertedEPKcS1_j + 300
 2   mongod                              0x00000001004165e4 _ZN5mongo11DataFileMgr9getExtentERKNS_7DiskLocE + 148
 3   mongod                              0x000000010040774b _ZN5mongo11DataFileMgr7findAllEPKcRKNS_7DiskLocE + 75
 4   mongod                              0x0000000100410823 _ZN5mongo13findTableScanEPKcRKNS_7BSONObjERKNS_7DiskLocE + 131
 5   mongod                              0x0000000100437df9 _ZNK5mongo9QueryPlan9newCursorERKNS_7DiskLocEi + 1081
 6   mongod                              0x00000001004b3006 _ZN5mongo11UserQueryOp5_initEv + 214
 7   mongod                              0x0000000100426693 _ZN5mongo7QueryOp4initEv + 323
 8   mongod                              0x0000000100426b53 _ZN5mongo12QueryPlanSet6Runner6initOpERNS_7QueryOpE + 35
 9   mongod                              0x0000000100429f45 _ZN5mongo12QueryPlanSet6Runner4initEv + 245
 10  mongod                              0x000000010042d8f0 _ZN5mongo12QueryPlanSet6Runner22runUntilFirstCompletesEv + 32
 11  mongod                              0x000000010043109e _ZN5mongo12QueryPlanSet5runOpERNS_7QueryOpE + 334
 12  mongod                              0x000000010043353b _ZN5mongo16MultiPlanScanner9runOpOnceERNS_7QueryOpE + 1115
 13  mongod                              0x000000010043662a _ZN5mongo16MultiPlanScanner5runOpERNS_7QueryOpE + 26
 14  mongod                              0x00000001004a13ca _ZN5mongo8runQueryERNS_7MessageERNS_12QueryMessageERNS_5CurOpES1_ + 3194
 15  mongod                              0x00000001003d5e0f _ZN5mongo13receivedQueryERNS_6ClientERNS_10DbResponseERNS_7MessageE + 623
 16  mongod                              0x00000001003e298a _ZN5mongo16assembleResponseERNS_7MessageERNS_10DbResponseERKNS_11HostAndPortE + 1402
 17  mongod                              0x0000000100603394 _ZN5mongo16MyMessageHandler7processERNS_7MessageEPNS_21AbstractMessagingPortEPNS_9LastErrorE + 148
 18  mongod                              0x0000000100148d8c _ZN5mongo3pms9threadRunEPNS_13MessagingPortE + 700
 19  mongod                              0x000000010060a554 thread_proxy + 132
Wed Nov  2 17:56:46 [conn1] assertion 0 assertion db/pdfile.h:300 ns:admin.system.namespaces query:{}
Wed Nov  2 17:56:51 [conn1] end connection 127.0.0.1:49234

I restart the mongod process but no help.
I tried to repair the db but also got the error.
bin: $ ./mongod --repair --dbpath  ../data/db
Wed Nov  2 18:10:51 [initandlisten] MongoDB starting : pid=678 port=27017 dbpath=../data/db 64-bit host=KTs-MacBook-Pro.local
Wed Nov  2 18:10:51 [initandlisten] db version v2.0.0, pdfile version 4.5
Wed Nov  2 18:10:51 [initandlisten] git version: 695c67dff0ffc361b8568a13366f027caa406222
Wed Nov  2 18:10:51 [initandlisten] build info: Darwin erh2.10gen.cc 9.6.0 Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_40
Wed Nov  2 18:10:51 [initandlisten] options: { dbpath: "../data/db", repair: true }
Wed Nov  2 18:10:51 [initandlisten] journal dir=../data/db/journal
Wed Nov  2 18:10:51 [initandlisten] recover : no journal files present, no recovery needed
Wed Nov  2 18:10:51 [initandlisten] ****
Wed Nov  2 18:10:51 [initandlisten] ****
Wed Nov  2 18:10:51 [initandlisten] need to upgrade database admin with pdfile version 4.5, new version: 4.5
Wed Nov  2 18:10:51 [initandlisten]      starting upgrade
Wed Nov  2 18:10:51 [initandlisten]  admin repairDatabase admin
Wed Nov  2 18:10:51 [initandlisten] removeJournalFiles
Wed Nov  2 18:10:51 [initandlisten]  admin.system.namespaces Assertion failure isOk() db/pdfile.h 300
0x10007d703 0x100087eec 0x1004165e4 0x10040774b 0x100410823 0x100437df9 0x1004b3006 0x100426693 0x100426b53 0x100429f45 0x10042d8f0 0x10043109e 0x10043353b 0x10043662a 0x1004a13ca 0x1003d5e0f 0x1003e298a 0x1003e480f 0x1000ed8ec 0x1000c8b73
 0   mongod                              0x000000010007d703 _ZN5mongo12sayDbContextEPKc + 195
 1   mongod                              0x0000000100087eec _ZN5mongo8assertedEPKcS1_j + 300
 2   mongod                              0x00000001004165e4 _ZN5mongo11DataFileMgr9getExtentERKNS_7DiskLocE + 148
 3   mongod                              0x000000010040774b _ZN5mongo11DataFileMgr7findAllEPKcRKNS_7DiskLocE + 75
 4   mongod                              0x0000000100410823 _ZN5mongo13findTableScanEPKcRKNS_7BSONObjERKNS_7DiskLocE + 131
 5   mongod                              0x0000000100437df9 _ZNK5mongo9QueryPlan9newCursorERKNS_7DiskLocEi + 1081
 6   mongod                              0x00000001004b3006 _ZN5mongo11UserQueryOp5_initEv + 214
 7   mongod                              0x0000000100426693 _ZN5mongo7QueryOp4initEv + 323
 8   mongod                              0x0000000100426b53 _ZN5mongo12QueryPlanSet6Runner6initOpERNS_7QueryOpE + 35
 9   mongod                              0x0000000100429f45 _ZN5mongo12QueryPlanSet6Runner4initEv + 245
 10  mongod                              0x000000010042d8f0 _ZN5mongo12QueryPlanSet6Runner22runUntilFirstCompletesEv + 32
 11  mongod                              0x000000010043109e _ZN5mongo12QueryPlanSet5runOpERNS_7QueryOpE + 334
 12  mongod                              0x000000010043353b _ZN5mongo16MultiPlanScanner9runOpOnceERNS_7QueryOpE + 1115
 13  mongod                              0x000000010043662a _ZN5mongo16MultiPlanScanner5runOpERNS_7QueryOpE + 26
 14  mongod                              0x00000001004a13ca _ZN5mongo8runQueryERNS_7MessageERNS_12QueryMessageERNS_5CurOpES1_ + 3194
 15  mongod                              0x00000001003d5e0f _ZN5mongo13receivedQueryERNS_6ClientERNS_10DbResponseERNS_7MessageE + 623
 16  mongod                              0x00000001003e298a _ZN5mongo16assembleResponseERNS_7MessageERNS_10DbResponseERKNS_11HostAndPortE + 1402
 17  mongod                              0x00000001003e480f _ZN5mongo14DBDirectClient4callERNS_7MessageES2_bPSs + 111
 18  mongod                              0x00000001000ed8ec _ZN5mongo14DBClientCursor4initEv + 76
 19  mongod                              0x00000001000c8b73 _ZN5mongo12DBClientBase5queryERKSsNS_5QueryEiiPKNS_7BSONObjEii + 739
Wed Nov  2 18:10:51 [initandlisten] assertion 0 assertion db/pdfile.h:300 ns:admin.system.namespaces query:{}
Wed Nov  2 18:10:51 [initandlisten]  admin clone failed for admin with error: query failed admin.system.namespaces
Wed Nov  2 18:10:51 [initandlisten] removeJournalFiles
Wed Nov  2 18:10:51 [initandlisten]  admin Assertion failure doDBUpgrade( dbName , errmsg , h ) db/db.cpp 298
0x10007d703 0x100087eec 0x1005f4f2f 0x1005f5c3c 0x1005f6274 0x1005f7d6f 0x1000013c4
 0   mongod                              0x000000010007d703 _ZN5mongo12sayDbContextEPKc + 195
 1   mongod                              0x0000000100087eec _ZN5mongo8assertedEPKcS1_j + 300
 2   mongod                              0x00000001005f4f2f _ZN5mongo30repairDatabasesAndCheckVersionEv + 2063
 3   mongod                              0x00000001005f5c3c _ZN5mongo14_initAndListenEi + 1036
 4   mongod                              0x00000001005f6274 _ZN5mongo13initAndListenEi + 36
 5   mongod                              0x00000001005f7d6f main + 3647
 6   mongod                              0x00000001000013c4 start + 52
Wed Nov  2 18:10:51 [initandlisten] exception in initAndListen: 0 assertion db/db.cpp:298, terminating
Wed Nov  2 18:10:51 dbexit:
Wed Nov  2 18:10:51 [initandlisten] shutdown: going to close listening sockets...
Wed Nov  2 18:10:51 [initandlisten] shutdown: going to flush diaglog...
Wed Nov  2 18:10:51 [initandlisten] shutdown: going to close sockets...
Wed Nov  2 18:10:51 [initandlisten] shutdown: waiting for fs preallocator...
Wed Nov  2 18:10:51 [initandlisten] shutdown: lock for final commit...
Wed Nov  2 18:10:51 [initandlisten] shutdown: final commit...
Wed Nov  2 18:10:51 [initandlisten] shutdown: closing all files...
Wed Nov  2 18:10:51 [initandlisten] closeAllFiles() finished
Wed Nov  2 18:10:51 [initandlisten] journalCleanup...
Wed Nov  2 18:10:51 [initandlisten] removeJournalFiles
Wed Nov  2 18:10:51 [initandlisten] shutdown: removing fs lock...
Wed Nov  2 18:10:51 dbexit: really exiting now

The mongodb version is v2.0.0, pdfile version is 4.5, git version is 695c67dff0ffc361b8568a13366f027caa406222.
There are 5 databases in the mongodb, but only one database to be wrong.
I also tried to recover data by mongodump, but got empty bson files.
Any ideas? Thanks

A: I was able to resolve this issue by going to my data directory (which in the example above would be
/data/db

and deleting all the jicd.x and local.x files
If the lock file is not 0 bytes in size you may want to delete that one as well.

A: The mongodb JIRA ticket link is https://jira.mongodb.org/browse/SERVER-4198
As the comments in the ticket, fix the issue by removing the master=true setting then running a repair.
I have not tried this method, just as a reference here.


text:
Q: Как вывести предложение с каждым словом в обратном порядке? не знаю как правильно написать код
def backwards(sentence: str) -> str:
backwards('hello python')
совсем запутался, не понимаю как вывести правильно, выход должен быть таким:
'olleh nohtyp'
буду благодарен за любую помощь

A: вариант 1:
' '.join(i[::-1] for i in text.split())

вариант 2:
' '.join(map(lambda i: i[::-1], text.split()))

вариант 3:
' '.join(map(''.join, map(reversed, text.split())))

вариант 4 (самый короткий):
' '.join(reversed(text[::-1].split()))

вариант 5:
' '.join(reversed(''.join(reversed(text)).split()))

A: def backwards(sentence: str) -> str:
    return ' '.join(w[::-1] for w in sentence.split())


text:
Q: micro sd card help I am running a fresh (full wipe install) of ubuntu 12.04 and I am trying to get my microsd card to work. The card is a samsung 2gb microsd card, and the reader I am using is a usb dongle (targus multi card reader, has been used once on the same computer when I was previously running windows)
The microsd card is inserted into a sandisk microsd to SD adapter.
the reader shows up under lsusb as:
Bus 002 Device 002: ID 058f:6366 Alcor Micro Corp. Multi Flash Reader

I have inserted the dongle and it does recognize the card reader under disk utility. It reads my cd drive, hard drive, and my "multiple card reader" and it reads the storage space as 2gb. However it says it is not partitioned?
If I use the disk utility to attempt to format the volume (not the drive, as it seems to be referring to the card reader itself), it fails and says the following
an error occurred while performing an operation on "2.0gb unrecognized" (whole-disk volume on multiple card reader): the operation failed
with the following details:
Error creating file system: helper exited with exit code 1: Error calling fsync(2) on /dev/sdb: Input/output error

To be honest I don't care if I get the card working. All I need to do is get the sd card as bootable for a project (trying to root my friend's nook tablet).
Suggestions? I would prefer to try fighting with this before going and trying to purchase a new card reader.

A: You need to unmount the card via Disk Utility, then format each partition on the card to create one partition, then format the card itself and create a new partition to your liking.
Some people struggle with Disk Utility logic in which case you could use Windows to format as usual and then plug it back into your Ubuntu machine.


text:
Q: how can i concatenate determined number of characters with another string? I'm new to programming and I'm trying to make a function that can concatenate determined number of characters to another string. It's counting the number of characters correctly but it wont display like the task wants.
Anyone could explain me why?
An example would be (expected output):
String 1: Testing
String 2: String
N: 4 (Value is asked for the user)
Result: TestingStri
My code so far is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void ConcatenateString(char *string, char *string2);
int main()
{

   char string[100];
   char string2[100];

   ConcatenateString(string, string2);
   DisplayStrings(string, string2);

}
void ConcatenateString(char *string, char *string2)
{
    int N;
    system("cls");
    printf ("First string: ");
    gets(string);
    fflush(stdin);
    printf ("Second string: ");
    gets(string2);
    printf("Number of characters: ");
    scanf ("%d", &N);

    int i;
    int count = 0;
    for(i=0;string2[i];i++)
    {
        count++;
    }

    while (count < N)
    {
        string2[count++] = string2[i];
    }
    strcat(string,string2);
}
void DisplayStrings(char *string, char *string2)
{
    printf("\nFirst String:\n");
    printf("%s\n", string);
    printf("\nSecond String:\n");
    printf("%s\n", string2);

}

The wrong (actual) output:
String 1: Testing
String 2: String
N: 4
Output: TestingString

It's not really displaying 4 characters from string 2 (for example) that I ask for.

A: for(i=0;string2[i];i++)
{
    count++;
}

This code counts the number of bytes in string2. I think you want string here instead.

while (count < N)
{
    string2[count++] = string2[i];
}

This code copies stuff in string2 from one place to the other. I think you want to copy from string2 to string instead.

strcat(string,string2);

This code concatenates string and string2. You definitely don't need this; it will only confuse you when you display the result.

A: Which book are you reading?
The pervasive errors you have are common for the populous who don't read books. That is to say, from my observations, those who read books don't have these kinds of problems...

*

*system("cls"); makes no sense when you learn from a nice book, as it defeats the purpose of the lesson it should teach: use the most appropriate tool for the job, and if you want to clear the screen that tool is a user interface other than the console. Don't clear consoles, and certainly don't use cls to do so. Consider anyone who uses Unix (and so no cls command exists); at best your code will show an error, and at worst cls could be a malicious program.

*Older books are still using gets, but that has been deprecated. Consider using fgets instead.

*You should never fflush(stdin). On that note, you should probably fflush(stdout) when you're writing data that doesn't end with '\n' to stdout.

*int n = scanf(...); make sure you check n... and don't just guess; read the manual.

int i;
int count = 0;
for(i=0;string2[i];i++)
{
    count++;
}

Since count and i both increment synchronously and start at 0, they'll both be equal to strlen(string2) here. You should just write count = strlen(string2);... on that note, these variables should be size_t, rather than int.

while (count < N)
{
    string2[count++] = string2[i];
}

This is undefined behaviour, at least for values of N that are larger than string2. It's essentially memset(string2 + count, '\0', N - count); that is to say, all you are doing here is zeroing the bytes at the end of the array. You don't need this code. Get rid of it. Burn it in fire!

fgets(string, sizeof string, stdin);
fgets(string2, sizeof string2, stdin);

strcat(string,string2);

Ahh, why didn't you do that in the first place? Don't forget to remove the newline characters...

A: As others have told you, never use gets() as it is infamous for its security issues.  Read this.
Use fgets() like
char str[100];
fgets(str, 100, stdin);

You may check the value returned by fgets() to see if all went well. NULL is returned on error.
fgets() will read in the trailing \n as well. You may remove it like
size_t l=strlen(str);
if(str[l-1]=='\n')
{
    str[l-1]='\0';
}

to replace the \n with \0 denoting end of string.

To concatenate n characters of a string str2 to str1 (assuming that str1 has enough space. Checks against overflow must be in place when you do this), you could do
sprintf(str1, "%s%.*s", str1, n, str2);

The value of n will stand in for the * in the format string. So if n is 4, it will be %.4s which means the first 4 characters from the corresponding string.
Before doing this, check if str1 has enough space with something like
if(strlen(str1)+n+1 < 100)// where 100 is the size of the character array str1
{
    sprintf(......);//the sprintf() call
}

See this post to see why fflush(stdin) is not considered good.
And this to see why the use of system() is better avoided.


text:
Q: Using gsub with pattern and x as vector I'm facing this problem, let's db a data.table object defined as below :
              X    Y
1:     Joe Snow  Joe
2: Sony Ericson Sony
3:    JP Morgan   JP
4:     KATAKURI   NA

I want then to delete Y from X, like this :
db[!is.na(Y), Z := sub(pattern = Y, replacement = "", x = X)]

As you can imagine, it does not work, because sub accepts only a single character as pattern.
I tried this trick, but does not work :
db[, pos := 1]
db[!is.na(Y), Z := sub(pattern = Y, replacement = "", x = X), by = .(pos)]

Do you have any solution for this?

A: If we are looking for corresponding elements of 'X' and 'Y' in the sub then Map can be used
db[!is.na(Y), Z := unlist(Map(sub, pattern = Y, X, replacement = ""))]
db
#             X    Y        Z
#1:     Joe Snow  Joe     Snow
#2: Sony Ericson Sony  Ericson
#3:    JP Morgan   JP   Morgan
#4:     KATAKURI   NA       NA

Or another option is map/pmap functions from purrr
library(purrr)
library(dplyr)
db %>%
   set_names(c('x', 'pattern')) %>%
   pmap_chr(., sub, replacement = '') %>%
   trimws %>%
   bind_cols(db, z = .)
#              X    Y       z
#1:     Joe Snow  Joe    Snow
#2: Sony Ericson Sony Ericson
#3:    JP Morgan   JP  Morgan
#4:     KATAKURI   NA      NA


text:
Q: Issues assigning value inside a service function in angular 6 I kind of lost here, I trying to assign a value to my variable in a function inside my Service, And i cant understand what is the problem. From inside the subscription it seems that its working, but when i try to call it is undefined
I trying to assign value to this variable: private userInfo: any Inside the autoAuthUser() Function
The funny thing that if i console.log the userInfo from my logout function, It showing the value
This is my service:
import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Subject } from "rxjs";
import { Router } from "@angular/router";
import { SignUpData } from "../models/sign-up.model";
import { LogInData } from "../models/log-in.model";
import { User } from "../models/user";
import { computeStyle } from "../../../node_modules/@angular/animations/browser/src/util";
import { TouchSequence } from "../../../node_modules/@types/selenium-webdriver";

@Injectable({ providedIn: "root" })
export class AuthService {
    private isAuthenticated = false
    private token: string
    private authStatusListner = new Subject<boolean>()
    private tokenTimer: any
    private isAdmin: boolean
    private userInfo: any

    signupUrl = "http://localhost:3000/signup";
    loginUrl = "http://localhost:3000/login"

    constructor(private http: HttpClient,
        private router: Router) { }

    getToken() {
        return this.token
    }

    checkIfAdmin() {
        return this.isAdmin
    }

    getAuthStatus() {
        return this.isAuthenticated

    }

    getAuthStatusListner() {
          return this.authStatusListner.asObservable()
    }

    // Cheacking if the user have the login token in the local storage for autoLogin and the exparation date
    autoAuthUser() {
        const AuthInformation = this.getAuthData()
        if (!AuthInformation) {
            return
        }
        const now = new Date();
        const expairesIn = AuthInformation.expirationDate.getTime() - now.getTime();
        if (expairesIn > 0) {
            this.token = AuthInformation.token
            this.setAuthTimer(expairesIn / 1000)
            this.autoLogin().subscribe(user => {
                this.userInfo = user
                console.log(this.userInfo)
            })
            this.authStatusListner.next(true)
            this.isAuthenticated = true
        }
    }

    getUserInfo() {
        if (this.token) {
            console.log(this.userInfo)
            return this.userInfo
        }
    }

    createUser(name: string, email: string, password: string) {
        const authData: SignUpData = { name: name, email: email, password: password }
        this.http.post(this.signupUrl, authData)
            .subscribe(response => {
            });
    }

    autoLogin() {
        return this.http.get<{ user: any }>(this.loginUrl)
    }

    login(email: string, password) {
        const authData: LogInData = { email: email, password: password }
        this.http.post<{ token: string, expiresIn: number, isAdmin: boolean, user: any }>(this.loginUrl, authData)
            .subscribe(response => {
                const token = response.token
                this.token = token;
                if (token) {
                    if (response.isAdmin) {
                        this.isAdmin = response.isAdmin
                    }
                    this.userInfo = response.user
                    const expiersInDuration = response.expiresIn
                    this.setAuthTimer(expiersInDuration)
                    this.isAuthenticated = true
                    this.authStatusListner.next(true);
                    const now = new Date;
                    const expirationDate = new Date(now.getTime() + expiersInDuration * 1000)
                    this.saveAuthData(token, expirationDate)
                    this.router.navigate(['/user'])
                }
            });
    }

    // User logout
    logout() {
        this.token = null
        this.isAuthenticated = false
        this.isAdmin = false
        this.authStatusListner.next(false)
        clearTimeout(this.tokenTimer)
        this.clearAuthData()
        this.router.navigate(['/user'])
        console.log(this.userInfo)

    }

    // Setting the timer for the token expiration
    private setAuthTimer(duration: number) {
        this.tokenTimer = setTimeout(() => {
            this.logout();
        }, duration * 1000)
    }

    // Setting the Auth token in the local storage
    private saveAuthData(token: string, expirationDate: Date) {
        localStorage.setItem("token", token)
        localStorage.setItem("expiration", expirationDate.toISOString())

    }

    // Clearing the token from local storage in logout
    private clearAuthData() {
        localStorage.removeItem('token')
        localStorage.removeItem('expiration')
    }

    // Geting the login token if it exist in the user local storage
    private getAuthData() {

        const token = localStorage.getItem("token");
        const expirationDate = localStorage.getItem("expiration")
        if (!token || !expirationDate) {
            return
        }
        return {
            token: token,
            expirationDate: new Date(expirationDate)

        }
    }

    // ******* Loading the token from local storage in the app component
}

[edit]
Calling the the service functions in the component
App component:
import { Component, OnInit } from '@angular/core';
import { AuthService } from './services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

constructor(private authService: AuthService){}

  ngOnInit(){
    this.authService.autoAuthUser()
  }
}

Header component:
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { Movies } from '../models/movies.model';
import { MoviesService } from '../services/movies.service';
import { FilterPipe } from 'ngx-filter-pipe';
import { DomSanitizer } from '@angular/platform-browser';
import { AuthService } from '../services/auth.service';
import { FormControl, Validators, NgForm, FormGroup } from '@angular/forms';
import { Subscription } from 'rxjs';
import { ModalDirective } from "angular-bootstrap-md";
import { User } from '../models/user';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],

})
export class HeaderComponent implements OnInit, OnDestroy {
  @ViewChild('signUpModal') signUpModal: ModalDirective;
  @ViewChild('logInModal') logInModal: ModalDirective;

  //Admincheck
  isAdmin = false

  userData: any
  //Spinners
  loginSpinner = false
  signUpSpinner = false
  //Authintications cheack
  userIsAuthinticated = false

  //Movies array for the search
  movies: Movies[]

  //Login Form
  loginForm: FormGroup

  //SignUp form
  signUpForm: FormGroup

  private authListnerSubs: Subscription;

  constructor(private movieService: MoviesService,
    private filterPipe: FilterPipe,
    public sanitizer: DomSanitizer,
    private authService: AuthService) { }

    sanitize(url: string) {
    return this.sanitizer.bypassSecurityTrustUrl('http://localhost:3000/' + url);
  }

  ngOnInit() {

    this.isAdmin = this.authService.checkIfAdmin()
    this.movieService.getAllMovies()
      .subscribe(
        (movies: Movies[]) => (this.movies = movies)

      )
    this.userData = this.authService.getUserInfo()
    this.userIsAuthinticated = this.authService.getAuthStatus()
    this.authService.getUserInfo()

    this.authListnerSubs = this.authService.getAuthStatusListner()
      .subscribe(isAuthonticated => {
        this.userIsAuthinticated = isAuthonticated
        if(this.userIsAuthinticated){
         console.log(this.userData)
          this.loginSpinner = false
          this.logInModal.hide();
          this.loginForm.reset()

        }
          this.loginSpinner = false

      });

A: Suresh has correctly pointed out your issue in the comments, you send off an async call to autoAuthUser in your AppComponent and, before it has completed, you are sending off a call to getUserInfo in your HeaderComponent. You already have all the plumbing to make this work, you just need to rearrange your code.
Move this.authStatusListner.next(true) inside the callback from autoLogin:
autoAuthUser() {
    const AuthInformation = this.getAuthData()
    if (!AuthInformation) {
        return
    }
    const now = new Date();
    const expairesIn = AuthInformation.expirationDate.getTime() - now.getTime();
    if (expairesIn > 0) {
        this.token = AuthInformation.token
        this.setAuthTimer(expairesIn / 1000)
        this.autoLogin().subscribe(user => {
            this.userInfo = user
            console.log(this.userInfo)
            this.authStatusListner.next(true)
        })
        this.isAuthenticated = true
    }
}

Don't call getUserInfo until after getAuthStatusListener has returned:
this.authListnerSubs = this.authService.getAuthStatusListner()
  .subscribe(isAuthonticated => {
    this.authService.getUserInfo()
    this.userIsAuthinticated = isAuthonticated
    if(this.userIsAuthinticated){
     console.log(this.userData)
      this.loginSpinner = false
      this.logInModal.hide();
      this.loginForm.reset()

    }
      this.loginSpinner = false

  });


text:
Q: Hyper-V CentOS 6.2 errors after LIC 3.3 installation I have CentOS 6.2 with LIC 3.3 (Hyper-V), everything is working fine but I have some errors in my /var/log/messages

*

*"eth0: Dropping NETIF_F_SG since no checksum feature."

*"SRAT: Hotplug area too small" (only with more then 4Gb of RAM)

Are this issues critical? Can I somehow fix it?


text:
Q: Laravel Auth::check() returns false even after successful login attempt This is my AdminAuthenticate.php
if ($this->attemptLogin($request)) {
      dd(Auth::guard('admin')->check());
      return $this->sendLoginResponse($request);
}

protected function attemptLogin(Request $request)
{
    return $this->guard('admin')->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}

I'm trying to implement customer for Admin. How com attemptLogin() return true, but Auth check return false?

A: When using the default login system, you are implicitely using the default guard to login. But afterwards, you are checking for successful login on the admin guard. So what you want to do is to add a function guard() in your LoginController that returns the proper guard:
protected function guard()
{
    return Auth::guard('admin');
}

Do not forget to import the Auth facade with use Illuminate\Support\Facades\Auth.

A: I failed to implement 'extends Authenticable' in Admin model.Issue resolved.


text:
Q: Rewriting of Formulas In this paper (Section 3.2), it says that z3 applies rewriting/simplification of formulas before it does any other steps.
Suppose I have a formula in QF_UF, that consists of multiple assert statements. Is there any rewriting rule that would somehow "break the barrier" between different assert statements? Or, asking the other way round: Can I be sure that rewrite rules are only applied locally, "within" one assert statement?
For example, consider the following formula:
(set-logic QF_UF)
(set-option :auto-config false)
(set-option :PROOF_MODE  2)

(declare-fun a () Bool)
(assert a)
(assert (not a))

(check-sat)
(get-proof)

Can I be sure that the proof will contain a resolution step to prove False, or is it possible that False will be concluded by a rewrite/simplification step?
The reason I am asking is that for my application, every assert statement has a special semantics. Rewriting/Simplification across several assert statements would render the resulting proof of unsatisfiability unusable (or at least: very hard to use) for me.

A: Z3 3.2 applies several preprocessing steps. Using (set-option :auto-config false) will disable most of them. You should also include the following two options:

(set-option :propagate-booleans false)
(set-option :propagate-values false)