text:
Q: Image manipulation and texture mapping using HTML5 Canvas? In a 3D engine I'm working on I've succesfully managed to draw a cube in 3D. The only method to fill the sides is using either a solid color or gradient as far as I'm concerned. To make things more exciting, I'd really love to implement texture mapping using a simple bitmap.
The point is that I can hardly find any articles or code samples on the subject of image manipulation in JavaScript. Moreover, image support in HTML5 canvas seems to be restricted to cropping.
How could I go about stretching a bitmap so that a rectangular bitmap can fill up a unregular cube face? In 2D, a projected square cube face is, due to perspective, not of a square shape, so I'll have to stretch it to make it fit in any quadrilateral.
Hopefully this image clarifies my point. The left face is now filled up with a white/black gradient. How could I fill it with a bitmap, after it has been texture-mapped?

Does anyone have any tips on perspective texture mapping (or image manipulation at all) using JavaScript and HTML5 Canvas?
Edit: I got it working, thanks to 6502!
It is, however, rather CPU intensive so I'd love to hear any optimization ideas.
Result using 6502's technique - Texture image used

A: I think you will never get an accurate result... I spent some time investigating how to do 3d graphics using canvas 2d context and I found it viable to do texture mapping gouraud shading by computing appropriate 2d gradients and matrices:

*

*Solid polygons are of course easy

*Gouraud filling is possible only on one component (i.e. you cannot have a triangle where every vertex is an arbitrary RGB filled with bilinear interpolation, but you can do that filling using for example three arbitrary shades of a single color)

*Linear texture mapping can be done using clipping and image drawing

I would implement perspective-correct texture mapping using mesh subdivision (like on PS1).
However I found many problems... for example image drawing with a matrix transform (needed for texture mapping) is quite inaccurate on chrome and IMO it's impossible to get a pixel-accurate result; in general there is no way to turn off antialiasing when drawing on a canvas and this means you will get visible see-through lines when subdividing in triangles. I also found multipass rendering working really bad on chrome (probably because of how hw-accellerated rendering is implemented).
In general this kind of rendering is surely a stress for web browsers and apparently these use cases (strange matrices for example) are not tested very well. I was even able to get Firefox crashing so bad that it took down the whole X susbsystem on my Ubuntu.
You can see the results of my efforts here or as a video here... IMO is surely impressing that this can be done in a browser without using 3D extensions, but I don't think current problems will be fixed in the future.
Anyway the basic idea used to draw an image so that the 4 corners ends up in specific pixels position is to draw two triangles, each of which will use bilinear interpolation.
In the following code I assume you have a picture object texture and 4 corners each of which is an object with fields x,y,u,v where x,y are pixel coordinates on the target canvas and u,v are pixel coordinates on texture:
function textureMap(ctx, texture, pts) {
    var tris = [[0, 1, 2], [2, 3, 0]]; // Split in two triangles
    for (var t=0; t<2; t++) {
        var pp = tris[t];
        var x0 = pts[pp[0]].x, x1 = pts[pp[1]].x, x2 = pts[pp[2]].x;
        var y0 = pts[pp[0]].y, y1 = pts[pp[1]].y, y2 = pts[pp[2]].y;
        var u0 = pts[pp[0]].u, u1 = pts[pp[1]].u, u2 = pts[pp[2]].u;
        var v0 = pts[pp[0]].v, v1 = pts[pp[1]].v, v2 = pts[pp[2]].v;

        // Set clipping area so that only pixels inside the triangle will
        // be affected by the image drawing operation
        ctx.save(); ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1, y1);
        ctx.lineTo(x2, y2); ctx.closePath(); ctx.clip();

        // Compute matrix transform
        var delta = u0*v1 + v0*u2 + u1*v2 - v1*u2 - v0*u1 - u0*v2;
        var delta_a = x0*v1 + v0*x2 + x1*v2 - v1*x2 - v0*x1 - x0*v2;
        var delta_b = u0*x1 + x0*u2 + u1*x2 - x1*u2 - x0*u1 - u0*x2;
        var delta_c = u0*v1*x2 + v0*x1*u2 + x0*u1*v2 - x0*v1*u2
                      - v0*u1*x2 - u0*x1*v2;
        var delta_d = y0*v1 + v0*y2 + y1*v2 - v1*y2 - v0*y1 - y0*v2;
        var delta_e = u0*y1 + y0*u2 + u1*y2 - y1*u2 - y0*u1 - u0*y2;
        var delta_f = u0*v1*y2 + v0*y1*u2 + y0*u1*v2 - y0*v1*u2
                      - v0*u1*y2 - u0*y1*v2;

        // Draw the transformed image
        ctx.transform(delta_a/delta, delta_d/delta,
                      delta_b/delta, delta_e/delta,
                      delta_c/delta, delta_f/delta);
        ctx.drawImage(texture, 0, 0);
        ctx.restore();
    }
}

Those ugly strange formulas for all those "delta" variables are used to solve two linear systems of three equations in three unknowns using Cramer's method and Sarrus scheme for 3x3 determinants.
More specifically we are looking for the values of a, b, ... f so that the following equations are satisfied
a*u0 + b*v0 + c = x0
a*u1 + b*v1 + c = x1
a*u2 + b*v2 + c = x2

d*u0 + e*v0 + f = y0
d*u1 + e*v1 + f = y1
d*u2 + e*v2 + f = y2

delta is the determinant of the matrix
u0  v0  1
u1  v1  1
u2  v2  1

and for example delta_a is the determinant of the same matrix when you replace the first column with x0, x1, x2. With these you can compute a = delta_a / delta.


text:
Q: php form html button I had a website where you could select a site that you want to be redirected to from a dropdown menu & then click a button to be redirected to it.
As smart as i am i got a virus on my pc, & restored from an old backup. Short story; the site no longer works.. here is the code:
HTML:
   <form method="post" name="form1" id="form1" action="process.php">
       <select name="taskOption" id="taskOption2">
        <option value="Select">Please select a site</option>
        <option value="http://www.Itslearning.com">Itslearning</option>
        <option value="http://www.NDLA.no">NDLA</option>
       </select>
    </form>

    <button onclick="FormSubmit()" class="button button1 button1:hover">Take me there</button>

PHP:
<?php
$taskOption $_POST["taskOption"];
if ($taskOption) {
    header("Location: $taskOption");

}
else {
   echo "Venligst velg en side.";
   exit;
}

?>

JAVASCRIPT:
    function FormSubmit() {
document.form1.submit();
}

A: What is the error you receive? At least one error is in your PHP file:
<?php
$taskOption = $_POST["taskOption"];
if ($taskOption) {
    header("Location: $taskOption");
} else {
   echo "Venligst velg en side.";
   exit;
}
?>

Note the "=" on the second line.

A: First off, looks like you're missing an assignment operator (=) in your PHP.
It should look like this:
<?php
$taskOption = $_POST["taskOption"];
if ($taskOption) {
    header("Location: $taskOption");

}
else {
   echo "Venligst velg en side.";
   exit;
}

?>

A: Simple table to store urls:

create table `urls` (
    `id` int(10) unsigned not null auto_increment,
    `url` varchar(255) not null default '0',
    `hash` varchar(16) not null default '0',
    `hits` smallint(5) unsigned not null default '0',
    primary key (`id`),
    unique index `hash` (`hash`)
)
engine=innodb;

Gives this structure:

+-------+----------------------+------+-----+---------+----------------+
| Field | Type                 | Null | Key | Default | Extra          |
+-------+----------------------+------+-----+---------+----------------+
| id    | int(10) unsigned     | NO   | PRI | NULL    | auto_increment |
| url   | varchar(255)         | NO   |     | 0       |                |
| hash  | varchar(16)          | NO   | UNI | 0       |                |
| hits  | smallint(5) unsigned | NO   |     | 0       |                |
+-------+----------------------+------+-----+---------+----------------+

Populated with dummy urls & unique hashes:

+----+--------------------------------+------------------+------+
| id | url                            | hash             | hits |
+----+--------------------------------+------------------+------+
|  1 | http://www.example.com/page/1  | 53abc566010de29a |   45 |
|  2 | http://www.example.com/page/2  | 8664d7fca34963d2 |   83 |
|  3 | http://www.example.com/page/3  | fe06dca79d3d0415 |   49 |
|  4 | http://www.example.com/page/4  | 3913aaaef701ecad |   35 |
|  5 | http://www.example.com/page/5  | eb2eddc3ca2406c3 |   93 |
|  6 | http://www.example.com/page/6  | acc809b96c6a42d9 |   50 |
|  7 | http://www.example.com/page/7  | 63a4e53b1b374fcb |   90 |
|  8 | http://www.example.com/page/8  | d9c13a146fc7c69a |   18 |
|  9 | http://www.example.com/page/9  | eaa944c7e9a4ef7c |   76 |
| 10 | http://www.example.com/page/10 | 59f9d294a29601c9 |   13 |
+----+--------------------------------+------------------+------+

In the php page that displays the menu for the user to choose from

<?php

    $dbhost =   'localhost';
    $dbuser =   'xxx';
    $dbpwd  =   'xxx';
    $dbname =   'xxx';
    $db =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

    $sql='select * from `urls` order by `id`;';
    $result=$db->query( $sql );

    if( $result ){

        $html=array();
        $html[]="<form name='launcher' method='post' action='process.php'>";
        $html[]="<select name='taskOption'>";

        while( $rs=$result->fetch_object() ){
            $html[]="<option value='{$rs->hash}'>{$rs->url}";
        }

        $result->close();
        $db->close();

        $html[]="</select>";
        $html[]="<input type='submit' value='Go' />";
        $html[]="</form>";

        echo implode( PHP_EOL, $html );
    }

?>

