text:
Q: How save Stack to SharedPreferences? In my Android app I have a custom stack for Strings which extends Stack. I would like to save the stack to Sharedpreferences and also retrieve it from SharedPreferences.
I know how to convert a stack to an ArrayList but I've read that SharedPreferences only supports sets not lists. So how can I save a stack to SP while preserving its order? And how can I retrieve it from SharedPreferences and rebuild the stack?
I'm really lost as to how to approach this. Any pointers in the right direction are highly appreciated - I'm not asking for code dump answers.

A: Here is one possible solution,
You can convert stack to string via serialization and save the string to shared preference
ByteArrayOutputStream bos = new ByteArrayOutputStream()
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(stack);
oos.flush();
String base64str = Base64.encode(bos.toByteArray(), Base64.DEFAULT);
...

When load string from preference, decode the base64 string to bytes and using ObjectInputStream to deserialize the stack.

A: As per earlier comment:
You will probably have to serialize/deserialize your Stack to a string representation, which can then be stored in the SharedPreferences.
It might be possible to (ab)use the json format for this, but it does not give any guarantees about the ordering of the individual elements in the result. It should be easy enough to include the 'position' for every element too though, which you can then use to sort the elements after deserializing.
Alternatively, you can come up with your own structure.


text:
Q: How to change redirect uri after login in identity server4 I have deployed a .net core app on localhost IIS, it is running on two port http://localhost:8010 and localhost:8011 and an identity server4 app running on localhost:5000. Consider if i try to login from http://localhost:8011 and after authenticating the given credentials in identity server4 login method i want to change the redirect URL to http://localhost:8011. How can i achieve this because i see that i can't change the redirect URL from identity server4 after login.

A: Sorry for misunderstood your question.
I do find a setting that might can help on your question but it is done on the caller server, not on IS4 server.
When you configure openidconnect on your server, you can configure some setting before sent the request to IS4 server.
This is done on OnRedirectToIdentityProvider events. There you can change the RedirectUri to any uri that you have when you configure client on IS4.
Example
options.Events.OnRedirectToIdentityProvider = context =>
                    {

                        context.ProtocolMessage.RedirectUri = "https://localhost:5006/signin-oidc";
                        return Task.CompletedTask;
                    };

A: IdentityServer4 do not control the default url after user login but do provide example on their Quickstart UI sample.
In the sample, by default will return to IS4 homepage if no returnurl is specified.
you can just modify it to redirect to your app after successful login

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL 5.1: Upgrade innodb plugin My application is running on MySQL 5.1.58 community edition. As I studied on SO websites that After acquisition by Oracle, new InnoDB plugin has been released and MySQL 5.1 with InnoDB plugin is the best for performance. Below is the command which displays the current InnoDB configuration in my system:
mysql> SELECT * FROM information_schema.plugins where plugin_name like 'InnoDB';
PLUGIN_NAME : InnoDB
PLUGIN_VERSION : 1.0
PLUGIN_STATUS : ACTIVE
PLUGIN_TYPE : STORAGE ENGINE
PLUGIN_TYPE_VERSION : 50158.0
PLUGIN_LIBRARY : NULL
PLUGIN_LIBRARY_VERSION : NULL
PLUGIN_AUTHOR : Innobase OY
PLUGIN_DESCRIPTION : Supports transactions, row-level locking, and foreign keys
PlUGIN_License: GPL
1 row in set (0.00 sec)

To upgrade this plugin, I have added below in my.ini file:
[mysqld]
ignore-builtin-innodb
plugin-load=innodb=ha_innodb_plugin.dll;

My plugin folder is below:
E:\MySQL\MySQL Server 5.1\lib\plugin

ha_innodb_plugin.dll and ha_innodb_plugin.pdb are available in the above plugin directory.
Now, when I check using show plugins; command, I can't see InnoDB entry in the resultset.
Please answer me below things:

*

*Why am I not able to see the InnoDB in plugin list?

*Is it possible to upgrade InnoDB plugin with my existing MySQL version?

*If yes, then is it my approach correct?

*If not, what will be the correct approach?

*Will it help me to improve the system performance?

*For this, should I upgrade from mysql 5.1.58 to 5.1.73?

A: I don't know why you can't see the InnoDB plugin. I've never seen that happen.
You can also use this method to check what version of InnoDB you have loaded:
mysql> SHOW VARIABLES LIKE 'innodb_version';

If it returns a number, then you're using the InnoDB plugin. If it returns nothing, then you're using the builtin InnoDB (or no InnoDB at all).
I suggest that you upgrade to MySQL 5.5. You don't have to fuss with loading the InnoDB plugin, it's loaded and enabled by default, and the builtin InnoDB is not present. Also, MySQL 5.1 is officially end-of-life, and it's no longer a supported product as of 2013-12-31.

Then, is there any other way through which I can upgrade InnoDB plugin related Dll files?

Virtually everyone does this by upgrading the version of MySQL, for example 5.1.58 (2011-07-05) to 5.1.73 (2013-12-03). As you can imagine, there were a lot of important fixes, including security fixes, in the 29 months between these two versions.
In theory, you could download a Zip file of 5.1.73, unpack it and retrieve the InnoDB plugin DLL, and manually move it into the plugin directory of your installed 5.1.58 instance. You should shut down the MySQL Service before doing this.
The caveat is that you would be enabling a version of the plugin (5.1.73) that was never tested with the older version of MySQL. They aren't supposed to break backward compatibility between point-releases, but internal interfaces aren't as strict about that.
Also, upgrading only the InnoDB plugin would not include any fixes implemented in the rest of the MySQL code outside the storage engine.

PS: For what it's worth, the InnoDB plugin existed in MySQL before the Oracle acquisition of MySQL.

*

*2005-10-07: Oracle announces acquisition of Innobase Oy.

*2008-04-15: First alpha of the InnoDB plugin.

*2009-09-01: First beta release of the InnoDB plugin in MySQL 5.1.38.

*2010-01-27: Oracle completes the acquisition of Sun Microsystems.

*2010-04-06: First GA release of the InnoDB plugin in MySQL 5.1.46.


text:
Q: integral inequality of a non-increasing function on [0,1]... I'm trying to prove an inequality from one of my real analysis books, and struggling. The problem is as follows:
Show that for any non-increasing f: that maps [0,1] to the reals, and any θ in (0,1) we have the following inequality:
$\displaystyle θ\int_{0 }^{1}f(x)dx$ $\leq$ $\displaystyle\int_{0}^{θ}f(x)dx$
I've tried to approach this similar to a previously asked question about the specific case where θ=1/2, however I haven't gotten far with that method. The other consideration I had was using a max to show that one integral had to be less than or equal to f at a certain point times the difference in x values.

A: Since $\theta\in(0,1)$ and $f$ is non increasing $$\theta x\leq x\implies f(x)\leq f(\theta x)\implies \int_{0}^{1} f(x) \;dx\leq\int_{0}^{1} f(\theta x)\;dx$$
Make the change of variable $t=\theta x$ in the second integral, and you get:
$$\int_{0}^{\theta}f(t) \frac{dt}{\theta}$$, so
$$\int_{0}^{1} f(t) \;dt\leq\int_{0}^{\theta} f(t)\;\frac{dt}{\theta}\implies\theta\int_{0}^{1} f(t) \;dt\leq\int_{0}^{\theta} f(t)\;dt$$
as we wanted.


text:
Q: MS access update subform with another subform entire dataset I am trying to create a form that has 2 subforms. SF1 is a list of classes, just the names, in this subform I can add more classes.
now my issue is with SF2, this subform has the names of all the teachers, but I want the names of the teachers of the classes already displaying in SF1. example:
classes
math
english
history

teachers
herodoto
arquimedes
shakespeare

classTeacher
math-arquimedes
english-shakespeare
history-herodoto
english-arquimedes
math-herodoto

when loaded 1st time
SF1
english

SF2
shakespeare-english
arquimedes-english

2nd pass
SF1
english
math

SF2
math-arquimedes
english-shakespeare
english-arquimedes
math-herodoto

as far as I got was to display the first SF1 correctly, but SF2 displays all data regardless, so my question would be how to connect SF1 and get all the values there and have that as a filter in SF2????
UPDATE
ok here is the real issue I am facing. I am trying to create a ticket management system and I need to identify if the issue is already being worked on or not. for that I created a piece of code that analyzes the ticket detail and adds KEYWORDS to it, so far I was able to do that. my next step on this is to have a list of all the issues related to the keywords that are open and see if I can find a match. if I do, I just click on it and that ticket is now related to that open issue.

1 - the issue detail
2 - keywords list
3 - issue list
so again, my problem is to show all the issues related to the keywords list in 3 and showing the whole list is impractical as there are close to a hundred or more as time passes. some of the issues are just common and this can also be used as a knowledge base but that is the next step...


text:
Q: jQuery how can I find the li that a div is in? I am trying
$(this).parent('li').attr('widgetid')

Because when I click within the following layout I want to find the widgetid

but I am getting "undefined" so I think I lost myself "widgetClose" is the trigger div for what I am attempting to do.

A: You could use:
$(this).closest('li').attr('widgetid');

References:

*

*closest().

A: you can use .parents along with event.stopPropagation
$("div").click(function(e){
    e.stopPropagation();
alert($(this).parents('li').attr('widgetid'));

});

http://jsfiddle.net/FhVgp/3/

A: Instead of using the parent method with a selector (which will only return a value if the immediate parent matches the selector), you could use the parents method:
$(this).parents("li:eq(0)").attr("widgetid")
The parents method will look at all ancestor elements and return all that match the selector (in this case the selector asks for the first li that if found).

A: You should bind only one click event listener for only the parent of all clickable elements anyway, then use event.target within the click function to refer to the clicked element.
From there, you can find the closest
 element using jQuery .closest() method.


