text:
Q: How to install games on 64bit linux mint with updated graphics? I am using Linux Mint 11 64 bit version, and I recently installed Counter strike Condition Zero. However the game performance is extremely poor.
 wine "C:\Program Files\Valve\hl.exe" -nomaster -game czero
fixme:d3d_caps:select_card_intel_mesa Card selection not handled for Mesa Intel driver
fixme:d3d_caps:init_driver_info Unhandled vendor 8086.
fixme:win:EnumDisplayDevicesW ((null),0,0x32f364,0x00000000), stub!
fixme:d3d_caps:select_card_intel_mesa Card selection not handled for Mesa Intel driver
fixme:d3d_caps:init_driver_info Unhandled vendor 8086.
fixme:win:EnumDisplayDevicesW ((null),0,0x32f380,0x00000000), stub!
fixme:x11drv:X11DRV_desktop_SetCurrentMode Cannot change screen BPP from 32 to 16
fixme:shdocvw:ViewObject_SetAdvise (0x1e7230)->(1 00000002 0xf27d10)

I later came to know that I needed 32 bit graphics drivers. I have onboard graphics chipset 945G from Intel Corp
glxinfo | grep OpenGL
Mesa: Initializing x86-64 optimizations
OpenGL vendor string: Tungsten Graphics, Inc
OpenGL renderer string: Mesa DRI Intel(R) 945G
OpenGL version string: 1.4 Mesa 7.12-devel (git-eab201b natty-oibaf-ppa)
OpenGL extensions:

and I want to install the correct drivers for my game to run. Can you tell me how to install them and also in case of source tell me how to compile and install.

A: I have the exact same Integrated graphics as you and HAD the same problem.  Do what these guys did and it will instantly solve your problem.
http://forums.debian.net/viewtopic.php?f=5&t=67231
You will have to update these packages to the version there or better
libdrm2_2.4.26-1~bpo60+1_i386.deb
libdrm-intel1_2.4.26-1~bpo60+1_i386.deb
libgl1-mesa-dri_7.10.3-4~bpo60+1_i386.deb
libgl1-mesa-glx_7.10.3-4~bpo60+1_i386.deb
libglu1-mesa_7.10.3-4~bpo60+1_i386.deb
libpciaccess0_0.12.0-1_i386.deb

You might also need libglapi-mesa


text:
Q: Two or more mysqli connection at the same time throws me Acces Denied error I'm getting this error Access denied for user 'user'@'localhost' (using password: NO)
when I open a second mysqli connection in the same script.
I have a class which has 2 properties(Subclasses). This both properties extends from the DataBase class(which makes a new mysqli connection). At the moment when this subclases get instantiate I got that Access denied error.
Is there a way to establish two mysqli connection or my logic is wrong and a class shoulnd't have 2 subclasses like this ?
I hope I could explain myself. Thanks in advance

A: There's no reason I can think of to open 2 connections to the same database server. You should create your connection and pass it to your functions as an argument.
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

class Foo {
      /** @var \mysqli */
      protected $db;

      public function __construct(mysqli $mysqli) {
           $this->db = $mysqli;
      }

      public function bar() {
           $res = $this->db->query('SELECT * FROM table');
           $data = array();
           while($row = $res->fetch_assoc()) $data[] = $row;
           return $data;
      }
}

$class = new Foo($mysqli);

A: Check your max_user_connections on your my.cfg file.

*

*max_user_connections
The maximum number of simultaneous connections permitted to any given MySQL user account. A value of 0 (the default) means "no limit."
This variable has a global value that can be set at server startup or runtime. It also has a read-only session value that indicates the effective simultaneous-connection limit that applies to the account associated with the current session. The session value is initialized as follows:
If the user account has a nonzero MAX_USER_CONNECTIONS resource limit, the session max_user_connections value is set to that limit.
Otherwise, the session max_user_connections value is set to the global value.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disabling the Squid Error pages I've just started looking at using Squid for a project and can't seem to see an easy way of disabling the Squid error pages (e.g. "Name Error: The domain name does not exist"). We use a custom browser which handles that scenario in our way, so the Squid error pages are overriding our custom logic.
Is it possible to set them too 'off'? I've been through the .conf and I've found where the error pages are stored, but no real options to disable them.

A: If you are moving from not using a proxy to using squid there are some functions that your browser will no longer be completing.
Using the "Name Error" you mention as an example...
Without a proxy, the browser will attempt a DNS name lookup from the local resolver and it will fail which results in a local application error.
When you use a proxy your local browser does not do DNS name lookup. It opens a connection to the proxy and sends it the URL, so the proxy does the lookup, has the resolver error then sends a http response back to the browser as that is the only interface between the two.
You can always copy and modify the squid error pages to match your browser (somewhere like /usr/share/squid-langpack/templates and then set error_directory). Or further customise your browser to provide your custom error messages for particular http error responses from squid. You may need to create simpler tags in the squid error pages that your browser can match easily.

A: probably http://wiki.squid-cache.org/Features/ICAP that will help you


text:
Q: what can you say about two exactly same neural networks after training on same dataset? Supposed you have two convolutional neural networks implemented in matlab and composed by these layers:

*

*imageInputLayer

*ConvolutionalLayer

*maxPoolinglayer

*relulayer

*softmaxlayer

*fullyconnectedlayer

*classification layer

Both of these networks have exactly same architecture.
I apply the same method of training for 2 networks with same hyperparameters.
Both of these networks have exactly same weights in their corresponding layers.
That is, both of these networks are a replica of each other.
Both of these networks are trained using exactly same training set and validation set without shuffle.
I am wondering:

*

*Will the scores (training error and validation error) and trained weights be different for both?

*Does it depend upon the method for training?

A: In short: Yes to both - because inital weights are usually initated using random numbers.
A tad less short: A neural network is simply an algorithm, if there is no noise (i.e. randomness) introduced in any function on the way, 2 networks will end up being completely the same.


text:
Q: How to send a private message to members of a specific role not in a voice channel? This is the code I use to count members with a specific role whom are in a voice channel. I want to send a private message to members with the role and not in a voice channel. How can I do so?
var takaci = 0;
let a = client.guilds
    .get(sunucuid)
    .roles.get(rolid)
    .members.filter(o => o.voiceChannel).size;
let ses = a;

A: *

*Inverse your predicate function in Collection.filter() to acquire only those members with the role and not in a voice channel. Use the ! character, or logical NOT operator.

*Iterate over your Collection.

*Use GuildMember.send() to send a direct message to each member individually.
const membersToMsg = client.guilds.get(sunucuid).roles.get(rolid).members.filter(m => !m.voiceChannel);

for (const [, member] of membersToMsg) {
  member.send('Hello, world!')
    .catch(console.error); // 'Cannot send messages to this user' is most likely due to privacy settings
}

I'm using a for...of loop in this code rather than Map.forEach() because the latter will simply fire promises and move on, possibly resulting in uncaught rejections.


text:
Q: Specifying wildcard paths for PowerShell I have a directory structure that is 2 folders deep(e.g. folder1/folder1/file1.txt, folder1/folder2/file1.txt, etc.). I need to traverse the directory structure recursively to extract all the data of the text files and put them in one large text file in the folder above. The command is:
Get-Content .\*\*\*.txt | Out-File ..\whole.txt

Here's the error for this command:
Get-Content : An object at the specified path .\*\*\*.geojson does not exist, or has been filtered by the -Include or
-Exclude parameter.
At line:1 char:1
+ Get-Content .\*\*\*.geojson | Out-File ..\whole_us.geojson
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (System.String[]:String[]) [Get-Content], Exception
    + FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand

How do I specify wildcard paths?

A:
have a directory structure that is 2 folders deep(e.g. folder1/folder1/file1.txt, folder1/folder2/file1.txt, etc.). I need to traverse the directory structure recursively to extract all the data of the text files and put them in one large text file in the folder above. The command is:
Get-Content .***.txt | Out-File ..\whole.txt
Here's the error for this command:
Get-Content : An object at the specified path .***.geojson does not
exist, or has been filtered by the -Include or
-Exclude parameter. At line:1 char:1
How do I specify wildcard paths?

As explained in a comment to your question, it appears that the file extension of the input file does not match the file extension of the file that actually exists.  This means that your syntax isn't correct. The description for the -PATH parameter is as follows:

Specifies the path to an item where Get-Content gets the content. Wildcard characters are permitted. The paths must be paths to items, not to containers. For example, you must specify a path to one or more files, not a path to a directory.

You will want to run the following command instead.
Get-Content -PATH .\*\*\*.txt | Out-File ..\whole.txt

The parameters for Get-Content are documented as follows:
Get-Content
   [-ReadCount <Int64>]
   [-TotalCount <Int64>]
   [-Tail <Int32>]
   [-Path] <String[]>
   [-Filter <String>]
   [-Include <String[]>]
   [-Exclude <String[]>]
   [-Force]
   [-Credential <PSCredential>]
   [-Delimiter <String>]
   [-Wait]
   [-Raw]
   [-Encoding <Encoding>]
   [-AsByteStream]
   [-Stream <String>]
   [<CommonParameters>]

Source: Get-Content Syntax


