Programs & Examples On #Selectnodes

Selects a list of nodes matching the XPath expression.

The response content cannot be parsed because the Internet Explorer engine is not available, or

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -Uri $url -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured:

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

Html Agility Pack get all elements by class

(Updated 2018-03-17)

The problem:

The problem, as you've spotted, is that String.Contains does not perform a word-boundary check, so Contains("float") will return true for both "foo float bar" (correct) and "unfloating" (which is incorrect).

The solution is to ensure that "float" (or whatever your desired class-name is) appears alongside a word-boundary at both ends. A word-boundary is either the start (or end) of a string (or line), whitespace, certain punctuation, etc. In most regular-expressions this is \b. So the regex you want is simply: \bfloat\b.

A downside to using a Regex instance is that they can be slow to run if you don't use the .Compiled option - and they can be slow to compile. So you should cache the regex instance. This is more difficult if the class-name you're looking for changes at runtime.

Alternatively you can search a string for words by word-boundaries without using a regex by implementing the regex as a C# string-processing function, being careful not to cause any new string or other object allocation (e.g. not using String.Split).

Approach 1: Using a regular-expression:

Suppose you just want to look for elements with a single, design-time specified class-name:

class Program {

    private static readonly Regex _classNameRegex = new Regex( @"\bfloat\b", RegexOptions.Compiled );

    private static IEnumerable<HtmlNode> GetFloatElements(HtmlDocument doc) {
        return doc
            .Descendants()
            .Where( n => n.NodeType == NodeType.Element )
            .Where( e => e.Name == "div" && _classNameRegex.IsMatch( e.GetAttributeValue("class", "") ) );
    }
}

If you need to choose a single class-name at runtime then you can build a regex:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    Regex regex = new Regex( "\\b" + Regex.Escape( className ) + "\\b", RegexOptions.Compiled );

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e => e.Name == "div" && regex.IsMatch( e.GetAttributeValue("class", "") ) );
}

If you have multiple class-names and you want to match all of them, you could create an array of Regex objects and ensure they're all matching, or combine them into a single Regex using lookarounds, but this results in horrendously complicated expressions - so using a Regex[] is probably better:

using System.Linq;

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String[] classNames) {

    Regex[] exprs = new Regex[ classNames.Length ];
    for( Int32 i = 0; i < exprs.Length; i++ ) {
        exprs[i] = new Regex( "\\b" + Regex.Escape( classNames[i] ) + "\\b", RegexOptions.Compiled );
    }

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            exprs.All( r =>
                r.IsMatch( e.GetAttributeValue("class", "") )
            )
        );
}

Approach 2: Using non-regex string matching:

The advantage of using a custom C# method to do string matching instead of a regex is hypothetically faster performance and reduced memory usage (though Regex may be faster in some circumstances - always profile your code first, kids!)

This method below: CheapClassListContains provides a fast word-boundary-checking string matching function that can be used the same way as regex.IsMatch:

private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {

    return doc
        .Descendants()
        .Where( n => n.NodeType == NodeType.Element )
        .Where( e =>
            e.Name == "div" &&
            CheapClassListContains(
                e.GetAttributeValue("class", ""),
                className,
                StringComparison.Ordinal
            )
        );
}

/// <summary>Performs optionally-whitespace-padded string search without new string allocations.</summary>
/// <remarks>A regex might also work, but constructing a new regex every time this method is called would be expensive.</remarks>
private static Boolean CheapClassListContains(String haystack, String needle, StringComparison comparison)
{
    if( String.Equals( haystack, needle, comparison ) ) return true;
    Int32 idx = 0;
    while( idx + needle.Length <= haystack.Length )
    {
        idx = haystack.IndexOf( needle, idx, comparison );
        if( idx == -1 ) return false;

        Int32 end = idx + needle.Length;

        // Needle must be enclosed in whitespace or be at the start/end of string
        Boolean validStart = idx == 0               || Char.IsWhiteSpace( haystack[idx - 1] );
        Boolean validEnd   = end == haystack.Length || Char.IsWhiteSpace( haystack[end] );
        if( validStart && validEnd ) return true;

        idx++;
    }
    return false;
}

Approach 3: Using a CSS Selector library:

HtmlAgilityPack is somewhat stagnated doesn't support .querySelector and .querySelectorAll, but there are third-party libraries that extend HtmlAgilityPack with it: namely Fizzler and CssSelectors. Both Fizzler and CssSelectors implement QuerySelectorAll, so you can use it like so:

private static IEnumerable<HtmlNode> GetDivElementsWithFloatClass(HtmlDocument doc) {

    return doc.QuerySelectorAll( "div.float" );
}

With runtime-defined classes:

private static IEnumerable<HtmlNode> GetDivElementsWithClasses(HtmlDocument doc, IEnumerable<String> classNames) {

    String selector = "div." + String.Join( ".", classNames );

    return doc.QuerySelectorAll( selector  );
}

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

Find position of a node using xpath

Try:

count(a/b[.='tsr']/preceding-sibling::*)+1.

Java method to swap primitives

For integer types, you can do

a ^= b;
b ^= a;
a ^= b;

using the bit-wise xor operator ^. As all the other suggestions, you probably shouldn't use it in production code.

For a reason I don't know, the single line version a ^= b ^= a ^= b doesn't work (maybe my Java compiler has a bug). The single line worked in C with all compilers I tried. However, two-line versions work:

a ^= b ^= a;
b ^= a;

as well as

b ^= a;
a ^= b ^= a;

A proof that it works: Let a0 and b0 be the initial values for a and b. After the first line, a is a1 = a0 xor b0; after the second line, b is b1 = b0 xor a1 = b0 xor (a0 xor b0) = a0. After the third line, a is a2 = a1 xor b1 = a1 xor (b0 xor a1) = b0.

Nginx location priority

Locations are evaluated in this order:

  1. location = /path/file.ext {} Exact match
  2. location ^~ /path/ {} Priority prefix match -> longest first
  3. location ~ /Paths?/ {} (case-sensitive regexp) and location ~* /paths?/ {} (case-insensitive regexp) -> first match
  4. location /path/ {} Prefix match -> longest first

The priority prefix match (number 2) is exactly as the common prefix match (number 4), but has priority over any regexp.

For both prefix matche types the longest match wins.

Case-sensitive and case-insensitive have the same priority. Evaluation stops at the first matching rule.

Documentation says that all prefix rules are evaluated before any regexp, but if one regexp matches then no standard prefix rule is used. That's a little bit confusing and does not change anything for the priority order reported above.

How to remove youtube branding after embedding video in web page?

That watermark in the bottom right only appears on mouseover. There's no parameter to remove that, however if you stack a transparent div on top of the video and make it a higher z-index and the same size of the video, your mouseover will not trigger the watermark because your mouse will be hitting the div.

Of course the tradeoff for this is that you lose the ability to actually click on the video to pause it. But if you want to leave the ability to pause it, you could display the controls and have the top layer div cover up until the bottom 30 pixels or so, letting you click the controls.

MySQL SELECT last few days?

Use for a date three days ago:

WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -3 DAY);

Check the DATE_ADD documentation.

Or you can use:

WHERE t.date >= ( CURDATE() - INTERVAL 3 DAY )

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

How can I get the client's IP address in ASP.NET MVC?

How I account for my site being behind an Amazon AWS Elastic Load Balancer (ELB):

public class GetPublicIp {

    /// <summary>
    /// account for possbility of ELB sheilding the public IP address
    /// </summary>
    /// <returns></returns>
    public static string Execute() {
        try {
            Console.WriteLine(string.Join("|", new List<object> {
                    HttpContext.Current.Request.UserHostAddress,
                    HttpContext.Current.Request.Headers["X-Forwarded-For"],
                    HttpContext.Current.Request.Headers["REMOTE_ADDR"]
                })
            );

            var ip = HttpContext.Current.Request.UserHostAddress;
            if (HttpContext.Current.Request.Headers["X-Forwarded-For"] != null) {
                ip = HttpContext.Current.Request.Headers["X-Forwarded-For"];
                Console.WriteLine(ip + "|X-Forwarded-For");
            }
            else if (HttpContext.Current.Request.Headers["REMOTE_ADDR"] != null) {
                ip = HttpContext.Current.Request.Headers["REMOTE_ADDR"];
                Console.WriteLine(ip + "|REMOTE_ADDR");
            }
            return ip;
        }
        catch (Exception ex) {
            Console.Error.WriteLine(ex.Message);
        }
        return null;
    }
}

Why is this jQuery click function not working?

Be sure there is nothing on your button (such a div or a trasparent img) that keeps from clicking the button. It sounds stupid, but sometimes we think that jQuery is not working and all that stuffs and the problem is on the positioning of DOM elements.

Convert Pandas column containing NaNs to dtype `int`

I had the problem a few weeks ago with a few discrete features which were formatted as 'object'. This solution seemed to work.

for col in discrete:
df[col] = pd.to_numeric(df[col], errors='coerce').astype(pd.Int64Dtype())

How to sum all values in a column in Jaspersoft iReport Designer?

iReports Custom Fields for columns (sum, average, etc)

  1. Right-Click on Variables and click Create Variable

  2. Click on the new variable

    a. Notice the properties on the right

  3. Rename the variable accordingly

  4. Change the Value Class Name to the correct Data Type

    a. You can search by clicking the 3 dots

  5. Select the correct type of calculation

  6. Change the Expression

    a. Click the little icon

    b. Select the column you are looking to do the calculation for

    c. Click finish

  7. Set Initial Value Expression to 0

  8. Set the increment type to none

  9. Leave Incrementer Factory Class Name blank
  10. Set the Reset Type (usually report)

  11. Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)

  12. Double Click the new Text Field
  13. Clear the expression “Text Field”
  14. Select the new variable

  15. Click finish

  16. Put the new text in a desirable position ?

Command not found when using sudo

Permission denied

In order to run a script the file must have an executable permission bit set.

In order to fully understand Linux file permissions you can study the documentation for the chmod command. chmod, an abbreviation of change mode, is the command that is used to change the permission settings of a file.

To read the chmod documentation for your local system , run man chmod or info chmod from the command line. Once read and understood you should be able to understand the output of running ...

ls -l foo.sh

... which will list the READ, WRITE and EXECUTE permissions for the file owner, the group owner and everyone else who is not the file owner or a member of the group to which the file belongs (that last permission group is sometimes referred to as "world" or "other")

Here's a summary of how to troubleshoot the Permission Denied error in your case.

$ ls -l foo.sh                    # Check file permissions of foo
-rw-r--r-- 1 rkielty users 0 2012-10-21 14:47 foo.sh 
    ^^^ 
 ^^^ | ^^^   ^^^^^^^ ^^^^^
  |  |  |       |       | 
Owner| World    |       |
     |          |    Name of
   Group        |     Group
             Name of 
              Owner 

Owner has read and write access rw but the - indicates that the executable permission is missing

The chmod command fixes that. (Group and other only have read permission set on the file, they cannot write to it or execute it)

$ chmod +x foo.sh               # The owner can set the executable permission on foo.sh
$ ls -l foo.sh                  # Now we see an x after the rw 
-rwxr-xr-x 1 rkielty users 0 2012-10-21 14:47 foo.sh
   ^  ^  ^

foo.sh is now executable as far as Linux is concerned.

Using sudo results in Command not found

When you run a command using sudo you are effectively running it as the superuser or root.

The reason that the root user is not finding your command is likely that the PATH environment variable for root does not include the directory where foo.sh is located. Hence the command is not found.

The PATH environment variable contains a list of directories which are searched for commands. Each user sets their own PATH variable according to their needs. To see what it is set to run

env | grep ^PATH

Here's some sample output of running the above env command first as an ordinary user and then as the root user using sudo

rkielty@rkielty-laptop:~$ env | grep ^PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

rkielty@rkielty-laptop:~$ sudo env | grep ^PATH
[sudo] password for rkielty: 
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin

Note that, although similar, in this case the directories contained in the PATH the non-privileged user (rkielty) and the super user are not the same.

The directory where foo.sh resides is not present in the PATH variable of the root user, hence the command not found error.

How do I keep a label centered in WinForms?

I wanted to do something similar, but on a form with a background image, I found that when the text in the label changed the repaints were obvious with this method, so I did the following: * Set the label AutoSize to true and TextAlign to MiddleCenter

Then, each time the text changed (mine was done using a timer) I called the following method:

    private Point GetPosition()
    {
        int y = (this.Height / 2) - (label1.Height / 2);
        int x = (this.Width / 2) - (label1.Width / 2);
        return new Point(x, y);
    }