text:
Q: Command PhaseScriptExecution Failed with nonzero exit Here is the error, when I run it in the xCode 12.
PhaseScriptExecution Run\ Script /Users/simonwong/Library/Developer/Xcode/DerivedData/Runner-frcmcdsmkzueqwaafgkobyjnbawp/Build/Intermediates.noindex/Runner.build/Debug-iphonesimulator/Runner.build/Script-9740EEB61CF901F6004384FC.sh (in target 'Runner' from project 'Runner')
cd /Users/simonwong/aigogo/ios
export ACTION\=build
export AD_HOC_CODE_SIGNING_ALLOWED\=YES
export ALTERNATE_GROUP\=staff
export ALTERNATE_MODE\=u+w,go-w,a+rX
export ALTERNATE_OWNER\=simonwong
export ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES\=YES
export ALWAYS_SEARCH_USER_PATHS\=NO
export ALWAYS_USE_SEPARATE_HEADERMAPS\=NO
export APPLE_INTERNAL_DEVELOPER_DIR\=/AppleInternal/Developer
export APPLE_INTERNAL_DIR\=/AppleInternal
export APPLE_INTERNAL_DOCUMENTATION_DIR\=/AppleInternal/Documentation
export APPLE_INTERNAL_LIBRARY_DIR\=/AppleInternal/Library
export APPLE_INTERNAL_TOOLS\=/AppleInternal/Developer/Tools
export APPLICATION_EXTENSION_API_ONLY\=NO
export APPLY_RULES_IN_COPY_FILES\=NO
export APPLY_RULES_IN_COPY_HEADERS\=NO
export ARCHS\=x86_64
export ARCHS_STANDARD\=arm64\ x86_64\ i386
export ARCHS_STANDARD_32_64_BIT\=arm64\ i386\ x86_64
export ARCHS_STANDARD_32_BIT\=i386
export ARCHS_STANDARD_64_BIT\=arm64\ x86_64
export ARCHS_STANDARD_INCLUDING_64_BIT\=arm64\ x86_64\ i386
export ARCHS_UNIVERSAL_IPHONE_OS\=arm64\ i386\ x86_64
export ASSETCATALOG_COMPILER_APPICON_NAME\=AppIcon
export ASSETCATALOG_FILTER_FOR_DEVICE_MODEL\=iPhone10,4
export ASSETCATALOG_FILTER_FOR_DEVICE_OS_VERSION\=14.4
export AVAILABLE_PLATFORMS\=appletvos\ appletvsimulator\ iphoneos\ iphonesimulator\ macosx\ watchos\ watchsimulator

../.pub-cache/hosted/pub.dartlang.org/ffi-0.1.3/lib/src/utf8.dart:23:7: Info: Struct 'Utf8' is empty. Support for empty structs is deprecated and will be removed in the next stable version of Dart. Use Opaque instead.

