text:
Q: Curl command line works, C++ curl library does not I'm trying to do some request via curl library of C++. I can successfully do my request and get the correct response via command line, but I cannot get the correct response via C++ code. My command line command looks like this
curl -X POST -H 'Accept: application/json' -H 'Content-Type: application/json' -H 'Authorization: <some_hash_value>' -k <my_full_url> -data '<my_json_string>'

That works fine. Now I try to do the same request in C++ code. My code looks like this
void performRequest(const std::string& json, const void* userData, CallbackFunction callback)
{
    struct curl_slist* headers = NULL;

    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, (std::string("Authorization: ") + m_authorization).c_str());

    CURL* curlHandle = curl_easy_init();
    if (!curlHandle)
    {
        std::cerr << "Curl handler initialization failed";
    }

    curl_easy_setopt(curlHandle, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(curlHandle, CURLOPT_HTTPHEADER, headers);

    // specify target URL, and note that this URL should include a file name, not only a directory
     curl_easy_setopt(curlHandle, CURLOPT_URL, m_url.c_str());

    // enable uploading
    curl_easy_setopt(curlHandle, CURLOPT_UPLOAD, 1L);

    // set HTTP method to POST
    curl_easy_setopt(curlHandle, CURLOPT_CUSTOMREQUEST, "POST");

    // set json data; I use EXACTLY the same string as in command line
    curl_easy_setopt(curlHandle, CURLOPT_COPYPOSTFIELDS, json.c_str());

    // set data size
    curl_easy_setopt(curlHandle, CURLOPT_POSTFIELDSIZE_LARGE, json.size());

    // set user data for getting it in response
    curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, userData);    // pointer to a custom struct

    // set callback function for getting response
    curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, callback);    // some callback

    // send request
    curl_easy_perform(curlHandle);

    curl_easy_cleanup(curlHandle);
    curl_slist_free_all(headers);
}

However, for some reason I get an error in the response from the server, from which I can assume that my code's request is not equivalent to command line's command. It seems that body is not sent. I cannot see my request Json body when I use CURLOPT_DEBUGFUNCTION for dumping debug info.
What is the problem here? What am I doing wrong? Any ideas?

A: Here is sample code that should work for you.
Notice that I:

*

*Removed CURLOPT_UPLOAD as it does not seem as you are actually uploading something but rather just doing a simple POST.

*Changed CURLOPT_CUSTOMREQUEST to CURLOPT_POST (not that it should matter), but I find it cleaner.

*Reordered CURLOPT_POSTFIELDSIZE_LARGE and CURLOPT_COPYPOSTFIELDS

*Removed the CURLOPT_WRITEDATA line for the sake of this sample code.
I have tested the following only by connecting to an instance of nc -l localhost 80

 static size_t callback(char *ptr, size_t size, size_t nmemb, void *userdata)
 {
   string s(ptr);
   cout << s << endl;
   return size * nmemb;
 }

 int main(int argc, char** argv)
 {
   string m_authorization("PWNED");
   string m_url("http://localhost");
   string m_json("{}");

   curl_global_init(CURL_GLOBAL_ALL);

   CURL* curlHandle = curl_easy_init();

   struct curl_slist* headers = nullptr;
   headers = curl_slist_append(headers, "Accept: application/json");
   headers = curl_slist_append(headers, "Content-Type: application/json");
   headers = curl_slist_append(headers, (std::string("Authorization: ") + m_authorization).c_str());

   curl_easy_setopt(curlHandle, CURLOPT_NOSIGNAL, 1);
   curl_easy_setopt(curlHandle, CURLOPT_HTTPHEADER, headers);

   // specify target URL, and note that this URL should include a file name, not only a directory
   curl_easy_setopt(curlHandle, CURLOPT_URL, m_url.c_str());

   // <= You are not uploading anything actually, this is a simple POST with payload
   // enable uploading
   // curl_easy_setopt(curlHandle, CURLOPT_UPLOAD, 1L);

   // set HTTP method to POST
   curl_easy_setopt(curlHandle, CURLOPT_POST, 1L);

   // set data size before copy
   curl_easy_setopt(curlHandle, CURLOPT_POSTFIELDSIZE_LARGE, m_json.size());

   // set json data; I use EXACTLY the same string as in command line
   curl_easy_setopt(curlHandle, CURLOPT_COPYPOSTFIELDS, m_json.c_str());

   // set user data for getting it in response
   // curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, userData);    // pointer to a custom struct

   // set callback function for getting response
   curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, callback);    // some callback

   // send request
   curl_easy_perform(curlHandle);

   curl_slist_free_all(headers);

   curl_easy_cleanup(curlHandle);
   curl_global_cleanup();
   return 0;
 }

A: The problem was solved tanks to Rocki's and drew010's comments.

*

*I have removed CURLOPT_CUSTOMREQUEST, CURLOPT_UPLOAD and CURLOPT_NOSIGNAL setting statements as there is no need of them.

*I have also removed the line for setting CURLOPT_POSTFIELDSIZE_LARGE, although it works fine if it is set before setting CURLOPT_COPYPOSTFIELDS.
If the size has not been set prior to CURLOPT_COPYPOSTFIELDS, the data is assumed to be a zero terminated string; else the stored size informs the library about the byte count to copy. In any case, the size must not be changed after CURLOPT_COPYPOSTFIELDS, unless another CURLOPT_POSTFIELDS or CURLOPT_COPYPOSTFIELDS option is issued. (See: curl.haxx.se/libcurl/c/CURLOPT_COPYPOSTFIELDS.html)

A: In windows, you must init the winsock stuff with below function
curl_global_init(CURL_GLOBAL_ALL);


text:
Q: Advice for researchers outside academia Perhaps some personal background is relevant to this question. A couple of years ago, I graduated with a master's degree in Applied Mathematics from a good Dutch university. Even though I obtained somewhat decent grades for the courses and the thesis (a 7/10 on average, maybe a B in the American system), I sensed that I probably wasn't good enough to pursue a PhD in a relevant mathematical research direction.
Therefore, I opted for a career in a different area. However, I keep coming back to mathematics over and over again. I am still drawn to some mathematical problems, and I work on them in my spare time. One day, I'd like to be a (co)author of (at least) one publication.
I've now come at a point that I think I have some interesting ideas for a certain problem. In order to flesh them out, I think it would be a good idea to collaborate with someone who has more expertise than me in the relevant domain. I've found a postdoc at my former institution, whom I suspect has the appropriate background to work on this problem with me.
I'm not quite sure, though, how to approach this person. I've never met him/her, and it seems somewhat odd or inappropriate to send him/her an e-mail out of the blue. I've thought of proposing to give a short presentation of my ideas to this person, after which s/he can decide whether the approach seems worthwhile enough to delve into more deeply.
This -- finding and approaching trustworthy fellow mathematicians who have the time and willingness to collaborate -- is one particular problem I've encountered while working as a researcher outside academia. As an "independent researcher", if you will, I encounter all sorts of other problems, including:

*

*Getting access to some journals, books and research papers;

*Obtaining licenses for expensive proprietary software;

I wonder whether you have any advice to independent researchers on these matters, and whether you can perhaps give some general guidelines or nuggets of wisdom to those working outside academia.

A: One point (mentioned in parenthesis by Alexandre Eremenko, but worth highlighting) is that since this postdoc is at your former institution, there's a chance there are professors there who remember you. (I myself is a professor who is terrible with names of people I meet in real life, but there are those who seem to remember everyone.) If so, that could be another way "in".
One way to play it could simply be to add a professor as a Cc: in your email to the postdoc, as a way of saying "BTW Prof, this is what I'm up to these days" without requesting a response on that part. Furthermore that does give the postdoc a chance to ask the professor about you before responding, should (s)he feel that advisable.
Another way to go ahead, especially if the postdoc you found ends up not being interested in your ideas (this happens; what research one wants to engage in is as much a matter of personal taste as one's choice of music), is to explore the possibility of you giving a talk at your old institution; maybe there is someone else there who would be interested. How feasible this is depends on the character of the institution; in a large department with research seminars every day it might be hard for a hobbyist to squeeze in, but in a smaller department (or one which for some reason doesn't have that many seminars going on) it can be easier to find an opening. Being an alumnus (even if at a low level) is a plus for you — many professors find it somewhat novel to hear of a former student who isn't himself a math professor doing math anyway. Talks by alumni addressing current students is also its own genre in academia, which can be given better resources than research activities.
One matter that can be tricky is knowing where to put the emphasis in your talk, when you do not know your audience. (Some things they all know and do not need to be reminded of, other things could be elementary to you but novelties to them.) If you get as far as being invited to give a talk then you may however be able to get the host to comment on an outline for your planned talk, if you ask nicely. They usually want the talk to be interesting as well.

A: Contact out of the blue; the postdoc will be proud to have been noticed. But remember that postdocs are in the tightest bottleneck of their lives, having to produce research of high quality quickly in order to get the next job right now. If the postdoc does not see how to get a paper out of your idea immediately, the postdoc should reject the opportunity for collaboration without wasting your time or hers. Do not be offended; starting a research collaboration with a new collaborator can take a lot of time, just to learn how to work together, even if both are very experienced in their fields. Many very top notch researchers have been rejected when they have asked to collaborate with even far less reknowned researchers who were too busy.
You will need to have a collaborator within the academic world, to make certain that your results are not already known, and to get access to academic journals. Obtaining that collaborator is the only problem you have to face before you can really join the international mathematical conversation.

A: I think it's a reasonable question. The quick answer is that there's nothing wrong with emailing someone you think might want to work with you.  The first email should be brief, polite, and give a very short explanation of who you are.  ("I graduated with a master's from X university in 201X and continue to have an interest in subject X.") Then it should give an again, very brief description of the problem and what you hope to achieve.
To your other question, I myself left academia eight years ago because of a two-body problem, and the biggest surprise for me was that MathSciNet was no longer available to me.  Not that an individual subscription would cost an exorbitant amount --- I was directly told by the AMS that if I am not affiliated to an institution, there is no way to subscribe, period. The best recommendation I can give you here is to look for SciHub, if I am allowed to say the name directly.