And set the label's Location property to this return value. This ensured that the label was always in the center of the form when the text changed and the repaints for a full-screen form weren't obvious.

How to initialize a list with constructor?

ContactNumbers = new List<ContactNumber>();

If you want it to be passed in, just take

public Human(List<ContactNumber> numbers)
{
 ContactNumbers = numbers;
}

Console output in a Qt GUI app?

Something you may want to investigate, at least for windows, is the AllocConsole() function in the windows api. It calls GetStdHandle a few times to redirect stdout, stderr, etc. (A quick test shows this doesn't entirely do what we want it to do. You do get a console window opened alongside your other Qt stuff, but you can't output to it. Presumably, because the console window is open, there is some way to access it, get a handle to it, or access and manipulate it somehow. Here's the MSDN documentation for those interested in figuring this out:

AllocConsole(): http://msdn.microsoft.com/en-us/library/windows/desktop/ms681944%28v=vs.85%29.aspx

GetStdHandle(...): http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231%28v=vs.85%29.aspx

(I'd add this as a comment, but the rules prevent me from doing so...)

.gitignore all the .DS_Store files in every folder and subfolder

Simply place this on a new line in .gitignore

**/.DS_Store

From git documentation

  • A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".

How do I get the current time zone of MySQL?

As Jakub Vrána (The creator or Adminer and NotORM) mentions in the comments, to select the current timezone offset in TIME use:

SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);

It will return: 02:00:00 if your timezone is +2:00 for that date

I made a cheatsheet here: Should MySQL have its timezone set to UTC?

How to parse a JSON string to an array using Jackson

The other answer is correct, but for completeness, here are other ways:

List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);

How do I check how many options there are in a dropdown menu?

Click here to see a previous post about this

Basically just target the ID of the select and do this:

var numberOfOptions = $('#selectId option').length;

ITSAppUsesNonExemptEncryption export compliance while internal testing?

According to WWDC2015 Distribution Whats New

enter image description here

Setting "ITSAppUsesNonExemptEncryption" to "NO" in info.plist works fine. if no cryptographic content in your app.

enter image description here

I had got this pop up During selecting build for internal testing i didn't included "ITSAppUsesNonExemptEncryption" key in my info.plist but still worked for me.

Even i successfully uploaded new application didn't included "ITSEncryptionExportComplianceCode" and "ITSAppUsesNonExemptEncryption" keys.

Also Apple Doc.

Important: If your app requires that you provide additional documents for the encryption review, your app won’t have the Ready for Sale status on the store until Export Compliance has reviewed and approved your documents. The app can’t be distributed for prerelease testing until Export Compliance has reviewed and approved it.

If your app is not using encryption and you don’t want to have to answer these questions at the time of submission, you can provide export compliance information with your build. You can also provide new or updated documentation via iTunes Connect to receive the appropriate key string value to include with your build before uploading it to iTunes Connect.

To add export compliance documentation in iTunes Connect:

Go to the Encryption section under Features. Click the plus sign next to the appropriate platform section. Answer the questions appropriately. Attach the file when prompted. Click Save. Your documents will then be sent for review immediately and the status of your document will show in Compliance Review. A key value will also be generated automatically that you can include in your Info.plist file. For more information on including the key value with your build, see the Resources and Help section Trade Compliance.

You can upload a build without an export compliance key. If you include a key, it can indicate that you do not need export compliance documentation; this requires no approval. If you include a key that references a specific export compliance document, that document must be approved; it cannot be in In Review or Rejected.

enter image description here

You can review your answers at any time by clicking the document file name and selecting More Information. If you need to update your documentation or change any of the answers to the questions, you will need to repeat the steps above to add a new document that corresponds with your changes.

How to group dataframe rows into list in pandas groupby

Use any of the following groupby and agg recipes.

# Setup
df = pd.DataFrame({
  'a': ['A', 'A', 'B', 'B', 'B', 'C'],
  'b': [1, 2, 5, 5, 4, 6],
  'c': ['x', 'y', 'z', 'x', 'y', 'z']
})
df

   a  b  c
0  A  1  x
1  A  2  y
2  B  5  z
3  B  5  x
4  B  4  y
5  C  6  z

To aggregate multiple columns as lists, use any of the following:

df.groupby('a').agg(list)
df.groupby('a').agg(pd.Series.tolist)

           b          c
a                      
A     [1, 2]     [x, y]
B  [5, 5, 4]  [z, x, y]
C        [6]        [z]

To group-listify a single column only, convert the groupby to a SeriesGroupBy object, then call SeriesGroupBy.agg. Use,

df.groupby('a').agg({'b': list})  # 4.42 ms 
df.groupby('a')['b'].agg(list)    # 2.76 ms - faster

a
A       [1, 2]
B    [5, 5, 4]
C          [6]
Name: b, dtype: object

Using Django time/date widgets in custom form

The below will also work as a last resort if the above failed

class PaymentsForm(forms.ModelForm):
    class Meta:
        model = Payments

    def __init__(self, *args, **kwargs):
        super(PaymentsForm, self).__init__(*args, **kwargs)
        self.fields['date'].widget = SelectDateWidget()

Same as

class PaymentsForm(forms.ModelForm):
    date = forms.DateField(widget=SelectDateWidget())

    class Meta:
        model = Payments

put this in your forms.py from django.forms.extras.widgets import SelectDateWidget

JCheckbox - ActionListener and ItemListener?

The difference is that ActionEvent is fired when the action is performed on the JCheckBox that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox is selected or deselected.

For instance, if JCheckBox c1 (say) is added to a ButtonGroup. Changing the state of other JCheckBoxes in the ButtonGroup will not fire an ActionEvent on other JCheckBox, instead an ItemEvent is fired.

Final words: An ItemEvent is fired even when the user deselects a check box by selecting another JCheckBox (when in a ButtonGroup), however ActionEvent is not generated like that instead ActionEvent only listens whether an action is performed on the JCheckBox (to which the ActionListener is registered only) or not. It does not know about ButtonGroup and all other selection/deselection stuff.

ReactJS: Maximum update depth exceeded error

that because you calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on

this line at your code

{<td><span onClick={this.toggle()}>Details</span></td>}

you need to make onClick refer to this.toggle not calling it

to fix the issue do this

{<td><span onClick={this.toggle}>Details</span></td>}

EditorFor() and html properties

I don't know why it does not work for Html.EditorFor but I tried TextBoxFor and it worked for me.

@Html.TextBoxFor(m => m.Name, new { Class = "className", Size = "40"})

...and also validation works.

Maven project version inheritance - do I have to specify the parent version?

As Yanflea mentioned, there is a way to go around this.

In Maven 3.5.0 you can use the following way of transferring the version down from the parent project:

Parent POM.xml

<project ...>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mydomain</groupId>
    <artifactId>myprojectparent</artifactId>
    <packaging>pom</packaging>
    <version>${myversion}</version>
    <name>MyProjectParent</name>

    <properties>
        <myversion>0.1-SNAPSHOT</myversion>
    </properties>

    <modules>
        <module>modulefolder</module>
    </modules>
    ...
</project>

Module POM.xml

<project ...>
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.mydomain</groupId>
        <artifactId>myprojectmodule</artifactId>
        <version>${myversion}</version> <!-- This still needs to be set, but you can use properties from parent -->
    </parent>

    <groupId>se.car_o_liner</groupId>
    <artifactId>vinno</artifactId>
    <packaging>war</packaging>
    <name>Vinno</name>
    <!-- Note that there's no version specified; it's inherited from parent -->
    ...
</project>

You are free to change myversion to whatever you want that isn't a reserved property.

How to write :hover condition for a:before and a:after?

Write a:hover::before instead of a::before:hover: example.

Returning unique_ptr from functions

I think it's perfectly explained in item 25 of Scott Meyers' Effective Modern C++. Here's an excerpt:

The part of the Standard blessing the RVO goes on to say that if the conditions for the RVO are met, but compilers choose not to perform copy elision, the object being returned must be treated as an rvalue. In effect, the Standard requires that when the RVO is permitted, either copy elision takes place or std::move is implicitly applied to local objects being returned.

Here, RVO refers to return value optimization, and if the conditions for the RVO are met means returning the local object declared inside the function that you would expect to do the RVO, which is also nicely explained in item 25 of his book by referring to the standard (here the local object includes the temporary objects created by the return statement). The biggest take away from the excerpt is either copy elision takes place or std::move is implicitly applied to local objects being returned. Scott mentions in item 25 that std::move is implicitly applied when the compiler choose not to elide the copy and the programmer should not explicitly do so.

In your case, the code is clearly a candidate for RVO as it returns the local object p and the type of p is the same as the return type, which results in copy elision. And if the compiler chooses not to elide the copy, for whatever reason, std::move would've kicked in to line 1.

Get the short Git version hash

A really simple way is to:

git describe --always

How to open a new tab in GNOME Terminal from command line?

For anyone seeking a solution that does not use the command line: ctrl+shift+t

How to declare a global variable in a .js file

Have you tried it?

If you do:

var HI = 'Hello World';

In global.js. And then do:

alert(HI);

In js1.js it will alert it fine. You just have to include global.js prior to the rest in the HTML document.

The only catch is that you have to declare it in the window's scope (not inside any functions).

You could just nix the var part and create them that way, but it's not good practice.

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Jason Bunting's last index of does not work. Mine is not optimal, but it works.

