text:
Q: Date_format validation Laravel i want to make date_format validation but only for 1 request(who i want to edit). Now when i try to submit i get multiple errors, but i edit only 1 request. How i can do it? This is screen from browser https://i.imgur.com/2f5qaY7.png and this is code in controller
public function do_event(Request $request)
{
    $this->validate($request,[
        'event'=>'unique:XWEB.XWEB_EVENT,event',
        'everyday'=>'date_format:H:i',
        'monday'=>'date_format:H:i',
        'tuesday'=>'date_format:H:i',
        'wednesday'=>'date_format:H:i',
        'thursday'=>'date_format:H:i',
        'friday'=>'date_format:H:i',
        'saturday'=>'date_format:H:i',
        'sunday'=>'date_format:H:i',

    ]);

    $decode = json_decode(file_get_contents(storage_path() . "/app/public/event_config.json"), true);

    foreach ($decode['events']['event_timers'] as $value)
    {
        $name = $request->event;
        $days = $request->days;
        if(in_array(0, $days)){
            $days = 0;
        }
        if($days == 0){
            $time = $request->everyday;
        }
        if(!is_array($days)){
            $config = ['name' => $name, 'days' => $time];
        } else {
            $d = [];
            foreach ($days as $key => $values) {
                if ($values == 1)
                    $d[$values] = $request->monday;
                if ($values == 2)
                    $d[$values] = $request->tuesday;
                if ($values == 3)
                    $d[$values] = $request->wednesday;
                if ($values == 4)
                    $d[$values] = $request->thursday;
                if ($values == 5)
                    $d[$values] = $request->friday;
                if ($values == 6)
                    $d[$values] = $request->saturday;
                if ($values == 7)
                    $d[$values] = $request->sunday;
            }

            $config = ['name' => $name, 'days' => $d];
        }
    }
    $new_config = array_push($decode['events']['event_timers'], $config);
    $newJsonString = json_encode($decode);
    file_put_contents(storage_path() . "/app/public/event_config.json", $newJsonString);
    return redirect()->back()->withSuccess('You have added this event successfully!');
}


text:
Q: linq objects grouping I have people object and poeple have property group that make them belong to different groups.
I want to get List and put it in an object GrouppedPeople, in which there would be List coll. One coll element contain only people that belong to same group.
So if I had 3 people:
List<People>(){new People{Name="Test", Group = "Group1"},
               new People{Name="SameGroup", Group = "Group1"},
               new People{Name="Other", Group = "OtherGroup"}}

I need to have a collection of 2 GrouppedPeople. First will contain Test and SameGroup, and second will contain Other (groupped by Group property). Im trying to do this using linq.
I need results to be of type List. GrouppedPeople is a class that have only one property of type List and all poeple are from the same group.
Ive came out with something like this:
from oneGroup in mates
                   group oneGroup by oneGroup.pGroupName into g
                   select g;

Its working fine, but the result object is not strongly typed. And Id like to have List as the result. Is there a way to get it from that anonymous object type? Any other ways to get this all with linq and keep strong typing?

A: This will return List of anonymous type objects:
var result = (from oneGroup in mates
                   group oneGroup by oneGroup.pGroupName into g
                   select g).ToList();

But if you want to return specific type objects you should create new class with required properties:
public class MateGroup
{
 public string Name {get;set;}
}

var result = (from oneGroup in mates
                   group oneGroup by oneGroup.pGroupName into g
                   select new MateGroup(){ Name =  g.<field_name>}).ToList();

UPD:
According to your comment please try the following:
var result = (from oneGroup in mates
                   group oneGroup by oneGroup.pGroupName into g
                   select new GrouppedPeople(){ People =  g.ToList()}).ToList();

A: What you will get is an IEnumerable<IGrouping<string, People>>. The IGrouping<TKey, TElement> interface has a Key containing the value that you grouped by (in your case a string containing a value from the Group property in a People object), and you can enumerate over it to get the items belonging to the group:
IEnumerable<IGrouping<string, People>> result = from oneGroup in mates
                group oneGroup by oneGroup.Group into g
                select g;

foreach (IGrouping<string, People> grouping in result)
{
    Console.WriteLine("Group: {0}", grouping.Key);
    foreach (People people in grouping)
    {
        Console.WriteLine(" - {0}", people.Name);
    }
}

Resulting output (based in your sample data):
Group: Group1
 - Test
 - SameGroup
Group: OtherGroup
 - Other

A: I prefer common C# syntax to write a LINQ query it's clearer than the simple query form.
You can use result selector to resolve grouping result as a typed object.
var resultList = mates
    .GroupBy(p => p.Group, (g, p) => new B() { Group = g, People = p.ToList() })
    .ToList();

Complete test console application code:
class People
{
    public string Name;
    public string Group;
}

class GroupedPeople
{
    public string Group;
    public List<People> People;
}

class Program
{
    static void Main(string[] args)
    {
        var mates = new List<People>()
        {
            new People{Name="Test", Group = "Group1"},
            new People{Name="SameGroup", Group = "Group1"},
            new People{Name="Other", Group = "OtherGroup"}
        };

        var resultList = mates
            .GroupBy(p => p.Group, (g, p) => new GroupedPeople() { Group = g, People = p.ToList() })
            .ToList();
    }
}

The GroupBy call require two arguments:

*

*p => p.Group - that lambda (anonymous method) used to return the grouping key

*(g, p) => new
GroupedPeople() { Group = g, People
= p.ToList() }
That lambda used to create GroupedPeople object based on group parameters, first argument is a grouping key that selected by first lambda, second argument is enumeration with items related to the current group.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stripe Volume-based Subscription How can I model volume-based subscriptions in stripe(.com)? Invoice are not sufficient, because there is a cap of 2000 items per invoice. We are a CDN and charge per GB. Ideally, there would be the option to increase a counter for an invoice item like (OnDemand Traffic - Amount 1500 - Price per Item: X cents). I looked very deeply into the docs but there is no example for this use case. Another way would be to model the GB traffic as quantity on a sub but this seems not very ... correct. Does stripe simply not have any option for volume-based pricing? Thanks!

A: Stripe supports metered billing by doing something like this:

*

*Subscribe your customer to a $0/month plan (or whatever billing internal you want to use).

*At the end of each billing period, a new invoice will be created and an invoice.created event will be sent to your webhook endpoint.

*Create an invoice item (or more than one) with the amount that needs to be billed to the customer for the past billing period.
After approximately one hour, the invoice will be closed and payment will be attempted for the invoice's total amount, which includes the plan's base cost ($0) plus the amount of all the items you created for this invoice.
Basically, the idea is that you only create the invoice item(s) at the last moment, when you already know exactly how much the customer needs to be billed for.
You can read more about invoices here: https://stripe.com/docs/subscriptions/invoices.


text:
Q: D drive not showing My hard disk which under Windows 7 was separated into 2 partitions: C (system part) and D. I keep my movies, music and files on D and use C for installed programs. When I installed Ubuntu 16.04, I selected free space partition as Linux's system directory. After installation however, the D partition completely disappeared. I can still see my C, but D is not visible on Windows and Linux. In Windows' disk manager, it is showing some 293 GB unallocated space, while on Linux it shows as a Linux filesystem. I am very much worried about my data which was on D. I want my data back. I can't understand what's going on and will be really thankful for any replies.
Here's a screenshot if it helps somehow:

A: Looks like you formatted your msdos d partition into a ext4 filesystem when you installed Ubuntu, unless you remember setting up another partition specifically to install Ubuntu into when you were installing?


text:
Q: android studio Arraylist sort by descending order I have a custom listview which fetch data from firebasedatabase ,question is how im i able to sort my arraylist ex. "1 alexander" , "500 Airene" , "3 Airene","200 Aiexa"
Expected output :
500 Airene
200 Aiexa
3 Airene
1 Alexander
Im fetching and sorting it this way
 FirebaseDatabase database = FirebaseDatabase.getInstance();
        database.getReference()
                .child("Users").child("Displayname")
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()){

                            System.out.println(snapshot.getKey());

                            Map<String, Object> map =(Map<String, Object>) snapshot.getValue();

                            for (Map.Entry<String, Object> entry : map.entrySet()){

                                System.out.println(entry.getKey());

                                System.out.println(entry.getValue().toString());
                                Cred = (String) entry.getValue();
                                int numberOfUsers = (int) dataSnapshot.getChildrenCount();

                                UsersNumber.setText("Total Users : "+String.valueOf(numberOfUsers));

                                professions = new String[numberOfUsers];
                                Prof.add(Cred);
                                professions = new String[Prof.size()];
                                Prof.toArray(professions);

                                friend = snapshot.getKey();
                                names = new String[numberOfUsers];
                                Usersname.add(Cred+"  "+friend);
                                names = new String[Usersname.size()];
                                Usersname.toArray(names);
                                names = new String[Usersname.size()];
                                Usersname.toArray(names);

                                customListView=(ListView)findViewById(R.id.custom_list_view);
                                userInfos=new ArrayList<>();
                                Arrays.sort(names, Collections.reverseOrder());
                                //Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
                               // Arrays.sort(professions, String.CASE_INSENSITIVE_ORDER);
                                customListAdapter=new CustomListAdapter(userInfos,MainActivityCustonlistViewnew.this);
                                customListView.setAdapter(customListAdapter);
                                getDatas();
                             //   Toast.makeText(MainActivityCustonlistViewnew.this,String.valueOf(numberOfUsers) , Toast.LENGTH_SHORT).show();

                                customListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                                    //    Toast.makeText(MainActivityCustonlistViewnew.this, "Name : " + names[i] + "\n Profession : " + professions[i], Toast.LENGTH_SHORT).show();

                                    }
                                });

                            }

                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

But when using this code my output is :
500 Airene
3 Airene
200 Aiexa
1 Alexander
Arrays.sort(names, Collections.reverseOrder());
is not working for me may be, because  " number and alphabet" are combine as string"??
Usersname.add(Cred+"  "+friend);

A: Here is a custom comparator that meets your need:
String[] mArray = new String[] {
        "1 alexander",
        "500 Airene",
        "3 Airene",
        "200 Aiexa"
};

Comparator comparator = new Comparator<String>() {
       @Override
            public int compare(String o1, String o2) {
                String num1 = o1.split(" ")[0];
                String num2 = o2.split(" ")[0];
                return Integer.parseInt(num2) - Integer.parseInt(num1);
            }
 };
 Arrays.sort(mArray, comparator);
 System.out.println(Arrays.toString(mArray));

This outputs:
[500 Airene, 200 Aiexa, 3 Airene, 1 alexander]
This will work assuming that all of your strings has the format: "<integer> <letters>"


text:
Q: Can I add a char to a variable specified position within a string? OK, this is the line I am working on:
newstring.charAt(w) += p;

trying to add a character/char (p) to the string 'newstring' at a particular position within the string which is defined by int 'w'. Is this possible?