class Utf8 extends Struct {
  ^

../.pub-cache/hosted/pub.dartlang.org/ffi-0.1.3/lib/src/utf16.dart:16:7: Info: Struct 'Utf16' is empty. Support for empty structs is deprecated and will be removed in the next stable version of Dart. Use Opaque instead.

class Utf16 extends Struct {
  ^

../.pub-cache/hosted/pub.dartlang.org/ffi-0.1.3/lib/src/allocation.dart:47:33: Info: Support for using non-constant type arguments 'T' in this FFI API is deprecated and will be removed in the next stable version of Dart. Rewrite the code to ensure that type arguments are compile time constants referring to a valid native type.

final int totalSize = count * sizeOf<T>();
                            ^

Command PhaseScriptExecution failed with a nonzero exit code

A: I don't know why but restarting the computer solved my problem.


text:
Q: Should I merge gh-pages with the master branch? I got two branches now that I can't merge because they have nothing in common.

*

*master

*gh-pages

Will there be trouble if I keep it this way or should I try and keep one branch for both gh-pages and master? (It's github enterprise and not on github.com.)
I can view the pages that are created and edit the pages. I just wonder if I should keep two branches with nothing in common or merge gh-pages with the master branch.

A: These days you do not have to use a gh-pages branch.

*

*Settings

*GitHub Pages

*Source

*master branch /docs folder

This way you can keep everything on one branch, and still keep code separate
from documentation.


text:
Q: How do I edit my code to make the 'next' button lead to a blank page IN THE SAME WINDOW? (not a new window ) from tkinter import Tk, Canvas, Frame, BOTH
from tkinter import *
from tkinter import Tk

#Welcome screen

root = Tk()
root.configure(bg = "steel blue")

canvas = Canvas(root, bg = "steel blue", highlightthickness = 0)
canvas.config(width = 350, height = 250)

#canvas.config(width = root.winfo_screenwidth(), height = root.winfo_screenheight() )
canvas.pack()

#Making of the round rectangle

class Rectangle:

    def round_rectangle(x1, y1, x2, y2, radius=25, **kwargs):

        points = [x1+radius, y1,
                  x1+radius, y1,
                  x2-radius, y1,
                  x2-radius, y1,
                  x2, y1,
                  x2, y1+radius,
                  x2, y1+radius,
                  x2, y2-radius,
                  x2, y2-radius,
                  x2, y2,
                  x2-radius, y2,
                  x2-radius, y2,
                  x1+radius, y2,
                  x1+radius, y2,
                  x1, y2,
                  x1, y2-radius,
                  x1, y2-radius,
                  x1, y1+radius,
                  x1, y1+radius,
                  x1, y1]

        return canvas.create_polygon(points, **kwargs, smooth=True)

    my_rectangle = round_rectangle(10, 60, 330, 250, radius=20, outline = "black", fill="white")

canvas.place(relx=0.5, rely=0.5,anchor=CENTER)

def UserIdentification():
    newWindow = Toplevel(root)

Next_button=Button(root,text = "Next", anchor = W, command = UserIdentification)
Next_button.configure(width = 10, bg = "black", fg = "blue" ,borderwidth = 4)
Next_button = canvas.create_window(150, 200, anchor=NW, window=Next_button)

canvas.create_text(170, 100, text = "Hey there, welcome to DeliverToday! \nWe bring your needs right at your doorstep ~ \nhave a great journey ahead!")

root.mainloop()

Hi, so the code above works completely but I am confused on how to make the "Next" button create a new blank screen(which I will design later but blank for now to make it less complicated). I cant use top-level because I don't want a whole new window to open up but I want it to open in the same window (one screen to exit and another to open). How do I do that with a very easy code?? (the button is on a canvas)

A: You can delete everything on the canvas with the delete method. If you pass it the literal string "all" it will delete everything on the canvas.
def UserIdentification():
    canvas.delete("all")


text:
Q: How to implement linked list quicksort? (most of code complete) I am having some difficulty implementing a linked list quicksort in visual basic, and the problem is the classic stack overflow. As it is a recursive algorithm I assume it is something fairly simple I am missing, but I have been staring at this for hours, tracing it on paper - it will only ever work with three items or less, sometimes four. Any help would be much appreciated.
The algorithm I am following is

*

*Pick an element, called a pivot, from the list.

*Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.

*Recursively apply the above steps to the sub-list of elements with smaller values and separately the sub-list of elements with greater values.

The variable "countABC" holds the number of items in the list.
Here is the code for the node class:
Public Class Node
    'Each node contains the values for one value and is stored
    'in the dynamic linked list.
    Public Name As String
    Public NextNode As Node
    Public PKey As Integer
    Public Sub New()
        'Initializes a new node
        Name = ""
        NextNode = Nothing
        PKey = 0
    End Sub
End Class
Public start As Node
Public Sub New()
    'Initializes a new linked list by setting start as the first node
    start = New Node
End Sub

For the add routine:
Public Sub AddABC(ByVal Name As String, ByVal PKey As Integer)
    'Adds items to a dynamic linked list ordered in alphabetical order
    Dim NewNode As New Node
    Dim ptr As Node = start.NextNode
    Dim prev As Node = start
    NewNode.PKey = PKey
    While ptr IsNot Nothing AndAlso ptr.Name < NewNode.Name
        prev = ptr
        ptr = ptr.NextNode
    End While
    NewNode.Name = Name
    NewNode.NextNode = ptr
    prev.NextNode = NewNode
    countABC += 1
End Sub

And the two functions needed to sort (the join lists is for concatenation)
Public Function SortAlphabetically() As AllColumns
    'This is a quicksort routine that creates a new linked list
    '(that is not saved) in alphabetical order
    If countABC > 1 Then
        Dim pivotPkey As Integer = Math.Ceiling(countABC / 2)
        Dim pivot As New Node
        Dim ptr As Node = start.NextNode

        While ptr IsNot Nothing
            If ptr.PKey = pivotPkey Then
                pivot = ptr
            End If
            ptr = ptr.NextNode
        End While

        Dim lower As New AllColumns
        Dim higher As New AllColumns

        ptr = start.NextNode

        While ptr IsNot Nothing
            If ptr.Name < pivot.Name Then
                lower.AddABC(ptr.Name, ptr.PKey)
            Else
                higher.AddABC(ptr.Name, ptr.PKey)
            End If
            ptr = ptr.NextNode
        End While

        Return (Joinlists(lower.SortAlphabetically, pivot,
                                         higher.SortAlphabetically))

    Else
        Return Me
    End If
End Function

Private Function Joinlists(ByVal lower As AllColumns,
                           ByVal pivot As Node,
                           ByVal higher As AllColumns) As AllColumns
    'Joins two dynamic linked lists together with a pivot value
    'separating them
    Dim list As AllColumns = lower
    list.AddABC(pivot.Name, pivot.PKey)

    Dim ptr As Node = higher.start.NextNode

    While ptr IsNot Nothing
        list.AddABC(ptr.Name, ptr.PKey)
        ptr = ptr.NextNode
    End While
    Return list

End Function

Thanks for reading, I hope I've explained the problem well enough and haven't missed anything out (which is possible because it's part of a larger program).
 Edit
Here is the complete class definition and first sub, which will hopefully explain it better:
Public Class AllColumns
Public countABC As Integer = 0
Public Class Node
    'Each node contains the values for one value and is stored in the dynamic linked list.
    Public Name As String
    Public NextNode As Node
    Public PKey As Integer
    Public Sub New()
        'Initialises a new node
        Name = ""
        NextNode = Nothing
        PKey = 0
    End Sub
End Class

Public start As Node

Public Sub New()
    'Initialises a new linked list by setting start as the first node
    start = New Node
    countABC = 0
End Sub

Is it not the case that as lower and higher are being declared as "New Allcolumns" they will have their own values for countABC that are incremented when nodes are put into the list?
I don't think the routine is navigating to the pivot and then sorting all values after it, this part of the routine is the actual sorting, and "ptr" is set to "start.nextnode" ie. the first item in the list beforehand.
 ptr = start.NextNode

    While ptr IsNot Nothing
        If ptr.Name < pivot.Name Then
            lower.AddABC(ptr.Name, ptr.PKey)
        Else
            higher.AddABC(ptr.Name, ptr.PKey)
        End If
        ptr = ptr.NextNode
    End While

    Return (Joinlists(lower.SortAlphabetically, pivot,
                                     higher.SortAlphabetically))

I should have made this more clear to begin with, apologies.

A: Public Function SortAlphabetically() As AllColumns
    'This is a quicksort routine that creates a new linked list
    '(that is not saved) in alphabetical order
    If countABC > 1 Then
        ...
        Return (Joinlists(lower.SortAlphabetically, pivot,
                                         higher.SortAlphabetically))

countABC appears to be your global node count, not the node count for the subsection you are currently sorting, so this condition is always going to be true and so you'll have infinite recursion.
Also, where exactly is start coming from (where is it updated)?
Finally, it looks to me like you are navigating to the pivot node and from there on adding to the left and right sub-lists based on the comparison, but what about the nodes before the pivot?


text:
Q: How do I convert a string to an array name (php)? I have 4 arrays, each with a question and answer. I want to select a random question/answer array. Here is my code:
<?php
$query_1 = array("What is two plus three?", "5");
$query_2 = array("What is four plus two?", "6");
$query_3 = array("What is seven plus one?", "8");
$query_4 = array("What is six plus three?", "9");

$rand_key = rand(1,4);
$current_query = ('$query_'.$rand_key);
$question = $current_query[0];

print $question;
?>

$question simply prints "$" rather than the first element of the array. How do I get $question to print the first element of the array?
-- yes, I'm a php noob.

A: This is probably a more straight-forward way of accomplishing your task. Instead of storing each question in its own array and fetching it dynamically (i.e. 'question' . $random_value) store each question and answer in the same array and take advantage of array_rand().
<?php
$questions[] = array("What is two plus three?", "5");
$questions[] = array("What is four plus two?", "6");
$questions[] = array("What is seven plus one?", "8");
$questions[] = array("What is six plus three?", "9");

$randomKey = array_rand($questions); // Returns a random key from $questions
$question = $questions[$randomKey];

print $question[0]; // Question
print $question[1]; // Answer

A: Fix your source:
$rand_key = rand(1,4);
$current_query = ${'query_'.$rand_key};
$question = $current_query[0];

print $question;

A: <?php
$qa = array(
array("What is two plus three?", "5"),
array("What is four plus two?", "6"),
array("What is seven plus one?", "8"),
array("What is six plus three?", "9")
);

$rand = rand(0,count($qa)-1);

print $qa[$rand][0];
?>

A: Try to use brackets.
$question = "{$current_query[0]}";

A: With your current data structure, you need to use Variable variables...
$current_query = 'query_'.$rand_key;  // Removed $ prefix in front of 'query'
$question = ${$current_query}[0]      // Variable variables

The name of your variable is stored in $current_query, by placing another $ in front of this you are accessing the value that is stored in a variable of that name. The curly braces (complex syntax) avoids any ambiguity ie. You are not referring to the name of a variable stored in the first element of an array.
However, there are better ways to store your data, such as suggested by @Mike B

A: Try:
eval("\$question = ".$current_query."[0];");

Reference: http://php.net/manual/en/function.eval.php


text:
Q: Spring REST 3 and JacksonMapper for JSON We are currently using spring web services that support application/xml and application/json that works fine. A new service requires returning of an XML string. The string must be kept as XML but I find that application/json is also serializing the contents of the string. Is there any way to prevent this ?
Edits:
//dto:
@XmlRootElement(name="mydata")
public class MyData {
    private String someData;
    @XmlElement(required = true)
    private String content;
    @XmlElement
    public String getSomeData(){
         return someData;
    }
    public String getContent() {
        return content;
}
   //setter and other fields...
}

From the above, the content field is an XML string in my class. I would like the content field to be returned but not serialized. Is this possible ?

A: If you want to return XML, then add this annotation to the service:
@RequestMapping(method = RequestMethod.POST, value = "xyz", headers = "Accept=application/xml")

A: If this string is just serialized object (just like JSON with @ResponseBody), than everything you need is jackson-jaxrs lib and marking return bean with javax.xml.bind.annotation.* annotations:
//in controller:
@RequestMapping
public @ResponseBody MyData getMyData(){
    MyData md = new MyData();
    //...
    return md;
}

//dto:
@XmlRootElement(name="mydata")
public class MyData {
    private String someData;
    @XmlElement
    public String getSomeData(){
         return someData;
    }
    //setter and other fields...
}


text:
Q: Populate H3 Tags with ALT Text in Sibling --> Child IMG Tags Thanks to other helpful people, I have learned how to populate the IMG ALT attributes of images in a jQuery Accordion. Now I want to do the opposite: Take the ALT text out of a set of images and populate the parent H3 tags. Here is the HTML:

    ...(repeat several times)

Here is my jQuery code:
$( document ).ready(function() {
    $( "#accordion" ).accordion();
    $("h3").each(function() {
        var $title = $(this).siblings().children("img").attr("alt");
        $("h3").text($title)
        });
});

This works, but only by populating all H3 tags with the ALT tag from the first image. I.e., all H3 tags had the text "Some stuff here".
What am I doing wrong? Should I somehow put all the ALT text into an array, and then feed it back? Every attempt I made at that just broke the page (no array, no accordion.)

A: You need to use this instead of h3 inside each. this referes to current element
Use
$("h3").each(function() {
    var $title = $(this).siblings().children("img").attr("alt");
    $(this).text($title); //Use this here
});

A: You can try below code:
$("h3").text( function() {
    return $(this).next().children("img").attr("alt");
});

JSFiddel


text:
Q: handle sending sms between users over Twilio I've read THIS Twilio post on how to enable text messaging between users. I am building using Ruby on Rails.
At the moment, this is what I have:

*

*A messaging system in my app where users can inbox each other.

*When a user X messages another user Y, the application also sends that message to user Y's email address. User Y can reply to the message on the app or by responding to the email received by user X. If user Y choses to respond to the email (inbound email) my application processes the email received - it knows that it is intended for user X so it will forward that the email to user X's email address.

This is great because I'm giving the user several means of communication between each other (in app or email).
Now i'd like a similar but instead using the Twilio API.
Particularly i'd like to enable this type of communication:
As per Twilio help center
I'm having trouble understanding the concept of having multiple numbers that can be used by different user but somehow you know who's the message for...( Wow, I'm even having trouble describing what i'm having trouble with!)
I'm using the Ruby wrapper for the Twilio API
To send a message to user it is fairly simple:
# set up a client to talk to the Twilio REST API
@client = Twilio::REST::Client.new account_sid, auth_token

# send sms
@client.messages.create(
  from: 'twilio_number',
  to: 'a user number',
  body: 'Hey there!'
)

To receive a message:
First configure the your Twilio phone number request url to point to an endpoint in your application. In my case its 'yourappurl.com/twilio/create'.
class TwilioController < ApplicationController

  include Webhookable

  after_filter :set_header
  skip_before_action :verify_authenticity_token

  def create
    # inbound messages arrive here. Need to do something with the message, identify who's it for
    # the receiving user and where its coming from ( the user who sent the text message)
    render_twiml response
  end

end

However this is for my application sending a message to a user's phone number. How can I handle communication between two users where user X can communicate with user Y via text messages (all going through my application)

A: Twilio developer evangelist here.
The help centre article on sending messages between users has a great explanation of how to implement this in theory, however you probably want to see some code.
Your best bet is to work through this tutorial on Masked numbers with Twilio which shows you practically how you would purchase a number for a user and then connect two users through that number.
In brief, you need to get a number that represents a relationship between two users. When you receive a message at that number and you get the webhook from Twilio then you can look up the relationship based on the Twilio number the message was sent to and the number it was sent from. You can then connect and send the message on to the number on the other side of the relationship.
But, as I said, I recommend going through the tutorial to really learn this in depth.
Let me know if this helps at all.


text:
Q: How to Simulate ActiveStorage Uploads in RSpec Request Specs I'm writing an API-Only Rails App (rails 5.2) and I need to make use of ActiveStorage. I want to write an RSpec Request Spec to ensure that file uploads work properly, but that's proving very difficult. Here's my spec so far:
RSpec.describe 'POST /profile/photos', type: :request do
  let(:url) { '/profile/photos' }
  let(:file) { fixture_file_upload('photo.jpg') }

  before do
    log_user_in

    ## Do a file upload ##
    post '/rails/active_storage/direct_uploads', params: {
      blob: {
        filename: "woman.jpg",
        content_type: "image/jpeg",
        byte_size: File.size(file.path),
        checksum:  Digest::MD5.base64digest(File.read(file.path))
      }
    }

    post url, params: {signed_id: json["signed_id"]}
  end

  it "Performs an upload" do
    # Never gets here, error instead
  end
end

I've tried using the put helper to upload the file between the first and second post call in the before step, but I keep running into 422 unprocessable entity errors, likely because the put helper doesn't support setting the raw request body. But I'm not entirely sure what the format of that put should be, or if there's a better way to test this.
I've tried using fixture_file_upload, as described in this question:
put json["direct_upload"]["url"], params: {file: fixture_file_upload('photo.jpg')}

But that request returns 422 like all of my other attempts. I think the direct_upload URL really wants the body of the request to contain the file and nothing else.
I suspect there's a lot wrong with my approach here, but the Rails docs are somewhat sparse on how to use ActiveStorage if you're not using the out-of-the-box javascript to hide most of the interactions.

A: You probably don't care about testing the Active Storage engine so you don't need to post '/rails/active_storage/direct_uploads', you just need a valid signature.
I ended up creating an ActiveStorage::Blob by hand and then I can ask it for the signature. Something like this off in a helper:
def blob_for(name)
  ActiveStorage::Blob.create_and_upload!(
    io: File.open(Rails.root.join(file_fixture(name)), 'rb'),
    filename: name,
    content_type: 'image/jpeg' # Or figure it out from `name` if you have non-JPEGs
  )
end

and then in your specs you can say:
post url, params: { signed_id: blob_for('photo.jpg').signed_id }


text:
Q: Merge changes from an external git repo into my local branch I asked a similar question here recently, but this is a more specific question.
I've cloned a open source project locally (OrchardCMS) & created a local branch (accom.dev) off a tag "1.6" in the origin/master branch in order to add my own tweaks to the codebase.
They have since made a lot of changes to the codebase, moving from 1.6 to 1.7 onto 1.7.1 and have even more commits (the current release is 1.7.1). What I want to do is take everything from the 1.7.1 tag (including everything that goes back to 1.6) and merge it into my local branch. From there I will address conflicts, fix my customizations and then deploy to my website.
Note this is NOT a cherry-pick as I want everything from 1.6 up to 1.7.1 merged into my local branch, BUT I don't want the stuff that has been committed SINCE the 1.7.1 release. IOW, I want my customizations to be based off the official 1.7.1 release, not on more recent stuff.
I'm pretty sure what I did gives me what I want, but I'm not sure if there was a better way:

*

*Switched back to to the origin/master

*Created a new local branch 1.7.1-release from the point where the 1.7.1 tag was created... this is treated as a temp branch because I couldn't figure out how to do a merge from a specific point

*Switched back to my accom.dev branch

*Merged the 1.7.1-release branch into my accom.dev branch

*Addressed conflicts & committed the changes in accom.dev

*Deleted the 1.7.1-release branch

At this point I am where I want to be, but I'm wondering if there was an easier way...

A: An easier way is as follows (assumes origin is the name of your remote and that you have already checked out your accom.dev branch):
$ git fetch --tags origin
From ...
* [new tag]    some-tag -> some-tag
* [new tag]     ...

$ git merge some-tag


text:
Q: For how many $n \in \{ 1 , 2 , \dots , 580 \}$ is $n$ a multiple of one or more of $4$, $6$ or $8$? So I believe I want to find the number of integers in the list divisible by 4,6,8
and then subtract the times I double counted the ones which are divisible by more then one.
But I'm not sure how I know how many are divisible by 4,6,8
?

A: Three hints:

*

*Number of multiples of $k$ in $\{1,2,3,...,n\}$ is $\lfloor\frac{n}{k} \rfloor$

*$|A \cup B \cup C| = |A|+|B|+|C|-|A \cap B|-|A \cap C|-|B \cap C|+|A \cap B \cap C|$

*Set $A$, $B$ and $C$ will be the sets of multiples of $4$, $6$ and $8$ respectively


text:
Q:  cannot appear as a child of `div`? I am following this example https://codesandbox.io/s/little-star-yq2h8
which use state. Now I make the same example using hooks
but getting this error
validateDOMNesting(...):  cannot appear as a child of
.
    in td (at editable-cell.js:34)
    in div (at editable-cell.js:56)
    in EditableCell (created by TableCell)
    in TableCell (created by TableRow)
    in tr (created by BodyRow)
    in BodyRow (created by TableRow)
    in TableRow (created by Connect(TableRow))
    in Connect(TableRow) (created by ExpandableRow)
    in ExpandableRow (created by Conne

and row view is not reflecting why ?
here is my code
https://codesandbox.io/s/reverent-burnell-l504y
const PmViewList = () => {
  return (
    <Fragment>
      <EditableFormTable />
    </Fragment>
  );
};

A: It looks like the editable-cell component is returning this:

            <EditableContext.Consumer>{renderCell}</EditableContext.Consumer>

Meanwhile renderCell returns something like this:

                   [cell contents]

My experience with react is limited, but I'm guessing that means that your cell is going to produce HTML that has a
 with a  inside of it, which is not valid. s are only allowed inside of table-oriented elements like
.
Simply removing those
 tags appears to make things work:


text:
Q: IPV6 Unique-local address and site local address Is there any difference between unique-local address and site-local addresses ? or both are meant to be same?

A: Site local addresses have been deprecated. Unique local addresses are designed to be used instead.
Because site local addresses would cause conflicts when setting up VPNs between networks and when merging networks they were deprecated. Unique local addresses make sure that each network uses different addresses so that linking and merging won't be a problem.


text:
Q: fast mobile QR-code to only save a UUID I need a barcode scanner for my mobile apps which works really fast and also with bad lightning conditions. As I only need to store UUIDs and not complete URLs etc., I guess there should be a possibility to limit the value range and therefore make the QR codes better recognizable. Is there a format which supports this?
I also find the WhatsApp QR-Code scanner very fast but I didn't find what they are using exactly...

A: One introduction might be this blogpost. It's based on Google's mobile vision api under the namespace com.google.android.gms.vision.barcode. It's fast, robust and easy to work with.
And I would also up the error correction level of the generated QR-codes if possible... But try the project linked in the blogpost first to see if you even need to.

A: You can use this library barcodescanner
With bad lightning conditions you can activate the flash, in the library there is all about it.


text:
Q: Database design - a many-to-many table which links the same entities? I have a table User with a column id. I want the user to have relationships with other users, so I create a table Relationships with columns user_id_1 and user_id_2.
The questions is how to constrain the table so that
1) there are no entries where user_id_1 equals user_id_2.
For example, entry (1, 1) is bad, because it indicates a relationship to oneself.
2) if there is an entry (user_id_1, user_id_2), the entry (user_id_2, user_id_1) is not allowed.
For example, having entries (1, 2) and (2, 1) is bad, because it indicates the same relationship.
I am using MySQL, although I think this is a general design issue. Thanks!

A: You can write a INSERT and UPDATE triggers on the join table that check these conditions.

A: You use a trigger:
DELIMITER $$

CREATE TRIGGER bi_relationschip_each BEFORE INSERT ON relationship FOR EACH ROW
BEGIN
  IF NEW.user1_id = NEW.user2_id THEN
    SELECT error_user1_cannot_be_equal_to_user2 FROM generate_error;
  END IF;
END $$

DELIMITER ;


text:
Q: Using SVG with IDs for subcomponents I am trying (in javascript) to access parts of a list of SVG components in a little test page, but I am not sure I can achieve what I want this way. The main question is:
Can I have sub-components having the same id in the two SVG top components?
In the code hereafter I want to change the color inside the first disk and the first rectangle. Here is what I tried, but it is not working.
Any tip would be appreciated.
<!DOCTYPE html>

<meta charset='utf-8'>
<meta name=viewport content='width=device-width, initial-scale=1'>
<title>SVG-ID-Test</title>

<svg id="theSVGOne" width="200" height="300" fill="#d55">
    <circle id="theCircle" cx="100" cy="75" r="50"
              stroke="firebrick" fill="#ddd" stroke-width="3" />
    <rect id="theRectangle" x="30" y="140" width="110" height="30"
              stroke="black" fill="#ddd" stroke-width="3" />
</svg>
<svg id="theSVGTwo" width="200" height="200">
    <circle id="theCircle" cx="100" cy="75" r="50"
              stroke="firebrick" fill="#ddd" stroke-width="3" />
    <rect id="theRectangle" x="30" y="140" width="110" height="30"
              stroke="black" fill="#ddd" stroke-width="3" />
</svg>

A: You can use a class instead of id on the child elements (you can have as many duplicate class attributes as you want in the document) and then use querySelector on each svg to target specific children.

let svgOne = document.getElementById('theSVGOne')
let svgTwo = document.getElementById('theSVGTwo')
let statusPane = document.getElementById('status')
statusPane.innerHTML = 'svgOne => '+svgOne.childElementCount.toString()
let circOne = svgOne.querySelector(".theCircle")
let rctOne = svgOne.querySelector(".theRectangle")
circOne.setAttribute('fill', '#ec3')
rctOne.setAttribute('fill', '#e3c')

let circTwo = svgTwo.querySelector(".theCircle")
let rctTwo = svgTwo.querySelector(".theRectangle")
circTwo.setAttribute('fill', 'blue')
rctTwo.setAttribute('fill', 'green')
<svg id="theSVGOne" width="200" height="300" fill="#d55">
  <circle class="theCircle" cx="100" cy="75" r="50" stroke="firebrick" fill="#ddd" stroke-width="3" />
  <rect class="theRectangle" x="30" y="140" width="110" height="30"  stroke="black" fill="#ddd" stroke-width="3" />
</svg>
<svg id="theSVGTwo" width="200" height="200">
  <circle class="theCircle" cx="100" cy="75" r="50" stroke="firebrick" fill="#ddd" stroke-width="3" />
  <rect class="theRectangle" x="30" y="140" width="110" height="30"  stroke="black" fill="#ddd" stroke-width="3" />
</svg>

Don't use IDs
While technically you can have duplicate ids in the DOM (and make it work), this is very bad practise. Id stands for identifier and should be unique to be able to "tell them apart". You can't do that with identical ids (which theCircle are we talking about?).
Problem is, html won't complain about duplicate ids (no errors are thrown).
To actually get feedback on right or wrong markup you can go to w3's validator and check your html there.
Eg. Error: Duplicate ID theCircle.
Working (but wrong) example using id:

let svgOne = document.getElementById('theSVGOne')
let svgTwo = document.getElementById('theSVGTwo')
let statusPane = document.getElementById('status')
statusPane.innerHTML = 'svgOne => '+svgOne.childElementCount.toString()
let circOne = svgOne.getElementById("theCircle")
let rctOne = svgOne.getElementById("theRectangle")
circOne.setAttribute('fill', '#ec3')
rctOne.setAttribute('fill', '#e3c')

let circTwo = svgTwo.getElementById("theCircle")
let rctTwo = svgTwo.getElementById("theRectangle")
circTwo.setAttribute('fill', 'pink')
rctTwo.setAttribute('fill', 'teal')
<svg id="theSVGOne" width="200" height="300" fill="#d55">
  <circle id="theCircle" cx="100" cy="75" r="50" stroke="firebrick" fill="#ddd" stroke-width="3" />
  <rect id="theRectangle" x="30" y="140" width="110" height="30"  stroke="black" fill="#ddd" stroke-width="3" />
</svg>
<svg id="theSVGTwo" width="200" height="200">
  <circle id="theCircle" cx="100" cy="75" r="50" stroke="firebrick" fill="#ddd" stroke-width="3" />
  <rect id="theRectangle" x="30" y="140" width="110" height="30"  stroke="black" fill="#ddd" stroke-width="3" />
</svg>


text:
Q: Sugar teeth meaning I was reading a poem in which the following expression is contained: "I'd be sugar teeth".
I tried to look for the right translation of this, but I couldn't find anything. I only saw on Urban Dictionary that "sugar tooth" means to be thirsty/horny. But it seems to me one of those fixed expressions that do not work when pluralized.
I've also seen that in music there are some things (bands, songs) named Sugar Teeth. Do you have any idea of what it could be its meaning, also in that sentence?

A: "Sugar teeth" are teeth damaged by sugar. In that sense it could imply 'having been damaged by something you love and can't get enough of'.
It also reminds me of the expression 'to have a sweet tooth', meaning you like or have a craving for sweet things.
Urban Dictionary's definition of "sugar tooth" is also what you refer to in your post (opposed to "sugar teeth", which you imply), where a craving for something sweet is generalized to a craving for something you can't get enough of, or for something tantalizing.
The meaning of "I'd be sugar teeth" is likely to be found in the overlapping area: 'a desire for something detrimental'.
I'll assume you are referring to this poem, "If I Could, I Would Have Named Myself Honeysuckle", by Robin Gow. In it, the author refers to the intrinsic danger of the beautiful eponymous flower: the presence of ticks as an invisible threat on an otherwise innocent and surrendering entity.
I think the author yearns for that wild, uncontrollable state, simultaneously embodying both the sweet and its detriment.
(I also found this blog post (warning: very explicit content!), where - similarly - "sugar teeth" is a literal combination of 'sugar' and 'teeth', but both in a metaphorical sense: 'sweet, innocent' and 'biting, raw, feral', respectively. This is remarkably similar to my interpretation of the meaning in the poem.)


text:
Q: Error 415 when trying to consume $http.post service from AngularJS to Spring MVC - Maven I'm trying to check if a user exist when clicking on Login button migrating from Spring Forms + JSTL + Spring MVC to AngularJS + Spring MVC, but I'm getting this error:

Failed to load resource: the server responded with a status of 415 (Tipo de Medio No Soportado)

I'm new to AngularJS and Spring so be nice.
This is my Java Controller:
@Controller
@SessionAttributes("empleado")
public class LoginController {

    @Autowired
    private IServiceEmpleado serviceEmpleado;

    @RequestMapping(value="/login/check", method = RequestMethod.POST,consumes = {"application/json;charset=UTF-8"}, produces={"application/json;charset=UTF-8"})
    public @ResponseBody void login(@RequestBody LoginDTO login, HttpSession session) throws ServicioException{

    Empleado empleado = serviceEmpleado.correctLogin(login.getDni(), login.getPassword());

    session.setAttribute("empleado",

    empleado);

    }
}

This is my AngularJS controller:
angular.module('electronicaDonPepe')
    .controller('LoginController', ['$scope', '$http', '$state', '$stateParams',
        function($scope, $http, $state, $stateParams) {

        $scope.login = function(){
            var param = {
                    dni: $scope.usuario.dni,
                    contrasenia: $scope.usuario.contrasenia
            };

            $http.post('http://localhost:8585/electronicaDonPepe/login/check', param).then(function(){
                $state.go('login');
            });
        };
    }]);

Finally, this is the error:
Request URL:http://localhost:8585/electronicaDonPepe/login/check
Request Method:POST
Status Code:415 Tipo de Medio No Soportado
Remote Address:[::1]:8585
Response Headers
view source
Cache-Control:no-cache
Cache-Control:no-store
Content-Language:es
Content-Length:1120
Content-Type:text/html;charset=utf-8
Date:Thu, 19 Jan 2017 13:44:02 GMT
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Pragma:no-cache
Server:Apache-Coyote/1.1
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:es-ES,es;q=0.8
Connection:keep-alive
Content-Length:43
Content-Type:application/json;charset=UTF-8
Cookie:JSESSIONID=4E1E018490CC15F29FBE205132C2CACD; __ngDebug=true
Host:localhost:8585
Origin:http://localhost:8585
Referer:http://localhost:8585/electronicaDonPepe/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
Request Payload
view source
{dni: "34631248", contrasenia: "34631248"}
contrasenia
:
"34631248"
dni
:
"34631248"

And some AngularJS Batarang hints:
Module "ui.router.util" was created but never loaded.
Module "ui.router.router" was created but never loaded.
Module "ui.router.state" was created but never loaded.
Module "ui.router" was created but never loaded.
Module "ui.router.compat" was created but never loaded.
Module "electronicaDonPepe" was created but never loaded.

I did my research but it seems to be a very particular case in each example I read. Thanks in advance.

A: {dni: "34631248", contrasenia: "34631248"}

Here is your Error. You are passing an invalid JSON format type. Try to use any formater online and you will see that it will give you and error.
{"dni": "34631248", "contrasenia": "34631248"}

This is the correct way of a Json Format Type. Hope it help you. Now the two are passing in strings.
  var param = {
                    "dni": $scope.usuario.dni,
                    "contrasenia": $scope.usuario.contrasenia
            };

Then try with this.

A: Try to set request header
$http.post('http://localhost:8585/electronicaDonPepe/login/check', param,{
    headers: {
        'Content-Type': 'application/json'
    }
}).then(function(){
    $state.go('login');
});


text:
Q: Is it hard to learn 4D database if I do not have any other database skill? As title, I am a programmer and offered a job in relation to 4D database work, but I never heard of this one, I did some research and found out it is a kind of old type of database technology that is not widely used nowadays, it is applied in a lot of legacy/law firms.
I am not a database coder or administrator so that I do not have any skill in database area, so just wondering is that gonna be an issue if I take this job? Or is it hard to learn it?

A: 4D (4D.com) contains a high level programming environment. 4D Development requires knowledge of database principals and experience in coding/scripting, but the language itself is easy to pick up. 4D delivers both back-end database structures (including SQL) AND front end GUI design. The current active version is "15" and 4D remains in active development, however old code from many versions ago remains usable today. Code is compile-able or run in interpreted mode at your discretion. 4D can run as a stand alone application, client-server with hundreds of users, or in web application scenarios. It is a modern and active product that is also cross platform (Windows and OS X): my favorite part is that a single application can run on both platforms, even simultaneously! It's not the fastest, or cheapest development platform, but it's hugely versatile.


text:
Q: Sensor supply current? I'm reading a datasheet for an accelerometer (specifically this) and it lists the max supply current as 290 uA. Does this mean that the power supply I use should never output more than 290 uA? Or does this just mean the device only consumes 290 uA max? In standby mode, the max supply current decreases. Does this mean I have to dynamically reduce the output current from the power supply?

A: No.Yes.No. If it was opposite, then there would be 10 extra pages in datasheet with description of power supply and manufacturer would never be able to sell a single device.
The only power critical device (voltage wise) I know is laser diode

A: You seem to be suffering from a fairly common misconception about current. Typical power supplies do not push current into loads. Instead, they provide a constant voltage. Under a given voltage, an intrinsic property of the device (AKA resistance or impedance) determines how much current will flow. In other words, the supply sets the voltage, and the device decides what the current will be.
In your case, the data sheet tells you the device will need 290 uA, presumably at some voltage which you didn't mention. This means your supply needs to be capable of at least that much current. Extra capability in the supply doesn't hurt the device, in fact, it's desirable, because when a device tries to draw more current than a supply is capable of, undesirable things happen. Better supplies will reduce their output voltage to keep the current down to what they can handle, but lower voltage may make the device operate erratically, or not at all. In a cheaper supply, you'll pop a fuse. Very poorly designed supplies may even burn out.


text:
Q: Table sorting doesn't work with IsotopeJs I am trying to sort my table with IsotopeJs but it isn't working. I followed what has been given in the Isotope documentation but my table doesn't react. Although the documentation used ul li, I changed it to a table layout. Besides that, I used a drop-down instead of buttons to sort the table. If selected an option from the drop-down list, the table should sort the data of countries and servers in descending order, that is from high to low, and prices in ascending order. It would be greatly appreciated if someone could check my code and see if I'm doing anything wrong.
Here's the Codepen link: https://codepen.io/zakero/pen/mddagyo
Here's the code:
HTML

Table

Sort By:
<select id="sorts">
  <option data-sort-value="countries">Most Countries</option>
  <option data-sort-value="servers">Most Servers</option>
  <option data-sort-value="price">Price</option>
</select>

            Options
            Countries
            Servers
            Monthly

            Option 1
            10
            3000+
            $10.95

            Option 2
            56
            3563
            $8.99

            Option 3
            34
            500+
            $6.95

            Option 4
            23
            200+
            $14.99

      Option 5
            86
            38
            $5.99

            Option 6
            33
            50
            $12.99

CSS
table{
    width: 100%;
    margin: 0 0 0 0;
}

table td{
    border: 1px solid #000;
    font-size: 13px;
}

table tr{
    text-align: center;
}

Javascript
// external js: isotope.pkgd.js

// init Isotope
var $table = $('.table-like').isotope({
  layoutMode: 'vertical',
  getSortData: {
    countries: '.countries parseInt',
    servers: '.servers parseInt',
    price: '.price parseInt',
    }
  }
});

$('#sorts').select(function() {
  var sortValue = $(this).attr('data-sort-value');
  $table.isotope({ sortBy: sortValue });
});

A: There are a couple of problem, the first one is that you have an extra closing bracket for the object that you pass to .isotope and second, you're using a .select(..) event listener on a <select> element, this event listener is triggered when that text of an input is selected not when the value of a <select> object is changed. There are a couple of other problems like invalid HTML and using isotope directly on a table and using parseInt for value that cannot be parsed to integer. Here is a working version of your snippet:

var $table = $('.table-like').isotope({
  layoutMode: 'vertical',
  itemSelector: 'tr',
  getSortData: {
    countries: '.countries parseInt',
    servers: '.servers parseInt',
    price: function(row) {
      return parseFloat($(row).find('.price').text().replace("$", ""))
    },
  }
});

$('#sorts').change(function() {
  var sortValue = $(this).find("option:selected").attr('data-sort-value');
  $table.isotope({
    sortBy: sortValue
  });
});
table {
  width: 100%;
  margin: 0 0 0 0;
}

table td {
  border: 1px solid #000;
  font-size: 13px;
}

table tr {
  text-align: center;
}

table body {
  position: static;
}

td, th {
  width: 100px;
}

Table

Sort By:
<select id="sorts">
  <option data-sort-value="countries">Most Countries</option>
  <option data-sort-value="servers">Most Servers</option>
  <option data-sort-value="price">Price</option>
</select>