text:
Q: Comand line argument to variable as integer I have a function with width currently defined as "unsigned long width" and then define it as "width = 16".
Instead, I'd like 16 to be the default number, but I want there to be an option to set a different integer for width with the command line when started.
Command could be /program command -width 100 filename
I've tried to do this as following but it does not compile and I'm not able to debug it successfully.
Main is set to int main(int argc, char *argv[]).
my attempt
void process_file(FILE *infile,unsigned long end)
{
    char ch;
    int width,start,f_index=0;   //File index
    unsigned long bb_index=0;  // Buffer index
    //width =16; // Width is fixed as 16
    if((argc == 5) && (strcmp(argv[2],"-width") == 0))
    {
        width = atoi(argv[3]);
    }
    else
    {
        width = 16;
    }
    unsigned char *byte_buffer = malloc(width);
    start=0; // Starting at zero
    while (!feof(infile))
    {
        ch = getc(infile);
        if ((f_index >= start)&&(f_index <= end))
        {
            byte_buffer[bb_index] = ch;
            bb_index++;
        }
        if (bb_index >= width)
        {
            print(byte_buffer,bb_index,width);
            bb_index=0;
        }
    }

original function with defined (static) width which works, but does not read argv[3]
void process_file(FILE *infile,unsigned long end)
{
    char ch;
    unsigned long width,start,f_index=0;   //File index
    unsigned long bb_index=0;  // Buffer index
    width =16; // Width is fixed as 16
    unsigned char *byte_buffer = malloc(width);
    start=0; // Starting at zero
    while (!feof(infile))
    {
        ch = getc(infile);
        if ((f_index >= start)&&(f_index <= end))
        {
            byte_buffer[bb_index] = ch;
            bb_index++;
        }
        if (bb_index >= width)
        {
            print(byte_buffer,bb_index,width);
            bb_index=0;
        }
        f_index++;
    }
    if (bb_index)
        print(byte_buffer,bb_index,width);
    fclose(infile);
    free(byte_buffer);
}

A: argc and argv aren't being passed into process_file so it wont compile.
Try parsing the command line parameters in your main function and passing in width as a parameter to process_file.
You should also reorder your parameters to have filename before width as width is optional and filename is not?
Maybe your main function could look something like.
int main(int argc, char** argv)
{
    /*
        usage program <command> <filename> -width 100
    */

    if(argc < 3)
    {
        printf("not enough args\n");
    } else
    {
        int width = 16;

        if((argc == 5) && (strcmp(argv[3],"-width") == 0))
        {
            // atoi doe not detect conversion failure use strol maybe?
            width = atoi(argv[4]);
        }

        FILE* f = fopen(argv[2], "r");

        if(f)
        {
            int arbitary_endval = 100;
            process_file(f, arbitary_endval, width);
        } else
        {
            printf("could not open file %s\n", argv[2]);
        }
    }
}

I've put 100 in as an arbitrary value for end.

A: The program will not compile because argc and argv are undefined within the scope of the function process_file. The declaration int main(int argc, char *argv[]) is OK, but it declares argc and argv only within the body of the main function itself.
I would recommend either passing argc and argv as additional arguments to the function process_file, or parse the command line outside process_file and pass the width as an argument to that function.
Your rules for the order of things on the command-line seem a bit rigid, but if width is the only optional command-line parameter then you may be able to make do with this kind of logic.
Here is more general question about command-line options with some good answers: Parsing command-line arguments?


text:
Q: How to perform testing of web services and WCF? Say I have created a webservice and WCF service.
How are the different kinds of testing (viz. unit testing, SIT, etc) performed for web services and WCF service.
Do i need to explicitly create a sample project to test the service by passing input parameters and analyzing output parameters or are there any tools through which we can perform all kinds of testing.

A: Since WCF services are just classes, they can generally be unit tested like any other class, provided you don't use any WCF-specific functionality in your service class.  You can start with Mark Seemann's blog post about this.
For more end-to-end style integration testing, there are a variety of considerations to keep in mind:

*

*Deployment/topology: Is the service hosted at a remote external endpoint, outside of the test client?  Or does the test environment need to install and host the service locally?  The answers to these and related questions will determine how to design the setup portion of the testing.

*Client types: Do the clients of your service communicate over specific transports (HTTP, TCP, etc.)? Do they require message-level or transport security?  Do they use transactions, asynchronous communication, large and small message sizes, etc.?  The answers to these questions will determine how large your possible "test matrix" might be.

*Server configuration: Does your service support multiple platforms or hosting types?  Do you have any "knobs" on your service that could be modified in production?  Ideally these will be tested so you know that you don't have any hidden bugs.

*Validation: How do you know that your service has done the right thing?  Do you need to inspect server-side logs for errors/warnings?  Are you concerned with performance or memory characteristics for various operations (if so, you may want performance counter readings)?  How much validation can be done solely from the client perspective?

This is just a small sampling of the kinds of things that go into testing a web service.  It is a hard problem that requires the right level of expertise and a good degree of teamwork.  Your test engineers should work closely with the developers/architects to understand how the service works and how it will be used in production.  This will help them create a plan with the right scope and coverage for the intended use cases.
To address the other part of the question: there are some libraries that can automatically generate simple tests with input/output values.  The Microsoft Research project "Pex" is one such example.

A: There are different kinds of testing like you said.
I like unittesting. To unit test your webservice, you would create a seperate project, and create a testclass that has a bunch of testmethods. In each of those methods you yould test your DLL (NOT The Webservice hosted by IIS/whatever) and verify it behaves as expected.
You should also make sure that the DLL is not comunication to anything on the outside during a UNIT-Test (That means: Filesystem, Database, other webservices, anything you dont control). Reason for that is that you want to test YOUR code, and not possible infrastructure issues like network, authorization, or state of the database...
There are testrunners in VS or you can download testdriven.Net or resharper.
See: http://en.wikipedia.org/wiki/Unit_testing
Then there are also integration tests. Those would basically test the webservice when it is hosted by IIS, and make sure that the setup as a whole works smoothly. An integration test supplements a unittest, but should not be the only test. I would go as far and say "Integration tests are late tests", and fixing bugs dicovered during integration usually costs more then fixing those dicovered during unit tests.


text:
Q: Как можно создать zipfile с паролем, и архивировать туда папку И так, у меня есть патч
paths = {"Root": os.getenv("APPDATA") + f"\\nuk.incorporation"}

и содержимое этой папки нужно архивировать (там есть подпапки их тоже нужно), но как на архив поставить пароль?


text:
Q: Redis Server Cluster Not Working On src directory, i am running below command
/redis-trib.rb create --replicas 1 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005

but getting below error.

Creating cluster
      [ERR] Sorry, can't connect to node 127.0.0.1:7000

However if i am starting the node at 7000 using command "redis-server redis.conf" where redis.conf is below
port 7000
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 10
cluster-slave-validity-factor 0
appendonly yes
and simillarly i started redis in all ports succesfully.
Now when i am running
/redis-trib.rb create --replicas 1 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005
i am getting another erorr.

Creating cluster [ERR] Node 127.0.0.1:7000 is not empty. Either the node already knows other nodes (check with CLUSTER NODES) or
        contains some key in database 0.

please help.

A: The first error is because redis-trib create attempts to connect to the redis instances while creating the cluster- however you do not have any redis instances running at 127.0.0.1:7000.
The second error looks like you started your redis instance, but now your cluster cannot be created because you already tried to create a cluster on node 7000 (Probably allocated slots to your node) before you got the first error message. To wipe the node clean, run
$redis-cli -p 7000
127.0.0.1:7000> flushall
127.0.0.1:7000> cluster reset
127.0.0.1:7000> exit

then your redis-trib create will work.

A: Perform steps in the following manner
stop -> clean -> start -> create
of the servers.


text:
Q: Need a shell script that bzip2's every single file recursively from a certain folder I know that this is really not my strong side to write those scripts.
I need a shell script which recursively packs every single file in its folder into the .bz2 format because I have a lot of files and when I do this manually it takes me hours.
For example here are alot of files(much more then this example):
/home/user/data/file1.yyy
/home/user/data/file2.xxx
/home/user/data/file3.zzz
/home/user/data/file4.txt
/home/user/data/file5.deb
/home/user/data/moredata/file1.xyz
/home/user/data/muchmoredata/file1.xyx

And I need them all formated into .bz2 like this:
/home/user/data/file1.yyy.bz2
/home/user/data/file2.xxx.bz2
/home/user/data/file3.zzz.bz2
/home/user/data/file4.txt.bz2
/home/user/data/file5.deb.bz2
/home/user/data/moredata/file1.xyz.bz2
/home/user/data/muchmoredata/file1.xyx.bz2

Another thing that would be great when at then end the script will run one times chown -R example:example /home/user/data
I hope you can help me

A: bzip2 will accept multiple files as arguments on the command line. To solve your specific example, I would do
cd /home/user/
find . -type f | egrep -v '\.bz2' | xargs bzip2 -9 &

This will find all files under /home/user, exclude any already existing .bz2 files from processing, and then send the remaining list via xargs to bzip2. The -9 gives you maximum compression (but takes more time). There is no limit to the number or length of filenames that can be processed when using xargs to feed the command (in this case bzip2).
The & char means "run all of this in the background". This means the command prompt will return to you immediately, and you continue other work, but don't expect all the files to be compressed for a while. At some point you'll also get messages like 'Job %1 ... started' and later, 'Job %1 ... finished'.
As you asked for a script, we can also do this
#!/bin/bash
if [[ ! -d "$1" ]] ; then
   echo "usage: b2zipper /path/to/dir/to/search" 1>&2
   exit 1
if
find "$1" -type f | egrep -v '\.bz2' | xargs bzip2 -9 &

Save this as b2zipper, and then make it executable with
chmod +x b2zipper

IHTH

A: To build on accepted answer, an alternative would be:
find /path/to/dir -type f -exec bzip2 {} \;


text:
Q: Can beats be produced by two waves moving in opposite direction? I've always seen beats to be produced when two waves are said to be moving in the same direction with different frequency.
Can beats be produced by addition of waves moving in opposite direction ?

A: Two waves moving in opposite directions that have the same amplitude and frequency produce a standing wave.  If one of those waves has a slightly different frequency than the other, it should produce a "standing wave" that slowly moves.  As the anti-nodes and nodes move past an observer's ear, they would hear an increase in amplitude followed by a decrease in amplitude, and this variation in sound amplitude would be interpreted as beats.
Generating such an effect would be "tricky".  A sound generator would have to broadcast a pure tone and face a sound reflector such that a standing wave was created.  Then, the sound reflector would have to be put in motion, moving either directly towards the sound generator or directly away from it such that the Doppler effect slightly shifted the frequency of the reflected sound.  If the sound reflector was very efficient (close to 100% reflectivity) and a small microphone was placed in the path of the reflected sound waves, it should be possible to record the effect.

A: Beats are produced by the superposition of two waves at a specific location. The superposition is the sum of the displacements produced by the waves, not by the direction of velocities of the waves.
If you're considering longitudinal (sound) waves, there are compressions and rarefactions produced along the paths of the waves. If we consider sinusoidal waves, the compressions are $\lambda/2$ and $\lambda '/2$ apart and travel at speed $f\lambda= f'\lambda '$. The superposition occurs at a point in space. The beat frequency is a consequence of the compressions matching or cancelling each other at that point. The direction from which they arrive has no bearing on how often they reinforce or cancel.
Hearing beats is actually a psychoacoustic phenomenon. If the frequencies are different enough you will hear two frequencies rather than one, beating. The point at which that occurs varies from person to person. The mechanical effects of beats depend on the coupling of the structures experiencing the two source frequencies. It may be benign if the beat or the average (higher) is not a resonant frequency of the structure, or the beat could be destructive if it is near a resonance and not properly damped.
Again, the velocity directions of the waves are unimportant for the beating effect to occur. For acoustic beating, consider that the sounds are bouncing off the walls and ceiling and floors, so the waves are coming from all directions.

A: This answer expands on the anwer by David White.
Take the case of two sources of propagating waves, let's make that sound sources.
Sound spreads in all directions, so the larger your distance to the source the smaller the amplitude of the sound that reaches your ears.
When the two sources are right next to each other then wherever you are positioned the two waves will have pretty much the same distance attenuation. So you can move closer to the source, or away from it, the beat frequency phenomenon remains roughly the same.
Now the case of the same two sources, but now they are a signicant distance apart, and you are positioned somewhere in between.
The two sources emit sound with a slightly different frequency, so there will be a beat frequency. Except, as indicated by David White, there will be only a single "sweet spot" where your distance to the two sources is such that the amplitudes of the sounds as they reach your ears are roughly the same.
Everywhere else you still get some degree of beating, but not as pronounced as when you are standing at the "sweet spot".

Overview:
The only necessary condition for beat frequency is that you have two sources that are off by a small fraction of their own frequency. Alignment of direction of propagation is immaterial.
It's just that if the two sources are not right next to each other the full wave cancellation will occur only at a relatively small "sweet spot".


text: Q: Посоветуйте ресурсы для изучения линукса Пожалуйста посоветуйте ресурсы где можно научиться пользоваться линуксом. Желательно, чтобы в этих ресурсах были задачи, которые нужно решить используя линукс (что на подобии проекта Эйлера).


text:
Q: Best way to render hand-drawn figures I guess I'll illustrate with an example:
In this game you are able to draw 2D shapes using the mouse and what you draw is rendered to the screen in real-time. I want to know what the best ways are to render this type of drawing using hardware acceleration (OpenGL). I had two ideas:

*

*Create a screen-size texture when drawing is started, update this when drawing, and blit this to the screen

*Create a series of line segments to represent the drawing, and render these using either lines or thin polygons

Are there any other ideas? Which of these methods is likely to be best/most efficient/easiest? Any suggestions are welcome.

A: I love crayon physics (music gets me every time). Great game!
But back to the point... He has created brush sprites that follow your mouse position.  He's created a few brushes that account for a little variation.  Once the mouse goes down, I imagine he is adding these sprites to a data structure and sending that structure through his drawing and collision functions to loop through. Thus popping out the real-time effect.  He is using Simple DirectMedia Layer library, which I give two thumbs up.

A: I'm pretty sure the second idea is the way to go.

A: First option if the player draws pure freehand (rather than lines), and what they draw doesn't need to be animated.
Second option if it is animated or is primarily lines. If you do choose this, it seems like you'd need to draw thin polygons rather than regular lines to get any kind of interesting look (as in the crayon example).


text:
Q: How does an iOS device identify itself to server without user log in I am writing an iOS app with a Rails API backend. The Rails backend will serve JSON data to the app. I have the following requirements.

*

*The app will be a free download

*The app will show data on a map

*The app will show data in the vicinity of the user

*Upon loading the app the device should send some unique identifier to the server identifying itself as a device that is running this app.

*There will be no authentication for the user as it is not required. The data is available to anyone who downloads the app. All the server needs to know is that the client is a device running the app. The server cannot serve data to any other client

*I would like to run the data using SSL between the device and server

*The user location will be sent to the server and the server returns the corresponding pieces of data that are in the vicinity of the user

*The client receives the JSON and caches the data locally.

Question: Given these requirements, how to set up steps 4 & 5?
Also: If I want to search more on this topic what keywords should I be googling for?

A: Consider using OpenUDID or SecureUDID.

A: I give you 2 options.
First of all, the easy way. From some time, apple forbids access to the device ID. However, they give you a device token instead.
To get this unique token, the user must register for remote notification.
Upon application launching, call the following function:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

Then this callback will be called:
 - (void)application:didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken.

Send the token to your server and you're done. Problems with this approach are obvious. Your user will have to register for remote notification.
Another approach is to use the MAC address of the wi-fi board.
To do this:
IPAddress.h
IPAddress.c
Import this files into your project.
Then use this function:
InitAddresses();
GetHWAddresses();

for (int i=0; i<MAXADDRS; ++i)
{
    //There is a way you can obtain more info about the hw_addrs, but in general, it's the first.
    NSLog(@"MAC: %s",  hw_addrs[i]);
}

FreeAddresses();

Create a hash using the mac address above and you're done.
Hope it helps.

A: Upon first launch, the app sends a request to the server saying Hi, I'm a new client, give me an id! The server generates a new, random id and sends it back. The app saves the id locally and uses it henceforth to uniquely identify itself.


text:
Q: Get Spring Security Principal in JSP EL expression I am using Spring MVC and Spring Security version 3.0.6.RELEASE. What is the easiest way to get the user name in my JSP? Or even just whether or not the user is logged in? I can think of a couple ways:
1. Using a scriptlet
Using a scriptlet like this to determine if the user is logged in:
<%=org.springframework.security.core.context.SecurityContextHolder.getContext()
    .getAuthentication().getPrincipal().equals("anonymousUser")
    ? "false":"true"%>

I'm not a fan of using scriptlets, though, and I want to use this in some <c:if> tags, which requires putting it back as a page attribute.
2. Using SecurityContextHolder
I could again use SecurityContextHolder from my @Controller and put it on the model. I need this on every page, though, so I'd rather not have to add this logic in every one of my Controllers.
I suspect there's a cleaner way to do this...

A: Check Spring security tags : <sec:authentication property="principal.username" />
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html
And you can check if logged :
<sec:authorize access="isAuthenticated()">

instead of c:if

A: I agree with alephx, I even voted his answer.
But if you need another approach, you could use the one that Spring Roo uses.
If you have the SecurityContextHolderAwareRequestFilter, it provides the standard servlet API security methods, using a request wrapper which accesses the SecurityContext.
This filter is registered with the <http> tag from the Spring Security namespace. You can also register it in the FilterChainProxy's security filter chain (just add the reference to a declared bean in your applicationContext-security.xml)
Then, you can access the security servlet API as Roo does (find the footer.jspx to see how a conditional logout link is written)
  <c:if test="${pageContext['request'].userPrincipal != null}">
<c:out value=" | "/>
...

A: I think <sec:authentication property="principal.username" /> will not always work because type returned by Authentication.getPrincipal() is Object, ie: it could be a UserDetail (for which the above will work), a String or anything else.
For purpose of displaying username in JSP page what I find more reliable is using ${pageContext.request.userPrincipal.name}.
This uses java.security.Principal.getName() which returns String.

A: This works whether user is logged in or not, and works when using Anonymous Authentication:
<sec:authorize access="isAuthenticated()">
    <sec:authentication property="principal.username" var="username" />
</sec:authorize>
<sec:authorize access="!isAuthenticated()">
    <sec:authentication property="principal" var="username" />
</sec:authorize>

Later...
Hello ${username}

A: j tag is:
<%@taglib prefix="j" uri="http://java.sun.com/jsp/jstl/core" %>

sec tag is:
<%@taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

Add to pom.xml:
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>3.1.3.RELEASE</version>
</dependency>

Add to the page:
<sec:authentication var="principal" property="principal"/>
<j:choose>
    <j:when test="${principal eq 'anonymousUser'}">
          NOT AUTHENTICATED
    </j:when>
    <j:otherwise>
          AUTHENTICATED
    </j:otherwise>
</j:choose>

A: I know there are other answers in the thread, but none have answered how you can check if user is authenticated. So I'm sharing what my code look likes.
Include the tag lib in your project:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

Then create a user object in current scope by adding:
<sec:authentication var="user" property="principal" />

Then you can easily show the username by adding. Remember the 'principal' object is generally of type string unless you have implemented the spring security in a way to change it to another Class in your project:
<sec:authorize access="hasRole('ROLE_USER') and isAuthenticated()">
${user}
</sec:authorize>

I hope this helps somebody looking to check user roles.
If you are using Maven, then add the dependency tag as mentioned by Christian Vielma in this thread.
Thanks!

A: You can use like this:
Spring Security Tag Lib - 3.1.3.RELEASE
<sec:authentication var="principal" property="principal" />

and Then:
${principal.username}

A: I was using Maven so I had to add the taglibs library adding this to the pom.xml
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>3.1.3.RELEASE</version>
</dependency>

Then in my jsp added:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

And:
<sec:authentication property="principal" />

principal.username kept giving me errors (maybe is the way I created the UsernamePasswordAuthenticationToken object, not sure).

A: As far as I know by default Spring Security 3.0.x installs a SecurityContextHolderRquestAwareFilter, so that you can get the Authentication object by calling HttpServletRequest.getUserPrincipal(), and you can also query roles by calling HttpServletRequest.isUserInRole().

A: For accessing a principal attribute use, first, create a variable for attributes:
<sec:authentication property="principal.attributes" var="principalAttr"/>

Then, you can use this map for retrieving values by the attribute key name:
${principalAttr.get("given_name")}

Do not forget to add spring security taglib in your maven dependencies list:
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>5.3.4.RELEASE</version>
    </dependency>

A: 1) MY CUSTOM USER CLASS with extra field mobile:
 public class SiteUser extends User {

    public SiteUser(String username, String password, Collection<? extends GrantedAuthority> authorities,
            String mobile) {
        super(username, password, true, true, true, true, authorities);
        this.mobile = mobile;
    }

    private String mobile;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

}