//Jason Bunting's
String.prototype.regexIndexOf = function(regex, startpos) {
var indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

String.prototype.regexLastIndexOf = function(regex, startpos) {
var lastIndex = -1;
var index = this.regexIndexOf( regex );
startpos = startpos === undefined ? this.length : startpos;

while ( index >= 0 && index < startpos )
{
    lastIndex = index;
    index = this.regexIndexOf( regex, index + 1 );
}
return lastIndex;
}

angularjs ng-style: background-image isn't working

If we have a dynamic value that needs to go in a css background or background-image attribute, it can be just a bit more tricky to specify.

Let’s say we have a getImage() function in our controller. This function returns a string formatted similar to this: url(icons/pen.png). If we do, the ngStyle declaration is specified the exact same way as before:

ng-style="{ 'background-image': getImage() }"

Make sure to put quotes around the background-image key name. Remember, this must be formatted as a valid Javascript object key.

How do you force a CIFS connection to unmount

umount -f -t cifs -l /mnt &

Be careful of &, let umount run in background. umount will detach filesystem first, so you will find nothing abount /mnt. If you run df command, then it will umount /mnt forcibly.

Git push rejected after feature branch rebase

One solution to this is to do what msysGit's rebasing merge script does - after the rebase, merge in the old head of feature with -s ours. You end up with the commit graph:

A--B--C------F--G (master)
       \         \
        \         D'--E' (feature)
         \           /
          \       --
           \    /
            D--E (old-feature)

... and your push of feature will be a fast-forward.

In other words, you can do:

git checkout feature
git branch old-feature
git rebase master
git merge -s ours old-feature
git push origin feature

(Not tested, but I think that's right...)

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

In SQL Server 2008 in addition to the above two options you have a third option to make this setting through SQL Server Management Studio.

1.Start Management Studio and connect to Report Server Instance (make sure you select 'Reporting Services' server type).

2.Right click on the ReportServer and Select Properties

3.Click Advanced

4.In EnableRemoteErrors, select True.

5.Click OK.

Where can I download english dictionary database in a text format?

The Gutenberg Project hosts Webster's Unabridged English Dictionary plus many other public domain literary works. Actually it looks like they've got several versions of the dictionary hosted with copyright from different years. The one I linked has a 2009 copyright. You may want to poke around the site and investigate the different versions of Webster's dictionary.

How to commit to remote git repository

You just need to make sure you have the rights to push to the remote repository and do

git push origin master

or simply

git push

Powershell script does not run via Scheduled Tasks

I had very similar issue, i was keeping the VSC window with powershell script all the time when running the schedule task manually. Just closed it and it started working as expected.

See :hover state in Chrome Developer Tools

EDIT: This answer was before the bug fix, see tnothcutt's answer.

This was a bit tricky, but here goes:

  • Right-click element, but DON'T move your mouse pointer away from the element, keep it in hover state.
  • Choose inspect element via keyboard, as in hit up arrow and then Enter key.
  • Look in developer tools under Matched CSS Rules, you should be able to see :hover.

PS: I tried this on one of your question tags.

What is std::move(), and when should it be used?

Here is a full example, using std::move for a (simple) custom vector

Expected output:

 c: [10][11]
 copy ctor called
 copy of c: [10][11]
 move ctor called
 moved c: [10][11]

Compile as:

  g++ -std=c++2a -O2 -Wall -pedantic foo.cpp

Code:

#include <iostream>
#include <algorithm>

template<class T> class MyVector {
private:
    T *data;
    size_t maxlen;
    size_t currlen;
public:
    MyVector<T> () : data (nullptr), maxlen(0), currlen(0) { }
    MyVector<T> (int maxlen) : data (new T [maxlen]), maxlen(maxlen), currlen(0) { }

    MyVector<T> (const MyVector& o) {
        std::cout << "copy ctor called" << std::endl;
        data = new T [o.maxlen];
        maxlen = o.maxlen;
        currlen = o.currlen;
        std::copy(o.data, o.data + o.maxlen, data);
    }

    MyVector<T> (const MyVector<T>&& o) {
        std::cout << "move ctor called" << std::endl;
        data = o.data;
        maxlen = o.maxlen;
        currlen = o.currlen;
    }

    void push_back (const T& i) {
        if (currlen >= maxlen) {
            maxlen *= 2;
            auto newdata = new T [maxlen];
            std::copy(data, data + currlen, newdata);
            if (data) {
                delete[] data;
            }
            data = newdata;
        }
        data[currlen++] = i;
    }

    friend std::ostream& operator<<(std::ostream &os, const MyVector<T>& o) {
        auto s = o.data;
        auto e = o.data + o.currlen;;
        while (s < e) {
            os << "[" << *s << "]";
            s++;
        }
        return os;
    }
};

int main() {
    auto c = new MyVector<int>(1);
    c->push_back(10);
    c->push_back(11);
    std::cout << "c: " << *c << std::endl;
    auto d = *c;
    std::cout << "copy of c: " << d << std::endl;
    auto e = std::move(*c);
    delete c;
    std::cout << "moved c: " << e << std::endl;
}

PHP Warning: Module already loaded in Unknown on line 0

Run php --ini and notice file path on Loaded Configuration File.
Then run command like cat -n /etc/php/7.2/cli/php.ini | grep intl to find if the extension is commented or not.
Then update loaded configuration file by commenting line by adding ; such as ;extension=intl

This can happen when you install php-intl package and also enable the same extension on php.ini file.

Given URL is not allowed by the Application configuration

For me it was the "Single Sign On" (can be seen at the bottome of the screenshot in phwd's answer) setting that was turned off.

When increasing the size of VARCHAR column on a large table could there be any problems?

This is a metadata change only: it is quick.

An observation: specify NULL or NOT NULL explicitly to avoid "accidents" if one of the SET ANSI_xx settings are different eg run in osql not SSMS for some reason

Writing/outputting HTML strings unescaped

Sometimes it can be tricky to use raw html. Mostly because of XSS vulnerability. If that is a concern, but you still want to use raw html, you can encode the scary parts.

@Html.Raw("(<b>" + Html.Encode("<script>console.log('insert')</script>" + "Hello") + "</b>)")

Results in

(<b>&lt;script&gt;console.log('insert')&lt;/script&gt;Hello</b>)

Checking session if empty or not

Use this if the session variable emp_num will store a string:

 if (!string.IsNullOrEmpty(Session["emp_num"] as string))
 {
                //The code
 }

If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.

Check If only numeric values were entered in input. (jQuery)

http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS

Check that out. It should be just what you're looking for. A US phone validation plugin for jQuery.

If you want to do it on your own, you're going to be in for a good amount of work. Check out the isNaN() function. It tells you if it is not a number. You're also going to want to brush up on your regular expressions for validation. If you're using RegEx, you can go without isNaN(), as you'll be testing for that anyway.

How to parseInt in Angular.js

Option 1 (via controller):

angular.controller('numCtrl', function($scope, $window) {
   $scope.num = parseInt(num , 10);
}

Option 2 (via custom filter):

app.filter('num', function() {
    return function(input) {
       return parseInt(input, 10);
    }
});

{{(num1 | num) + (num2 | num)}}

Option 3 (via expression):

Declare this first in your controller:

$scope.parseInt = parseInt;

Then:

{{parseInt(num1)+parseInt(num2)}}

Option 4 (from raina77ow)

{{(num1-0) + (num2-0)}}

How to uninstall Apache with command line

If Apache was installed using NSIS installer it should have left an uninstaller. You should search inside Apache installation directory for executable named unistaller.exe or something like that. NSIS uninstallers support /S flag by default for silent uninstall. So you can run something like "C:\Program Files\<Apache installation dir here>\uninstaller.exe" /S

From NSIS documentation:

3.2.1 Common Options

/NCRC disables the CRC check, unless CRCCheck force was used in the script. /S runs the installer or uninstaller silently. See section 4.12 for more information. /D sets the default installation directory ($INSTDIR), overriding InstallDir and InstallDirRegKey. It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported.

How do I get the coordinates of a mouse click on a canvas element?

Here is some modifications of the above Ryan Artecona's solution.

function myGetPxStyle(e,p)
{
    var r=window.getComputedStyle?window.getComputedStyle(e,null)[p]:"";
    return parseFloat(r);
}

function myGetClick=function(ev)
{
    // {x:ev.layerX,y:ev.layerY} doesn't work when zooming with mac chrome 27
    // {x:ev.clientX,y:ev.clientY} not supported by mac firefox 21
    // document.body.scrollLeft and document.body.scrollTop seem required when scrolling on iPad
    // html is not an offsetParent of body but can have non null offsetX or offsetY (case of wordpress 3.5.1 admin pages for instance)
    // html.offsetX and html.offsetY don't work with mac firefox 21

    var offsetX=0,offsetY=0,e=this,x,y;
    var htmls=document.getElementsByTagName("html"),html=(htmls?htmls[0]:0);

    do
    {
        offsetX+=e.offsetLeft-e.scrollLeft;
        offsetY+=e.offsetTop-e.scrollTop;
    } while (e=e.offsetParent);

    if (html)
    {
        offsetX+=myGetPxStyle(html,"marginLeft");
        offsetY+=myGetPxStyle(html,"marginTop");
    }

    x=ev.pageX-offsetX-document.body.scrollLeft;
    y=ev.pageY-offsetY-document.body.scrollTop;
    return {x:x,y:y};
}

Running PHP script from the command line

UPDATE:

After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?

Look for lines that start with LoadModule php... There probably are configuration files/directories named mods or something like that, start from there.

You could also check output from php -r 'phpinfo();' | grep php and compare lines to phpinfo(); from web server.

To run php interactively:

(so you can paste/write code in the console)

php -a

To make it parse file and output to console:

php -f file.php

Parse file and output to another file:

php -f file.php > results.html

Do you need something else?

To run only small part, one line or like, you can use:

php -r '$x = "Hello World"; echo "$x\n";'

If you are running linux then do man php at console.

if you need/want to run php through fpm, use cli fcgi

SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"

where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.

What is @RenderSection in asp.net MVC

Here the defination of Rendersection from MSDN

In layout pages, renders the content of a named section.MSDN

In _layout.cs page put

@RenderSection("Bottom",false)

Here render the content of bootom section and specifies false boolean property to specify whether the section is required or not.

@section Bottom{
       This message form bottom.
}

That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.

How to leave space in HTML

After, or in-between your text, use the &nbsp; (non-breaking space) extended HTML character.

  • EG 1 :

    This is an example paragraph. &nbsp;&nbsp; This is the next line.

Iterate through object properties

If running Node I'd recommend:

Object.keys(obj).forEach((key, index) => {
    console.log(key);
});

ERROR 2003 (HY000): Can't connect to MySQL server (111)

I had the same problem trying to connect to a remote mysql db.

I fixed it by opening the firewall on the db server to allow traffic through:

sudo ufw allow mysql

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Added: I found something that should do the trick right away, but the rest of the code below also offers an alternative.

Use the subplots_adjust() function to move the bottom of the subplot up:

fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.

Then play with the offset in the legend bbox_to_anchor part of the legend command, to get the legend box where you want it. Some combination of setting the figsize and using the subplots_adjust(bottom=...) should produce a quality plot for you.

Alternative: I simply changed the line:

fig = plt.figure(1)

to:

fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')

and changed

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))

to

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))

and it shows up fine on my screen (a 24-inch CRT monitor).

Here figsize=(M,N) sets the figure window to be M inches by N inches. Just play with this until it looks right for you. Convert it to a more scalable image format and use GIMP to edit if necessary, or just crop with the LaTeX viewport option when including graphics.

Html: Difference between cell spacing and cell padding

CellSpacing as the name suggests it is the Space between the Adjacent cells and CellPadding on the other hand means the padding around the cell content.

Create a Maven project in Eclipse complains "Could not resolve archetype"

Adding the following inside "mirrors" section in the user setting.xml file worked for me.

<mirror>
  <id>ibiblio.org</id>
  <url>http://mirrors.ibiblio.org/maven2</url>
  <mirrorOf>central</mirrorOf>
</mirror>

Invoking JavaScript code in an iframe from the parent page

Continuing with JoelAnair's answer:

For more robustness, use as follows:

var el = document.getElementById('targetFrame');

if(el.contentWindow)
{
   el.contentWindow.targetFunction();
}
else if(el.contentDocument)
{
   el.contentDocument.targetFunction();
}

Workd like charm :)

Truncating long strings with CSS: feasible yet?

2014 March: Truncating long strings with CSS: a new answer with focus on browser support

Demo on http://jsbin.com/leyukama/1/ (I use jsbin because it supports old version of IE).

<style type="text/css">
    span {
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;     /** IE6+, Firefox 7+, Opera 11+, Chrome, Safari **/
        -o-text-overflow: ellipsis;  /** Opera 9 & 10 **/
        width: 370px; /* note that this width will have to be smaller to see the effect */
    }
</style>

<span>Some very long text that should be cut off at some point coz it's a bit too long and the text overflow ellipsis feature is used</span>

The -ms-text-overflow CSS property is not necessary: it is a synonym of the text-overflow CSS property, but versions of IE from 6 to 11 already support the text-overflow CSS property.

Successfully tested (on Browserstack.com) on Windows OS, for web browsers:

  • IE6 to IE11
  • Opera 10.6, Opera 11.1, Opera 15.0, Opera 20.0
  • Chrome 14, Chrome 20, Chrome 25
  • Safari 4.0, Safari 5.0, Safari 5.1
  • Firefox 7.0, Firefox 15

Firefox: as pointed out by Simon Lieschke (in another answer), Firefox only support the text-overflow CSS property from Firefox 7 onwards (released September 27th 2011).

I double checked this behavior on Firefox 3.0 & Firefox 6.0 (text-overflow is not supported).

Some further testing on a Mac OS web browsers would be needed.

Note: you may want to show a tooltip on mouse hover when an ellipsis is applied, this can be done via javascript, see this questions: HTML text-overflow ellipsis detection and HTML - how can I show tooltip ONLY when ellipsis is activated

Resources:

How to put sshpass command inside a bash script?

Do which sshpass in your command line to get the absolute path to sshpass and replace it in the bash script.

You should also probably do the same with the command you are trying to run.

The problem might be that it is not finding it.

C# Telnet Library

I doubt very much a telnet library will ever be part of the .Net BCL, although you do have almost full socket support so it wouldnt be too hard to emulate a telnet client, Telnet in its general implementation is a legacy and dying technology that where exists generally sits behind a nice new modern facade. In terms of Unix/Linux variants you'll find that out the box its SSH and enabling telnet is generally considered poor practice.

You could check out: http://granados.sourceforge.net/ - SSH Library for .Net http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh

You'll still need to put in place your own wrapper to handle events for feeding in input in a scripted manner.

How can I delete multiple lines in vi?

d5d "cuts" five lines

I usually just throw the number in the middle like:

d7l = delete 7 letters

What does "select 1 from" do?

The construction is usually used in "existence" checks

if exists(select 1 from customer_table where customer = 'xxx')

or

if exists(select * from customer_table where customer = 'xxx')

Both constructions are equivalent. In the past people said the select * was better because the query governor would then use the best indexed column. This has been proven not true.

extract column value based on another column pandas dataframe

You could use loc to get series which satisfying your condition and then iloc to get first element:

In [2]: df
Out[2]:
    A  B
0  p1  1
1  p1  2
2  p3  3
3  p2  4

In [3]: df.loc[df['B'] == 3, 'A']
Out[3]:
2    p3
Name: A, dtype: object

In [4]: df.loc[df['B'] == 3, 'A'].iloc[0]
Out[4]: 'p3'

node.js: cannot find module 'request'

if some module you cant find, try with Static URI, for example:

var Mustache = require("/media/fabio/Datos/Express/2_required_a_module/node_modules/mustache/mustache.js");

This example, run on Ubuntu Gnome 16.04 of 64 bits, node -v: v4.2.6, npm: 3.5.2 Refer to: Blog of Ben Nadel