A: Strings are immutable in Java, so the answer is no. But there are many ways around it. The easiest is to create a StringBuilder and use the setCharAt() method. Or insert() if you want to insert a new character at a given position.
If you make multiple modifications to your string, you can (and indeed should) reuse your StringBuilder.

A: Well, you can't modify your string, because Strings are immutable in Java. If you try to change the string, you will get a new string object as a result.
Now, you can use String#substring method for that, using which you can get new string which is generated by some concatenation of substring of original string.: -
str = str.substring(0, w) + "p" + str.substring(w);

But, of course, using StringBuilder as specified in @biziclop's answer is the best approach you can follow.


text:
Q: Tracking stock prices and email alerts I have a google spreadsheet which helps us to track some stocks prices from the NASDAQ and DOWJONES. When I open the spreadsheet the prices automatically refresh via google finance built-in functions.
That is, for instance, the Apple price in a certain cell:
=GoogleFinance("AAPL";"price")

So far so good. Now we have a target buying price for each value and when the price falls below our target price we get an alert. I have written a script so that when this happens it sends me an email notification. Moreover, I have also configured a time-driven trigger which executes the script every 5 minutes.
But WHAT I really need is the WHOLE spreadsheet to open every 5 minutes not just only the script so that the Google finance funcions load and get the updated stock prices.
Is there a way to do that?
Not sure if this is the best approaching for a stock tracking spreadsheet so any ideas will be highly appreciated.

A: A standalone script will open a spreadsheet but it does not wait for the functions like GoogleFinance to complete so you may need to put in an explicit wait or loop until complete


text:
Q: Maya Python/Mel : Retrieve name of last object deleted Was wondering if it is possible to retrieve the name of the last object deleted.
I have looked into listHistory, but that seems to list the history of a selected or named object. I have also looked into undoHistory printqueue, which prints out the undo history into the script editor, but i can't retrieve that information from the console.
Any ideas? I've looked around and can't find any info on this. Thanks in advance.

A: You can get the list with:
undoInfo -q -pq;

There are a few really really good use cases for scalping Maya undo. Such as determining selection order after the fact. In any case it may be difficult to know what it actually was form the queue so you may need to undo and redo to get what the deleted object was.
So this may or may not work, mileage may vary.
As a side note since your restoring stuff why not save the object list at time of save. The order is going to be the same (ensured), so you can see the changes in the end and deletions as missing objects. See the objects in in a plain ls are in creation order. You can use this for rudimentary diff from import to import for example. Same works for deletions.

A: Catching any individual deletion after the fact is not possible. However you can stick an attributeDeleted scriptJob on objects you want to monitor - it will fire when they are deleted.  If you really want to catch every object, a scriptJob listening for the event DagObjectCreated will let you hook the other scriptJob to each new object - however that's not a good idea most of the time, since it will create a ton of scriptJobs in your scene (plus you'd have to also loop through the scene on load and attach the same deletion callback to existing objects as well...)
import maya.cmds as cmds
from functools import partial

def objectDeleted(obj):
    print "%s was deleted" % obj

def catch_deletion(obj):
   cmds.scriptJob ( attributeDeleted = ( (obj + ".tx"), partial(objectDeleted, obj) ) )

catch_deletion('pCube1')


text:
Q: Seconds to Time in XSLT I'm not asking a question actually.  I signed up stackoverflow to give something back to a community that has helped me so many times.
If you are using XSLT 1.0 there are no built-in time calculations.  I came up with this to convert seconds into minutes and hours.  I hope this helps someone!
<xsl:template name="format-duration">
  <xsl:param name="value" />

  <xsl:variable name="minutes" select="floor($value div 60) mod 60" />
  <xsl:variable name="seconds" select="$value mod 60" />
  <xsl:variable name="hours" select="floor($value div 3600)" />

  <xsl:if test="$hours">
    <xsl:if test="$hours < 10">
      <xsl:text>0</xsl:text>
    </xsl:if>
    <xsl:value-of select="$hours" />

    <xsl:text>:</xsl:text>
  </xsl:if>

  <xsl:if test="$minutes">
    <xsl:if test="$minutes < 10">
      <xsl:text>0</xsl:text>
    </xsl:if>
    <xsl:value-of select="$minutes" />
    <xsl:text></xsl:text>
  </xsl:if>

  <xsl:if test="$minutes and $seconds">
    <xsl:text>:</xsl:text>
  </xsl:if>

  <xsl:if test="$seconds">
    <xsl:value-of select="$seconds" />
    <xsl:text></xsl:text>
  </xsl:if>
</xsl:template>

EDIT:
  Do you have any other methods to achieve the same?

A: Firt of all, thank you for your contribution. There are, however, a few issues with this implementation. The seconds output doesn't take the leading 0 into account, but even if that's fixed, the output can be ambiguous if any of the figures happens to be 0. For example, the inputs 36005, 605, and 36300 all produce the result 10:05.
Likewise if two of the figures happen to be zero.  The input 36000 produces the output 10:, and the inputs 600 and 10 both produce the result 10.
Here is how I would go about implementing this functionality:
  <xsl:template name="format-duration">
    <xsl:param name="value" select="." />
    <xsl:param name="alwaysIncludeHours" select="false()" />
    <xsl:param name="includeSeconds" select="true()" />

    <xsl:if test="$value > 3600 or $alwaysIncludeHours">
      <xsl:value-of select="concat(format-number($value div 3600, '00'), ':')"/>
    </xsl:if>

    <xsl:value-of select="format-number(floor($value div 60) mod 60, '00')" />

    <xsl:if test="$includeSeconds">
      <xsl:value-of select="concat(':', format-number($value mod 60, '00'))" />
    </xsl:if>
  </xsl:template>

This way, hours are only displayed if they are non-zero or optionally turned on, and seconds are included by default, but can be optionally omitted by using the parameter values. This should reduce the ambiguity about what a time is supposed to represent.
It also allows omitting the value parameter if the value you want to format is the current context node.

A: Converting number of seconds to time (HH:MM:SS) in XSLT 1.0:
<xsl:template name="seconds-to-time">
    <xsl:param name="seconds"/>
    <xsl:variable name="h" select="floor($seconds div 3600)"/>
    <xsl:variable name="m" select="floor($seconds div 60) mod 60"/>
    <xsl:variable name="s" select="$seconds mod 60"/>

    <xsl:value-of select="format-number($h, '00')" />
    <xsl:value-of select="format-number($m, ':00')" />
    <xsl:value-of select="format-number($s, ':00')" />
</xsl:template>


