Programs & Examples On #Google search

SEARCH ENGINE OPTIMIZATION(SEO) IS OFF-TOPIC. This tag is only for programming questions about the Google search engine.

What is ' and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.

You can use JavaScript/Canvas to do the job but it is still experimental.

What database does Google use?

And it's maybe also handy to know that BigTable is not a relational database (like MySQL) but a huge (distributed) hash table which has very different characteristics. You can play around with (a limited version) of BigTable yourself on the Google AppEngine platform.

Next to Hadoop mentioned above there are many other implementations that try to solve the same problems as BigTable (scalability, availability). I saw a nice blog post yesterday listing most of them here.

How to find Google's IP address?

Here is a bash script that returns the IP (v4 and v6) ranges using @WorkWise's answer:

domainsToDig=$(dig @8.8.8.8 _spf.google.com TXT +short | \
    sed \
        -e 's/"v=spf1//' \
        -e 's/ ~all"//' \
        -e 's/ include:/\n/g' | \
    tail -n+2)
for domain in $domainsToDig ; do
    dig @8.8.8.8 $domain TXT +short | \
        sed \
            -e 's/"v=spf1//' \
            -e 's/ ~all"//' \
            -e 's/ ip.:/\n/g' | \
        tail -n+2
done

How do search engines deal with AngularJS applications?

Crawlers (or bots) are designed to crawl HTML content of web pages but due to AJAX operations for asynchronous data fetching, this became a problem as it takes sometime to render page and show dynamic content on it. Similarly, AngularJS also use asynchronous model, which creates problem for Google crawlers.

Some developers create basic html pages with real data and serve these pages from server side at the time of crawling. We can render same pages with PhantomJS on serve side which has _escaped_fragment_ (Because Google looks for #! in our site urls and then takes everything after the #! and adds it in _escaped_fragment_ query parameter). For more detail please read this blog .

How can I use a search engine to search for special characters?

Unfortunately, there doesn't appear to be a magic bullet. Bottom line up front: "context".

Google indeed ignores most punctuation, with the following exceptions:

  1. Punctuation in popular terms that have particular meanings, like [ C++ ] or [ C# ] (both are names of programming languages), are not ignored.
  2. The dollar sign ($) is used to indicate prices. [ nikon 400 ] and [ nikon $400 ] will give different results.
  3. The hyphen - is sometimes used as a signal that the two words around it are very strongly connected. (Unless there is no space after the - and a space before it, in which case it is a negative sign.)
  4. The underscore symbol _ is not ignored when it connects two words, e.g. [ quick_sort ].

As such, it is not well suited for these types of searchs. Google Code however does have syntax for searching through their code projects, that includes a robust language/syntax for dealing with "special characters". If looking at someone else's code could help solve a problem, this may be an option.

Unfortunately, this is not a limitation unique to google. You may find that your best successes hinge on providing as much 'context' to the problem as possible. If you are searching to find what $- means, providing information about the problem's domain may yield good results.

For example, searching "special perl variables" quickly yields your answer in the first entry on the results page.

How can I add a Google search box to my website?

Figured it out, folks! for the NAME of the text box, you have to use "q". I had "g" just for my own personal preferences. But apparently it has to be "q".

Anyone know why?

What are the alternatives now that the Google web search API has been deprecated?

Yes, Google Custom Search has now replaced the old Search API, but you can still use Google Custom Search to search the entire web, although the steps are not obvious from the Custom Search setup.

To create a Google Custom Search engine that searches the entire web:

  1. From the Google Custom Search homepage ( http://www.google.com/cse/ ), click Create a Custom Search Engine.
  2. Type a name and description for your search engine.
  3. Under Define your search engine, in the Sites to Search box, enter at least one valid URL (For now, just put www.anyurl.com to get past this screen. More on this later ).
  4. Select the CSE edition you want and accept the Terms of Service, then click Next. Select the layout option you want, and then click Next.
  5. Click any of the links under the Next steps section to navigate to your Control panel.
  6. In the left-hand menu, under Control Panel, click Basics.
  7. In the Search Preferences section, select Search the entire web but emphasize included sites.
  8. Click Save Changes.
  9. In the left-hand menu, under Control Panel, click Sites.
  10. Delete the site you entered during the initial setup process.

Now your custom search engine will search the entire web.

Pricing

  • Google Custom Search gives you 100 queries per day for free.
  • After that you pay $5 per 1000 queries.
  • There is a maximum of 10,000 queries per day.

Source: https://developers.google.com/custom-search/json-api/v1/overview#Pricing


  • The search quality is much lower than normal Google search (no synonyms, "intelligence" etc.)
  • It seems that Google is even planning to shut down this service completely.

MaxLength Attribute not generating client-side validation attributes

Props to @Nick-Harrison for his answer:

$("input[data-val-length-max]").each(function (index, element) {
var length = parseInt($(this).attr("data-val-length-max"));
$(this).prop("maxlength", length);
});

I was wondering what the parseInt() is for there? I've simplified it to this with no problems...

$("input[data-val-length-max]").each(function (index, element) {
    element.setAttribute("maxlength", element.getAttribute("data-val-length-max"))
});

I would have commented on Nicks answer but don't have enough rep yet.

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

A lot of the code here was very helpful, but I cleaned it up for my purposes and added some tests. Here's what I ended up with:

using System;
using System.Linq;
using System.Net;
using System.Web;

public class RequestHelpers
{
    public static string GetClientIpAddress(HttpRequestBase request)
    {
        try
        {
            var userHostAddress = request.UserHostAddress;

            // Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
            // Could use TryParse instead, but I wanted to catch all exceptions
            IPAddress.Parse(userHostAddress);

            var xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(xForwardedFor))
                return userHostAddress;

            // Get a list of public ip addresses in the X_FORWARDED_FOR variable
            var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();

            // If we found any, return the last one, otherwise return the user host address
            return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
        }
        catch (Exception)
        {
            // Always return all zeroes for any failure (my calling code expects it)
            return "0.0.0.0";
        }
    }

    private static bool IsPrivateIpAddress(string ipAddress)
    {
        // http://en.wikipedia.org/wiki/Private_network
        // Private IP Addresses are: 
        //  24-bit block: 10.0.0.0 through 10.255.255.255
        //  20-bit block: 172.16.0.0 through 172.31.255.255
        //  16-bit block: 192.168.0.0 through 192.168.255.255
        //  Link-local addresses: 169.254.0.0 through 169.254.255.255 (http://en.wikipedia.org/wiki/Link-local_address)

        var ip = IPAddress.Parse(ipAddress);
        var octets = ip.GetAddressBytes();

        var is24BitBlock = octets[0] == 10;
        if (is24BitBlock) return true; // Return to prevent further processing

        var is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
        if (is20BitBlock) return true; // Return to prevent further processing

        var is16BitBlock = octets[0] == 192 && octets[1] == 168;
        if (is16BitBlock) return true; // Return to prevent further processing

        var isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
        return isLinkLocalAddress;
    }
}

And here are some NUnit tests against that code (I'm using Rhino Mocks to mock the HttpRequestBase, which is the M<HttpRequestBase> call below):

using System.Web;
using NUnit.Framework;
using Rhino.Mocks;
using Should;

[TestFixture]
public class HelpersTests : TestBase
{
    HttpRequestBase _httpRequest;

    private const string XForwardedFor = "X_FORWARDED_FOR";
    private const string MalformedIpAddress = "MALFORMED";
    private const string DefaultIpAddress = "0.0.0.0";
    private const string GoogleIpAddress = "74.125.224.224";
    private const string MicrosoftIpAddress = "65.55.58.201";
    private const string Private24Bit = "10.0.0.0";
    private const string Private20Bit = "172.16.0.0";
    private const string Private16Bit = "192.168.0.0";
    private const string PrivateLinkLocal = "169.254.0.0";

    [SetUp]
    public void Setup()
    {
        _httpRequest = M<HttpRequestBase>();
    }

    [TearDown]
    public void Teardown()
    {
        _httpRequest = null;
    }

    [Test]
    public void PublicIpAndNullXForwardedFor_Returns_CorrectIp()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void PublicIpAndEmptyXForwardedFor_Returns_CorrectIp()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(string.Empty);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void MalformedUserHostAddress_Returns_DefaultIpAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(MalformedIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(DefaultIpAddress);
    }

    [Test]
    public void MalformedXForwardedFor_Returns_DefaultIpAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MalformedIpAddress);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(DefaultIpAddress);
    }

    [Test]
    public void SingleValidPublicXForwardedFor_Returns_XForwardedFor()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MicrosoftIpAddress);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(MicrosoftIpAddress);
    }

    [Test]
    public void MultipleValidPublicXForwardedFor_Returns_LastXForwardedFor()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(GoogleIpAddress + "," + MicrosoftIpAddress);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(MicrosoftIpAddress);
    }

    [Test]
    public void SinglePrivateXForwardedFor_Returns_UserHostAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(Private24Bit);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void MultiplePrivateXForwardedFor_Returns_UserHostAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        const string privateIpList = Private24Bit + "," + Private20Bit + "," + Private16Bit + "," + PrivateLinkLocal;
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void MultiplePublicXForwardedForWithPrivateLast_Returns_LastPublic()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        const string privateIpList = Private24Bit + "," + Private20Bit + "," + MicrosoftIpAddress + "," + PrivateLinkLocal;
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(MicrosoftIpAddress);
    }
}

C# elegant way to check if a property's property is null

When I need to chain calls like that, I rely on a helper method I created, TryGet():

    public static U TryGet<T, U>(this T obj, Func<T, U> func)
    {
        return obj.TryGet(func, default(U));
    }

    public static U TryGet<T, U>(this T obj, Func<T, U> func, U whenNull)
    {
        return obj == null ? whenNull : func(obj);
    }

In your case, you would use it like so:

    int value = ObjectA
        .TryGet(p => p.PropertyA)
        .TryGet(p => p.PropertyB)
        .TryGet(p => p.PropertyC, defaultVal);

C++ Singleton design pattern

#define INS(c) private:void operator=(c const&){};public:static c& I(){static c _instance;return _instance;}