A: I agree with the other two answers.  I'm an independent researcher myself.  Like you I only have a Master's degree.  I've been lucky to coordinate with another coauthor in academia.  I might not have been able to continue publishing if it weren't for that connection.
So, yes, contact this person out of the blue.  The worst thing that can happen is that they'll tell you no.

A: The question of how to contact a person you were never introduced to, is not a question about mathematical research, so it is out of place here. (Perhaps you may contact some of your professors of fellow students with whom you studied, and who do research in mathematics, all depends on individual circumstances).
I will address the second part: how to get access to books and journals. Of course, this is absolutely necessary for study and research.

*

*There is arXiv. www.arxiv.org. It is a free resource, and more and more people
upload their results to this place. I believe that a majority of mathematicians already do this, and want to use this opportunity to call all the rest to join this majority. This is the only remedy against ongoing "privatization of mathematical knowledge" by big corporations.

*You should try to get access to some good university library. This depends on a country of course. In principle, university libraries are supposed to be accessible to the public. You enter, you browse, and you can copy whatever you want, perhaps paying some charge for copying.
Unfortunately this free access is curtailed more and more with years, and especially
bad situation is now, because of the epidemic. Paper subscriptions are eliminated,
and for electronic access you need a university ID. Unfortunately, this is a worldwide trend now. The only thing I can advise in this connection: contact someone in your university (where you studied, or some other university) and ask whether you, as a former student, or as an independent researcher, can have
an access to their electronic library resources. Some libraries may have
computers on their premises which allow you access to their resources without an ID.

*There are many books and journals on Internet with free access. And finally there are "pirate sites". I do not recommend any particular one, because some of them may be illegal, in some countries. But finding them is not a big problem.
They have very many books and journals for download.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Impossible to display a TopoJson map with Svelte I'm trying to view a TopoJson map with Svelte (and D3), but I can't figure out what's wrong because there is absolutely nothing displayed and yet the console output does not return any errors.
Does anyone have a clue?
I put below the link of a Svelte repl and the code used :
https://svelte.dev/repl/1cadb042523d40a5803171b9d29367af?version=3.48.0
<script>
  import { geoAlbers, geoPath, geoAlbersUsa, } from "d3-geo";
  import { onMount } from "svelte";
  import * as topojson from 'topojson-client';
    import { draw } from 'svelte/transition';

  const path = geoPath().projection(null);
    let deps = [];
    let mesh;

onMount(async () => {
    const france = await fetch('https://gist.githubusercontent.com/Fralacticus/b6584c5865607300b2b5a0559ae47cbb/raw/8287c28f9a3eab4e3d1aa5f7e6181f064957c9de/deptopo.json'
    ).then(d => d.json());
    console.log({ france });

    deps = topojson.feature(france, france.objects.dep).features;
    console.log({ deps });

    mesh = topojson.mesh(france, france.objects.dep, (a, b) => a !== b);
});
</script>

<svg viewBox="0 0 910 610">
  <g fill="white" stroke="black">
        {#each deps as feature, i}
            <path d={path(feature)} />
        {/each}
    </g>
</svg>

The map viewer and what it displays (this is the expected result):
https://mapshaper.org/?files=https://gist.githubusercontent.com/Fralacticus/b6584c5865607300b2b5a0559ae47cbb/raw/8287c28f9a3eab4e3d1aa5f7e6181f064957c9de/deptopo.json

A: If you look at the data, you will see that the values are huge and just do not fit the current dimensions of the SVG. You can e.g. increase the viewBox to make the map show up:
<svg viewBox="0 0 10000000 10000000">
  <!-- stroke-width adjusted for large viewBox -->
  <g stroke="black" stroke-width="1000px" fill="none">

REPL
france.transform appears to contain some additional information, but I do not know how that is supposed to be used. You can always calculate the bounding box yourself from the data and there appears to be function for this: bbox.
If the large scale of the data points is maintained, the stroke-width needs to be very high (e.g. 1000px), because it gets scaled down by the viewBox.


text:
Q: What is the difference between stdin with fscanf and scanf I want to get a integer from to user. But I wonder what is the difference between fscanf(stdin, "%d", &x); and  scanf("%d", &x);?

A:
What is the difference between stdin with fscanf and scanf?

The scanf function is equivalent to fscanf with the argument stdin interposed before the arguments to scanf.  C11 §7.21.6.4 2
So aside from a different amount of typing the code, they are the same.

A: Unless you #defined fscanf, scanf or stdin, both calls will do the same thing.  Note that such redefinitions would invoke undefined behavior.
Some standard input output functions have shorter versions for dealing with stdin or stdout:

*

*fscanf(stdin, ...) is equivalent to scanf(...

*getc(stdin) is the same as getchar()

*putc(c, stdout) can be written putchar(c)

*fprintf(stdout, "Hello world\n"); is usually shortened to printf("Hello world\n");


text:
Q: AttributeError: 'int' object has no attribute 'directions' I've updated the code so that it appears exactly as it does on my machine.
I've been developing a simple Python text adventure engine, and I've run into a problem. If you can solve my problem or have a more efficient way to code/structure a method or class, please tell me! I'm new to this sort of thing, and any advice would be great! Also, formatting might not be up to par, but hey, I tried!
Okay, so my project has two modules, titled Game and Map. The first module, Game, "parses" user input and change the room the player is standing in. The second module, Map, outlines a Room class that contains a constructor and some functions relating to directions, exits, etc. I hadn't yet solved moving into a non-existing room, and I'm sure that my code is fairly terrible, but here it is:

Error message
>>> ================================ RESTART ================================
>>>
You are in a small, cramped space.
It is cold and dark. There is a door to your North.

 > Go North

Traceback (most recent call last):
  File "C:\Users\Spencer\Documents\Python\Game.py", line 25, in <module>
    currentRoom = currentRoom.directions[0]
AttributeError: 'int' object has no attribute 'directions'
>>>

Game module
# It is the main engine for PyrPG
import Map

currentRoom = Map.currentRoom

def updateGame():
    currentRoom.displayName()
def invalidCommand():
    print("Invalid command. Try again.")
while(True):
    updateGame()
    command = input(" > ")
    print()

    partition = command.partition("Go" or "go" or "Take" or "take")
    action = partition[1]
    item = partition[2]
    if(action == "Go" or "go"):
        if(item == " North" or " north"):
            currentRoom = currentRoom.directions[0]
        if(item == " East" or " east"):
            currentRoom = currentRoom.directions[0]
        if(item == " South" or " south"):
            currentRoom = currentRoom.directions[0]
        if(item == " West" or " west"):
            currentRoom = currentRoom.directions[0]
    else:
        print("Invalid command.")

Map module
# It handles rooms.
class Room:
    rmCount = 0
    directions = [0, 0, 0, 0]

    def __init__(self, name, description):
        # Name and description
        self.name = name
        self.description = description

        # Directions
        self.directions = None
        self.canNorth = False
        self.canWest = False
        self.canSouth = False
        self.canEast = False

        # Increase room count
        Room.rmCount += 1

    def displayName(self):
        print(self.name)
        print(self.description)
        print()

    def displayDirections(self, directions):
        # Check directions, modify booleans
        if(self.directions[0] != 0):
            self.canNorth = True
            gNorth = "North"
        else:
            gNorth = ""
        if(self.directions[1] != 0):
            self.canEast = True
            gEast = "East"
        else:
            gEast = ""
        if(self.directions[2] != 0):
            self.canSouth = True
            gSouth = "South"
        else:
            gSouth = ""
        if(self.directions[3] != 0):
            self.canWest = True
            gWest = "West"
        else:
            gWest = ""

        print("Directions:", gNorth, gEast, gSouth, gWest)

    def setDirections(self, directions):
        self.directions = directions

    def displayInfo():
        displayName()
        displayDirections()

introRoom = Room("Welcome to the Cave.", "To start the game, type \"Go North\"")
storageCloset = Room("You are in a small, cramped space.", "It is cold and dark. There is a door to your North.")
mainOffice = Room("the main office.", "It is cold and empty.")
currentRoom = storageCloset

introRoom.setDirections([storageCloset, 0, 0, 0])
storageCloset.setDirections([mainOffice, 0, 0, 0])
mainOffice.setDirections([0, 0, storageCloset, 0])

Again, if you see something hideous, please tell me! This is the first project I have written on my own without any instruction. Thanks!

A: The problem is here...
if(item == " North" or " north"):

This is an incorrect way to test the condition.
What you need to do is
if (item == " North") or (item == " north"):

Look at other places too where you are checking a condition using "or".

A: You have two major bugs I can see, a bunch of not-bug-but-still-bad bits, and probably more problems I haven't noticed. Here are the major bugs.
Problem 1:
partition = command.partition("Go" or "go" or "Take" or "take")

or doesn't work like that. This won't try command.partition with four possible arguments. Instead,
"Go" or "go" or "Take" or "take"

evaluates to "Go", and the call becomes
partition = command.partition("Go")

This problem occurs every single place you use or. The biggest impact is when it occurs in an if condition, where it causes the if to always be taken.
Problem 2:
currentRoom = currentRoom.directions[0]

There are 4 lines that all say this. Each one picks the same directions element. They shouldn't be doing that; they should all go in a different direction.

A: I've modified Map.py to be a bit more flexible:
class CaseInsensitiveDict(dict):
    def __getitem__(self, key):
        return dict.__getitem__(self, key.lower())
    def __setitem__(self, key, value):
        return dict.__setitem__(self, key.lower(), value)

# room index
all_rooms = CaseInsensitiveDict()

class Room:
    def __init__(self, name, description):
        all_rooms[name] = self   # add to index
        self.name = name
        self.description = description
        self.dirs = CaseInsensitiveDict()

    def add_dir(self, dir, room_name):
        self.dirs[dir] = all_rooms[room_name]

    @property
    def directions(self):
        return "From here you can go: " + ", ".join(sorted(self.dirs.keys())) + "\n"

    def go(self, dir):
        try:
            next_room = self.dirs[dir]
            print(next_room)
            return next_room
        except KeyError:
            print("You can't go {} from here.\n".format(dir))
            return self

    def __str__(self):
        return (
            self.name + "\n" +
            self.description + "\n"
        )

def make_link(dir_a, room_a, dir_b, room_b):
    if dir_b:
        all_rooms[room_a].add_dir(dir_b, room_b)
    if dir_a:
        all_rooms[room_b].add_dir(dir_a, room_a)

which you can then use like
Room("Small closet", "You are in a small, cramped space. It is cold and dark. There is a door to your North.")
Room("Dusty office", "This must be the main office. It is still cold and dark. There is a door marked 'Supplies' to the South, and a set of double doors to the East.")
Room("Foyer", "Blah blah")

make_link("North", "Dusty office", "South", "Small closet")
make_link("East", "Foyer", "West", "Dusty office")

here = all_rooms["small closet"]

then
>>> print(here)
Small closet
You are in a small, cramped space. It is cold and dark. There is a door to your North.

>>> here = here.go("north")
Dusty office
This must be the main office. It is still cold and dark. There is a door marked 'Supplies' to the South, and a set of double doors to the East.

>>> here = here.go("north")
You can't go north from here.

>>> print(here.directions)
From here you can go: east, south

>>> here = here.go("east")
Foyer
Blah blah


text:
Q: What functionality does Dropbox provide that Evernote does not? I currently use Evernote as a catch-all storage system, note-taking app, and file transfer system.
What, if anything, would Dropbox add to my capabilities?
(If it matters, I'm an OSX/iphone/ipad user.)

A: Evernote's strong suit is capturing notes, ideas, web snippets and such and then making it easy to synchronize and search that stuff.
Dropbox is all about automatically synchronizing one directory/folder. You save stuff to the Dropbox folder under your home directory -- any files. The Dropbox app synchronizes the files with its server and then with any other devices running Dropbox with your account.
Dropbox cannot grab arbitrary snippets or notes. Evernote does not interact directly with a folder on your disk.
They're complementary applications.

A: I've never used Evernote so I don't know if it can do this, but an important feature of DropBox is sharing.  You can selectivly share files and folders with other DropBox users.  This is useful for collaborating on documents with other people, especially on an ad-hoc basis for just a single project.
DropBox also keeps a history of your files, so you can revert to older versions or get back deleted files.

A: I use Dropbox to sync profiles for programs accross Macs. TextExpander, Google Chrome, and a lot of other apps act the same thanks to Dropbox.

A: Sharing files both privately and publicly.  Version backup.  Ample storage for free.  The agent doesn't bog down the system.


text:
Q: How to fetch only updated object from Relatime Firebase Database? I am new to Firebase Real-time Database and don't have an idea that how to fetch only the recent updated object from the table.
I have tried using "ChildEventListener" but when I initialize the Listener for the first time it fetches the last row from the database.
It should not be fetched if it was not updated.
I want object only when it is updated or newly added.
I have done this,
databaseReference.child("last_chat").orderByChild("s_id").equalTo(preference.getUserData().getId()).limitToLast(1).addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Log.e("dataSnapShot", dataSnapshot.toString() + "      " + s);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            Log.e("dataSnapShotChagned", dataSnapshot.toString() + "      " + s);

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            Log.e("dataSnapShotRemoved", dataSnapshot.toString());

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("onCalcnelle", databaseError.toString());
        }
    });