2) IN MY UserDetailsServiceImpl.java
I POPULATED THIS CUSTOM SiteUser object.
public SiteUser loadUserByUsername(String username)  {
        UserInfoVO userInfoVO = userDAO.getUserInfo(username);
        GrantedAuthority authority = new SimpleGrantedAuthority(userInfoVO.getRole());

        SiteUser siteUser = new SiteUser(userInfoVO.getUsername(), userInfoVO.getPassword(),
                Arrays.asList(authority), userInfoVO.getMobile());

        return siteUser;
}

3) AND IN VIEW I AM ACCESSING IT AS:
< a href="#" th:text="${#httpServletRequest.userPrincipal.principal.mobile}">


text:
Q: Distance from a 3d point to x-axis How do I find the formula for the shortest distance between points
(a , b, c) and the x-axis.
The answer I came up with was
sqrt((1-a)^2+b^2+c^2)

A: Why, of course it is $\sqrt{b^{2}+c^{2}}$. Translation alongside $x$ axis does not alter the distance.
Another method can be $|\{a,b,c\}\times\{1,0,0\}|$ which yield the same answer


text:
Q: How to use ng-repeat in AngularJS with using array? myApp.controller("myctrl", function($scope) {
    $scope.fullname = [
        { fname: 'Mohil', age: '25', city: 'San Jose', zip:'95112' },
        { fname: 'Darshit', age: '25', city: 'San Jose', zip:'95112'},
        { fname: 'Suchita', age: '25', city: 'Santa Clara', zip:'95182'}
    ]
}

A: Here is a Plunker which shows the same. All you need is,
HTML

app.js
$scope.fullname = [
    { fname: 'Mohil', age: '25', city: 'San Jose', zip:'95112' },
    { fname: 'Darshit', age: '25', city: 'San Jose', zip:'95112'},
    { fname: 'Suchita', age: '25', city: 'Santa Clara', zip:'95182'}
 ];

A: This is pretty much what repeaters were designed to do, and you'd reference the properties of the object the same way you would anywhere else in JavaScript. An example that's a little bit simpler than the other given:

    {{ person.fname }} is {{ person.age }} years old.

What part are you struggling with?


text:
Q: How to print python execution time with specific numbers from a random list to output both time and the random number generated? I have been trying to calculate Python's execution time with this code, I've got the time but I don't know which number is being used from the list to be measured any help with how to print it would be helpful and much appreciated
import time
import random

def algorithm(c):
    b = []
    for i in c:
        b.append(i*2)

def data():
    c=[]
    for x in range(10000000):
        c.append(random.randint(1,100000))
timer(c)

def timer(c):
    time_start = time.time()
    algorithm(c)
    time_end = time.time()
    time_taken = time_end - time_start
    print(time_taken)
data()

A: I believe your code is fine you just need to restructure the code a bit.
import time
import random
import timeit
randomNumbersAndTime = {}
def algorithm(c):

    b = []
    for i in c:
        b.append(i*2)

def data():
    c=[]
    setupCode = "pass"
    print ("Random Number , Time Taken to Generate\n")
    for x in range(10000000):
        codeToExecute = str(random.randint(1,100000))
        randomNumb = timeit.timeit(stmt=codeToExecute, setup=setupCode, number=1000000)
        randomNumbersAndTime[codeToExecute] =  randomNumb

        for randomNumber in randomNumbersAndTime.keys() :
            print ("{0} , {1} \n".format(randomNumber,randomNumbersAndTime[randomNumber]))

data()

this will give you the desired results.
This is a sample output :
Random Number , Time Taken to Generate

44806 , 0.433061423485

44806 , 0.433061423485

38079 , 0.44243301193

44806 , 0.433061423485

66713 , 0.435066187359

38079 , 0.44243301193

85426 , 0.422678350883

44806 , 0.433061423485

66713 , 0.435066187359

38079 , 0.44243301193

85426 , 0.422678350883

I hope i understood correctly .

A: You could leverage the timeit module:
import timeit

codeToExecute = """

def algorithm(c):
    b = []
    for i in c:
        b.append(i*2)

algorithm(range(500))
"""

#
setupCode = "pass"

meas =  timeit.timeit(stmt=codeToExecute, setup=setupCode, number=100000)

print(meas)

Output:
17.0021979809

This will execute the given function number times and print your time in seconds for it. You can use the setup to provide "data" or "imports" to your test that only has to be executed once and not on each run.

A: import time
import random
import timeit
randomNumbersAndTime = {}
def algorithm(c):

    b = []
    for i in c:
        b.append(i*2)

def data():
    c=[]
    setupCode = "pass"
    print ("Random Number , Time Taken to Generate\n")
    for x in range(10000000):
        codeToExecute = str(random.randint(1,100000))
        randomNumb = timeit.timeit(stmt=codeToExecute, setup=setupCode, number=1000000)
        randomNumbersAndTime[codeToExecute] =  randomNumb

        for randomNumber in randomNumbersAndTime.keys() :
            print ("{0} , {1} \n".format(randomNumber,randomNumbersAndTime[randomNumber]))

data()


text:
Q: NSConnection throwing 303 error after large data POST ERROR: Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn't be completed. (kCFErrorDomainCFNetwork error 303.)" UserInfo=0x1cd24f40 {NSErrorFailingURLKey=http://test.com/test/, NSErrorFailingURLStringKey=http://test.com/test/}

I can POST without an attachment and it wont break but as soon as I attach an image and POST it all other requests after that fail with 303 error. If I restart the App everything works again until I post another image.
To clarify the post works fine, the image is uploaded correctly and returns.


text:
Q: Dynamic Background images advice I am creating a site where users can upload there own background images, after upload they see each background they uploaded in a menu represented by a number, clicking on the number will in theory load in the new background, however I have noticed that does this calls in the view again as well (the view is already loaded from another function, is there a ways I can pass the data to the view without loading the view, can I do it with ajax? if so how?
My code currently
public function set_background() {
        $this->load->model('image_model');
        if($query = $this->image_model->get_background_by_id($this->uri->segments[3])) {
            if($query) {
                $data['new_background'] = $query;
            }
        }
        $this->load->view('template/background-select', $data);
    }

My Model:
public function get_background_by_id($background_id) {
    $this->db->select('background_name');
    $this->db->from('background');
    $this->db->where('background_id', $background_id);

    $query = $this->db->get();
    return $query->result_array();
}

My View

    <?php
        $count = 0;
            if(isset($special)) {
                foreach ($special as $row) {
                    $count ++;
                    print '
';
                        print "$count";
                    print '
';
                    if($count == 1) {
                        $background = $row['background_name'];
                    }

                }
            }
            if(isset($generic)) {
                foreach ($generic as $row) {
                    $count ++;
                    print '
';
                        print "$count";
                    print '
';
                    if($count == 1) {
                        $background = $row['background_name'];
                    }

                }
            }
            if(isset($user_background)) {
                foreach ($user_background as $row) {
                $count ++;
                    print '
';
                        print "$count";
                    print '
';
                    if($count == 1) {
                        $background = $row['background_name'];
                    }

                }
            }
        ?>

    <div id="wrapper" style=<?php echo"background:url(/media/uploads/backgrounds/".$background.");";?>>

The view gets loaded in originally here
public function index() {
    //  $this->output->enable_profiler(TRUE);
        $data = array();
        if($query = $this->category_model->get_all_online()) {
            $data['main_menu'] = $query;
        }
        $this->load->model('image_model');
        /*
        * Sort out the users backgrounds, basically do a check to see if there is a 'special' background
        * if there is not a 'special' background then IF the user is logged in and has a background of there
        * own show that one, if not show a generic one, if they are not logged in show a bang one
        */
        $image = array();
        if ($query = $this->image_model->get_special_backgrounds()) {
            $image['special'] = $query;
        } elseif(!isset($image['special']) && !isset($this->session->userdata['user_id'])) {
            if($query = $this->image_model->get_bang_background()) {
                $image['generic'] = $query;
            }
        }

        if(isset($this->session->userdata['user_id'])) {
            if($query = $this->image_model->get_user_backgrounds($this->session->userdata['user_id'])) {
                $image['user_background'] = $query;
            }
        }
        $data = array_merge($data, $image);
        $this->load->view('home/main_page.php', array_merge($data, $image));
    }

Hope some can help thanks

A: This may be too much 'out of the box' and not faithful enough to your code to be useful, but here goes:
Given the description of what the code is supposed to do, you could always have your PHP output the list of background images into a JavaScript snippet on the view (To pseudocode very roughly: ), then have javascript dynamically create your list of background-changing links client-side and each click just change the background image with JavaScript ( setting document.getElementById('wrapper')'s background image).
No Ajax necessary.
With that concept in mind, the simplest adjustment to your code I can concot in a hurry is this:
Instead of passing the IDs to the view, pass the URLs to the view (you'd have to adjust your querying accordingly, of course), and change:
""
   . $count
. ""

to something like
""
   . $count
. ""

The JavaScript function would be something like this:

Mind, the lot of that is still pseudocode, I doubt it'll run out of the box, my JS is very rusty, and this is meant to be an idea-share more than an outright fix. :) But I hope that it'll help you tackle your issue!
Is that kind of approach feasible for you?


text:
Q: Untangling entwined rigid chains in 3-space I am interested in exploring the degree of "tangledness"
of two rigid chains in space.
A polygonal chain is a simple (non-self-intersecting) path
of segments in
$\mathbb{R}^3$, viewed as a rigid body.  Think of it as a bent
wire in space.
Define a move of a chain as either a translation of the whole chain
in a fixed direction, or a rotation of the chain about a fixed point axis.
I.e., a translation moves each point $p$ of the chain along the path
$p(t) = p + t v$ for a fixed direction $v$ as $t$ varies from $0$ to $1$.
Say that two chains are separable if there is a sequence of moves
during which the chains never touch one another, and eventually
end up on opposite sides of a plane.

Q1.
  If each chain consists of $n$ segments, is there an upper bound as
  a function of $n$ (and independent of the geometry of the chains)
  on the number of moves needed to separate a separable pair?

Here is an example for which I believe $O(n)$ moves suffices to separate:

A more focussed question seeks difficult-to-untangle chains:

Q2.
  Is there a pair of chains that requires $\Omega(n^2)$ moves to separate?

My explorations have not led to an example that clearly requires
many moves to separate.  For example, I think this pair of spirals also only
needs $O(n)$ moves.

A simplification would also be of interest:

Q3.
  The same questions but with "moves" restricted to translations.

Thanks for ideas or pointers to relevant literature!

A: Hopefully, someone with better graphics-making ability than me will be able to post a picture of what I'm thinking of (or show that it doesn't work), but here's an attempt to show a pair that require $\Omega(n^2)$ moves.
For now, I'm restricting to translations only.
The first chain is the standard square wave form in the first figure above. For the second chain, take a square spiral on a plane perpendicular to the square wave. The spiral should have largest side length equal to the vertical height of the square wave (so the only way to move a vertical segment through is by pushing it through that one slot. Now, to force the wave to travel the spiral over and over, we add another piece to the second chain. It should be on a plane parallel to the plane of the spiral, and should be a modified square that is just too small for the wave to fit through. We modify the square on the pair of horizontal sides, adding a small detour to each edge, pushing out a small section and adding little extra space, so that the square wave can fit through only if it is centered on the square. Then, line the two up so the center of the square is lined up with the center of the spiral.
Then, the square wave starts going through the center of both parts of the second chain. In order to get each vertical segment through the spiral, we need to go around the spiral to the outside slot, but then to get that vertical segment through the square, we need to spiral back around to the middle.
Does that make sense?
If it does, it seems plausible to me that we'd be able to make 'rotation guards' to add to the second chain, that force us to do those motions even if rotations are allowed, but I'm not sure.

A: You can twist one wire into a linked double noose (with free endtips):

If, in turn, you link two of these "loops", the whole thing cannot be unentangled.


text:
Q: Firebase database query returning same data for all endpoints I've tried to create a firebase function for sending push notification to all the devices when a new post is inserted to the Firebase Realtime Database. My device tokens are under the profile-notifications endpoint. When I try to execute my function by inserting a new post to the database my response is something unexpected. I read the docs from https://firebase.google.com/docs/functions/ and https://firebase.google.com/docs/reference/admin/node/admin.database, but couldn't get much further. Here are my logs:

5:23:47.451 PM debug sendNewPostNotification
  Function execution took 1145 ms, finished with status: 'ok'

5:23:47.447 PM info sendNewPostNotification
  p:0: from server: {"r":4,"b":{"s":"ok","d":""}}

5:23:47.446 PM info sendNewPostNotification
  p:0: from server: {"r":3,"b":{"s":"ok","d":{}}}

5:23:47.444 PM info sendNewPostNotification
  Result: T { A: P { k: Sb { Ka: [Function: vb], ba: [Object] }, aa: P { k: [Object], aa: null, wb: [Object], Bb: '' }, wb: Zc { ld: [Object], ac: [Object] }, Bb: null }, V: R { u: Gd { app: [Object], L: [Object], Ua: [Object], Sc: null, ca: [Object], td: 1, Qa: [Object], va: [Object], qg: [Object], jc: [Object], ee: [Object], md: [Object], ia: [Object], Xa: [Object], cd: 1, fe: null, K: [Object] }, path: J { o: [Object], Y: 0 }, m: Df { xa: false, ka: false, Ib: false, na: false, Pb: false, oa: 0, kb: '', bc: null, xb: '', Zb: null, vb: '', g: Tc {} }, Kc: false, then: undefined, catch: undefined }, g: Tc {} }

5:23:47.439 PM info sendNewPostNotification
  p:0: {"r":4,"a":"n","b":{"p":"/profile-notifications"}}

5:23:47.439 PM info sendNewPostNotification
  p:0: Unlisten on /profile-notifications for default

5:23:47.438 PM info sendNewPostNotification
  p:0: Unlisten called for /profile-notifications default

5:23:47.437 PM info sendNewPostNotification
  event: /profile-notifications:value:{"jane_doe@gmail*com":{"deviceToken2":true},"john_doe@gmail*com":{"deviceToken1":true}}

5:23:47.430 PM info sendNewPostNotification
  p:0: handleServerMessage d {"p":"profile-notifications","d":{"jane_doe@gmail*com":{"deviceToken2":true},"john_doe@gmail*com":{"deviceToken1":true}}}

5:23:47.429 PM info sendNewPostNotification
  p:0: from server: {"r":2,"b":{"s":"ok","d":{"auth":null,"expires":1491492227}}}

5:23:47.429 PM info sendNewPostNotification
  c:0:0: Primary connection is healthy.

5:23:47.290 PM info sendNewPostNotification
  p:0: from server: {"r":1,"b":{"s":"ok","d":""}}

5:23:47.289 PM info sendNewPostNotification
  p:0: {"r":3,"a":"q","b":{"p":"/profile-notifications","h":""}}

5:23:47.289 PM info sendNewPostNotification
  p:0: Listen on /profile-notifications for default

5:23:47.288 PM info sendNewPostNotification
  p:0: {"r":2,"a":"gauth","b":{"cred":"ya29.El0lBHwnjCRAbk5q-vLmvHyYlxEv7zKP03kvxA7ktrRQgHpDAhDxM0bkUwfHUNaAJUxK4n7MsS1tTqXBF35NojUCPeMB5CJAhxuI8iTvXEWLvQQW-rbjUwKCIXF9oCQ"}}

5:23:47.287 PM info sendNewPostNotification
  p:0: {"r":1,"a":"s","b":{"c":{"sdk.admin_node.4-2-0":1}}}

5:23:47.287 PM info sendNewPostNotification
  p:0: reportStats {"c":{"sdk.admin_node.4-2-0":1}}

5:23:47.285 PM info sendNewPostNotification
  p:0: connection ready

5:23:47.285 PM info sendNewPostNotification
  c:0:0: Realtime connection established.

5:23:47.283 PM info sendNewPostNotification
  c:0:0:1 Websocket connected.

5:23:47.262 PM info sendNewPostNotification
  c:0:0:1 Websocket connecting to wss://s-usc1c-nss-135.firebaseio.com/.ws?v=5&ns=rally-zone

5:23:47.262 PM info sendNewPostNotification
  c:0:0:0 Websocket connection was disconnected.

5:23:47.259 PM info sendNewPostNotification
  c:0:0:0 WebSocket is being closed

5:23:47.259 PM info sendNewPostNotification
  c:0:0: Shutting down all connections

5:23:47.259 PM info sendNewPostNotification
  c:0:0: Reset packet received. New host: s-usc1c-nss-135.firebaseio.com

5:23:47.254 PM info sendNewPostNotification
  c:0:0:0 Websocket connected.

5:23:47.167 PM info sendNewPostNotification
  c:0:0:0 Websocket connecting to wss://rally-zone.firebaseio.com/.ws?v=5

5:23:47.165 PM info sendNewPostNotification
  c:0:0: Connection created

5:23:47.164 PM info sendNewPostNotification
  getToken() completed. Creating connection.

5:23:47.162 PM info sendNewPostNotification
  p:0: Auth token refreshed

5:23:47.101 PM info sendNewPostNotification
  p:0: Making a connection attempt

5:23:47.099 PM info sendNewPostNotification
  p:0: Listen called for /profile-notifications default

5:23:47.084 PM info sendNewPostNotification
  p:0: Browser went online.

5:23:46.307 PM debug sendNewPostNotification
  Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions

5:23:46.307 PM debug sendNewPostNotification
  Function execution started

So from what I can see, the response from the database is what I expect, but when I try to log my result, I get a long json with nothing close to what I was expecting. Could this be because I don't have a billing account? Can somebody help me on this? Here is my code as well.
const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendNewPostNotification = functions.database.ref('/posts/{postId}').onWrite(event => {
  const postId = event.params.postId;

  admin.database.enableLogging(true);
  return admin.database().ref("profile-notifications").once('value').then(result => {
    if (result) {
      console.log('Result: ', result); // "Stuff worked!"
    }
  }, err => {
    console.log('Error: ', err); // Error: "It broke"
  });
});

A: As jacobawenger pointed out in the comment, the problem was, that the result was a DataSnapshot, so I needed to add result.val() to get the value of it.


text:
Q: How to solve authorizer issue in Serverless framework 3? When I use Serverless framework 2, I defined authorizer like the below way.
sample:
  handler: sample.handler
  events:
    - http:
        path: sample
        method: get
        cors: true
        authorizer: verify-token

But It's not supported in Serverless framework 3. Now, I am getting the below error.
Incorrect type. Expected "Aws.HttpAuthorizer".yaml-schema: Serverless Framework Configuration

I looked at their deprecated doc But I don't find the solution. How can resolve this issue?

A: Seems like serverless expects you to define HttpAuthorizer instead of Lambda Authorizer for AWS REST API
Definitions of the settings are here: https://raw.githubusercontent.com/lalcebo/json-schema/master/serverless/reference.json
Rest API (V1) is actually more advanced. see:
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_ApiGateway.html or https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_ApiGatewayV2.html

A: Check the following documentation: https://serverless.com/framework/docs/providers/aws/events/apigateway#http-endpoints-with-custom-authorizers
The authorizer declaration must be completed in v3:
sample:
  handler: sample.handler
  events:
    - http:
        path: sample
        method: get
        cors: true
        authorizer:
          arn: xxx:xxx:verify-token
          managedExternally: false
          resultTtlInSeconds: 0
          identitySource: method.request.header.Authorization
          identityValidationExpression: someRegex


text:
Q: Chrome extension breaks when tab is changed I'm working on a chrome extension that simulates a keypress to submit a form. This works great as long as I stay on the page and do not switch tabs. When I switch tab the form doesn't get fill out the same.
What's strange is that it's the replaceCommentHtmlAndSetSender function that doesn't seem to propagate information properly on after one comment has been submitted and keypress event is fired. If I click back in to the page then the extension works.
I've tried viewing all events in the console using monitorEvents(window) and they seem to be the same. I've also tried adding a window.focus() event in replaceCommentHtmlAndSetSender without luck.
What events / differences could leaving the tab lead to this behavior?
var replaceCommentHtmlAndSetSender = function(reply_link, resp, id) {
  $(document.activeElement).sendkeys("txt")
  setTimeout(function() {
    var str = '<span data-text="true" data-comment-sender="true">txt >/span>'
    $(document.activeElement).replaceWith(str)
  })
  submitComment()
}

var submitComment = function() {
  var foundElementScript = document.createElement("script")
  foundElementScript.textContent = "foundElement()"
  document.head.appendChild(foundElementScript)
  foundElementScript.parentNode.removeChild(foundElementScript)
}

// this script is injected into the page
function foundElement(){
    found=document.querySelectorAll('[data-comment-sender="true"]')[0];
    found.setAttribute("data-comment-sender", "false");
    submitComment(found);
  }
}

function submitComment(element) {
  var event;

  if(document.createEvent) {
    event = document.createEvent("HTMLEvents");
    event.initEvent('keydown', true, true);
  } else {
    event = document.createEventObject();
    event.eventType = 'keydown';
  }

  event.eventName = 'keydown';
  event.keyCode = 13;
  event.which = 13;

  if(document.createEvent) {
    element.dispatchEvent(event);
  } else {
    element.fireEvent("on" + event.eventType, event);
  }
}


text:
Q: Trouble in adding a search widget in actionbar I would like to add a search function in the action bar following this as a guide but I still got these errors.
    07-02 13:36:05.175  21813-21813/com.example.fieldbookv2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.fieldbookv2, PID: 21813
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference
            at com.example.fieldbookv2.LoginActivity.onCreateOptionsMenu(LoginActivity.java:1621)
            at android.app.Activity.onCreatePanelMenu(Activity.java:2823)
            at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:277)
            at android.support.v7.internal.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:84)
            at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:273)
            at android.support.v7.app.AppCompatDelegateImplV7.preparePanel(AppCompatDelegateImplV7.java:1111)
            at android.support.v7.app.AppCompatDelegateImplV7.doInvalidatePanelMenu(AppCompatDelegateImplV7.java:1396)
            at android.support.v7.app.AppCompatDelegateImplV7.access$100(AppCompatDelegateImplV7.java:89)
            at android.support.v7.app.AppCompatDelegateImplV7$1.run(AppCompatDelegateImplV7.java:126)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