Where does Git store files?

It will create your repository in the .git folder in the current directory.

Casting string to enum

Use Enum.Parse().

var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);

Loop in react-native

 render() {
    var myloop = [];

    for (let i = 0; i < 10; i++) {
      myloop.push(
        <View key={i}>
        <Text style={{ textAlign: 'center', marginTop: 5 }} >{i}</Text>
        </View>
      );
    }

     return (

            <View >
              <Text >Welcome to React Native!</Text>
               {myloop}
            </View>


        );
      }

Output 1 2 3 4 5 6 7 8 9

Update TextView Every Second

Add following code in your onCreate() method:

Thread thread = new Thread() {

  @Override
  public void run() {
    try {
      while (!thread.isInterrupted()) {
        Thread.sleep(1000);
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            // update TextView here!
          }
        });
      }
    } catch (InterruptedException e) {
    }
  }
};

thread.start();

This code starts an thread which sleeps 1000 milliseconds every round.

Algorithm to generate all possible permutations of a list?

I know this a very very old and even off-topic in today's stackoverflow but I still wanted to contribute a friendly javascript answer for the simple reason that it runs in your browser.

I've also added the debugger directive breakpoint so you can step through the code (chrome required) to see how this algorithm works. Open up your dev console in chrome (F12 in windows or CMD + OPTION + I on mac) and then click "Run code snippet". This implements the same exact algorithm that @WhirlWind presented in his answer.

Your browser should pause execution at the debugger directive. Use F8 to continue code execution.

Step through the code and see how it works!

_x000D_
_x000D_
function permute(rest, prefix = []) {_x000D_
  if (rest.length === 0) {_x000D_
    return [prefix];_x000D_
  }_x000D_
  return (rest_x000D_
    .map((x, index) => {_x000D_
      const oldRest = rest;_x000D_
      const oldPrefix = prefix;_x000D_
      // the `...` destructures the array into single values flattening it_x000D_
      const newRest = [...rest.slice(0, index), ...rest.slice(index + 1)];_x000D_
      const newPrefix = [...prefix, x];_x000D_
      debugger;_x000D_
_x000D_
      const result = permute(newRest, newPrefix);_x000D_
      return result;_x000D_
    })_x000D_
    // this step flattens the array of arrays returned by calling permute_x000D_
    .reduce((flattened, arr) => [...flattened, ...arr], [])_x000D_
  );_x000D_
}_x000D_
console.log(permute([1, 2, 3]));
_x000D_
_x000D_
_x000D_

How to escape the equals sign in properties files

This method should help to programmatically generate values guaranteed to be 100% compatible with .properties files:

public static String escapePropertyValue(final String value) {
    if (value == null) {
        return null;
    }

    try (final StringWriter writer = new StringWriter()) {
        final Properties properties = new Properties();
        properties.put("escaped", value);
        properties.store(writer, null);
        writer.flush();

        final String stringifiedProperties = writer.toString();
        final Pattern pattern = Pattern.compile("(.*?)escaped=(.*?)" + Pattern.quote(System.lineSeparator()) + "*");
        final Matcher matcher = pattern.matcher(stringifiedProperties);

        if (matcher.find() && matcher.groupCount() <= 2) {
            return matcher.group(matcher.groupCount());
        }

        // This should never happen unless the internal implementation of Properties::store changed
        throw new IllegalStateException("Could not escape property value");
    } catch (final IOException ex) {
        // This should never happen. IOException is only because the interface demands it
        throw new IllegalStateException("Could not escape property value", ex);
    }
}

You can call it like this:

final String escapedPath = escapePropertyValue("C:\\Users\\X");
writeToFile(escapedPath); // will pass "C\\:\\\\Users\\\\X"

This method a little bit expensive but, writing properties to a file is typically an sporadic operation anyway.

Javascript: how to validate dates in format MM-DD-YYYY?

Simple way to solve

var day = document.getElementById("DayTextBox").value;

var regExp = /^([1-9]|[1][012])\/|-([1-9]|[1][0-9]|[2][0-9]|[3][01])\/|-([1][6-9][0-9][0-9]|[2][0][01][0-9])$/;

return regExp.test(day);

Android video streaming example

I had the same problem but finally I found the way.

Here is the walk through:

1- Install VLC on your computer (SERVER) and go to Media->Streaming (Ctrl+S)

2- Select a file to stream or if you want to stream your webcam or... click on "Capture Device" tab and do the configuration and finally click on "Stream" button.

3- Here you should do the streaming server configuration, just go to "Option" tab and paste the following command:

:sout=#transcode{vcodec=mp4v,vb=400,fps=10,width=176,height=144,acodec=mp4a,ab=32,channels=1,samplerate=22050}:rtp{sdp=rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/}

NOTE: Replace YOURCOMPUTER_SERVER_IP_ADDR with your computer IP address or any server which is running VLC...

NOTE: You can see, the video codec is MP4V which is supported by android.

4- go to eclipse and create a new project for media playbak. create a VideoView object and in the OnCreate() function write some code like this:

mVideoView = (VideoView) findViewById(R.id.surface_view);

mVideoView.setVideoPath("rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/");
mVideoView.setMediaController(new MediaController(this));

5- run the apk on the device (not simulator, i did not check it) and wait for the playback to be started. please consider the buffering process will take about 10 seconds...

Question: Anybody know how to reduce buffering time and play video almost live ?

Searching in a ArrayList with custom objects for certain strings

contains() method just calls equals() on ArrayList elements, so you can overload your class's equals() based on the name class variable. Return true from equals() if name is equal to the matching String. Hope this helps.

How to change color of Toolbar back button in Android?

Here is the simplest way of achieving Light and Dark Theme for Toolbar.You have to change the value of app:theme of the Toolbar tag

  • For Black Toolbar Title and Black Up arrow, your toolbar should implement following theme:

app:theme="@style/ThemeOverlay.AppCompat.Light"

Black Toolbar Title and Up Arrow

  • For White Toolbar Title and White Up arrow, your toolbar should implement following theme:

app:theme="@style/ThemeOverlay.AppCompat"

White Toolbar Title and Up Arrow

How to see top processes sorted by actual memory usage?

Building on gaoithe's answer, I attempted to make the memory units display in megabytes, and sorted by memory descending limited to 15 entries:

ps -e -orss=,args= |awk '{print $1 " " $2 }'| awk '{tot[$2]+=$1;count[$2]++} END {for (i in tot) {print tot[i],i,count[i]}}' | sort -n | tail -n 15 | sort -nr | awk '{ hr=$1/1024; printf("%13.2fM", hr); print "\t" $2 }'

       588.03M  /usr/sbin/apache2
       275.64M  /usr/sbin/mysqld
       138.23M  vim
        97.04M  -bash
        40.96M  ssh
        34.28M  tmux
        17.48M  /opt/digitalocean/bin/do-agent
        13.42M  /lib/systemd/systemd-journald
        10.68M  /lib/systemd/systemd
        10.62M  /usr/bin/redis-server
         8.75M  awk
         7.89M  sshd:
         4.63M  /usr/sbin/sshd
         4.56M  /lib/systemd/systemd-logind
         4.01M  /usr/sbin/rsyslogd

Here's an example alias to use it in a bash config file:

    alias topmem="ps -e -orss=,args= |awk '{print \$1 \" \" \$2 }'| awk '{tot[\$2]+=\$1;count[\$2]++} END {for (i in tot) {print tot[i],i,count[i]}}' | sort -n | tail -n 15 | sort -nr | awk '{ hr=\$1/1024; printf(\"%13.2fM\", hr); print \"\t\" \$2 }'"

Then you can just type topmem on the command line.

How to connect to SQL Server database from JavaScript in the browser?

This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.

How do you redirect HTTPS to HTTP?

this works for me.

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
    Redirect "https://www.example.com/" "http://www.example.com/"
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.com
    # ... 
</VirtualHost>

be sure to listen to both ports 80 and 443.

How do you scroll up/down on the console of a Linux VM

I ran into the same problem with VMWare workstation with Ubuntu guest, turns out VmWare doesn't support scrolling back up from the server view. What I did was to install x GUI, then run xterm from there. For some reason it runs the same, but lets you scroll the normal ways. Hope this helps future readers in VmWare virtual boxes.

How to change color and font on ListView

Even better, you do not need to create separate android xml layout for list cell view. You can just use "android.R.layout.simple_list_item_1" if the list only contains textview.

private class ExampleAdapter extends ArrayAdapter<String>{

    public ExampleAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        View view =  super.getView(position, convertView, parent);

        TextView tv = (TextView) view.findViewById(android.R.id.text1);
        tv.setTextColor(0);

        return view;
    }

How to check if a symlink exists

Is the file really a symbolic link? If not, the usual test for existence is -r or -e.

See man test.

Create a hexadecimal colour based on a string with JavaScript

Here's a solution I came up with to generate aesthetically pleasing pastel colours based on an input string. It uses the first two chars of the string as a random seed, then generates R/G/B based on that seed.

It could be easily extended so that the seed is the XOR of all chars in the string, rather than just the first two.

Inspired by David Crow's answer here: Algorithm to randomly generate an aesthetically-pleasing color palette

//magic to convert strings to a nice pastel colour based on first two chars
//
// every string with the same first two chars will generate the same pastel colour
function pastel_colour(input_str) {

    //TODO: adjust base colour values below based on theme
    var baseRed = 128;
    var baseGreen = 128;
    var baseBlue = 128;

    //lazy seeded random hack to get values from 0 - 256
    //for seed just take bitwise XOR of first two chars
    var seed = input_str.charCodeAt(0) ^ input_str.charCodeAt(1);
    var rand_1 = Math.abs((Math.sin(seed++) * 10000)) % 256;
    var rand_2 = Math.abs((Math.sin(seed++) * 10000)) % 256;
    var rand_3 = Math.abs((Math.sin(seed++) * 10000)) % 256;

    //build colour
    var red = Math.round((rand_1 + baseRed) / 2);
    var green = Math.round((rand_2 + baseGreen) / 2);
    var blue = Math.round((rand_3 + baseBlue) / 2);

    return { red: red, green: green, blue: blue };
}

GIST is here: https://gist.github.com/ro-sharp/49fd46a071a267d9e5dd

Creating a 3D sphere in Opengl using Visual C++

I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:

inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
    int curRow = r * sectors;
    int nextRow = (r+1) * sectors;

    indices.push_back(curRow + s);
    indices.push_back(nextRow + s);
    indices.push_back(nextRow + (s+1));

    indices.push_back(curRow + s);
    indices.push_back(nextRow + (s+1));
    indices.push_back(curRow + (s+1));
}

void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
             float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);

    for(int r = 0; r < rings; ++r) {
        for(int s = 0; s < sectors; ++s) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

            texcoords.push_back(vec2(s*S, r*R));
            vertices.push_back(vec3(x,y,z) * radius);
            push_indices(indices, sectors, r, s);
        }
    }
}

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

see if their duplicate jars or dependencies your adding remove it and your error will be gone: Eg: if you add android:supportv4 jar and also dependency you will get the error so remove the jar error will be gone

JavaScript require() on client side

Yes it is very easy to use, but you need to load javascript file in browser by script tag

<script src="module.js"></script> 

and then user in js file like

var moduel = require('./module');

I am making a app using electron and it works as expected.

'python' is not recognized as an internal or external command

If you want to see python version then you should use py -V instead of python -V

C:\Users\ghasan>py -V

Python 3.7.1

If you want to go to python's running environment then you should use py instead of python

C:\Users\ghasan>py

Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

Here you can run the python program as:

print('Hello Python')

Hello Python

In Python, how to check if a string only contains certain characters?

Use python Sets when you need to compare hm... sets of data. Strings can be represented as sets of characters quite fast. Here I test if string is allowed phone number. First string is allowed, second not. Works fast and simple.

In [17]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(898) 64-901-63 ');p.issubset(allowed)").timeit()

Out[17]: 0.8106249139964348

In [18]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(950) 64-901-63 ???');p.issubset(allowed)").timeit()

Out[18]: 0.9240323599951807

Never use regexps if you can avoid them.

C# '@' before a String

What is this for and why would I use @":\" instead of ":\"?

Because when you have a long string with many \ you don't need to escape them all and the \n, \r and \f won't work too.

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

I'm not sure why your current code is failing (what is the Exception you get?), but I would like to point out this approach performs O(N-squared). Consider pre-sorting your input arrays (if they are not defined to be pre-sorted) and merging the sorted arrays:

http://www.algolist.net/Algorithms/Merge/Sorted_arrays

Sorting is generally O(N logN) and the merge is O(m+n).