Thank you in advance.

A: I have solved the issue.
I just need to put my code inside the OnChildChanged instead of putting my code in OnChildAdded.
Log dataSnapShot shown when first running the application, whereas as soon as I change or update object dataSnapShotChagned is shown.
Thus it worked for me, OnChildAdded method is called every time while initializing the listener where OnChildChanged method is called only when there is a change in a particular object.
Thanks a lot all for the help.

A: public ValueEventListener addValueEventListener (ValueEventListener listener)

Also: Google Play services
Add a listener for changes in the data at this location. Each time time the data changes, your listener will be called with an immutable snapshot of the data.
Firebase Doc
Hope this helps.


text:
Q: Group heading is not displayed after grouping in ItemsControl I'm trying to group my ObservableCollection using CollectionViewSource, it seems to work for items but it's not showing the bind property value for GroupBox.
Here is what I'm trying:
I've List<Object> containing properties Description, Season. I want to group by Season. Here is my xml:
<mah:MetroWindow x:Class="eCatalog_Launcher.MainWindow"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:eCatalog_Launcher"
             xmlns:mah="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
             xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks"
             mc:Ignorable="d"
             Title="eCatalog Launcher"
             WindowState="Maximized"
             Loaded="MetroWindow_Loaded"
             Closing="MetroWindow_Closing">

<Window.Resources>
    <CollectionViewSource x:Key="catalogsBySeasons"
                          Source="{Binding Path=Catalogs, Mode=TwoWay}">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="Season" />
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>

</Window.Resources>

<ScrollViewer>
    <ItemsControl ItemsSource="{Binding Source={StaticResource catalogsBySeasons}}">
        <ItemsControl.GroupStyle>
            <GroupStyle>
                <GroupStyle.ContainerStyle>
                    <Style TargetType="{x:Type GroupItem}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type GroupItem}">
                                    <GroupBox Header="{Binding Season}">
                                        <ItemsPresenter />
                                    </GroupBox>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </GroupStyle.ContainerStyle>
            </GroupStyle>
        </ItemsControl.GroupStyle>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <mah:Tile Title="{Binding Description}"
                          Tag="{Binding}"
                          Style="{StaticResource SmallTileStyle}"
                          Click="Tile_Click">
                    <iconPacks:PackIconMaterial Width="32"
                                                Height="32"
                                                Margin="0, -30, 0, 0"
                                                Kind="{Binding Kind}">
                    </iconPacks:PackIconMaterial>
                </mah:Tile>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</StackPanel>

It's showing the Season value as GroupBox Heading.
Is there anything wrong?

A: You should bind to the Name property of the group:
<ControlTemplate TargetType="{x:Type GroupItem}">
    <GroupBox Header="{Binding Name}">
        <ItemsPresenter />
    </GroupBox>
</ControlTemplate>

This should display the actual value of the Season property that you group by.


text:
Q: jquery datatables and bootstrap issue I am using bootstrap and jquery datatables together.
When the datatables are rendered they leave spaces above and below.
Initally in those spaces there was search bar feature (above) and pagination feature (below). Later I disabled these options, now they dont appear any more but still I can see occupied space for them`

Over All Summary

                                Customer Group
                                # of Customer Contacted
                                # of Customer Responded
                                Response Rate
                                Revenue (AED)
                                AMS
                                %Customer
                                %Revenue
                                Shopping Frequency
                                ATV
                                UPT
                                PPI

                                    + Tiger Nixon

                                System Architect
                                Edinburgh
                                61
                                2011/04/25
                                $320,800
                                18thFEb,1990
                                No
                                2011/04/25
                                $320,800
                                18thFEb,1990
                                No

                                     Tiger Nixon
                                    Hidden1
                                    Edinburgh
                                    61
                                    2011/04/25
                                    $320,800
                                    18thFEb,1990
                                    No
                                    2011/04/25
                                    $320,800
                                    18thFEb,1990
                                    No

                                     Tiger Nixon
                                    Hidden1
                                    Edinburgh
                                    61
                                    2011/04/25
                                    $320,800
                                    18thFEb,1990
                                    No
                                    2011/04/25
                                    $320,800
                                    18thFEb,1990
                                    No

                                     Tiger Nixon
                                    Hidden1
                                    Edinburgh
                                    61
                                    2011/04/25
                                    $320,800
                                    18thFEb,1990
                                    No
                                     2011/04/25
                                    $320,800
                                    18thFEb,1990
                                    No

                                    + Tiger Nixon

                                System Architect2
                                Edinburgh
                                61
                                2011/04/25
                                $320,800
                                18thFEb,1990
                                No
                                2011/04/25
                                $320,800
                                18thFEb,1990
                                No

                                     Tiger Nixon
                                    Hidden2
                                    Edinburgh
                                    61
                                    2011/04/25
                                    $320,800
                                    18thFEb,1990
                                     2011/04/25
                                    $320,800
                                    18thFEb,1990
                                    No
                                    No

                                    + Tiger Nixon

                                System Architect2
                                Edinburgh
                                61
                                2011/04/25
                                $320,800
                                18thFEb,1990
                                No
                                2011/04/25
                                $320,800
                                18thFEb,1990
                                No

                                     Tiger Nixon
                                    Hidden2
                                    Edinburgh
                                    61
                                    2011/04/25
                                    $320,800
                                    18thFEb,1990
                                    No
                                    2011/04/25
                                    $320,800
                                    18thFEb,1990
                                    No

`
Blue spaces on the top and bottom and when I inspect element I can see   added where as its not in my code

A: .dataTables_wrapper .row-fluid:first-child {paddding:0px}


text:
Q: What does the domain in vm host TCP/IP stack DNS config do? We are pulling an Active Directory server out and modifying DNS settings on all systems. Attempting to update DNS list on a vm host results in a validation error that the domain value is not filled. How could this have been setup originally without, what does it do and is there any harm in adding our domain?

A: It's for your Fully-Qualified Domain Name (FQDN) for the host.
Ideally, the domain name of the ESXi host is defined. You don't have to, but it's generally helpful if the rest of your network has internal DNS.