text:
Q: PSET 2: Vigenere Cipher partially working? I have created the following code as an answer to CS50x PSET2: Vigenere and it works to some extent however when running through check50 I get some errors listed below:
:) vigenere.c exists.
:) vigenere.c compiles.
:) encrypts "a" as "a" using "a" as keyword
:( encrypts "barfoo" as "caqgon" using "baz" as keyword - output not valid ASCII text
:( encrypts "BaRFoo" as "CaQGon" using "BaZ" as keyword - output not valid ASCII text
:) encrypts "BARFOO" as "CAQGON" using "BAZ" as keyword
:( encrypts "world!$?" as "xoqmd!$?" using "baz" as keyword- output not valid ASCII text
:( encrypts "hello, world!" as "iekmo, vprke!" using "baz" as keyword- output not valid ASCII text
:) handles lack of argv[1]
:) handles argc > 2
:( rejects "Hax0r2" as keyword - timed out while waiting for program to exit

What seems to be happening is where the key contains a high value (i.e z/Z) it causes the code to skip to the next line and miss out what appears to be random sequences. eg. in the first word of the string it missed out the 3rd character, then the second word it misses the 3rd and 4th and then the third word the 1st. I just can't understand what is happening.
I have used printf to ensure that all the variables being set and passed into functions are correct at runtime. The functions themselves are returning the correct responses (except validation of Hax0r2). I have tried debugging by comparing results to an online vigenere cipher tool.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int Validate1(int argc);
int Validate2(string argv);
void Cypher(string x);
void KeyCalc(string argv);

string MESSAGE;
int LENGTH;
int *KEY;
int COUNTER = 0;

int main(int argc, string argv[])
{
    //Check if right amount of arguments are supplied
    int Val1 = Validate1(argc);

    if (Val1 == 0)
    {
        //Check if argument is a string of chars
        int Val2 = Validate2(argv[1]);

        if (Val2 == 0)
        {
            //get the string length
            LENGTH = strlen(argv[1]);

            //Dynamically update KEY array length
            KEY = (int *)malloc(LENGTH * sizeof(*KEY));
            if (KEY == NULL)
            {
                fprintf(stderr, "malloc failed\n");
            }

            //calculate the key
            KeyCalc(argv[1]);

            //get the message from the user to be encrypted
            MESSAGE = get_string("plaintext: ");
            printf("ciphertext: ");

            //encrypt message from user
            Cypher(argv[1]);
            free(KEY);
            return 0;
        }
        else
        {
            //validation failed
            printf("Usage: ./vigenere keyword\n");
            return 1;
        }
    }
    else
    {
        //validation failed
        printf("Usage: ./vigenere keyword\n");
        return 1;
    }
}

//Validate the number of arguments supplied
int Validate1(int argc)
{
    if (argc != 2)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

//Validate the argument is a string
int Validate2(string argv)
{
    int k = 0;

    //loop through all characters in argument line string and check if alphabetic
    for (int i = 0; i < LENGTH; i++)
    {
        if isalpha(argv[i])
        {
            //Do Nothing
        }
        else
        {
            k++;
        }
    }

    //k counts the number of non-alphabetic characters, so if > 0 then invalid input
    if (k > 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

void Cypher(string x)
{
    //identify the length of the message to be coded
    int Mlength = strlen(MESSAGE);

    //identify the length of the key
    int Slen = strlen(x);

    //cycle through all characters in message supplied by user
    for (int i = 0; i < Mlength; i++)
    {
        // loop through key
        if (COUNTER > Slen - 1)
        {
            COUNTER = 0;
        }
        //check if the character is alphabetic
        if (isalpha(MESSAGE[i]))
        {
            //convert the character to ASCII int value
            char l = MESSAGE[i];

            //add key value to message value and wrap around ascii mapping
            if (isupper(MESSAGE[i]))
            {
                l = l + KEY[COUNTER];
                if (l > 'Z')
                {
                    l = l - 26;
                }
            }
            else
            {
                l = l + KEY[COUNTER];
                if (l > 'z')
                {
                    l = l - 26;
                }
            }

            //convert value back into character and store in array
            MESSAGE[i] = (char) l;
            // print character
            printf("%c", MESSAGE[i]);
            COUNTER++;
        }
        else
        {
            //character is 'numeric' or 'symbol' or 'space' just display it
            printf("%c", MESSAGE[i]);
        }
    }
    printf("\n");
}

void KeyCalc(string argv)
{
    //convert key entry to values A/a = 0 to Z/z = 26
    for (int i = 0; i < LENGTH; i++)
    {
        char k = argv[i];
        if (islower(argv[i]))
        {
            KEY[i] = k - 'a';
        }
        else
        {
            KEY[i] = k - 'A';
        }
    }
}

*

*encrypts "barfoo" as "caqgon" using "baz" as keyword

*encrypts "BaRFoo" as "CaQGon" using "BaZ" as keyword

*encrypts "world!$?" as "xoqmd!$?" using "baz" as keyword

*encrypts "hello, world!" as "iekmo, vprke!" using "baz" as keyword

*rejects "Hax0r2" as keyword

A: From the spec for the caesar pset:

...Caesar's algorithm (i.e., cipher) encrypts messages by
  "rotating" each letter by k positions. More formally, if p is some
  plaintext (i.e., an unencrypted message), pi is the ith character in
  p, and k is a secret key (i.e., a non-negative integer), then each
  letter, ci, in the ciphertext, c, is computed as
ci = (pi + k) % 26

This algorithm (in either "case") does not do that:
 l = l + KEY[COUNTER];
                if (l > 'Z')
                {
                    l = l - 26;
                }

This walkthrough starting at 9:30 is a good primer on how to implement the "shift".
The proximate cause of the problem in this code is that this l = l + KEY[COUNTER];  can yield a result outside the ascii range. In the CS50 implementation, char defaults to a signed char. So, for example, 'r' + 'z' (as in "barfoo" ciphered with "baz") will yield -117.


text:
Q: Excel, split one cell into other specific cells based on the value from the first cell I wan't to split a cell with data, into other cells, based on the first data in the original cell. The data from the original cell looks like this (all in the same cell):
Field95-4,Field97-4,Field98-0,Field100-2,Field103-0,Field105-3,Field107-4,Field109-4,Field110-2,Field111-0,Field112-0,Field113-192,Field114-87,Field115-0,Field116-0,Field117-60

It should be split by "," and I found out that I could do that with a script:
Private Sub CommandButton1_Click()
Dim X As Variant
X = Split(Range("A1").Value, ",")
Range("A1").Resize(UBound(X) - LBound(X) + 1).Value = Application.Transpose(X)
End Sub

Then the result is like this:
Field95-4
Field97-4
Field98-0
Field100-2
Field103-0
Field105-3
Field107-4
Field109-4
Field110-2
Field111-0
Field112-0
Field113-192
Field114-87
Field115-0
Field116-0
Field117-60

Now it should look for a cell containing the fieldnumber:
There is a cell containing the text: Field95, and a field with Field97 etc. Then I want to replace the text with the result: Field95 should be replaced by 4, and Field97 should be replaced with 4. etc.
This should be the endresult

I know it's much to ask, but I'we tried a lot, and I can't get it to work.
I'm looking forward to your answers. Thanks in advance!
UPDATE:
This is an excel file I uploaded, so you can see what my question is about.
link
UPDATE 2:
Maybe this, combined with an IF statement could be used?
Sub UpdateWhole()
With ActiveSheet.UsedRange
.Replace "A1", "System", xlWhole
.Replace "A2", "System", xlWhole
.Replace "A3", "System", xlWhole
.Replace "B1", "ACC", xlWhole
.Replace "B2", "ACC", xlWhole
End With
End Sub

I don't know if that's an option?

A: How about:
Sub RedHawk()
    Dim X As Variant
    X = Split(Range("A1").Value, ",")
    Range("A1").Resize(UBound(X) - LBound(X) + 1).Value = Application.Transpose(X)
    For i = LBound(X) + 1 To UBound(X) + 1
        Cells(i, 1).Value = Split(Cells(i, 1).Value, "-")(1)
    Next i
End Sub


text:
Q: Ruby on Rails - Find by SQL adding apostrophes I have wrote a SQL query which I am using in my model, provided below:
Tag.find_by_sql(["SELECT tags.id, tags.name, count(*) AS count FROM tags
    INNER JOIN taggings ON tags.id = taggings.tag_id
    WHERE
    (taggings.taggable_type = 'Discussion' AND taggings.taggable_id IN (SELECT id FROM  `discussions` WHERE discussions.group_id = ?))
     GROUP BY tag_id ORDER BY ? LIMIT ?;", self.id, self.id, self.id, self.id, order, limit])

This works fine and pulls out the required tags.  However the tags do  not order correctly.  I noticed in the server console that the query has apostrophes around the order statement like so:
ORDER BY 'count desc'

When I remove the apostrophes, like so:
ORDER BY count desc

and run the query manually it pulls the tags in the correct order.  Is there a way to stop the apostrophes being added to the query?
Cheers
Tony

A: the reason is because you have parameterized the column name
ORDER BY ?

The value you have pass has been sanitized that's why it becomes 'count desc'.
You cannot pass column names and tables name by design. The only way is to concatenate the column name within the string.


text:
Q: Streaming of mp3 files I need a lightweight module that can stream a mp3 file from an HTTP server, play it on speakers, and allow seeking.
I'll write the GUI part, I just need a very simple backend to do something like this:
obj = MediaSource(r'http://myserver.com/my_song.mp3')
obj.play()
obj.seek(30)


text:
Q: Getting bad request with CURL in PHP posting XML data I am using PHP CURL to post some xml data to another server using that IP, i fullfilled all the requirements for making it work, but still getting an error of "BAD REQUEST".
Have a look on the code below.
 $var2 ="<doc><item>Some content.</item></doc>";
    $url = "server IP";
    $header  = "POST HTTP/1.1 \r\n";
    $header .= "Content-type: text/xml \r\n";
    $header .= "Content-length: ".strlen($var2)." \r\n";
    $header .= "Content-transfer-encoding: text \r\n";
    $header .= "Connection: close \r\n\r\n";
    $header .= $var2;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 4);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $var2);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);

    // Get Response
    $data = curl_exec($ch);

    if(curl_errno($ch))

        print curl_error($ch);
    else
        curl_close($ch);

    echo  $data;

A: First, you are using this as request-line :
$header  = "POST HTTP/1.1 \r\n";

According to the HTTP 1.1 RFC, the **Request-Line** should look like this :
Request-Line   = Method SP Request-URI SP HTTP-Version CRLF

So, it seems you should add an URI between POST and HTTP/1.1
(But, before coding that, read what I've written in the next paragraphs of my answer)

Then, you are passing a lot of things as CURLOPT_CUSTOMREQUEST.
I don't think you can pass all those header using that option (quoting) :

Valid values are things like "GET", "POST", "CONNECT" and so on;
  i.e. Do not enter a whole HTTP request line here. For
  instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be
  incorrect.

If you want to specify custom headers (it seems you do), you should use the CURLOPT_HTTPHEADER option, instead of CURLOPT_CUSTOMREQUEST (quoting the documentation of the first one) :

An array of HTTP header fields to set, in the format
  array('Content-type: text/plain', 'Content-length: 100')


text:
Q: How to assign value to destination property on aftermap in automapper I have these classes
public class Student
{
    public int StudentId { get; set; }
    public int Name { get; set; }
    public string SubjectIds { get; set; } //Comma delimited string of subject ID
    public string Grades { get; set; } //Comma delimited string of subject ID
}

public class StudentListItemDto
{
    public int StudentId { get; set; }
    public int StudentName { get; set; }
    public IEnumerable<SubjectGradeDto> Tags { get; set; }
}

public class SubjectGradeDto
{
    public int SubjectId { get; set; }
    public string Grade { get; set; }
}

In my mapping profile I have this where I map IEnumerable<Student> to List<StudentListItemDto>:
CreateMap<IEnumerable<Student>, List<StudentListItemDto>>()
        .AfterMap((src, dest) =>
            {
                List<StudentListItemDto> iStudentListItemDto;
                iStudentListItemDto= src.Select(p =>
                  new StudentListItemDto
                  {
                      StudentId= p.StudentId,
                      StudentName= p.Name,
                      Tags = p.SubjectIds!= null ? p.SubjectIds.Split(",").Select((tag, i) => new SubjectGradeDto { SubjectIds= int.Parse(tag), Grade= p.Grades.Split(",")[i] }) : null
                  }).ToList();
                dest = iStudentListItemDto; // I'm assigning values to destination
            });

The reason why I am mapping it this ways is because I need to map Subjects and Grades property of Students class, which is are comma delimited values to IEnumerable<SubjectGradeDto>
Further improvement to the mapping would be much appreciated.
But my problem is when I am assigning
dest = iStudentListItemDto;

in the AfterMap. When I debug it, it has a value, but when the mapping gets executed here
IEnumerable<StudentListItemDto> iStudentListItemDto= new List<StudentListItemDto>();
        iStudentListItemDto = _mapper.Map<IEnumerable<Student>, IEnumerable<StudentListItemDto>>(searchResult, iStudentListItemDto);

where search result is IEnumerable<Student>
iStudentListItemDto evaluates to empty List.
The question is why?

A: In your CreateMap your mapping IEnumerable to List and when effectively mapping you are mapping from IEnumerable to IEnumerable.
List is IEnumerable, but IEnumerable is not a List, basically.
With this mapping you created you only have the direction from IEnumerable to List.
A better approach, as I can see you are only using this way for mapping the tags, is to do something like this
CreateMap<Student, StudentListItemDto>()
        .ForMember(dto => dto.StudentName, opt => opt.MapFrom(s => s.Name))
        .ForMember(dto => dto.Tags, opt => opt.Ignore())
        .AfterMap((student, dto) =>
            {
                dto.Tags = student.SubjectIds!= null ? student.SubjectIds.Split(",").Select((tag, i) => new SubjectGradeDto { SubjectIds= int.Parse(tag), Grade= student.Grades.Split(",")[i] }) : null;
            });

Now if AutoMapper sees that you are mapping a single object or a list of these objects, it will map each object of this list correctly.
This because you are not using the whole list to create this list of Tags.


text:
Q: Access form data after submitting Contact Form 7 I installed Contact Form 7 and I would like to access the form data after or before the email is sent. Ideally I don't need an email to be sent, I just need the form data in order to populate custom fields
What I found so far is this:
add_action('wpcf7_mail_sent', function ($cf7) {
    // Run code after the email has been sent
    echo $cf7;
    die();
});

After adding the above action to functions.php, the form action never completes. I want to view the data, find the postID and create the custom fields.
Any help is appreciated.

A: The die() prevents the code from running, remove it and it should work as normal.
Now about the from data, you will need to get the form instance and then you will have access to all the form data.
Here's an example
add_action('wpcf7_mail_sent', function ($cf7) {
  $submission = WPCF7_Submission::get_instance();
  if ($submission) {
    $cf7_data = $submission->get_posted_data();
  }
}

Now because all of this happens in the backend you will not be able to echo any of it to check what you get.
I use phps error_log function for this.
Heres a snippet:
error_log(print_r($your_value_here, true), 3, __DIR__ . '/temp-log.txt');
error_log("\r\n\r\n", 3, __DIR__ . '/temp-log.txt');

This will create a file, named temp-log.txt in the root of your theme with the data that you passed to error_log.
Change $your_value_here to what ever you need.
Hope this helps =]


text:
Q: How to cast a struct of 2 uint into a double I have a struct like below:
struct pts_t
{
    uint32_t lsb;
    uint32_t msb;
};

I would like cast that into a double.  Is it safe of directly write:
pts_t t;

double timestamp = t;

and more complex, if the struct type is part of a C dll API, without having "packing" attribute (for all compiler) in that case I have to copy the pts_t*receive througth the API to pts_t instance i create to control the struct packing ?
void f(pts_t* t)
{
   pts_t myt; myt.lsb = t->lsb; myt.msb = t->msb;

   double timestamp = *(double*)(&myt.lsb);
}

A: Even if you assume that your double are 64 bit wide, if you are looking for portable code you should be really careful with that: your structure and double might have different alignment constraints and your compiler may get confused because of aliasing rules. A way to avoid problems with that is to use a union
union {
 struct pts_t pts;
 double timestamp;
} x = { .pts = t };

and then use x.timestamp.
Also be careful that "composing" doubles like that might result in strange values such as infinities that you wouldn't encounter otherwise.

A: You have to write
double timestamp = *( (double*)(&t.lsb));

You should use something like
struct __attribute__((__packed__)) pts_t {
    ...
};

to make sure that your struct is packed (though I can't see why any compiler would pad something after the lsb in this case).
...
Actually depending whether your platform is big- or littleendian you might have to switch lsb and msb or do something like this:
double timestamp;
double* p_timestamp = &timestamp;
*((uint32_t*)p_timestamp) = t.msb;
*( ((uint32_t*)p_timestamp) + 1) = t.lsb;

A: The initial thought would be to write the following:
double timestamp = *( ( double * ) &( t.lsb ) );

To step through this (assuming you are in a 32-bit environment):

*

*You are getting the address of the identifier t.lsb because you need to find the memory address of the first byte in your structure. Note, you can alternatively do &t.

*You are then casting that memory address to be a pointer to a double (8 bytes).

*You are lastly dereferencing that pointer and storing all 8 bytes in the 8 byte block of memory that the identifier timestamp uses.

Remark:

*

*You will need to consider little/big endianness.

*You are assuming that both the structure and double are aligned properly (as mentioned below).

*This is not portable, you are assuming that a double is 8 bytes.

Now, the three points in the remark blurb are a lot to worry about. It becomes a big pain when porting this code accross multiple platforms. As mentioned below, using C unions is a much better and correct solution that is portable.
It would be written as follows with C unions:
double timestamp = ( union { double d; struct pts_t pts; } ) { t } .d;

A: You have:
struct pts_t
{
    uint32_t lsb;
    uint32_t msb;
};

This:
pts_t t;
double timestamp = t;

is perfectly "safe", in the sense that it won't compile so it can't do any harm. You haven't defined a type pts_t; you've defined a type struct pts_t.
This:
struct pts_t t;
double timestamp = t;

also won't compile, because you can't convert (either explicitly, with a cast, or implicitly, with an assignment) a value of a struct type to an object of numeric type.
I humbly suggest that you would have saved some time if you'd tried that before posting.
Probably the most straightforward approach is to use memcpy():
#include <assert.h>
#include <string.h>
/* ... */
struct pts_t t = { some_lsb_value, some_msbZ_value };
double timestamp;
assert(sizeof t == sizeof timestamp);
memcpy(&timestamp, &t, sizeof timestamp);

By using memcpy() rather than pointer casts, you avoid any risk of misaligned memory access; depending on the system, your struct might require either more or less strict alignment than a double.
There's also no guarantee that your struct is the same size as a double. The struct is almost certainly 64 bits, and double is probably 64 bits, but neither is actually guaranteed, and it doesn't hurt to make your assumptions explicit.
That leaves open the question of whether the values you've stored in t.lsb and t.msb, when taken together, make up a representation for a valid double value, particularly for the value you want.  The language says very little about how floating-point types are represented. In particular, endianness can and does vary across different systems. It's up to you to make sure that reinterpreting the representation in this way actually makes sense -- and your code is likely to be non-portable.


text:
Q: Documenting Camel Routes I have several Camel contexts in my project and i would like to document the routes if possible in a reverse engineering fashion since we want to keep the documentation up to date related to the context. what would be the best approach?

A: We tend to actually design the routes up front and model them using the iconography from the EIP book.  That gives us a guide to then test drive our routes.  Are your routes changing really often that reverse engineering is required?  We are slowly looking at building a dynamic UI for our routes - but that won't be until will into 2011 :)

A: You can just add documentation in the actual DSL and then have some tooling or whatever that extracts that route and documentation.
In the Spring XML DSL you ought to be able to add  elements to the EIPs in the route. Also you can also add general XML comments as well.
Also as mentioned above some GUI tooling is also what some people want to use. Then often the visual diagram of the routes using the EIP icons is the documentation.
FuseSource is current building a GUI tool called FuseSource Rider. It will be in public beta later this month.
At Apache Camel there is some maven tooling for generating gui diagrams
http://camel.apache.org/visualisation.html


text:
Q: Selecting DEM that best determines shore line using ArcGIS Desktop? I want to extract the shore line (Z=0) from DEM files. the earth explorer provides two DEM sources (ASTER & SRTM).
In the following figure if the blue line represents the shore line as digitized from the topographic map, and both the other red and green lines are the shore lines as extracted from the two DEM sources.
Is there a tool in ArcGIS allows me to determine which of the red and green polylines is closer to the blue one.

A: I tried replicating this using Spatial Analyst.  Firstly, I created three lines in different feature classes (though they could be in the same feature class).

*

*Topo Line (blue)

*DEM 1 (red)

*DEM 2 (green)

You can see that in my case, the red follows the blue more closely.
Then, I created a Euclidean Distance Raster from the blue topo line. My extents were slightly larger than the input.

Finally, I ran Zonal Statistics as table on both the red and green lines.
The results look like this:
DEM1:

DEM2:

You can see that the mean is larger for the green line (DEM 2).
There might be better ways to assess this.  You might need a different method if your lines are actually polygons and not lines.
EDIT: I have also added a vector solution as a separate answer.

A: In addition to the raster solution I provided, here's a vector solution.
The first thing I did was to convert the vertices of the DEM1 and DEM2 lines to points. To convert to points, you can use Feature Vertices to Points, or if you don't have an Advanced licence, you can use the Feature Class to Points tool, or create your own arcpy solution.
In the below image, DEM1 is red and DEM2 is green. The topo line is blue.

Next, in your points layer, create a field to store distance.  This will hold the distance from the point to the Topo line.  You can use the Near tool, or if you don't have the Advanced license, you can use arcpy.
I used arcpy, which looked something like this:
First get the geometry of the topo line ( sr is your spatial reference -  whatever coordinate system you're using).
with arcpy.da.SearchCursor("Topo_Line", "SHAPE@", spatial_reference = sr) as sTopoCur:
    for row in sTopoCur:
        topoGeom = row[0]

Then calculate the distance from each point to the topoline.
with arcpy.da.UpdateCursor("DEM1_Points",["SHAPE@X","SHAPE@Y","Distance"], sr) as uCur:
    for row in uCur:
        thePoint = arcpy.Point(row[0],row[1])
        thePointGeom = arcpy.PointGeometry(thePoint,sr)
        row[2] = thePointGeom.distanceTo(topoGeom)
        uCur.updateRow(row)

Repeat again for DEM2_Points.
The results can be seen in the attribute table:

Right clicking on the Distance field name in the attribute table, click on Statistics...

You can see how the point distances differ by comparing the statistics for each of them:
DEM1 Points:

DEM2 Points:

You can see that DEM1 Points have a smaller mean, which is expected since it follows the topo line more closely.
+-------------+----------+------------+------------+--------------------+
| TableName   | Minimum  | Maximum    | Mean       | Standard Deviation |
+-------------+----------+------------+------------+--------------------+
| DEM1_Points | 0.000001 | 110.073997 | 25.955782  | 38.645082          |
+-------------+----------+------------+------------+--------------------+
| DEM2_Points | 0.000094 | 310.643433 | 129.651896 | 72.359374          |
+-------------+----------+------------+------------+--------------------+

The results are different than the raster solution because we're looking at distance of vertices to the topo line, rather than the entire line to the topo line.  However, overall, both methods result in showing that DEM1 line is a better fit.


text:
Q: Convert each Byte of NSData to equivalent Int Value I have an NSData object that is being allocated with bytes that are representing unsigned integers from 0-255. What is the simplest way to convert these bytes to integers, or, if it is easier, to a string/NSString?
For instance, if I have bytes 0x00, 0x02, and 0x0A in my NSData object, then I would like to have either an integer array of {0,2,10} or the string/NSString "0210".
It seems that there are plenty of ways to turn NSData into ASCII NSStrings,UInt8 arrays, etc, but I cannot for the life of me figure out how to do this simple conversion in Swift.
Edit: Example Code of what I want:
var data:NSData
/*allocate NSData*/
var unsignedInts = [Int]()
/*Allocate each byte of data to an individual index of unsignedInts */
print(unsignedInts)
//should see {0, 1, 10} if bytes are 0x00, 0x01, and 0x0A

A: It is necessary to create a new Array of Int because Int require more bytes per entry.
var nsData: NSData = NSData(bytes: [0x00, 0x02, 0x0A] as [UInt8], length: 3)
let buffer = UnsafeBufferPointer<UInt8>(start:UnsafePointer<UInt8>(nsData.bytes), count:nsData.length)
print("nsData: \(nsData)")

var intData = [Int]()
intData.reserveCapacity(nsData.length)

var stringData = String()

for i in 0..<nsData.length {
    intData.append(Int(buffer[i]))
    stringData += String(buffer[i])
}

print("intData: \(intData)")
print("stringData: \(stringData)")

nsData: <00020a>
intData: [0, 2, 10]
stringData: 0210

A: I can recommend a method like this:
import Foundation

extension NSData {
    var byteBuffer : UnsafeMutableBufferPointer<UInt8> {
        return UnsafeMutableBufferPointer(start: UnsafeMutablePointer(bytes), count: length)
    }

    var array : [UInt8] {
        return Array(byteBuffer)
    }

    var intArray : [Int] {
        return byteBuffer.map(Int.init)
    }

    var byteString : String {
        return byteBuffer.lazy.map(String.init).joinWithSeparator("")
    }
}

Usage:
let data1 = NSData(bytes: [0x48, 0xa1, 0x95, 0xe, 0x1c, 0x38, 0x82] as [UInt8], length: 7)       // <48a1950e 1c3882>

print(data1.array)       // "[72, 161, 149, 14, 28, 56, 130]"
print(data1.intArray)    // "[72, 161, 149, 14, 28, 56, 130]"
print(data1.byteString)  // "72161149142856130"

let data2 = NSData(bytes: [0x00, 0x02, 0x0A] as [UInt8], length: 3)

print(data2.array)       // "[0, 2, 10]"
print(data2.intArray)    // "[0, 2, 10]"
print(data2.byteString)  // "0210"

It's very easy, Swift-y and efficient like this.
Note that in some cases you don't actually need an array like this, because you can just access all the values of the data in the same way without allocating a new array (recommended):
data1.byteBuffer[4]      // 28
data1.byteBuffer.count   // 7
data1.byteBuffer(14)     // 3

EDIT: I added a property that returns an Int array, although I can't see a reason you'd need it


text:
Q: Programmatically press button react native I have a button that I was to programmatically click:
<TouchableOpacity ref={ref}>
          <Text>Hello</Text>
</TouchableOpacity>

This is the button I am using to trigger the button above:
<SubscribeButton onPress={handleNext}>
              <SubscribeText>Subscribe</SubscribeText>
</SubscribeButton>

Here is my onPress function:
const ref = useRef();

const handleNext = () => {
    ref.current.click();
  };

I keep getting the error: undefined is not an object (evaluating 'ref.current.click')
Any idea what's going on?


text:
Q: variable imageLen is not reseting after input[type file] change I have this piece of code that are creating me problem....

    "use strict";
    $(document).ready(function() {
      $(".mylbl").click(function() {
        var imageslen, imagesSize, imagesName; //decleartion variale
        //Intiallize variables for prevent to upload many time images
        imageslen = imagesSize = imagesName = 0;
        $(".inputfile").click();
        $(".inputfile").change(function() {
          imageslen = 0;
          var uploadedImages = $(".inputfile")[0].files;
          imageslen = uploadedImages.length;
          imagesSize = [];
          imagesName = [];
          for (var i = 0; i < imageslen; i++) {
            imagesSize[i] = uploadedImages[i].size;
            imagesName[i] = uploadedImages[i].name;
            console.log(imagesSize[i]);
            console.log(imagesName[i]);
          }
        });
      });
    });
body {
  margin: 0px;
  padding: 0px;
  background-color: #ccc;
  color: #f4f9c4;
  width: 100%;
  height: 100%;
}
form {
  box-sizing: border-box;
  border: 10px solid #fff;
  width: 250px;
  height: 300px;
  margin: auto;
  padding: 20px;
}
.mylbl {
  box-sizing: border-box;
  text-align: center;
  display: block;
  min-width: 80px;
  height: 50px;
  background-color: #ff4500;
  line-height: 300%;
  border: 5px solid #C33100;
  border-radius: 10px;
  cursor: pointer;
}
.inputfile {
  display: none;
}
.btn {
  width: 200px;
  height: 70px;
  background-color: #129EA4;
  border: none;
  border: 5px solid #fff;
  border-radius: 10px;
  margin: 10px 10px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form class="myform" method="post" id="myform" enctype="multipart/form-data">
  <input type="file" name="album" name="gallry[]" multiple class="inputfile" />
  <label for="imgrs" class="mylbl">Please Choose Images..</label>
  <input id="_d11re" type="button" name="addimagedata" value="Upload" class="_p25ed btn" />
</form>

Before run this code open console of browser.. to check problem and upload more than 3 o four time images
The problem is in js code that the variable imageslen isnt reset.. when first time i upload image, the code works correct and when i click second time on that labal("please choose image") for upload image image upload but two time..
here i show u small image of my google chrome..

A: everytime mylbl gets clicked, a new Change EventListener gets bound to inputfile.
$(".mylbl").click(function() {
    $(".inputfile").click();
    // move the rest of the function from HERE
}
// to HERE

if you have any problems more, make a jsFiddle or something else to show us your intermediate result.


text:
Q:  extends non-API type  I get this warning
[ClassName] extends non-API type [SuperclassName]

The package superclass sits is visible, and the warning goes on. What does this mean, and how do we prevent this?

A: This seems to be a bug that is still not fixed in 2019-06. I use a usage problem filter to get rid of the warning.
Edit: If your interfaces are @ProviderType, adding @noimplement to both interfaces javadoc solves the issue.


text:
Q: jquery validator not working for require from group? HTML
<form id="myForm" method="post" action="/" >
    <input type="text"   name="number0" class="form-control">
    <input type="text"  name="amount0"  class="form-control send">
    <input type="text"  name="operator0" class="form-control ">
    <select id="bundle0" name="bundle" class="bundle send" >
        <option>a</option>
        <option>b</option>
    </select>
    <input type="text"   name="number1" class="form-control">
    <input type="text"  name="amount1"  class="form-control send">
    <input type="text"  name="operator1" class="form-control ">
    <select id="bundle" name="bundle2" class="bundle send" >
        <option>a</option>
        <option>b</option>
    </select>
    ........//upto n numbers
    <input type="submit" value="Submit" />
</form>

JQUERY VALIDATOR
$("#myForm").validate({
    rules : {
        amount0: {
            require_from_group: [1, ".send"]
        },
        bundle0: {
            require_from_group: [1, ".send"]
        },
        operator0:"required"
    }
});

issues:
1) require from group not working for select box. i want either selectbox            for bundle or amount to be filled
2) how to do validation for all the fileds operator0,operator1 etc..

A:
1) require from group not working for select box.

You don't even have the select box properly declared in your rules object.  The rules are declared based on the name, not the id.
Additionally, to validate a select element with this plugin, the first option must contain a value='' attribute.  Notice that the value is an empty string.  Otherwise, the default value is the content between the <option></option> tags.  Since your value is not empty, the rule is always immediately satisfied before making a selection.
<select id="bundle0" name="bundle" class="bundle send">
    <option value=''>please choose</option>
    <option>a</option> <!-- // value defaults to "a" //-->
    ....


text:
Q: Translating integrals by scalar premultiplication Say I have the integral $$I=\int_a^b e^{f(x)} \text{d}x,$$
if I premultiply $I$ by $e^{\delta}$, I can translate the argument of the exponential inside the integral, e.g.
$$e^\delta I = \int_a^b e^{f(x)+\delta} \text{d}x.$$
What's important/cool here, is that I can work with just the value of $I$, for example $I$ could be found from numerical integration of some complicated $f(x)$.  So I've done a different integral, without having to integrate again.
Is there a way to generalise this beyond just the exponential?  For example I'm working with the hyperbolic tangeant,
$$J = \int^b_a \tanh{\left( f(x)\right)}\text{d}x.$$
I was hoping, that by expressing $\tanh(y)=\frac{e^{2y}-1}{e^{2y}+1}$, and then expanding it and working with each individual part, I'd be able to find a way to achieve a similar effect, but I'm struggling with dealing with the denominator.
The question then, is: Is there a way to take $J\rightarrow \int^b_a \tanh{\left( f(x) +\delta \right)}\text{d}x$, without needing to re-do the integral $J$?


text:
Q: Как адаптировать toggle панель для всех браузеров? Приветствую! Установлена раскрывающаяся панель с быстрым поиском на сайте.
$(".slide-panel-btn").click(function(){
    $("#slide-panel").slideToggle(250);
    $(this).toggleClass("active"); return false;
});

...

Почему-то она работает как нужно только в firefox, потому-что к
 прописывается style="overflow: hidden;" и из-за этого содержимого быстрого поиска просто не видно.
Как сделать чтоб не добавлялся style="overflow: hidden;"

A: Не понятно до конца ваша проблема, но чтобы убрать style="overflow: hidden;" можно написать так:
$(".slide-panel-btn").click(function(){
    $("#slide-panel").css("overflow","visible !important");
    $("#slide-panel").slideToggle(250);
    $(this).toggleClass("active"); return false;
});


text:
Q: How to validate if the user's account is accepted or still in pending in PHP? I need a php file that if a user try to login, the php file will get the username and password and if it's correct it will proceed to check the status, if the account of the user is already approved or still in pending. So if the account of the user in approved it will print '1', if still in pending it will print '2' and if the username and password of the user is incorrect it will just print '3'. The problem is after the PHP file check the username and password of the user, it should check again the database if the account already approved first or still in progress before it print '1' or '2'
<?php

$user_name = filter_input(INPUT_POST, "user_name");
$user_pass = filter_input(INPUT_POST, "user_pass");

$mysqli = new mysqli("server", "username", "password", "db");

$result = mysqli_query($mysqli, "SELECT * FROM user_info WHERE user_name='$user_name' AND user_pass = MD5('".$user_pass."')");

if ($data = mysqli_fetch_array($result)){
    $status = mysqli_query($mysqli, "SELECT `status` FROM `user_info` WHERE `user_name`='$user_name'");
    $data2 = mysqli_fetch_object($status);
    if  ($data2 = "Approved") {
        echo '1';
    } else if ($data2 = "Pending") {
        echo '2';
    }
} else {
echo '3';
}
?>

A: You don't need to do two queries. $data contains the row for the user, so you can just check the status there.
<?php

$user_name = filter_input(INPUT_POST, "user_name");
$user_pass = filter_input(INPUT_POST, "user_pass");

$mysqli = new mysqli("server", "username", "password", "db");

$result = mysqli_query($mysqli, "SELECT * FROM user_info WHERE user_name='$user_name' AND user_pass = MD5('".$user_pass."')");

if ($data = mysqli_fetch_array($result)){
    if ($data['status'] == 'Approved') {
        echo '1';
    } else if ($data['status'] = "Pending") {
        echo '2';
    }
} else {
    echo '3';
}
?>


text:
Q: How to solve no input in StreamTokenizer I have the following lines of code :
public static void main(String[] args) {
    InputStreamReader inputStreamReader = new InputStreamReader(System.in);
    StreamTokenizer t = new StreamTokenizer(inputStreamReader);
    while (t.nextToken() != StreamTolenizer.TT_EOF) {
        // process here
    }
}

So, when I run, I call : java example.java < input.txt
However, I can't handle the situation "no input file" when I call : java example.
It seems to run forever.

A: If you don't redirect anything to stdin (System.in) such as "input.txt" in your example command line then your program will expect you to type data into the console window.
Perhaps you should refactor your program to expect a command line argument (e.g. by checking that "args.length >= 1") and interpret it as the name of the file to read.  If no file name is given then you can print an error message.  Additionally, you could interpret the special pseudo-filename "-" (a single hypen) to mean stdin so you can still redirect data.
For example:
public static void main(String[] args) {
  if (args.length < 1) throw new IllegalArgumentException("no filename given");
  InputStream in = ("-".equals(args[0])) ? System.in : new FileInputStream(args[0]);
  InputStreamReader inputStreamReader = new InputStreamReader(in);
  StreamTokenizer t = new StreamTokenizer(inputStreamReader);
  while(t.nextToken() != StreamTolenizer.TT_EOF) {
    // ...

However, don't forget to close the FileInputStream, e.g. in a finally block.


text:
Q: Acer C720 trackpad not working Ubuntu 14.10 Just installed Ubuntu 14.10 on my acer c720 chromebook. The touchpad is unresponsive.

A: Determine whether a touchpad has been detected
To check if a touchpad has been detected open a terminal and check the input device list given by this command:
xinput list

If one of the lines mentions a touchpad or glidepoint (perhaps also "Synaptics" or "ALPS"), your touchpad has been detected.
If one of the lines mentions an "ADB mouse", then your touchpad is old. Use the trackpad command line tool to configure it. Here's an example to switch on tapping and dragging:
sudo trackpad show
sudo trackpad tap
sudo trackpad drag

Followthis for more details

A: Trackpad works with Linux ver 3.18 and later. I suggest to upgrade to 15.04 which comes with 3.19.


text:
Q: Call make on a FreeBSD port outside the port's directory Can make be called on a FreeBSD port outside of the port's directory? I.e. without the use of the cd command.
To contextualise, whilst the following can be done :cd /usr/ports/www/apache24 && sudo make config-recursive install distclean, something like this pseudocode would be preferred: sudo make config-recursive install distclean -p /usr/ports/www/apache24
Thank you

A: This is what the -C option of make is for.

-C directory
     Change to directory before reading the makefiles or doing any-
     thing else.  If multiple -C options are specified, each is inter-
     preted relative to the previous one: -C / -C etc is equivalent to
     -C /etc.

So you want to use this:
make -C /usr/ports/www/apache24 config-recursive install distclean


text:
Q: Ffmpeg stream from 2 pipes in Python I want to create a UDP stream from 2 input pipes (video from an image pipe, and audio from multiple wav files or another pipe) and generate one combined output. Ideally this would be done using ffmpeg for python, and no command line.
All my tests failed.
I tried:
ffmpeg.input('pipe:pipeout').output('udp://127.0.0.1:1234', r='30', ss='0').global_args('-re').run()
but the framerate is too fast and also it gets the output "trailing options were found on the commandline" and generates no stream.
How can I generate the stream?


text:
Q: Finding Optimal Number of Clusters in Expectation Maximization Algorithm I know that there are several methods (Elbow method, silhouette analysis etc) which can help me to find the best number of clusters.
My questions are:

*

*What are the best methods to use in Expectation Maximization (EM) Algorithm?

*Can I use elbow method (as if it were for K-means algorithm) to get the "best" number of clusters, but to use in EM Algorithm?
Thanks in advance.

A: The "elbow" method never works well...
Instead, use any of the other internal measures such as Silhouette, Dunn, CH Index, BIC, AIC, C index, etc. that are much better and should also work for EM.
If you really want to stick with the worst method (Elbow), you could try to look for an elbow in the score function of EM too. Just as with k-means we'd expect the loglikelihood to improve as you increase the number of clusters. There could be an elbow there too, where the rate of improval slows down.


text:
Q: Уникализировать значения выборки msql Имееться таблица допустим:
names | folders
------+--------
name1 | folder1
name2 | folder1
name3 | folder1
name4 | folder2
name5 | folder2
name6 | folder2

Хочу, чтобы мускул вернул результат folder1, folder2, т.е всего 2 значения А как сделать не знаю.... даже не знаю как гугл об этом правильно спросить.

A: Используйте оператор DISTINCT:
SELECT DISTINCT FOLDERS FROM TABLE;

A: select * from `table` GROUP BY `folders`


text:
Q: How do I check the size of the data file before I upload it (Flutter) When I take the file I want the data file size information, in the future the upload file limit will be made based on the file size. the following code that I use

void _openFileExplorer() async {
    setState(() => _loadingPath = true);
    try {
      _directoryPath = null;
      _paths = (await FilePicker.platform.pickFiles(
        type: _pickingType,
        allowMultiple: _multiPick,
        allowedExtensions: ['jpg', 'pdf', 'doc', 'docx', 'png', 'jpeg'],
      ))
          ?.files;
    } on PlatformException catch (e) {
      print("Unsupported operation" + e.toString());
    } catch (ex) {
      print(ex);
    }
    if (!mounted) return;
    setState(() {
      _loadingPath = false;
      _fileName = _paths != null ? _paths.map((e) => e.name).toString() : '...';
    });
  }

A: you can get file size using function named lengthSync.
just use this function like
var size = file.lengthSync()

it will give file size in bytes.


text:
Q: c struct queue error: "array type has incomplete element type" I'm trying to implement a simple priority queue from array of queues. I'm trying to define a struct queue, and than a struct priority queue that has an array of queues as its member variable. However, when I try to compile the code, I get the following error:

pcb.h:30: error: array type has incomplete element type

The code is below:
typedef struct{
    pcb *head;
    pcb *tail;
    SINT32 size;
} pcb_Q;

typedef struct {
 struct pcb_Q queues[5];
 SINT32 size;
} pcb_pQ;

Could someone give me a hand? Thanks a lot.

A: You already typedef the pcb_Q, no need to use struct keyword any more.
Just use this:
typedef struct {
    pcb_Q queues[5];
    SINT32 size;
} pcb_pQ;

A: typedef struct {
 pcb_Q queues[5];
 SINT32 size;
} pcb_pQ;

Your struct type has no name.  Only the typedef is called pcb_Q.

A: I don't like this line:
struct pcb_Q queues[5];

Which references structure pcb_Q.
You have not defined pcb_Q as a structure.
Instead, you typedef'd pcb_Q as a new type (which happens to be an un-named struct).
Try this instead:
pcb_Q queues[5];


text:
Q: I understand the intuition of the Monty hall problem, I do not understand the math Take the famous Monty Hall problem. There are three doors, one has a prize. If you pick the door with a goat, he reveals the other door with the goat. If you picks the door with the car, he randomizes and reveals one of the goats.
The calculations of the probabilities are what is confusing to me. So say you pick door 1 initially. and I define event $A_i =$ car is behind door $i$, and event $B_i$, Monty Hall reveals door $i$.
I have seen this calculation made:
$\mathbb{P}(A_1 \cap B_2)=$ probability the car is behind door 1 and he opens door 2 $= \frac{1}{3} \times \frac{1}{2} = \frac{1}{6}$.
$\mathbb{P}(A_1 \cap B_3)= \frac{1}{3}\times\frac{1}{2} = \frac{1}{6}$
$\mathbb{P}(A_2 \cap B_3)= \frac{1}{3}\times 1 = \frac{1}{3}$
$\mathbb{P}(A_3 \cap B_2)= \frac{1}{3}\times 1= \frac{1}{3}$
It can then be shown using conditional probabilities that you have a $\frac{2}{3}$ chance of winning if you switch, and $\frac{1}{3}$ if you stay, and this is because Monty's choice is not random, it is conditional on your choice.
I actually do not understand why we can calculate the above probabilities. For instance, take the first one, $\mathbb{P}(A_1 \cap B_2)$. We are calculating above it seems as $\mathbb{P}(A_1)\times \mathbb{P}(B_2)$. Are we assuming $A_1$ and $B_2$ are independent? How can we do that - isn't the probability that he reveals door 2 dependent on whether or not the prize is behind door 1? So shouldn't this itself be a conditional probability, i.e. something like $\mathbb{P}(A_1)\times \mathbb{P}(B_1\mid A_1)$?

A:
so shouldn't this itself be a conditional probability, i.e. something like pr(A1)*pr(B1|A1)?

It should, and it is.  That is why the second factor in each expression have differing values: they depend on the first event.
$\qquad\begin{align}\Pr(A_1\cap B_2)&=\Pr(A_1)\cdot\Pr(B_2\mid A_1)\\&=(1/3)\cdot(1/2)&&\raise{1ex}{\small\text{Monty has equal chance to reveal door 2 or 3}\\\small\text{ when the car is behind door 1}}\\&=1/6\\[2ex]\Pr(A_2\cap B_2) &=\Pr(A_2)\cdot\Pr(B_2\mid A_2)\\ &= (1/3)\cdot (0)&&\raise{1ex}{\small\text{Monty can not reveal door 2 when}\\\small\text{ the car is behind that door}}\\&=0\\[2ex]\Pr(A_3\cap B_2)&=\Pr(A_3)\cdot\Pr(B_2\mid A_3)\\&=(1/3)\cdot(1)&&\raise{1ex}{\small\text{Monty can only reveal door 2}\\\small\text{ the car is behind door 3}}\\&=1/3\end{align}$
Hence:
$\qquad\begin{align}\Pr(A_3\mid B_2)&=\dfrac{\Pr(A_3\cap B_2)}{\Pr(A_1\cap B_2)+\Pr(A_2\cap B_2)+\Pr(A_3\cap B_2)}\\&=\dfrac{1/3}{1/6+0+1/3}\\&=2/3\end{align}$


text:
Q: GCP deploy cloud function failed I was trying to deploy a GCP cloud function using git hub actions and I got this error:
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Build failed: ERROR: Invalid requirement: 'Creating virtualenv xxxxxx-nJ6OriN1-py3.8 in /github/home/.cache/pypoetry/virtualenvs' (from line 1 of requirements.txt)
Hint: It looks like a path. File 'Creating virtualenv retry-failed-reports-nJ6OriN1-py3.8 in /github/home/.cache/pypoetry/virtualenvs' does not exist.; Error ID: 0ea8a540
Up until today, when all git hub workflows failed with this problem, my CI-CD pipeline was working as expected.
I was able to deploy the function manually using gcloud, it fails on cloud build step

How can I solve this issue?

A: We were using this command to generate the requirements.txt:
poetry export -f requirements.txt --without-hashes > requirements.txt
However, this stopped working.
Now I tried this command and is working fine:
poetry export -f requirements.txt --output requirements.txt --without-hashes


text:
Q: How to add 2 callback to the Jshelper in Cakephp 2.x I want to add 2 callback to Js->submit, My first return true or false. Continuing with that I want to put action. I mean If it is true then it continue to action else halt at that moment.
What I have tried yet but its not taking 2 callback. Plaese help.
echo $this->Js->submit("Apply",
array(
     'id' => 'submitForm', 'div' => false, 'class' => 'general_button', 'style' => array('float:none;', 'margin: 10px;'),
     'url' => array(
                 'controller' => 'categories', 'action' => 'index', 'field' => $search_term, 'value' => $search_value, 'parentId' => $parentId
              ),
     'update' => '#listID',
     'confirm' => 'Are you sure you want to apply action to selected records ??',
     'before' => $this->Js->event('click', 'return checkboxCount();', false),
     'before' => $this->Js->get('#loaderID')->effect('fadeIn', array('buffer' => false)),
     'complete' => $this->Js->get('#loaderID')->effect('fadeOut', array('buffer' => false)),
     )
);

How will I continue with it. As function return checkboxCount(); returns true or false. but in here case my function is not even called.


text:
Q: Problem with removing last row of JTable This is my first time asking here so forgive me if something isn't appropriate, and sorry if my English isn't very good.
Well, to make it short, currently I'm developing a Java desktop app with Swing and I have a problem using table. I have rows with each row have a button to delete the row. Everything is okay (i can delete rows with no problem) until i try to delete the last row. The last row can be deleted but apparently there is an exception, something like this:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 4 >= 4
    at java.util.Vector.elementAt(Vector.java:427)
    at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:648)
    at javax.swing.JTable.setValueAt(JTable.java:2710)
    at javax.swing.JTable.editingStopped(JTable.java:4712)
    at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:125)

From the stack trace, it seems that "4" is my previously deleted last row index, but i have no idea how to deal with this. I already search for solution but i still can't solve it. Note that there are still other rows when i delete the last row, and after that i can't delete the others rows. The same exception also resulted when i click the delete button.
Oh. and I use removeRow() from DefaultTableModel to delete the row. Any help will be appreciated. Thanks.
EDIT
These are the code I use.
public class ViewDetail extends JInternalFrame implements ActionListener {
    ...
    String column[] = { "Aaa", "Bbb", "Delete This"};

    tableModel = new DefaultTableModel();
    Object row[][] = new Object[size][column.length];

    //fill the data from db
    int r = 0;
    for (int i = 0; i < size; i++) {
    row[r][0] = ...;
    row[r][1] = ...;
    row[r][2] = "Delete";
    r++;
    }

    tableModel.setDataVector(row, column);
    table = new JTable(tableModel);

    tableColumn = table.getColumn("Aaa");
    tableColumn.setPreferredWidth(75);
    tableColumn = table.getColumn("Bbb");
    tableColumn.setPreferredWidth(75);
    tableColumn = table.getColumn("Delete This");
    tableColumn.setPreferredWidth(75);
    tableColumn.setCellRenderer(new ButtonRenderer());
    tableColumn.setCellEditor(new ButtonEditor(new JCheckBox());
     ...
}

public class ButtonRenderer extends JButton implements TableCellRenderer {
    public ButtonRenderer() {
        setOpaque(true);
    }
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        if (isSelected) {
            setForeground(table.getSelectionForeground());
            setBackground(table.getSelectionBackground());
        } else {
            setForeground(table.getForeground());
            setBackground(UIManager.getColor("Button.background"));
        }
        setText((value == null) ? "" : value.toString());
        return this;
    }
}

public class ButtonEditor extends DefaultCellEditor {
    protected JButton button;
    private String label;
    private boolean isPushed;
    private JTable table;
    public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            fireEditingStopped();
            }
        });
    }

    public Component getTableCellEditorComponent(JTable table, Object value,
        boolean isSelected, int row, int column) {
    if (isSelected) {
        button.setForeground(table.getSelectionForeground());
        button.setBackground(table.getSelectionBackground());
    } else {
        button.setForeground(table.getForeground());
        button.setBackground(table.getBackground());
    }
    label = (value == null) ? "" : value.toString();
    button.setText(label);
    isPushed = true;
    this.table = table;
    return button;
    }

    public Object getCellEditorValue() {
    if (isPushed) {
                  DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
                  tableModel.removeRow(table.getSelectedRow());
            }
            isPushed = false;
    return new String(label);
    }

    public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
}

protected void fireEditingStopped() {
        super.fireEditingStopped();
    }
}

A: Swing is trying to set the new value into the row you remove!  Try moving the remove code into a Runnable and use invokeLater in the swing utility class to execute it.

A: could you post the code where you init, add elements and delete in your JTable?
My first guess is that you are either doing the classical mistake
"I have 4 elements in my table so to delete the last one I remove(4)" when you your table goes from 0 to 3 in indices
or you are trying to remove several object in the same loop like
  for(int i = 0; i<lenght; i++){
       if(i%2==0){//every even number
         tab.remove(i);
        }
    }

then your are modifying the size of your table, the elements are shifted but your not taking it in account when removing.
those are just guesses/pointer to what might cause the problem. please post your code if this doesn't solve it

A: The Table Button Column shows how you can render a column as a button and how to add an Action that is executed when the button is clicked. The example Action just happens to show how to delete a row.

A: Here you need to remove only 0 th row that should be iterated
private void refreshTable() {
       int rowCount= model.getRowCount();
      // System.out.println(rowCount);
   for(int i=0;i<rowCount;i++ ){
        model.removeRow(0);
        //System.out.println(i);
   }

}

A: you can add new vaiable and check to fireEditingStopped() :
public class ButtonEditor extends DefaultCellEditor {

//create new variable
private boolean isDeleteRow = false;
/////////////////

protected JButton button;
private String label;
private boolean isPushed;
private JTable table;
public ButtonEditor(JCheckBox checkBox) {
super(checkBox);
button = new JButton();
button.setOpaque(true);
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
        }
    });
}