Example:

   class CCtrl
    {
    private:
        CCtrl(void);
        virtual ~CCtrl(void);

    public:
        INS(CCtrl);

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Now there is official FAQ for using Google Play in How do I install Google Play Services?, here the FAQ text:

For intellectual property reasons, Google Play Services are not included by default in Genymotion virtual devices. However, if you really need them, you can use the packages provided by OpenGapps. Simply follow these steps:

  1. Visit opengapps.org
  2. Select x86 as platform
  3. Choose the Android version corresponding to your virtual device
  4. Select nano as variant
  5. Download the zip file
  6. Drag & Drop the zip installer in new Genymotion virtual device (2.7.2 and above only)
  7. Follow the pop-up instructions

Please note Genymobile Inc. and Genymotion assume no liability whatsoever resulting from the download, install and use of Google Play Services within your virtual devices. You are solely responsible for the use and assume all liability related thereto. Moreover, we disclaim any warranties of any kind for a particular purpose regarding the compatibility of the OpenGapps packages with any version of Genymotion.

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

I had a similar issue some time ago. You must be careful with quotes and double quotes. It's recommended to reset the user password, using a admin credentials.

ALTER USER user_name IDENTIFIED BY new_password;

But don't use double quotes in both parameters.

How to write to an existing excel file without overwriting data (using pandas)?

Solution by @MaxU worked very well. I have just one suggestion:

If truncate_sheet=True is specified than "startrow" should NOT be retained from existing sheet. I suggest:

        if startrow is None and sheet_name in writer.book.sheetnames:
            if not truncate_sheet: # truncate_sheet would use startrow if provided (or zero below)
                startrow = writer.book[sheet_name].max_row

Append an empty row in dataframe using pandas

Append "empty" row to data frame and fill selected cells:

Generate empty data frame (no rows just columns a and b):

import pandas as pd    
col_names =  ["a","b"]
df  = pd.DataFrame(columns = col_names)

Append empty row at the end of the data frame:

df = df.append(pd.Series(), ignore_index = True)

Now fill the empty cell at the end (len(df)-1) of the data frame in column a:

df.loc[[len(df)-1],'a'] = 123

Result:

     a    b
0  123  NaN

And of course one can iterate over the rows and fill cells:

col_names =  ["a","b"]
df  = pd.DataFrame(columns = col_names)
for x in range(0,5):
    df = df.append(pd.Series(), ignore_index = True)
    df.loc[[len(df)-1],'a'] = 123

Result:

     a    b
0  123  NaN
1  123  NaN
2  123  NaN
3  123  NaN
4  123  NaN

Cursor adapter and sqlite example

CursorAdapter Example with Sqlite

...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...

class CustomAdapter extends CursorAdapter {
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    public void bindView(View view, Context context, Cursor cursor) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        // Get all the values
        // Use it however you need to
        TextView textView = (TextView) view;
        textView.setText(name);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
        TextView view = new TextView(context);
        return view;
    }
}

private final class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "db_name";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TIMELINE);
        db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public Cursor getAllContacts() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }
}

Best TCP port number range for internal applications

I decided to download the assigned port numbers from IANA, filter out the used ports, and sort each "Unassigned" range in order of most ports available, descending. This did not work, since the csv file has ranges marked as "Unassigned" that overlap other port number reservations. I manually expanded the ranges of assigned port numbers, leaving me with a list of all assigned port numbers. I then sorted that list and generated my own list of unassigned ranges.

Since this stackoverflow.com page ranked very high in my search about the topic, I figured I'd post the largest ranges here for anyone else who is interested. These are for both TCP and UDP where the number of ports in the range is at least 500.

Total   Start   End
829     29170   29998
815     38866   39680
710     41798   42507
681     43442   44122
661     46337   46997
643     35358   36000
609     36866   37474
596     38204   38799
592     33657   34248
571     30261   30831
563     41231   41793
542     21011   21552
528     28590   29117
521     14415   14935
510     26490   26999

Source (via the CSV download button):

http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml

How to use 'find' to search for files created on a specific date?

You could do this:

find ./ -type f -ls |grep '10 Sep'

Example:

[root@pbx etc]# find /var/ -type f -ls | grep "Dec 24"
791235    4 -rw-r--r--   1 root     root           29 Dec 24 03:24 /var/lib/prelink/full
798227  288 -rw-r--r--   1 root     root       292323 Dec 24 23:53 /var/log/sa/sar24
797244  320 -rw-r--r--   1 root     root       321300 Dec 24 23:50 /var/log/sa/sa24

Use multiple css stylesheets in the same html page

You can't. The last stylesheet you specify will be the one html page will use. Think of it as a big single .css document.

header location not working in my php code

The function ob_start() will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. So browser will not receive any output and the header will work.Also we should make sure that header() is used on the top of the code.

source command not found in sh shell

The source command is built into some shells. If you have a script, it should specify what shell to use on the first line, such as:

#!/bin/bash

Make $JAVA_HOME easily changable in Ubuntu

Put the environment variables into the global /etc/environment file:

...
export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun
...

Execute "source /etc/environment" in every shell where you want the variables to be updated:

$ source /etc/environment

Check that it works:

$ echo $JAVA_HOME
$ /usr/lib/jvm/java-1.5.0-sun

Great, no logout needed.

If you want to set JAVA_HOME environment variable in only the terminal, set it in ~/.bashrc file.

How do I merge my local uncommitted changes into another Git branch?

If it were about committed changes, you should have a look at git-rebase, but as pointed out in comment by VonC, as you're talking about local changes, git-stash would certainly be the good way to do this.

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I removed my .classpath file in my project directory to correct this issue. No need to remove the Maven Nature from the project in Eclipse.

The specific error I was getting was: Project 'my-project-name' is missing required Java project: 'org.some.package-9.3.0 But my project wasn't dependent on org.some.package in any way.

Perhaps an old version of the project relied on it and Maven wasn't properly updating the .classpath file.

Updating a dataframe column in spark

While you cannot modify a column as such, you may operate on a column and return a new DataFrame reflecting that change. For that you'd first create a UserDefinedFunction implementing the operation to apply and then selectively apply that function to the targeted column only. In Python:

from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import StringType

name = 'target_column'
udf = UserDefinedFunction(lambda x: 'new_value', StringType())
new_df = old_df.select(*[udf(column).alias(name) if column == name else column for column in old_df.columns])

new_df now has the same schema as old_df (assuming that old_df.target_column was of type StringType as well) but all values in column target_column will be new_value.

Align div with fixed position on the right side

With position fixed, you need to provide values to set where the div will be placed, since it's a fixed position.

Something like....

.test
{
   position:fixed;
   left:100px;
   top:150px;
}

Fixed - Generates an absolutely positioned element, positioned relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties

More on position here.

How can I create objects while adding them into a vector?

// create a vector of unknown players.
std::vector<player> players;

// resize said vector to only contain 6 players.
players.resize(6);

Values are always initialized, so a vector of 6 players is a vector of 6 valid player objects.

As for the second part, you need to use pointers. Instantiating c++ interface as a child class

How to set min-font-size in CSS

It will work perfectly with 50px. Which will act as a static and thus as min-width.

font-size: calc(50px + 5vw);

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

I had this problem as well and only really started to hone in on the root cause after opening up the browser's web console. Until that, I was unable to get any error messages (even with <p:messages>). The web console showed an HTTP 405 status code coming back from the <h:commandButton type="submit" action="#{myBean.submit}">.

In my case, I have a mix of vanilla HttpServlet's providing OAuth authentication via Auth0 and JSF facelets and beans carrying out my application views and business logic.

Once I refactored my web.xml, and removed a middle-man-servlet, it then "magically" worked.

Bottom line, the problem was that the middle-man-servlet was using RequestDispatcher.forward(...) to redirect from the HttpServlet environment to the JSF environment whereas the servlet being called prior to it was redirecting with HttpServletResponse.sendRedirect(...).

Basically, using sendRedirect() allowed the JSF "container" to take control whereas RequestDispatcher.forward() was obviously not.

What I don't know is why the facelet was able to access the bean properties but could not set them, and this clearly screams for doing away with the mix of servlets and JSF, but I hope this helps someone avoid many hours of head-to-table-banging.

label or @html.Label ASP.net MVC 4

When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance

  • When dealing with hyperlinks, since the HTML helper simplifies routing
  • When you bind to your model, using @Html.LabelFor, @Html.TextBoxFor, etc
  • When you use the @Html.EditorFor, as you can assign specific behavior och looks in a editor view

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

    String str1,str2;
    Scanner S=new Scanner(System.in);
    str1=S.nextLine();
    System.out.println(str1);
    str2=S.nextLine();
    str1=str1.concat(str2);
    System.out.println(str1.toLowerCase()); 

Call fragment from fragment

If you want to replace the entire Fragment1 with Fragment2, you need to do it inside MainActivity, by using:

Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment2);
fragmentTransaction.commit();

Just put this code inside a method in MainActivity, then call that method from Fragment1.

Pandas/Python: Set value of one column based on value in another column

try:

df['c2'] = df['c1'].apply(lambda x: 10 if x == 'Value' else x)

Reading PDF documents in .Net

PDFClown might help, but I would not recommend it for a big or heavy use application.

Skipping every other element after the first

def skip_elements(elements):
  new_list = []
  for index,element in enumerate(elements):
    if index == 0:
      new_list.append(element)
    elif (index % 2) == 0: 
      new_list.append(element)
  return new_list

Also can use for loop + enumerate. elif (index % 2) == 0: ## Checking if number is even, not odd cause indexing starts from zero not 1.

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

CSS display:inline property with list-style-image: property on <li> tags

I would suggest not to use list-style-image, as it behaves quite differently in different browsers, especially the image position

instead, you can use something like this

ol.widgets,
ol.widgets li { list-style: none; }
ol.widgets li { padding-left: 20px; backgroud: transparent ("image") no-repeat x y; }

it works in all browsers and would give you the identical result in different browsers.

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

I was able to overcome this issue with the following Visual Studio 2017 change:

  1. In Team Explorer, go to Settings. Go to Global Settings to configure this option at the global level; go to Repository Settings to configure this option at the repo level.
  2. Set Rebase local branch when pulling to the desired setting (for me it was True), and select Update to save.

See: https://docs.microsoft.com/en-us/vsts/git/concepts/git-config?view=vsts&tabs=visual-studio#rebase-local-branch-when-pulling

Which websocket library to use with Node.js?

npm ws was the answer for me. I found it less intrusive and more straight forward. With it was also trivial to mix websockets with rest services. Shared simple code on this post.

var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var port = process.env.PORT || 5000;

var app = express();
    app.use(express.static(__dirname+ "/../"));
    app.get('/someGetRequest', function(req, res, next) {
       console.log('receiving get request');
    });
    app.post('/somePostRequest', function(req, res, next) {
       console.log('receiving post request');
    });
    app.listen(80); //port 80 need to run as root

    console.log("app listening on %d ", 80);

var server = http.createServer(app);
    server.listen(port);

console.log("http server listening on %d", port);

var userId;
var wss = new WebSocketServer({server: server});
    wss.on("connection", function (ws) {

    console.info("websocket connection open");

    var timestamp = new Date().getTime();
    userId = timestamp;

    ws.send(JSON.stringify({msgType:"onOpenConnection", msg:{connectionId:timestamp}}));


    ws.on("message", function (data, flags) {
        console.log("websocket received a message");
        var clientMsg = data;

        ws.send(JSON.stringify({msg:{connectionId:userId}}));


    });

    ws.on("close", function () {
        console.log("websocket connection close");
    });
});
console.log("websocket server created");

XCOPY switch to create specified directory if it doesn't exist?

I tried this on the command line using

D:\>xcopy myfile.dat xcopytest\test\

and the target directory was properly created.

If not you can create the target dir using the mkdir command with cmd's command extensions enabled like

cmd /x /c mkdir "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\"

('/x' enables command extensions in case they're not enabled by default on your system, I'm not that familiar with cmd)

use

cmd /? 
mkdir /?
xcopy /?

for further information :)

How to copy file from host to container using Dockerfile

I faced this issue, I was not able to copy zeppelin [1GB] directory into docker container and was getting issue

COPY failed: stat /var/lib/docker/tmp/docker-builder977188321/zeppelin-0.7.2-bin-all: no such file or directory

I am using docker Version: 17.09.0-ce and resolved the issue with the following steps.

Step 1: copy zeppelin directory [which i want to copy into docker package]into directory contain "Dockfile"

Step 2: edit Dockfile and add command [location where we want to copy] ADD ./zeppelin-0.7.2-bin-all /usr/local/

Step 3: go to directory which contain DockFile and run command [alternatives also available] docker build