text:
Q: iframe breaks div sequence I have a site (http://maladrerie.heliohost.org/mkh/index.html) using CSS to keep header, menu and footer fixed while the content scrolls. I am trying to add a photo page using an iframe and it works pretty well (I still need to tune it for different browsers).
But after the iframe the page stops displaying, which means that I lose my footer. The relevant code is (I think) in fotopag.php:

   ... (header and menu)

  <iframe class="fotoframe" src="<?php print($foto) ; ?>"

  ...

The site is in Dutch but you can see that all pages have a footer except the page "Foto's". I have googled and tried everything I can think of, but am making no progress.
One odd thing is that if I replace the php code with a fixed reference and save the page as HTML I still get no footer, but KompoZer (my HTML editor) does show the footer.
I'm probably missing something simple but pretty-please tell me what it is!
--- Derek

A: The browser doesn't run PHP. It runs the HTML code generated by PHP. When you look at the PHP code, you're making it hard to debug what's wrong in the browser, because you're not seeing what the browser sees.
Instead, you should do a View Source in the browser so you can see what is actually happening. Your code should look something like this:

    ... (header and menu)

        <iframe class="fotoframe" src="someurl"

        ...

Does the problem jump out at you now?
If it doesn't, take a close look at the  on the <iframe line?)


text:
Q: Ajax Call using Jquery in HTML and take a response to other Html Page I am doing this for the first time. i want a data of another HTML page using AJAX call and jQuery in HTML page.
Below is mycode
this is my .js code


text:
Q: Why is there no warning for unnecessary "ref" in method? If you have code like this:
    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            test.PropOne = 123;
            test.PropTwo = "testing";

            ModifyTestClassWithRef(ref test);
        }

        public static void ModifyTestClassWithRef(ref Test test)
        {
            test.PropOne++;
            test.PropTwo += "_abc";
        }
    }

    public class Test
    {
        public int PropOne { get; set; }
        public string PropTwo { get; set; }
    }

Why does the compiler not provide a warning about "ref" not being necessary since it is unnecessary in this particular situation?

A: There shouldn't be a warning for the issue you raise. A lot of developers go to the trouble to understand and clear all their warnings. Some teams even elevate their warnings to errors. If an interface or abstract base class "demand" that a method have a ref parameter, and the implementation didn't need to set the ref, then the implementer would get the warning and would have to explicitly decorate the method with a exclusion. I'm certain that would be unsatisfactory in a lot of shops.
An out parameter, on the other hand, has the explicit guarantee that the implementor set the parameter - you can't even compile without setting it. If that's the behavior you want, then out parameter is your friend.


text:
Q: How my Web server can send Web requests to my IoT thing? CAUTION: A newbie about IoT concepts here!
I'll try to be short and explain what I want to do:

*

*Suppose that I already have connected my development board (be whatever you want; arduino, rpi, esp8266. The only requirement is to have a WiFi module on it) to my electric water heater.

*I return from my work and I want the water to be ready for my bath.

*The only thing I do is to visit (via my amazing smartphone) mywaterheater.herokuapp.com/manage/ and just press the button named activate!

*Bang! The development board has received a Web request from a User-agent, it activates the relay and my water heater is now turned on.

Can this be accomplished?
I suspect that I have to turn my dev board to a router in order to listen for Web requests (GET, POST, PUT). Is the WoT trying to solve this kind of things?
It is assumed that any authentication/authorization and security issues have been taken care of.

A: In order to listen for HTTP requests, an HTTP server should be started on the board. Depending on the board type there could be different options, for example:

*

*NodeMcu firmware for ESP8266 has built-in HTTP server;

*Web Server with Arduino and Ethernet
Shield;

*Multiple choices for Raspberry Pi.

After you enable a server on the board, it will listen for incoming requets on the specified IP and port. Assuming that your board will be placed in your local network, you will have to setup port forwarding to that IP:port on your router. You will also need external IP from your service provider to be able to access your board from the Heroku application.
Next step is to add HTTP client to your Heroku application that will send requests to the board. Again there are a lot of different options. As an example, if your app is written in Python, than you can use Requests library for this.
So when you will press a button on a web page served by Heroku, a HTTP client from your application will send a request to the IP address of your router. Then it should reach HTTP server on your board because of the port forwarding on the router.

A: Yes a lot of IoT device has web server framework. You can trigger IO from web request. But you need accsess the device from internet (port forwarding, static ip or dynds). Also there are generic smart phone app.


text:
Q: mercurial hg partial checkin It is a very simple and stupid question,
I am working on 2 tasks and modified 2 sets of files in the code.
Now when I type 'hg ci', it checks in all the files. Can I remove certain files from the checkin i.e. do checking for only one task?
If I remove the files in the 'check in message' will they be removed from the checkin
Thanks for all the answers
This seems like a big flaw, My use case is very simple and general. Most of the time dev are working on various tasks , some are ready , some are not, bug fixes etc.
Now the only simple solution seems to be multiple local repos or clones

A: Use hg ci <files>... to commit only certain files in your working directory.

A: If you want to pick file by file you can use the record command.  It ships with mercurial, but you have to turn it on if you want to use it by putting: record= in the [extensions] section of your ~/.hgrc.
It goes hunk by hunk, but you can answer for a whole file:
y - record this change
n - skip this change

s - skip remaining changes to this file
f - record remaining changes to this file

d - done, skip remaining changes and files
a - record all changes to all remaining files
q - quit, recording no changes

? - display help

I'll point out that if you're committing some files but not others it's certain that you've not run your test suite on the one change without the other, but maybe that doesn't apply in your case.

A: The real problem here is the fact that you're doing changes related to different tasks jumbled together. Mercurial has a few ways you can keep things separate.
Task Branches
Suppose you've been working on a task and you've checked in a few times since you last pulled, but things aren't ready to share yet.
o----o----B----o----o----o

Here, B is the revision where you started your changes. What we do is (after making sure our current changes are checked in):
> hg update -r B
<do our work on the other task>
> hg commit

We've now created a new branch with the changes for this task separated from the changes for our original task.
o----o----B----o----o----o
           \
            ----o

We can do this for as many different tasks as we want. The only problem is that sometimes remembering which branch is which can be awkward. This is where features like bookmarks come in useful. A bookmark is a tag which moves forward as commits are made so that it always points at the head of a branch.
Mercurial Queues
MQ adds the ability to work on changes incrementally and move between them by pushing and poping then off a stack (or "Queue" I guess). So if I had a set of uncommitted changes that I needed to split up I'd:
> hg qrecord taska
> hg qrecord taskb
> hg qrecord taskc

I'd use the record extension (or more likely the crecord extension) to select which parts of files I want to select.
If I needed to go back to taska and make some changes:
> hg qpop; hg qpop    # pop two off the queue to go back to task a
<Do changes>
> hg qrefresh         # update task a with the new changes

When I want to turn the queue into normal changesets:
> hg qpush or hg qpop # get the changes I want converted onto the queue
> hg qfinish -a       # converts mq changes to normal changesets

There's other methods too, but that will do for now.

A: This isn't possible with mercurial out of the box. As have been suggested there are several ways of selecting what files you want to commit. To get this function via the commit message template, you would need an extension or a shell script wrapping the commit command.  Here's one way to do that:
[alias]
ci = ! hg-partial-commit

hg-partial-commit:
#!/bin/sh
# partial commit

edit=$(mktemp ${TMPDIR:-/tmp}/$(basename $0).XXXXXXXXXXXX)
filelist=$(mktemp ${TMPDIR:-/tmp}/$(basename $0).XXXXXXXXXXXX)
logmessage=$(mktemp ${TMPDIR:-/tmp}/$(basename $0).XXXXXXXXXXXX)
cleanup="rm -f '$edit' '$filelist' '$logmessage'"
trap "$cleanup" 0 1 2 3 15

(
    echo user: $(hg debugconfig ui.username)
    echo branch: $(hg branch)
    hg parents --template 'parent: {rev}:{node|short}  {author}  {date|isodate}\n'
    echo
    echo 'Enter commit message.  Select files to commit by deleting lines:'
    hg status 'set:not unknown()' | sed -e 's/^/@/'
) | sed -e 's/^/HG: /' >"$edit"

${VISUAL:-${EDITOR:-vi}} "$edit"
egrep -v '^HG:' "$edit" >"$logmessage"
egrep '^HG: @' "$edit" | cut -c8- >"$filelist"

hg commit -l "$logmessage" "listfile:$filelist"
$cleanup