public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row, int column) {
if (isSelected) {
    button.setForeground(table.getSelectionForeground());
    button.setBackground(table.getSelectionBackground());
} else {
    button.setForeground(table.getForeground());
    button.setBackground(table.getBackground());
}
label = (value == null) ? "" : value.toString();
button.setText(label);
isPushed = true;
this.table = table;

// set false when click to button
isDeleteRow = false;
/////////////////
return button;
}

public Object getCellEditorValue() {
if (isPushed) {

              // set true when isPushed button
              isDeleteRow = true;
              /////////////////

        }
        isPushed = false;
return new String(label);
}

public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
}

protected void fireEditingStopped() {
    super.fireEditingStopped();

     //check if isDeleteRow, remove row
     if(isDeleteRow)
     {
          DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
          tableModel.removeRow(table.getSelectedRow());
     }
     /////////////////
}
}


text:
Q: Set contents on NSTableViewCell depending on NSPopUpButton i was just wondering how to set a NSTableCellView to show a specific string depending on what option a user selected from a NSPopUpButton, any and all help would be greatly appreciated…
I would like to do this without using binding also

A: First, make sure you understand the Model-View-Controller design pattern.  You need to do three things:

*

*Create a data structure to store your model.

*Have the NSTableView display the state of the model.

*Have the NSPopUpButton change the model.