      Options
      Countries
      Servers
      Monthly

      Option 1
      10
      3000+
      $10.95

      Option 2
      56
      3563
      $8.99

      Option 3
      34
      500+
      $6.95

      Option 4
      23
      200+
      $14.99

      Option 5
      86
      38
      $5.99

      Option 6
      33
      50
      $12.99


text:
Q: Read just a part of a big string I have a large string to read and it's always different, but one word is always the same. The word is MESSAGE, so if my string reader comes across that word it has to write that whole string to disc. I did some code but it's not working, the if segment never triggers, what is wrong here?
string aLine;
StringReader strRead = new StringReader(str);
aLine = strRead.ReadLine();

if (aLine == "MESSAGE")
{
    //Write the whole file on disc
}

A: You can use Contains,
if(aLine.Contains("MESSAGE")
{
}

A: You can use String.Contains
if (aLine.Contains("MESSAGE"))

You can also use String.IndexOf but as index is not relevant here so better to use Contains.
if (aLine.IndexOf("MESSAGE") != -1)

If you need ignore case or Cultrue sensitivity then you IndexOf would provide you overloaded method for it, String.IndexOf(string value,   StringComparison comparisonType)
if (aLine.IndexOf("MESSAGE", StringComparison.InvariantCultureIgnoreCase) != -1)

A: You can change your code to work with Contains.
            string aLine;
            StringReader strRead = new StringReader(str);
            aLine = strRead.ReadLine();

            if (aLine.Contains("MESSAGE"))
            {

              //Write the whole file on disc

            }

A: I think you might be looking for something like String.IndexOf. In that case you could use the following:
if (aLine.IndexOf("MESSAGE") > -1)
{
    ....
}


text:
Q: Probability of winning the league using Chernoff Bound The soccer team "Team A" plays in a league of $n\geq 2$ teams and in each match Team A has probability $p=\frac{1}{10}$ of winning (there are no ties), independent of the last match. In this league, every team plays each of the other teams exactly once. The winner of the league is the team with more wins than any other team. I want to show that the probability of Team A winning the league is less than $(\frac{e}{5})^{\frac{n-1}{2}}$
Since there are $n$ teams, each team will have $n-1$ games. Let $X_1,\dots,X_{n-1}$ be i.i.d. and Bernoulli distributed with $p=\frac{1}{10}$, therefore $X_i$ models whether Team A wins the $i$-th game ($X_i=1)$ or loses the $i$-th game ($X_i=0$).
Let $Y=\sum^{n-1}_{i=1}X_i$ be the number of games that Team A wins, therefore $Y$ is binomially distributed with $E[Y]=\sum^{n-1}_{i=1}E[X_i]=(n-1)E[X_1]=\frac{n-1}{10}$.
Team A can't win the league by winning half their games or less, because then at least one other team would win half their games or more, meaning, for it to be possible to win the league it would have to hold that $Y\gt \frac{n-1}{2}$. Let $\delta=4$, we obtain:
$$P(Y\gt \frac{n-1}{2})=P(Y\gt (1+4)\frac{n-1}{10})=P(Y\gt (1+\delta) E[Y])\leq \begin{pmatrix}\frac{e^\delta}{(1+\delta)^{1+\delta}}\end{pmatrix}^{E[Y]}=\begin{pmatrix}\frac{e^4}{5^{5}}\end{pmatrix}^{\frac{n-1}{10}}=\begin{pmatrix}\frac{e^{4/5}}{5}\end{pmatrix}^{\frac{n-1}{2}} $$
In this inequality I  used that $Y$ is a sum of Bernoulli random variables in order to find a Chernoff bound. As $e^{4/5}\lt e$ this yields the desired result. Is this correct and are there better ways to solve this? Thanks for any feedback!


text:
Q: How can I define a "Do-Nothing" sort? I'm working on a system where I need to be able to sort a vector by a given predicate, which my classes shouldn't have control over. Basically, I pass them a derived class and they blindly sort on it.
As one of the "delightful quirks", one of the sort patterns is order of entry.
Here's what I've got so far.
struct Strategy
{
   virtual bool operator()(const Loan& lhs, const Loan& rhs) const = 0;
};

struct strategyA : public Strategy
{
   bool operator()(const Loan& lhs, const Loan& rhs) const
   {
      return true;
   }
};

struct strategyB : public Strategy
{
   bool operator()(const Loan& lhs, const Loan& rhs) const
   {
      return lhs.getID() > rhs.getID();
   }
};

struct strategyC : public Strategy
{
   bool operator()(const Loan& lhs, const Loan& rhs) const
   {
      return lhs.getFee() > rhs.getFee();
   }
};

Obviously, as strategyA is reflexive, it can't be used, and if I set it to false, it'll treat everything as equal and I can kiss my data goodbye.
So here's my question. Is there a way of defining a predicate function for sorting a vector which will NOT change anything?
I'm aware that possibly the simplest solution is to add an order of entry variable to the Loan class, or partner it with one in a pair. Alternatively I could feed a parameter in with the predicate that tells the sorter whether to use it or not.

A:
Is there a way of defining a predicate function for sorting a vector which will NOT change anything?

It depends on the algorithm. If your sort is a stable sort, the order of "equal" elements won't be changed (which is undefined for unstable sorts).
Consider using std::stable_sort.

A: Personally, I think your strategy class should have a "sort" method. That way, it can either call std::sort or not, as it sees fit. Whether as well as how becomes part of the sorting strategy.
Darios stable_sort answer is very good, if you can use it.
It is possible to do sorting based on item position in a vector, but it doesn't mean items won't move (many sort algorithms will basically scramble-then-resort your data), so you have to have some reliable way of determining where the items were when you started.
It's possible for the comparison to keep a mapping of current-position to original-position, but a lot of work. Ideally the logic needs to be built into the sort algorithm - not just the comparison - and that's essentially how stable_sort works.
Another problem - depending on the container - the order of (say) item addresses isn't always the order of the items.

A: if it is simply a vector you are talking about, perhaps you can get away with providing an interface that determines whether you should sort or not. vectors are not an ordered container, so you need to explicitly sort them. Just don't sort them at all.

A: There is no sort function which would keep the order of items based only on items' values. You need to provide more information to your Strategy, if it's possible.

A: A different approach might be to bring the semantics of your data to the container. Consider using boost::multi_index for different ways of access and ordering on the same data:
http://www.boost.org/doc/libs/1_42_0/libs/multi_index/doc/index.html


text:
Q: How to warn user if he/she accidentally close/leave session at website? We develop accounting system on a web with ASP.NET MVC and encountered this problem - if user is in the middle of the work and somehow manages to close browser all work is gone (and users are not geeks at all it did happen and will happen). Especially problematic at Chrome in Windows after they removed warning of closing tabs from philosophical reasons so now it will just shut down. We would like to be able to somehow catch this behavior. Also even when Firefox for example has warning that user is going to shut down his tabs - simple clicking the checkbox will remove it all again. So is it possible to keep track of this action to prevent user accidentally closing browser and lost all the work? Or is it even possible to do for example in Chrome? The solution would be simple warning window but it needs to show basically everytime if closing while our web application is alive. We don't want to keep session alive after closing browser for obvious security reasons. Also - it should work at Chrome, IE and Firefox. Thank you for your help.

A: you can try the below code:
window.onbeforeunload = function()
{
   return "Are you sure you want to exit";
}

A: If your front end is using MVVM such as AngularJS or Knockout, or any of the other popular binding libraries, consider a different approach to preventing the user from quitting the page.
In a client-side interval, serialize your view model and store it in local storage.
When the save/exit condition for the current page is met, clear the local storage.
If the page is loaded again, and there is something in local storage, this means that on the previous session, the browser was closed before saving - so deserialize the local storage object back into the viewmodel (use a unique key per page) - you can combine this with some UI that tells the user that their previous state has been restored, click ok to continue or start over to start again (which would reset the viewmodel)
I should add that you'll have to watch out for multiple simultaneous tabs, so you may want to work around this by making the key unique somehow, e.g. creating two invoices simultaneously.
This essentially provides an auto-save but client-side only.
You can combine this technique with using window.onBeforeUnload as per Tejinder's answer, but as you cannot style the "unload confirmation" prompt, providing an auto-resume is a much better experience.


text:
Q: Edge.js- -Access to DLL file doesn't work I want to access the OpenHardwareMonitorLib.dll file with node.js using the edge.js module and monitor the computer's CPU and GPU temperatures. I created a Node.js file in Visual Studio Code and added the DLL file to the references.
var edge = require('edge-js');

var add7 = edge.func({
    source: function() {/*

        using System;
        using System.Data;
        using System.Threading.Tasks;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using OpenHardwareMonitor.Hardware;

         public class Startup
        {

                public class UpdateVisitor : IVisitor
                {
                    public void VisitComputer(IComputer computer)
                    {
                        computer.Traverse(this);
                    }
                    public void VisitHardware(IHardware hardware)
                    {
                        hardware.Update();
                        foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
                    }
                    public void VisitSensor(ISensor sensor) { }
                    public void VisitParameter(IParameter parameter) { }
                }

                public async Task Invoke()
                {

                        while (true)
                        {
                            await Task.Run(() =>  GetSystemInfo());

                        }

                }

                static async void GetSystemInfo()
                {
                    UpdateVisitor updateVisitor = new UpdateVisitor();
                    Computer computer = new Computer();
                    computer.Open();
                    computer.CPUEnabled = true;
                    computer.Accept(updateVisitor);
                    for (int i = 0; i < computer.Hardware.Length; i++)
                    {
                        if (computer.Hardware[i].HardwareType == HardwareType.CPU)
                        {
                            for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
                            {
                                if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
                                        Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
                            }
                        }
                    }
                    computer.Close();
                }

        }

    */},
    references: [ 'System.Data.dll','OpenHardwareMonitorLib.dll']

});

I'm pretty sure the C# code works. I created an empty C# console application in Visual Studio and added the DLL file to the references. When I ran this C# code, I reached CPU temperatures without any problems. But in Visual Studio when I run it in my Nodejs project using edge-js, I get the following output;
'app.js' exited with code -1 (0xffffffff)

When I run it in Visual Studio Code, I can't get any output. I don't fully understand why it occurs. I would be glad if you help.
Visual Studio Code Output;


text:
Q: Cannot move out of `*X` which is behind a shared reference when using Box I understand the reason why this error is being raised, but not sure how I should go about fixing it. Ideally I would want to avoid using Copy.
fn get_random_samples<'a>(kmers: &[Box<str>], sample_size: usize) -> Vec<Box<str>> {
    let mut rng = rand::thread_rng();

    kmers
        .choose_multiple(&mut rng, sample_size)
        .map(|item| *item)
        .collect::<Vec<Box<str>>>()
}

This raises the compilation error:
error[E0507]: cannot move out of `*item` which is behind a shared reference
   --> src\lib.rs:384:21
    |
384 |         .map(|item| *item)
    |                     ^^^^^ move occurs because `*item` has type `Box<str>`, which does not implement the `Copy` trait

I've also tried:
fn get_random_samples<'a>(kmers: &[Box<str>], sample_size: usize) -> Vec<Box<str>> {
    let mut rng = rand::thread_rng();