This is my main_activity_action.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:yourapp="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/tools">
<item android:id="@+id/action_search"
      android:title="Search"
      android:icon="@drawable/ic_search_white"
      app:showAsAction="ifRoom|collapseActionView"
      app:actionViewClass="android.widget.SearchView"/>
</menu>

searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
      android:label="@string/search"
      android:hint="@string/enter" />

LoginActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activity_main_actions, menu);

    // Associate searchable configuration with the SearchView
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search) .getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
  return super.onCreateOptionsMenu(menu);
}

and AndroidManifest.xml
<activity
    android:name="com.example.fieldbookv2.LoginActivity"
    android:label="@string/title_activity_login" >
        <meta-data
            android:name="android.app.default_searchable"
            android:value=".SearchResultsActivity" />
</activity>

Any idea why it says null reference?

A: Fixed the error. The main_actions_menu.xml should be like this
<?xml version="1.0" encoding="utf-8"?>
   <menu xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:app="http://schemas.android.com/apk/res-auto">
        <item android:id="@+id/action_search"
              android:title="Search"
              android:icon="@drawable/ic_search_white"
              app:showAsAction="ifRoom|collapseActionView"
              app:actionViewClass="android.widget.SearchView"/>
   </menu>

remove unnecessary tags and changed "yourapp" to "app since app is the one assigned.