Step 4: docker image created Successfully with logs

Step 5/9 : ADD ./zeppelin-0.7.2-bin-all /usr/local/ ---> 3691c902d9fe

Step 6/9 : WORKDIR $ZEPPELIN_HOME ---> 3adacfb024d8 .... Successfully built b67b9ea09f02

How to unpack and pack pkg file?

Packages are just .xar archives with a different extension and a specified file hierarchy. Unfortunately, part of that file hierarchy is a cpio.gz archive of the actual installables, and usually that's what you want to edit. And there's also a Bom file that includes information on the files inside that cpio archive, and a PackageInfo file that includes summary information.

If you really do just need to edit one of the info files, that's simple:

mkdir Foo
cd Foo
xar -xf ../Foo.pkg
# edit stuff
xar -cf ../Foo-new.pkg *

But if you need to edit the installable files:

mkdir Foo
cd Foo
xar -xf ../Foo.pkg
cd foo.pkg
cat Payload | gunzip -dc |cpio -i
# edit Foo.app/*
rm Payload
find ./Foo.app | cpio -o | gzip -c > Payload
mkbom Foo.app Bom # or edit Bom
# edit PackageInfo
rm -rf Foo.app
cd ..
xar -cf ../Foo-new.pkg

I believe you can get mkbom (and lsbom) for most linux distros. (If you can get ditto, that makes things even easier, but I'm not sure if that's nearly as ubiquitously available.)

unsigned int vs. size_t

Classic C (the early dialect of C described by Brian Kernighan and Dennis Ritchie in The C Programming Language, Prentice-Hall, 1978) didn't provide size_t. The C standards committee introduced size_t to eliminate a portability problem

Explained in detail at embedded.com (with a very good example)

Create a CSV File for a user in PHP

Simple method -

$data = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"');

$fp = fopen('data.csv', 'wb');
foreach($data as $line){
    $val = explode(",",$line);
    fputcsv($fp, $val);
}
fclose($fp);

So each line of the $data array will go to a new line of your newly created CSV file. It only works only for PHP 5 and later.

How to group subarrays by a column value?

$arr = Data Araay;

$fldName = Group By Colum Name;

function array_group_by( $arr, $fldName) {
    $groups = array();
    foreach ($arr as $rec) {
        $groups[$rec[$fldName]] = $rec;
    }
    return $groups;
}

function object_group_by( $obj, $fldName) {
    $groups = array();
    foreach ($obj as $rec) {
        $groups[$rec->$fldName] = $rec;
    }
    return $groups;
}

Getting URL parameter in java and extract a specific text from that URL

this will work for all sort of youtube url :
if url could be

youtube.com/?v=_RCIP6OrQrE
youtube.com/v/_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE&feature=whatever&this=that

Pattern p = Pattern.compile("http.*\\?v=([a-zA-Z0-9_\\-]+)(?:&.)*");
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
Matcher m = p.matcher(url.trim()); //trim to remove leading and trailing space if any

if (m.matches()) {
    url = m.group(1);        
}
System.out.println(url);

this will extract video id from your url

further reference

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

Return list from async/await method

You need to correct your code to wait for the list to be downloaded:

List<Item> list = await GetListAsync();

Also, make sure that the method, where this code is located, has async modifier.

The reason why you get this error is that GetListAsync method returns a Task<T> which is not a completed result. As your list is downloaded asynchronously (because of Task.Run()) you need to "extract" the value from the task using the await keyword.

If you remove Task.Run(), you list will be downloaded synchronously and you don't need to use Task, async or await.

One more suggestion: you don't need to await in GetListAsync method if the only thing you do is just delegating the operation to a different thread, so you can shorten your code to the following:

private Task<List<Item>> GetListAsync(){
    return Task.Run(() => manager.GetList());
}

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

CLI commands for github API v3 (replace all CAPS keywords):

curl -u 'USER' https://api.github.com/user/repos -d '{"name":"REPO"}'
# Remember replace USER with your username and REPO with your repository/application name!
git remote add origin [email protected]:USER/REPO.git
git push origin master

How do I measure separate CPU core usage for a process?

I thought perf stat is what you need.

It shows a specific usage of a process when you specify a --cpu=list option. Here is an example of monitoring cpu usage of building a project using perf stat --cpu=0-7 --no-aggr -- make all -j command. The output is:

CPU0         119254.719293 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU1         119254.724776 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU2         119254.724179 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU3         119254.720833 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU4         119254.714109 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU5         119254.727721 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU6         119254.723447 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU7         119254.722418 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU0                 8,108 context-switches          #    0.068 K/sec                    (100.00%)
CPU1                26,494 context-switches                                              (100.00%)
CPU2                10,193 context-switches                                              (100.00%)
CPU3                12,298 context-switches                                              (100.00%)
CPU4                16,179 context-switches                                              (100.00%)
CPU5                57,389 context-switches                                              (100.00%)
CPU6                 8,485 context-switches                                              (100.00%)
CPU7                10,845 context-switches                                              (100.00%)
CPU0                   167 cpu-migrations            #    0.001 K/sec                    (100.00%)
CPU1                    80 cpu-migrations                                                (100.00%)
CPU2                   165 cpu-migrations                                                (100.00%)
CPU3                   139 cpu-migrations                                                (100.00%)
CPU4                   136 cpu-migrations                                                (100.00%)
CPU5                   175 cpu-migrations                                                (100.00%)
CPU6                   256 cpu-migrations                                                (100.00%)
CPU7                   195 cpu-migrations                                                (100.00%)

The left column is the specific CPU index and the right most column is the usage of the CPU. If you don't specify the --no-aggr option, the result will aggregated together. The --pid=pid option will help if you want to monitor a running process.

Try -a --per-core or -a perf-socket too, which will present more classified information.

More about usage of perf stat can be seen in this tutorial: perf cpu statistic, also perf help stat will help on the meaning of the options.

SSRS - Checking whether the data is null

try like this

= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "",  FormatNumber(  MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )

How to create EditText with rounded corners?

Thanks for Norfeldt's answer. I slightly changed its gradient for a better inner shadow effect.

<item android:state_pressed="false" android:state_focused="false">
    <shape>
        <gradient
            android:centerY="0.2"
            android:startColor="#D3D3D3"
            android:centerColor="#65FFFFFF"
            android:endColor="#00FFFFFF"
            android:angle="270"
            />
        <stroke
            android:width="0.7dp"
            android:color="#BDBDBD" />
        <corners
            android:radius="15dp" />
    </shape>
</item>

Looks great in a light backgrounded layout..

enter image description here

Accessing an array out of bounds gives no error, why?

As mentioned now in the question using std::vector::at will solve the problem and make a bound check before accessing.

If you need a constant size array that is located on the stack as your first code use the C++11 new container std::array; as vector there is std::array::at function. In fact the function exists in all standard containers in which it have a meaning,i.e, where operator[] is defined :( deque, map, unordered_map) with the exception of std::bitset in which it is called std::bitset::test.

Clicking URLs opens default browser

If you're using a WebView you'll have to intercept the clicks yourself if you don't want the default Android behaviour.

You can monitor events in a WebView using a WebViewClient. The method you want is shouldOverrideUrlLoading(). This allows you to perform your own action when a particular URL is selected.

You set the WebViewClient of your WebView using the setWebViewClient() method.

If you look at the WebView sample in the SDK there's an example which does just what you want. It's as simple as:

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

Check that the directory the keytool executable is in is on your %PATH% environment variable.

For example, on my Windows 7 machine, it is in C:\Program Files (x86)\Java\jre6\bin, and my %PATH% variable looks like C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Java\jre6\bin;C:\WINDOWS\System32\WindowsPowerShell\v1.0\ (and many other entries)

Switching between GCC and Clang/LLVM using CMake

If the default compiler chosen by cmake is gcc and you have installed clang, you can use the easy way to compile your project with clang:

$ mkdir build && cd build
$ CXX=clang++ CC=clang cmake ..
$ make -j2

Check if a specific tab page is selected (active)

in .Net 4 can use

if (tabControl1.Controls[5] == tabControl1.SelectedTab)
                MessageBox.Show("Tab 5 Is Selected");

OR

if ( tabpage5 == tabControl1.SelectedTab)
         MessageBox.Show("Tab 5 Is Selected");

How to pick an image from gallery (SD Card) for my app?

Do this to launch the gallery and allow the user to pick an image:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK);

Then in your onActivityResult() use the URI of the image that is returned to set the image on your ImageView.

In C#, why is String a reference type that behaves like a value type?

Also, the way strings are implemented (different for each platform) and when you start stitching them together. Like using a StringBuilder. It allocats a buffer for you to copy into, once you reach the end, it allocates even more memory for you, in the hopes that if you do a large concatenation performance won't be hindered.

Maybe Jon Skeet can help up out here?

Use Excel pivot table as data source for another Pivot Table

You have to convert the pivot to values first before you can do that:

  • Remove the subtotals
  • Repeat the row items
  • Copy / Paste values
  • Insert a new pivot table

android pinch zoom

I have created a project for basic pinch-zoom that supports Android 2.1+

Available here

Setting Custom ActionBar Title from Fragment

Setting Activity’s title from a Fragment messes up responsibility levels. Fragment is contained within an Activity, so this is the Activity, which should set its own title according to the type of the Fragment for example.

Suppose you have an interface:

interface TopLevelFragment
{
    String getTitle();
}

The Fragments which can influence the Activity’s title then implement this interface. While in the hosting activity you write:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager fm = getFragmentManager();
    fm.beginTransaction().add(0, new LoginFragment(), "login").commit();
}

@Override
public void onAttachFragment(Fragment fragment)
{
    super.onAttachFragment(fragment);

    if (fragment instanceof TopLevelFragment)
        setTitle(((TopLevelFragment) fragment).getTitle());
}

In this manner Activity is always in control what title to use, even if several TopLevelFragments are combined, which is quite possible on a tablet.

Daemon Threads Explanation

A simpler way to think about it, perhaps: when main returns, your process will not exit if there are non-daemon threads still running.

A bit of advice: Clean shutdown is easy to get wrong when threads and synchronization are involved - if you can avoid it, do so. Use daemon threads whenever possible.

What is the difference between user and kernel modes in operating systems?

Other answers already explained the difference between user and kernel mode. If you really want to get into detail you should get a copy of Windows Internals, an excellent book written by Mark Russinovich and David Solomon describing the architecture and inside details of the various Windows operating systems.

Breaking up long strings on multiple lines in Ruby without stripping newlines

I modified Zack's answer since I wanted spaces and interpolation but not newlines and used:

%W[
  It's a nice day "#{name}"
  for a walk!
].join(' ')

where name = 'fred' this produces It's a nice day "fred" for a walk!

ASP.NET page life cycle explanation

There are 10 events in ASP.NET page life cycle, and the sequence is:

  1. Init
  2. Load view state
  3. Post back data
  4. Load
  5. Validate
  6. Events
  7. Pre-render
  8. Save view state
  9. Render
  10. Unload

Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.

ASP.NET life cycle

Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010

What does '?' do in C++?

Just a note, if you ever see this:

a = x ? : y;

It's a GNU extension to the standard (see https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html#Conditionals).

It is the same as

a = x ? x : y;

"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

Try putting it in quotes -- you're running into the shell's wildcard expansion, so what you're acually passing to find will look like:

find . -name bobtest.c cattest.c snowtest.c

...causing the syntax error. So try this instead:

find . -name '*test.c'

Note the single quotes around your file expression -- these will stop the shell (bash) expanding your wildcards.

How to format current time using a yyyyMMddHHmmss format?

Time package in Golang has some methods that might be worth looking.

func (Time) Format

func (t Time) Format(layout string) string Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,

Mon Jan 2 15:04:05 -0700 MST 2006 would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.

Source (http://golang.org/pkg/time/#Time.Format)

I also found an example of defining the layout (http://golang.org/src/pkg/time/example_test.go)

func ExampleTime_Format() {
        // layout shows by example how the reference time should be represented.
        const layout = "Jan 2, 2006 at 3:04pm (MST)"
        t := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.Local)
        fmt.Println(t.Format(layout))
        fmt.Println(t.UTC().Format(layout))
        // Output:
    // Nov 10, 2009 at 3:00pm (PST)
        // Nov 10, 2009 at 11:00pm (UTC)
    }

How to insert current_timestamp into Postgres via python

If you use psycopg2 (and possibly some other client library), you can simply pass a Python datetime object as a parameter to a SQL-query:

from datetime import datetime, timezone

dt = datetime.now(timezone.utc)
cur.execute('INSERT INTO mytable (mycol) VALUES (%s)', (dt,))

(This assumes that the timestamp with time zone type is used on the database side.)

More Python types that can be adapted into SQL (and returned as Python objects when a query is executed) are listed here.

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

You can create a setTimeout loop using recursion:

function timeout() {
    setTimeout(function () {
        // Do Something Here
        // Then recall the parent function to
        // create a recursive loop.
        timeout();
    }, 1000);
}

The problem with setInterval() and setTimeout() is that there is no guarantee your code will run in the specified time. By using setTimeout() and calling it recursively, you're ensuring that all previous operations inside the timeout are complete before the next iteration of the code begins.

Get random sample from list while maintaining ordering of items?

Following code will generate a random sample of size 4:

import random

sample_size = 4
sorted_sample = [
    mylist[i] for i in sorted(random.sample(range(len(mylist)), sample_size))
]

(note: with Python 2, better use xrange instead of range)

Explanation

random.sample(range(len(mylist)), sample_size)

generates a random sample of the indices of the original list.

These indices then get sorted to preserve the ordering of elements in the original list.

Finally, the list comprehension pulls out the actual elements from the original list, given the sampled indices.

JQuery $.ajax() post - data in a java servlet

To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

Splitting comma separated string in a PL/SQL stored proc

I use apex_util.string_to_table to parse strings, but you can use a different parser if you wish. Then you can insert the data as in this example:

declare
  myString varchar2(2000) :='0.75, 0.64, 0.56, 0.45';
  myAmount varchar2(2000) :='0.25, 0.5, 0.65, 0.8';
  v_array1 apex_application_global.vc_arr2;
  v_array2 apex_application_global.vc_arr2;
begin

  v_array1 := apex_util.string_to_table(myString, ', ');
  v_array2 := apex_util.string_to_table(myAmount, ', ');

  forall i in 1..v_array1.count
     insert into mytable (a, b) values (v_array1(i), v_array2(i));
end;

Apex_util is available from Oracle 10G onwards. Prior to this it was called htmldb_util and was not installed by default. If you can't use that you could use the string parser I wrote many years ago and posted here.

Formatting a double to two decimal places

Since you are working in currency why not simply do this:

Console.Writeline("Earnings this week: {0:c}", answer);

This will format answer as currency, so on my machine (UK) it will come out as:

Earnings this week: £209.00

How to change font of UIButton with Swift

You don't need to force unwrap the titleLabel to set it.

myButton.titleLabel?.font = UIFont(name: YourfontName, size: 20)

Since you're not using the titleLabel here, you can just optionally use it and if it's nil it will just be a no-op.

I'll also add as other people are saying, the font property is deprecated, and make sure to use setTitle:forControlState: when setting the title text.

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

How do I parse a YAML file in Ruby?

I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

This is the best solution I have found:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])
end

Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files

window.onunload is not working properly in Chrome browser. Can any one help me?

This works :

var unloadEvent = function (e) {
    var confirmationMessage = "Warning: Leaving this page will result in any unsaved data being lost. Are you sure you wish to continue?";
    (e || window.event).returnValue = confirmationMessage; //Gecko + IE
    return confirmationMessage; //Webkit, Safari, Chrome etc.
};
window.addEventListener("beforeunload", unloadEvent);

Checking if a list is empty with LINQ

Ok, so what about this one?

public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
    return !enumerable.GetEnumerator().MoveNext();
}

EDIT: I've just realized that someone has sketched this solution already. It was mentioned that the Any() method will do this, but why not do it yourself? Regards

How to display a Windows Form in full screen on top of the taskbar?

A tested and simple solution

I've been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn't work correctly, so after a lot code testing I solved this puzzle.

Note: I'm using Windows 8 and my taskbar isn't on auto-hide mode.

I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.

The code

I created this class that have two methods, the first enters in the "full screen mode" and the second leaves the "full screen mode". So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Usage example

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

I have placed this same answer on another question that I'm not sure if is a duplicate or not of this one. (Link to the other question: How do I make a WinForms app go Full Screen)

How to locate the git config file in Mac

You don't need to find the file.

Only write this instruction on terminal:

git config --global --edit

Create JSON object dynamically via JavaScript (Without concate strings)

Perhaps this information will help you.

_x000D_
_x000D_
var sitePersonel = {};_x000D_
var employees = []_x000D_
sitePersonel.employees = employees;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var firstName = "John";_x000D_
var lastName = "Smith";_x000D_
var employee = {_x000D_
  "firstName": firstName,_x000D_
  "lastName": lastName_x000D_
}_x000D_
sitePersonel.employees.push(employee);_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var manager = "Jane Doe";_x000D_
sitePersonel.employees[0].manager = manager;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
console.log(JSON.stringify(sitePersonel));
_x000D_
_x000D_
_x000D_

Regular expression \p{L} and \p{N}

These are Unicode property shortcuts (\p{L} for Unicode letters, \p{N} for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)

At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:

[\p{L}\p{N}_.-]*

How do I create an executable in Visual Studio 2013 w/ C++?

  1. Click BUILD > Configuration Manager...
  2. Under Project contexts > Configuration, select "Release"
  3. BUILD > Build Solution or Rebuild Solution

How to view instagram profile picture in full-size?

You can even set the prof. pic size to its high resolution that is '1080x1080'

replace "150x150" with 1080x1080 and remove /vp/ from the link.

Column calculated from another column?

I hope this still helps someone as many people might get to this article. If you need a computed column, why not just expose your desired columns in a view ? Don't just save data or overload the performance with triggers... simply expose the data you need already formatted/calculated in a view.

Hope this helps...

Convert xlsx file to csv using batch

To follow up on the answer by user183038, here is a shell script to batch rename all xlsx files to csv while preserving the file names. The xlsx2csv tool needs to be installed prior to running.

for i in *.xlsx;
 do
  filename=$(basename "$i" .xlsx);
  outext=".csv" 
  xlsx2csv $i $filename$outext
done

How to get current foreground activity context in android?

I don't like any of the other answers. The ActivityManager is not meant to be used for getting the current activity. Super classing and depending on onDestroy is also fragile and not the best design.

Honestly, the best I have came up with so far is just maintaining an enum in my Application, which gets set when an activity is created.

Another recommendation might be to just shy away from using multiple activities if possible. This can be done either with using fragments, or in my preference custom views.

Allow all remote connections, MySQL

As pointed out by Ryan above, the command you need is

GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password'; 

However, note that the documentation indicates that in order for this to work, another user account from localhost must be created for the same user; otherwise, the anonymous account created automatically by mysql_install_db takes precedence because it has a more specific host column.

In other words; in order for user user to be able to connect from any server; 2 accounts need to be created as follows:

GRANT ALL ON *.* to user@localhost IDENTIFIED BY 'password'; 
GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password'; 

Read the full documentation here.

And here's the relevant piece for reference:

After connecting to the server as root, you can add new accounts. The following statements use GRANT to set up four new accounts:

mysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'admin'@'localhost';
mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
mysql> CREATE USER 'dummy'@'localhost';

The accounts created by these statements have the following properties:

Two of the accounts have a user name of monty and a password of some_pass. Both accounts are superuser accounts with full privileges to do anything. The 'monty'@'localhost' account can be used only when connecting from the local host. The 'monty'@'%' account uses the '%' wildcard for the host part, so it can be used to connect from any host.

It is necessary to have both accounts for monty to be able to connect from anywhere as monty. Without the localhost account, the anonymous-user account for localhost that is created by mysql_install_db would take precedence when monty connects from the local host. As a result, monty would be treated as an anonymous user. The reason for this is that the anonymous-user account has a more specific Host column value than the 'monty'@'%' account and thus comes earlier in the user table sort order. (user table sorting is discussed in Section 6.2.4, “Access Control, Stage 1: Connection Verification”.)

How to listen to route changes in react router v4?

withRouter, history.listen, and useEffect (React Hooks) works quite nicely together:

import React, { useEffect } from 'react'
import { withRouter } from 'react-router-dom'

const Component = ({ history }) => {
    useEffect(() => history.listen(() => {
        // do something on route change
        // for my example, close a drawer
    }), [])

    //...
}

export default withRouter(Component)

The listener callback will fire any time a route is changed, and the return for history.listen is a shutdown handler that plays nicely with useEffect.

$(form).ajaxSubmit is not a function

this is new function so you have to add other lib file after jQuery lib

<script src="http://malsup.github.com/jquery.form.js"></script>

it will work.. I have tested.. hope it will work for you..

How to use OpenSSL to encrypt/decrypt files?

Additional comments to mti2935 good answer.

It seems the higher iteration the better protection against brute force, and you should use a high iteration as you can afford performance/resource wise.

On my my old Intel i3-7100 encrypting a rather big file 1.5GB:

 time openssl enc -aes256 -e -pbkdf2 -iter 10000 -pass pass:"mypassword" -in "InputFile" -out "OutputFile"
 Seconds: 2,564s

 time openssl enc -aes256 -e -pbkdf2 -iter 262144 -pass pass:"mypassword" -in "InputFile" -out "OutputFile"
 Seconds:  2,775s

Not really any difference, didn't check memory usage though(?)

With today's GPUs, and even faster tomorrows, I guess billion brute-force iteration seems possible every seconds.

12 years ago a NVIDIA GeForce 8800 Ultra could iterate over 200.000 millions/sec iterations (MD5 hashing though)

source: Ainane-Barrett-Johnson-Vivar-OpenSSL.pdf

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

This is maybe the wrong answer for you. But this was the first hit on Google when I tried to solve my problem. With that said...

The same error message occurred for me as well, but when I tried to run IIS Express through Visual Studio.

My problem was that I mistakenly commited my applicationhost.config to TFS. Later when I tried to run the project on my laptop after getting the latest commits. that's when the error occurred.

I found that the virtual directory path was wrong.

<virtualDirectory path="/" physicalPath="C:\Users\user1\Documents\Visual Studio 2015\Projects\ProjectName\ProjectName\ProjectName.Web" />

Hope that this help somebody!

This is my first post, so be gentle :)

How to return a list of keys from a Hash Map?

Using map.keySet(), you can get a set of keys. Then convert this set into List by:

List<String> l = new ArrayList<String>(map.keySet());

And then use l.get(int) method to access keys.