<?php
    /* process.php */

    /*

        Rather than sending the actual URL via POST we only send a hash
        which is then used in the sql to find the real url from the database.

    */

    $errors=array();
    $url=false;

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['taskOption'] ) ){

        /* rudimentary sanitisation of the string */
        $hash = filter_input( INPUT_POST, 'taskOption', FILTER_SANITIZE_STRING );

        /* db credentials */
        $dbhost =   'localhost';
        $dbuser =   'xxx';
        $dbpwd  =   'xxx';
        $dbname =   'xxx';
        $db =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

        /* construct statement to find the url */
        $sql='select `url` from `urls` where `hash`=?';
        $stmt=$db->prepare( $sql );
        if( $stmt ){

            /* bind the variable - hash */
            $stmt->bind_param( 's', $hash );
            $result=$stmt->execute();

            /* */
            if( $result ){
                $stmt->store_result();
                $stmt->bind_result( $url );
                $stmt->fetch();
                $stmt->free_result();

                if( !$url ) $errors[]='Unable to locate url';

                $sql='update `urls` set `hits`=`hits`+1 where `hash`=?';
                $stmt=$db->prepare( $sql );

                if( $stmt ){
                    $stmt->bind_param('s',$hash);
                    $stmt->execute();
                    $stmt->free_result();

                } else {
                    $errors[]='sql error updating hit count';
                }
            } else {
                $errors[]='No result found in database';
            }
        } else {
            $errors[]='sql error whilst preparing initial statement';
        }

        $stmt->close();
        $db->close();

        /* Redirect the user if all went well otherwise show an error message */
        if( empty( $errors ) ) exit( header("Location: $url") );
        else exit( "There were errors processing your request." );

    }

    /* only accept POST requests */
    exit( 'Bad foo - wrong method' );
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set all li element's width, to the one that has the largest width Currently I have a list of elements of varying content sizes like so:

         Name

         Longer Name

         Longest Name in the World

I want the li elements to all have the same width, and that width to be determined by the one that has the longest content. I've seen that I can use display: inline-block; to adjust the li element's width based on it's content, but I don't want them all to have different widths, but instead for each of them to share the width of the one that has largest content. How can I do this using html5, css, and/or bootstrap?

A: inline-block is a good start, but for ul :

ul {
  display: inline-block;
}
li {
  background: gray;
}

     Name

     Longer Name

     Longest Name in the World

    hi !

table can do if you want to keep the block behavior.

ul {
  display: table;
}
li {
  background: gray;
}

     Name

     Longer Name

     Longest Name in the World

hi !

Float does too :

ul {
  float:left;
}
li {
  background: gray;
}

     Name

     Longer Name

     Longest Name in the World

hi !

A: With flexbox you can achieve that. display: inline-flex; work as display: inline-block, size's itself based on content. The flex: 1 on the flex item make them all fill the remaining space and will therefore be come equal width

.list-group {
  display: inline-flex;
  flex-direction: column;
}
.list-group-item {
  flex: 1;
  border: 1px solid gray;
}

         Name

         Longer Name

         Longest Name in the World

A: In the end of 2018, I found and used a cool feature:
https://caniuse.com/#search=max-content
ul.list-group {
  width: max-content;
}

Please try.


text:
Q: How can you strip non-ASCII characters from a string? (in C#) How can you strip non-ASCII characters from a string? (in C#)

A: I believe MonsCamus meant:
parsememo = Regex.Replace(parsememo, @"[^\u0020-\u007E]", string.Empty);

A: I found the following slightly altered range useful for parsing comment blocks out of a database, this means that you won't have to contend with tab and escape characters which would cause a CSV field to become upset.
parsememo = Regex.Replace(parsememo, @"[^\u001F-\u007F]", string.Empty);

If you want to avoid other special characters or particular punctuation check the ascii table

A: no need for regex. just use encoding...
sOutput = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(sInput));

A: I came here looking for a solution for extended ascii characters, but couldnt find it. The closest I found is bzlm's solution. But that works only for ASCII Code upto 127(obviously you can replace the encoding type in his code, but i think it was a bit complex to understand. Hence, sharing this version). Here's a solution that works for extended ASCII codes i.e. upto 255 which is the ISO 8859-1
It finds and strips out non-ascii characters(greater than 255)
Dim str1 as String= "â, ??î or ôu� n☁i✑++$-♓!‼⁉4⃣od;/⏬'®;☕:☝)///1!@#"

Dim extendedAscii As Encoding = Encoding.GetEncoding("ISO-8859-1",
                                                New EncoderReplacementFallback(String.empty),
                                                New DecoderReplacementFallback())

Dim extendedAsciiBytes() As Byte = extendedAscii.GetBytes(str1)

Dim str2 As String = extendedAscii.GetString(extendedAsciiBytes)

console.WriteLine(str2)
'Output : â, ??î or ôu ni++$-!‼⁉4od;/';:)///1!@#$%^yz:

Here's a working fiddle for the code
Replace the encoding as per the requirement, rest should remain the same.

A: string s = "søme string";
s = Regex.Replace(s, @"[^\u0000-\u007F]+", string.Empty);

The ^ is the not operator. It tells the regex to find everything that doesn't match, instead of everything that does match. The \u####-\u#### says which characters match.\u0000-\u007F is the equivalent of the first 128 characters in utf-8 or unicode, which are always the ascii characters. So you match every non ascii character (because of the not) and do a replace on everything that matches.
(as explained in a comment by Gordon Tucker  Dec 11, 2009 at 21:11)

A: This is not optimal performance-wise, but a pretty straight-forward Linq approach:
string strippedString = new string(
    yourString.Where(c => c <= sbyte.MaxValue).ToArray()
    );

The downside is that all the "surviving" characters are first put into an array of type char[] which is then thrown away after the string constructor no longer uses it.

A: If you want not to strip, but to actually convert latin accented to non-accented characters, take a look at this question: How do I translate 8bit characters into 7bit characters? (i.e. Ü to U)

A: Here is a pure .NET solution that doesn't use regular expressions:
string inputString = "Räksmörgås";
string asAscii = Encoding.ASCII.GetString(
    Encoding.Convert(
        Encoding.UTF8,
        Encoding.GetEncoding(
            Encoding.ASCII.EncodingName,
            new EncoderReplacementFallback(string.Empty),
            new DecoderExceptionFallback()
            ),
        Encoding.UTF8.GetBytes(inputString)
    )
);

It may look cumbersome, but it should be intuitive. It uses the .NET ASCII encoding to convert a string. UTF8 is used during the conversion because it can represent any of the original characters. It uses an EncoderReplacementFallback to to convert any non-ASCII character to an empty string.

A: Inspired by philcruz's Regular Expression solution, I've made a pure LINQ solution
public static string PureAscii(this string source, char nil = ' ')
{
    var min = '\u0000';
    var max = '\u007F';
    return source.Select(c => c < min ? nil : c > max ? nil : c).ToText();
}

public static string ToText(this IEnumerable<char> source)
{
    var buffer = new StringBuilder();
    foreach (var c in source)
        buffer.Append(c);
    return buffer.ToString();
}

This is untested code.

A: I used this regex expression:
    string s = "søme string";
    Regex regex = new Regex(@"[^a-zA-Z0-9\s]", (RegexOptions)0);
    return regex.Replace(s, "");

A: I use this regular expression to filter out bad characters in a filename.
Regex.Replace(directory, "[^a-zA-Z0-9\\:_\- ]", "")

That should be all the characters allowed for filenames.

A: public string ReturnCleanASCII(string s)
    {
        StringBuilder sb = new StringBuilder(s.Length);
        foreach (char c in s)
        {
            if ((int)c > 127) // you probably don't want 127 either
                continue;
            if ((int)c < 32)  // I bet you don't want control characters
                continue;
            if (c == '%')
                continue;
            if (c == '?')
                continue;
            sb.Append(c);
        }
        return sb.ToString();
    }

A: If you want a string with only ISO-8859-1 characters and excluding characters which are not standard, you should use this expression :
var result = Regex.Replace(value, @"[^\u0020-\u007E\u00A0-\u00FF]+", string.Empty);

Note : Using Encoding.GetEncoding("ISO-8859-1") method will not do the job because undefined characters are not excluded.
.Net Fiddle sample
Wikipedia ISO-8859-1 code page for more details.

A: I did a bit of testing, and @bzlm 's answer is the fastest valid answer.
But it turns out we can do much faster.
The conversion using encoding is equivalent to the following code when inlining Encoding.Convert
public static string StripUnicode(string unicode) {
    Encoding dstEncoding = GreedyAscii;
    Encoding srcEncoding = Encoding.UTF8;
    return dstEncoding.GetString(dstEncoding.GetBytes(srcEncoding.GetChars(srcEncoding.GetBytes(unicode))));
}

As you can clearly see we perform two redundant actions by reencoding UTF8. Why is that you may ask? C# exclusively stores strings in UTF16 graphmemes. These can ofc also be UTF8 graphmemes, since unicode is intercompatible. (Sidenote: @bzlm 's solution breaks UTF16 characters which may throw an exception during transcoding.)
=> The operation is independant of the source encoding, since it always is UTF16.
Lets get rid of the redundant reencoding, and prevent edgecase failures.
public static string StripUnicode(string unicode) {
    Encoding dstEncoding = GreedyAscii;
    return dstEncoding.GetString(dstEncoding.GetBytes(unicode));
}

We alreadly have a simplified and perfectly workable solution. Which requries less then half as much time to compute.
There is not much more performance to be gained, but for further memory optimization we can do two things:

*

*Accept a ReadOnlySpan<char> for a more usable api.

*Attempt to fit the tempoary byte[] unto the stack; otherwise use an array pool.

public static string StripUnicode(ReadOnlySpan<char> unicode) {
    return EnsureEncoding(unicode, GreedyAscii);
}

/// <summary>Produces a string which is compatible with the limiting encoding</summary>
/// <remarks>Ensure that the encoding does not throw on illegal characters</remarks>
public static string EnsureEncoding(ReadOnlySpan<char> unicode, Encoding limitEncoding) {
    int asciiBytesLength = limitEncoding.GetMaxByteCount(unicode.Length);
    byte[]? asciiBytes = asciiBytesLength <= 2048 ? null : ArrayPool<byte>.Shared.Rent(asciiBytesLength);
    Span<byte> asciiSpan = asciiBytes ?? stackalloc byte[asciiBytesLength];

    asciiBytesLength = limitEncoding.GetBytes(unicode, asciiSpan);
    asciiSpan = asciiSpan.Slice(0, asciiBytesLength);

    string asciiChars = limitEncoding.GetString(asciiSpan);
    if (asciiBytes is { }) {
        ArrayPool<byte>.Shared.Return(asciiBytes);
    }

    return asciiChars;
}

private static Encoding GreedyAscii { get; } = Encoding.GetEncoding(Encoding.ASCII.EncodingName, new EncoderReplacementFallback(string.Empty), new DecoderExceptionFallback());

You can see this snipped in action on sharplab.io