How to find a string inside a entire database?

I think you have to options:

  1. Build a dynamic SQL using sys.tables and sys.columns to perform the search (example here).

  2. Use any program that have this function. An example of this is SQL Workbench (free).

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

Difference between static memory allocation and dynamic memory allocation

Static Memory Allocation:

  • Variables get allocated permanently
  • Allocation is done before program execution
  • It uses the data structure called stack for implementing static allocation
  • Less efficient
  • There is no memory reusability

Dynamic Memory Allocation:

  • Variables get allocated only if the program unit gets active
  • Allocation is done during program execution
  • It uses the data structure called heap for implementing dynamic allocation
  • More efficient
  • There is memory reusability . Memory can be freed when not required

Forking vs. Branching in GitHub

You cannot always make a branch or pull an existing branch and push back to it, because you are not registered as a collaborator for that specific project.

Forking is nothing more than a clone on the GitHub server side:

  • without the possibility to directly push back
  • with fork queue feature added to manage the merge request

You keep a fork in sync with the original project by:

  • adding the original project as a remote
  • fetching regularly from that original project
  • rebase your current development on top of the branch of interest you got updated from that fetch.

The rebase allows you to make sure your changes are straightforward (no merge conflict to handle), making your pulling request that more easy when you want the maintainer of the original project to include your patches in his project.

The goal is really to allow collaboration even though direct participation is not always possible.


The fact that you clone on the GitHub side means you have now two "central" repository ("central" as "visible from several collaborators).
If you can add them directly as collaborator for one project, you don't need to manage another one with a fork.

fork on GitHub

The merge experience would be about the same, but with an extra level of indirection (push first on the fork, then ask for a pull, with the risk of evolutions on the original repo making your fast-forward merges not fast-forward anymore).
That means the correct workflow is to git pull --rebase upstream (rebase your work on top of new commits from upstream), and then git push --force origin, in order to rewrite the history in such a way your own commits are always on top of the commits from the original (upstream) repo.

See also:

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

you can delete the corresponding failed artifact directory in you local repository. And also you can simply use the -U in the goal. It will do the work. This works with maven 3. So no need to downgrade to maven 2.

Organizing a multiple-file Go project

I have studied a number of Go projects and there is a fair bit of variation. You can kind of tell who is coming from C and who is coming from Java, as the former dump just about everything in the projects root directory in a main package, and the latter tend to put everything in a src directory. Neither is optimal however. Each have consequences because they affect import paths and how others can reuse them.

To get the best results I have worked out the following approach.

myproj/
  main/
    mypack.go
  mypack.go

Where mypack.go is package mypack and main/mypack.go is (obviously) package main.

If you need additional support files you have two choices. Either keep them all in the root directory, or put private support files in a lib subdirectory. E.g.

myproj/
  main/
    mypack.go
  myextras/
    someextra.go
  mypack.go
  mysupport.go

Or

myproj.org/
  lib/
    mysupport.go
    myextras/
      someextra.go
  main/
    mypack.go
  mypage.go

Only put the files in a lib directory if they are not intended to be imported by another project. In other words, if they are private support files. That's the idea behind having lib --to separate public from private interfaces.

Doing things this way will give you a nice import path, myproj.org/mypack to reuse the code in other projects. If you use lib then internal support files will have an import path that is indicative of that, myproj.org/lib/mysupport.

When building the project, use main/mypack, e.g. go build main/mypack. If you have more than one executable you can also separate those under main without having to create separate projects. e.g. main/myfoo/myfoo.go and main/mybar/mybar.go.

How to know function return type and argument types?

Docstrings (and documentation in general). Python 3 introduces (optional) function annotations, as described in PEP 3107 (but don't leave out docstrings)

When use getOne and findOne methods Spring Data JPA

while spring.jpa.open-in-view was true, I didn't have any problem with getOne but after setting it to false , i got LazyInitializationException. Then problem was solved by replacing with findById.
Although there is another solution without replacing the getOne method, and that is put @Transactional at method which is calling repository.getOne(id). In this way transaction will exists and session will not be closed in your method and while using entity there would not be any LazyInitializationException.

Sort array by firstname (alphabetically) in Javascript

Shortest possible code with ES6!

users.sort((a, b) => a.firstname.localeCompare(b.firstname))

String.prototype.localeCompare() basic support is universal!

Where are Magento's log files located?

To create your custom log file, try this code

Mage::log('your debug message', null, 'yourlog_filename.log');

Refer this Answer

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

Change file permission to 755 for the file:

/var/lib/mongodb/mongod.lock

Difference between if () { } and if () : endif;

They are the same but the second one is great if you have MVC in your code and don't want to have a lot of echos in your code. For example, in my .phtml files (Zend Framework) I will write something like this:

<?php if($this->value): ?>
Hello
<?php elseif($this->asd): ?>
Your name is: <?= $this->name ?>
<?php else: ?>
You don't have a name.
<?php endif; ?>

Difference between EXISTS and IN in SQL?

If you are using the IN operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS, the SQL engine will stop the scanning process as soon as it found a match.

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

How to delete multiple pandas (python) dataframes from memory to save RAM?

In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).

You can manually trigger the garbage collection using

import gc
gc.collect()

But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.

Reference

Looping through a DataTable

Please try the following code below:

//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.

using (reader = cmd.ExecuteReader())
{
// Load the Data table object
  dataTable.Load(reader);
  if (dataTable.Rows.Count > 0)
  {
    DataColumn col = dataTable.Columns["YourColumnName"];  
    foreach (DataRow row in dataTable.Rows)
    {                                   
       strJsonData = row[col].ToString();
    }
  }
}

How to get a string after a specific substring?

Try this general approach:

import re
my_string="hello python world , i'm a beginner "
p = re.compile("world(.*)")
print (p.findall(my_string))

#[" , i'm a beginner "]

zsh compinit: insecure directories

On macOS Sierra you need to run: sudo chown -R $(whoami):staff /usr/local

How to output an Excel *.xls file from classic ASP

You can always just export the HTML table to an XLS document. Excel does a pretty good job understanding HTML tables.

Another possiblitly is to export the HTML tables as a CSV or TSV file, but you would need to setup the formatting in your code. This isn't too difficult to accomplish.

There's some classes in the Microsoft.Office.Interop that allow you to create an Excel file programatically, but I have always found them to be a little clumsy. You can find a .NET version of creating a spreadsheet here, which should be pretty easy to modify for classic ASP.

As for .NET, I've always liked CarlosAG's Excel XML Writer Library. It has a nice generator so you can setup your Excel file, save it as an XML spreadsheet and it generates the code to do all the formatting and everything. I know it's not classic ASP, but I thought that I would throw it out there.


With what you're trying above, try adding the header:

"Content-Disposition", "attachment; filename=excelTest.xls"

See if that works. Also, I always use this for the content type:

  Response.ContentType = "application/octet-stream"
    Response.ContentType = "application/vnd.ms-excel"

Creating the Singleton design pattern in PHP5

I know this is probably going to cause an unnecessary flame war, but I can see how you might want more than one database connection, so I would concede the point that singleton might not be the best solution for that... however, there are other uses of the singleton pattern that I find extremely useful.

Here's an example: I decided to roll my own MVC and templating engine because I wanted something really lightweight. However, the data that I want to display contains a lot of special math characters such as ≥ and μ and what have you... The data is stored as the actual UTF-8 character in my database rather than pre-HTML-encoded because my app can deliver other formats such as PDF and CSV in addition to HTML. The appropriate place to format for HTML is inside the template ("view" if you will) that is responsible for rendering that page section (snippet). I want to convert them to their appropriate HTML entities, but PHPs get_html_translation_table() function is not super fast. It makes better sense to retrieve the data one time and store as an array, making it available for all to use. Here's a sample I knocked together to test the speed. Presumably, this would work regardless of whether the other methods you use (after getting the instance) were static or not.

class EncodeHTMLEntities {

    private static $instance = null;//stores the instance of self
    private $r = null;//array of chars elligalbe for replacement

    private function __clone(){
    }//disable cloning, no reason to clone

    private function __construct()
    {
        $allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);
        $specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
        $this->r = array_diff($allEntities, $specialEntities);
    }

    public static function replace($string)
    {
        if(!(self::$instance instanceof self) ){
            self::$instance = new self();
        }
        return strtr($string, self::$instance->r);
    }
}
//test one million encodings of a string
$start = microtime(true);
for($x=0; $x<1000000; $x++){
    $dump = EncodeHTMLEntities::replace("Reference method for diagnosis of CDAD, but clinical usefulness limited due to extended turnaround time (=96 hrs)");
}
$end = microtime(true);
echo "Run time: ".($end-$start)." seconds using singleton\n";
//now repeat the same without using singleton
$start = microtime(true);
for($x=0; $x<1000000; $x++){
    $allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);
    $specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
    $r = array_diff($allEntities, $specialEntities);
    $dump = strtr("Reference method for diagnosis of CDAD, but clinical usefulness limited due to extended turnaround time (=96 hrs)", $r);
}
$end = microtime(true);
echo "Run time: ".($end-$start)." seconds without using singleton";

Basically, I saw typical results like this:

php test.php
Run time: 27.842966794968 seconds using singleton
Run time: 237.78191494942 seconds without using singleton

So while I'm certainly no expert, I don't see a more convenient and reliable way to reduce the overhead of slow calls for some kind of data, while making it super simple (single line of code to do what you need). Granted my example only has one useful method, and therefore is no better than a globally defined function, but as soon as you have two methods, you're going to want to group them together, right? Am I way off base?

Also, I prefer examples that actually DO something, since sometimes it's hard to visualise when an example includes statements like "//do something useful here" which I see all the time when searching for tutorials.

Anyway, I'd love any feedback or comments on why using a singleton for this type of thing is detrimental (or overly complicated).

Xcode 9 Swift Language Version (SWIFT_VERSION)

This can happen when you added Core Data to an existing project.
Check the:
<Name>/<Name>.xcdatamodeld/<Name>.xcdatamodel/contents
file.
This file contains an entry "sourceLanguage" that (by default) might have been set to "Swift". Change it to "Objective-C".