Also, why do you want to do this without bindings?  Bindings are often simpler and easier than creating your own NSTableViewDataSource.  For some complex problems you have to do the work yourself, but if bindings will solve the problem, they are often the best solution.

A: Maybe I dont understand you correctly but wouldnt it be the easiest way to just implement what is needed for NSTableViewDataSources, that is
-numberOfRowsInTableView
-tableView:objectValueForTableColumn:row

and return to your Table View, what might be needed. As far as I know, this even works with your NSTableCellView.
You could use the IBAction your Button causes and use
reloadData

on the Table View.
By the way, usually Table Views are intended to show large amounts of data. If you only want to show a short statement depending on the button selection consider using a NSTextField instead.


text:
Q: Is it possible to implement header-only non-template class? As far as I understand standard, the only way to implement something non-template and non-inline in header without violating One Definition Rule, is to implement this is anonymous namespace.
But I'm unsure what happens with static variables in such class methods implementation:
// MyHeader.h
// ... pragma once, defines, etc. ...

// (anonymous namespace removed due to suggestions below)
// namespace
// {
    class A // a simplified single-threaded kind of Singleton
    {
        // ... some private not static data ...
    public:
        static A& instance()
        {
            static A instance;   // is it guaranteed to be module-global?
            return instance;
        }

        void doNothing();
    }

    // inline added as suggested in answers below
    // actually, I disabled inline in compile settings,
    // checked that inlining was not happened using disassembler,
    // but `inline` keyword is needed and it matters. Any suggestions, why?
    inline void A::doNothing()
    {
        // it's a very long method, so long that I don't want to
        // implement it as inline within class body.

        // but not so long to consider refactoring it to smaller functions :)
    }