A: Necromancing.
Also, the method by bzlm can be used to remove characters that are not in an arbitrary charset, not just ASCII:
// https://en.wikipedia.org/wiki/Code_page#EBCDIC-based_code_pages
// https://en.wikipedia.org/wiki/Windows_code_page#East_Asian_multi-byte_code_pages
// https://en.wikipedia.org/wiki/Chinese_character_encoding
System.Text.Encoding encRemoveAllBut = System.Text.Encoding.ASCII;
encRemoveAllBut = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.InstalledUICulture.TextInfo.ANSICodePage); // System-encoding
encRemoveAllBut = System.Text.Encoding.GetEncoding(1252); // Western European (iso-8859-1)
encRemoveAllBut = System.Text.Encoding.GetEncoding(1251); // Windows-1251/KOI8-R
encRemoveAllBut = System.Text.Encoding.GetEncoding("ISO-8859-5"); // used by less than 0.1% of websites
encRemoveAllBut = System.Text.Encoding.GetEncoding(37); // IBM EBCDIC US-Canada
encRemoveAllBut = System.Text.Encoding.GetEncoding(500); // IBM EBCDIC Latin 1
encRemoveAllBut = System.Text.Encoding.GetEncoding(936); // Chinese Simplified
encRemoveAllBut = System.Text.Encoding.GetEncoding(950); // Chinese Traditional
encRemoveAllBut = System.Text.Encoding.ASCII; // putting ASCII again, as to answer the question

// https://stackoverflow.com/questions/123336/how-can-you-strip-non-ascii-characters-from-a-string-in-c
string inputString = "RäksmörПривет, мирgås";
string asAscii = encRemoveAllBut.GetString(
    System.Text.Encoding.Convert(
        System.Text.Encoding.UTF8,
        System.Text.Encoding.GetEncoding(
            encRemoveAllBut.CodePage,
            new System.Text.EncoderReplacementFallback(string.Empty),
            new System.Text.DecoderExceptionFallback()
            ),
        System.Text.Encoding.UTF8.GetBytes(inputString)
    )
);

System.Console.WriteLine(asAscii);

AND for those that just want to remote the accents:
(caution, because Normalize != Latinize != Romanize)
// string str = Latinize("(æøå âôû?aè");
public static string Latinize(string stIn)
{
    // Special treatment for German Umlauts
    stIn = stIn.Replace("ä", "ae");
    stIn = stIn.Replace("ö", "oe");
    stIn = stIn.Replace("ü", "ue");

    stIn = stIn.Replace("Ä", "Ae");
    stIn = stIn.Replace("Ö", "Oe");
    stIn = stIn.Replace("Ü", "Ue");
    // End special treatment for German Umlauts

    string stFormD = stIn.Normalize(System.Text.NormalizationForm.FormD);
    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    for (int ich = 0; ich < stFormD.Length; ich++)
    {
        System.Globalization.UnicodeCategory uc = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);

        if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)
        {
            sb.Append(stFormD[ich]);
        } // End if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)

    } // Next ich

    //return (sb.ToString().Normalize(System.Text.NormalizationForm.FormC));
    return (sb.ToString().Normalize(System.Text.NormalizationForm.FormKC));
} // End Function Latinize


text:
Q: wp_list _table You do not have sufficient permissions to access this page error I'm trying to develop a plugin which uses custom post and custom database table with class that extends the wp_list_table to show the data from a database table. But everytime I try to do something with the record it just gives me an error that I don't have sufficient permissions. I'm trying to do the rollover edit and delete and bulk action delete and also the search box. But when I click on the button it always gives me this error and I don't know why. Any suggestions?

A: I figured it out.
I just needed to change the form method from get to post and I don't have an error that I don't have sufficient permissions anymore.


text:
Q: Can't Get Google Plus to Align With Other Social Media Buttons I am trying to put a Google Plus One and other social media buttons inline next to each other. For some reason the Google Plus button has moves it down by a few pixel. It says there is a p tag separating them but there is no p tag in the code. The Google Plus code has it's own div tag but I don't know how to align it with the other buttons. I am using Wordpress.
Is there a better way to align these?
 Tweet

Wedding Photographer: Gio Morales

example of how I want it to look but need google plus:

Tweet

Wedding Photographer:
    Gio Morales

I've found out that this jQuery code works but it disables the plug in that's on the page and the 'Wedding Photographer' text that's right justified:


text:
Q: JQuery Import successful, but doesn't run I have the bare bones of what will eventually become a webpage, and am running it locally for the time being with XXAMP control panel.
My plugin is successfully linking all of the necessary files and importing the outside stuff, but JQuery does not seem to work in my javascript file. Can someone help me out?
Here are my imports:
    <!-- Most Recent JQuery -->
    <script  src="https://code.jquery.com/jquery-latest.js"></script>
    <!-- JQuery Box Shadown Plugin -->
    <script src="https://cdn.jsdelivr.net/jquery.shadow-animation/1/mainfile"></script>
    <!-- Most Recent Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <!-- Most Recent Bootsrap -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
    <!-- Most Recent Font Awesome -->
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- Fancybox for Images/Iframes -->
    <link rel="stylesheet" href="fancybox/jquery.fancybox.css" type="text/css" media="screen" />
    <!-- Custom CSS -->
    <link rel="stylesheet" href="css/custom.css">
    <!-- Fancybox JS -->
    <script src="fancybox/jquery.fancybox.pack.js"></script>
    <!-- Custom JS -->
    <script src="javascript/javascript.js"></script>

And here is the javascript file (the first is suppose to do what I want, the others are just for test cases):
$('#openIcon').hover(function(){
    console.log("Hovered");
    $('#openIcon').animate({
        boxShadow: "2px, 2px, 5px, #FFFFFF"
    }, 100, "linear");
});

$('#openIcon').click(function(){
    console.log("Clicked");
});

$('#openIcon').mouseenter(function(){
    console.log("Entered");
});

$('#openIcon').mouseleave(function(){
    console.log("Left");
});

EDIT: I already found a post on this site about the same type of problem, where the guy didn't have the https: before the two slashes. This WAS a problem that I had, but have since fixed and it has made no change.

A: Try adding $( document ).ready() :
$( document ).ready(function() {

$('#openIcon').hover(function(){
    console.log("Hovered");
    $('#openIcon').animate({
        boxShadow: "2px, 2px, 5px, #FFFFFF"
    }, 100, "linear");
});

$('#openIcon').click(function(){
    console.log("Clicked");
});

$('#openIcon').mouseenter(function(){
    console.log("Entered");
});

$('#openIcon').mouseleave(function(){
    console.log("Left");
});

});


text:
Q: Asp.Net Core Razor Pages authorization handlers for policies with Authorize attribute on PageModel still run after executing policies set to folders I'm creating a simple Asp.Net Core Web App using Razor Pages and Asp.Net Core Identity and I having an issue where the authorization handlers for policies applied to a PageModel are still executed after a policy applied for the same Page's folder despite each authorization handler is related to a different Requirement Class. My problem is that even calling Context.Fail() at the folder policy authorization handler, an unauthenticated user seems to still reach the Page and this fires the Page policy authorization handler then throws an exception because the User object is null. I want to implement a simple Flow where requests to Pages are first validated by the policies set on the Folders they belong to, ok? continue to Page (and run the Page authorization handler), not ok, return a forbidden response immediately.
Any help is really appreciated.
Requirements:
public class SectionsAccessRequirement : IAuthorizationRequirement
{
    public string SectionName { get; }

    public SectionsAccessRequirement(string Name)
    {
        SectionName = Name;
    }
}

public class RecordCreateRequirement : IAuthorizationRequirement { }

Authorization handlers:
public class SectionsAccessHandler : AuthorizationHandler<SectionsAccessRequirement>
{
    public IHttpContextAccessor _accessor;

    public SectionsAccessHandler(IHttpContextAccessor Accessor) => _accessor = Accessor;

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, SectionsAccessRequirement requirement)
    {
        // Require authentication
        if (!_accessor.HttpContext.User.Identity.IsAuthenticated) context.Fail();

        // Admin
        if (context.User.HasClaim(c => c.Type == ClaimNameConstants.UserGroup && c.Value == UserGroupConstants.AdminGroup)) context.Succeed(requirement);

        if (requirement.SectionName == SectionNameConstants.AdminSection) context.Fail();

        // Client
        if (requirement.SectionName == SectionNameConstants.ClientSection && context.User.HasClaim(c => c.Type == ClaimNameConstants.ClientSection)) context.Succeed(requirement);

        return Task.CompletedTask;
    }
}

public class RecordCreateAuthorizationHandler : AuthorizationHandler<RecordCreateRequirement>
{
    private readonly UserManager<AppUser> _users;

    public RecordCreateAuthorizationHandler(UserManager<AppUser> Users) => _users = Users;

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RecordCreateRequirement requirement)
    {
        // User ID
        int sessionUserId = int.Parse(_users.GetUserId(context.User));

        // Privileges
        if (!context.User.HasClaim(c => c.Type == ClaimNameConstants.UserGroup && c.Value == UserGroupConstants.AdminGroup))
        {
            if (context.User.HasClaim(c => c.Type == ClaimNameConstants.ClientCreate)) context.Succeed(requirement);
        }
        else
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

I have these two extension methods:
public static class AuthorizationOptionsExtension
{
    public static void AddPolicies(this AuthorizationOptions Options)
    {
        // Folders policies
        Options.AddPolicy(PolicyNameConstants.AdminSectionPolicy, p => p.Requirements.Add(new SectionsAccessRequirement(SectionNameConstants.AdminSection)));
        Options.AddPolicy(PolicyNameConstants.ClientSectionPolicy, p => p.Requirements.Add(new SectionsAccessRequirement(SectionNameConstants.ClientSection)));

        // Pages policies
        Options.AddPolicy(PolicyNameConstants.ClientRecordCreatePolicy, p => p.Requirements.Add(new Client.RecordCreateRequirement()));

        // Fallback policy
        Options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    }
}

And:
public static class RazorPagesOptionsExtension
{
    public static void AddFoldersAuthorization(this RazorPagesOptions Options)
    {
        Options.Conventions.AuthorizeFolder("/Admin", PolicyNameConstants.AdminSectionPolicy);

        Options.Conventions.AuthorizeFolder("/Client", PolicyNameConstants.ClientSectionPolicy);
    }
}

The Page's policy is applied using an Authorize attribute:
[Authorize(Policy = PolicyNameConstants.ClientRecordCreatePolicy)]
public class CreateModel : PageModel
{ ... }

This is my startup class, I'm using Asp.Net Core Identity:
public class Startup
{
    private readonly IConfiguration _config;

    public Startup(IConfiguration config)
    {
        _config = config;
    }

    // Add (and configure) services to the container
    public void ConfigureServices(IServiceCollection services)
    {
        // Global application settings (formerly known as Web.config) and other settings
        services.Configure<ApplicationSettings>(_config);

        // Application
        services.AddApplicationLayerServices();

        services.AddRazorPages();
        services.AddHttpContextAccessor();

        services.Configure<RazorViewEngineOptions>(options =>
        {
            options.PageViewLocationFormats.Add("/Pages/Shared/Partials/{0}" + RazorViewEngine.ViewExtension);
            options.PageViewLocationFormats.Add("/Pages/Client/Partials/{0}" + RazorViewEngine.ViewExtension);
        });

        // Data store
        services.AddDbContext<DataContext>(options => options.UseOracle(_config.GetConnectionString("AppConnectionString")));

        // Security
        services.AddIdentity<AppUser, IdentityRole<int>>(options => {
            options.Password.RequireUppercase = false;
            options.Password.RequiredLength = 8;
        }).AddEntityFrameworkStores<DataContext>();

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(15);

            options.LoginPath = "/SignIn";
            options.AccessDeniedPath = "/FourZeroSomething";
            options.SlidingExpiration = true;
        });

        services.AddAccessControlLayerServices();

        services.AddAuthorization(options => options.AddPolicies());

        services.Configure<RazorPagesOptions>(options => options.AddFoldersAuthorization());
    }

    // Configure the HTTP request pipeline
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }

        // Navigation
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();

        // Security
        app.UseAuthentication();
        app.UseAuthorization();

        // Endpoints
        app.UseEndpoints(endpoints => endpoints.MapRazorPages());
    }
}

}

