text:
Q: Is .Net memory hungry? A friend of mine told me that .NET Framework is memory hungry and he gave me an example that if I make an application (in .NET web forms) which will take 20 mb of your RAM, it will be actually wasting 1.5 MB
This means that it will leak 15 mb for 200 MB application which is way too much.
Is it true? Can anyone provide me any links which describes it?

A: I doubt that there really is a direct answer to this.
There are two problems to consider. First, with garbage collection, you generally get a fairly direct trade-off between speed and memory consumption. If you run the garbage collector more often, you reduce memory consumption at the expense of using more CPU time. Running the garbage collector less often improves speed at the expense of consuming more memory. Testing has shown that garbage collection can provide the same speed as manual memory management, at the expense of consuming roughly six times as much memory1.
The second basic point is generality versus specificity. On one hand, the people working on .NET are (beyond a doubt) very smart, and work very hard at making it work well. For the most part, they succeed. On the other hand, .NET gets used for a wide variety of purposes across an even wider range of hardware. That has a large effect on the design goal. In particular, the emphasis is almost entirely to avoid really bad performance under any conditions, not necessarily to provide great performance under your conditions.
As far as the specific allegation of 20 MB leading to 1.5 MB of "waste", I doubt that anybody can really address it directly -- it's impossible to even be sure what he was trying to say, not to mention trying to say anything about whether (and if to so what degree and/or under what circumstances) it might be accurate. It's certainly not true that memory usage is necessarily linear, so even if 20 MB of use lead to 1.5 MB of waste, that wouldn't imply 15 MB of waste for 200 MB of use. Depending on what he was talking about, it might remain at 1.5 MB regardless, or it might scale sub-linearly (or, possibly, super-linearly).

1Those specific tests were run with Java, but .NET is sufficiently similar that while the number might change a little, I wouldn't expect the difference to be huge. For that matter, I know of at least three different garbage collection methods used in different JVMs, so the exact number probably varies for different Java implementations.

A: Although most of my experience is with non-GC programming, I don't really believe either GC or non-GC is universally superior.
What I will say, however, is that trading memory overheads for speed, or for other resources, is quite common - even for non-GC languages.
Some examples...
A naive resizeable array grows by fixed increments. When inserting a large number of items, this results in O(n^2) performance because of the O(n) reallocate-and-copy operations on the array. A faster alternative is "array doubling" - more accurately, growing by a fixed factor. This gives amortized O(n) performance for a long sequence of inserts. The cost is that, instead of having a fixed maximum memory overhead, the maximum overhead is proportional to the number of items in the array.
EDIT - silly mistake above - array gives amortized O(1) for each insert, but strictly O(n) for a series of n inserts, due to how "amortized" is defined.
Array doubling is not only applied to simple resizable vector/array types, but also to types that have resizeable arrays underlying them - the most obvious being hash tables. Without this proportional memory overhead, the amortised O(1) insert/delete times for resizeable hashtables cannot be achieved. This applies irrespective of whether garbage collection is used.
Similarly, with B trees and B+ trees (commonly used for database indexes), each node is guaranteed to be at least half full - with the exception of the root, which may even be completely empty. These data structures are more likely used on disk than in main memory, but either way they have an expected memory/storage overhead that grows in proportion with the number of items.
With garbage collection algorithms, there are also trade-offs between memory and performance. This can be seen as an extra layer on top of the data structures in some cases, adding an extra layer of waste, but this isn't a general rule - I don't know what weight to put on each two cases.
In unmanaged languages, you need some other mechanism to keep track of memory that needs to be freed anyway. Sometimes, that comes pretty much for free in the data structure itself - e.g. in a binary tree, you need the child links irrespective of whether you use them for a delete-all-items operation or not. But other times that too can involve a tradeoff between extra memory overheads and performance. For example, "memory pools" are often used to trade memory overheads (the whole pool remains allocated, even though relatively few items within the pool are in use at any particular time) for a faster and more convenient free of all items at once.
My basic point is, I guess, a variation on "avoid premature optimisation". Don't worry too much about memory overheads unless you know they will cause a problem. And be aware that when you reduce memory overheads, you are likely to pay with increases to other overheads - so do before and after measurements of more than just memory usage.
It may seem like it's too late to think of changing language when you find a problem with garbage collection memory overheads, but there are things you can do without re-writing your whole system. For example, when coding in C# for .NET, one option is to reimplement a critical data structure using some unmanaged C++.

A: .net utilizes a managed heap that exists in conjugation with the os memory functions built into windows.  While the initial start up cost of the runtime can make the system look very memory intensive for large scale programs I have found it to not be that significant.   You need to remember that the managed memory access is tested by thousands of developers every year and on average will beat your best efforts at memory management for any program of significant scope.


text:
Q: Django REST framework: AttributeError: 'User' object has no attribute 'books' http://127.0.0.1:8000/app_restFramework/users/ , return text

AttributeError at /app_restFramework/users/
  'User' object has no attribute 'books'

models.py
class User(models.Model):
    username = models.CharField(max_length=100)

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    publisher = models.CharField(max_length=100)
    time = models.CharField(max_length=100)
    owner = models.ManyToManyField(User)

serializers.py
from app_restFramework.models import Book,User
class UserSerializer(serializers.ModelSerializer):
    books = serializers.PrimaryKeyRelatedField(many = True, read_only = True)

    class Meta:
        model = User
        fields = ('id', 'username', 'books')

views.py
class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

urls.py
url(r'^app_restFramework/users/$', app_restFramework.views.UserList.as_view() ),

A: You have not specified the related_name in the ManyToManyField. By default it will be book_set. Therefore you can do:
book_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

If you want to use books in the serializers, you can do this in the Book model:
owner = models.ManyToManyField(User, related_name="books")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex matching string formatted as @ or # followed dot-separated string containing no spaces I am looking for a JavaScript regex that matches a string starting with a # or @ followed by a string containing only one dot / period (full stop) and no spaces. Note that there must be characters on either side of the dot, and the strings may contain multiple _ characters.  So,
"@xxxx.yyyyyy" = match
"@x.yyyyy" = match
"a@xxxxx.yy" = fail because first character not @ or #
"@@xxxxx.yy" = fail because it contains 2 @ characters
"@#xxxxx.yy" = fail because it contains 2 @ of the characters @ or # and should contain only 1
"@xxxxx.yy#" = fail same reason
"  @xx yyyyyy" = fail because it contains a space.
"#x_x.y_y" = pass
"@_._" = fail because no a-z chars are present
"@_.y" = fail because no a-z chars present on left of dot.