A: You will unavoidably have to either specify the files that you want to add or the files you want to leave out. If you have a lot of files, as you indicate above, the following steps will simplify the procedure (I'm assuming a UNIX-ish system here, Windows would be slightly different).
First, generate a list of changed files:
hg status -mard -n >/tmp/changedlist.txt

The -mard options will list all files that were modified, added, removed, or delated. The -n option will list them without the status prefix so that all you have is a raw list of files.
Second, edit /tmp/changedlist.txt with your favorite text editor so that it contains only the files you wish to commit.
Third, commit these files:
hg commit `cat /tmp/changedlist.txt`

You will be able to review the files to be committed before actually performing the commit.
Alternatively, you can add more files to a commit incrementally by using
`hg commit --amend file...`

Here, hg commit --amend will not create a new commit, but add the new files to the existing commit. So, you start out with committing just a couple of files, then incrementally adding more until you are done. This still requires you to type all of them in.
For yet another alternative, you can use Mercurial Queues to split a commit in more sophisticated ways, but that's a bit more of an advanced topic.


text:
Q: Host Private Pip Repository I am trying to host my private python package in aws ec2. I use flask app for this. I placed my package inside a folder in the root of the flask app. In the route function, after successful aunthentication, i am trying to send the file using send_file. when i try the url with my browser, the response is the attachment of my package. But when i try to install using pip
pip install mypackage --extra-index-url=https://myurl
I am getting the following error :
Could not find a version that satisfies the requirement packagename (from versions: none)
No matching distribution found
Pip expects the response from the url to be in 'text/html' format. Initially, i was getting an error that  the response is of type octset, but i changed the mimetype. eventhough somehow i am unable to get the package downloaded.
also, i tried with PEP503 directory structure,

*

*simple
-packagename

*

*index.html
-index.html

In this case, what should my url return?. render the index.html? or link to the file?
Directory structure in Ubuntu AMI:
directory1

*

*package-name

*

*package.name-0.0.0-py3-none-any.whl

*app.py

*templates

*static

A: If your packages are at /simple/ then you need to include this in your extra-index-url e.g. the command to install from piwheels (a third-party public repo) is:
pip install numpy --extra-index-url https://www.piwheels.org/simple

The / root of your website is not used by pip, only the simple index is. The / index (and anything other than /simple/) can simply be used to provide human-readable information for users, like a homepage and possibly even /project/<package>/ project pages (like https://www.piwheels.org/project/numpy/) but that's probably not necessary if it's a private index.
You can run an index without server-side code, simply generate /simple/index.html and /simple/<package>/index.html for each package, store your wheel files in /simple/<package>/<filename>.whl:
www
└── simple
    ├── index.html
    ├── numpy
    │   ├── index.html
    │   └── numpy-1.19.4-cp37-cp37m-linux_armv7l.whl
    └── scipy
        ├── index.html
        └── scipy-1.5.3-cp37-cp37m-linux_armv7l.whl

And (optionally) extra pages and project pages outside of /simple/:
www
├── about.html
├── index.html
├── project
│   ├── index.html
│   ├── numpy
│   │   └── index.html
│   └── scipy
│       └── index.html
└── simple
    ├── index.html
    ├── numpy
    │   ├── index.html
    │   └── numpy-1.19.4-cp37-cp37m-linux_armv7l.whl
    └── scipy
        ├── index.html
        └── scipy-1.5.3-cp37-cp37m-linux_armv7l.whl

But if you stick with Flask, that's fine (as long as Flask stays up), provided you route everything in the first example.
Refer to the HTML files in PyPI and piwheels for reference, e.g. view source of https://www.piwheels.org/simple/numpy/index.html and (DOWNLOAD FILE - DO NOT OPEN IN BROWSER - IT'S HUGE)... piwheels.org/simple/index.html


text:
Q: Ubuntu Freezes, REISUB won't save me I've recently come across a pretty distressing crash in my Ubuntu installation.

*

*The mouse and keyboard will suddenly become unresponsive.

*I thought the screen also froze, but it happened while I was typing in the
terminal and I comically saw it fill with hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh,meaning that the last
button pressed kept going

*I tried ALT + SYSREQ + F and REISUB, but
neither of them worked (perhaps because my keyboard doesn't even
work when this happens?).

*Pressing the shutdown button once will
still give me the shutdown screen, telling me that shutdown will
happen in 60 seconds, and the counter does decrement by 10 every 10
seconds.
Not sure what my exact problem is here. Most answers I found pertained to a simple restart, but I don't think this would work anyway, since this has happened to me at least four times in the last 15 minutes. Here's hoping it does nottttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt - just kidding. Please help. Thank you in advance.
PS: Some info, in case relevant.

*

*OS: Ubuntu 20.04.2 LTS x86_64

*Kernel: 5.8.0-50-generic

*CPU: Intel i5-1035G1 (8) @ 3.600GHz

*GPU: Intel Device 8a56

*(Also I use GNOME)


text: Q: Api response as a zip not as JSON I am building an Android app and with the help of a remote API I am getting responses to parse into my application. Some of the responses are returned into a zip file (not like the others as JSON) just because of the data are so big. Have you any idea how handle this problem? Should I download the zip file and parse it locally ? (even with my mac I am having trouble to open the file). Is there any special treat with this problem? Should I use other tools than retrofit ?


text:
Q: Problems with canvas buttons in unity So, i have buttons for my game that include : Main Menu button , Restart button and Play button. Everything works fine, but occasionally one of the button's text doesn't load , one of them doesn't work. I'm not sure how to fix this, because it happens randomly and not every time.
The code for the buttons :
GameObject[] pauseObjects;
void Start()
{
    Time.timeScale = 1;
    pauseObjects = GameObject.FindGameObjectsWithTag("ShowOnPause");
    hidePaused();
}

public void showPaused()
{
    foreach (GameObject g in pauseObjects)
    {
        g.SetActive(true);
    }
}

public void hidePaused()
{
    foreach (GameObject g in pauseObjects)
    {
        g.SetActive(false);
    }
}

public void LoadLevel(string level)
{
    Application.LoadLevel(level);
}

public void pauseControl()
{
    if (Time.timeScale == 1)
    {
        Time.timeScale = 0;
        showPaused();
    }
    else if (Time.timeScale == 0)
    {
        Time.timeScale = 1;
        hidePaused();
    }
}

A: The way your UI is setup is not right. If you have to loop through everything during pause, you are doing it wrong. I have answered a similar question before and will just copy and paste this here.
Use different Canvas to separate your UI and group them depending on when they are displayed. Then you can toggle the whole Canvas on/off. Your [post][1] before this post shows that you are using image as button and you have a different script attached to two images you are using as buttons. Use Buttons for buttons and image for non-clickable objects. Simple as that. So change those images to buttons.
You don't need the GameOver scene. A GameOverCanvas is fine.
The GameObjects in bold are the parent Objects(Canvas). The ones under that starts with '-' are the child GameObjects.
Step 1:
Create Canvas and name it MainMenuCanvas (First UI to display when game Loads).Create each child button and rename them as below(GameObject->UI->Button):
-playButton;
-settingsButton;
-exitGameButton;

Attach the MainMenuCanvas script to the MainMenuCanvas Object.
Step 2:
Create a Canvas and name it GameCanvas (Displayed during game).Create each child button and rename them as below(GameObject->UI->Button):
-pauseButton
-jumpButton

Attach the GameCanvas script to the GameCanvas Object.
Step 3:
Create a Canvas and name it PauseCanvas (Displayed when pause button is clicked).Create each child button and rename them as below(GameObject->UI->Button):
-resumeButton;
-backToMainMenuButton;
-settingsButton;
-exitGameButton;

Attach the PauseCanvas script to the PauseCanvas Object.
Step 4:
Create a Canvas and name it SettingsCanvas (Displayed when settings button is clicked).Create each child button and rename them as below(GameObject->UI->Button):
-backButton;

Attach the SettingsCanvas script to the SettingsCanvas Object.
Step 5:
Create a Canvas and name it GameOverCanvas (Displayed when Game is Over or player is killed).Create each child button and rename them as below(GameObject->UI->Button):
-playAgainButton;
-backToMainMenuButton;
-exitGameButton;

Attach the GameOverCanvas script to the GameOverCanvas Object.
Step 6:
In the Game scene, make sure that only GameCanvas is enabled. The rest of the canvas should be manually disabled.
Step 7:
In the Menu scene, make sure that only MainMenuCanvas is enabled. The rest of the canvas should be manually disabled.
Once you get this setup correctly, the UI code templates I provided should work. No more UI overlapping or text disappearing. You can easily add or remove features.
Your UI setup should look like the image below.


text:
Q: How to avoid using too much foreign key django I just want to store tags data inside entry model
Entry

*

*title

*content

*tags

Tags should be Array but ArrayField is not portable to other database. I want to use portable alternative.

A: The portable alternative is to use a proper relational schema - in this case a many to many relationship, which in django models is named models.ManyToManyField.
class Tag(models.Model):
    label = models.CharField(...)

class Entry(models.Model):
    # ...
    tags = models.ManyToManyField(Tag)

If you want to keep tags ordering per entry, you'll need an intermediate model to store it, cf https://docs.djangoproject.com/en/1.10/topics/db/models/#intermediary-manytomany


text:
Q: Redirect Loop after header location Good morning, I am dealing with an existing code and I need to solve a problem:
When you write a URL without logging into the Web, you can see the page in question (except the layout), what I need is to redirect to the login to avoid this.
So you can see the page without logging in
Checking the code I have seen that it is like this:
layout.php

<?php if(isset($_SESSION["user_id"])):?>
    HTML code (Logo, menu...)
<?php else:?>
  <?php
  View::load("login");
    ?>
<?php endif;?>

If I change "View::load("login");" to "header("Location: index.php"); exit();", it causes an Infinite loop and does not load anything.
I have investigated a lot in Stackoverflow and other websites but I do not find the solution. Any ideas?
UPDATE:
index-view.php

LegoBox

login-view.php
<?php
if(Session::getUID()!=""){
        print "";
}

?>

        <?php if(isset($_COOKIE['password_updated'])):?>

 Se ha cambiado la contraseña exitosamente.

Pruebe iniciar sesion con su nueva contraseña.

        <?php setcookie("password_updated","",time()-18600);
         endif; ?>

Acceder

                    <form accept-charset="UTF-8" role="form" method="post" action="index.php?view=processlogin">
                    <fieldset>

                            <input class="form-control" placeholder="Usuario" name="mail" type="text">

                            <input class="form-control" placeholder="Contraseña" name="password" type="password" value="">

                        <input class="btn btn-primary btn-block" type="submit" value="Iniciar Sesion" style="background-color:#339c24">
                    </fieldset>
                    </form>

processlogin-view.php
<?php
if(Session::getUID()=="") {
$user = $_POST['mail'];
$pass = sha1(md5($_POST['password']));

$base = new Database();
$con = $base->connect();
 $sql = "select * from user where (email= \"".$user."\" or username= \"".$user."\") and password= \"".$pass."\" and is_active=1";
//print $sql;
$query = $con->query($sql);
$found = false;
$userid = null;
while($r = $query->fetch_array()){
    $found = true ;
    $userid = $r['id'];
}

if($found==true) {
//  print $userid;
    ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);
    $_SESSION['user_id']=$userid;
//  setcookie('userid',$userid);
//  print $_SESSION['userid'];
    print "Cargando ... $user";
    print "";
}else {
    print "";
}

}else{
    print "";

}
?>


text:
Q: Strange tikz problem (memoir vs xcolor vs tikz) Consider the MWE below, on a fully updated TeX Live 2015, this gives me this error:
/opt/texlive/2015/texmf-dist/tex/generic/pgf/libraries/pgflibraryarrows.meta.co
de.tex:208: You can't use `\unskip' in vertical mode.
<recently read> \unskip

l.208 }