    kmers
        .choose_multiple(&mut rng, sample_size)
        .copied()
        .collect::<Vec<Box<str>>>()
}

as learned from a previous question (Random sampling of a string slice), but this raises a different error:
error[E0277]: the trait bound `Box<str>: std::marker::Copy` is not satisfied
    --> src\lib.rs:384:10
     |
384  |         .copied()
     |          ^^^^^^ the trait `std::marker::Copy` is not implemented for `Box<str>`
     |
note: required by a bound in `std::iter::Iterator::copied`
    --> C:\Users\shant\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\core\src\iter\traits\iterator.rs:2987:12
     |
2987 |         T: Copy,
     |            ^^^^ required by this bound in `std::iter::Iterator::copied`

Both errors seem to point to the Copy trait which ideally I would like to avoid.
Any help would be appreciated!.
PS: Quite new to Rust, please do suggest if there's better ways to do this.

A: If you want to avoid copying/cloning, you need to return a reference. For example:
use rand::prelude::SliceRandom;
fn get_random_samples(kmers: &[Box<str>], sample_size: usize) -> Vec<&Box<str>> {
    let mut rng = rand::thread_rng();

    kmers
        .choose_multiple(&mut rng, sample_size)
        .collect()
}

Playground
or:
use rand::prelude::SliceRandom;
fn get_random_samples(kmers: &[Box<str>], sample_size: usize) -> Vec<&str> {
    let mut rng = rand::thread_rng();

    kmers.choose_multiple(&mut rng, sample_size).map(|e| e as &str).collect()
}

Playground


text:
Q: How to resolve the expected semicolon error in Java? I have the ";" expected error and I already tried to put the ";" but in vain. This is the code:
 public static XYZDataset createDataset(JTable table )
   {
    DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset();

    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
    double[][] ad = new double[nRow][1];
    double[][] ad1 = new double[nRow][1];
    double[][] ad2 = new double[nRow][1];
    double ad3[][]=null;

    for (int i = 0 ; i < nRow ; i++)
           {
              ad[i] = (double[]) dtm.getValueAt(i,1);
              ad1[i] = (double[]) dtm.getValueAt(i,2);
               ad2[i] = (double[]) dtm.getValueAt(i,3);
               ad3[][]={ad[i],ad1[i],ad2[i]}  ;
           }

      defaultxyzdataset.addSeries( "Series 1" , ad3 );
      return defaultxyzdataset;
   }

I have the error on this line: ad3[][]={ad[i],ad1[i],ad2[i]}

A: try
 public static XYZDataset createDataset(JTable table )
   {
    DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset();

    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
    double[][] ad = new double[nRow][1];
    double[][] ad1 = new double[nRow][1];
    double[][] ad2 = new double[nRow][1];
    double ad3[][][]= new double[nRow][3][1];

    for (int i = 0 ; i < nRow ; i++)
           {
               ad[i] = (double[]) dtm.getValueAt(i,1);
               ad1[i] = (double[]) dtm.getValueAt(i,2);
               ad2[i] = (double[]) dtm.getValueAt(i,3);
               ad3[i]={ad[i],ad1[i],ad2[i]} ;
           }

      defaultxyzdataset.addSeries( "Series 1" , ad3 );
      return defaultxyzdataset;
   }

Your current code is trying to assign an array to nothing really since ad3[][] has no interpretative meaning without some numbers in the [].

A: Array constants can only be used in array initializers; use this statement instead:
ad3 = new double[][]{ad[i],ad1[i],ad2[i]};

A: You can't use array constants after array initialization.  If you declare and initialize ad3 in the loop it would work or if you do this:
ad3= new double[][]{ad[i],ad1[i],ad2[i]}  ;

See this previous question for further discussion.

A: *

*First of all ad3 is not initialized .

*Secondly as far as i know you cannot add element to array like the
one you have done. ad3[][]={ad[i],ad1[i],ad2[i]}  ;

*If you want to do you can do like this:
        int [][] arr = new int [5][5];
        arr[1] = new int []{1,2,3,4,5};
         arr[2] = new int []{1,2,3,4,5};

A: The error is caused by the way you are assigning a value to ad3 inside the loop. Assuming that you really want to assign a new value to that array during for each iteration, you'll have to change that line as follows:
ad3 = new double[][] {ad[i],ad1[i],ad2[i]};
Please be aware though, that after the loop that means the contents of ad3 will be ad[nRow - 1], ad1[nRow - 1], and add[nRow - 1] - it is not clear why you are using a loop at all in that case.

A: I resolved the problem,
this is the new code