I believe the use case here is quite common. I am seeking to establish whether a string contains a valid reference to a variable of the form @aaa_aaa_aaaaa.bb_b_bb, where the 'a' portion represents a query and the 'b' portion represents a column. The @ is a leading trigger to indicate the intention that the string is a variable. The '#' case is the same general intent except the '#' signifies a localisation string with the 'a' portion being a topic and the 'b' potion being the specific string.
I am by no means a regex guru and have been caught out before using online generators and misunderstanding some of the nuances. So far I have this but I'm struggling to limit the period to only one and I do not know how to apply a negative whitespace rule.
^(@|#)[a-zA-Z.]*

Any help greatly appreciated.
EDITS:

*

*Thanks for pointing out I should have said 'starts with # or @'

*The dot IS mandatory. Also at least one character either side of the dot.

*A further use case has arisen: - there may also be multiple '_' (underscore) characters on both sides (either or both) of the dot. Example: '@aa_aaa_a.bb_bb'.
Thank you for the responses - I think all would have worked but I can only mark one as the correct answer so I have picked one and given the others an upvote.

A: This regex does the job:
/^[@#][a-z]+(?:\.[a-z]+)?$/i

with optionnal dot.
If the dot is mandatory, use:
/^[@#][a-z]+\.[a-z]+$/i

var test = [
    "@xxxx.yyyyyy",
    "@x.yyyyy",
    "a@xxxxx.yy",
    "@@xxxxx.yy",
    "@#xxxxx.yy",
    "@xxxxx.yy#",
    "   @xx yyyyyy",
];
console.log(test.map(function (a) {
  return a + ' :' + a.match(/^[@#][a-z]+(?:\.[a-z]+)?$/i);
}));

A: Your question states a string starting with a * or @ but I assume that is a # instead.
Another option is to match 0+ times the character class using * in front of the dot and follow by reating 1+ times the character class after the dot:
^[@#][a-zA-Z]*\.[a-zA-Z]+$

*

*^ Start of string

*[@#] Match @ or #

*[a-zA-Z]* Match 0+ times a char a-zA-Z

*\.[a-zA-Z]+ Match a literal dot and 1+ times a-zA-Z

*$ End of string

Regex demo

const pattern = /^[@#][a-z]*\.[a-z]+$/i;
["@xxxx.yyyyyy",
  "@x.yyyyy",
  "@x.yyyyy.",
  "a@xxxxx.yy",
  "@@xxxxx.yy",
  "@#xxxxx.yy",
  "@xxxxx.yy#",
  "#xxxx.yyyyyy",
  "#x.yyyyy",
  "#x.yyyyy.",
  "##xxxxx.yy",
  "##xxxxx.yy",
  "##xxxxx.yy",
  "#xxxxx.yy#"
].forEach(s => console.log(s + " --> " + pattern.test(s)));

A: this is what you need, it will check for having @ or # at the beggining and then it will match for a-zA-Z OR a . character and continue checking for letters.

var test = [
  "@xxxx.yyyyyy",
  "@x.yyyyy",
  "a@xxxxx.yy",
  "@@xxxxx.yy",
  "@#xxxxx.yy",
  "@xxxxx.yy#",
  "   @xx yyyyyy",
];

const regex = new RegExp(/^[@#]([a-zA-Z]|\.)*$/i);

console.log(test.map(entry => `${entry}:  ${regex.test(entry)}`));

A: Based on your requirements, you can use this regex,
^[@#][^@.#\s]+\.[^@.#\s]+$

Demo

const list = ['@xxxx.yyyyyy','@x.yyyyy','a@xxxxx.yy','@@xxxxx.yy','@#xxxxx.yy','@xxxxx.yy#','@xx yyyyyy']

list.forEach(s => {
console.log(s, ' --> ', /^[@#][^@.#\s]+\.[^@.#\s]+$/.test(s))
})

Also, in case you want to be restrictive about the allowed characters in your dot separated string, you can use [a-zA-Z] instead of a generic character set that I have used which is [^@.#\s] and in that case your regex becomes,
^[@#][a-zA-Z]+\.[a-zA-Z]+$

Explanation:
^ - Start of string
[@#] - Match either @ or # as the first character
[a-zA-Z]+ - Match at least one letter to make it a DOT SEPARATED string
\. - Match a literal dot
[a-zA-Z]+ - Again match at least one letter to make it a DOT SEPARATED string
$ - End of string
Demo2

const list = ['@xxxx.yyyyyy','@x.yyyyy','a@xxxxx.yy','@@xxxxx.yy','@#xxxxx.yy','@xxxxx.yy#','@xx yyyyyy']

list.forEach(s => {
console.log(s, ' --> ', /^[@#][a-zA-Z]+\.[a-zA-Z]+$/.test(s))
})

Edit:
For allowing _ in addition to alphabets in dot separated string, just include _ within those square brackets and the regex you can use is this,
^[@#][a-zA-Z_]+\.[a-zA-Z_]+$

Demo with underscores included


text:
Q: Bundling multiple existing projects I currently have two existing projects, one Node.js and one React. Both in their own folders with their own package.json and node_modules.
I wanted to create a third folder for Electron and bundle the existing projects together. Is this possible or do I need to merge all three projects together and use a single package.json and node_modules?

A: From my own experience with similar tasks: I'd find a good boilerplate project for that setup, clone the repo and install it. Then I'd study how they did it on the boilerplate and try to structure my own code in a similar way.
The reason for me doing it like that: the boilerplate guys are the true experts and I'm not. They know what they're doing and so their result would be good for me too.
A good candidate would be electron-react-boilerplate.


text:
Q: How to play sound in Qt5 (Qt4 migration)? In Qt4 I used to use
QT += multimedia phonon
//...
#include <Phonon>
//...
        Phonon::MediaObject *mediaObject = Phonon::createPlayer(Phonon::NoCategory, Phonon::MediaSource(QUrl("./assets/audio/window_appear.wav")));
        //   "\"" + Qdir().absolutePath() + "/audio/click.wav" + "\""
        mediaObject->play();

and it all worked fine. But now Phonon is not supported in Qt 5. So I wonder - how can I play media files such as sound in Qt5?
Using WebKit? (It is entirely possible but looks kind of bad from many points of view)

A: The Qt developers started to reduce their efforts on Phonon integration already during the later versions of Qt4, focussing on the Qt Multimedia and Qt Mobility modules instead. Though they did still support Phonon.
As you say, as of Qt5, Phonon is no longer supported. So look into Qt Multimedia instead, especially QAudioOutput.
As listed within their documentation under "Detailed Description", playing an audio file looks something like this:
QFile inputFile;     // class member.
QAudioOutput* audio; // class member.
inputFile.setFileName("/tmp/test.raw");
inputFile.open(QIODevice::ReadOnly);

QAudioFormat format;
// Set up the format, eg.
format.setFrequency(8000);
format.setChannels(1);
format.setSampleSize(8);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);

QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
if (!info.isFormatSupported(format)) {
    qWarning()<<"raw audio format not supported by backend, cannot play audio.";
    return;
}

audio = new QAudioOutput(format, this);

connect(audio,SIGNAL(stateChanged(QAudio::State)),SLOT(finishedPlaying(QAudio::State)));
 audio->start(&inputFile);


text:
Q: Can't connect to router
Possible Duplicate:
How to reset a Fritz!Box DSL router to factory settings?

I need to change the setting of router Fritz Box. The setting were set by another person. I can't connect to router using cable, may be standard port or address were changed. So the only option is to switch to factory settings. Usually there is a button which deletes all the settings. I read the documentation and they tell to call the number #991*15901590* on the router. Do I have to connect telephone to router?

A: Connect to the router via Ethernet or WiFi and negotiate an IP address via DHCP (most Operating System configurations will do that automatically). The Fritz!Box should now be set as the default gateway. You can use route on the command line to determine it.
If DHCP doesn't work anymore, you can still scan the whole private IPv4 address range. For example, nmap -sP 192.168.0.0/16 10.0.0.0/8 172.16.0.0/20 will list a Fritz!Box without a configured DHCP server (but functioning IPv4).

A: No matter how the FritzBox is configured, it is always reachable via ethernet cable http://192.168.178.254 - there you'll find an option to reset to factory settings.


text:
Q: Fill Comboboxes by comboboxes i have 2 comboxes.,..,cbocourse and cboyearandsection
if i click BSIT on cbocurse then cboyearandsection will be automatically fill in without clicking any button except the selection of the index of cbocourse
 Dim BSIT() As String = {"1A", "1B", "1C", "2A", "2B", "2C", "3A", _
           "3B", "3C", "4A", "4B"}

 If cbocourse.SelectedIndex = "BSIS" Then
      cboyear.Items.AddRange(BSIT)

A: For starters, If cbocourse.SelectedIndex refers to the INDEX of the selected item, which will be an Integer value.  You can think of the items in your combobox as being in array.
If you want to compare to the String value of the selected item, you need
If cbocourse.SelectedItem.toString()

A: Module level:
    Dim BSIT() As String = {"1A", "1B", "1C", "2A", "2B", "2C", "3A", _
       "3B", "3C", "4A", "4B"}

Assuming cboCourse contains strings like "ABC", "DEF", "BSIT", then:
 Private Sub cboCourse_SelectedIndexChanged(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles cboCourse.SelectedIndex

    If cboCourse.SelectedItem.ToString = "BSIS" Then
        ' dont want to add 2ce
        cboyear.Items.Clear()
        cboyear.Items.AddRange(BSIT)
    End If

End Sub

Caveats:
We dont know what is in cboCourse, it looks like strings.  If it is an object or index to something else, that would have to be resolved.  After you read up on events and cbo Selected... properties, work out how to start accepting some of the answers you get.


text:
Q: Scala how to use defaults without redefining them I have a function defined as:
def par(min: Int = -1, exact: Int = -1, auto: Boolean = false) = {
  require(min > 0 || exact > 0 || auto, "Invalid argument")
  OpPar(drm, minSplits = min, exactSplits = exact)
}

In another function that uses this I pass in Options for the par params. I would like to allow par to use it's own defaults but don't see how to do that in Scala (without ugly logic) so I have to redefine, in effect, the defaults like this.
drmARaw.par(
  min = minPar.getOrElse(-1),// if par changes this may the be wrong default
  exact = exactPar.getOrElse(-1),// if par changes this may the be wrong default
  auto = autoPar.getOrElse(true))

If the defaults ever change this will pass the wrong defaults to min and exact. Using complicated logic I can decide which version of par to call based on which Option params are nonEmpty for minPar and exactPar but this is pretty ugly and would have to be written differently for every function with default params. This situation occurs with virtually every Scala lib out there. If they change the defaults and I don't notice it, my code will break.
The example above illustrates the problem but I'm looking for a Scala idiom that would cover every case where a function has defaults that could change. I want to write code that is independent of default param changes in lib functions.

A: You could extract the logic into a separate case class which has a zero or empty state.
case class ParInput(min: Int, exact: Int, auto: Boolean)

object ParInput {
  def apply(min: Option[Int], exact: Option[Int], auto: Option[Boolean]) = {

    ParInput(
      min.getOrElse(empty.min),
      exact.getOrElse(empty.exact),
      auto.getOrElse(empty.auto)
    )
  }
  val empty = ParInput(-1, -1, false)
}

Here's the rest of this:
def par(input: ParInput = ParInput.empty) = {
  require(min > 0 || exact > 0 || auto, "Invalid argument")
  OpPar(drm, minSplits = input.min, exactSplits = input.exact)
}

def par(
  min: Option[Int] = None,
  exact: Option[Int] = None,
  auto: Option[Boolean] = None
): OpPar = {
  val input = ParInput(min, exact, auto)
  // now call the original library method.
  par(drm, input.min, input.exact)
}

Now all you need to update is the empty state, and done. You even get a free Monoid.

A: So, as I understand it, you have three Options that you need to unpack and send as passed parameters, except if any option is None then the invoked method should use its own default value for the missing parameter.
It seems to me your only choice is brute force.
(minPar, exactPar, autoPar) match {
  case (Some(m),Some(e),Some(a)) => par(min=m, exact=e, auto=a)
  case (Some(m),Some(e),None)    => par(min=m, exact=e        )
  case (Some(m),None,   Some(a)) => par(min=m,          auto=a)
  case (Some(m),None,   None)    => par(min=m                 )
  case (None,   Some(e),Some(a)) => par(       exact=e, auto=a)
  case (None,   Some(e),None)    => par(       exact=e        )
  case (None,   None,   Some(a)) => par(                auto=a)
  case (None,   None,   None)    => par()
}

With 2 parameters it's easy.  With 3 it's manageable.  After that .... painful.


text:
Q: How do I disable all the keys of the keyboard except for three? So I want to disable all the keys on my keyboard except for 'ctrl', 'alt', and 'E'. How do I do this with the help of a command that I can bind to a keyboard shortcut.
I figured out how to disable the entire keyboard using the following command xinput float 17.
Thanks

A: Try xmodmap:

xmodmap - utility for modifying keymaps and pointer button mappings in X

*

*Use xmodmap -pke to find out which keys have which keycode on your keyboard.

*Disable a key by using xmodmap -e 'keycode 24 = 0x0000' replacing 24 with the respective keycode of the key which you want to disable.

*Repeat step 2 for all listed keycodes to disable all keys. You can for example use a for loop to do so quickly:

#!/bin/bash

for i in {8..255}
do
    echo "Disabling keycode $i ..."
    xmodmap -e "keycode $i = 0x0000"
done


text:
Q: Interpolate python lists at different rates to get equally spaced values I have two lists in Python, which correspond to the x-coordinates and the y-coordinates in a 2d array while circling around an ellipse. The x-coordinates look something like this: x_coords = [299.97, 298, 297, 296, 295.41, 295, 294.91, 295.012, 295.58, 296.1, ...], and y_coords is the same length but has different values.
As you can see, the values are not equally spaced, and they increase and decrease throughout the list (as they are going around the ellipse). I can compute the distance between any two adjacent (x,y) points on the ellipse with:
import numpy as np
distances = []
for i in range(len(x_coords)):
    if i==len(x_coords)-1:
        break
    dist = np.sqrt((x_coords[i+1]-x_coords[i])**2 + (y_coords[i+1]-y_coords[i])**2)
    distances.append(dist)

When I print distances, I can see that they are all different. So my (x, y) coordinate pairs are not equally spaced. I would like to find a way to make them all equally spaced. I imagine this would involve interpolating in between each value within x_coords and y_coords such that distances returns values that are all equal. Of course, x_coords and y_coords also need to still have equal lengths so that (x_coords[i], y_coords[i]) will correspond to an (x, y) point at the same position in space. How can I accomplish this?


text:
Q: Not able to detect text from other application window using accessibility service I created an accessibilty service and when I enable the service from settings service is getting connected.
What I need to know is if I tap on any screen point outside my applications,
Window text of surrounding should be detected something similar to U-dictionary.
android:accessibilityEventTypes="typeViewClicked|typeViewFocused|typeAllMask"
android:accessibilityFeedbackType="feedbackGeneric"
android:canRetrieveWindowContent="true"
android:notificationTimeout="0"

Now I see randomly method is fired, but I need to be sure about the event.
public void onAccessibilityEvent(AccessibilityEvent event) {

Could you please suggest what event i should handle when I click on point or finger up on a point.
Also to detect the text from surroundings.


text:
Q: Need help testing TCP server I recently built a server for one of my project. The server works with TCP connection. (5 devices comunicate with it simultaniously). Foreach device that connects to it i then create a new grid row with informations recieved.
My problem is that if i have the clients turned on before the server is started the server is not able to handle the incoming connection rush and crashes. I need to start it few times before it finally fires on.
Unfortunetly i am not able to reproduce the error at my home to debug it. Is there any app which would be able to always try connecting to the server and when it finally succeds send a string over the network to it?

A: In the end i wrote my app for this purpose. The app is very primitive. It just tries to reconect all the time it is not connected to the server and when it succeeds it sends connection string to the server and reads answer.
Here is the code if someone would like to utilize it: (for more connections at once just run more instances of this app or change the code aproprietly)
https://pa ste bin(.)com / g0wcJXh7 (i am sorry but i just wasnt able to paste all of the code inside the codeblock - it always put there just a part of it)
static TcpClient client;
    static string ipAdress = "10.10.2.29";
    static int port = 11800;
    static string cnnMess;
    static string junkMess;
    static Byte[] bytes;
    static Byte[] bytes_junk;
    static void Main(string[] args)
    {
        //initializing variables
        Random r = new Random();
        cnnMess = string.Format("CNN?AA:BB:CC:DD:{0}!", r.Next(10, 99));
        bytes = Encoding.UTF8.GetBytes(cnnMess);
        junkMess = "JUNK!";
        bytes_junk = Encoding.UTF8.GetBytes(junkMess);

        while (true)
        {
            try
            {
                client.GetStream().Write(bytes_junk, 0, bytes_junk.Length); //App tries to send junk packet to the server (used to determine wether the connection still exist)
                Thread.Sleep(50); //Put the thread to sleep to minimize the trafic
            }
            catch //if the sending fails it means that the client is no longer connected --> reconnect
            {
                Connect();
            }
        }

    }
    static void Connect()
    {
        client = new TcpClient();
        try
        {
            client.Connect(ipAdress, port);
        }
        catch { }
        int count = 0;
        while (!client.Connected)
        {
            Thread.Sleep(500);
            count++;
            if(count >= 5)
            {
                try
                {
                    client.Connect(ipAdress, port);
                }
                catch { }
                count = 0;
                Console.WriteLine("Connection Failed - retrying");
            }
        }
        var writer = new StreamWriter(client.GetStream());
        var reader = new StreamReader(client.GetStream());
        client.GetStream().Write(bytes, 0, bytes.Length);

        Console.WriteLine(cnnMess);
        while (client.GetStream().DataAvailable)
        {
            Console.Write(client.GetStream().ReadByte());
        }
        Console.WriteLine();

        }


text:
Q: Split comma-separated parameters in LaTeX I am trying to build a command which is similar to LaTeX \cite{}, which accepts a comma-separated list of parameters like this
\cite{Wall91, Schwartz93}
I would like to pass each item in the comma-separated list which the parameter represents to another command and return the concatenation of the individual results. I imagine it to be something like this:
\newcommand{\mycite}[1]{%
  \@for\var:=\split{#1} do{%
    \processCitation{\var}%
  }%
}

Literature on String manipulation, variables and looping in LaTeX would be great!
Also: Is there a way to join the individual results using commas again?
Thanks!

A: Using Roberto's link I arrived at this solution:
\makeatletter

% Functional foreach construct
% #1 - Function to call on each comma-separated item in #3
% #2 - Parameter to pass to function in #1 as first parameter
% #3 - Comma-separated list of items to pass as second parameter to function #1
\def\foreach#1#2#3{%
  \@test@foreach{#1}{#2}#3,\@end@token%
}

% Internal helper function - Eats one input
\def\@swallow#1{}

% Internal helper function - Checks the next character after #1 and #2 and
% continues loop iteration if \@end@token is not found
\def\@test@foreach#1#2{%
  \@ifnextchar\@end@token%
    {\@swallow}%
    {\@foreach{#1}{#2}}%
}

% Internal helper function - Calls #1{#2}{#3} and recurses
% The magic of splitting the third parameter occurs in the pattern matching of the \def
\def\@foreach#1#2#3,#4\@end@token{%
  #1{#2}{#3}%
  \@test@foreach{#1}{#2}#4\@end@token%
}

\makeatother

Usage example:
% Example-function used in foreach, which takes two params and builds hrefs
\def\makehref#1#2{\href{#1/#2}{#2}}

% Using foreach by passing #1=function, #2=constant parameter, #3=comma-separated list
\foreach{\makehref}{http://stackoverflow.com}{2409851,2408268}

% Will in effect do
\href{http://stackoverflow.com/2409851}{2409851}\href{http://stackoverflow.com/2408268}{2408268}


text:
Q: Mapping groups of events to segments using a logarithmic scale I have some events (an array of groups of events) and I want to map those events to segments using a logarithmic scale.
There are some rules I want the solution to obey to:

*

*Math.log(x+1) must be used as it scales well 1 and numbers smaller than 1

*I want to calculate the single segments and not only the total

*The sum of the segments of a group i must be equal to the sum of the segments of another
  group j if the linear sums of the events are equal (i.e. if I have the events [1, 1] and [2] the total
  of the mapped segments of the two groups must be equal)
I have developed the solution you see below but it works partially, as the sum of groups[0].segments is different from the sum of groups[1].segments, because log(1+1)+log(1+1) != log(2+1)
How can I use Math.log(x+1) to scale the events while having rule 3 working?

var logSegmentLen = function(x) {
  return Math.log(x+1);
}

var groupOfSegmentsTotal = function(segmentLenFn) {
  var f = function(arrayOfSegments) {
    let segments = arrayOfSegments.map(segmentLenFn);
    let total = segments.reduce((a,b) => a+b,0);
    return {
      total: total,
      segments: segments
    }
  }
  return f;
}

var events = [ [1, 1], [2]]
var groups = events.map(groupOfSegmentsTotal(logSegmentLen));
console.log(groups[0].segments, groups[1].segments);
console.log(Math.abs(groups[0].total - groups[1].total) < 0.001); // true must be printed

A:
How can I use Math.log(x+1) to scale the events while having rule 3 working?

Apparently this is just impossible. Your requirement #3 which can be restated as for given scale function F(x)
sum(Xi) = sum(Yj)  =>  sum(F(Xi)) = sum(F(Yj))

actually implies that the only F(x) that fits it is of form F(x) = k*x i.e. just a linear scale. Any non-linear scale (including logarithmic) will break that requirement. You probably should describe your higher-level problem and somebody might be able to come up with non-self-contradicting translation of that problem.
Sidenote Sketch of the proof. Fix {Xi} to be just a collection of n identical values x and {Yj} to be a collection of m identical y. So
sum(Xi) = n*x
sum(Yj) = m*y
sum(F(Xi)) = n*F(x)
sum(F(Yj)) = m*F(y)

and the requirement becomes:
sum(Xi) = sum(Yj)  =>  sum(F(Xi)) = sum(F(Yj))
n*x = m*y => n*F(x) = m*F(y)

And this holds for arbitrary integers n and m. Now lets fix F(1) = k. It means that for any m/n F(m/n) = m/n*k. As real numbers can be approximated by fractions with arbitrary precision, it means that for any x F(x) = x*k.


text:
Q: How can i set to only our country and google bot can see my web site? I added to this code to index.php on opencart system.
if(!strstr(strtolower($_SERVER['HTTP_USER_AGENT']), "googlebot"))
{
    if($_SERVER["HTTP_CF_IPCOUNTRY"] =! 'UK')
    {
       echo "You can not see this page.";
       die();
    }
}

But i can see this page with proxy web sites from other countries. I want to only My Country IP and googlebot see this page.

A: You may want to  try:
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'googlebot') !== false OR $_SERVER["HTTP_CF_IPCOUNTRY"] == 'UK') {
    echo "GoogleBot and UK users will see this";
}else{
    die("DENIED");
}


text:
Q: Ionic 3 + One Signal handleNotificationReceived doesn't get fired I'm following this Ionic SDK Setup link. I'm setting up the push notification on my app.
It's working, I can get the notification. Here's my code.
this.platform.ready().then(() => {
    let OneSignal = window["plugins"].OneSignal;

    OneSignal
      .startInit(AppSettings.ONESIGNAL_APP_ID)
      .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
      .handleNotificationOpened(function(jsonData) {
        console.log('OPENED');
      })
      .handleNotificationReceived(function(jsonData) {
        console.log('RECEIVED');
      })
      .endInit();

    OneSignal.getIds(notificationsCallBack.getIdReceived.bind(this));
});

However, the function handleNotificationReceived is only called if the app is open. I need to execute some code (I need an in-app badge), even if the app is closed. I'm setting the content_available to true on my OneSignal API, I also tested directly on the OneSignal website and I couldn't make it works. The function handleNotificationOpened works as expected.
How can I handle the notification received event when my app is not open?
I'm testing on iPhone 6+, iOS 11.0.3
My env:
Ionic 3.12.0
Cordova 7.0.1
My package.json
{
    "name": "XXX",
    "author": "XXXX XX",
    "homepage": "XXX",
    "private": true,
    "scripts": {
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve"
    },
    "dependencies": {
        "@angular/common": "4.2.2",
        "@angular/compiler": "4.2.2",
        "@angular/compiler-cli": "4.2.2",
        "@angular/core": "4.2.2",
        "@angular/forms": "4.2.2",
        "@angular/http": "4.2.2",
        "@angular/platform-browser": "4.2.2",
        "@angular/platform-browser-dynamic": "4.2.2",
        "@angular/platform-server": "4.2.2",
        "@angular/router": "^4.2.2",
        "@ionic-native/camera": "^3.4.4",
        "@ionic-native/core": "^3.10.3",
        "@ionic-native/facebook": "^4.3.1",
        "@ionic-native/geolocation": "^3.2.2",
        "@ionic-native/google-maps": "^3.4.4",
        "@ionic-native/google-plus": "^3.4.4",
        "@ionic-native/image-picker": "^3.2.2",
        "@ionic-native/native-storage": "^3.4.4",
        "@ionic-native/splash-screen": "^3.12.1",
        "@ionic-native/status-bar": "^3.12.1",
        "@ionic-native/toast": "^3.10.3",
        "@ionic-native/transfer": "^3.2.2",
        "@ionic/storage": "^2.0.0",
        "bourbon": "^4.2.7",
        "cordova-ios": "^4.5.1",
        "cordova-plugin-camera": "^2.4.1",
        "cordova-plugin-compat": "^1.2.0",
        "cordova-plugin-console": "^1.0.7",
        "cordova-plugin-crop": "^0.3.1",
        "cordova-plugin-device": "^1.1.6",
        "cordova-plugin-facebook4": "^1.7.4",
        "cordova-plugin-googlemaps": "^2.0.11",
        "cordova-plugin-googlemaps-sdk": "git+https://github.com/mapsplugin/cordova-plugin-googlemaps-sdk.git",
        "cordova-plugin-googleplus": "^5.1.1",
        "cordova-plugin-nativestorage": "^2.2.2",
        "cordova-plugin-splashscreen": "^4.0.3",
        "cordova-plugin-statusbar": "^2.2.3",
        "cordova-plugin-whitelist": "^1.3.2",
        "cordova-plugin-x-toast": "^2.6.0",
        "cordova-sqlite-storage": "^2.0.4",
        "cropperjs": "^1.1.0",
        "font-awesome": "^4.7.0",
        "ionic-angular": "3.3.0",
        "ionic-native": "2.9.0",
        "ionic-plugin-keyboard": "^2.2.1",
        "ionic2-auto-complete": "^1.5.0-beta",
        "ionicons": "3.0.0",
        "ios-sim": "^6.1.2",
        "ng2-cookies": "^1.0.4",
        "onesignal-cordova-plugin": "^2.0.11",
        "rxjs": "5.4.0",
        "sw-toolbox": "3.6.0",
        "zone.js": "0.8.12"
    },
    "devDependencies": {
        "@ionic/app-scripts": "1.3.7",
        "typescript": "2.3.4"
    },
    "cordovaPlugins": [
        "cordova-plugin-device",
        "cordova-plugin-console",
        "cordova-plugin-whitelist",
        "cordova-plugin-splashscreen",
        "cordova-plugin-statusbar",
        "ionic-plugin-keyboard",
        "cordova-plugin-geolocation",
        "cordova-plugin-compat",
        "cordova-plugin-file-transfer",
        "cordova-plugin-file"
    ],
    "cordovaPlatforms": [
        {
            "platform": "ios",
            "version": "",
            "locator": "ios"
        },
        {
            "platform": "android",
            "version": "",
            "locator": "android"
        }
    ],
    "description": "ion2-FullApp: The Best Ionic 2 Starter app",
    "config": {
        "ionic_sass": "./config/sass.config.js",
        "ionic_copy": "./config/copy.config.js"
    },
    "cordova": {
        "platforms": [
            "ios"
        ],
        "plugins": {
            "cordova-plugin-camera": {
                "CAMERA_USAGE_DESCRIPTION": " ",
                "PHOTOLIBRARY_USAGE_DESCRIPTION": " "
            },
            "cordova-plugin-console": {},
            "cordova-plugin-crop": {},
            "cordova-plugin-device": {},
            "cordova-plugin-facebook4": {
                "APP_ID": "XX",
                "APP_NAME": "XXX"
            },
            "cordova-plugin-googleplus": {
                "REVERSED_CLIENT_ID": "XX"
            },
            "cordova-plugin-nativestorage": {},
            "cordova-plugin-splashscreen": {},
            "cordova-plugin-statusbar": {},
            "cordova-plugin-whitelist": {},
            "cordova-plugin-x-toast": {},
            "cordova-sqlite-storage": {},
            "ionic-plugin-keyboard": {},
            "onesignal-cordova-plugin": {},
            "cordova-plugin-googlemaps": {
                "API_KEY_FOR_ANDROID": "XX",
                "API_KEY_FOR_IOS": "XX",
                "LOCATION_WHEN_IN_USE_DESCRIPTION": "Show your location on the map",
                "LOCATION_ALWAYS_USAGE_DESCRIPTION": "Trace your location on the map",
                "key": "XX"
            }
        }
    }
}

A: The notification opened event was fixed in the OneSignal Cordova SDK 2.2.0. It was only an issue for iOS 11 devices.

A: you need to check this. Let me know if it works for you.
You need to set content_available and mutable_content in true in the body of the POST request.


text:
Q: Proof Using Mathematical Induction that $2^n \geq n + 1$ $2^n \geq  n + 1$, for all $n \geq  1$
So I know that first I should use 1, which I did to make sure step 1 holds.
$$2 ^ 1 \geq 1 + 1\\2 \geq 2\\ \mathsf{TRUE}$$
After I figure this out, I know I am then supposed to assume it true for $k$, so I get $2 ^ k \geq k + 1$, but its the whole $k+1$ step that completely looses me. Where would I do from here? I am assuming that I have to get $2 ^ k \geq k + 1$ to equal   $2 ^{k+1} \geq k+1 + 1$, but am not sure how to get there.

A: You want to show that $2^{k+1}\geq(k+1)+1$ using the induction hypothesis. This hypothesis concerns $2^k$, so you will want to make this term appear from $2^{k+1}$. Just remark that $2^{k+1}=2\cdot2^{k}$. Hence, using the induction hypothesis, you can infer
$$
2^{k+1}=2\cdot2^{k}\geq2\cdot(k+1)=2k+2\geq k+2=(k+1)+1
$$
which is what you wanted.

A: $2^{k+1}=2^k\cdot 2=2^k+2^k\ge(k+1)+1=k+2$ by using induction hypothesis $2^k\ge k+1$ and $2^k\ge 1$

A: You are off to a great start.
So, assuming that $2^k\geq k+1$ then: $$\begin{align}&\quad 2^{k+1} \\[1ex]&= 2(2^k) \\[1ex]&\geq 2(k+1) \tag 1 \\[1ex]&= (k+1)+(k+1)\\[1ex]&\geq (k+1)+1 \tag 2\end{align}$$
Can you justify these steps?
Then you have that $\forall k\geq 1: \Big(\big(2^k\geq k+1\big) ~\implies~\big(2^{k+1}\geq (k+1)+1\big)\Big)$ and $2^1\geq 1+1$ so...

A: By AM-GM inequality $\frac{2^n+(n-1)}{n}=\frac{2^n+1+1+...+1}{n}\ge \sqrt[n]{2^n}=2\implies 2^n \ge 2n-(n-1)=n+1$


text:
Q: Math in Mechanics I thought $\frac{d}{dx}, \frac{\partial }{\partial x}$ are basically the same thing and whenever it occurs in a problem I used just $\left(x\right)^{'}$. But recently my professor has been using $\int \:$ for $\frac{d}{dx}$. Why is that so? What fundamental misunderstandings have I? Or is is something else? Specific example that my professer used:
First: $$\frac{dV}{dr}=\frac{r}{2a}\cdot \frac{\partial p}{\partial s}=\frac{r}{2a}\cdot \frac{dp}{ds}$$ (side question: is it ok to just change $\frac{\partial p}{\partial s}$ to $\frac{dp}{ds}$ like he did? or am I still missing something here)
After: $$V\left(r\right)=\frac{r^2}{4a}\cdot \frac{dp}{ds}+C$$
P.S. It's laminar   pipe flow example. $V$-Volume, $r$-pipe radius, $p$-pressure, $a$-liquid viscosity, $s$-depth.

A: Take a look at these examples: $f = f(x)$ is a notation for a function of the variable $x$, $g = g(x,y)$ for a function of the variables $x,y$, and again $h = h(x,y(x))$ is a notation for a function of two variables $x,y$, where $y$ in turn depends on $x$. When you differentiate a function of one variable like $f$ you usually write
$$f' = \frac{df}{dx}$$
whereas when the function depends on two variables (like $g$ above) you use the notation of partial derivation:
$$\frac{\partial g}{\partial x} \quad \text{ and } \quad \frac{\partial g}{\partial y}.$$
The notation $\frac{\partial }{\partial x}$ (resp. $\frac{\partial}{\partial y}$) has the meaning of differentiating with respect to the first (resp. second) variable! To see what I mean, check this: suppose you want to differentiate $h$ as above with respect to the variable $x$. In that case you still use the notation $\frac{d}{dx}$ as follows:
$$\frac{d}{dx}h(x,y(x)) = \frac{\partial h}{\partial x}(x,y)+ \frac{\partial h}{\partial y}(x,y)\frac{dy}{dx}(x).$$
This is sometimes called 'total derivative'. Observe how the notation changes and that this derivation is fundamentally different from the partial derivation with respect to the first $\mbox{variable, $\frac{\partial }{\partial x}$.}$
Finally, about your side question: if $\rho$ depends only on $s$ yes, you should change your notation.


text:
Q: how to connect mobile camera or other camera to the picture box in c#,winforms? Started learning c# from past 1 month,I have a question that whether is it possibility to connect and display mobile camera or other web camera in the picture box.,in c# .net framework in windows forms. thanks in advance

A: You question is a bit too broad for this site. The answer is "Yes it is possible" but it is not as simple as writing a few lines of code in C#. You will need some kind of toolkit/library/framework that allows you to connect to the camera and display the video. There are tons of them out there, each having pros and cons, some simple, some complicated.
If you are using Visual Studio, in the Solution Explorer right-click on your Project name and select "Manage Nuget Packages". In the Window that opens select "Browse" and then type "camera" into the search box. You will see a number of packages that provide support for using cameras.

A: There are several ways to communicate with the camera.
I use this code to communicate with the camera.
public class CameraAPI
{
    public bool IsAvailable { get; set; }

    [DllImport("avicap32.dll")]
    public static extern IntPtr capCreateCaptureWindowA(byte[] lpszWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, int nID);
    [DllImport("avicap32.dll")]
    public static extern bool capGetDriverDescriptionA(short wDriver, byte[] lpszName, int cbName, byte[] lpszVer, int cbVer);
    [DllImport("User32.dll")]
    public static extern bool SendMessage(IntPtr hWnd, int wMsg, bool wParam, long lParam);
    [DllImport("User32.dll")]
    public static extern bool SendMessage(IntPtr hWnd, int wMsg, short wParam, long lParam);

    [System.Runtime.InteropServices.DllImport("user32")]
    public static extern bool DestroyWindow(IntPtr hWnd);

    public const int WM_USER = 0x400;
    public const int WS_CHILD = 0x40000000;
    public const int WS_VISIBLE = 0x10000000;
    public const int SWP_NOMOVE = 0x2;
    public const int SWP_NOZORDER = 0x4;
    public const int WM_CAP_DRIVER_CONNECT = WM_USER + 10;
    public const int WM_CAP_DRIVER_DISCONNECT = WM_USER + 11;
    public const int WM_CAP_SET_CALLBACK_FRAME = WM_USER + 5;
    public const int WM_CAP_SET_PREVIEW = WM_USER + 50;
    public const int WM_CAP_SET_PREVIEWFORMAT = WM_USER + 45;
    public const int WM_CAP_SET_PREVIEWRATE = WM_USER + 52;
    public const int WM_CAP_START = WM_USER;
    public const int WM_CAP_SAVEDIB = WM_CAP_START + 25;
    public const int WM_CAP_EDIT_COPY = (WM_CAP_START + 30);

    private IntPtr hWnd;
    private IntPtr mControlPtr;
    private int mWidth;
    private int mHeight;

    public CameraAPI(IntPtr handel, int width, int height)
    {
        mControlPtr = handel; //handle of video dom
        mWidth = width; //video width
        mHeight = height; //video height
    }

    public void StartPreviewWebcam()
    {
        if (hWnd != null)
            DestroyWindow(hWnd);

        byte[] lpszName = new byte[100];
        byte[] lpszVer = new byte[100];
        capGetDriverDescriptionA(0, lpszName, 100, lpszVer, 0);
        hWnd = capCreateCaptureWindowA(lpszName, WS_CHILD | WS_VISIBLE, 0, 0, mWidth, mHeight, mControlPtr, 0);
        if (SendMessage(hWnd, WM_CAP_DRIVER_CONNECT, 0, 0))
        {
            SendMessage(hWnd, WM_CAP_SET_PREVIEWRATE, 100, 0);
            SendMessage(hWnd, WM_CAP_SET_PREVIEW, true, 0);
            IsAvailable = true;
        }
        else
        {
            IsAvailable = false;
        }
    }

    public void CloseWebcam()
    {
        SendMessage(hWnd, WM_CAP_DRIVER_DISCONNECT, 0, 0);
        IsAvailable = false;
    }

    public void SavePictureByPath(string path)
    {
        IntPtr hBmp = Marshal.StringToHGlobalAnsi(path);
        SendMessage(hWnd, WM_CAP_SAVEDIB, 0, hBmp.ToInt64());
    }

    public byte[] TakePicture()
    {
        byte[] imgByteArray = null;
        var path = Application.StartupPath + @"\Image.png";
        try
        {
            DeleteExist(path);
            SavePictureByPath(path);

            if (File.Exists(path))
            {
                using (Image img = Image.FromFile(path))
                {
                    imgByteArray = ImageToByteArray(img);
                }
            }
        }
        catch (Exception exp)
        {
            var a = 1;
        }
        finally
        {
            DeleteExist(path);
        }

        return imgByteArray;
    }

    public void DeleteExist(string path)
    {
        if (File.Exists(path))
        {
            File.Delete(path);
        }
    }

    public byte[] ImageToByteArray(System.Drawing.Image imageIn)
    {
        using (var ms = new MemoryStream())
        {
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }
    }
}


text:
Q: Adding Return Button In Keyboard Extension I am making a customized iOS 8 keyboard. I created a button called Return and I'm stuck because I don't know how to make Return or Enter key work properly. I found many textFielsShouldReturn tutorials but I don't think it belongs to iOS keyboard extensions.

A: Okay. I got it so easy in short time. This is what i did.
@IBAction func returnPressed(sender: AnyObject) {
    var proxy = textDocumentProxy as UITextDocumentProxy
    proxy.insertText("\n")
}


text:
Q: Smart way to remove mutual edges with python-igraph 0.7 Let L be a directed graph, I have to remove the mutual edges of L. Remember that two edges are mutual if they are of the type a--->b and b---->a.
For example L.is_mutual() returns  list of booleans, every boolean corresponding to an edge. True is returned for a given edge a --> b if there exists another edge b -->a in the original graph.
How to use L.is_mutual() for removing mutual edges?
possible solution (slow):
 L.delete_edges([l[i] for i in range(len(l)) if mut[i]==True])

A: Does l contain the edge list of your graph? In that case, your solution is slow because for every edge to be deleted, igraph has to look up its identifier from the endpoints (since you give the endpoints to delete_edges and not the edge index). Since delete_edges can work with edge indices as well, it is faster to say:
L.delete_edges(index for index, mut in enumerate(L.is_mutual()) if mut)

Another (somewhat slower but more concise) variant:
L.es.select(_is_mutual=True).delete()


text:
Q: Unit test for method that uses a service I'm writing a unit tests for a component. One of it's methods uses a service and it's giving me a cannot read property 'then' of undefined error.
I've seen how to call a service in the test but I'm trying to use a method that calls a service outside of my spec file.
Spec
describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        imports: [...],
        declarations: [MyComponent],
        providers: [...],
      }).compileComponents();
    })
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should save', () => {
    ...
    component.myMethod();
  });

});

Component
  public myMethod() {
      ...
      this.myService.something(this.item).then((resp) => {
       // Error comes from here
      });
    }
  }

A: You can solve this in multiple ways, by mocking services method:

*

*Using spyOn

it('should save', () => {
  const service = TestBed.inject(MyService);
  spyOn(service , 'something').and.returnValue(Promise.resolve('test'));
  component.myMethod();
});

*

*Mocking service
let userServiceStub: Partial<MyService>;

myServiceStub = {
  something: () => Promise.resolve('test'),
};

// configureTestingModule
providers: [
  { provide: MyService, useValue: MockService(myServiceStub ) }
]

*

*Using ng-mocks (my favourite)

// configureTestingModule
providers: [
  MockProvider(MyService, { something: () => Promise.resolve('test') })
]

There are other ways, but one of these should do.


text:
Q: Add Form In Every Row with table helper Codeigniter Hi i am creating table using table helper, but in every row i want to add form, in html like this :

  <form action="">

    <input type="text" name="name2">

  </form>

  <form action="">

    <input type="text" name="name2">

  </form>

But i want in table helper:
 I have tried this one:
    $this->table->add_row(
                form_open('myAction').
                form_input('name'.$i),
                form_submit('Submit')
                form_close()
        );

And I use firebugs to inspect element produces, like this:

       <form action="myAction">
         <input type="text" name="name1">
       </form>
          <input type="submit">

why tag  doesn't show at the last tag , but show at the first tag .
Thanks

A: You are missing some dots
$this->table->add_row(
            form_open('myAction').
            form_input('name'.$i).
            form_submit('Submit').
            form_close()
    );


text:
Q: Canonical quantisation harmonic oscillator I have a question on the canonical quantisation as described at the linked wiki page:
https://en.wikipedia.org/wiki/Quantum_field_theory#Canonical_quantisation
we take the displacement of a classical harmonic oscillator described as $$  x(t)={\frac {1}{\sqrt {2\omega }}}ae^{-i\omega t}+{\frac {1}{\sqrt {2\omega }}}a^{*}e^{i\omega t}, $$
and promote $x(t)$ to a linear operator ${\displaystyle {\hat {x}}(t)}$:
$${\displaystyle {\hat {x}}(t)={\frac {1}{\sqrt {2\omega }}}{\hat {a}}e^{-i\omega t}+{\frac {1}{\sqrt {2\omega }}}{\hat {a}}^{\dagger }e^{i\omega t}.}$$
the coefficients $a$ and it's complex conjugate $a^*$ are replaced ${\hat  a}$ and ${\hat  a}^{\dagger }$.
Question: why following this instruction ${\hat  a}$ becomes creation operator and ${\hat  a}^{\dagger }$ annihilation opererator and not conversely? is there any physical reason that justifies it based on the plus or minus sign of $e^{-i\omega t}$ resp. $e^{i\omega t}$? or is it just a "random choice"?

A: *

*In quantum mechanics, $a$ and $a^\dagger$ are ladder operators, in that they raise and lower the number of excitations presence in the harmonic oscillator:
$$ a^\dagger |0\rangle \propto |1\rangle \quad \Rightarrow \quad a^\dagger |n\rangle = \sqrt{n+1}|n+1\rangle, \\
a|1\rangle \propto |0\rangle \quad \Rightarrow \quad a|n\rangle = \sqrt{n}|n-1\rangle.$$
Each application on $a$ on your number-eigenstate $|n\rangle$ removes a quantum of excitation ($\hbar \omega$ for the harmonic oscillator). The opposite for $a^\dagger$.
$a^\ast$ is the specific case of $a^\dagger$ when $a$ is a scalar, not a matrix.
In field theory now, the vacuum $|0\rangle$ has no field excitations (i.e. no particles, no waves on the string). I can create one excitation by applying $a^\dagger$, like before. Since in the field theory context I am now creating a particle, it's called the creation operator. Same reasoning for the annihilation operator $a$.

*In the Heisenberg picture, the time dependence of an operator is given by:
$$ \dot{A} = \frac{i}{\hbar} [H,A],$$
so:
$$ \dot{a} = \frac{i}{\hbar}[H, a] = \frac{i}{\hbar}[\hbar \omega \, a^\dagger a,a] = -\mathrm{i}\omega a \quad \Rightarrow \quad a(t) = a(0)e^{-\mathrm{i}\omega t},$$
and
$$ \dot{a^\dagger} = \frac{i}{\hbar}[H, a^\dagger] = \frac{i}{\hbar}[\hbar \omega \, a^\dagger a,a^\dagger] = \mathrm{i}\omega a^\dagger \quad \Rightarrow \quad a^\dagger(t) = a^\dagger(0)e^{\mathrm{i}\omega t}.$$


text:
Q: Django migrate command doesn't create any table on Heroku It shows that tables are successfully created when I do heroku run -a "app-name" python manage.py migrate
Running python manage.py migrate on ⬢ app_name... up, run.0000 (Free)
System check identified some issues:

...

Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, home, sessions, taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  ...

But when I create a superuser, it tells me that there is no table
Any suggestions? I'm sticking in it for 3 days now so I will be grateful for any help.
P.S. I use heroku postgresql hobby-dev.
P.P.S.
  File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: auth_user

Base settings.py https://pastebin.com/DLh3KrK7
My production configuration (settings.py)
from .base import *
import dj_database_url
import environ

DEBUG = False

try:
    from .local import *
except ImportError:
    pass

environ.Env.read_env()
env = environ.Env()

DATABASES = {
    'default': env.db()
}

A: Re-check your database configuration. The error trace shows that it's using sqlite as the database backend, instead of Postgres as expected:
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute

This is then failing because the sqlite database is stored on the filesystem, and filesystems on Heroku are not persistent across commands - so the database you created in the migrate step no longer exists when you run createsuperuser.

A: please run these command
python manage.py syncdb
python manage.py migrate
python manage.py createsuperuser

please make sure that you in your installed app
'django.contrib.auth'

and tell me if you still got the same error and then please add your settings.py


text:
Q: Does the local Bertini theorem in mixed characteristic imply the global Bertini theorem Let $R$ be a discrete valuation ring with fraction field $K$ and residue field $k$. Assume that the characteristic of $K$ is $0$ and of $k$ is $p>0$. Let $\pi:X \to \mbox{Spec}(R)$ be a flat, projective morphism with $X$ a regular scheme. Is it true that a general hypersurface of $H_X$ is a regular scheme, flat over $\mbox{Spec}(R)$?
If I understand correctly, this is true "locally" by a result of Flenner proven in Die Sätze von Bertini für lokale Ringe.


text:
Q: referencing foreign key attributes rails I have a scaffold VirtualTransaction referencing my User model.
virtual_transaction.rb
class VirtualTransaction < ApplicationRecord
  has_one :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
  has_one :seller, :class_name => 'User', :foreign_key => 'seller_id'
end

user.rb
class User < ApplicationRecord
  has_many :virtual_transactions
end

But I can't take any further steps to access the association.
I get:
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column
users.buyer_id does not exist
LINE 1: SELECT  "users".* FROM "users" WHERE "users"."buyer_id" = $1...
: SELECT  "users".* FROM "users" WHERE "users"."buyer_id" = $1 LIMIT $2
from (irb):7

when I try to do:
virtual_transaction=VirtualTransaction.first
virtual_transaction.buyer

All I intend to do is access the name of the user referencing the buyer/seller id and display it in my view.
VirtualTransaction(id: integer, buyer_id: integer, seller_id: integer, amount: decimal, created_at: datetime, updated_at: datetime)

A: I think you should use belongs_to instead of has_one as your association.  That will cause ActiveRecord to look for the buyer_id foreign key in the virtual_transactions table:
class VirtualTransaction < ApplicationRecord
  belongs_to :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
  belongs_to :seller, :class_name => 'User', :foreign_key => 'seller_id'
end

A: You're using buyer_id as your table column to store the reference, and postgresql can't find that column.
I don't know your table structure, but you can add a column for foreign key in that case like this:
rails g migration AddBuyerIdToVirtualTransaction buyer_id:integer

Also, you said your scaffold is called VirtualTransaction, but in the piece of code you pasted, the class is name only Transaction.
I think you doing some mistake with the names of your tables/columns. If you post more details about that, we could help better. Good luck


text:
Q: MongoClient() is successful, but Database(MongoClient(), dbName) returns NoneType I'm trying to implement a MongoDB connection handler, but am running into an issue where my Database call returns None, even though my MongoClient() call is successful.
#mongoconn.py

from pymongo import MongoClient
from pymongo.database import Database

class MongoConnection():
    mongoconn = None

    def __init__(self, db=None, collection=None, endpoint=None):
        self.mongodb = db
        self.mongocollection = collection
        self.mongoendpoint = endpoint
        mongoconn = self.__mongo_connect()

    def __mongo_connect(self):
        if self.mongoendpoint is not None:
            mc = MongoClient(host=self.mongoendpoint, port=27017, document_class=dict, tz_aware=False, connect=True)
            print mc    #successful object
            return Database(mc)
        else:
            mc = MongoClient(host='localhost', port=27017, document_class=dict, tz_aware=False, connect=True)
            print mc    #successful object
            return Database(mc, self.mongodb)

m1 = MongoConnection("torbot")

print m1.mongoconn    # None

I can see that this collection torbot does exist, so I don't believe that's the issue:
MongoDB shell version v3.4.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0
use torbot
switched to db torbot
db.requests.find();
{ "_id" : ObjectId("584f7e17bc1d1b7f37d54756"), "requestor" : "ctote", "request" : "Scott Pilgrim Vs The World" }

But I can't find any debug options to see why the call to Database(mc, self.mongodb) fails.

A: mongoconn is a class attribute to access it in the __init__ method you need to prefix it with the class name or self. In your case you are doing self.mongoconn will create an instance attribute which is probably not what you want so what you need is MongoConnection.mongoconn = self.__mongo_connect(). Your __init__ method becomes:
class MongoConnection():
    mongoconn = None

    def __init__(self, db=None, collection=None, endpoint=None):
        self.mongodb = db
        self.mongocollection = collection
        self.mongoendpoint = endpoint
        MongoConnection.mongoconn = self.__mongo_connect()

I don't know if what you are doing is something you should be doing though


text:
Q: Multi-dimensional array - splice the full array based on indexOf value So I currently have a multi-dimensional array, am am trying to splice a value with the index of it is a channel name which has just been removed, then removed that value where that value is.
But its not doing that, its always splicing the very last value, I have debugged to ensure the correct value is being passed that I want to remove but.....still to no avail, I don't have much experience with MD arrays but this is proving to be a pain thus far.
I have attempted to fiddle with the index but just always ends up the same or just the opposite result.
Here is the code as it stands right now for the splice function:
    function stasisEnd(event, channel) {
    console.log(util.format(
        'Channel %s just left our application', channel.name));
    console.log(channel.name);

    //This is where the channels are removed from the array once they leave or are kicked from the channel.
    var index = channelArr.indexOf(channel.name);
    channelArr.splice(index, 1);
    console.log(channelArr);
  }

This is what the array looks like with 3 arrays inside it:
[["1447667845.0","SIP/488-00000000"],["1447667858.4","SIP/477-00000002"],["1447667847.1","SIP/487-00000001"]]

And so far it always removes the last channel where I want to remove an array if it has the index off the channel.name value being removed so aka:

*

*SIP/477-00000002 has been removed.

*Remove the 2nd array based on that value.

*Can continue to remove arrays based off the channel.name.

Hope you guys can shed a little light on this.
EDIT: I am aware this works on a single normal array.

A: channelArr.indexOf(channel.name); works only if "channelArr" contains one element that is EQUAL to channel.name, but "channelArr" do not contains "strings" but "arrays", thus it won't work. You have to cicle the entire array or use two simple arrays instead a MD one
Try something like this
var index = 0;
var foundIndex = false;
for( var i in channelArr ) {
  var channelArrElem = channelArr[ i ];
  if( channelArrElem[ 1 ] == channel.name ) {
    index = i;
    foundIndex = true;
  }
}
if( foundIndex ) {
  channelArr.splice(index, 1);
  console.log(channelArr);
  updateSip();
} else {
  // Something went very wrong and the channel wasn't there.
}


text:
Q: Launch activity from notification instantiating activity even if already there My app has a background service which can run even if the app is destroyed.
The app has two activities: A, which is the main activity, and B, a settings activity.
The notification is created whenever the app goes to background.
If I am in A, go to home screen and launch the activity from the notification (with the intent to A), a new (duplicate) activity A will be created!
I would like to implement this logic:
if (launched from notification with app destroyed) {
    // this is the case where the service is running in background with the app destroyed
    create A;
} else {
    // don't create a new instance since A is already there. If current activity is B, stay in B (as if you pressed the launcher icon)
}

I currently use the following PendingIntent to launch the activity from notification:
PendingIntent launchActivity = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

What is the correct way to implement the above logic, preferably programmatically. Thanks.
EDIT: FLAG_ACTIVITY_SINGLE_TOP does what I wanted, but there is still one problem: with this flag, the activity will not be created if and only if it's on top of the stack.
So, in the case the current stack is [MainActivity > Settings], since Settings is on top of the stack, the new stack will be [MainActivity > Settings > MainActivity], but what I wanted should be [MainActivity > Settings].
EDIT 2: basically, clicking on the notification should resume the app in the state it was.

A: First of all, try to set PendingIntent flag to PendingIntent.FLAG_UPDATE_CURRENT instead of 0:
PendingIntent launchActivity = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

Then set android:launchMode="singleTop" for the Activity A (i.e. MainActivity) to avoid recreating it when it's opened:
<activity
    android:name=".MainActivity"
    ...
    android:launchMode="singleTop">
    ...
</activity>

Finally in the MainActivity, do the Intent handling in onCreate (when the Activity was destroyed and now created by clicking on notification) and onNewIntent method (when the Activity is created and we want to handle notification click).
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    if(intent.hasExtra("KEY_TO_EXTRA")){
        // ...
    }
}

A: You can open RedirectActivity instead of your own activity :
public class RedirectAcivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(this, HomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }
}

And your pendingIntent will be like:
PendingIntent launchActivity = PendingIntent.getActivity(this, 0, new Intent(this, RedirectActivity.class), 0);


text:
Q: dd copies more data than exists in .img? I'm trying to dd an .img file over to my micro sd (8 GB). The rom (.img) is 2.66 GB, but in my output of DD (live) it says its transfered 9 GB. I don't get how it's turning a 2 GB image into 9 GB. I'm running OSX Lion and using a Belkin card read. The card reader is not the problem, I have used disk utility with it with no problem. I think the problem is dd or my card (I hope it's not my card :(    ).
EDIT:Here is the command I use to copy the file
dd if=honey.img of=/dev/disk1 bs=1m

This is the code I use to check the status:
killall -INFO dd

A: The behavior you describe and the nature of the file make me suspect that this is a sparse file. Sparse files are a primitive compression technique, in which large sequences of null bytes in a file are not stored on the disk. Here is an example where I create a sparse file:
$ echo a | dd seek=999999999 >sparse
0+1 records in
0+1 records out
2 bytes (2 B) copied, 6.614e-05 s, 30.2 kB/s
$ ls -l a
-rw-r--r-- 1 gilles gilles 511999999490 Apr 30 00:03 sparse
$ du sparse
16      sparse

The file sparse contains 511999999490 bytes (999999999 blocks of 512 bytes, all zero, plus the two bytes a followed by a newline). Yet the total disk space used by the file is 16kB (4kB for the final block, and 3 other blocks containing only metadata related to the location of the other blocks — all of them absent).
If honey.img is a disk image which was created carefully enough, it may be sparse where the disk had unused space.
When you read from a file, there is nothing to mark it as sparse. So if honey.img is a large disk image, dd may be reading gigabyte upon gigabyte containing only null bytes.
Running ls -l and du on the file (or, on OSX, ls -ls) would show the number of bytes and the number of blocks used for storage. If the bytes wouldn't fit in the number of blocks, the file is sparse. As I write, you haven't posted legible data that could confirm or infirm this.
The one tool I know on OSX that can copy sparse files efficiently is rsync. However, what you're doing here is not copying a file from one filesystem to another, but copying a byte stream (that happens to come from a file) onto a disk. You can only do this if the data actually fits on the target disk.

A: I ran into a very similar problem trying to transfer a Debian live binary.img to a 2GB usb flash drive.  The image size was listed as 1.6GB.  Matt's comment above regarding using stat was very helpful and after calculating the block size at 4096 times the number of blocks (3,109,040), it puts the size at 12,734,627,840 which is nearly 8 times the 1.6GB size listed.  I noticed that on the dd command I was using the bs=1M also, so I retried with the bs=4096 as listed in the stat command, and it copied the file as originally expected at 1.6GB.  So my impression is that if you copy bigger chunks than the block size, it just copies block by block.  But if you copy at the block size (and possibly smaller, although untested) dd evaluates what is inside the block and trims superfluous garbage.  Thanks for the tip Matt.


text:
Q: Alert after touch in UIView I have a UIView with several UILabel. Now I want to add an alert when the UIView has been clicked. Is a click event on a view possible?
Thats my unfinished code:
class viewController: UIViewController {

@IBOutlet weak var view1: UIView!
@IBOutlet weak var view2: UIView!
@IBOutlet weak var view3: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
}

func action(_ sender: UIView) {
    // Create the alert controller
    let alertController = UIAlertController(title: "title", message: "message", preferredStyle: .alert)

    // Create the actions
    let okAction = UIAlertAction(title: "title", style: UIAlertActionStyle.default) {
    }

    // Add the actions
    alertController.addAction(okAction)

    // Present the controller
    self.present(alertController, animated: true, completion: nil)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

The function action should look like my example. Now I need to know how to call it and refer it to the UIView

A: Simply you can override touchesBegan method when clicking specific controls. Instead of checking tag you can directly compare UIView
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        switch touch.view? {
           case self.view1:
                      // show alert
                       break
           case self.view2:
                      // show alert
                       break
           case self.view3:
                      // show alert
                       break
           default:
                   break
        }

    }
}

A: Yes. In your viewDidLoae, add a silenter
let gesture = UITapGestureRecognizer(target: self, action:  #selector (viewClicker(sender:)))
self.view1.addGestureRecognizer(gesture)

Then catch your click action in this function
func viewClicker(sender : UITapGestureRecognizer) {
    // Do what you want
}


text:
Q: Handling usage of shortcut with epstopdf On windows I have a problem when the source file is on a directory that is a shortcut.
This problem occurs with with MikTex (MiKTeX EPS-to-PDF Converter 2.9.7229 (MiKTeX 2.9.7250 64-bit)) as well as with Tex Live (Sorry I don't have the version information from epstopdf, but This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live 2020/W32TeX)).
I have the directory Path_original with a shortcut called Path to this directory (for the tests they are both in the current directory). On the Path_original dirctory there is the file an_eps.eps
The command:
epstopdf "Path/an_eps.eps" "--outfile=Path/an_eps.pdf"

gives the error message (on the console):
Sorry, but epstopdf did not succeed.

The log file hopefully contains the information to get MiKTeX going again:

  C:\Users\User\AppData\Local\MiKTeX\2.9\miktex\log\epstopdf.log

and in the log file:
2020-05-10 15:40:03,882+0200 INFO  epstopdf - starting with command line: epstopdf Path/an_eps.eps --outfile=Path/an_eps.pdf
2020-05-10 15:40:03,882+0200 FATAL epstopdf - The input file does not exist.
2020-05-10 15:40:03,882+0200 FATAL epstopdf - The input file does not exist.
2020-05-10 15:40:03,882+0200 FATAL epstopdf - Info:
2020-05-10 15:40:03,882+0200 FATAL epstopdf - Source:
2020-05-10 15:40:03,882+0200 FATAL epstopdf - Line: 0

whilst
epstopdf "Path_original/an_eps.eps" "--outfile=Path_original/an_eps.pdf"

succeeds without problems
The way of addressing the directory is out of my control i.e. the user of the (doxygen) package decides where the files reside (it is however possible that I modify doxygen slightly to address this problem).
Is there a solution inside epstopdf or outside epstopdf for this problem?

A: MiKTeX does not follow file/folder shortcuts (aka shell links). You can instead create a "directory junction":
mklink /J Path Path_original

A directory junction is similar to a symbolic link but works only for directories.


text:
Q: Is there a way to ease the pain of setting Windows 11 file associations? I just used Windows 11 for the first time and the file association business there is really awful, I have to set every single extension one by one to my preferred application. Whereas on Windows 10, I can just set what I want to be the photo viewer, the browser, the video player, the music player, etc.
Is there some kind of way to make this process easier on Windows 11? Maybe somebody has made an automation tool or something?
When I looked around, this seems to have been a problem for a long while now so I thought maybe somebody has already come up with a solution for it.


text:
Q: Microsoft Orleans - How to activate X reminder grains in different silos? Is there a way in Orleans to make sure X reminder grains of same type are hosted on different silos?
Motivation:
I want to use Orleans in an Azure cloud service that runs background processing and should be highly resilient to failures and to silos downtime due to in-place upgrade. In my scenario there is a need for a grain that is always active doing it's job using timers, and if it's hosting silo goes down then it should be activated again on another silo in few seconds. During an Azure cloud service upgrade, the instances are divided into 5 groups, one group is upgraded at a time, which means during an upgrade I always have 20% of my instances shut down, which makes it challenging to have an always active grain. I consulted with Sergey Bykov and we came up with several ideas, one of them was introducing "keep alive" grains that their purpose is to ping the "always active" grain to make sure it's active. In order to make that work during upgrades, I need to make sure there is always at least one "keep alive" grain that its hosting silo isn't in the same upgrade group as the silo that hosts the "always active" grain, so that "keep alive" grain will be able to make the "always active" grain be re-activated on another silo that isn't shutdown at that moment.

A: I recently was reading the Orleans Timers and Reminders documentation which contained the following nugget which may be relevant.  Highlighting is my own.
Reminders
Description
Reminders are similar to timers with a few important differences:

*

*Reminders are persistent and will continue to trigger in all situations (including partial or full cluster restarts) unless explicitly cancelled.

*Reminders are associated with a grain, not any specific activation.

*If a grain has no activation associated with it and a reminder ticks, one will be created. e.g.: If an activation becomes idle and is deactivated, a reminder associated with the same grain will reactivate the grain when it ticks next.

*Reminders are delivered by message and are subject to the same interleaving semantics as all other grain methods.

*Reminders should not be used for high-frequency timers– their period should be measured in minutes, hours, or days.

Further Comments
It is possible that this isn't a solution in your case because of the final note about high-frequency.  If you have a single point of failure that can't go down, it might be relevant to consider alternative solutions. :-/
The particular case that I am looking at using this for is precisely for a 5 minute polling interval.  I need to call a web service, gather some data and then process it.
My only other thought is to make my polling-based implementation super lightweight so that it can be quickly brought up to speed as the underlying infrastructure is changed.
It appears that there is a decent bit of documentation here regarding activation placement strategies.


text:
Q: Connecting remote mysql database to local mysql databse? I want to write a php code to be embedded in drupal7 module.
I want to call a procedure which can copy the newly generated data in local mysql database to the remote mysql database.
When data is inserted in tables 'A' of my local data base it should be copied to the specific table 'B' of the remote mysql server's database.
Table 'A' is on local host.
Table 'B' is on remote server.
insert data on 'A' -> copied data in 'B'
Is this possible?
Thanks for the help.

A: Trigger + Federated tables should do the trick:
http://dev.mysql.com/doc/refman/5.0/en/federated-use.html
http://dev.mysql.com/doc/refman/5.0/en/federated-limitations.html

A: If you're looking for automatic backups or master->slave duplication, there are ways to accomplish that without touching a line of code.
See here for how:
http://dev.mysql.com/doc/refman/5.0/en/replication-howto.html
This is my personal favorite:
http://blog.evandavey.com/2008/05/how-to-setup-mysql-replication-a-simple-guide.html
Related post:
phpmyadmin synchronize
Still need help doing that? Post.


text:
Q: EasyPHP DevServer and PHP include I'm using the last version of EasyPHP DevServer. I have a new working directory called "myproject" that contains several php files (index.php included). Some php files use the function
<?include("_afile.php");?>

These file seem not be called from the include. I have tried to change the php.ini files with the absolute path of the included files but nothing seems to be changed. What I'm missing ?
Thank you

A: I should activate short_open_tag in php.ini.


text:
Q: Can the Neo4j Enterprise Edition Run on Heroku? There's really not much more to this question than the title, but I can't seem to find this answer anywhere.
I'm primarily interested in the backup capability of the Enterprise Edition and whether that is accessible when Neo4j is running on Heroku.

A: The Neo4j Heroku Add On (https://addons.heroku.com/neo4j) is managed by the Neo4j team. This is a developer instance, and it is currently free.
Production instances will be released in upcoming weeks, when Neo4j version 1.8 GA is released.
See https://groups.google.com/d/msg/neo4j/kidc4VeV_NA/spFwz2EeORgJ


text:
Q: How to resolve could not decode a text frame as UTF 8 though boost websocket I write a websocket though boost, and I receive the message though the client in chrome.
When I use ws, it works well, I can receive correct msg.
but when I use wss, it works bad, and said could not decode a text frame as UTF 8.
the picture is what's wrong is ssl mode.

c++ send msg code
  Json::Value jsonMsg;
        jsonMsg["msgType"] = Json::Value("MspServiceStartUp");
        jsonMsg["version"] = Json::Value(std::string(MSP_VERSION));
        ws_->async_write(boost::asio::buffer((void *) jsonMsg.toStyledString().data(), jsonMsg.toStyledString().size()),
                         boost::asio::bind_executor(*strand_, [&, sp](boost::system::error_code ec1,
                                                                      std::size_t bytes_transferred1) {
                             boost::ignore_unused(bytes_transferred1);
                             if (ec1) {
                                 LOG_ERR << "async write failed, ec = " << ec1 << ", msg = "
                                         << ec1.message();
                                 return;
                             }
                             // Clear the buffer
                             buffer_->consume(buffer_->size());
                             task();
                         }));
    }

js code
var ws=new WebSocket("wss://localhost.com:17801/");
ws.onopen=()=>{console.log('ws open')};
ws.onclose=()=>{console.log('ws close')};
ws.onmessage=(msg)=>{console.log('ws onMessage');console.log(msg)};

Where does this odd character come from?
What is the problem? How to fix this ?

A: The problem is with sending data. async_write() ends immediately, it doesn't make a copy of data buffer, you have to ensure that data passed into boost::asio::buffer lives until the full message will be sent.
Even if we added some delay code between async_write and ending brace {:
async_write(boost::asio::buffer((void *) jsonMsg.toStyledString().data(), ..));
... some code waiting until write is completed
}

this code will not work also, because toStyledString returns string by value.
So temporary string is created, string::data() is called, async_write() ends, and you have dangling pointer inside task initiated by async_write().
Quick solution, prolong lifetime of string for example by using smart pointer:
std::shared_ptr<std::string> buf(std::make_shared<std::string>(jsonMsg.toStyledString()));
ws_->async_write(boost::asio::buffer(*buf),
                 boost::asio::bind_executor(*strand_,
                 [&, sp, buf](boost::system::error_code ec1,
                             std::size_t bytes_transferred1)
                 {
                         boost::ignore_unused(bytes_transferred1);
                         if (ec1) {
                             LOG_ERR << "async write failed, ec = " << ec1 << ", msg = "
                                     << ec1.message();
                             return;
                         }
                         // Clear the buffer
                         buffer_->consume(buffer_->size());
                         task();
                 }));

pass buf by boost::asio::buffer(*buf), and capture it by value inside lambda: [&,sp,buf].


text:
Q: How to retrived Custom Object from Java Bean using reflection? I retrived the Java Bean Properties using reflection.But I am unable to get Collections,Custom Object from Orignal Bean.For Example,
@Entity
@Table(name = "ucms_user_tbl")
public class Employee {

@Id
@Column(name="employee_no")
private int employeeno;
@Column(name="Employee_name")
private String employeeName,
//one-to-Many
@OneToMany(mappedBy="EmpDtl")
private List<EmpDtl> dtlList=new ArrayList<EmpDtl>();
@ManyToOne
@JoinColumn(name="status_id")
//Many-to-One
private EMPStatus empStatus;

}

I retrived the employeeno,employeename using reflection.But i unable to find out dtlList,empStatus properties.
for(Method metd:method){
    Annotation[] annotations = m.getAnnotations();
         for(Annotation annotation : annotations){
                  if(annotation instanceof Column){
                Column myAnnotation = (Column) annotation;
                name=myAnnotation.name();

                   }
         }
}


text:
Q: How to install a conda environment with Spyder and Python 2.7? SOmething as simple as:
conda create -n py2 python=2.7

and then in that environment
conda install spyder=3

fails to solve for the environment. Although the only things here are python=2.7 basics and spyder=3, which on their own website specifies requires python 2.7
https://www.psych.mcgill.ca/labs/mogillab/anaconda2/lib/python2.7/site-packages/spyder/doc/installation.html#requirements
Why does this fail, and how can one get something that basic to work?
New attempts: (Last one are specific versions that I know work together, as I have them on my main system wide install).
conda create -n py2 python=2.7 spyder                    --> Fails to solve env

conda create -n py2 python=2.7 spyder -c free            --> installs spyder4

conda create -n py2 python=2.7 spyder=3 -c free          --> AttributeError on launch

conda create -n py2 python=2.7.17 spyder=3.2.3 -c free   --> AttributeError on launch

All fail. If I don't specify spyder=3, conda installs spyder=4, which is a no-go as those versions of python and spyder do not work together (why doesn;t conda know this when checking for compatibility?). When specifying spyder=3, environment fails to solve except when using channel free, as kindly suggested in the comments. But this method also fails when launching Spyder, throwing AttributeErrors.

A: I hit some Qt issues when launching, that seem to resolve with fixing qtawesome to an older version. Here's the final spec that works for me (osx-64):
conda create -n py2 --override-channels -c conda-forge python=2.7 spyder=3.3 qtawesome=0.7

or as a YAML
py2.yaml
name: py2
channels:
  - conda-forge
dependencies:
  - python=2.7
  - spyder=3.3
  - qtawesome=0.7


text:
Q: Turn a button into a loading circle animation I would like to reproduce the animation below :
http://gph.is/1MILWlq
I found this but i would not have the progress bar (the loading time will not be defined) :
http://tympanus.net/Tutorials/CircularProgressButton/
How can I do it ?

A: You can add an event listener to temporarily replace it with an image and then have the callback of the ajax (or whatever happens) perform a replacement of it. In my example, I just used setTimeout to have it replace the button again after 3 seconds. Normally that functionality would go inside of the ajax callback (or whatever else it was waiting on):
Here's a jsFiddle example: https://jsfiddle.net/jetweedy/m0qpm1xh/2/
var myButton = document.getElementById('myButton');
var myParent = document.getElementById('myParent');
myButton.onclick = function() {
    myParent.removeChild(myButton);
    var myImage = document.createElement("img");
    myImage.src = "http://chimplyimage.appspot.com/images/samples/classic-spinner/animatedCircle.gif";
    myParent.appendChild(myImage);
    setTimeout(function() {
        myParent.removeChild(myImage);
        myParent.appendChild(myButton);
    }, 3000);
};

An alternative would be to write some JavaScript to gradually decrease/increase its size, position, color, and other properties while it processes whatever it's processing, and then (again, inside the callback) put a stop to all that (by ending a setInterval that you had initiated) after you're done.