MWE:
\documentclass[a4paper]{memoir}
% if xcolor is removed, file compiles
\usepackage{xcolor}
% if \SingleSpacing is removed, file compiles
\SingleSpacing
\usepackage{tikz}
% arrows.meta removed, file compiles
\usetikzlibrary{arrows.meta}
\begin{document}

test

\end{document}

As listed remove one of the three, and the example compiles.
I'm guessing this is somehow related to \SingleSpacing, a memoir macro defined as
\newcommand*{\SingleSpacing}{%
  \setSpacing{\m@m@singlespace}%
  \edef\m@m@footnote@spacing{\baselinestretch}%
  \edef\m@m@float@spacing{\baselinestretch}%
  \vskip\baselineskip% correction for coming into single spacing
}

if I remove the \vskip it works again.
Any idea what on earth is going on here?
Can others reproduce the problem?

A: As diagnosed by @UlrikeFischer, the problem originates in an \unskip issued by \pgfmathsetlength under certain circumstances.
I don't know the innards of TikZ, but here is a re-definition of the first branch of \pgfmathsetlength which uses a temporary box, as it apparently needs to issue a \selectfont and then an \unskip (presumably to get rid of some extraneous space following some dimension definition).
\documentclass[a4paper]{memoir}

\usepackage{xcolor}

\SingleSpacing

%\tracingmacros1
%\def\unskip{\BOOM}
\usepackage{tikz}
\typeout{Original meaning of pgfmathsetlength\meaning\pgfmathsetlength}

\newbox\tempbox
\newif\ifdebug
\debugtrue

\makeatletter
\def\pgfmathsetlength #1#2{\expandafter \pgfmath@onquick #2\pgfmath@
  {\ifdebug\typeout{HERE\detokenize{#1}\detokenize{#2}}\fi
   \setbox\tempbox\hbox{\pgfmath@selectfont#1#2\relax\expandafter}\expandafter#1\the #1\relax
   \ifdebug\typeout{#1=\the#1}\fi}%
  {\pgfmathparse {#2}\ifpgfmathmathunitsdeclared #1\pgfmathresult mu\relax
                     \else #1\pgfmathresult pt\relax \fi }\ignorespaces }
\makeatother

\usetikzlibrary{positioning}
\usetikzlibrary{arrows.meta}
\usetikzlibrary{bending}
\begin{document}

% from the manual
\begin{tikzpicture}
\node [circle,draw] (A) {A};
\node [circle,draw] (B) [right=of A] {B};
\draw [draw = blue, thick,
       arrows={
              Computer Modern Rightarrow [sep]
              - Latex[blue!50,length=8pt,bend,line width=0pt]
                Stealth[length=8pt,open,bend,sep]}]
      (A) edge [bend left=45] (B)
      (B) edge [in=-110, out=-70,looseness=8] (B);
\end{tikzpicture}
\end{document}


text:
Q: Null Pointer Exception Spring Integration messaging i"m getting started with Spring integration ....The following code produced a null pointer exception.
Spring context.xml(Spring configuration)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/integration
    http://www.springframework.org/schema/integration/spring-integration-2.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="co.in" />

    <int:channel id="input" />
    <int:channel id="output">
        <int:queue capacity="10" />
    </int:channel>
    <int:service-activator input-channel="input"
        output-channel="output" ref="messageHandler" />
</beans>

app.java(The main class)
package co.in;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.core.PollableChannel;
import org.springframework.integration.support.MessageBuilder;

public class app {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "classpath:resources/spring-context.xml");
        context.start();

        MessageChannel input = (MessageChannel) context.getBean("input",
                MessageChannel.class);
        PollableChannel output = (PollableChannel) context.getBean("output",
                PollableChannel.class);
        input.send(MessageBuilder.withPayload("Pro Spring Integration Example")
                .build());

        Message<?> reply = output.receive();
        System.out.println("received: " + reply);

    }
}

MessageHandler.java (Service activator bean defnition)
package co.in;

import org.springframework.integration.annotation.ServiceActivator;

@Component
public class MessageHandler {

    @ServiceActivator
    public String handleMessage(String message) {
        System.out.println("Received message: " + message);
        return "MESSAGE:" + message;
    }
}

Error stack
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [resources/spring-context.xml]; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:420)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:113)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:80)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at co.in.app.main(app.java:11)
Caused by: java.lang.NullPointerException
    at org.springframework.beans.factory.support.BeanDefinitionReaderUtils.generateBeanName(BeanDefinitionReaderUtils.java:115)
    at org.springframework.beans.factory.support.BeanDefinitionReaderUtils.generateBeanName(BeanDefinitionReaderUtils.java:159)
    at org.springframework.beans.factory.support.DefaultBeanNameGenerator.generateBeanName(DefaultBeanNameGenerator.java:31)
    at org.springframework.beans.factory.xml.XmlReaderContext.generateBeanName(XmlReaderContext.java:77)
    at org.springframework.beans.factory.xml.AbstractBeanDefinitionParser.resolveId(AbstractBeanDefinitionParser.java:102)
    at org.springframework.beans.factory.xml.AbstractBeanDefinitionParser.parse(AbstractBeanDefinitionParser.java:59)
    at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:69)
    at org.springframework.integration.config.xml.AbstractIntegrationNamespaceHandler.parse(AbstractIntegrationNamespaceHandler.java:57)
    at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1297)
    at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1287)
    at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135)
    at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:507)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
    ... 14 more

A: Based on the stack trace, it looks like you are using Spring Integration 2.0.x.
What version of Spring are you using?
I suggest you use the current release (2.1.3.RELEASE).