PS:- source- Most concise way to convert a Set<String> to a List<String>

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

These days a drop-down template is included in the API Gateway Console on AWS.

For your API, click on the resource name... then GET

Expand "Body Mapping Templates"

Type in

application/json

for Content-Type (must be explicitly typed out) and click the tick

A new window will open with the words "Generate template" and a dropdown (see image).

Select

Method Request passthrough

enter image description here

Then click save

To access any variables, just use the following syntax (this is Python) e.g. URL:

https://yourURL.execute-api.us-west-2.amazonaws.com/prod/confirmReg?token=12345&uid=5

You can get variables as follows:

from __future__ import print_function

import boto3
import json

print('Loading function')


def lambda_handler(event, context):
    print(event['params']['querystring']['token'])
    print(event['params']['querystring']['uid'])

So there is no need to explicitly name or map each variable you desire.

Fastest way to get the first object from a queryset in django?

r = list(qs[:1])
if r:
  return r[0]
return None

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

Adding a line break in MySQL INSERT INTO text

For the record, I wanted to add some line breaks into existing data and I got \n to work ok...

Sample data:

Sentence. Sentence. Sentence

I did:

UPDATE table SET field = REPLACE(field, '. ', '.\r\n')

However, it also worked with just \r and just \n.

What does %5B and %5D in POST requests stand for?

Well it's the usual url encoding

So they stand for [, respectively ]

SQL select * from column where year = 2010

If i understand that you want all rows in the year 2010, then:

select * 
  from mytable 
 where Columnx >= '2010-01-01 00:00:00' 
       and Columnx < '2011-01-01 00:00:00'

Updating GUI (WPF) using a different thread

You have a couple of options here, I think.

One would be to use a BackgroundWorker. This is a common helper for multithreading in applications. It exposes a DoWork event which is handled on a background thread from the Thread Pool and a RunWorkerCompleted event which is invoked back on the main thread when the background thread completes. It also has the benefit of try/catching the code running on the background thread so that an unhandled exception doesn't kill the application.

If you don't want to go that route, you can use the WPF dispatcher object to invoke an action to update the GUI back onto the main thread. Random reference:

http://www.switchonthecode.com/tutorials/working-with-the-wpf-dispatcher

There are many other options around too, but these are the two most common that come to mind.

How do I pipe a subprocess call to a text file?

You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:

$ /path/to/the/script.py > output.txt

This will overwrite the file. You can use >> to append to it.

If you want errors to be logged in the file as well, use &>> or &>.

c# foreach (property in object)... Is there a simple way of doing this?

Give this a try:

foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
   // do stuff here
}

Also please note that Type.GetProperties() has an overload which accepts a set of binding flags so you can filter out properties on a different criteria like accessibility level, see MSDN for more details: Type.GetProperties Method (BindingFlags) Last but not least don't forget to add the "system.Reflection" assembly reference.

For instance to resolve all public properties:

foreach (var propertyInfo in obj.GetType()
                                .GetProperties(
                                        BindingFlags.Public 
                                        | BindingFlags.Instance))
{
   // do stuff here
}

Please let me know whether this works as expected.

List submodules in a Git repository

You could use the same mechanism as git submodule init uses itself, namely, look at .gitmodules. This files enumerates each submodule path and the URL it refers to.

For example, from root of repository, cat .gitmodules will print contents to the screen (assuming you have cat).

Because .gitmodule files have the Git configuration format, you can use git config to parse those files:

git config --file .gitmodules --name-only --get-regexp path

Would show you all submodule entries, and with

git config --file .gitmodules --get-regexp path | awk '{ print $2 }'

you would only get the submodule path itself.

Why is char[] preferred over String for passwords?

Character arrays (char[]) can be cleared after use by setting each character to zero and Strings not. If someone can somehow see the memory image, they can see a password in plain text if Strings are used, but if char[] is used, after purging data with 0's, the password is secure.

Command to get time in milliseconds

To show date with time and time-zone

date +"%d-%m-%Y %T.%N %Z"

Output : 22-04-2020 18:01:35.970289239 IST

Changing fonts in ggplot2

You just missed an initialization step I think.

You can see what fonts you have available with the command windowsFonts(). For example mine looks like this when I started looking at this:

> windowsFonts()
$serif
[1] "TT Times New Roman"

$sans
[1] "TT Arial"

$mono
[1] "TT Courier New"

After intalling the package extraFont and running font_import like this (it took like 5 minutes):

library(extrafont)
font_import()
loadfonts(device = "win")

I had many more available - arguable too many, certainly too many to list here.

Then I tried your code:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16,  family="Comic Sans MS"))
print(a)

yielding this:

enter image description here

Update:

You can find the name of a font you need for the family parameter of element_text with the following code snippet:

> names(wf[wf=="TT Times New Roman"])
[1] "serif"

And then:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16,  family="serif"))
print(a)

yields: enter image description here

Pass data to layout that are common to all pages

instead of going through this you can always use another approach which is also fast

create a new partial view in the Shared Directory and call your partial view in your layout as

@Html.Partial("MyPartialView")

in your partial view you can call your db and perform what ever you want to do

@{
    IEnumerable<HOXAT.Models.CourseCategory> categories = new HOXAT.Models.HOXATEntities().CourseCategories;
}

<div>
//do what ever here
</div>

assuming you have added your Entity Framework Database

Enum ToString with user friendly strings

You can use Humanizer package with Humanize Enums possiblity. An eaxample:

enum PublishStatusses
{
    [Description("Custom description")]
    NotCompleted,
    AlmostCompleted,
    Error
};

then you can use Humanize extension method on enum directly:

var st1 = PublishStatusses.NotCompleted;
var str1 = st1.Humanize(); // will result in Custom description

var st2 = PublishStatusses.AlmostCompleted;
var str2 = st2.Humanize(); // will result in Almost completed (calculated automaticaly)

How to print all key and values from HashMap in Android?

Java 8

map.entrySet().forEach(System.out::println);

Change x axes scale in matplotlib

The scalar formatter supports collecting the exponents. The docs are as follows:

class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter

Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.

your technique would be:

from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3))  # Or whatever your limits are . . .
{{ Make your plot }}
gca().xaxis.set_major_formatter(xfmt)

To get the exponent displayed in the format x10^5, instantiate the ScalarFormatter with useMathText=True.

After Image

You could also use:

xfmt.set_useOffset(10000)

To get a result like this:

enter image description here

Catching errors in Angular HttpClient

If you find yourself unable to catch errors with any of the solutions provided here, it may be that the server isn't handling CORS requests.

In that event, Javascript, much less Angular, can access the error information.

Look for warnings in your console that include CORB or Cross-Origin Read Blocking.

Also, the syntax has changed for handling errors (as described in every other answer). You now use pipe-able operators, like so:

this.service.requestsMyInfo(payload).pipe(
    catcheError(err => {
        // handle the error here.
    })
);

Close Current Tab

Use this:

window.open('', '_self');

This only works in chrome; it is a bug. It will be fixed in the future, so use this hacky solution with this in mind.

Value Change Listener to JTextField

DocumentFilter ? It gives you the ability to manipulate.

[ http://www.java2s.com/Tutorial/Java/0240__Swing/FormatJTextFieldstexttouppercase.htm ]

Sorry. J am using Jython (Python in Java) - but easy to understand

# python style
# upper chars [ text.upper() ]

class myComboBoxEditorDocumentFilter( DocumentFilter ):
def __init__(self,jtext):
    self._jtext = jtext

def insertString(self,FilterBypass_fb, offset, text, AttributeSet_attrs):
    txt = self._jtext.getText()
    print('DocumentFilter-insertString:',offset,text,'old:',txt)
    FilterBypass_fb.insertString(offset, text.upper(), AttributeSet_attrs)

def replace(self,FilterBypass_fb, offset, length, text, AttributeSet_attrs):
    txt = self._jtext.getText()
    print('DocumentFilter-replace:',offset, length, text,'old:',txt)
    FilterBypass_fb.replace(offset, length, text.upper(), AttributeSet_attrs)

def remove(self,FilterBypass_fb, offset, length):
    txt = self._jtext.getText()
    print('DocumentFilter-remove:',offset, length, 'old:',txt)
    FilterBypass_fb.remove(offset, length)

// (java style ~example for ComboBox-jTextField)
cb = new ComboBox();
cb.setEditable( true );
cbEditor = cb.getEditor();
cbEditorComp = cbEditor.getEditorComponent();
cbEditorComp.getDocument().setDocumentFilter(new myComboBoxEditorDocumentFilter(cbEditorComp));

String.contains in Java

Similarly:

"".contains("");     // Returns true.

Therefore, it appears that an empty string is contained in any String.

Lost connection to MySQL server during query?

In my case, I ran into this problem when sourcing an SQL dump which had placed the tables in the wrong order. The CREATE in question included a CONSTRAINT ... REFERENCES that referenced a table that had not been created yet.

I located the table in question, and moved its CREATE statement to above the offending one, and the error disappeared.

The other error I encountered relating to this faulty dump was ERROR 1005/ errno: 150 -- "Can't create table" , again a matter of tables being created out of order.

how to open a url in python

I think this is the easy way to open a URL using this function

webbrowser.open_new_tab(url)

Google Chrome Printing Page Breaks

If you are using Chrome with Bootstrap Css the classes that control the grid layout eg col-xs-12 etc use "float: left" which, as others have pointed out, wrecks the page breaks. Remove these from your page for printing. It worked for me. (On Chrome version = 49.0.2623.87)

MySQL equivalent of DECODE function in Oracle

Another MySQL option that may look more like Oracle's DECODE is a combination of FIELD and ELT. In the code that follows, FIELD() returns the argument list position of the string that matches Age. ELT() returns the string from ELTs argument list at the position provided by FIELD(). For example, if Age is 14, FIELD(Age, ...) returns 2 because 14 is the 2nd argument of FIELD (not counting Age). Then, ELT(2, ...) returns 'Fourteen', which is the 2nd argument of ELT (not counting the FIELD() argument). IFNULL returns the default AgeBracket if no match to Age is found in the list.

Select Name, IFNULL(ELT(FIELD(Age,
       13, 14, 15, 16, 17, 18, 19),'Thirteen','Fourteen','Fifteen','Sixteen',
       'Seventeen','Eighteen','Nineteen'),
       'Adult') AS AgeBracket
FROM Person

While I don't think this is the best solution to the question either in terms of performance or readability it is interesting as an exploration of MySQL's string functions. Keep in mind that FIELD's output does not seem to be case sensitive. I.e., FIELD('A','A') and FIELD('a','A') both return 1.

Spring Boot @Value Properties

I had the same problem like you. Here's my error code.

@Component
public class GetExprsAndEnvId {
    @Value("hello")
    private String Mysecret;


    public GetExprsAndEnvId() {
        System.out.println("construct");
    }


    public void print(){
        System.out.println(this.Mysecret);
    }


    public String getMysecret() {
        return Mysecret;
    }

    public void setMysecret(String mysecret) {
        Mysecret = mysecret;
    }
}

This is no problem like this, but we need to use it like this:

@Autowired
private GetExprsAndEnvId getExprsAndEnvId;

not like this:

getExprsAndEnvId = new GetExprsAndEnvId();

Here, the field annotated with @Value is null because Spring doesn't know about the copy of GetExprsAndEnvId that is created with new and didn't know to how to inject values in it.

Can I call a function of a shell script from another shell script?

Refactor your second.sh script like this:

function func1 {
   fun=$1
   book=$2
   printf "fun=%s,book=%s\n" "${fun}" "${book}"
}

function func2 {
   fun2=$1
   book2=$2
   printf "fun2=%s,book2=%s\n" "${fun2}" "${book2}"
}

And then call these functions from script first.sh like this:

source ./second.sh
func1 love horror
func2 ball mystery

OUTPUT:

fun=love,book=horror
fun2=ball,book2=mystery

Python script to do something at the same time every day

I needed something similar for a task. This is the code I wrote: It calculates the next day and changes the time to whatever is required and finds seconds between currentTime and next scheduled time.

import datetime as dt

def my_job():
    print "hello world"
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,my_job,()).start()