A: As detailed in the docs, this behaviour is by design:

If a handler calls context.Succeed or context.Fail, all other handlers are still called. This allows requirements to produce side effects, such as logging, which takes place even if another handler has successfully validated or failed a requirement. When set to false, the InvokeHandlersAfterFailure property short-circuits the execution of handlers when context.Fail is called. InvokeHandlersAfterFailure defaults to true, in which case all handlers are called.

If you'd rather not set the InvokeHandlersAfterFailure option, you can check the AuthorizationHandlerContext.HasFailed property in your more specific handlers to see if it's false and return early. e.g.:
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RecordCreateRequirement requirement)
{
    if (context.HasFailed)
        return;

    // User ID
    int sessionUserId = int.Parse(_users.GetUserId(context.User));

    // ...
}


text:
Q: What factors affect the rate of decay of a radioactive atom? I saw a specific quote that made me question this :
"Other atoms in the universe don't influence the rate, it's just an intrinsic property of each separate atom that it has some chance to decay."
(from this Q&A)
I'm assuming there are some factors that do influence rate of decay? Also assuming that statement is generally correct in a broad sense, or even technically correct because it only mentions other atoms not influencing the rate - I've no idea, why I'm asking.
But there has to be some factors that influence rate of decay, even if only at a quantum level, right?
I've read here amongst other answers. I understand this may not be answerable, or the answer is simply "best evidence says its random" - but that question is 3 years old, and I'm hoping maybe the consensus has changed/shifted/new concepts are being explored.
I'm also curious about environmental factors. i.e. could uranium 233 decay differently (more rapidly/slowly), on average, in different settings? What causes the differences (pressure, presence of other atoms, ?) - this part I've yet to find any answer on, the others, I assume, imply a standard environment to show randomness of decay.
To go further, and my apologies if my ignorance is showing, does the presence of one versus many atoms change the rate of decay (again, avg)
To restate the question (title): What factors affect the rate of decay of an atom?
Please comment with any improvements

A: There is one factor that definitely influences decay rates: speed. An accelerated radioactive nucleus will decay slower due to relativistic effects. An extreme example of this are cosmic ray-generated muons. A muon at rest decays to an electron, a neutrino, and an anti-neutrino after 2.2 microseconds on average. This would mean that, if it was traveling very close to the speed of light, it could only go about 660 meters before decaying. But, muons generated by cosmic rays high in the atmosphere are detectable on the ground dozens of kilometers below where they are created. This is because the muons are traveling at high speed and so decay at a slower rate due to time dilation.
Other effects require some interpretation. A critical mass of radioactive substance, such as in a nuclear fission bomb, can result in not just a speeding up of decay, but in an exponential explosion of decay. In a fission bomb, the neutrons released from one radioactive decay trigger the decay of multiple neighboring atoms. In one sense, the surrounding atoms speed up the decay of a given atom. In another sense, the neutrons bouncing around transmute the original isotopes into more radioactive isotopes. If a bomb uses uranium-235, you could say that the decay rate has not changed; the neutrons in the environment changed the $^{235}U$ to an excited $^{236}U$, which is much more unstable. So, everything decays at its natural rate.
There is an ongoing controversy regarding decay rates. Some labs that measure the rates of radioactive decay claim to see annual variations of about 0.1%. I call this controversial because some labs see the variation, some don't. The labs that do see variation posit that the changes are related to the Earth's distance from the Sun so that the local density of neutrinos or other particles are the cause of the variation. Those that are skeptical of the observation say that the labs have unaccounted for errors in their measurements. Here's a bibliography from December 2020 of hundreds of papers on the topic, both for and against. Again, the claim of decay rate variation is very controversial and most physicists are skeptical.


text:
Q: Translating DECODE in Postgres How can I translate the DECODE expression in Postgres?
MAX(DECODE(r.name,'AREA_SEC_TRANVERSAL',r.value,NULL)) AREA

I found the following type, but i did not know how "MAX" can fit in this case.
CASE search-expression
    WHEN expression [, expression [ ... ]] THEN
      statements
  [ WHEN expression [, expression [ ... ]] THEN
      statements
    ... ]
  [ ELSE
      statements ]
END CASE;

A: You can just keep max as is:
MAX(CASE
      WHEN r.name = 'AREA_SEC_TRANVERSAL'
      THEN r.value
    END) AREA

or
MAX(CASE r.name
      WHEN 'AREA_SEC_TRANVERSAL'
      THEN r.value
      ELSE null
    END) AREA

A: A common translation would use case a expression:
MAX(CASE WHEN r.name = 'AREA_SEC_TRANVERSAL' THEN r.value END) as AREA

In fact, the general replacement for DECODE() is CASE, which is the SQL standard for conditional logic -- I would recommend CASE even in databases that support DECODE().
However, Postgres supports the standard SQL filter operator.  I would recommend using this instead:
MAX(r.value) FILTER (WHERE r.name = 'AREA_SEC_TRANVERSAL') as AREA

I find this easier to follow (perhaps now that I'm used to it).  More importantly, it gives the optimizer better options for improving performance.


text:
Q: how to add double quotes to a string which contains comma? I successfully imported following file in database but my import method removes double quotes during saving process. but i want to export this file as it is , i.e add quotes to a string which contains delimiter so how to achieve this .
here is my csv file with headers and 1 record.
PTNAME,REGNO/ID,BLOOD GRP,WARD NAME,DOC NAME,XRAY,PATHO,MEDICATION,BLOOD GIVEN
Mr. GHULAVE VASANTRAO PANDURANG,SH1503/00847,,RECOVERY,SHELKE SAMEER,"X RAY PBH RT IT FEMUR FRACTURE    POST OP XRAY   -ACCEPTABLE WITH IMPLANT IN SITU    2D ECHO MILD CONC LVH  GOOD LV SYSTOLIC FUN,  ALTERED LV DIASTOLIC FUN.",  HB-11.9gm%  TLC-8700  PLT COUNT-195000  BSL-173  UREA -23  CREATININE -1.2  SR.ELECTROLYTES-WNR  BLD GROUP-B +  HIV-NEGATIVE  HBsAG-NEGATIVE  PT INR  -15/15/1.0.    ECG  SINUS TACHYCARDIA  ,IV TAXIMAX 1.5 GM 1-0-1      IV TRAMADOL DRIP 1-0-1      TAB NUSAID SP     1-0-1      TAB ARCOPAN D 1-0-1      CAP BONE C PLUS 1 -0-1      TAB ANXIT 0.5 MG 0-0-1        ANKLE TRACTION 3 KG RT LL  ,NOT GIVEN

Here is my method of export:
    public void DataExport(string SelectQuery, string fileName)
    {
        try
        {
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(SelectQuery, con);
            da.Fill(dt);

            //Sets file path and print Headers
          //  string filepath = txtreceive.Text + "\\" + fileName;
            string filepath = @"C:\Users\Priya\Desktop\R\z.csv";
            StreamWriter sw = new StreamWriter(filepath);

            int iColCount = dt.Columns.Count;

            // First we will write the headers if IsFirstRowColumnNames is true: //
            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(dt.Columns[i]);

                if (i < iColCount - 1)
                {
                    sw.Write(',');
                }
            }
            sw.Write(sw.NewLine);

            foreach (DataRow dr in dt.Rows) // Now write all the rows.
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        sw.Write(dr[i].ToString());
                    }

                    if (i < iColCount - 1)
                    {
                        sw.Write(',');
                    }
                }
                sw.Write(sw.NewLine);
            }
            sw.Close();
        }
        catch { }
    }

A: if (myString.Contains(","))
{
    myWriter.Write("\"{0}\"", myString);
}
else
{
    myWriter.Write(myString);
}

A: The very simplest thing that you can do is replace the line sw.Write(dr[i].ToString()); with this:
var text = dr[i].ToString();
text = text.Contains(",") ? String.Format("\"{0}\"", text) : text;
sw.Write(text);

However, there are quite a few other issues with your code - most importantly you are opening a lot of disposable resources without disposing them properly.
I'd suggest a bit of a rewrite, like this:
public void DataExport(string SelectQuery, string fileName)
{
    using (var dt = new DataTable())
    {
        using (var da = new SqlDataAdapter(SelectQuery, con))
        {
            da.Fill(dt);

            var header = String.Join(
                ",",
                dt.Columns.Cast<DataColumn>().Select(dc => dc.ColumnName));

            var rows =
                from dr in dt.Rows.Cast<DataRow>()
                select String.Join(
                    ",",
                    from dc in dt.Columns.Cast<DataColumn>()
                    let t1 = Convert.IsDBNull(dr[dc]) ? "" : dr[dc].ToString()
                    let t2 = t1.Contains(",") ? String.Format("\"{0}\"", t1) : t1
                    select t2);

            using (var sw = new StreamWriter(fileName))
            {
                sw.WriteLine(header);
                foreach (var row in rows)
                {
                    sw.WriteLine(row);
                }
                sw.Close();
            }
        }
    }
}

I've also broken apart the querying of the data from the data adapter from the writing of the data to the stream writer.
And, of course, I'm adding double-quotes to text that contains commas.
The only other thing I was concerned about was the fact that con is clearly a class-level variable and it is being left open. That's bad. Connections should be opened and closed each time they are used. You should probably consider making that change too.
You could also remove the stream write entirely by replacing that block with this:
File.WriteAllLines(fileName, new [] { header }.Concat(rows));