 public static XYZDataset createDataset(JTable table )
   {
    DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset();

    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();

    for (int i = 0 ; i < nRow ; i++)
           {
              double ad [ ] = { (double)dtm.getValueAt(i, 1)};
              double ad1 [ ] = { (double)dtm.getValueAt(i, 2)};
              double ad2 [ ] = { (double)dtm.getValueAt(i, 3)};
              double ad3[][]={ad,ad1,ad2}  ;
           }

      defaultxyzdataset.addSeries( "Series 1" , ad3 );
      return defaultxyzdataset;
   }


text:
Q: Error passing C array as char* function parameter I'm trying to make a simple code in c language (Stupid question, but I'm learning), I dont  understand that this code gives me an error ... I must be doing wrong, I can not know that I have to change...sorry for my English ... thanks in advance to all
#include <stdio.h>
#include <ctype.h>

char* to_up(char* str_);

int main()
{
    char any_phrase[] = "This is a phrase";
    printf("%s\n", to_up(any_phrase));
    printf("%s\n", to_up("this is another phrase"));
    return 0;
}

char* to_up(char* str_)
{
    int i;
    for (i=0; str_[i]; i++)
        str_[i] = toupper(str_[i]);
    return str_;
}

A: The reason for the error is that when you pass the string as "this is another phrase" on its own, as in not contained in a variable, the string is what's known as a string literal.  What this means, among other things, is that the string is constant: you simply are not allowed to modify.
To solve your problem you'd have to store the string in a variable so it is allowed to be modified by your to_up() function call since it modifies the contents of the string.