A: Try This and I am Using EditText not actionbar:
 <EditText
        android:id="@+id/members_search"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:padding="10dp"
        android:ems="8"
        android:singleLine="true"
        android:background="@drawable/round_corner_edittext"
        android:hint="Search Box" />

In class:
members_search.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub
            adapter_members.getFilter().filter(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });


text:
Q: How to change the width of columns in a table that has merging cells looking around in forums but I can't find the solution for it.
I have a table as below. How can we change the width of columns 3rd (A, 2, 5) and 4th (B, 3, 4) so that they have same width value?
Thanks,
    \begin{table}[!htbp]
    \centering
    \caption{My caption}
    \label{my-label}
    \begin{tabular}{|c|c|c|c|c}
    \cline{1-4}
    \multicolumn{1}{|c|}{\multirow{2}{*}{Type of raw materials}} &   \multirow{2}{*}{Stock} & \multicolumn{2}{c|}{
        \begin{tabular}[c]{c} Demande quantity of raw material \\ to manufacture a product \end{tabular}}       &  \\ \cline{3-4}
    \multicolumn{1}{|c|}{} &           & A           & B           &  \\ \cline{1-4}
    I                      & 18        & 2           & 3           &  \\ \cline{1-4}
    II                     & $30$      & 5           & 4           &  \\ \cline{1-4}
    \end{tabular}
    \end{table}