And, finally, wrapping your code in a try { ... } catch { } is just a bad practice. It's like saying "I'm writing some code that could fail, but I don't care and I don't want to be told if it does fail". You should only even catch specific exceptions that you do deal with. In this code you should consider catching file exceptions like running out of hard drive space, or writing to a read-only file, etc.


text:
Q: Whats the implication of SSD Capacity for a server running Elastic Search I'm evaluating Bonsai Elastic Search packages to run my elastic search operations but I don't understand all plan specifications. What are the implications of SSD capacity?
Source: https://elements.heroku.com/addons/bonsai
I've researched that SSD = solid state drive, but I don't understand what that means in this context.
What is "SSD capacity" in the context of a server running elastic search and when would it need to be increased?


text:
Q: How to set NSLocalNotification to run on monthly or weekly basis for the same time scheduled? I have my app with data coming from server. I have 2 type of notifications say monthly. Now I will get data say for month with (date-time format) 2-2:30,6-9:00,23-10:00,26-12:00. where 2 denotes date followed by time with colon (:) format.
Now I want to run the notification every month on the same dates and time. I am able to run the multiple notifications. But they do not repeat every month. How to do that? Following is my code for the same.
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
          [UIApplication sharedApplication].idleTimerDisabled = YES;
            UIUserNotificationSettings *notiSett = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:NULL];
            [[UIApplication sharedApplication]registerUserNotificationSettings:notiSett];
                    [self generateLocalNotificationDaily];
    }

   -(void)generateLocalNotificationDaily
{
//  [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [self compareDateDaily];
}

-(void)compareDateDaily
{
    NSString *strTime = [Helper getPREF:PREF_AlARM_DAILY_TIME];
    NSArray *arrtime = [strTime componentsSeparatedByString:@","];

    for(int i=0;i<[arrtime count];i++)
    {
        NSArray *arrfirstTime = [[NSString stringWithFormat:@"%@",[arrtime objectAtIndex:i]]componentsSeparatedByString:@":"];

        int hh = (int)[[arrfirstTime objectAtIndex:0]integerValue];
        int mm = (int)[[arrfirstTime objectAtIndex:1]integerValue];

        NSDate *now = [NSDate date];
        NSTimeInterval secondsPerDay = 1;//24 * 60 * 60;
        NSDate *date = [now dateByAddingTimeInterval:secondsPerDay];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
        [components setHour:hh];
        [components setMinute:mm];
        NSDate *todaySpecificDate = [calendar dateFromComponents:components];

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        [formatter setTimeZone:[NSTimeZone systemTimeZone]];
        NSDate *currentDate = [NSDate date];
        NSString *strCurrentDate = [formatter stringFromDate:currentDate];
        NSString *strSystemDate = [formatter stringFromDate:todaySpecificDate];
        currentDate = [formatter dateFromString:strCurrentDate];
        todaySpecificDate = [formatter dateFromString:strSystemDate];

        NSComparisonResult result = [currentDate compare:todaySpecificDate];

        NSString *strAlertMessage = [NSString stringWithFormat:@"%@",[Helper getPREF:PREF_AlARM_MESSAGE]];
        NSString *strUserName = [Helper getPREF:PREF_NAME];
        NSString *strmsg = [strAlertMessage stringByReplacingOccurrencesOfString:@"user_name" withString:strUserName];
        NSString *alertMsg = [strmsg stringByReplacingOccurrencesOfString:@"notification_type" withString:@"daily"];

        //
        switch (result)
        {
            case NSOrderedAscending:
            {
                UILocalNotification* localNotificationDaily = [[UILocalNotification alloc] init];
                localNotificationDaily.fireDate = todaySpecificDate;
                localNotificationDaily.alertBody = alertMsg;
                localNotificationDaily.repeatInterval = NSCalendarUnitDay;

                localNotificationDaily.soundName = UILocalNotificationDefaultSoundName;
                [[UIApplication sharedApplication] scheduleLocalNotification:localNotificationDaily];
                NSLog(@"%@ is in future from %@", todaySpecificDate, currentDate);
            }
                break;
            case NSOrderedDescending:
                NSLog(@"%@ is in past from %@", todaySpecificDate, currentDate);
                break;
            case NSOrderedSame:
                NSLog(@"%@ is the same as %@", todaySpecificDate, currentDate);
                break;
            default:
                NSLog(@"erorr dates %@, %@", todaySpecificDate, currentDate);
                break;
        }
    }
}

A: there is a property in uiLocalNotification "repeatInterval". You have to set the repeat interval to month like this
localNotificationMonthly.repeatInterval = NSCalendarUnitMonth;

It will repeat your notification every month depending upon the date and time you set for the notification. For further inquiry please refer to
https://developer.apple.com/library/ios/documentation/iPhone/Reference/UILocalNotification_Class/#//apple_ref/occ/instp/UILocalNotification/repeatInterval
for week repeat interval would be NSCalendarUnitWeekOfYear


text:
Q: Why is this pygame program not working so when I hover over the computer screen it turns blue? Hello I am quite new to pygame and I am trying to make an intro for a game where the user hovers over the computer screen and the screen then turns blue so indicate that when you press it the game will start. However, the blue rect simply isn't showing up?
By the way, the introScreen is a like a gif but constructed from many different frames.
This is my code:
import pygame
import pygame.gfxdraw
import threading

pygame.init()

width = 800
height = 600
fps = 30
clock = pygame.time.Clock()

white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

screen = pygame.display.set_mode((width, height))

def introLoop():

    while intro:

        for i in range(0, 26):

            clock.tick(8)

            i = str(i)

            introScreen = pygame.image.load("introScreen/" + i + ".gif")
            introScreen = pygame.transform.scale(introScreen, (width, height))

            screen.blit(introScreen, (30, 30))

            pygame.display.flip()

def gameLoop():

    while intro:

        mouseX, mouseY = pygame.mouse.get_pos()
        startRectArea = pygame.Rect(279, 276, 220, 128)

        if startRectArea.collidepoint(mouseX, mouseY):

            StartRect = pygame.draw.rect(screen, blue, (279, 276, 220, 128), 0)

            pygame.display.update()

    for event in pygame.event.get():

        holder = 0

introThread = threading.Thread(target = introLoop)
gameThread = threading.Thread(target = gameLoop)

intro = True

introThread.start()
gameThread.start()

There is no error message it just doesn't display the blue rect?
Please help as I need this for a school project.

A: To use multithreading in PyGame, you've to consider 2 things:

*

*Process an event loop in the main thread

*Do all the drawing on and the update of the window in a single thread. If there is an "intro" thread and a "game" thread, then the "intro" thread has to terminate first, before the "game" thread can start.
In the main thread (program) you've to declare the threads and to initialize the control (state) variables. Start the "intro" thread immediately and run the event loop.
I recommend to implement at least the pygame.QUIT, which signals that the program has to be terminated (run = False).
Further it can be continuously checked if the mouse is in the start area (inStartRect = startRectArea.collidepoint(*pygame.mouse.get_pos())):
introThread = threading.Thread(target = introLoop)
gameThread = threading.Thread(target = gameLoop)

run = True
intro = True
inStartRect = False
startRectArea = pygame.Rect(279, 276, 220, 128)

introThread.start()

while run:
    if intro:
        inStartRect = startRectArea.collidepoint(*pygame.mouse.get_pos())
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.MOUSEBUTTONDOWN and inStartRect:
            intro = False

In the intro thread the entire intro screen has to be drawn, including the background and the blue start area. If the intro is finished (the game is started), then at the end of the intro thread the main game loop is started:
def introLoop():

    i = 0
    while run and intro:
        clock.tick(8)

        filename = "introScreen/" + str(i) + ".gif"
        i = i+1 if i < 26 else 0

        introScreen = pygame.image.load(filename)
        introScreen = pygame.transform.scale(introScreen, (width, height))

        screen.blit(introScreen, (30, 30))
        if inStartRect:
            pygame.draw.rect(screen, blue, (279, 276, 220, 128), 0)
        pygame.display.flip()

    gameThread.start()

The game thread starts, when the intro thread terminates. So the game thread can do the drawing of the game scene:
def gameLoop():

    while run:
        clock.tick(60)

        screen.fill(red)

        # [...]

        pygame.display.flip()
        clock.tick(60)

A: Try passing intro directly into the introLoop function. Pass arguments into the thread with the args parameter...
introThread = threading.Thread(target=introLoop, args=(intro))

You will also have to redefine the function as well:
def introLoop(intro):

A: Try converting the images you want to load with .convert()
pygame.image.load("image file path").convert()

Or try converting the image to an image with .convert_alpha()
pygame.image.load("image file path").convert_alpha()

Pygame finds it MUCH easier and faster to load images that are converted with .convert(), and with .convert_alpha() it converts the images with their alpha layers (E.G. Transparency...) Hope this helps!
for more information, see these google results:
I recommend the first link, although this link is pretty pointless


text:
Q: Build definition to compare branches Not sure if I am using the correct tool/approach, but here is what I am trying to do:
We have TFS 2010 and a number of branches. A number of times we have a parent branch and a feature branch. Different teams are working on both branch, and we need to make sure that branch A(parent) is always merged in branch B(feature/child). Normally we have a manual process in place so that somebody is assigned to merge once or twice a week.
I am trying to add an automated check for this. Is it possible to create a build definition which i can execute nightly, and it can compare two branches and send an alert(or failed build), in case branch B does not have any contents of branch A?
i already have nightly build happening, so perhaps I can add something to it to do this comparison and somehow flag a failure or alert?