//}

// File executable_part1.cpp
// ... includes, etc. ....
A::instance().doNothing();

// File executable_part2.cpp
// ... includes, etc. ....
A::instance().doNothing();

The main questions are:

*

*Is it guaranteed that instance is module-global?

*Is this portable code or behavior is compiler implementation-defined?

I have experimented with this code on MSVS 2012 on Windows. I have included this header in 2 .cpp-files for each of 3 modules: one executable and 2 dlls, loaded by executable. 6 times overall.
Without namespace: constuctor was called 3 times, once for each 'OS-level' module.
With namespace: constuctor was called 6 times, once for each cpp file.
UPDATE:
As pointed below, chapter 7.1.2 of C++'03 standard solves my question. Inline matters here.

A: You should not use unnamed namespace as each translation unit will have its own struct A.
just do
class A
{
    // ... some private not static data ...
public:
    static A& instance()
    {
        static A instance;
        return instance;
    }

    void doNothing();
};

inline void A::doNothing()
{
    // it's a very long method, so long that I don't want to
    // implement it as inline within class body.

    // but not so long to consider refactoring it to smaller functions :)
}

*

*It is normal that the singleton are not shared between exe/dll.

*with unnamed namespace you have singleton for each TU, whereas without it, the singleton is shared for the whole exe (and respectively for the whole Dll).