A: You can take advantage of array package   to customize columns, you can for example define new column type for column 3 and 4 rather then c try with
>{\centering}m{2.5cm}.
\documentclass{article}
\usepackage{array}
\usepackage{multirow}
\begin{document}
\begin{table}[!htbp]
    \centering
    \caption{My caption}
    \label{my-label}
    \begin{tabular}{|c|c|>{\centering}m{2.5cm}|>{\centering}m{2.5cm}|c}
    \cline{1-4}
    \multicolumn{1}{|c|}{\multirow{2}{*}{Type of raw materials}} &   \multirow{2}{*}{Stock} & \multicolumn{2}{c|}{
        \begin{tabular}[c]{c} Demande quantity of raw material \\ to manufacture a product \end{tabular}}       &  \\ \cline{3-4}
    \multicolumn{1}{|c|}{} &           & A           & B           &  \\ \cline{1-4}
    I                      & 18        & 2           & 3           &  \\ \cline{1-4}
    II                     & $30$      & 5           & 4           &  \\ \cline{1-4}
    \end{tabular}
    \end{table}
\end{document}

Or you can define new column type with
\newcolumntype{C}{>{\centering}m{2.5cm}}

Which can be applied for column 3 and 4
\begin{tabular}{|c|c|C|C|c}

Result