How to perform Join between multiple tables in LINQ lambda

 public ActionResult Index()
    {
        List<CustomerOrder_Result> obj = new List<CustomerOrder_Result>();

       var  orderlist = (from a in db.OrderMasters
                         join b in db.Customers on a.CustomerId equals b.Id
                         join c in db.CustomerAddresses on b.Id equals c.CustomerId
                         where a.Status == "Pending"
                         select new
                         {
                             Customername = b.Customername,
                             Phone = b.Phone,
                             OrderId = a.OrderId,
                             OrderDate = a.OrderDate,
                             NoOfItems = a.NoOfItems,
                             Order_amt = a.Order_amt,
                             dis_amt = a.Dis_amt,
                             net_amt = a.Net_amt,
                             status=a.Status,  
                             address = c.address,
                             City = c.City,
                             State = c.State,
                             Pin = c.Pin

                         }) ;
       foreach (var item in orderlist)
       {

           CustomerOrder_Result clr = new CustomerOrder_Result();
           clr.Customername=item.Customername;
           clr.Phone = item.Phone;
           clr.OrderId = item.OrderId;
           clr.OrderDate = item.OrderDate;
           clr.NoOfItems = item.NoOfItems;
           clr.Order_amt = item.Order_amt;
           clr.net_amt = item.net_amt;
           clr.address = item.address;
           clr.City = item.City;
           clr.State = item.State;
           clr.Pin = item.Pin;
           clr.status = item.status;

           obj.Add(clr);



       }

How to get absolute path to file in /resources folder of your project

The proper way that actually works:

URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();

It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.

(The seemingly obvious new File(resource.getPath()) doesn't work for all paths! The path is still URL-encoded!)

What is the C++ function to raise a number to a power?

Use the pow(x,y) function: See Here

Just include math.h and you're all set.

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

Just include SizeToReportContent="true" as shown below

<rsweb:ReportViewer ID="ReportViewer1" runat="server" SizeToReportContent="True"...

How can I count occurrences with groupBy?

List<String> list = new ArrayList<>();

list.add("Hello");
list.add("Hello");
list.add("World");

Map<String, List<String>> collect = list.stream()
                                        .collect(Collectors.groupingBy(o -> o));
collect.entrySet()
       .forEach(e -> System.out.println(e.getKey() + " - " + e.getValue().size()));

Most efficient way to get table row count

Couldn't you just create a record in a separate table or whatever with a column called Users and UPDATE it with the last inserted id on User Registration?

Then you would just check this field with a simple query.

It might be rough but it would work perfectly.

Clear and reset form input fields

To clear your form, admitted that your form's elements values are saved in your state, you can map through your state like that :

  // clear all your form
  Object.keys(this.state).map((key, index) => {
      this.setState({[key] : ""});
   });

If your form is among other fields, you can simply insert them in a particular field of the state like that:

 state={ 
        form: {
        name:"",
        email:""}
      }

      // handle set in nested objects
      handleChange = (e) =>{ 
        e.preventDefault(); 

        const newState = Object.assign({}, this.state);
        newState.form[e.target.name] = e.target.value;
        this.setState(newState);
      }

      // submit and clear state in nested object 
      onSubmit = (e) =>{ 
        e.preventDefault(); 

       var form =   Object.assign({}, this.state.form);
       Object.keys(form).map((key, index) => {
          form[key] = "" ;
        });

       this.setState({form})
      } 

How can I create an object based on an interface file definition in TypeScript?

You can set default values using Class.

Without Class Constructor:

interface IModal {
  content: string;
  form: string;
  href: string;
  isPopup: boolean;
};

class Modal implements IModal {
  content = "";
  form = "";
  href: string;  // will not be added to object
  isPopup = true;
}

const myModal = new Modal();
console.log(myModal); // output: {content: "", form: "", isPopup: true}

With Class Constructor

interface IModal {
  content: string;
  form: string;
  href: string;
  isPopup: boolean;
}

class Modal implements IModal {
  constructor() {
    this.content = "";
    this.form = "";
    this.isPopup = true;
  }

  content: string;

  form: string;

  href: string; // not part of constructor so will not be added to object

  isPopup: boolean;
}

const myModal = new Modal();
console.log(myModal); // output: {content: "", form: "", isPopup: true}

How to install mcrypt extension in xampp

The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.

Using JQuery hover with HTML image map

I found this wonderful mapping script (mapper.js) that I have used in the past. What's different about it is you can hover over the map or a link on your page to make the map area highlight. Sadly it's written in javascript and requires a lot of in-line coding in the HTML - I would love to see this script ported over to jQuery :P

Also, check out all the demos! I think this example could almost be made into a simple online game (without using flash) - make sure you click on the different camera angles.

Tracking the script execution time in PHP

It is going to be prettier if you format the seconds output like:

echo "Process took ". number_format(microtime(true) - $start, 2). " seconds.";

will print

Process took 6.45 seconds.

This is much better than

Process took 6.4518549156189 seconds.

How do you create a REST client for Java?

As I mentioned in this thread I tend to use Jersey which implements JAX-RS and comes with a nice REST client. The nice thing is if you implement your RESTful resources using JAX-RS then the Jersey client can reuse the entity providers such as for JAXB/XML/JSON/Atom and so forth - so you can reuse the same objects on the server side as you use on the client side unit test.

For example here is a unit test case from the Apache Camel project which looks up XML payloads from a RESTful resource (using the JAXB object Endpoints). The resource(uri) method is defined in this base class which just uses the Jersey client API.

e.g.

    clientConfig = new DefaultClientConfig();
    client = Client.create(clientConfig);

    resource = client.resource("http://localhost:8080");
    // lets get the XML as a String
    String text = resource("foo").accept("application/xml").get(String.class);        

BTW I hope that future version of JAX-RS add a nice client side API along the lines of the one in Jersey

Should methods in a Java interface be declared with or without a public access modifier?

I always write what I would use if there was no interface and I was writing a direct implementation, i.e., I would use public.

Python object deleting itself

In this specific context, your example doesn't make a lot of sense.

When a Being picks up an Item, the item retains an individual existence. It doesn't disappear because it's been picked up. It still exists, but it's (a) in the same location as the Being, and (b) no longer eligible to be picked up. While it's had a state change, it still exists.

There is a two-way association between Being and Item. The Being has the Item in a collection. The Item is associated with a Being.

When an Item is picked up by a Being, two things have to happen.

  • The Being how adds the Item in some set of items. Your bag attribute, for example, could be such a set. [A list is a poor choice -- does order matter in the bag?]

  • The Item's location changes from where it used to be to the Being's location. There are probably two classes os Items - those with an independent sense of location (because they move around by themselves) and items that have to delegate location to the Being or Place where they're sitting.

Under no circumstances does any Python object ever need to get deleted. If an item is "destroyed", then it's not in a Being's bag. It's not in a location.

player.bag.remove(cat)

Is all that's required to let the cat out of the bag. Since the cat is not used anywhere else, it will both exist as "used" memory and not exist because nothing in your program can access it. It will quietly vanish from memory when some quantum event occurs and memory references are garbage collected.

On the other hand,

here.add( cat )
player.bag.remove(cat)

Will put the cat in the current location. The cat continues to exist, and will not be put out with the garbage.

Sublime Text 3, convert spaces to tabs

Here is how you to do it automatically on save: https://coderwall.com/p/zvyg7a/convert-tabs-to-spaces-on-file-save

Unfortunately the package is not working when you install it from the Package Manager.

How to configure log4j with a properties file

I believe the log4j.properties directory it needs to be in the java classpath. In your case adding the CWD to the classpath should work.

"java.lang.OutOfMemoryError: PermGen space" in Maven build

If you want to make this part of your POM for a repeatable build, you can use the fork-variant of a few of the plugins (especially compiler:compile and surefire:test):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.2</version>
    <configuration>
      <fork>true</fork>
      <meminitial>128m</meminitial>
      <maxmem>1024m</maxmem>
      <compilerArgs>
        <arg>-XX:MaxPermSize=256m</arg>
      </compilerArgs>
    </configuration>
  </plugin>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18</version>
    <configuration>
        <forkCount>1</forkCount>
        <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
    </configuration>
</plugin>

How do I get the domain originating the request in express.js?

Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host') is deprecated, that's why giving Undefined. Use,

    req.header('Origin');
    req.header('Host');
    // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.

No connection could be made because the target machine actively refused it?

I came across this error and took some time to resolve it. In my case I had https and net.tcp configured as IIS bindings on same port. Obviously you can't have two things on the same port. I used netstat -ap tcp command to check whether there is something listening on that port. There was none listening. Removing unnecessary binding (https in my case) solved my issue.

Valid values for android:fontFamily and what they map to?

Available fonts (as of Oreo)

Preview of all fonts

The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.

For code sleuths: fonts.xml is the definitive and ever-expanding list of Android fonts.


Using these fonts

Set the android:fontFamily and android:textStyle attributes, e.g.

<!-- Roboto Bold -->
<TextView
    android:fontFamily="sans-serif"
    android:textStyle="bold" />

to the desired values from this table:

Font                     | android:fontFamily          | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin              | sans-serif-thin             |
Roboto Light             | sans-serif-light            |
Roboto Regular           | sans-serif                  |
Roboto Bold              | sans-serif                  | bold
Roboto Medium            | sans-serif-medium           |
Roboto Black             | sans-serif-black            |
Roboto Condensed Light   | sans-serif-condensed-light  |
Roboto Condensed Regular | sans-serif-condensed        |
Roboto Condensed Medium  | sans-serif-condensed-medium |
Roboto Condensed Bold    | sans-serif-condensed        | bold
Noto Serif               | serif                       |
Noto Serif Bold          | serif                       | bold
Droid Sans Mono          | monospace                   |
Cutive Mono              | serif-monospace             |
Coming Soon              | casual                      |
Dancing Script           | cursive                     |
Dancing Script Bold      | cursive                     | bold
Carrois Gothic SC        | sans-serif-smallcaps        |

(Noto Sans is a fallback font; you can't specify it directly)

Note: this table is derived from fonts.xml. Each font's family name and style is listed in fonts.xml, e.g.

<family name="serif-monospace">
    <font weight="400" style="normal">CutiveMono.ttf</font>
</family>

serif-monospace is thus the font family, and normal is the style.


Compatibility

Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:

  • Ice Cream Sandwich: Roboto regular, bold, italic, and bold italic
  • Jelly Bean: Roboto light, light italic, condensed, condensed bold, condensed italic, and condensed bold italic
  • Jelly Bean MR1: Roboto thin and thin italic
  • Lollipop:
    • Roboto medium, medium italic, black, and black italic
    • Noto Serif regular, bold, italic, bold italic
    • Cutive Mono
    • Coming Soon
    • Dancing Script
    • Carrois Gothic SC
    • Noto Sans
  • Oreo MR1: Roboto condensed medium

How do I count unique visitors to my site?

Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.

In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.

Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!


Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).

Writing a Python list of lists to a csv file

Ambers's solution also works well for numpy arrays:

from pylab import *
import csv

array_=arange(0,10,1)
list_=[array_,array_*2,array_*3]
with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(list_)

Disable Drag and Drop on HTML elements?

This works. Try it.

<BODY ondragstart="return false;" ondrop="return false;">

Font.createFont(..) set color and size (java.awt.Font)

Because font doesn't have color, you need a panel to make a backgound color and give the foreground color for both JLabel (if you use JLabel) and JPanel to make font color, like example below :

JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);

JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);

The background color of label is maroon with yellow font color.

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

Async await in linq select

I have the same problem as @KTCheek in that I need it to execute sequentially. However I figured I would try using IAsyncEnumerable (introduced in .NET Core 3) and await foreach (introduced in C# 8). Here's what I have come up with:

public static class IEnumerableExtensions {
    public static async IAsyncEnumerable<TResult> SelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector) {
        foreach (var item in source) {
            yield return await selector(item);
        }
    }
}

public static class IAsyncEnumerableExtensions {
    public static async Task<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource> source) {
        var list = new List<TSource>();

        await foreach (var item in source) {
            list.Add(item);
        }

        return list;
    }
}

This can be consumed by saying:

var inputs = await events.SelectAsync(ev => ProcessEventAsync(ev)).ToListAsync();

Update: Alternatively you can add a reference to "System.Linq.Async" and then you can say:

var inputs = await events
    .ToAsyncEnumerable()
    .SelectAwait(async ev => await ProcessEventAsync(ev))
    .ToListAsync();

SQL Server - Create a copy of a database table and place it in the same database?

1st option

select *
  into ABC_1
  from ABC;

2nd option: use SSIS, that is right click on database in object explorer > all tasks > export data

  • source and target: your DB
  • source table: ABC
  • target table: ABC_1 (table will be created)

Loop through Map in Groovy?

Quite simple with a closure:

def map = [
           'iPhone':'iWebOS',
           'Android':'2.3.3',
           'Nokia':'Symbian',
           'Windows':'WM8'
           ]

map.each{ k, v -> println "${k}:${v}" }

Cannot connect to Database server (mysql workbench)

For those who ignored that the initial error message displaying is the following one:

The name org.freedesktop.secrets was not provided by any .service files

Make sure to install gnome-keyring using the following

sudo apt install gnome-keyring

Save PL/pgSQL output from PostgreSQL to a CSV file

To Download CSV file with column names as HEADER use this command:

Copy (Select * From tableName) To '/tmp/fileName.csv' With CSV HEADER;

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

returning a Void object

If you just don't need anything as your type, you can use void. This can be used for implementing functions, or actions. You could then do something like this:

interface Action<T> {
    public T execute();
}

abstract class VoidAction implements Action<Void> {
    public Void execute() {
        executeInternal();
        return null;
    }

    abstract void executeInternal();
}

Or you could omit the abstract class, and do the return null in every action that doesn't require a return value yourself.

You could then use those actions like this:

Given a method

private static <T> T executeAction(Action<T> action) {
    return action.execute();
}

you can call it like

String result = executeAction(new Action<String>() {
    @Override
    public String execute() {
        //code here
        return "Return me!";
    }
});