Remove special symbols and extra spaces and replace with underscore using the replace method

Remove the \s from your new regex and it should work - whitespace is already included in "anything but alphanumerics".

Note that you may want to add a + after the ] so you don't get sequences of more than one underscore. You can also chain onto .replace(/^_+|_+$/g,'') to trim off underscores at the start or end of the string.

python JSON object must be str, bytes or bytearray, not 'dict

You are passing a dictionary to a function that expects a string.

This syntax:

{"('Hello',)": 6, "('Hi',)": 5}

is both a valid Python dictionary literal and a valid JSON object literal. But loads doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).

If you pass this string to loads:

'''{"('Hello',)": 6, "('Hi',)": 5}'''

then it will return a dictionary that looks a lot like the one you are trying to pass to it.

You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:

json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))

But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?

how do I use an enum value on a switch statement in C++

  • Note: I do know that this doesn't answer this specific question. But it is a question that people come to via a search engine. So i'm posting this here believing it will help those users.

You should keep in mind that if you are accessing class-wide enum from another function even if it is a friend, you need to provide values with a class name:

class PlayingCard
{
private:
  enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
  int rank;
  Suit suit;
  friend std::ostream& operator<< (std::ostream& os, const PlayingCard &pc);
};

std::ostream& operator<< (std::ostream& os, const PlayingCard &pc)
{
  // output the rank ...

  switch(pc.suit)
  {
    case PlayingCard::HEARTS:
      os << 'h';
      break;
    case PlayingCard::DIAMONDS:
      os << 'd';
      break;
    case PlayingCard::CLUBS:
      os << 'c';
      break;
    case PlayingCard::SPADES:
      os << 's';
      break;
  }
  return os;
}

Note how it is PlayingCard::HEARTS and not just HEARTS.

Bootstrap 3: Keep selected tab on page refresh

This one use HTML5 localStorage to store active tab

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
   $('#navtab-container a[href="' + activeTab + '"]').tab('show');
}

ref: http://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php https://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp

How to set adaptive learning rate for GradientDescentOptimizer?

If you want to set specific learning rates for intervals of epochs like 0 < a < b < c < .... Then you can define your learning rate as a conditional tensor, conditional on the global step, and feed this as normal to the optimiser.

You could achieve this with a bunch of nested tf.cond statements, but its easier to build the tensor recursively:

def make_learning_rate_tensor(reduction_steps, learning_rates, global_step):
    assert len(reduction_steps) + 1 == len(learning_rates)
    if len(reduction_steps) == 1:
        return tf.cond(
            global_step < reduction_steps[0],
            lambda: learning_rates[0],
            lambda: learning_rates[1]
        )
    else:
        return tf.cond(
            global_step < reduction_steps[0],
            lambda: learning_rates[0],
            lambda: make_learning_rate_tensor(
                reduction_steps[1:],
                learning_rates[1:],
                global_step,)
            )

Then to use it you need to know how many training steps there are in a single epoch, so that we can use the global step to switch at the right time, and finally define the epochs and learning rates you want. So if I want the learning rates [0.1, 0.01, 0.001, 0.0001] during the epoch intervals of [0, 19], [20, 59], [60, 99], [100, \infty] respectively, I would do:

global_step = tf.train.get_or_create_global_step()
learning_rates = [0.1, 0.01, 0.001, 0.0001]
steps_per_epoch = 225
epochs_to_switch_at = [20, 60, 100]
epochs_to_switch_at = [x*steps_per_epoch for x in epochs_to_switch_at ]
learning_rate = make_learning_rate_tensor(epochs_to_switch_at , learning_rates, global_step)

How does a Breadth-First Search work when looking for Shortest Path?

Technically, Breadth-first search (BFS) by itself does not let you find the shortest path, simply because BFS is not looking for a shortest path: BFS describes a strategy for searching a graph, but it does not say that you must search for anything in particular.

Dijkstra's algorithm adapts BFS to let you find single-source shortest paths.

In order to retrieve the shortest path from the origin to a node, you need to maintain two items for each node in the graph: its current shortest distance, and the preceding node in the shortest path. Initially all distances are set to infinity, and all predecessors are set to empty. In your example, you set A's distance to zero, and then proceed with the BFS. On each step you check if you can improve the distance of a descendant, i.e. the distance from the origin to the predecessor plus the length of the edge that you are exploring is less than the current best distance for the node in question. If you can improve the distance, set the new shortest path, and remember the predecessor through which that path has been acquired. When the BFS queue is empty, pick a node (in your example, it's E) and traverse its predecessors back to the origin. This would give you the shortest path.

If this sounds a bit confusing, wikipedia has a nice pseudocode section on the topic.

Regex to accept alphanumeric and some special character in Javascript?

I forgot to mention. This should also accept whitespace.

You could use:

/^[-@.\/#&+\w\s]*$/

Note how this makes use of the character classes \w and \s.

EDIT:- Added \ to escape /

m2eclipse error

I had same problem with Eclipse 3.7.2 (Indigo) and maven 3.0.4.

In my case, the problem was caused by missing maven-resources-plugin-2.4.3.jar in {user.home}\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3 folder. (no idea why maven didn't update it)

Solution:

1.) add dependency to pom.xml

<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.4.3</version>
</dependency>

2.) run mvn install from Eclipse or from command line

3.) refresh the project in eclipse (F5)

4.) run Maven > Update Project Configuration... on project (right click)

JAR file is downloaded to local repository and there are no errors in WS.

Increasing the Command Timeout for SQL command

Setting CommandTimeout to 120 is not recommended. Try using pagination as mentioned above. Setting CommandTimeout to 30 is considered as normal. Anything more than that is consider bad approach and that usually concludes something wrong with the Implementation. Now the world is running on MiliSeconds Approach.

Property 'json' does not exist on type 'Object'

UPDATE: for rxjs > v5.5

As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json() method anymore.

import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';

export interface Order {
  // Properties
}

interface ResponseOrders {
  results: Order[];
}

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get<ResponseOrders >(this.baseUrl,{
       params
    }).pipe(
       map(res => res.results || []),
       catchError(error => _throwError(error.message || error))
    );
} 

Notice that you could easily transform the returned Observable to a Promise by simply invoking toPromise().

ORIGINAL ANSWER:

In your case, you can

Assumming that your backend returns something like:

{results: [{},{}]}

in JSON format, where every {} is a serialized object, you would need the following:

// Somewhere in your src folder

export interface Order {
  // Properties
}

import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { Order } from 'somewhere_in_src';    

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get(this.baseUrl,{
       params
    })
    .map(res => res.results as Order[] || []); 
   // in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])
  }
} 

I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:

https://gist.github.com/jotatoledo/765c7f6d8a755613cafca97e83313b90

And to consume you just need to call it like:

// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]

http://localhost/phpMyAdmin/ unable to connect

You dont start phpmyadmin from your webbrowser. When you want to start PHPMyAdmin you have to do so from the XAMPP control-panel. When you've started phpmyadmin from your control-panel you can access it from the web-browser.

JOptionPane Input to int

Simply use:

int ans = Integer.parseInt( JOptionPane.showInputDialog(frame,
        "Text",
        JOptionPane.INFORMATION_MESSAGE,
        null,
        null,
        "[sample text to help input]"));

You cannot cast a String to an int, but you can convert it using Integer.parseInt(string).

iPhone hide Navigation Bar only on first page

Give my credit to @chad-m 's answer.

Here is the Swift version:

  1. Create a new file MyNavigationController.swift

import UIKit

class MyNavigationController: UINavigationController, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.delegate = self
    }

    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        if viewController == self.viewControllers.first {
            self.setNavigationBarHidden(true, animated: animated)
        } else {
            self.setNavigationBarHidden(false, animated: animated)
        }
    }

}
  1. Set your UINavigationController's class in StoryBoard to MyNavigationController MyNavigationController That's it!

Difference between chad-m's answer and mine:

  1. Inherit from UINavigationController, so you won't pollute your rootViewController.

  2. use self.viewControllers.first rather than homeViewController, so you won't do this 100 times for your 100 UINavigationControllers in 1 StoryBoard.

How to make unicode string with python3

In a Python 2 program that I used for many years there was this line:

ocd[i].namn=unicode(a[:b], 'utf-8')

This did not work in Python 3.

However, the program turned out to work with:

ocd[i].namn=a[:b]

I don't remember why I put unicode there in the first place, but I think it was because the name can contains Swedish letters åäöÅÄÖ. But even they work without "unicode".

In Python how should I test if a variable is None, True or False

I would like to stress that, even if there are situations where if expr : isn't sufficient because one wants to make sure expr is True and not just different from 0/None/whatever, is is to be prefered from == for the same reason S.Lott mentionned for avoiding == None.

It is indeed slightly more efficient and, cherry on the cake, more human readable.

In [1]: %timeit (1 == 1) == True
38.1 ns ± 0.116 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [2]: %timeit (1 == 1) is True
33.7 ns ± 0.141 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

connecting to phpMyAdmin database with PHP/MySQL

The database is a MySQL database, not a phpMyAdmin database. phpMyAdmin is only PHP code that connects to the DB.

mysql_connect('localhost', 'username', 'password') or die (mysql_error());
mysql_select_database('db_name') or die (mysql_error());

// now you are connected

Limit the length of a string with AngularJS

< div >{{modal.title | limitTo:20}}...< / div>

Watching variables contents in Eclipse IDE

You can do so by these ways.

Add watchpoint and while debugging you can see variable in debugger window perspective under variable tab. OR Add System.out.println("variable = " + variable); and see in console.

single line comment in HTML

No, you have to close the comment with -->.

Uploading multiple files using formData()

The way to go with javascript:

var data = new FormData();

$.each($("input[type='file']")[0].files, function(i, file) {
    data.append('file', file);
});

$.ajax({
    type: 'POST',
    url: '/your/url',
    cache: false,
    contentType: false,
    processData: false,
    data : data,
    success: function(result){
        console.log(result);
    },
    error: function(err){
        console.log(err);
    }
})

If you call data.append('file', file) multiple times your request will contain an array of your files.

From MDN web docs:

"The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. The difference between FormData.set and append() is that if the specified key already exists, FormData.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values."

Myself using node.js and multipart handler middleware multer get the data as follows:

router.post('/trip/save', upload.array('file', 10), function(req, res){
    // Your array of files is in req.files
}

Get type name without full namespace

best way to use:

typeof(T).Name

What do these operators mean (** , ^ , %, //)?

You are correct that ** is the power function.

^ is bitwise XOR.

% is indeed the modulus operation, but note that for positive numbers, x % m = x whenever m > x. This follows from the definition of modulus. (Additionally, Python specifies x % m to have the sign of m.)

// is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the / in most programming languages. However, Python 3 changed the behavior of / to perform floating-point division even if the arguments are integers. The // operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:

| context                                | `/` behavior   | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison   |
---------------------------------------------------------------------------
| integer arguments, python 2            | int division   | int division  |
---------------------------------------------------------------------------
| integer arguments, python 3            | float division | int division  |

For more details, see this question: Division in Python 2.7. and 3.3

Resource u'tokenizers/punkt/english.pickle' not found

My issue was that I called nltk.download('all') as the root user, but the process that eventually used nltk was another user who didn't have access to /root/nltk_data where the content was downloaded.

So I simply recursively copied everything from the download location to one of the paths where NLTK was looking to find it like this:

cp -R /root/nltk_data/ /home/ubuntu/nltk_data

How to configure port for a Spring Boot application

This question is the first result if you google for Gradle Spring Port.

If you use gradle you can do something like this if you have the Spring Boot Gradle Plugin already applied:

bootRun {
    args += ["--server.port=[PORT]"]
}

For a more sophisticated answer please see my answer here.

How to unblock with mysqladmin flush hosts

mysqladmin is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).

You type that command from a shell prompt.

Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:

FLUSH HOSTS;

http://dev.mysql.com/doc/refman/5.6/en/flush.html

http://dev.mysql.com/doc/refman/5.6/en/mysqladmin.html

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

C++ code file extension? .cc vs .cpp

It doesn't matter which of those extensions you'd use. Pick whichever you like more, just be consistent with naming. The only exception I'm aware of with this naming convention is that I couldn't make WinDDK (or is it WDK now?) to compile .cc files. On Linux though that's hardly a problem.

warning: control reaches end of non-void function [-Wreturn-type]

You just need to return from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.

  /* .... */
  if (Date1 == Date2)  
     fprintf (stderr , "Indicating that the first date is equal to second date.\n"); 

  return 0;
}

Reading in from System.in - Java

You can use System.in to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.

class MyProg {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Printing the file passed in:");
        while(sc.hasNextLine()) System.out.println(sc.nextLine());
    }
}

Node.js Write a line into a .txt file

Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.

The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback) function from fs module:

var fs = require('fs')
fs.appendFile('log.txt', 'new data', function (err) {
  if (err) {
    // append failed
  } else {
    // done
  }
})

But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options]) function instead:

var fs = require('fs')
var logger = fs.createWriteStream('log.txt', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

logger.write('some data') // append string to your file
logger.write('more data') // again
logger.write('and more') // again

Node will keep appending new data to your file every time you'll call .write, until your application will be closed, or until you'll manually close the stream calling .end:

logger.end() // close string

How to position the form in the center screen?

The following example centers a frame on the screen:

package com.zetcode;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import javax.swing.JFrame;


public class CenterOnScreen extends JFrame {

    public CenterOnScreen() {

        initUI();
    }

    private void initUI() {

        setSize(250, 200);
        centerFrame();
        setTitle("Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void centerFrame() {

            Dimension windowSize = getSize();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Point centerPoint = ge.getCenterPoint();

            int dx = centerPoint.x - windowSize.width / 2;
            int dy = centerPoint.y - windowSize.height / 2;    
            setLocation(dx, dy);
    }


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenterOnScreen ex = new CenterOnScreen();
                ex.setVisible(true);
            }
        });       
    }
}

In order to center a frame on a screen, we need to get the local graphics environment. From this environment, we determine the center point. In conjunction with the frame size, we manage to center the frame. The setLocation() is the method that moves the frame to the central position.

Note that this is actually what the setLocationRelativeTo(null) does:

public void setLocationRelativeTo(Component c) {
    // target location
    int dx = 0, dy = 0;
    // target GC
    GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
    Rectangle gcBounds = gc.getBounds();

    Dimension windowSize = getSize();

    // search a top-level of c
    Window componentWindow = SunToolkit.getContainingWindow(c);
    if ((c == null) || (componentWindow == null)) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
        gcBounds = gc.getBounds();
        Point centerPoint = ge.getCenterPoint();
        dx = centerPoint.x - windowSize.width / 2;
        dy = centerPoint.y - windowSize.height / 2;
    }

  ...

  setLocation(dx, dy);
}

ValueError: unconverted data remains: 02:05

Best answer is to use the from dateutil import parser.

usage:

from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())

Count number of columns in a table row

You could do

alert(document.getElementById('table1').rows[0].cells.length)

fiddle here http://jsfiddle.net/TEZ73/

VBA Count cells in column containing specified value

If you're looking to match non-blank values or empty cells and having difficulty with wildcard character, I found the solution below from here.

Dim n as Integer
n = Worksheets("Sheet1").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

By default, IUSR account is used for anonymous user.

All you need to do is:

IIS -> Authentication --> Set Anonymous Authentication to Application Pool Identity.

Problem solved :)

bootstrap 3 tabs not working properly

Make sure your jquery is inserted BEFORE bootstrap js file:

<script src="jquery.min.js" type="text/javascript"></script>
<link href="bootstrap.min.css" rel="stylesheet" type="text/css"/>
<script src="bootstrap.min.js" type="text/javascript"></script>

How can I change the remote/target repository URL on Windows?

Take a look in .git/config and make the changes you need.

Alternatively you could use

git remote rm [name of the url you sets on adding]

and

git remote add [name] [URL]

Or just

git remote set-url [URL]

Before you do anything wrong, double check with

git help remote

"could not find stored procedure"

One more possibility to check. Listing here because it just happened to me and wasn't mentioned;-)

I had accidentally added a space character on the end of the name. Many hours of trying things before I finally noticed it. It's always something simple after you figure it out.

Self-references in object literals / initializers

The get property works great, and you can also use a binded closure for "expensive" functions that should only run once (this only works with var, not with const or let)

_x000D_
_x000D_
var info = {
  address: (function() {
    return databaseLookup(this.id)
  }).bind(info)(),

  get fullName() {
    console.log('computing fullName...')
    return `${this.first} ${this.last}`
  },

  id: '555-22-9999',
  first: 'First',
  last: 'Last',
}

function databaseLookup() {
  console.log('fetching address from remote server (runs once)...')
  return Promise.resolve(`22 Main St, City, Country`)
}

// test
(async () => {
  console.log(info.fullName)
  console.log(info.fullName)
  console.log(await info.address)
  console.log(await info.address)
  console.log(await info.address)
  console.log(await info.address)
})()
_x000D_
_x000D_
_x000D_

MySQL how to join tables on two fields

JOIN t2 ON t1.id=t2.id AND t1.date=t2.date

How to update the constant height constraint of a UIView programmatically?

Drag the constraint into your VC as an IBOutlet. Then you can change its associated value (and other properties; check the documentation):

@IBOutlet myConstraint : NSLayoutConstraint!
@IBOutlet myView : UIView!

func updateConstraints() {
    // You should handle UI updates on the main queue, whenever possible
    DispatchQueue.main.async {
        self.myConstraint.constant = 10
        self.myView.layoutIfNeeded()
    }
}

MySQL SELECT last few days?

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

use quotes on the -3 value

Check if input is number or letter javascript

Just find the remainder by dividing by 1, that is x%1. If the remainder is 0, it means that x is a whole number. Otherwise, you have to display the message "Must input numbers". This will work even in the case of strings, decimal numbers etc.

function checkInp()
{
    var x = document.forms["myForm"]["age"].value;
    if ((x%1) != 0) 
    {
        alert("Must input numbers");
        return false;
    }
}

How do you find the row count for all your tables in Postgres

This worked for me

SELECT schemaname,relname,n_live_tup FROM pg_stat_user_tables ORDER BY n_live_tup DESC;

VB.net Need Text Box to Only Accept Numbers

You can use the onkeydown Property of the TextBox for limiting its value to numbers only.

<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32);"></asp:TextBox>

!(keyCode>=65) check is for excludng Alphabets.

keyCode!=32 check is for excluding Space character inbetween the numbers.

If you want to exclude Symbols also from entering into the textbox, then include the below condition also in the 'onkeydown' property.

!(event.shiftKey && (event.keyCode >= 48 && event.keyCode <= 57))

Thus the TextBox will finally become

<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32 && !(event.shiftKey && (event.keyCode >= 48 && event.keyCode <= 57)));"></asp:TextBox>

Explanation:

KeyCode for 'a' is '65' and 'z' is '90'.

KeyCodes from '90' to '222' which are other symbols are also not needed.

KeyCode for 'Space' Key is '32' which is also not needed.

Then a combination of 'Shift' key and 'Number' keys (which denotes Symbols) also not needed. KeyCode for '0' is '48' and '9' is '57'.

Hence all these are included in the TextBox declaration itself which produces the desired result.

Try and see.

How to "select distinct" across multiple data frame columns in pandas?

I think use drop duplicate sometimes will not so useful depending dataframe.

I found this:

[in] df['col_1'].unique()
[out] array(['A', 'B', 'C'], dtype=object)

And work for me!

https://riptutorial.com/pandas/example/26077/select-distinct-rows-across-dataframe

Count the occurrences of DISTINCT values

What about something like this:

SELECT
  name,
  count(*) AS num
FROM
  your_table
GROUP BY
  name
ORDER BY
  count(*)
  DESC

You are selecting the name and the number of times it appears, but grouping by name so each name is selected only once.

Finally, you order by the number of times in DESCending order, to have the most frequently appearing users come first.

MySQL/Writing file error (Errcode 28)

You can also try using this line if the other doesn't work:

du -sh /var/lib/mysql/database_Name

You may also want to check with your host and see how big they allow your databases to be.

How to revert initial git commit?

You just need to delete the branch you are on. You can't use git branch -D as this has a safety check against doing this. You can use update-ref to do this.

git update-ref -d HEAD

Do not use rm -rf .git or anything like this as this will completely wipe your entire repository including all other branches as well as the branch that you are trying to reset.

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

Difference between attr_accessor and attr_accessible

attr_accessor is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname and you can use this field in your View, or model, if you wanted, but mostly in your View.

Let's consider the following example

class Address
    attr_reader :street
    attr_writer :street  
    def initialize
        @street = ""
    end
end

Here we have used attr_reader (readable attribute) and attr_writer (writable attribute) for accessing purpose. But we can achieve the same functionality using attr_accessor. In short, attr_accessor provides access to both getter and setter methods.

So modified code is as below

class Address
    attr_accessor :street  
    def initialize
        @street = ""
    end
end

attr_accessible allows you to list all the columns you want to allow Mass Assignment. The opposite of this is attr_protected which means this field I do NOT want anyone to be allowed to Mass Assign to. More than likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.

How do I format a string using a dictionary in python-3.x?

print("{latitude} {longitude}".format(**geopoint))

Selecting option by text content with jQuery

Replace this:

var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
    $(this).select(); // This is where my problem is
});

With this:

$('#cbCategory').val(cat);

Calling val() on a select list will automatically select the option with that value, if any.

why numpy.ndarray is object is not callable in my simple for python loop

Avoid loops. What you want to do is:

import numpy as np
data=np.loadtxt(fname="data.txt")## to load the above two column
print data
print data.sum(axis=1)

Drawing Isometric game worlds

If you have some tiles that exceed the bounds of your diamond, I recommend drawing in depth order:

...1...
..234..
.56789.
..abc..
...d...

Batch file script to zip files