text:
Q: Как сделать анимацию картинки в SwiftUI? Всем привет, помогите разобраться, как сделать чтоб при нажатии на кнопку сверху вниз падала картинка, была разных размеров (например: 64х64, 128х128) и падала не только по центру, а в разных местах экрана?
Также, хотелось бы узнать, как сделать, чтоб допустим при апгрейде за 100 баллов, счетчик считал сам +1, +10, +100 и так далее каждую секунду, ну и соответственно автоанимация падающей картинки.
Хочу сделать типа Cookie Clicker для себя, но пока только учусь.
@State var Count: Int = 0

var body: some View {
    ZStack {

        VStack {
            Text("\(Count) Cookies")

        Button(action: {
            self.Count += 1
        }) {
            Image("cookie").renderingMode(.original)
            .resizable()
            .frame(width: 128, height: 128)
            }
        }
    }
}

A: UIView animate
animate
Посмотрите эти ссылки. Они дадут вам базу и вы сможете переделать так как вам нужно. В этом посте слишком много вопрос. Вам лучше разделить их на несколько постов.

A: Нашел способ сделать анимацию уменьшения кнопки при нажатии, а как сделать чтоб после уменьшения она вернулась в исходное состояние?
VStack {
    Text("\(Count) Cookies")

    Button(action: {
        withAnimation(.easeInOut(duration: 1)) {
            self.Count += 1
            self.buttonScale = 0.5
        }
    }) {
        Image("cookie").renderingMode(.original)
                .resizable()
                .frame(width: 128, height: 128)
                .shadow(radius: 3)
                .scaleEffect(self.buttonScale)
    }
}


text:
Q: How is the Riemann-Siegel Z function evaluated in Mathematica? How is the Riemann-Siegel Z function evaluated in Mathematica?
Is it calculated using the first so many terms of its power series or by other means?


text:
Q: Validating an attribute inside JsonArray using restassured I have a json like below
{
"hasErrorResponse": "false",
"responseObject": [{
    "success": true,
    "errorMessage": null,
    "availablity": "YES",
    "errorCode": null,
    "availableQtys": 1234,
    "prId": "451667"
}]

}
Now using RestAssured if I do
response.then().assertThat().body("responseObject.prId", equalTo("451667"));

It's failing because it says Expected: 451667 but Got: [451667]
I guess it's because it's getting the prId attribute as an ArrayList and not as String. How do I go about validating this sceanrio?

A: hasItems matcher works to validate anything inside collection


text:
Q: External Display not displaying full OSD function tech said solution is HDMI Adapter? I would like to start off saying I have 0 tech knowledge and this staying at home period has forced me to learn alot!
So recently I bought a new 4k monitor to upgrade my work at home experience.  Previously, an employee at a store helped my set up my Macbook Air (13inch 2017) to an external display monitor via a cable that one end connects to thunderbolt and the other to DP.  Everything worked good.
Then I bought this new monitor that has more options such as blue screen filter, change contrast etc etc (https://www.bhphotovideo.com/lit_files/152620.pdf).  Following what I had done before I connected the two but discovered I am missing the full display option to change this blue light filter and others.  Google didn't give me an answer so I called the tech department of the store and they said this (https://www.bestbuy.ca/en-ca/product/insignia-insignia-mini-displayport-to-hdmi-adapter-ns-pd94592-c-ns-pd94592-c/10294299) is the magic solution to everything?
Is this true?  I know next to nothing about DP and HDMI and my question is as I only have 1 thunderbold if I buy this adapter does it mean there is no need then for my current thunderbolt to DP cable?
If what the store employee said is true would someone be so kind to link/explain why this would solve my problem, and if not what is the solution to my problem.
Thank you and have a great day :)

A: Your cable has nothing to do with the features of the monitor.   What the store employee told you was utter nonsense.
It simply can't influence the OSD functionality of the monitor as there's no logic in a cable that will enable it.  What does influence the OSD is the "mode" that the display is in and that's dependent on how you have things configured.
In fact, speaking of configurations, the (cable) configuration you had previously, going from mini DisplayPort to Display port (mDP to DP) was better than going from mDP to HDMI as there's no conversion of the signal.  You'll get a more stable and reliable connection.
That aside, the monitor's features are dependent on what "mode" you have it in.
For instance on page 3-2 it states the following:

*

*In the Racing Mode, the Saturation, SkinTone, Sharpness, and ASCR functions are not user-configurable.

*In the sRGB, the Saturation, Color Temp., SkinTone, Sharpness, Brightness, Contrast and ASCR functions are not user-configurable.

Then on page 3-3 specifically about the Blue Light Filter it states

When Blue Light Filter is activated,the default settings of Racing Mode will be automatically imported.

Based on what you're describing, that "blue light filter" may be one of the options that get disabled when selecting a certain mode.


text:
Q: Email configuration for post-build in Jenkins: Where can I find the Server name and port number? I need the following information to set up automatic-email notifications in Jenkins using my office email, when I run selenium test scripts in Jenkins .
1. SMTP server name
2. SMTP server port number
Where can I find the Server name and port number.
Help would be appreciated.
Thanks


text:
Q: How to solve this error (Uncaught TypeError: Cannot read property 'aDataSort' of undefined)? How can i solve this problem, this is my code:

No

Nomor Permohonan

Tanggal Permohonan

Nama

Tanggal Lahir

Status

And i got this error:

Uncaught TypeError: Cannot read property 'aDataSort' of undefined

I don't know what is the problem exactly, help me please. Thanks.

A: if you use datatable maybe you can set like this:
in controller you make getData function
public function getData(Request $request){
    $pemohon = YourModel::select('your_coloum_in_database.*');
    return Datatables::of($pemohon)
                    ->make(true);
}

in you view you can call like this:


text:
Q: Update a field in mysql table on click I have a binary field in a mysql database that gets updated by a button on an html form.
So, I click the button for every row and it changes the mysql value for each of the rows…
The problem is that it has a delay, when I click on one button of a certain row it only gets updated when I click on the next. But if I click on that button and refresh the page it gets changed.
I've look into ways of updating the page, but I just can't get it to work...
<form action='index.php' method='POST'>
<input type=hidden name='keyword2' value='$keyword'>
<input type='submit' value = 'SELECT' >
</form>";

<?php