For your configuration: 1 exe with 2 cpp, and 2 Dll with both 2 cpp:
your experiment is correct: 6 with unnamed namespace, and 3 without it.

A: I really didn´t understand well the question (maybe I missed something ) so keep what you need.
To my understanding, static methods and data, pertain to the class itself and not to the instances of the class.
So static data exist just once and are the same independently if these are accessed from different objects.
Static methods are like normal external functions and no this pointer is available to them.
Belong to the namespace of the class so every class could implement a static function with the same name, and there would be no name clash because their names are not equal because the fully qualified name is: "classOfAppartenence::nameOfFunction" and the fully qualified name is different for each of them.
Essentially if you don't implement any object for the class, the class works as just a namespace.


text:
Q: Производительный фреймворк на node js с архитектурой MVC? Сейчас использую express + handlebars. На клиенте MVC фреймворк.
Почитал статью с фреймворками и там большой выбор.
https://habrahabr.ru/post/316244/
Ишу высокопроизводительный (такой же как express), для крупных приложений, гибкий, надежный основанный на классах.   С большим функционалом встроенным, перспективный и активно развивающийся.

*

*Желательно, чтобы был единый код на клиенте и сервере.

*Больше для разработки админок и SPA приложений со сложной логикой, чем с простой отдачей html кода по запросу.

*Желательно чтоб была хорошая документация на русском или книга.


text:
Q: Space being used without having any file I just created my Ubuntu One account, and I've been testing it (uploading and deleting files), but I realized that I have 836.0 KB being used without having any file. Is this normal? How can i fix this?
I already checked for hidden files in the Ubuntu One folder (the only one i have syncing), but i have none. I also checked in one.ubuntu.com/files but i have the message that says "Let's get started with syncing your files!" which, I think, it means that I have no files.

A: I got my problem fixed. From what I read in the FAQs it is a known bug. For anybody with a similar problem, I suggest sending threw the Contact Us from the Ubuntu One main page a request similar to my original question and, in my case, they answered quickly and the problem solved immediately.