text:
Q: Добавить зацикливание для консольного меню C# Суть моего вопроса в том, что могу ли я как-то зациклить перемещение по меню (т.е чтобы я не упирался в границы верха и низа, а перескакивал в начало/конец) не переписывая меню с  case на if'ы
У меня есть код моего консольного меню (если что на gitlab'e есть проект, скину если нужно):
static void Main(string[] args)
        {
            int index = 0;
            while (true)
            {
                DrawMenu(Menu.menuItems, index);
                switch (Console.ReadKey(true).Key)
                {
                    case ConsoleKey.DownArrow:
                        if (index < Menu.menuItems.Length - 1 || index == Menu.menuItems.Length)
                            index++;
                        break;
                    case ConsoleKey.UpArrow:
                        if (index > 0)
                            index--;
                            break;
                    case ConsoleKey.Enter:
                        switch (index)
                        {
                            case 0:
                                PrintPeopleList(readedPeople);
                                ReturnToMainMenu(Menu.menuItems, index);
                                break;
                            case 1:
                                PrintTimelineList(readedTimeline);
                                ReturnToMainMenu(Menu.menuItems, index);
                                break;
                            case 2:
                                PrintNamesPeople();
                                ReturnToMainMenu(Menu.menuItems, index);
                                break;
                            case 3:
                                PrintDeltaTimeline();
                                ReturnToMainMenu(Menu.menuItems, index);
                                break;
                            case 4:
                                AddNewEvent(readedPeople);
                                ReturnToMainMenu(Menu.menuItems, index);
                                break;
                            case 5:
                                AddNewPeople(readedPeople);
                                Console.WriteLine("Человек успешно добавлен!");
                                ReturnToMainMenu(Menu.menuItems, index);
                                break;
                            case 6:
                                Console.WriteLine("Выбран выход из приложения");
                                return;
                        }
                        break;
                }
            }
        }

И метод для того, чтобы видеть перемещение по меню:
        static void DrawMenu(string[] items, int index)
        {
            ClearScreen();
            for (int i = 0; i < items.Length; i++)
            {
                if (i == index)
                {
                    Console.BackgroundColor = ConsoleColor.Gray;
                    Console.ForegroundColor = ConsoleColor.Black;
                }
                Console.WriteLine(items[i]);
                Console.ForegroundColor = ConsoleColor.Black;
                Console.BackgroundColor = ConsoleColor.White;
            }
            Console.WriteLine();
        }

Меню состоит из 6 пунктов, их могу прикрепить, если нужно, но чтобы вопрос был совсем огромным, пока упущу.

A: Это должно было быть просто.
case ConsoleKey.DownArrow:
    if (index < Menu.menuItems.Length - 1)
        index++;
    else
        index = 0;
    break;
case ConsoleKey.UpArrow:
    if (index > 0)
        index--;
    else
        index = Menu.menuItems.Length - 1;
    break;

Кстати, вот это вот || index == Menu.menuItems.Length я не понимаю, зачем.


text:
Q: How do you use PHP on the command line to run jpegoptim? In the putty command line I use this code:
jpegoptim --max=75 /home/testuser/public_html/img/test.jpg

It works well. Then I tried to use this code using the PHP command line interface, like this.
<?php
$command = 'jpegoptim --max=75 /home/testuser/public_html/img/test.jpg';
shell_exec($command);
?>

But it doesn't work. Can anyone help?


text:
Q: Invalid Hook Call, returning a function inside of custom hook that also using the useContext hook I'm trying to write a custom hook that returns a connectWallet function that i can use in components to connect Metamask but i get 'Invalid Hook Call' error.
The 'connect' function that i imported from 'utils/wallet' is making user to connect to my website via Metamask chrome extension.
Inside of the WalletContext.js
import { createContext, useContext, useEffect, useState } from "react";
import {
  connect,
  currentWallet,
  walletListener,
} from "../utils/wallet";

export const WalletContext = createContext();

const WalletProvider = ({ children }) => {
  const [wallet, setWallet] = useState();

  useEffect(() => {
    currentWallet(setWallet);
    walletListener(setWallet);
  });

  const data = {
    wallet,
    setWallet,
  };

  return (
    <WalletContext.Provider value={data}>{children}</WalletContext.Provider>
  );
};

const connectWallet = () => {
  const { setWallet } = useContext(WalletContext);
  connect(setWallet);
};

export const useConnect = () => {
  return { connectWallet };
};

export const useWallet = () => useContext(WalletContext);

export default WalletProvider;

Inside of the ConnectButton component
import { Button } from "@nextui-org/react";
import { Icon } from "@iconify/react";

import { useConnect, useWallet } from "../context/WalletContext";

export default function ConnectButton() {
  const { wallet, setWallet } = useWallet();
  const { connectWallet } = useConnect();

  return (
    <Button
      auto
      css={{
        // position: "absolute",
        // top: "0px",
        // right: "50px",
        zIndex: 1,
      }}
      color={"primary"}
      icon={<Icon icon="entypo:wallet" width="28px" />}
      onPress={connectWallet}
    >
      {wallet
        ? wallet.substring(0, 4) + "..." + wallet.substring(wallet.length - 4)
        : "Connect Metamask"}
    </Button>
  );
}


text:
Q: 401 Unauthorized when calling Stormpath REST API with WebRequest object? I am using Stormpath for my authentication service. I call the RestAPI of Stormpath by using HttpWebRequest.
I am also using HttpWebRequest to call the RestAPI but it does not work.
private void BtnGetResetApiClick(object sender, EventArgs e)
{

var username = "aaaa";
var password = "bbbb";
ServicePointManager.ServerCertificateValidationCallback = Callback;
var request = WebRequest.Create("https://api.stormpath.com/v1/tenants/current") as HttpWebRequest;

request.UserAgent = ".NET SDK";
request.Method = "GET";
request.Accept = "*/*";

var data = string.Format("{0}:{1}", username, HttpUtility.HtmlEncode(password));

var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
string authHeader = string.Format("Basic {0}", token);

request.Headers.Add("Authorization", authHeader);
request.ServerCertificateValidationCallback = Callback;

using (var response = request.GetResponse())
{
    var stream = response.GetResponseStream();
    if (stream != null)
    {
        var streamReader = new StreamReader(stream);
        var str = streamReader.ReadToEnd();
        streamReader.Close();
        stream.Close();
    }
  }
}

private bool Callback(object obj, X509Certificate certificate, X509Chain  chain, SslPolicyErrors errors)
{
 return true;
}

When calling:
var response = request.GetResponse()

I got an exception:

An unhandled exception of type 'System.Net.WebException' occurred in System.dll The remote server returned an error: (401) Unauthorized.

Can you help me to see if my code has something wrong?

A: Update - use the SDK, it's much easier!
If you're calling the Stormpath API from C# frequently, don't bother with writing requests by hand. Use the Stormpath .NET SDK instead. I'm the author. :)
Install it using install-package Stormpath.SDK from the Package Manager Console. Then, create an IClient object:
// In a production environment, you'll want to load these from
// environment variables or a secure file, instead of hardcoding!
var apiKey = ClientApiKeys.Builder()
                 .SetId("Your_Stormpath_API_key_ID")
                 .SetSecret("Your_Stormpath_API_key_secret")
                 .Build();
var client = Clients.Builder()
                 .SetApiKey(apiKey)
                 .Build();

Getting the tenant info is now just a simple call:
var tenant = await client.GetCurrentTenantAsync();
Console.WriteLine($"Current tenant is: {tenant.Name}");

If you really want to make raw requests, you can still do that! I'll explain below.

Constructing the Authorization header
A 401 Unauthorized response means that the API was not able to find a valid Authorization header in your request. To authenticate correctly, you need two things:

*

*An authorization payload in the format apiKeyID:apiKeySecret

*An Authorization header with value: Basic base64(payload)
Here's how to construct the complete header:
// API_KEY_ID and API_KEY_SECRET populated elsewhere
var authPayload = string.Format("{0}:{1}", API_KEY_ID, API_KEY_SECRET);
var authPayloadEncoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authPayload));
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authPayloadEncoded);

You don't need the ServerCertificateValidationCallback = Callback stuff. With the above header, the request will be seen by the API as a valid request (assuming your API Key ID and Secret are correct, of course).

Redirection handling
One thing to watch out for (this tripped me up at first!) is that WebRequest will follow HTTP 302 redirects automatically, but will not apply the existing headers to the new request.
The solution is to disable redirect following:
request.AllowAutoRedirect = false;

This means you'll have to handle 302 responses yourself, but it's the only way to correctly apply the Authorization header to each request.

Working example
I created a simple working example in this gist. Since I'll be creating requests multiple times, I wrote a helper function:
private static HttpWebRequest BuildRequest(string method, string uri)
{
    var request = WebRequest.Create(uri) as HttpWebRequest;
    request.UserAgent = "dotnet/csharp web-request";
    request.Method = method;
    request.ContentType = "application/json";

    // Important, otherwise the WebRequest will try to auto-follow
    // 302 redirects without applying the authorization header to the
    // subsequent requests.
    request.AllowAutoRedirect = false;

    // Construct HTTP Basic authorization header
    var authPayload = string.Format("{0}:{1}", API_KEY_ID, API_KEY_SECRET);
    var authPayloadEncoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authPayload));
    request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authPayloadEncoded);

    return request;
}

And a simple console app to demonstrate getting the current tenant URL and name:
// Get these from the Stormpath admin console
private static string API_KEY_ID = "Your_Stormpath_API_key_ID";
private static string API_KEY_SECRET = "Your_Stormpath_API_key_secret";

static void Main(string[] args)
{
    // First, we need to get the current tenant's actual URL
    string tenantUrl = null;
    var getCurrentTenantRequest = BuildRequest("GET", "https://api.stormpath.com/v1/tenants/current");

    try
    {
        using (var response = getCurrentTenantRequest.GetResponse())
        {
            tenantUrl = response.Headers["Location"];
        }
    }
    catch (WebException wex)
    {
        Console.WriteLine("Request failed. {0}", wex.Message);
        throw;
    }

    // Now that we have the real tenant URL, get the tenant info
    string tenantData = null;
    var getTenantInfoRequest = BuildRequest("GET", tenantUrl);

    try
    {
        using (var response = getTenantInfoRequest.GetResponse())
        using (var responseStream = response.GetResponseStream())
        using (var reader = new StreamReader(responseStream))
        {
            tenantData = reader.ReadToEnd();
        }
    }
    catch (WebException wex)
    {
        Console.WriteLine("Request failed. {0}", wex.Message);
        throw;
    }

    // Use JSON.NET to parse the data and get the tenant name
    var parsedData = JsonConvert.DeserializeObject<Dictionary<string, object>>(tenantData);
    Console.WriteLine("Current tenant is: {0}", parsedData["name"]);

    // Wait for user input
    Console.ReadKey(false);
}

The code is pretty verbose because we're making raw requests to the API. Again, if you're making requests frequently, use the SDK instead!


text:
Q: resultant map to be separated on the basis of comma in java I have developed this below program which sorts the HashMap on the basis of the keys as shown below:
Map<String, String> countryCapitalMap = new HashMap<>();
countryCapitalMap.put("guyana", "georgetown");
countryCapitalMap.put("nepal", "kathmandu");
countryCapitalMap.put("australia", "canberra");
countryCapitalMap.put("india", "newdelhi");
countryCapitalMap.put("japan", "tokyo");
System.out.println("Original Map : \n" + countryCapitalMap);

Map<String, String> sortedMap = new LinkedHashMap<>();
Stream<Map.Entry<String, String>> stream = countryCapitalMap.entrySet().stream();
stream.sorted(Map.Entry.comparingByKey()).forEach(System.out::print);

Now the program is working fine and its output is:
Original Map:
{guyana=georgetown, japan=tokyo, nepal=kathmandu, australia=canberra, india=newdelhi}
australia=canberraguyana=georgetownindia=newdelhijapan=tokyonepal=kathmandu

As shown in the case of the original map that it is comma separated, so I want the resultant map that is sorted on the basis of the keys to be also comma separated. Please advise how to achieve that.
Looking for a solution with method references only.

A: forEach(x -> System.out.println(x + ", "));

or
String result = stream.sorted(Map.Entry.comparingByKey())
         .collect(Collectors.joining(","));

A: The reason is that you output only the text of the entries. So you only use Entry#toString which prints key=value. The map itself concatenates all those entry-texts with commas.
You can fix this by building the String on your own, for example by using StringBuilder, StringJoiner, String#join or Collectors#joining:
String result = stream
    .sorted(Map.Entry.comparingByKey())    // Sorted
    .map(Map.Entry::toString);             // Entry -> String
    .collect(Collectors.joining(", "));    // Collect by joining

// Print the result
System.out.println(result);

Another solution using StringJoiner:
StringJoiner sj = new StringJoiner(", ");
stream.sorted(Map.Entry.comparingByKey())  // Sorted
    .map(Map.Entry::toString);             // Entry -> String
    .forEach(sj::add);                     // Add to joiner

// Print the result
String result = sj.toString();
System.out.println(result);

Here are the documentations of said classes:

*

*StringBuilder

*StringJoiner

*String#join

*Collectors#joining


text:
Q: Concurrent Tasks/Children Processes in ZeroRPC server I am using a ZeroRPC server to implement a service. Some of the functions of the service are long CPU intensive tasks. Since I don't want the RPC call to block, they must be handled appropriately. Considering the GIL, threading does not seem like an appropriate choice. I've tried multiprocessing but the children processes are unable to connect as an RPC client to another (unrelated) RPC server. See the code below. It is important that I am able to spawn off multiple children processes, every time the spin_off_worker() is called. What is the best way of handling/designing these long-lasting CPU intensive tasks within the ZeroRPC server?
RPC server #1
import zerorpc
import multiprocessing
import time
import threading