No external dependency on 7zip or ZIP - create a vbs script and execute:

    @ECHO Zipping
    mkdir %TEMPDIR%
    xcopy /y /s %FILETOZIP% %TEMPDIR%
    echo Set objArgs = WScript.Arguments > _zipIt.vbs
    echo InputFolder = objArgs(0) >> _zipIt.vbs
    echo ZipFile = objArgs(1) >> _zipIt.vbs
    echo CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
    echo Set objShell = CreateObject("Shell.Application") >> _zipIt.vbs
    echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
    echo objShell.NameSpace(ZipFile).CopyHere(source) >> _zipIt.vbs
    @ECHO *******************************************
    @ECHO Zipping, please wait..
    echo wScript.Sleep 12000 >> _zipIt.vbs
    CScript  _zipIt.vbs  %TEMPDIR%  %OUTPUTZIP%
    del _zipIt.vbs
    rmdir /s /q  %TEMPDIR%

    @ECHO *******************************************
    @ECHO      ZIP Completed

Is div inside list allowed?

Yes it is valid according to xhtml1-strict.dtd. The following XHTML passes the validation:

<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test</title>
</head>
<body>
<ul>
  <li><div>test</div></li>
</ul>
</body>
</html>

Javascript ajax call on page onload

Or with Prototype:

Event.observe(this, 'load', function() { new Ajax.Request(... ) );

Or better, define the function elsewhere rather than inline, then:

Event.observe(this, 'load', functionName );

You don't have to use jQuery or Prototype specifically, but I hope you're using some kind of library. Either library is going to handle the event handling in a more consistent manner than onload, and of course is going to make it much easier to process the Ajax call. If you must use the body onload attribute, then you should just be able to call the same function as referenced in these examples (onload="javascript:functionName();").

However, if your database update doesn't depend on the rendering on the page, why wait until it's fully loaded? You could just include a call to the Ajax-calling function at the end of the JavaScript on the page, which should give nearly the same effect.

How to require a controller in an angularjs directive

I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".


It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.

Share a Controller

Two directives can use the same controller by passing the same method to two directives, like so:

app.controller( 'MyCtrl', function ( $scope ) {
  // do stuff...
});

app.directive( 'directiveOne', function () {
  return {
    controller: 'MyCtrl'
  };
});

app.directive( 'directiveTwo', function () {
  return {
    controller: 'MyCtrl'
  };
});

Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.

Require a Controller

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive

How to have a default option in Angular.js select box

My solution to this was use html to hardcode my default option. Like so:

In HAML:

%select{'ng-model' => 'province', 'ng-options' => "province as province for province in summary.provinces", 'chosen' => "chosen-select", 'data-placeholder' => "BC & ON"}
  %option{:value => "", :selected => "selected"}
    BC &amp; ON

In HTML:

<select ng-model="province" ng-options="province as province for province in summary.provinces" chosen="chosen-select" data-placeholder="BC & ON">
  <option value="" selected="selected">BC &amp; ON</option>
</select>

I want my default option to return all values from my api, that's why I have a blank value. Also excuse my haml. I know this isn't directly an answer to the OP's question, but people find this on Google. Hope this helps someone else.

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

As of Visual Studio 2017, this looks to be a built-in feature. Hit Ctrl + . while your cursor is in the class body, and select "Generate Constructor" from the Quick Actions and Refactorings dropdown.

How to use in jQuery :not and hasClass() to get a specific element without a class

It's much easier to do like this:

if(!$('#foo').hasClass('bar')) { 
  ...
}

The ! in front of the criteria means false, works in most programming languages.

How to calculate sum of a formula field in crystal Reports?

The only reason that I know of why a formula wouldn't be available to summarize on is if it didn't reference any database fields or whose value wasn't dynamic throughout sections of the report. For example, if you have a formula that returns a constant it won't be available. Or if it only references a field that is set throughout the report and returns a value based on that field, like "if {parameter}=1 then 1" would not be available either.

In general, the formula's value should not be static through the sections of the report you're summarizing over (Though the way Crystal determines this is beyond me and this doesn't seem to be a hard and fast rule)

EDIT: One other reason why a formula wouldn't be available is if you're already using a summary function in that formula. Only one level of summaries at a time!

How to return value from an asynchronous callback function?

This is impossible as you cannot return from an asynchronous call inside a synchronous method.

In this case you need to pass a callback to foo that will receive the return value

function foo(address, fn){
  geocoder.geocode( { 'address': address}, function(results, status) {
     fn(results[0].geometry.location); 
  });
}

foo("address", function(location){
  alert(location); // this is where you get the return value
});

The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.

If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.

Big-O summary for Java Collections Framework implementations?

The Javadocs from Sun for each collection class will generally tell you exactly what you want. HashMap, for example:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).

TreeMap:

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

TreeSet:

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

(emphasis mine)

Cookies on localhost with explicit domain

document.cookie = valuename + "=" + value + "; " + expires + ";domain=;path=/";

this "domain=;path=/"; will take dynamic domain as its cookie will work in subdomain. if u want to test in localhost it will work

'list' object has no attribute 'shape'

firstly u have to import numpy library (refer code for making a numpy array) shape only gives the output only if the variable is attribute of numpy library .in other words it must be a np.array or any other data structure of numpy. Eg.

`>>> import numpy
>>> a=numpy.array([[1,1],[1,1]])
>>> a.shape
(2, 2)`

Accessing constructor of an anonymous class

Peter Norvig's The Java IAQ: Infrequently Answered Questions

http://norvig.com/java-iaq.html#constructors - Anonymous class contructors

http://norvig.com/java-iaq.html#init - Construtors and initialization

Summing, you can construct something like this..

public class ResultsBuilder {
    Set<Result> errors;
    Set<Result> warnings;

...

    public Results<E> build() {
        return new Results<E>() {
            private Result[] errorsView;
            private Result[] warningsView;
            {
                errorsView = ResultsBuilder.this.getErrors();
                warningsView = ResultsBuilder.this.getWarnings();
            }

            public Result[] getErrors() {
                return errorsView;
            }

            public Result[] getWarnings() {
                return warningsView;
            }
        };
    }

    public Result[] getErrors() {
        return !isEmpty(this.errors) ? errors.toArray(new Result[0]) : null;
    }

    public Result[] getWarnings() {
        return !isEmpty(this.warnings) ? warnings.toArray(new Result[0]) : null;
    }
}

Running MSBuild fails to read SDKToolsPath

Besides the registry mods, you may need to change version of the .net sdk your settings set to in Visual Studio.

I was having this problem and decided to check the project debug settings.

Project => Toolbar Properties => Debug Advance Compile Options button

The Target Framework (all configurations) was set to 3.0 which is not on my system.

I changed that to 4.0, then had to restart the project and Visual Studio 2010.

The project then built without errors and ran.

How do I fix the multiple-step OLE DB operation errors in SSIS?

This error will also occur when trying to do an insert and a field is coded not null and nulls are trying to be inserted.

How do I choose the URL for my Spring Boot webapp?

As of spring boot 2 the server.contextPath property is deprecated. Instead you should use server.servlet.contextPath.

So in your application.properties file add:

server.servlet.contextPath=/myWebApp

For more details see: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide#servlet-specific-server-properties

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

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

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

How to detect if javascript files are loaded?

I don't have a reference for it handy, but script tags are processed in order, and so if you put your $(document).ready(function1) in a script tag after the script tags that define function1, etc., you should be good to go.

<script type='text/javascript' src='...'></script>
<script type='text/javascript' src='...'></script>
<script type='text/javascript'>
$(document).ready(function1);
</script>

Of course, another approach would be to ensure that you're using only one script tag, in total, by combining files as part of your build process. (Unless you're loading the other ones from a CDN somewhere.) That will also help improve the perceived speed of your page.

EDIT: Just realized that I didn't actually answer your question: I don't think there's a cross-browser event that's fired, no. There is if you work hard enough, see below. You can test for symbols and use setTimeout to reschedule:

<script type='text/javascript'>
function fireWhenReady() {
    if (typeof function1 != 'undefined') {
        function1();
    }
    else {
        setTimeout(fireWhenReady, 100);
    }
}
$(document).ready(fireWhenReady);
</script>

...but you shouldn't have to do that if you get your script tag order correct.


Update: You can get load notifications for script elements you add to the page dynamically if you like. To get broad browser support, you have to do two different things, but as a combined technique this works:

function loadScript(path, callback) {

    var done = false;
    var scr = document.createElement('script');

    scr.onload = handleLoad;
    scr.onreadystatechange = handleReadyStateChange;
    scr.onerror = handleError;
    scr.src = path;
    document.body.appendChild(scr);

    function handleLoad() {
        if (!done) {
            done = true;
            callback(path, "ok");
        }
    }

    function handleReadyStateChange() {
        var state;

        if (!done) {
            state = scr.readyState;
            if (state === "complete") {
                handleLoad();
            }
        }
    }
    function handleError() {
        if (!done) {
            done = true;
            callback(path, "error");
        }
    }
}

In my experience, error notification (onerror) is not 100% cross-browser reliable. Also note that some browsers will do both mechanisms, hence the done variable to avoid duplicate notifications.

How to convert all tables in database to one collation?

This is my version of a bash script. It takes database name as a parameter and converts all tables to another charset and collation (given by another parameters or default value defined in the script).

#!/bin/bash

# mycollate.sh <database> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables

DB="$1"
CHARSET="$2"
COLL="$3"

[ -n "$DB" ] || exit 1
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_general_ci"

echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql

echo "USE $DB; SHOW TABLES;" | mysql -s | (
    while read TABLE; do
        echo $DB.$TABLE
        echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql $DB
    done
)

Check if a number is a perfect square

a=int(input('enter any number'))
flag=0
for i in range(1,a):
    if a==i*i:
        print(a,'is perfect square number')
        flag=1
        break
if flag==1:
    pass
else:
    print(a,'is not perfect square number')

How do I loop through rows with a data reader in C#?

That's the way the DataReader works, it's designed to read the database rows one at a time.

while(reader.Read()) 
{
  var value1 = reader.GetValue(0); // On first iteration will be hello
  var value2 = reader.GetValue(1); // On first iteration will be hello2
  var value3 = reader.GetValue(2); // On first iteration will be hello3
}

How can I connect to a Tor hidden service using cURL in PHP?

Try to add this:

curl_setopt($ch, CURLOPT_HEADER, 1); 
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); 

nginx upload client_max_body_size issue

Does your upload die at the very end? 99% before crashing? Client body and buffers are key because nginx must buffer incoming data. The body configs (data of the request body) specify how nginx handles the bulk flow of binary data from multi-part-form clients into your app's logic.

The clean setting frees up memory and consumption limits by instructing nginx to store incoming buffer in a file and then clean this file later from disk by deleting it.

Set body_in_file_only to clean and adjust buffers for the client_max_body_size. The original question's config already had sendfile on, increase timeouts too. I use the settings below to fix this, appropriate across your local config, server, & http contexts.

client_body_in_file_only clean;
client_body_buffer_size 32K;

client_max_body_size 300M;

sendfile on;
send_timeout 300s;

Safely override C++ virtual functions

As far as I know, can't you just make it abstract?

class parent {
public:
  virtual void handle_event(int something) const = 0 {
    // boring default code
  }
};

I thought I read on www.parashift.com that you can actually implement an abstract method. Which makes sense to me personally, the only thing it does is force subclasses to implement it, no one said anything about it not being allowed to have an implementation itself.