A: A string literal is usually in read-only memory.  As far as the standard is concerned, trying to modify it will result in undefined behaviour regardless of where it is in memory.  There have been many questions asked about this problem already.

A: In this call
printf("%s\n", to_up("this is another phrase"));

You are trying to modify a string literal.

A: The code compiles OK for me, but gives a bus error (core dump) at runtime.
The trouble is that a string literal can be stored in read-only memory, so you can't modify the literal string as your code does.  With enough compiler warnings enabled, your compiler will warn you (GCC requires -Wwrite-strings - at least, in GCC 4.4 and above).


text:
Q: Book where boy doesn't have magic but everyone else does I remembered reading a book about a boy who doesn't have magic while everyone does. His uncle is a famous wizard and helps him get into a wizard school. Later on, it Is revealed that the boy doesn't have magic because the uncle took it away when he was young.
Added: it was around 5 years ago when I read it. the cover of the book shows a little boy and on the background they have some flying pigs and castle-like structures.

A: I was looking for this as well. I believe the book is called Missing Magic by Emma Laybourn. They are flying sheep not pigs. It was published in 2012, which is two years off from your date, but otherwise matches.

Thanks to his influential uncle Kelver, Ned's gotten into an elite new school. But there's a problem—everyone there can do magic. And Ned? Not a lick. Amidst whispers of the terrifying Necromancers (rumored to be kidnapping unsuspecting kids!), Ned struggles to adjust to his new situation, avoid making enemies, and jump-start his magic skills, all with very little luck. Then, just as he's getting accustomed to having his hair turned into snakes and his books into bricks, the Necromancers strike! Ned and his classmates are kidnapped. But without magic, how can he possibly help them escape? Things can't get any worse—until they do.

TV Tropes has an entry on The Magic Goes Away that mentions the uncle as the person who stole Kelver's magic:

In the book Missing Magic, a young boy has to deal with being the only one without magic powers. When his uncle turns out to have been the Big Bad (after taking his powers and killing his father) his uncle uses the same spell and removes everyone's magic by accident. The boy comes to realize that eventually magic will return and someone will pioneer its discovery, long after everyone forgets it existed and moves on.

A: Although it's not an exact match, your question has some vague similarities to the Codex Alera series.

*

*Tavi is the central character of the books, and as the story starts, he indeed cannot use any of the magic known as furycrafting, even as every other human in the series can even to a limited degree

*His uncle Bernard is an earth and woodcrafter who leads the local steadholdt.  Not exactly famous but a solid leader, and he helps Tavi develop his other talents as much as he can, like his brain

*Tavi does get into an Academy through the patronage of the First Lord of Alera.  It is a school for training furycrafting, among other intellectual trainings.  He still can't do magic however.

*Long past these events, Tavi does eventually learn that ....

 his aunt Isana, who is actually his mother, at first unintentionally but then with more intent, surpressed all his fury ability and stunted his growth through watercrafting in a desperate bid to hide his identity.

A: Outcast: The Un-Magician by Christopher Golden

The most dangerous boy in the world? Timothy is a freak, a weakling, an impossibility. He's the only person in existence without magical powers and has spent his entire life hidden on a remote island. When Timothy is finally taken back to the city of this birth, he is fascinated by the current of magic that fuels the world, and mesmerized by the buildings and orbs that hang weightlessly in the sky. But he is also marked for death.
Assassins are watching his every move, and the government wants him destroyed. Timothy can't imagine what threat he could possible pose; after all, he wields no power in this world.
Or does he?

The cover does have a boy and some castle-like structures, and Timothy has no magic. His father was a magician. The book was released in 2004 (and according to some of the reviews, was based on an earlier book by the same author), so that would fit your timeframe. No flying pigs, though.


text:
Q: Dummy variable in the probability generating function I'm struggling to understand what the purpose of the dummy variable $t$ in the probability generating function is?
I know it takes a value between 0 and 1, and have heard it described as a 'relative ratio'. But physically what does it mean? Why, when this variable takes a value of 1, will the function also be equal to 1?
$G_{X} (t) = E (t^{x})$
$G_{X} (1) = 1$

A: I assume your question is about the probability generating function of a discrete random variable $X$ taking nonnegative integer values, defined as
$$G_X(t) = E(t^X) = \sum_{k \ge 0} \Pr(X = k)\, t^k.$$
Your second question on why $G_X(1) = 1$ is easy to answer: when $t=1$, we have
$$G_X(1) = E(1^X) = E(1) = 1$$
as $1^X$ is always $1$ no matter what the value of $X$. Or you can use the fact that
$$G_X(1) = \sum_{k \ge 0} \Pr(X = k) = 1$$
as probabilities must add up to $1$.