or, for the void action (note that you're not assigning the result to anything)

executeAction(new VoidAction() {
    @Override
    public void executeInternal() {
        //code here
    }
});

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

I had tried almost all the above methods.

Finally fixed it by including the

script src="{%static 'App/js/jquery.js' %}"

just after loading the staticfiles i.e {% load staticfiles %} in base.html

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

I believe this has been answered in some sections already, just test with gmail for your "MAIL_HOST" instead and don't forget to clear cache. Setup like below: Firstly, you need to setup 2 step verification here google security. An App Password link will appear and you can get your App Password to insert into below "MAIL_PASSWORD". More info on getting App Password here

MAIL_DRIVER=smtp
[email protected]
MAIL_FROM_NAME=DomainName
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=YOUR_GMAIL_CREATED_APP_PASSWORD
MAIL_ENCRYPTION=tls

Clear cache with:

php artisan config:cache

Check if a record exists in the database

protected void btnsubmit_Click(object sender, EventArgs e)
{

        string s = @"SELECT * FROM tbl1 WHERE CodNo = @CodNo";
    SqlCommand cmd1 = new SqlCommand(s, con);
    cmd1.Parameters.AddWithValue("@CodNo", txtid.Text);
    con.Open();
    int records = (int)cmd1.ExecuteScalar();

    if (records > 0)
    {

        Response.Write("<script>alert('Record not Exist')</script>");

    }
    else
    {
        Response.Write("<script>alert('Record Exist')</script>"); 
     }
  }
        private void  insert_data()
{

        SqlCommand comm = new SqlCommand("Insert into tbl1(CodNo,name,lname,fname,gname,EmailID,PhonNo,gender,image,province,district,village,address,phonNo2,DateOfBirth,school,YearOfGraduation,exlanguage,province2,district2,village2,PlaceOfBirth,NIDnumber,IDchapter,IDpage,IDRecordNumber,NIDCard,Kankur1Year,Kankur1ID,Kankur1Mark,Kankur2Year,Kankur2ID,Kankur2Mark,Kankur3Year,Kankur3ID,Kankur3Mark) values(@CodNo,N'" + txtname.Text.ToString() + "',N'" + txtlname.Text.ToString() + "',N'" + txtfname.Text.ToString() + "',N'" + txtgname.Text.ToString() + "',N'" + txtemail.Text.ToString() + "','" + txtphonnumber.Text.ToString() + "',N'" + ddlgender.Text.ToString() + "',@image,N'" + txtprovince.Text.ToString() + "',N'" + txtdistrict.Text.ToString() + "',N'" + txtvillage.Text.ToString() + "',N'" + txtaddress.Value.ToString() + "','" + txtphonNo2.Text.ToString() + "',N'" + txtdbo.Text.ToString() + "',N'" + txtschool.Text.ToString() + "','" + txtgraduate.Text.ToString() + "',N'" + txtexlanguage.Text.ToString() + "',N'" + txtprovince1.Text.ToString() + "',N'" + txtdistrict1.Text.ToString() + "',N'" + txtvillage1.Text.ToString() + "',N'" + txtpbirth.Text.ToString() + "','" + txtNIDnumber.Text.ToString() + "','" + txtidchapter.Text.ToString() + "', '" + txtidpage.Text.ToString() + "','" + txtrecordNo.Text.ToString() + "',@NIDCard,'" + txtkankuryear1.Text.ToString() + "','" + txtkankurid1.Text.ToString() + "','" + txtkankurscore1.Text.ToString() + "','" + txtkankuryear2.Text.ToString() + "','" + txtkankurid2.Text.ToString() + "','" + txtkankurscore2.Text.ToString() + "','" + txtkankuryear3.Text.ToString() + "','" + txtkankurid3.Text.ToString() + "','" + txtkankurscore3.Text.ToString() + "')", con);

        flpimage.SaveAs(Server.MapPath("~/File/") + flpimage.FileName);
        string img = @"~/File/" + flpimage.FileName;
        flpnidcard.SaveAs(Server.MapPath("~/Tazkiera/") + flpnidcard.FileName);
        string img1 = @"~/Tazkiera/" + flpnidcard.FileName;

        comm.Parameters.AddWithValue("CodNo", Convert.ToInt32(txtid.Text));
        comm.Parameters.AddWithValue("image", flpimage.FileName);
        comm.Parameters.AddWithValue("NIDCard", flpnidcard.FileName);

        comm.ExecuteNonQuery();
        con.Close();

        Response.Redirect("~/SecondPage.aspx");
        //Response.Write("<script>alert('Record Inserted')</script>");

        }
    }

move_uploaded_file gives "failed to open stream: Permission denied" error

If you have Mac OS X, go to the file root or the folder of your website.

Then right-hand click on it, go to get information, go to the very bottom (Sharing & Permissions), open that, change all read-only to read and write. Make sure to open padlock, go to setting icon, and choose Apply to the enclosed items...

Check if object is a jQuery object

You may also use the .jquery property as described here: http://api.jquery.com/jquery-2/

var a = { what: "A regular JS object" },
b = $('body');

if ( a.jquery ) { // falsy, since it's undefined
    alert(' a is a jQuery object! ');    
}

if ( b.jquery ) { // truthy, since it's a string
    alert(' b is a jQuery object! ');
}

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

calculating execution time in c++

If you have cygwin installed, from it's bash shell, run your executable, say MyProgram, using the time utility, like so:

/usr/bin/time ./MyProgram

This will report how long the execution of your program took -- the output would look something like the following:

real    0m0.792s
user    0m0.046s
sys     0m0.218s

You could also manually modify your C program to instrument it using the clock() library function, like so:

#include <time.h>
int main(void) {
    clock_t tStart = clock();
    /* Do your stuff here */
    printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
    return 0;
}

How can I use async/await at the top level?

I can't seem to wrap my head around why this does not work.

Because main returns a promise; all async functions do.

At the top level, you must either:

  1. Use a top-level async function that never rejects (unless you want "unhandled rejection" errors), or

  2. Use then and catch, or

  3. (Coming soon!) Use top-level await, a proposal that has reached Stage 3 in the process that allows top-level use of await in a module.

#1 - Top-level async function that never rejects

(async () => {
    try {
        var text = await main();
        console.log(text);
    } catch (e) {
        // Deal with the fact the chain failed
    }
})();

Notice the catch; you must handle promise rejections / async exceptions, since nothing else is going to; you have no caller to pass them on to. If you prefer, you could do that on the result of calling it via the catch function (rather than try/catch syntax):

(async () => {
    var text = await main();
    console.log(text);
})().catch(e => {
    // Deal with the fact the chain failed
});

...which is a bit more concise (I like it for that reason).

Or, of course, don't handle errors and just allow the "unhandled rejection" error.

#2 - then and catch

main()
    .then(text => {
        console.log(text);
    })
    .catch(err => {
        // Deal with the fact the chain failed
    });

The catch handler will be called if errors occur in the chain or in your then handler. (Be sure your catch handler doesn't throw errors, as nothing is registered to handle them.)

Or both arguments to then:

main().then(
    text => {
        console.log(text);
    },
    err => {
        // Deal with the fact the chain failed
    }
);

Again notice we're registering a rejection handler. But in this form, be sure that neither of your then callbacks doesn't throw any errors, nothing is registered to handle them.

#3 top-level await in a module

You can't use await at the top level of a non-module script, but the top-level await proposal (Stage 3) allows you to use it at the top level of a module. It's similar to using a top-level async function wrapper (#1 above) in that you don't want your top-level code to reject (throw an error) because that will result in an unhandled rejection error. So unless you want to have that unhandled rejection when things go wrong, as with #1, you'd want to wrap your code in an error handler:

// In a module, once the top-level `await` proposal lands
try {
    var text = await main();
    console.log(text);
} catch (e) {
    // Deal with the fact the chain failed
}

Note that if you do this, any module that imports from your module will wait until the promise you're awaiting settles; when a module using top-level await is evaluated, it basically returns a promise to the module loader (like an async function does), which waits until that promise is settled before evaluating the bodies of any modules that depend on it.

Fixed width buttons with Bootstrap

You can also use the .btn-block class on the button, so that it expands to the parent's width.

If the parent is a fixed width element the button will expand to take all width. You can apply existing markup to the container to ensure fixed/fluid buttons take up only the required space.

<div class="span2">
<p><button class="btn btn-primary btn-block">Save</button></p>
<p><button class="btn btn-success btn-block">Download</button></p>
</div>

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<div class="span2">_x000D_
  <p><button class="btn btn-primary btn-block">Save</button></p>_x000D_
  <p><button class="btn btn-success btn-block">Download</button></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to reload/refresh jQuery dataTable?

Allan Jardine’s DataTables is a very powerful and slick jQuery plugin for displaying tabular data. It has many features and can do most of what you might want. One thing that’s curiously difficult though, is how to refresh the contents in a simple way, so I for my own reference, and possibly for the benefit of others as well, here’s a complete example of one way if doing this:

HTML

<table id="HelpdeskOverview">
  <thead>
    <tr>
      <th>Ärende</th>
      <th>Rapporterad</th>
      <th>Syst/Utr/Appl</th>
      <th>Prio</th>
      <th>Rubrik</th>
      <th>Status</th>
      <th>Ägare</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Javascript

function InitOverviewDataTable()
{
  oOverviewTable =$('#HelpdeskOverview').dataTable(
  {
    "bPaginate": true,
    "bJQueryUI": true,  // ThemeRoller-stöd
    "bLengthChange": false,
    "bFilter": false,
    "bSort": false,
    "bInfo": true,
    "bAutoWidth": true,
    "bProcessing": true,
    "iDisplayLength": 10,
    "sAjaxSource": '/Helpdesk/ActiveCases/noacceptancetest'
  });
}

function RefreshTable(tableId, urlData)
{
  $.getJSON(urlData, null, function( json )
  {
    table = $(tableId).dataTable();
    oSettings = table.fnSettings();

    table.fnClearTable(this);

    for (var i=0; i<json.aaData.length; i++)
    {
      table.oApi._fnAddData(oSettings, json.aaData[i]);
    }

    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
    table.fnDraw();
  });
}

function AutoReload()
{
  RefreshTable('#HelpdeskOverview', '/Helpdesk/ActiveCases/noacceptancetest');

  setTimeout(function(){AutoReload();}, 30000);
}

$(document).ready(function () {
  InitOverviewDataTable();
  setTimeout(function(){AutoReload();}, 30000);
});

Source

Processing Symbol Files in Xcode

In my case symbolicating was take forever. I force restart my phone with both of on/off and home button. Now quickly finished symbolicating and I am starting run my app via xcode.

CSS for grabbing cursors (drag & drop)

I may be late, but you can try the following code, which worked for me for Drag and Drop.

.dndclass{
    cursor: url('../images/grab1.png'), auto; 

}

.dndclass:active {
    cursor: url('../images/grabbing1.png'), auto;
}

You can use the images below in the URL above. Make sure it is a PNG transparent image. If not, download one from google.

enter image description here enter image description here

input() error - NameError: name '...' is not defined

We are using the following that works both python 2 and python 3

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Enter your name: "))

File Explorer in Android Studio

View > Tool Windows > Device File Explorer

Installing J2EE into existing eclipse IDE

Step 1 Go to Help ---> Install New Software...

Step 2 Try to find "http://download.eclipse.org/webtools/updates" under work with drop down. If you find then select and install all the available updates.

If you can not find then click on Add -> Add Repository. Name: Eclipse Webtools Location: http://download.eclipse.org/webtools/updates Select all available updates and Install them.

Visit http://download.eclipse.org/webtools/updates/ for more details.

Laravel use same form for create and edit

For example, your controller, retrive data and put the view

class ClassExampleController extends Controller
{

    public function index()
    {   

        $test = Test::first(1);

        return view('view-form',[
            'field' => $test,
        ]);
    }
}

Add default value in the same form, create and edit, is very simple

<!-- view-form file -->
<form action="{{ 
    isset($field) ? 
    @route('field.updated', $field->id) : 
    @route('field.store')
}}">
    <!-- Input case -->
    <input name="name_input" class="form-control" 
    value="{{ isset($field->name) ? $field->name : '' }}">
</form>

And, you remember add csrf_field, in case a POST method requesting. Therefore, repeat input, and select element, compare each option

<select name="x_select">
@foreach($field as $subfield)

    @if ($subfield == $field->name)
        <option val="i" checked>
    @else
        <option val="i" >
    @endif

@endforeach
</select>

How to code a BAT file to always run as admin mode?

You use runas to launch a program as a specific user:

runas /user:Administrator Example1Server.exe

How to submit an HTML form on loading the page?

using javascript

 <form id="frm1" action="file.php"></form>
    <script>document.getElementById('frm1').submit();</script>

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

In addition to what was already said - in order to avoid this error from interfering (stopping) other Javascript code on your page, you could try forcing the YouTube iframe to load last - after all other Javascript code is loaded.

How to add a browser tab icon (favicon) for a website?

I'd recommend you to try http://faviconer.com to convert your .PNG or .GIF to a .ICO file.

You can create both 16x16 and 32x32 (for new retina display) in one .ICO file.

No issues with IE and Firefox

Case insensitive comparison NSString

 NSString *stringA;
 NSString *stringB;

 if (stringA && [stringA caseInsensitiveCompare:stringB] == NSOrderedSame) {
     // match
 }

Note: stringA && is required because when stringA is nil:

 stringA = nil;
 [stringA caseInsensitiveCompare:stringB] // return 0

and so happens NSOrderedSame is also defined as 0.