A: You could use the tf folderdiff command.  So it would look something like this where you would send the output to a file to process and look for summary differences.  Perhaps you could do the summary check in the pipeline but that would be more complicated.
> & 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\tf.exe' `
   folderdiff $/branchA/folder $/branchB/folder /recursive /noprompt `
   | out-file c:\temp.txt

You may also filter out file types you don't want to compare.


text:
Q: An error show "The method XXX is undefined for the type XXX"... Is there something wrong with my JFrame? Long story short, I want to create using my own JFrame, since I'm using SpringLayout, it's much easier for me not to use extends JFrame.
Instead I got an error when I'm try to call the frame in
public static void main(String[] args)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DatingMatch
{
  JFrame frame = new JFrame("Dating Match");
  Container contentPane = frame.getContentPane();
  SpringLayout layout = new SpringLayout();

  private JMenuBar mainbar = new JMenuBar();
  private JMenu menu1 = new JMenu("FILE");
  private JMenu menu2 = new JMenu("HELP");
  private JMenuItem close = new JMenuItem("CLOSE");
  private JMenuItem about = new JMenuItem("ABOUT");
  private JMenuItem help = new JMenuItem("HELP");

  private JLabel name = new JLabel("NAME :");
  private JTextField nameF = new JTextField(40);

  private JLabel address = new JLabel ("CITY :");
  private JTextField addressF = new JTextField(40);

  private JLabel phoneNum = new JLabel("PHONE NO. : ");
  private JTextField phoneNumF = new JTextField(40);

  private JLabel gender = new JLabel("GENDER");
  private String genderS[] = {"MALE","FEMALE"};
  private JComboBox genderC = new JComboBox(genderS);

  private JButton next = new JButton("NEXT");

  public static void main(String[] args)
  {
    DatingMatch frame = new DatingMatch();
    frame.setVisible(true);

  }
}


text:
Q: Variable number of arguments to a single function I tried some code but I am not getting a satisfactory answer. The output of the code should be the exact number arguments from the call site:
>>> def  Hello(PitU,*V):
    print("you passed" , PitU,"Arguments")
    for Pit in V:
        print(Pit)

#case1
>>> Hello(3,"one","two","three")
you passed 3 Arguments
one
two
three

#case2
>>> Hello(3,"one","two")
you passed 3 Arguments
one
two

#case3
>>> Hello(3,"one","two","three","four")
you passed 3 Arguments
one
two
three
four
>>>

I expect the output to be:
A. case-1
you passed 3 Arguments
one
two
three

B. case-2
error

C. case-3
error

instead of

Case1
you passed 3 Arguments
one
two
three

case2
you passed 3 Arguments
one
two

case3
you passed 3 Arguments
one
two
three
four

A: For that you need to put a check yourself, python won't do that for you.
def Hello(PitU, *V):
    if len(V) != PitU:
        print("error")
        return
    print("you passed", PitU, "Arguments")
    for Pit in V:
        print(Pit)

A: Because PITu isn't the number of the arguments you must pass, it's just another argument you put there. there is nothing wrong with python technique, you just misunderstood its concept.


text:
Q: Orthonormal basis of a vector space with polynomials of the form $ax+b$ Find the Orthonormal basis of vector space $V$ of the linear polynomials of the form $ax+b$  such that  $\:$, $p:[0,1] \to \mathbb{R}$. with inner product
$$\langle p,q \rangle= \int_0^1 p(x)q(x) dx$$ for $q, p \in V$
The polynomial in $V$ are linear so the basis of $V$ are $\left \{1,x  \right \}$ further i am not getting how to proceedes further
please help
Thankyou.

A: With Gram-Schmidt
$v_{1} = 1$, $v_{2} = \frac{x - <x,v_{1}>v_{1}}{ \| x - <x,v_{1}> v_{1}\|} $
So $<x,1> = \int_{[0,1]}xdx = \frac{1}{2}$
And $\| x - <x,1> \|^{2} = \int_{[0,1]} (x - \frac{1}{2})^{2} = \frac{1}{12}$
Then $v_{2} = \frac{x - \frac{1}{2}}{\sqrt{12}}$
$\{v_{1},v_{2} \}$ is a orthonormal basis

A: An orthonormal base can be
$\{1,\frac{(x-\frac{1}{2})}{\sqrt{\langle x-\frac{1}{2},x-\frac{1}{2}\rangle}}\}$
The idea is simple. The space has dimension $2$, so you must choose two polynomials of order at most $1$.
The first polynomial can be $1$, that has norm $1$. Then the second polynomial $p$ must verifies the condition
$\langle 1,p\rangle =\int_0^1pdx=0$
Moreover $p$ must be unitary so you can simply consider
$q=\frac{p}{\sqrt{\langle p,p\rangle}}$
So
$\{1,q\}$ is an orthonormal base for your space.
How can you calcolate $p$?
You can observe that
$\int_0^1 xdx=\frac{1}{2}$ so
$\int_0^1 xdx-\frac{1}{2}=\int_0^1( x-\frac{1}{2})dx=0$
Then you can choose
$p:=x-\frac{1}{2}$
You can observe that, fixed a polynomial $s$, you can always choose $p=s-\int_0^1sdx$
because
$\langle 1,p\rangle =\int_0^1 p dx=0$
This is not a mysterious result because it follows the same idea of the Gram-Schmidt orthogonalization

A: A standard approach for these types of problems is to use the Gram-Schmidt procedure:

You already found a basis of $V$, so let $\mathbf{v}_1=1$ and $\mathbf{v}_2=x$. Then an orthogonal basis $\{\mathbf{u}_1,\mathbf{u}_2\}$ is given by:
$$\mathbf{u}_1=\mathbf{v}_1$$
$$\mathbf{u}_2=\mathbf{v}_2-\frac{\langle \mathbf{v}_2,\mathbf{u}_1\rangle}{\langle \mathbf{u}_1,\mathbf{u}_1\rangle}\mathbf{u}_1$$
So in your case, all you have to do is compute two simple integrals.
An orthonormal basis $\{\mathbf{w}_1,\mathbf{w}_2\}$ can be found by normalizing the two vectors $\mathbf{u}_1$ and $\mathbf{u}_2$. Namely:
$$\mathbf{w}_1=\frac{\mathbf{u}_1}{\|\mathbf{u}_1\|}=\frac{\mathbf{u}_1}{\sqrt{\langle \mathbf{u}_1,\mathbf{u}_1\rangle}}$$
$$\mathbf{w}_2=\frac{\mathbf{u}_2}{\|\mathbf{u}_2\|}=\frac{\mathbf{u}_2}{\sqrt{\langle \mathbf{u}_2,\mathbf{u}_2\rangle}}$$
This requires the computation of one additional (easy) integral.


text:
Q: TreeView nodes not being displayed
Possible Duplicate:
XAML Code for TREEVIEW

Following is the code for TreeView in XAML:
<TreeView Height="338" HorizontalAlignment="Left" Margin="6,6,0,0"
          Name="DisksTreeView1" VerticalAlignment="Top" Width="293">
    <TreeView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding ImagePath}" Width="32" Height="32"/>
                <TextBlock Text="{Binding Namee}"/>
            </StackPanel>
        </DataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

And following is the code behind:
Dim adpt As New DatabaseDearDataSetTableAdapters.DiskListTableAdapter
For Each k As KeyValuePair(Of String, GenreSet) In GenreSetDictionary
    Dim t As New TreeNodeSet
    t.Genre = True
    t.Imagepath = k.Value.IconPath
    t.Namee = k.Key
    Dim pnode As New TreeViewItem
    pnode.DataContext = t
    For Each z As DatabaseDearDataSet.DiskListRow In adpt.GetDataByGenre(t.Namee)
        Dim tt As New TreeNodeSet
        tt.Genre = False
        tt.Imagepath = IconDictionary(z.DiskIcon).IconPath
        tt.Namee = z.DiskName
        Dim cnode As New TreeViewItem
        cnode.DataContext = tt
        pnode.Items.Add(cnode)
    Next
    DisksTreeView1.Items.Add(pnode)
Next

I am able to get the pnode added to the TreeView and all the node breakpoints are hit.  The problem is that in the TreeView, I am only able to see the parent view arrow, the rest of the name, image, etc. are not getting displayed. It is like this:

How can I fix this?

A: In your code-behind you are creating a TreeViewItem instances and adding them to the TreeView. But what you need to do - is to define your model classes in a hierarchical way, bind top level items collection to the ItemsSource property of the TreeView, and use HierarchicalDataTemplate instead of the DataTemplate to display nested items.

A: The answer for the above issue is displayed at the following page:
XAML and Required Code Set


text:
Q: rEFInd: very slow boot when using EFI Stub Loader After a recent re-install, I found myself experiencing a very strange problem with rEFInd: while it detects both GRUB and vmlinuz on my /boot partition, using the latter is extremely slow.
Specifically, immediately after selecting "Boot vmlinuz-4.8.0-53-generic from 191 MiB ext2 volume", I'm shown a black screen with the following text:
Starting vmlinuz-4.8.0-53-generic
Using load options 'root=UUID=6641e1e2-6829-49cc-bf88-85ba5eefbff8 ro quiet splash nomodeset vt.handoff=7 initrd=\initrd.img-4.8.0-53-generic'

After about a minute of waiting (!), Linux boots normally (and rather quickly).
If I select GRUB on the other hand, I'm taken to the GRUB boot menu and, after selecting the default option, Linux immediately starts booting.
What could be the reason for this?
My setup includes an SSD (where I have Linux and Windows installed) and an HDD (where my /home is), with a an ext2 /boot partition and the EFI partition (created by Windows initially) mounted on /boot/efi. Here's my /etc/fstab:
UUID=6641e1e2-6829-49cc-bf88-85ba5eefbff8 /               ext4    errors=remount-ro 0       1
UUID=3c804805-c41e-4b9d-af02-118b98858ae4 /boot           ext2    defaults        0       2
UUID=8EA5-5319  /boot/efi       vfat    umask=0077      0       1
UUID=bf088ec8-140d-4829-8de7-deb1d375b0e5 /home           ext4    defaults        0       2
UUID=E2A8CA84A8CA5727 /mnt/Windows    ntfs    defaults,umask=007,gid=46 0       0
UUID=3fb0b28d-87d8-4162-b469-1c157a4d00b0 none            swap    sw              0       0

A: I'm rEFInd's maintainer.
This is a filesystem driver issue. For reasons I don't fully understand, some of rEFInd's filesystem drivers (especially the ext2_x64.efi driver) are slow on some computers. I added a crude readahead cache to the driver code several years ago, and this helped a lot -- under VirtualBox, the speed improved from about a 3-minute load time to a few tens of seconds, IIRC. Some computers continue to have problems even with this cache, though.
The solution is to change to another filesystem. rEFInd's ext4fs driver is much faster than its ext2/3fs driver, and the Btrfs and ReiserFS drivers are faster still. (Note that the ext4fs driver can read ext2fs, but will provide little or no speed improvement that way; it needs to read an actual ext4 filesystem to provide a speed improvement.) In a worst-case scenario, you could use FAT, which requires no special driver (it's built into all EFIs); or on a Mac, you could use HFS+. (There's also an HFS+ driver that comes with rEFInd, so in principal you could use HFS+ even on a non-Mac PC, but there's little or no point to doing so.) Moving outside of a standard Linux filesystem is inadvisable, though. Ubuntu relies on symbolic links for some (but not all) kernel updates, making FAT a poor choice; and although HFS+ should work, it's not officially supported by Ubuntu. Even ReiserFS is not an option in the Ubuntu installer, so I'd steer clear of it for Ubuntu. That leaves ext4fs and Btrfs.
Switching is fairly straightforward, but not risk-free -- if you make a mistake, your system might be rendered unbootable. The bare-bones procedure is:

*

*Copy the new filesystem driver to the rEFInd drivers or drivers_x64 subdirectory (/boot/efi/EFI/refind/drivers or /boot/efi/EFI/refind/drivers_x64, probably). Removing the old ext2_x64.efi file from that location will reduce rEFInd's load time by a second or so.

*Unmount the ESP (/boot/efi).

*Back up the /boot partition. You can use zip, tar, cp, or some other file-level tool for this.

*Unmount /boot.

*Create a new filesystem on the /boot partition.

*Type sudo blkid /dev/sda{x} (changing /dev/sda{x} to the identifier for your /boot partition) to learn its new UUID value.

*Edit /etc/fstab to change the UUID value and filesystem type for the /boot partition.

*Type sudo mount -a to mount the new /boot partition. (It will likely complain that there's no /boot/efi mount point. You can ignore this warning.)

*Restore the backed-up /boot files to the new /boot filesystem.

At this point, you should be able to reboot and it will work better. A mistake, though, could cause the system to be unbootable. To reduce that risk, you can copy at least one working kernel, initrd file, and refind_linux.conf from /boot to /boot/efi and test your ability to boot the kernel from the ESP before you begin. This will give you a fallback way of booting in case of a problem. If there are no problems, you can of course delete the kernel from the ESP once you're done.
For more on rEFInd's drivers, see its documentation on this subject:
http://www.rodsbooks.com/refind/drivers.html


text:
Q: Class method picks hidden base class property over new subclass property I'm trying to write a unit test for one of my classes that uses a base class from a third party library, but my first attempt is fragile as the tests depend on integration with texts managed by content managers.
First, a small repro. This will represent the third party base class I have to work with:
namespace ThirdPartyXyz
{
    public class SomeFancyBaseClass
    {
        public SomeFancyBaseClass()
        {
            this.myMap = new Dictionary<string, string> { { "title", "Greatness" } };
        }

        public IReadOnlyDictionary<string, string> myMap { get; private set; }
    }
}

Then I'm unit testing code along these lines:
namespace MyCorp
{
    public class MyThing : ThirdPartyXyz.SomeFancyBaseClass
    {
        public string GetHeadline()
        {
            return "[" + this.myMap["title"] + "]";
        }
    }
}

With the following NUnit test method:
namespace MyCorp.UnitTestExperiments
{
    [TestFixture]
    public class MyThingTests
    {
        [Test]
        public void GetHeadlineWillOutputBracketedResource()
        {
            var thing = new MyThing();
            var result = thing.GetHeadline();
            Assert.That(result, Is.EqualTo("[Greatness]"));
        }
    }
}

This is green, but will turn red if a content manager changes the "Greatness" value to something else. So I'm trying to mock / stub / fake the actual dictionary from the base class, but this is not straightforward because the third party library declares myMap's dictionary setter as private.
Here's what I've tried:
namespace MyCorp.UnitTestExperiments
{
    [TestFixture]
    public class MyThingTests
    {
        private class TestableMyThing : MyThing
        {
            public TestableMyThing(Dictionary<string, string> texts) { this.myMap = texts; }
            public new IReadOnlyDictionary<string, string> myMap { get; private set; }
        }

        [Test]
        public void GetHeadlineWillOutputBracketedResource()
        {
            var fakeTexts = new Dictionary<string, string> { { "title", "test text" } };
            var thing = new TestableMyThing(fakeTexts);
            var result = thing.GetHeadline();
            Assert.That(result, Is.EqualTo("[test text]"));
        }
    }
}

However, this doesn't work: the test still fails. The GetHeadline method uses the hidden myMap property from SomeFancyBaseClass as opposed to the fake dictionary containing the "test text".
My goals / questions currently are two-fold. First, by now I'm curious how I (c/w)ould get my current approach to work. But second, I fear my way of making MyThing testable is not the best one, and would like to know if there's a way to avoid this situation altogether.

A: Three options:

*

*Use reflection to access the seter of the dictionary

*Second option, make your class more easily to stub:
public class MyThing : ThirdPartyXyz.SomeFancyBaseClass
{
    public virtual new IReadOnlyDictionary<string, string> myMap;
    {
        get { return base.myMap; }
    }

    public string GetHeadline()
    {
        // this will use your 'virtual new myMap'!
        return "[" + this.myMap["title"] + "]";
    }
}

Now in your unit tests you can:
public class MyThingTestable : MyThing
{
     public override IReadOnlyDictionary<string, string> myMap { get; set; }
}

and now you can set the myMap, and your class will use it (but note that the SomeFancyBaseClass class won't use it! It will use its myMap! Not very good!)

*Third option: use Microsoft Fakes or similar product.


text:
Q: Building an android library in Jitpack: ERROR: No build artifacts found I've forked an Android library and merge some changes that I need
https://github.com/ceessay/kdgaugeView
In order to use the library in my Android project I've tried publishing it on Jitpack.
The problem is after pushing changes on Github, the builds on Jitpack seem to pass but there's this message
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.5.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 543ms
4 actionable tasks: 1 executed, 3 up-to-date
Build tool exit code: 0
Looking for artifacts...
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dhttps.protocols=TLSv1.2
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dhttps.protocols=TLSv1.2
Looking for pom.xml in build directory and ~/.m2
2020-07-13T12:27:13.425592193Z
Exit code: 0
ERROR: No build artifacts found

full log here: https://jitpack.io/com/github/ceessay/kdgaugeView/1.0.5/build.log
Adding the library in my project also failes with the following message:

Could not find com.github.ceessay:kdgaugeView:1.0.4.

I've followed the guidelines on Jitpack documentation, Upgraded gradle on the library but i wont work.
I am new to publishing libraries for Android so I might be missing something. Any clue of what that is ?

A: You can use the maven-publish gradle plugin. The documentation for maven-publish is https://developer.android.com/studio/build/maven-publish-plugin.
I'm sure it's also possible to use com.github.dcendents.android-maven which is already in that project, but it isn't as obvious to me.
You can also check out the excellent plugin https://vanniktech.github.io/gradle-maven-publish-plugin/.

A: Spent half a day fighting the same problem. I forgot to define publication for my artifact in build.gradle.kts:
publishing {
  publications {
    create<MavenPublication>("maven") {
      groupId = "com.github.username"
      artifactId = "library-name"
      version = "1.0.0"

      from(components["kotlin"])
    }
  }
}

Hope, this helps.


text:
Q: asp checkbox oncheckedchanged not firing that is inside a bootstrap popover I am having an issue where the oncheckedchanged event does not fire when the checkbox is inside a bootstrap popover. The event fires up when it is not inside a popover.
I am working with a grid that has few fields and one of them is an asp:Button that is used to pop the bootstrap popover from the code behind like this.
 if (e.CommandName == "Actions")
        {
            var button = e.CommandSource as Button;

            UserActivityManager.ButtonClicked(User, button);

            if (button != null)
            {
                var row = (GridViewRow)button.NamingContainer;

                if (approvedUsersGrid != null)
                {
                    var user = approvedUsersGrid.DataKeys[row.RowIndex].Values["Id"].ToString();

                    approvedUserHieldField.Value = user;

                    var approvedUser = approvedUsers.FirstOrDefault(x => x.Id == user);

                    if (approvedUser != null && approvedUser.Role == UserRoles.Guest)
                    {
                        addWaterMarkCheck.Enabled = false;
                    }
                    else
                    {
                        addWaterMarkCheck.Enabled = true;
                    }

  ScriptManager.RegisterStartupScript(this, GetType(), "approvedUserPopoverScript", "$('#" + button.ClientID + "').popover({ html: true, content: $('#aprprovedUserActionButtonDiv'), container: 'body', trigger: 'focus', placement: 'left'});", true);
  ScriptManager.RegisterStartupScript(this, GetType(), "approvedUserShowButtons", "$('#" + button.ClientID + "').popover('show');", true);
                }

            }
        }

As we can see in the code above, I am storing the selected row in a hidden field which is later used to perform other events such as button onclick event for the selected row. I do have other asp:Linkbuttons inside a popover which works.
Furthermore, the button inside the grid pops a popover and the it's content that is located in the aspx file.
This markup of the checkbox.

   <asp:CheckBox CssClass="bigger-watermark-checkbox" ID="addWaterMarkCheck" runat="server" AutoPostBack="True" OnCheckedChanged="addWaterMarkCheck_OnCheckedChanged"/>
        Add Watermark

Any suggestion or idea is highly appreciated.


text:
Q: What is the logic behind the "using" keyword in C++? What is the logic behind the "using" keyword in C++?
It is used in different situations and I am trying to find
if all those have something in common and there is a reason
why the "using" keyword is used as such.
using namespace std; // to import namespace in the current namespace
using T = int; // type alias
using SuperClass::X; // using super class methods in derived class

A: Another difference between typedef and using: you may do this:
    using vector3d_t = double[3];
    vector3d_t v = {1,2,3};
    v[1] = 4;

It is not possible with typedef:
    typedef double[3] vector3d_t; // Compilation error

A: In C++11, the using keyword when used for type alias is identical to typedef.
7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The
identifier following the using keyword becomes a typedef-name and the
optional attribute-specifier-seq following the identifier appertains
to that typedef-name. It has the same semantics as if it were
introduced by the typedef specifier. In particular, it does not define
a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:
typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // not valid in C++11
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):
class Derived : public Base {
public:
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f
    void f(int);      // prefer this f to Base::f(int)

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor
    Derived(int);     // prefer this constructor to Base::Base(int)
    // ...
};

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.

Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let's consider a toy example:
template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact
for this proposal, is that the idiom causes the template parameters to
appear in non-deducible context. That is, it will not be possible to
call the function foo below without explicitly specifying template
arguments.
template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type
We'd prefer something like the following:
template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term "typedef template" and
introduce the new syntax involving the pair "using" and "=" to help avoid
confusion: we are not defining any types here, we are introducing a
synonym (i.e. alias) for an abstraction of a type-id (i.e. type
expression) involving template parameters. If the template parameters
are used in deducible contexts in the type expression then whenever
the template alias is used to form a template-id, the values of the
corresponding template parameters can be deduced – more on this will
follow. In any case, it is now possible to write generic functions
which operate on Vec<T> in deducible context, and the syntax is
improved as well. For example we could rewrite foo as:
template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing
template aliases was so that argument deduction and the call to foo(p)
will succeed.

The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the
paper [4] — to introduce template aliases:
template<class T>
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to
introduce a type alias. However, it also displays several
disavantages among which the confusion of using a keyword known to
introduce an alias for a type-name in a context where the alias does
not designate a type, but a template; Vec is not an alias for a
type, and should not be taken for a typedef-name. The name Vec is a
name for the family std::vector< [bullet] , MyAllocator< [bullet] > >
– where the bullet is a placeholder for a type-name. Consequently we
do not propose the "typedef" syntax. On the other hand the sentence
template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I'll be using Vec<T> as a
synonym for std::vector<T, MyAllocator<T> >. With that reading, the
new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias-
declaration introduces a name into a declarative region as an alias
for the type designated by the right-hand-side of the declaration. The
core of this proposal concerns itself with type name aliases, but the
notation can obviously be generalized to provide alternate spellings
of namespace-aliasing or naming set of overloaded functions (see ✁
2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef
declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

*

*template aliases (or template typedefs, the former is preferred namewise)

*namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)

*the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.

*bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:
int i;
using r = i; // compile-error

Instead do:
using r = decltype(i);

Naming a set of overloads.
// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);


text:
Q: Gremlin query to search across vertices for a substring I have a graph in which I run the following commands and obtain the below results:
gremlin> g.V().has("ip") //Query 1
==>v[127.0.0.11]
==>v[127.0.0.22]
==>v[127.0.0.33]

gremlin> g.V().has("mac") //Query 2
==>v[AA:BB:CC:00:11:FF]
==>v[A2:B2:C2:00:12:F2]
==>v[A3:B3:C3:00:13:F3]

gremlin> g.V().has("ip",like("*11*")) //Query 3
==>v[127.0.0.11]

gremlin> g.V().has("mac",like("*11*")) //Query 4
==>v[AA:BB:CC:00:11:FF]

gremlin> g.V().has("ip").or().has("macAddr") //Query 5
==>v[127.0.0.11]
==>v[127.0.0.22]
==>v[127.0.0.33]
==>v[AA:BB:CC:00:11:FF]
==>v[A2:B2:C2:00:12:F2]
==>v[A3:B3:C3:00:13:F3]

gremlin> g.V().union(has("ip"),has("macAddr")) //Query 6
==>v[127.0.0.11]
==>v[127.0.0.22]
==>v[127.0.0.33]
==>v[AA:BB:CC:00:11:FF]
==>v[A2:B2:C2:00:12:F2]
==>v[A3:B3:C3:00:13:F3]

I have a requirement where I want to search through both "mac" and "ip" for a given search term.
I tried the following two queries but only got back the same results as Query 5 and Query 6. Can anyone point me in the right direction?
g.V().has("ip",like("*11*")).or().has("macAddr",like("*11*"))

g.V().union(has("ip",like("*11*")),has("macAddr",like("*11*")))

A: I figured this out after a lot of trial and error (probably should've been my first step, but anyway).
The required solution can be obtained by including the g.V() inside the union like so:
g.V().union(g.V().has("ip",like("*11*")),g.V()has("macAddr",like("*11*")))


text:
Q: SubSonic - Generated Classes have the following error - the type or namespace name does not exist in KimDal Im trying to generate my dal and this works but when i check my code in visual studio 2008 i get this message "the type or namespace name does not exist in KimDal"
Im using sql expreess 2005, full version of vs2008, and i setup a new c# 2.0 website.
I installed the 2.1 installer for subsonic, add added it to my external tools, i added a refernce to the dll which added it and other dlls to my bin folder.
I also addeded references to system.web and system.configuration as i saw somehwere that this resolved someone elses issue.
My config is below, is the error im geting normal within intelisense when i look at the class, or do i need to fix something and how do i fix it.
<configuration>
 <configSections>

 </configSections>
 <appSettings/>
 <connectionStrings>

  <add name="kimWebApp" connectionString="Data Source=7NQ384J\SQLExpress;Initial Catalog=kim2;Integrated Security=True"/>
 </connectionStrings>
 <SubSonicService defaultProvider="kimWebAppProvider">
  <providers>
   <clear/>
   <add name="kimWebAppProvider" type="SubSonic.SqlDataProvider, SubSonic" connectionStringName="kimWebApp" generatedNamespace="KimDal"/>
  </providers>
 </SubSonicService>
 <system.web>

  <compilation debug="false" defaultLanguage="c#">
  </compilation>

  <authentication mode="Windows"/>

 </system.web>
 <system.codedom>
 </system.codedom>

 <system.webServer>
 </system.webServer>
</configuration>

A: Dont worry i now have this working, and was able to generate the code, to do so, i basically had to do the following.
Create a webconfig that looks like this
<?xml version="1.0"?>

<configuration>
    <configSections>

    </configSections>
    <appSettings/>
    <connectionStrings>
        <add name="kimconnection" connectionString="Data Source=7NQ384J\SQLExpress;Initial Catalog=kim2;Integrated Security=True;"/>
    </connectionStrings>
    <SubSonicService defaultProvider="kimAppProvider">
        <providers>
            <clear/>
            <add name="kimAppProvider" type="SubSonic.SqlDataProvider, SubSonic" connectionStringName="kimconnection" generatedNamespace="kimdata"/>
        </providers>
    </SubSonicService>
    <system.web>

        <compilation debug="true" defaultLanguage="C#">
            <buildProviders>
                <add extension=".abp" type="SubSonic.BuildProvider, SubSonic"/>
            </buildProviders>
            <assemblies>
                <add assembly="System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="System.Configuration.Install, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91"/>
                <add assembly="System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            </assemblies>
        </compilation>

        <authentication mode="Windows"/>
        <pages>
            <controls>
                <add assembly="SubSonic" namespace="SubSonic" tagPrefix="subsonic"/>
            </controls>
        </pages>

    </system.web>
</configuration>

I copied the config file from my installation of subsonic C:\Program Files\SubSonic\SubSonic 2.1 Final\src\SubSonicCentral
Changed for my needs, i then added the reference to subsonic which included all the dlls below.
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.ObjectBuilder.dll
MySql.Data.dll
System.Data.SQLite.dll
subsonic.dll


text:
Q: nomatch argument in r data table causing bad behavior I have 2 data tables and am trying to get a column from cortable into finaltable.
cortable
cor,tickerkey
0.7539,AAL_AAN
0.573,AAL_ABB
0.6384,AAL_ACM
0.7193,AAL_ACXM
0.8386,AAL_ADP
0.7392,AAL_ADT
0.732,AAL_AER
0.4805,AAL_AGCO
0.9363,AAL_AL
0.9064,AAL_ALK
0.7545,AAL_ALSN
0.8586,AAL_AME
0.3356,AAL_AMT
0.8239,AAL_AN
0.8637,AAL_AOS
0.7638,AAL_APD
0.7915,AAL_APH
0.8785,AAL_APOL
0.8073,AAL_ARMH
0.7744,AAL_ASH
0.4179,AAL_ATLS
0.8282,AAL_AWI
-0.2539,AAL_AWK
0.8213,AAL_AXLL
0.827,AAL_BA
0.8642,AAL_BC
0.7982,AAL_BCO
0.2002,AAL_BEAV
0.7079,AAL_BERY
0.858,AAL_BGC
0.5943,AAL_BRK.B
0.1522,AAL_BWC
0.2793,AAL_CAR
0.8537,AAL_CAT
0.9115,AAL_CBI

finaltable
tickerkey,ticker1,ticker2
AAL_ALK,AAL,ALK
AAL_CAR,AAL,CAR
AAL_CHRW,AAL,CHRW
AAL_CNW,AAL,CNW
AAL_CSX,AAL,CSX
AAL_DAL,AAL,DAL
AAL_EXPD,AAL,EXPD
AAL_FDX,AAL,FDX
AAL_HTZ,AAL,HTZ
AAL_JBHT,AAL,JBHT

I am getting column into finaltable by
setkey(cortable, "tickerkey")
setkey(finaltable, "tickerkey")

finaltable[cortable,cor:=cor,allow.cartesian=TRUE,nomatch=0]

The correct expected output would be
finaltable
tickerkey,ticker1,ticker2,cor
AAL_ALK,AAL,ALK,0.9064
AAL_CAR,AAL,CAR,0.2793

with the rest of the rows having value of NA for cor
but it gives an output

finaltable
tickerkey,ticker1,ticker2,cor
AAL_ALK,AAL,ALK,0.2793
AAL_CAR,AAL,CAR,0.9064

with the rest of the rows NA for cor.
and a warning on execution..
In [.data.table(finaltable, cortable, :=(cor, cor), allow.cartesian = TRUE,  :
  Supplied 2 items to be assigned to 35 items of column 'cor' (recycled leaving remainder of 1 items).
If I remove nomatch argument, the mismatch doesn't happen.
I tried to look into the definition/behaviour of nomatch, didn't find much in the context of the above usage. If anyone could give some explanation, will be very helpful.


text:
Q: As used in combination CollapsingToolbarLayout, Toolbar and Navigation Drawer? I have a project that contains only one activity with navigation drawer. Other pages is fragments. Other pages are fragments that are placed in FrameLayout the the markup of this activity. Accordingly, one toolbar for all the pages and added to the layout in the activity.
Activity has the following layout
    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_mainactivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.design.widget.AppBarLayout
            android:layout_height="60dp"
            android:layout_width="match_parent">
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">
           <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar_mainactivity"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:theme="@style/AppTheme.toolbartheme"
                    style="@style/AppTheme.toolbarstyle"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    app:layout_scrollFlags="scroll|enterAlways">
                </android.support.v7.widget.Toolbar>
        </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <FrameLayout
            android:id="@+id/frame_content_mainactivity"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            style="@style/AppTheme.framestyle">
        </FrameLayout>
        <ListView
            android:id="@+id/left_drawer"
            android:layout_width="@dimen/menudrawer_layout_width"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            style="@style/AppTheme.navigationdrawer"
            android:footerDividersEnabled="false"/>
    </android.support.v4.widget.DrawerLayout>
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

The fragments I want to do сollapsing toolbar. How can i do this? However, this property can only be done in the layout which includes a toolbar. But I have a layouts fragments without toolbar. I would really appreciate any ideas. Thank you for advance!


text:
Q: 'UITableViewCell' not showing label This is my code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];}

    self.credits = (UILabel*)[cell viewWithTag:101];
    self.credits.text = @"Available Credits";
        cell.backgroundColor = [UIColor redColor];
    self.credits.textColor = [UIColor blackColor];
    [cell.contentView addSubview:self.credits];

credits is the label here

A: You store a cell label in your UIViewController and then try to addSubview in the content view.
The right approach for this should be:

*

*Create a subclass of UITableViewCell

*Assign a label inside this cell as a property (could be by code, by xib)

*In cellForRowAtIndexPath: use that property name to assign Available Credits
Your cellForRowAtIndexPath should look like this in the end:
- (MyCustomUITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCustomUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    self.myNewProperty.text = @"Available Credits";
}