A: This probably some hidden files or the disk allocation issue, this is hardly a problem considering its so small. Its probably displaying files needed by Ubuntu one or size on disk.

A: I've got a similar issue. By mistake I chosen to sync a folder. When I realized this I tried to stop the sync but it had already loaded data into the cloud. However, this data is not visible and uses 700mb of my storage!
Is there a way to format Ubuntu-One?
Thanks,
Fabian


text:
Q: Is the formula $|G|=|\ker \varphi|.|\text{im}\space \varphi|$ connected to the formula $ab = \gcd(a,b) \cdot \operatorname{lcm}(a,b)$? I was reading the corollary;

Let $\varphi :G\rightarrow G'$ be a homomorphism of finite groups. Then $$|G|=|\ker \varphi| \cdot |\text{im}\space \varphi|$$

Then I suddenly remember one of my 6-th or 7-th grade formula

Let $a,b\in \mathbb{N}$, then $$a \cdot b=\gcd (a,b) \cdot\text{lcm} (a,b)$$

Are these two result really related!! If so then what is $\varphi$ here?

A: Consider the groups $\mathbb Z_a$ and $\mathbb Z_b$ and the group homomorphism  $$\phi: \mathbb Z\to\mathbb Z_a\times\mathbb Z_b,~~~~n\mapsto(n|_{\text{mod}~a},n|_{\text{mod}~b})$$


text:
Q: yii insert subform/subpage inside gridview value I'm a newbie to yii and have difficulty on using subform and gridview.
I want to create a simple accounting journal with these tables:
t_journal
---------
id_journal
dates

t_journal_detail
----------------
id
id_journal
journal_code
journal_name
desc
debit_value
credit_value

I'd like to use two gridview for this, one for t_journal, and one for t_journal_detail which is inside t_journal gridview, just like below:
$this->widget( 'bootstrap.widgets.TbGridView', array(
    'id'             => 'jurnal-harian-grid',
    'template'       => "
{pager}

{summary}

\n{items}\n
{pager}

{summary}

",
    'dataProvider'   => $model->search(),
    'columns'        => array(
        array(
            'name'   => 'id_journal',
            'header' => 'ID',
        ),
        array(
            'name'   => 'dates',
            'header' => 'Date',
            'value'  => 'date("d-m-Y",strtotime($data["dates"]))',
        ),
        array(
            'header' => 'Details',
            'value'  => $this->renderPartial('_subjurnal', array("modelDetail"=>$modelDetail), true),
        ),
    ),
) );

inside _subjurnal.php, I insert a one column table with word "Testing"

        Testing

Is that the right way to insert another subform or subpage inside gridview? Because I got an error on every row of journal gridview:
Parse error: syntax error, unexpected '<' in D:\xampp\htdocs\cvsunrise\yii\framework\base\CComponent.php(616) : eval()'d code on line 1

What is the right way to do that? A help for this would be much appreciated.

A: "modelDetail"=>$modelDetail its not defined i assume. Actually it should work with few corrections:

*

*column type - use 'type'=>'raw'

*If you want to use external variable in gridview you need to import it. Also better to make this with function:
'value'  => function ($data,$row) use $modelDetail {$this->renderPartial('_subjurnal', array("modelDetail"=>$modelDetail), true);},
Also avoid double loading of js scripts.

A: The @ineersa answer it's a correct solution.
after that, if you will have a javascript problem, try putting this line al last of "inside_journal.php" view:
    <?php Yii::app()->getClientScript()->scriptMap=array('jquery.js'=>false, 'jquery.ui.js'=>false); ?>

In the array() put the libs that are charging twice.


text:
Q: Why a nested QStateMachine inside subclass of QState with this pointer in constructor causes that an outer state machine can't make a transition? There is a state machine (called the outer). This machine has two states - first and the final. First state is custom implemented. Inside the first state there is created another state machine (called the inner) which in this example does nothing.
Outer state machine with two states:
  #include <QDebug>
  #include <QCoreApplication>
  #include <QTimer>
  #include <custom_outer_state.hpp>
  #include <QFinalState>
  #include "a.hpp"

  class Functor
  {
  public:
     void operator()()
     {
        // just emits a signal
        TestObject outerTestObject;

        // create outer state machine with all states
        QStateMachine outerStateMachine;
        CustomOuterState *state1 = new CustomOuterState();
        QFinalState *state2 = new QFinalState();
        state1->addTransition(&outerTestObject, SIGNAL(testObjectSignal()), state2);
        outerStateMachine.addState(state1);
        outerStateMachine.addState(state2);
        outerStateMachine.setInitialState(state1);
        outerStateMachine.start();

        // process state machine transitions
        QCoreApplication::processEvents();
        qDebug() << &outerStateMachine << ": Outer state machine first state " <<  outerStateMachine.configuration();
        outerTestObject.testObjectSignal();
        QCoreApplication::processEvents();
        qDebug() << &outerStateMachine << ": Outer state machine second state " <<  outerStateMachine.configuration();
     }
  };

  int main(int argc, char *argv[])
  {
    QCoreApplication app(argc, argv);
    QTimer::singleShot(0, Functor());
    return QCoreApplication::exec();
  }

And custom state:
  #ifndef CUSTOM_OUTER_STATE_H
  #define CUSTOM_OUTER_STATE_H

  #include <QState>
  #include <QStateMachine>

  class CustomOuterState : public QState
  {
     Q_OBJECT
  public:
     virtual void onEntry(QEvent * event)
     {
        // create inner state machine
        machine = new QStateMachine();
        /*
         * some operations with the machine
         */
     }
  private:
     QStateMachine* machine;
  };

  #endif

And test object which just emits a signal:
  #ifndef A_H
  #define A_H

  #include <QObject>

  class TestObject : public QObject
  {
     Q_OBJECT
  signals:
     void testObjectSignal();
  };

  #endif

So this code works as expected - the outer state machine goes from the first state to the final:
  QStateMachine(0x7fffc00f0a20) : Outer state machine first state  QSet(CustomOuterState(0xe0a380) )
  QStateMachine(0x7fffc00f0a20) : Outer state machine second state  QSet(QFinalState(0xe0a460) )

But with a little change inside the custom state - passing this (which is a subclass of QState) to the inner state machine constructor
  -        machine = new QStateMachine();
  +        machine = new QStateMachine(this);

results that the outer state machine doesn't want to make a transition - it stays in the first state although the transition signal was sent
  QStateMachine(0x7fff219edcb0) : Outer state machine first state  QSet(CustomOuterState(0x1fc4380) )
  QStateMachine(0x7fff219edcb0) : Outer state machine second state  QSet(CustomOuterState(0x1fc4380) )

The solution is simple - just delete the inner state machine and everything works. But the question is why the bad thing happens.
So, why adding this which is a subclass of QState to the inner state machine constructor results so that the outer state machine doesn't want to make a transition?

A: You're trying to modify a state machine's statechart from a state's event handler. That's not supported by the state machine. Since QStateMachine is-a QState, by adding it as a child you're modifying the statechart.
When onEntry is called, the statechart looks as follows:

During onEntry, you change it to something resembling the following. The machine is not an initial state, it's just a dangling, useless state.  Even if it weren't dangling, it'd still be unusable as it was added during a state transition.

Since QStateMachine is a QState, when you make it a direct child of a state it becomes a substate of that state. If all you want is to use the state as a container for the state machine, you can insert an intervening non-state object between the parent and the state.
// https://github.com/KubaO/stackoverflown/tree/master/questions/statemachine-nested-32619103
#include <QtCore>

struct OuterState : QState
{
   QStateMachine * machine { nullptr };
   virtual void onEntry(QEvent *) Q_DECL_OVERRIDE
   {
      // through an intervening container
      auto container = new QObject(this);
      machine = new QStateMachine(container);
   }
   OuterState(QState * parent = 0) : QState(parent) {}
};

Finally, the pseudo-synchronous code that invokes processEvents is unnecessary. You can do things when states are entered, etc. Recall that since a signal is an invokable method just like a slot is, you can connect signals to signals. In fact, since all you want to achieve is an unconditional transition, you might as well use one.
int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);

   // create outer state machine with all states
   QStateMachine outerStateMachine;
   OuterState state1 { &outerStateMachine };
   QFinalState state2 { &outerStateMachine };
   state1.addTransition(&state2);
   outerStateMachine.setInitialState(&state1);
   outerStateMachine.start();

   a.connect(&state1, &QState::entered, []{ qDebug() << "state1 entered"; });
   a.connect(&state2, &QState::entered, []{ qDebug() << "state2 entered"; });
   a.connect(&state2, &QState::entered, qApp, &QCoreApplication::quit);
   return a.exec();
}

The above is, more or less, how self-contained test cases should look: single file, no fluff and verbosity that detracts from the issue at hand.


text:
Q: Explanation of the Posterior Derivation of the Gaussian Distribution I'm reading through my notes and I don't quite understand this bit:

I understand how the likelihood was calculated but no more than that.Can anyone  explain the steps and exactly how they go from one step to the other? My main problem is how the prior and posterior distribution are found. Thanks

A: The first image is just variable change from $\sigma^{-2}=\tau$. They assume $\mu$ is known, therefore it's just constant, with no distribution (ignoring the non-degenerate case, which doesn't change the analysis). The likelihood is just multiplication of $p(y_i|\tau)\ \ \  \forall i$. We're trying to find the posterior distribution, i.e. $p(\tau|D)$, the distribution of $\tau$ given the data. Bayes formula says $$p(\tau|D)=\frac{p(\tau)p(D|\tau)}{p(D)}$$
This is a univariate PDF for $\tau$, and all other things can be regarded as constant. Since $p(D)$ doesn't depend on $\tau$, it's just a normalizing constant, and can be ignored for now, which is why we insist on using proportionality in these types of problems: $p(\tau|D)\propto p(\tau)p(D|\tau)$.
The reason is to figure out the form of the PDF and guess the normalizing constant w/o even computing $p(D)$. For example if it was $p(\tau)\propto e^{-2\tau}$, then the prior would be in exponential form, with normalizing constant $\lambda=2$, since the exponential PDF is in the form $\lambda e^{-\lambda x}$, which is normalized by default.
Going back to where we left, we had $p(\tau|D)\propto p(\tau)p(D|\tau)$. We know the likelihood, and it's in Gamma form (for $\tau$). Recall that it was a Gaussian PDF for $y_i$. So, the format actually takes different names if you change the variable. Now, we don't know the prior, and need to choose one. From the conjugate prior list, we see that $p(\tau)$ is Gamma . (5th entry in the 2nd table).
Conjugate priors make the posterior calculation much easier by allowing them to be in known forms (because posterior and prior are in the same family). You could choose any prior you want, but, then you'd have to integrate the denominator for having the full posterior, if the resulting multiplication of prior and likelihood is not in a known form. And, it's very typical to choose conjugate priors in Bayesian inference.