The following example is a typical pitfall:

 NSString *rank = [[NSUserDefaults standardUserDefaults] stringForKey:@"Rank"];
 if ([rank caseInsensitiveCompare:@"MANAGER"] == NSOrderedSame) {
     // what happens if "Rank" is not found in standardUserDefaults
 }

How can I link a photo in a Facebook album to a URL

You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."

Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.

Update:

The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg

Parse JSON in JavaScript?

The standard way to parse JSON in JavaScript is JSON.parse()

The JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:

_x000D_
_x000D_
const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);
_x000D_
_x000D_
_x000D_


The only time you won't be able to use JSON.parse() is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. Alternatively, you may be in an esoteric JavaScript environment that doesn't include the standard APIs. In these cases, use json2.js, the reference implementation of JSON written by Douglas Crockford, the inventor of JSON. That library will provide an implementation of JSON.parse().

When processing extremely large JSON files, JSON.parse() may choke because of its synchronous nature and design. To resolve this, the JSON website recommends third-party libraries such as Oboe.js and clarinet, which provide streaming JSON parsing.

jQuery once had a $.parseJSON() function, but it was deprecated with jQuery 3.0. In any case, for a long time, it was nothing more than a wrapper around JSON.parse().

How to get StackPanel's children to fill maximum space downward?

An alternative method is to use a Grid with one column and n rows. Set all the rows heights to Auto, and the bottom-most row height to 1*.

I prefer this method because I've found Grids have better layout performance than DockPanels, StackPanels, and WrapPanels. But unless you're using them in an ItemTemplate (where the layout is being performed for a large number of items), you'll probably never notice.

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

user334291's answer was a life saver for me. Just want to add how you can add what the OP originally intended to do (what I ended up using):

Overriding the GetWebRequest function on the generated webservice code:

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
    System.Net.WebRequest request = base.GetWebRequest(uri);          
    string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(this.Credentials.GetCredential(uri, "Basic").UserName + ":" + this.Credentials.GetCredential(uri, "Basic").Password));
    request.Headers.Add("Authorization", auth);
    return request;
}

and setting the credentials before calling the webservice:

  client.Credentials = new NetworkCredential(user, password);       

Remove rows with all or some NAs (missing values) in data.frame

Try na.omit(your.data.frame). As for the second question, try posting it as another question (for clarity).

Setting std=c99 flag in GCC

Instead of calling /usr/bin/gcc, use /usr/bin/c99. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc after having added the -std=c99 flag, which is precisely what you want.

What is external linkage and internal linkage?

In terms of 'C' (Because static keyword has different meaning between 'C' & 'C++')

Lets talk about different scope in 'C'

SCOPE: It is basically how long can I see something and how far.

  1. Local variable : Scope is only inside a function. It resides in the STACK area of RAM. Which means that every time a function gets called all the variables that are the part of that function, including function arguments are freshly created and are destroyed once the control goes out of the function. (Because the stack is flushed every time function returns)

  2. Static variable: Scope of this is for a file. It is accessible every where in the file
    in which it is declared. It resides in the DATA segment of RAM. Since this can only be accessed inside a file and hence INTERNAL linkage. Any
    other files cannot see this variable. In fact STATIC keyword is the only way in which we can introduce some level of data or function
    hiding in 'C'

  3. Global variable: Scope of this is for an entire application. It is accessible form every where of the application. Global variables also resides in DATA segment Since it can be accessed every where in the application and hence EXTERNAL Linkage

By default all functions are global. In case, if you need to hide some functions in a file from outside, you can prefix the static keyword to the function. :-)

Avoid line break between html elements

nobr is too unreliable, use tables

<table>
      <tr>
          <td> something </td>
          <td> something </td>
      </tr>
</table>

It all goes on the same line, everything is level with eachother, and you have much more freedom if you want to change something later.

How to get the children of the $(this) selector?

Try this code:

$(this).children()[0]

What is Parse/parsing?

Parsing is just process of analyse the string of character and find the tokens from that string and parser is a component of interpreter and compiler.It uses lexical analysis and then syntactic analysis.It parse it and then compile this code after this whole process of compilation.

Asserting successive calls to a mock method

You can use the Mock.call_args_list attribute to compare parameters to previous method calls. That in conjunction with Mock.call_count attribute should give you full control.

How to transfer data from JSP to servlet when submitting HTML form

first up on create your jsp file : and write the text field which you want
for ex:

after that create your servlet class:

public class test{

protected void doGet(paramter , paramter){

String name  = request.getparameter("name");
 }

}

What is the meaning of Bus: error 10 in C

For one, you can't modify string literals. It's undefined behavior.

To fix that you can make str a local array:

char str[] = "First string";

Now, you will have a second problem, is that str isn't large enough to hold str2. So you will need to increase the length of it. Otherwise, you will overrun str - which is also undefined behavior.

To get around this second problem, you either need to make str at least as long as str2. Or allocate it dynamically:

char *str2 = "Second string";
char *str = malloc(strlen(str2) + 1);  //  Allocate memory
//  Maybe check for NULL.

strcpy(str, str2);

//  Always remember to free it.
free(str);

There are other more elegant ways to do this involving VLAs (in C99) and stack allocation, but I won't go into those as their use is somewhat questionable.


As @SangeethSaravanaraj pointed out in the comments, everyone missed the #import. It should be #include:

#include <stdio.h>
#include <string.h>

C# DateTime.ParseExact

It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

You already specified the culture, so try escaping the slashes.

Select rows where column is null

Use Is Null

select * from tblName where clmnName is null    

Python foreach equivalent

Its also interesting to observe this

To iterate over the indices of a sequence, you can combine range() and len() as follows:

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
  print(i, a[i])

output

0 Mary
1 had
2 a
3 little
4 lamb

Edit#1: Alternate way:

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

for i, v in enumerate(['tic', 'tac', 'toe']):
  print(i, v)

output

0 tic
1 tac
2 toe

PHP: Calling another class' method

File 1

class ClassA {

    public $name = 'A';

    public function getName(){
        return $this->name;
    }

}

File 2

include("file1.php");
class ClassB {

    public $name = 'B';

    public function getName(){
        return $this->name;
    }

    public function callA(){
        $a = new ClassA();
        return $a->getName();
    }

    public static function callAStatic(){
        $a = new ClassA();
        return $a->getName();
    }

}

$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();

Oracle SQL update based on subquery between two tables

Try it ..

UPDATE PRODUCTION a
SET (name, count) = (
SELECT name, count
        FROM STAGING b
        WHERE a.ID = b.ID)
WHERE EXISTS (SELECT 1
    FROM STAGING b
    WHERE a.ID=b.ID
 );

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

i work on a multi platform project, so i can't use _s function and i don't want pollute my code with visual studio specific code.
my solution is disable the warning 4996 on the visual studio project. go to Project -> Properties -> Configuration properties -> C/C++ -> Advanced -> Disable specific warning add the value 4996.
if you use also the mfc and/or atl library (not my case) define before include mfc _AFX_SECURE_NO_DEPRECATE and before include atl _ATL_SECURE_NO_DEPRECATE.
i use this solution across visual studio 2003 and 2005.

p.s. if you use only visual studio the secure template overloads could be a good solution.

How to call VS Code Editor from terminal / command line

On Ubuntu the flatpak version seemed broken. I uninstalled it and downloaded the deb package right from Microsoft.

How do I horizontally center a span element inside a div

Applying inline-block to the element that is to be centered and applying text-align:center to the parent block did the trick for me.

Works even on <span> tags.

How to check if any flags of a flag combination are set?

I use extension methods to write things like that :

if (letter.IsFlagSet(Letter.AB))
    ...

Here's the code :

public static class EnumExtensions
{
    private static void CheckIsEnum<T>(bool withFlags)
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException(string.Format("Type '{0}' is not an enum", typeof(T).FullName));
        if (withFlags && !Attribute.IsDefined(typeof(T), typeof(FlagsAttribute)))
            throw new ArgumentException(string.Format("Type '{0}' doesn't have the 'Flags' attribute", typeof(T).FullName));
    }

    public static bool IsFlagSet<T>(this T value, T flag) where T : struct
    {
        CheckIsEnum<T>(true);
        long lValue = Convert.ToInt64(value);
        long lFlag = Convert.ToInt64(flag);
        return (lValue & lFlag) != 0;
    }

    public static IEnumerable<T> GetFlags<T>(this T value) where T : struct
    {
        CheckIsEnum<T>(true);
        foreach (T flag in Enum.GetValues(typeof(T)).Cast<T>())
        {
            if (value.IsFlagSet(flag))
                yield return flag;
        }
    }

    public static T SetFlags<T>(this T value, T flags, bool on) where T : struct
    {
        CheckIsEnum<T>(true);
        long lValue = Convert.ToInt64(value);
        long lFlag = Convert.ToInt64(flags);
        if (on)
        {
            lValue |= lFlag;
        }
        else
        {
            lValue &= (~lFlag);
        }
        return (T)Enum.ToObject(typeof(T), lValue);
    }

    public static T SetFlags<T>(this T value, T flags) where T : struct
    {
        return value.SetFlags(flags, true);
    }

    public static T ClearFlags<T>(this T value, T flags) where T : struct
    {
        return value.SetFlags(flags, false);
    }

    public static T CombineFlags<T>(this IEnumerable<T> flags) where T : struct
    {
        CheckIsEnum<T>(true);
        long lValue = 0;
        foreach (T flag in flags)
        {
            long lFlag = Convert.ToInt64(flag);
            lValue |= lFlag;
        }
        return (T)Enum.ToObject(typeof(T), lValue);
    }

    public static string GetDescription<T>(this T value) where T : struct
    {
        CheckIsEnum<T>(false);
        string name = Enum.GetName(typeof(T), value);
        if (name != null)
        {
            FieldInfo field = typeof(T).GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
    }
}

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

.loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

JavaFX "Location is required." even though it is in the same package

If your problem is not Maven related and you get the same NullPointerException running this in a browser (while running it from the IDE is fine), try this:

-> Netbeans -> Right-Click Project -> Properties -> Build -> Deployment -> Check "Request unrestricted access (Enable signing, self-signed)"

This is due to the @FXML Annotation needing permission to inject the value from the FXML markup (see http://docs.oracle.com/javafx/2/fxml_get_started/fxml_deployment.htm )

I was running my App on JDK8u31 and it would never run without the certificate in Chrome / Firefox / IE.

How to convert a std::string to const char* or char*?

If you just want to pass a std::string to a function that needs const char* you can use

std::string str;
const char * c = str.c_str();

If you want to get a writable copy, like char *, you can do that with this:

std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0

// don't forget to free the string after finished using it
delete[] writable;

Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.

boost::scoped_array

boost::scoped_array will delete the memory for you upon going out of scope:

std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = '\0'; // don't forget the terminating 0

// get the char* using writable.get()

// memory is automatically freed if the smart pointer goes 
// out of scope

std::vector

This is the standard way (does not require any external library). You use std::vector, which completely manages the memory for you.

std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');

// get the char* using &writable[0] or &*writable.begin()

Release generating .pdb files, why?

.PDB file is the short name of "Program Database". It contains the information about debug point for debugger and resources which are used or reference. Its generated when we build as debug mode. Its allow to application to debug at runtime.

The size is increase of .PDB file in debug mode. It is used when we are testing our application.

Good article of pdb file.

http://www.codeproject.com/Articles/37456/How-To-Inspect-the-Content-of-a-Program-Database-P

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

Here's a solution using a negative lookahead (not supported in all regex engines):

^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$

Test that it works as expected:

import re
tests = [
   ('a', True),
   ('_', False),
   ('zz', True),
   ('a0', True),
   ('A_', False),
   ('a0_b', True),
   ('a__b', False),
   ('a_1_c', True),
]

regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
   is_match = re.match(regex, test[0]) is not None
   if is_match != test[1]:
       print "fail: "  + test[0]

Odd behavior when Java converts int to byte?

byte in Java is signed, so it has a range -2^7 to 2^7-1 - ie, -128 to 127. Since 132 is above 127, you end up wrapping around to 132-256=-124. That is, essentially 256 (2^8) is added or subtracted until it falls into range.

For more information, you may want to read up on two's complement.

make div's height expand with its content

I would just use

height: auto;

in your div. Yes, I know I'm a-little late but I figured this might help somebody like it would have helped me if it was here.

set dropdown value by text using jquery

For GOOGLE, GOOGLEDOWN, GOOGLEUP i.e similar kind of value you can try below code

   $("#HowYouKnow option:contains('GOOGLE')").each(function () {

                        if($(this).html()=='GOOGLE'){
                            $(this).attr('selected', 'selected');
                        }
                    });

In this way,number of loop iteration can be reduced and will work in all situation.