For your first question, the variable $t$ is used to encapsulate the entire probability distribution in a single function. It matters not so much for its physical meaning (that after all is why you're calling it a dummy variable), but for the fact that it enables a compact representation of the entire probability distribution in one function $G_X$.
All the information about the distribution of $X$ can be recovered from the function $G_X$; for instance $\Pr(X=k)$ can be recovered by asking "what is the coefficient of $t^k$ in $G_X(t)$?"
You may like to look at generating functions (see for example the fantastic book generatingfunctionology by Wilf) of which this is a special case. Given any sequence of numbers $a_0, a_1, a_2, a_3, \dots$, their generating function $A(t) = a_0 + a_1t + a_2t^2 + a_3 t^3 + \dots$ gives a (possibly) compact representation of the entire sequence as a single function $A$. As Wilf says in the first sentence on page 1 of the book, "A generating function is a clothesline on which we hang up a sequence of numbers for display". The purpose of the dummy variable $t$ is to provide that clothesline on which we attach the probabilities $\Pr(X=k)$.
A particular value of $t$ has (to the best of my knowledge) no special meaning beyond that; what matters the entire function (how it varies with varying $t$, etc.) Thus for instance differentiating $G_X(t)$ with respect to $t$ can help you find the expected value (and higher moments), taking the $k$th derivative at $0$ can help you find the coefficient of $t^k$, it converts sums of independent random variables to products of probability generating functions ($G_{X+Y}(t) = G_X(t)G_Y(t)$ if $X$ and $Y$ are independent), etc. It is, in short, a transform of the probability distribution into a different representation, that can be more convenient for certain purposes.


text:
Q: Final URL (after following all redirections) in the console This URL:
https://httpbin.org/absolute-redirect/3

redirects to:
https://httpbin.org/absolute-redirect/2

then redirects to:
https://httpbin.org/get

What shell command can I use to get the final URL?

A: I am using this at the moment:
curl -sS -L -I -o /dev/null https://httpbin.org/absolute-redirect/3  -w %{url_effective}'\n'

My first attempt is worth mentioning. It can be modified to display all redirections, if you remove this part tail -1:
curl -sS -v -o -L -I /dev/null https://httpbin.org/absolute-redirect/3 2>&1 | grep Locat | tail -1 | cut -c 13-3000


text: Q: Compile cvblob library in 32bit on 64bit OS Is there any way for me to compile the cvblob library in 32bit on a 64bit Debian OS? I tried to look for this in the cvblob documentation but couldnt find anything relevant.


text:
Q: Update Live Tile depending on tile size pinned by user I am facing a problem with Live Tiles in my UWP application. Microsoft provides different templates (MSDN) for different tile sizes to set the content but it also depends on the device how the content is displayed.
For example the wide tile can show more characters on a mobile device than on a desktop computer in a single row, but I want to use the most of the tile area for information display. Let's say the user has installed my app on a desktop computer and he has pinned the big square tile to his start menu. How can I detect the tile size to load the appropriate template? Basically I just want to use a different template depending on the tile the user has pinned (and then I want to handle the filling of the content depending on the used device, but I got that already covered).
Currently I am just using a wide template that does nothing if the user has pinned any other size than the wide one. If the user pinns the wide tile, it works. But I am struggling to find a generic solution for this issue. I'm using SheduledTileNotifications because my app only uses local data for the tile contents.
This is my code to update a tile with a given template:
public static void UpdatePrimaryTile(XmlDocument tileTemplate)
{
    var dt = DateTime.Now.AddSeconds(5);
    dt = DateTime.SpecifyKind(dt, DateTimeKind.Unspecified);
    var not = new ScheduledTileNotification(tileTemplate, new DateTimeOffset(dt, TimeZoneInfo.Local.BaseUtcOffset));
    var tu = TileUpdateManager.CreateTileUpdaterForApplication();
    tu.EnableNotificationQueue(true);
    tu.Clear();
    tu.AddToSchedule(not);
}

A: You should include all tile sizes in your tileTemplate, not just the wide tile. That way whatever the user chooses will have an appropriate tile to show.
Just showing the currently chosen tile template isn't sufficient since the user could change it after your notification fired.
If you look at the adaptive tile documentation at https://learn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-create-adaptive-tiles it says:

For a single tile notification XML payload, provide  elements for each tile size that you'd like to support, as shown in this example:

<tile>
  <visual>

    <binding template="TileSmall">
      <text>Small</text>
    </binding>

    <binding template="TileMedium">
      <text>Medium</text>
    </binding>

    <binding template="TileWide">
      <text>Wide</text>
    </binding>

    <binding template="TileLarge">
      <text>Large</text>
    </binding>

  </visual>
</tile>

The same applies to the Windows 8.1 templates as shown in Quickstart: Sending a tile update (XAML)

The user can resize your tile on the Start screen at any time, and there is no way for you to know which state (small, medium, wide, or large) the tile is in when you send a notification.


text:
Q: How can I tell if a control is disabled because of a parent container? I have a bug in a Windows Forms app that I have to fix.  There is a groupbox that contains some controls (a few labels, some DevXPress "SpinEdit"s, and some checkboxes).  The groupbox is disabled when the form is instantiated, which causes the controls inside to be disabled.  In certain cases, the user can press a toolbar button to enable those controls.  What I am seeing is that when I enable the groupbox, the controls inside don't re-enable.  If I loop through and enable them manually, the labels and checkboxes "work," but the SpinEdit's don't.  The up/down buttons work, but the text entry area is stubbornly disabled or readonly or something.  Inspecting the SpinEdit shows that everything should be fine for editing.
Is there any way to check to see if there is some container control that's keeping these controls disabled?


text:
Q: updating tkinter window (Python 3.4) Good Afternoon all,
I've been working on a contact-book program for a school project. I've got all of the underlying code complete. However I've decided to take it one step further and implement a basic interface. I am trying to display all of the contacts using the code snippet below:
    elif x==2:
    phonebook_data= open(data_path,mode='r',encoding = 'utf8')
    if os.stat(data_path)[6]==0:
        print("Your contact book is empty.")
    else:
        for line in phonebook_data:
            data= eval(line)
        for k,v in sorted(data.items()):
            x= (k + ": " + v)
            from tkinter import *
            root = Tk()
            root.title("Contacts")
            text = Text(root)
            text.insert('1.0', x)
            text.pack()
            text.update()
    root.mainloop()
    phonebook_data.close()

The program works, however every contact opens in a new window. I would like to display all of the same information in a single loop. I'm fairly new to tkinter and I apologize if the code is confusing at all. Any help would be greatly appreciated!!

A: First of all, the top of the snippet could be much more efficient:
phonebook_data= open(data_path,mode='r',encoding = 'utf8') should be changed to
phonebook_data = open(data_path).
Afterwards, just use:
contents = phonebook_data.read()
if contents == "":       # Can be shortened to `if not contents:`
    print("Your contact book is empty.")

And by the way, it's good practice to close the file as soon as you're done using it.
phonebook_data = open(data_path)
contents = phonebook_data.read()
phonebook_data.close()

if contents == "":
    print("Your contact book is empty.")

Now for your graphics issue. Firstly, you should consider whether or not you really need a graphical interface for this application. If so:
# Assuming that the contact book is formatted `Name` `Number` (split by a space)
name_number = []
for line in contents.split("\n"): # Get each line
    name, number = line.split()
    name_number.append(name + ": " + number) # Append a string of `Name`: `Number` to the list
name_number.sort() # Sort by name

root = Tk()
root.title("Contact Book")
text = Text(root)
text.pack(fill=BOTH)
text.insert("\n".join(name_number))
root.mainloop()

Considering how much I have shown you, it would probably be considered cheating for you to use it. Do some more research into the code though, it didn't seem like the algorithm would work in the first place.


text:
Q: Programatically access specific rows in List of CheckedTextView's - Android is it possible to programatically access specific rows in a list of CheckedTextViews to change the state of their textboxes?
my program has a listview which has several CheckedTextViews which the user can press to toggle state.
I want to save the state of the checkboxes when the user leaves the activity, so I have in my onPause method:
public void onPause(){
         super.onPause();
         SparseBooleanArray positions;
         positions = listView.getCheckedItemPositions();
         ListAdapter items = listView.getAdapter();
         int j = items.getCount();

         ArrayList<Long> ids = new ArrayList<Long>();
         for (int k =0; k < j;k++){
             if(positions.get(k)==true){
                 ids.add(items.getItemId(k));
             }
         }
         this.application.getServicesHelper().open();
         this.application.getServicesHelper().storeServices(ids,visit_id);
         this.application.getServicesHelper().close();
     }

which very simply iterates the list view, adds the checked items to an ArrayList and then saves that list of ids to the database.
My problem lise in trying to reset the list once a user goes back to that activity.
so far in my onStart method, I recall the checked items from the database, but I do not know how to march the ids returned to the listview elements. can I do something like:
listView.getElementById(id_from_database).setChecked?
I know I cant use getElementById but I have it here to show what I mean
Thanks in advance
Kevin

A: You can call
listView.setItemChecked(int position, boolean value)

A: This is what Ive ended up doing.. but it seems like a complete hack.
Basically I have to set up a double for loop.. one to iterate through my list elements, and one to iterate through the cursor that I have retreived my check list state (a simply array of ids of elements that were checked when state was last saved)
my outer for iterates through the list elements checking each id against a loop through the list of ids to be set as checked. if they equal each other then set that item as checked.
    // mAdapter is contains the list of elements I want to display in my list.
ServiceList.this.setListAdapter(mAdapter);

        // Getting a list of element Ids that had been previously checked by the user. getState is a function I have defined in my ServicesAdapter file.

    Cursor state = ServiceList.this.application.getServicesHelper().getState(visit_id);
    int checks = state.getCount();
    int check_service;
    int c = mAdapter.getCount();
    if(checks>0){
        state.moveToFirst();
        for (int i=0; i<checks; i++) {
            // set check_service = the next id to be checked
            check_service = state.getInt(0);
            for(int p=0;p<c;p++){

                if(mAdapter.getItemId(p)==check_service){
                        // we have found an id that needs to be checked. 'p' corresponds to its position in my listView
                    listView.setItemChecked(p,true);
                    break;
                }
            }
            state.moveToNext();
        }
    }
    ServiceList.this.application.getServicesHelper().close();

Please tell me there is a more efficient way of achieving this!!
Thanks
Kevin


text:
Q: How to prevent OAuth asking sign-in for each run of python script I can access to youtube analytics by following the v2 sample code at https://github.com/youtube/api-samples/blob/master/python/yt_analytics_v2.py.
And my previous code (youtube api v1) successfully integrated with oauth2client's Storage so each time when my python script is run, I do not need to go to browser, choosing the account for granting the permission.
But when migrating to youtube api v2 I do not find any docs providing a working solution for preventing asking me granting permission by sign-in from browser, including https://developers.google.com/api-client-library/python/auth/installed-app and google/ duck duck go search.
It seems because the v2 code executes run_console() so the app keeps asking me to sign-in with a specific account.
Previously my code exploits oauth2client's Storage, etc APIs (it was working without a problem).
flags = tools.argparser.parse_args(args=[])
flags.noauth_local_webserver = True

flow = flow_from_clientsecrets(...)
storage = Storage("%s.v1.json" % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, flags)
...
youtube = build(...)

I tried borrowing the code (for my v2 python script) from How do I use google.auth instead of oauth2client in Python to get access to my Google Calendar with code snippet similar to
creds = get_saved_credentials()
if not creds:
    creds = get_credentials_via_oauth()
youtube = get_service(creds)

But it still asks me to choose an account (even I've chosen in the previous round) each time when executing the python script.
How can I fix this (prevent the python script asking me to choose account to sign in from browser)?
Thanks


text:
Q: Error running pseudo-distributed hbase I installed Hadoop and HBase in Mac OSX 10.9 through Homebrew. The version of Hadoop is 2.5.1, and the version of HBase is 0.98.6.1.
After I started HDFS, and try to start HBase, I got these errors:

Error: Could not find or load main class org.apache.hadoop.hbase.util.HBaseConfTool
Error: Could not find or load main class org.apache.hadoop.hbase.zookeeper.ZKServerTool
starting master, logging to /usr/local/Cellar/hbase/0.98.6.1/logs/hbase-lsphate-master-Ethans-MacBook-Pro.local.out
Error: Could not find or load main class org.apache.hadoop.hbase.master.HMaster
localhost: starting regionserver, logging to /usr/local/Cellar/hbase/0.98.6.1/logs/hbase-lsphate-regionserver-Ethans-MacBook-Pro.local.out
localhost: Error: Could not find or load main class org.apache.hadoop.hbase.regionserver.HRegionServer

Is there any suggestion of this error? I've googled it and tried any solution I can find but they were all no use.

A: Your's HBASE_HOME might not be pointing to the correct location. Try exporting HBASE_HOME and HBASE_CONF_DIR like
export HBASE_HOME=/usr/local/Cellar/hbase/0.98.6.1/libexec
export HBASE_CONF_DIR=$HBASE_HOME/conf
Thanks.


text:
Q: Lower than low level common bsd sockets How do you do low low level sockets in C, example: actually sending a SYN.

A: Raw sockets are your friend.
There have been some links to useful information on this question.
Also consult Chapter 25 "Raw sockets" of Steven's "Unix Network Programming"
If you're attempting cross platform code you may find libpcap a useful alternative.

A: You want to use raw sockets.  In *nix, you need to be root to be able to create raw sockets.  I'm not sure if it's possible in Windows.

A: What you actually want is a raw socket ... you can completely control the headers and flags with the raw socket interface, but programming them is much more challenging.  Here's a great tutorial to get you started: http://www.cs.binghamton.edu/~steflik/cs455/rawip.txt.

A: I suspect the nmap sources would be an excellent place to look.