class Foo(object):

    def heavy_task(self):
        # some long processing...

        # this RPC call never gets made...
        cli = zerorpc.Client(connect_to="tcp://0.0.0.0:3334", timeout=30, heartbeat=5)
        cli.test()
        cli.close()
        return

    def spin_off_worker(self):
        s = multiprocessing.Process(target=self.heavy_task)
        s.start()
        s.join()

def start():
    s = zerorpc.Server(Foo(), heartbeat=5)
    s.bind("tcp://0.0.0.0:3333")
    s.run()
    return s

svr_proc = multiprocessing.Process(target=start)
svr_proc.start()

RPC Server 2
import zerorpc
import time
class Foo(object):
    def test(self):
        print "TIGR"

s = zerorpc.Server(Foo(), heartbeat=5)
s.bind("tcp://0.0.0.0:3334")
s.run()

A: You solution is in the right direction. It just needs few tweaks:

*

*zerorpc requires gevent, and so, runs in a cooperative coroutine environment. Because your worker (server #2) process is going to hold on the CPU for a while, zerorpc will miss heartbeats. You can disable the heartbeat between your master (server #1) and worker (server #2) process. Set heartbeat=None on both side.

*since you are doing local interprocess communication, you might as well use a local unix socket (if you have access to unix sockets on your system). Use something like unix://workers.sock. This might be more efficient than having the full TCP stack on the way.
Heart-beating is more important on the network than locally on the same machine anyway. If want to run your worker on a different machine across the network, do something like: client machine -> [zerorpc heartbeat] -> server machine -> [local zerorpc no heartbeat] -> worker process.
Note: You do not have to instantiate a new zerorpc client for every heavy_task call. You can reuse the same instance over and over.


text:
Q: How to write call back functions for text positioning operators to get text position in pdf search in iPhone? In my iPad app I need to highlight the searched pdf word. I used text showing operators TJ,Tj for finding the text in a pdf document but not able to highlight the searched words. Through googling I found FastPDFKit example for highlighting the searched words but they have used a third party library to achieve that. In my app I should not have to use third party API. I also found
//text positioning operators
CGPDFOperatorTableSetCallback(table, "Td", &op_Td);
CGPDFOperatorTableSetCallback(table, "TD", &op_TD);
CGPDFOperatorTableSetCallback(table, "Tm", &op_Tm);
CGPDFOperatorTableSetCallback(table, "T*", &op_T);

But not getting how to write call back methods (&op_Td, &op_TD, &op_Tm, &op_T)for finding the position of the searched text and how to highlight it???? Do anyone have code for this?? Any help on this will be very helpful.
Thank You :)


text:
Q: The partial sum $\sum_{n \le N} \mu(n)/n \ne 0$ for finite $N \in \mathbb{N}$ Is it known if for any finite $N$, the partial sum $\sum_1^N \frac{\mu(n)}{n}$ is equal to $0$ or, alternatively, isn't $0$ for any finite $N$? Where $\mu(n)$ is a Mobius function.see here.
We know that the sum converges to $0$ when $N \rightarrow \infty$see here. But I am wondering about the partial sum for finite $N$.
I have no ideas about how one could prove or disprove it.
Thanks in advance.

A: There is no $N$ for which the sum is zero.
First, recall that for any integer $N>1$, there is a prime number $p$ such that $N/2<p\le N$.
Let $S_n = \sum_{n=1}^N \mu(n)/n$, and let's consider the value of $p\cdot S_n$ modulo $p$: we can do that as, apart from the term $n=p$, the denominators are all non-zero modulo $p$. This gives us
$$
p\cdot S_n = \sum_{n=1}^N \mu(n)\cdot\frac{p}{n}
\equiv \mu(p) = -1 \pmod p
$$
as the terms for $n\not=p$ all vanish modulo $p$ after multiplication by $p$.


text:
Q: Continuity theorem for Laplace transform: limiting function uniqueness Let $(\mu_n)_{n\in\mathbb{N}}$ be a sequence of probability measures on $[0,\infty)$. Assume we know that
$\lim_{n\to\infty}\int e^{-tx}\mu_n(dx) = \psi(t)$ for $t\geq0$, $n\in\mathbb{N}$, and $\psi:[0,\infty)\to[0,1]$ is a map continuos in $0$.
How can I show that $\psi$ is the Laplance transform of a probability measure $\mu$ on $[0,\infty)$? (This is Ex 15.3.4 of Probability Theory by A. Klenke, 3rd version).
My main doubt is that, if I am able to show that the sequence of $\mu_n$ is tight, how can I check that the limit function $\psi$ is a Laplace transform and not something else? (Basically I am trying to apply Theorem 13.34 of the same book for the interested ones).
Edit
How would you check the tightness of the sequence?
Thank you.

A: By tightness there is a subsequence $(\mu_{n_k})$ converging weakly to some probability measure $\mu$. Since $e^{-tx}$ is a bounded continuous function we get $\psi (t)=\int e^{-tx}d\mu(x)$ for all $t \geq 0$.
Let $\epsilon >0$. Since $\psi (0)=1$ and $\psi$ is continuous at $0$ we can find $r$ such that $\int e^{-rx}d\mu_n(x) >1-\epsilon$  for all $n$. Now, $$1-\epsilon \leq \mu_n ([0,M])+\int_M^{\infty} e^{-rx}d\mu_n(x) \leq \mu_n ([0,M])+ e^{-rM}\mu_n(M,\infty).$$ This can be written as $\mu_n(M,\infty) \leq   \epsilon +e^{-rM}\mu_n(x)(M,\infty)$. I will let you finish the proof from here.


text:
Q: Using batch for processing Text file I am new to batch scripting and  would like to process my input file with the content :
MD5 hash of sample.js,
81f87dd81ef88f59a57d95d9ede5f92e
MD5 hash of searchReplace.js,
3493b216e1024f0d6de417ef6c8b3962
MD5 hash of Select Anything.js,
009f2b911b50550502b87aeeeb969b55

The output should look like :
MD5 hash of sample.js,81f87dd81ef88f59a57d95d9ede5f92e
MD5 hash of searchReplace.js,3493b216e1024f0d6de417ef6c8b3962
MD5 hash of Select Anything.js,009f2b911b50550502b87aeeeb969b55

 Can someone please help me out with it ?

A: try this:
@echo off
setlocal enableDelayedExpansion
set "info_file=.\example1.txt"

for /f "useback tokens=* delims=" %%a in ("%info_file%") do (
    set "line=%%a"
    if "!line:~0,3!" EQU "MD5" (
        set "to_echo=!line!"
    ) else (
        set "to_echo=!to_echo!,!line!"
        echo !to_echo!
    )
)

endlocal

A: This works:
@echo off
setlocal

call :procFile < input.txt > output.txt
goto :EOF

:procFile
   set /P "line1="
   if errorlevel 1 exit /B
   set /P "line2="
   echo %line1%%line2%
goto procFile

You may also read the file via a for /F command this way:
@echo off
setlocal EnableDelayedExpansion

set "line="
(for /F "delims=" %%a in (input.txt) do (
   if not defined line (
      set "line=%%a"
   ) else (
      echo !line!%%a
      set "line="
   )
)) > output.txt


text:
Q: Cannot connect to my hosting service's MySql database. NB I am EXTREMELY new to the html/php scene but I have been working at this for hours. I am stumped.
I am trying to connect to a sql database that will store username and password information. I use fortune city for hosting and I have already used their phpAdmin to setup up all of the necessary stuff (db, tables, etc..).
I am using Eclipse with Zend on the side. I am also running Sql Server and Apache 2.2.
I believe my issue is the following:
I have a db located at a certain ip address (remote fortunecity server) and I am testing my project on the local server. Fortune city offers two different host names, one for internal connections and one for external connections. I get different results from each one:
If I connect to the internal site it doesn't make any connection, I know this because of my die statement. If I connect to the external host it connects, but doesn't allow me to connect to the database. (see cases below code)
Currently my process is as follows. (PLEASSSSE TELL ME A BETTER WAY IF I'M DOING THINGS THE INEFFICIENTLY, I feel dirty every time I do it!!)

*

*Create or edit my index.php, login.php, etc... in eclipse.

*Copy the files that I edit into my Apache root.

*Go back to eclipse and run the project in a browser "firefox."

*repeat n to the n times.

Keep in mind my sql database is located on the net
Can this be done? Testing locally while accessing a db on the net?
Here is the code:
<?php

if (!isset($_POST['username']) || !isset($_POST['password'])) {
header( "Location: http://localhost/index.php" );
}

elseif (empty($_POST['username']) || empty($_POST['password'])) {
header( "Location: http://localhost/index.php" );
}
else{

$user = addslashes($_POST['username']);
$pass = md5($_POST['password']);

$dbHost = "mysql3341.dotsterhost.com";
$dbUser = "*********";
$dbPass = "******";
$dbDatabase = "**********";

$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");

mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");

$result=mysql_query("select * from userInfo where username='$user' AND password='$pass'", $db);

$rowCheck = mysql_num_rows($result);
if($rowCheck > 0){
while($row = mysql_fetch_array($result)){

session_start();
session_register('username');

echo 'Success!';

header( "Location: checkLogin.php" );

}

}
else {

echo 'Incorrect login name or password. Please try again.';
}
}
?>

Again, I have never made it past

Case :1 $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
Case :2 mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
Thanks for reading my novel!

A:
Can this be done? Testing locally while accessing a db on the net?

Yes you can, but be aware if you are storing anything sensitive in your database you probably wouldn't want to be sending that data unencrypted over the net.  (Unless you are connecting over a VPN or another type of secure network connection.)
Usually you'd want to setup a development environment on your local box or you can edit your files locally in something like Aptana (http://www.aptana.com/) and have it automatically deploy your files to the server every time you save.
Also, as suggested in the comments, using a framework to develop on usually give you a powerful database library without the need to reinvent it on your own.  (That is unless you feel like wrapping your own!)