j($_POST['keyword2']);
function j($q){
    $n = "SELECT `CÔR` FROM `keywords` WHERE `keyword`='$q'";
    $b = mysql_query ($n);
    $row = mysql_fetch_array($b);
    echo $row['CÔR'];
    $t = $row['CÔR'];

    if ($t == 1) {
        $m = "UPDATE `keywords` SET `CÔR`=0 WHERE `keyword`='$q'";
        mysql_query ($m);
    }

    if ($t == 0) {
        $l = "UPDATE `keywords` SET `CÔR`=1 WHERE `keyword`='$q'";
        mysql_query ($l);
    }


text:
Q: Update google sheet from python script I'm trying to have a python script update a google sheets. The script scrapes a dynamically loaded webpage and retrieves some values.
Because the site loads dynamically, I can't use google scripts. But if I wan't the python script to access the google sheet, I need a google service account. This requires a credit card, but I don't have access to a non-prepaid one.
I could also host the python API on gae, but this also requires a credit card.
Any ideas for how I could work around this?

A: I believe your goal as follows.

*

*You want to put the values to Google Spreadsheet using python.

In order to achieve your goal, how about the following patterns?
1. Access to Google Spreadsheet using Sheets API with OAuth2.
When Sheets API is used, the values can be put to the Google Spreadsheet.
In this case, you can see the sample script at Quickstart. And, I think that in your situation, the use of Google Sheets API is free of charge. If you want to increase the quota of Sheets API, please check it at https://developers.google.com/sheets/api/limits.
2. Access to Google Spreadsheet using Sheets API with Service account.
When Sheets API is used, the values can be put to the Google Spreadsheet.
In this case, you can see the sample script from these threads. And also, I think that in your situation, the use of Google Sheets API is free of charge.
3. Access to Google Spreadsheet using Web Apps created by Google Apps Script.
When Google Apps Script is used, the values can be put to the Google Spreadsheet. And, in this method, Google Apps Script is used as the wrapper.
At first, create Web Apps using Google Apps Script, and your python script accesses to the Web Apps by sending the values with requests module. By this, at the Web Apps side, the retrieved values are put to Google Spreadsheet using Google Apps Script. The Web Apps is used as the wrapper API for using Google Spreadsheet. And also, in this case, you can also access to the Web Apps with and without using the access token. In this method, I think that your python script is simple modification.
In this case, you can see the detail information about Web Apps at Web Apps and Taking advantage of Web Apps with Google Apps Script.


text:
Q: python3/email: parsing a list of email addresses with embedded commas? I know how to use email.utils.parseaddr() to parse an email address. However, I want to parse a list of multiple email addresses, such as the address portion of this header:
Cc: "abc" <foo@bar.com>, "www, xxyyzz" <something@else.com>

In general, I know I can split on a regex like \s*,\s* to get the individual addresses, but in my example, the name portion of one of the addresses contains a comma, and this regex therefore will split the header incorrectly.
I know how to manually write state-machine-based code to properly split that address into pieces, and I also know how to code a complicated regex that would match each email address. I'm not asking for help in writing such code. Rather, I'm wondering if there are any existing python modules which I can use to properly split this email address list, so I don't have to "re-invent the wheel".
Thank you in advance.

A: Borrowing the answer from this question How do you extract multiple email addresses from an RFC 2822 mail header in python?
msg = 'Cc: "abc" <foo@bar.com>, "www, xxyyzz" <something@else.com>'

import email.utils

print(email.utils.getaddresses([msg]))

produces:
[('abc', 'foo@bar.com'), ('www, xxyyzz', 'something@else.com')]

A: This is not elegant in the least and I'm sure someone will come along and improve upon this. However, this works for me and hopefully gives you an idea of how this can be done.
The split method is what you're looking for here I believe. In the simplest terms, you take your string and choose a character to split upon. This will separate the string into a list that you can iterate over assuming the split key selection is found. If it's not found then the string is a one element list.
emails = 'Cc: "abc" <foo@bar.com>, "www, xxyyzz" <something@else.com>'
emails
Out[37]:
'Cc: "abc" <foo@bar.com>, "www, xxyyzz" <something@else.com>'
In [38]:
emails = emails.split(' ')
new_emails = []
for e in emails:
    if '@' in e:
        new_email = e.replace('<', '')
        new_email = new_email.replace('>', '')
        new_email = new_email.replace(',', '')
        new_emails.append(new_email)
print(new_emails)
['foo@bar.com', 'something@else.com']

If you want to use regex to do this, someone smarter than I will have to help.

A: I know I can do something like the following, but again, I'm hoping that there is already an existing package which could do this for me ...
#!/usr/bin/python3

import email.utils

def getaddrs(text):
    def _yieldaddrs(text):
        inquote = False
        curaddr = ''
        for x in text:
            if x == '"':
                inquote = not inquote
                curaddr += x
            elif x == ',':
                if inquote:
                    curaddr += x
                else:
                    yield(curaddr)
                    curaddr = ''
            else:
                curaddr += x
        if curaddr:
            yield(curaddr)
    return [email.utils.parseaddr(x) for x in _yieldaddrs(text)]

addrstring = '"abc" <foo@bar.com>, "www, xxyyzz" <something@else.com>'
print('{}'.format(getaddrs(addrstring)))
# Prints this ...
#   [('abc', 'foo@bar.com'), ('www, xxyyzz', 'something@else.com')]


text:
Q: REACT NATIVE / my child component don't re-render despite props change I'm facing an issue on the code below (sandbox here https://codesandbox.io/s/silly-rubin-9ghc5?fontsize=14&hidenavigation=1&theme=dark ), the props change but doesn't refresh the component accordingly.
I would like to be able to keep track of different votes / options within a state in the parent node, hence i'm using an array where the index is the index of my option and the value the number of votes.
import { useEffect, useState } from "react";
import { Button, View } from "react-native";

import "./styles.css";

const myList = [
  {
    cid: 0,
    cTx: "Paris"
  },
  {
    cid: 1,
    cTx: "Lyon"
  },
  {
    cid: 2,
    cTx: "Marseille"
  },
  {
    cid: 3,
    cTx: "Valence"
  },
  {
    cid: 4,
    cTx: "Bordeaux"
  }
];

interface mTprop {
  myItemId: number;
  myItemTxt: string;
  myItemSt: number[];
  myItemClck: () => void;
}

const MyItem = (props: mTprop) => {
  const onBtPress = () => {
    props.myItemClck();
    console.log(props.myItemSt);
  };

  return (
    <View
      style={{
        flexDirection: "row"
      }}
    >

{props.myItemTxt}

      <Button onPress={onBtPress} title="Learn More" />

{props.myItemSt[props.myItemId]}

    </View>
  );
};

export default function App() {
  const [selectedOpt, setSelectedOpts] = useState(new Array(0));

  useEffect(() => {
    setSelectedOpts(new Array(myList.length).fill(0));
  }, []);

  const updateOptions = (ix: number) => {
    ++selectedOpt[ix];
    setSelectedOpts(selectedOpt);
  };

  return (

Hello CodeSandbox

Start editing to see some magic happen!

      {myList.map((itm, ix) => {
        return (
          <MyItem
            key={ix}
            myItemId={ix}
            myItemTxt={itm.cTx}
            myItemSt={selectedOpt}
            myItemClck={() => updateOptions(ix)}
          />
        );
      })}

  );
}

Thanks a million in advance !
Please let me know if further info is needed

A: In order to change data in list. You need to do this
 const updateOptions = (ix: number) => {
    const newList = selectedOpt.map((m, i) => {
      if (i === ix) {
        return m + 1;
      }
      return m;
    });
    setSelectedOpts(newList);
  };


text:
Q: MacBook Air 7.1 (early 2015) freezes for five to ten minutes after login Recently, my MacBook Air 7.1 (early 2015) has been very slow on startup. That is, the system boots quickly, and then I'm able to login, and the desktop begins to load. Initially, I have control and can open one or two applications, but after about thirty seconds, the desktop freezes. Typically, this lasts around five to ten minutes.
I checked login items under the Users & Groups menu, and there were only two applications listed. I disabled them, but the problem persists.
I was able to view the system.log before the slowdown began, and the last entry with which the log was populated was
(com.apple.imfoundation.IMRemoteURLConnectionAgent): Unknown key for integer: _DirtyJetsamMemoryLimit

Later, once I regained control, I could see that this entry appears in the log a large number of times, about ten to fifty1 more times during the next ten seconds, and then not again until about five minutes later, when I regain control. My understanding is that this is just recording the fact that the system is running out of RAM, and has to being paging, which would be consistent with the slowdown / loss of control.
The questions are two. First:

*

*What is causing the system to hang and how do I fix it?

However, I appreciate that that's a difficult question to answer, and, in any case, I would really prefer to know:

*How do I figure out what's going wrong?

That is, what other steps do I need to take to understand what's causing the slowdown? It would be nice if I could use htop or something similar to log memory usage during that period, but I'm not sure how to start it running in time. Similarly, I have tried to look through system.log during the same period, including using
cat /private/var/system.log | cut -d: -f4- | uniq -c

to identify the most common messages, but nothing, other than _DirtyJetsamMemoryLimit, jumps out.

1: Since repeat messages are logged as ---last message repeated N times--- it's hard to count exactly.

A: This is going back to the basics.
Try a safe boot.
    Shutdown your machine.  Hold down the shift key.  Poweron.  The boot up will take longer than normal because the filesystem on the startup drive is being checked and repaired as needed.   All about safe mode including what features and apps safe boot leaves out.  Safe boot uses a software driver instead of using your machines video hardware.
  [http://support.apple.com/kb/ht1455][1]

Secondly,
I'd run etrecheck. Your proprietary stuff gets filtered.
-- Download etrecheck.  The download link is at the bottom of the screen.
http://etrecheck.com/
-- Run etrecheck.   The first five runs are free.
-- How to install, run and report output for the EtreCheck Application
https://discussions.apple.com/docs/DOC-250000632
-- Explanation of EtreCheck  output by etresoft, the author
https://discussions.apple.com/docs/DOC-11591
How to report etrecheck data.
When the report is done, click on the export icon.
click on "Copy report" to copy to the clipboard
Get back in your web browser and access your discussion. Paste you etrecheck output into the code {} block.
which results in...
Robert


text:
Q: PCI card reader stopped working after upgrading to Ubuntu 14.10 Here's my configuration:
sudo lspci
00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor DRAM Controller (rev 06)
00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)
00:03.0 Audio device: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor HD Audio Controller (rev 06)
00:14.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB xHCI (rev 05)
00:16.0 Communication controller: Intel Corporation 8 Series/C220 Series Chipset Family MEI Controller #1 (rev 04)
00:1a.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #2 (rev 05)
00:1b.0 Audio device: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller (rev 05)
00:1c.0 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #3 (rev d5)
00:1c.2 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #1 (rev d5)
00:1c.3 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #4 (rev d5)
00:1c.6 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #7 (rev d5)
00:1d.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #1 (rev 05)
00:1f.0 ISA bridge: Intel Corporation HM87 Express LPC Controller (rev 05)
00:1f.2 SATA controller: Intel Corporation 8 Series/C220 Series Chipset Family 6-port SATA Controller 1 [AHCI mode] (rev 05)
00:1f.3 SMBus: Intel Corporation 8 Series/C220 Series Chipset Family SMBus Controller (rev 05)
01:00.0 Network controller: Broadcom Corporation BCM4352 802.11ac Wireless Network Adapter (rev 03)
03:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS5227 PCI Express Card Reader (rev 01)
09:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 0c)

sudo file -s /dev/mmcblk0p1
/dev/mmcblk0p1: DOS/MBR boot sector

Every time I try to mount it manually I get the following:
sudo mount  /dev/mmcblk0p1 /media/vova/
mount: /dev/mmcblk0p1: more filesystems detected. This should not happen,
       use -t <type> to explicitly specify the filesystem type or
       use wipefs(8) to clean up the device.

Can anyone help out? I can't figure this out.

A: Try
sudo mount -t exfat /dev/mmcblk0p1 /media/vova/

as suggested by Google, when encountering similar error messages.
Better still, add a suitable line to /etc/fstab. Something like this?
UUID="insert uuid here"   /media/vova  exfat    rw,user,noauto  0       0

You can obtain the UUID by checking for the device's UUID withblkid with the device attached to your computer. Doing this saves you from having to check which device file represents your reader.
Automating the mount would be an even better idea. I have used usbmount in the past. This may work with exfat if you add exfat to the following line in your
/etc/usbmount/usbmount.conf.
FILESYSTEMS="vfat ext2 ext3 ext4 hfsplus"

which is the default, I think. I have "ntfs" added in mine. Change
from VERBOSE=no to VERBOSE=yes in /etc/usbmount/usbmount.conf and test by plugging in. Look at /var/log/messages and /var/log/syslog for output.