Programs & Examples On #Persistent

Generally in ORM and OOP , a persistent object refers to an object that exists (or persists) in the database

HTML text input field with currency symbol

For bootstrap its works

<span class="form-control">$ <input type="text"/></span>

Don't use class="form-control" in input field.

SecurityException: Permission denied (missing INTERNET permission?)

remove this in your manifest file

 xmlns:tools="http://schemas.android.com/tools"

Select info from table where row has max date

You can use a window MAX() like this:

SELECT
  *, 
  max_date = MAX(date) OVER (PARTITION BY group)
FROM table

to get max dates per group alongside other data:

group  date      cash  checks  max_date
-----  --------  ----  ------  --------
1      1/1/2013  0     0       1/3/2013
2      1/1/2013  0     800     1/1/2013
1      1/3/2013  0     700     1/3/2013
3      1/1/2013  0     600     1/5/2013
1      1/2/2013  0     400     1/3/2013
3      1/5/2013  0     200     1/5/2013

Using the above output as a derived table, you can then get only rows where date matches max_date:

SELECT
  group,
  date,
  checks
FROM (
  SELECT
    *, 
    max_date = MAX(date) OVER (PARTITION BY group)
  FROM table
) AS s
WHERE date = max_date
;

to get the desired result.

Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.

You can try the method at SQL Fiddle.

List to array conversion to use ravel() function

If all you want is calling ravel on your (nested, I s'pose?) list, you can do that directly, numpy will do the casting for you:

L = [[1,None,3],["The", "quick", object]]
np.ravel(L)
# array([1, None, 3, 'The', 'quick', <class 'object'>], dtype=object)

Also worth mentioning that you needn't go through numpy at all.

Should I make HTML Anchors with 'name' or 'id'?

How about using name attribute for old browsers and id attribute to the new browsers. Both options will be used and fallback method will be implemented by default!!!

Why use HttpClient for Synchronous Connection

I'd re-iterate Donny V. answer and Josh's

"The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support."

(and upvote if I had the reputation.)

I can't remember the last time if ever, I was grateful of the fact HttpWebRequest threw exceptions for status codes >= 400. To get around these issues you need to catch the exceptions immediately, and map them to some non-exception response mechanisms in your code...boring, tedious and error prone in itself. Whether it be communicating with a database, or implementing a bespoke web proxy, its 'nearly' always desirable that the Http driver just tell your application code what was returned, and leave it up to you to decide how to behave.

Hence HttpClient is preferable.

Match linebreaks - \n or \r\n?

In Python:

# as Peter van der Wal's answer
re.split(r'\r\n|\r|\n', text, flags=re.M) 

or more rigorous:

# https://docs.python.org/3/library/stdtypes.html#str.splitlines
str.splitlines()

How to break line in JavaScript?

alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");

or %0D%0A in a url

Understanding checked vs unchecked exceptions in Java

Checked - Prone to happen. Checked in Compile time.

Eg.. FileOperations

UnChecked - Due to Bad data. Checked in Run time.

Eg..

String s = "abc";
Object o = s;
Integer i = (Integer) o;

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at Sample.main(Sample.java:9)

Here exception is due to bad data and in no way it can be determined during compile time.

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

Update: This will create a second context same as in applicationContext.xml

or you can add this code snippet to your web.xml

<servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

instead of

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

How to connect to a MS Access file (mdb) using C#?

Here's how to use a Jet OLEDB or Ace OLEDB Access DB:

using System.Data;
using System.Data.OleDb;

string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                           "Data Source=C:\myPath\myFile.mdb;" +                                    
                           "Persist Security Info=True;" +
                           "Jet OLEDB:Database Password=myPassword;";
try
{
    // Open OleDb Connection
    OleDbConnection myConnection = new OleDbConnection();
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();

    // Execute Queries
    OleDbCommand cmd = myConnection.CreateCommand();
    cmd.CommandText = "SELECT * FROM `myTable`";
    OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete

    // Load the result into a DataTable
    DataTable myDataTable = new DataTable();
    myDataTable.Load(reader);
}
catch (Exception ex)
{
    Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}

Can Windows Containers be hosted on linux?

No, you cannot run windows containers directly on Linux.

But you can run Linux on Windows.

Windows Server/10 comes packaged with base image of ubuntu OS (after september 2016 beta service pack). That is the reason you can run linux on windows and not other wise. Check out here. https://thenewstack.io/finally-linux-containers-really-will-run-windows-linuxkit/

You can change between OS containers Linux and windows by right clicking on the docker in tray menu.

enter image description here

enter image description here

How to convert date format to DD-MM-YYYY in C#

I ran into the same issue. What I needed to do was add a reference at the top of the class and change the CultureInfo of the thread that is currently executing.

using System.Threading;

string cultureName = "fr-CA";
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);

DateTime theDate = new DateTime(2015, 11, 06);
theDate.ToString("g");
Console.WriteLine(theDate);

All you have to do is change the culture name, for example: "en-US" = United States "fr-FR" = French-speaking France "fr-CA" = French-speaking Canada etc...

What does the @Valid annotation indicate in Spring?

It's for validation purposes.

Validation It is common to validate a model after binding user input to it. Spring 3 provides support for declarative validation with JSR-303. This support is enabled automatically if a JSR-303 provider, such as Hibernate Validator, is present on your classpath. When enabled, you can trigger validation simply by annotating a Controller method parameter with the @Valid annotation: After binding incoming POST parameters, the AppointmentForm will be validated; in this case, to verify the date field value is not null and occurs in the future.


Look here for more info:
http://blog.springsource.com/2009/11/17/spring-3-type-conversion-and-validation/

Heap space out of memory

I also faced the same problem.I resolved by doing the build by following steps as.

-->Right click on the project select RunAs ->Run configurations

Select your project as BaseDirectory. In place of goals give eclipse:eclipse install

-->In the second tab give -Xmx1024m as VM arguments.

How can I determine the URL that a local Git repository was originally cloned from?

You cloned your repo with SSH clone.

git config --get remote.origin.url
[email protected]:company/product/production.git

But you want to get http url to open it in the browser or share it:

git config --get remote.origin.url | sed -e 's/:/\//g'| sed -e 's/ssh\/\/\///g'| sed -e 's/git@/https:\/\//g'

https://gitlab.com/company/product/production.git

GitHub or GitLab doesn’t matter.

LinkButton Send Value to Code Behind OnClick

Just add to the CommandArgument parameter and read it out on the Click handler:

<asp:LinkButton ID="ENameLinkBtn" runat="server" 
    style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere" 
    OnClick="ENameLinkBtn_Click" >

Then in your click event:

protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)(sender);
    string yourValue = btn.CommandArgument;
    // do what you need here
}   

Also you can set the CommandArgument argument when binding if you are using the LinkButton in any bindable controls by doing:

CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'

Send POST data via raw json with postman

Unlike jQuery in order to read raw JSON you will need to decode it in PHP.

print_r(json_decode(file_get_contents("php://input"), true));

php://input is a read-only stream that allows you to read raw data from the request body.

$_POST is form variables, you will need to switch to form radiobutton in postman then use:

foo=bar&foo2=bar2

To post raw json with jquery:

$.ajax({
    "url": "/rest/index.php",
    'data': JSON.stringify({foo:'bar'}),
    'type': 'POST',
    'contentType': 'application/json'
});

Execute CMD command from code

if you want to start application with cmd use this code:

string YourApplicationPath = "C:\\Program Files\\App\\MyApp.exe"   
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.FileName = "cmd.exe";
processInfo.WorkingDirectory = Path.GetDirectoryName(YourApplicationPath);
processInfo.Arguments = "/c START " + Path.GetFileName(YourApplicationPath);
Process.Start(processInfo);

How to recursively list all the files in a directory in C#?

In .NET 4.5, at least, there's this version that is much shorter and has the added bonus of evaluating any file criteria for inclusion in the list:

public static IEnumerable<string> GetAllFiles(string path, 
                                              Func<FileInfo, bool> checkFile = null)
{
    string mask = Path.GetFileName(path);
    if (string.IsNullOrEmpty(mask)) mask = "*.*";
    path = Path.GetDirectoryName(path);
    string[] files = Directory.GetFiles(path, mask, SearchOption.AllDirectories);

    foreach (string file in files)
    {
        if (checkFile == null || checkFile(new FileInfo(file)))
            yield return file;
    }
}

Use like this:

var list = GetAllFiles(mask, (info) => Path.GetExtension(info.Name) == ".html").ToList();

TypeError: Cannot read property "0" from undefined

The while increments the i. So you get:

data[1][0]
data[2][0]
data[3][0]
...

It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

Pressed <button> selector

Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active active is pseudo.

Reference:

http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!

Your code:

The code that you're having the basic but helpfull. And yes :active will only occur once the click event is triggered.

button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}

button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}

This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a tag.

How to use CSS:

You can use :focus too. :focus would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus to make the buttons change.

What JS would do:

The JavaScript's jQuery library is going to help us for this code. Here is the example:

$('button').click(function () {
  $(this).css('border', '1px solid red');
}

This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:

$('button').click(function () {
  $(this).css('border', '1px solid red');
  // find any other button with a specific id, and change it back to white like
  $('button#red').css('border', '1px solid white');
}

This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)

Hope you get the answer. Good luck! Cheers.

Is there a command line utility for rendering GitHub flavored Markdown?

I wrote a small CLI in Python and added GFM support. It's called Grip (Github Readme Instant Preview).

Install it with:

$ pip install grip

And to use it, simply:

$ grip

Then visit localhost:5000 to view the readme.md file at that location.

You can also specify your own file:

$ grip CHANGES.md

And change port:

$ grip 8080

And of course, specifically render GitHub-Flavored Markdown, optionally with repository context:

$ grip --gfm --context=username/repo issue.md

Notable features:

  • Renders pages to appear exactly like on GitHub
  • Fenced blocks
  • Python API
  • Navigate between linked files (thanks, vladwing!) added in 2.0
  • Export to a single file (thanks, iliggio!) added in 2.0
  • New: Read from stdin and export to stdout added in 3.0

Hope this helps someone here. Check it out.

Matching a space in regex

It seems to me like using a REGEX in this case would just be overkill. Why not just just strpos to find the space character. Also, there's nothing special about the space character in regular expressions, you should be able to search for it the same as you would search for any other character. That is, unless you disabled pattern whitespace, which would hardly be necessary in this case.

How to dismiss keyboard iOS programmatically when pressing return

The simple way is to connect the delegate of UITextField to self (self.mytestField.delegate = self) and dismiss the keyboard in the method textFieldShouldReturn using [textField resignFirstResponder];

Another way to dismiss the keyboard is the following:

Objective-C

[self.view endEditing:YES];

Swift:

self.view.endEditing(true)

Put [self.view endEditing:YES]; where you would like to dismiss the keyboard (Button event, Touch event, etc.).

Redirect from asp.net web api post action

You can check this

[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{

   string url = "https://localhost:44305/Templates/ReportPage.html";

   System.Uri uri = new System.Uri(url);

   return Redirect(uri);
}

How to convert std::string to lower case?

Since none of the answers mentioned the upcoming Ranges library, which is available in the standard library since C++20, and currently separately available on GitHub as range-v3, I would like to add a way to perform this conversion using it.

To modify the string in-place:

str |= action::transform([](unsigned char c){ return std::tolower(c); });

To generate a new string:

auto new_string = original_string
    | view::transform([](unsigned char c){ return std::tolower(c); });

(Don't forget to #include <cctype> and the required Ranges headers.)

Note: the use of unsigned char as the argument to the lambda is inspired by cppreference, which states:

Like all other functions from <cctype>, the behavior of std::tolower is undefined if the argument's value is neither representable as unsigned char nor equal to EOF. To use these functions safely with plain chars (or signed chars), the argument should first be converted to unsigned char:

char my_tolower(char ch)
{
    return static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}

Similarly, they should not be directly used with standard algorithms when the iterator's value type is char or signed char. Instead, convert the value to unsigned char first:

std::string str_tolower(std::string s) {
    std::transform(s.begin(), s.end(), s.begin(), 
                // static_cast<int(*)(int)>(std::tolower)         // wrong
                // [](int c){ return std::tolower(c); }           // wrong
                // [](char c){ return std::tolower(c); }          // wrong
                   [](unsigned char c){ return std::tolower(c); } // correct
                  );
    return s;
}

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

You can use karma-jasmine plugin to set the default time out interval globally.

Add this config in karma.conf.js

module.exports = function(config) {
  config.set({
    client: {
      jasmine: {
        timeoutInterval: 10000
      }
    }
  })
}

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How to test REST API using Chrome's extension "Advanced Rest Client"

From the screenshot I can see that you want to pass "user" and "password" values to the service. You have send the parameter values in the request header part which is wrong. The values are sent in the request body and not in the request header. Also your syntax is wrong. Correct syntax is: {"user":"user_val","password":"password_val"}. Also check what is the the content type. It should match with the content type you have set to your service.

Git error: "Host Key Verification Failed" when connecting to remote repository

If you are using git for Windows.

  • Open the git GUI.
  • Open the local git repository in git GUI.
  • Add the remote or push if the remote already exists.
  • Answer "yes" to the question about whether you want to continue.

The GUI client adds the key for you to ~/.ssh/known_hosts. This is easier to remember if you don't do it often and also avoids the need to use the git command line (the standard Windows command lines don't have the ssh-keyscan executable.

Pass object to javascript function

function myFunction(arg) {
    alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}

myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });

How to call code behind server method from a client side JavaScript function?

// include jquery.js
//javascript function
var a1="aaa";
var b1="bbb";
                         **pagename/methodname**     *parameters*
CallServerFunction("Default.aspx/FunPubGetTasks", "{a:'" + a1+ "',b:'" + b1+ "'}",
            function(result)
            {

            }
);
function CallServerFunction(StrPriUrl,ObjPriData,CallBackFunction)
 {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        dataType: "json",
        success: function(result) 
        {
            if(CallBackFunction!=null && typeof CallBackFunction !='undefined')
            {
                CallBackFunction(result);
            }

        },
        error: function(result) 
        {
            alert('error occured');
            alert(result.responseText);
            window.location.href="FrmError.aspx?Exception="+result.responseText;
        },
        async: true
    });
 }

//page name is Default.aspx & FunPubGetTasks method
///your code behind function
     [System.Web.Services.WebMethod()]
        public static object FunPubGetTasks(string a, string b)
        {
            //return Ienumerable or array   
        }

How to detect orientation change in layout in Android?

In case this is of use to some newer dev's because its not specified above. Just to be very explicit:

You need two things if using onConfigurationChanged:

  1. An onConfigurationChanged method in your Activity Class

  2. Specify in your manifest which configuration changes will be handled by your onConfigurationChanged method

The manifest snippet in the above answers, while no doubt correct for the particular app that manifest belongs to, is NOT exactly what you need to add in your manifest to trigger the onConfigurationChanged method in your Activity Class. i.e. the below manifest entry may not be correct for your app.

<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>

In the above manifest entry, there are various Android actions for android:configChanges="" which can trigger the onCreate in your Activity lifecycle.

This is very important - The ones NOT Specified in the manifest are the ones that trigger your onCreate and The ones specified in the manifest are the ones that trigger your onConfigurationChanged method in your Activity Class.

So you need to identify which config changes you need to handle yourself. For the Android Encyclopedically Challenged like me, I used the quick hints pop-out in Android Studio and added in almost every possible configuration option. Listing all of these basically said that I would handle everything and onCreate will never be called due to configurations.

<activity name= ".MainActivity" android:configChanges="screenLayout|touchscreen|mnc|mcc|density|uiMode|fontScale|orientation|keyboard|layoutDirection|locale|navigation|smallestScreenSize|keyboardHidden|colorMode|screenSize"/>

Now obviously I don't want to handle everything, so I began eliminating the above options one at a time. Re-building and testing my app after each removal.

Another important point: If there is just one configuration option being handled automatically that triggers your onCreate (You do not have it listed in your manifest above), then it will appear like onConfigurationChanged is not working. You must put all relevant ones into your manifest.

I ended up with 3 that were triggering onCreate originally, then I tested on an S10+ and I was still getting the onCreate, so I had to do my elimination exercise again and I also needed the |screenSize. So test on a selection of platforms.

<activity name= ".MainActivity" android:configChanges="screenLayout|uiMode|orientation|screenSize"/>

So my suggestion, although I'm sure someone can poke holes in this:

  1. Add your onConfigurationChanged method in your Activity Class with a TOAST or LOG so you can see when its working.

  2. Add all possible configuration options to your manifest.

  3. Confirm your onConfigurationChanged method is working by testing your app.

  4. Remove each config option from your manifest file one at a time, testing your app after each.

  5. Test on as large a variety of devices as possible.

  6. Do not copy/paste my snippet above to your manifest file. Android updates change the list, so use the pop-out Android Studio hints to make sure you get them all.

I hope this saves someone some time.

My onConfigurationChanged method just for info below. onConfigurationChanged is called in the lifecycle after the new orientation is available, but before the UI has been recreated. Hence my first if to check the orientation works correctly, and then the 2nd nested if to look at the visibility of my UI ImageView also works correctly.

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            pokerCardLarge = findViewById(R.id.pokerCardLgImageView);

            if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
                Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
                pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
                pokerCardLarge.setImageBitmap(image);
            }

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            pokerCardLarge = findViewById(R.id.pokerCardLgImageView);

            if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
                Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
                pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
                pokerCardLarge.setImageBitmap(image);
            }

        }
    }

Creating a list of objects in Python

I think this simply demonstrates what you are trying to achieve:

# coding: utf-8

class Class():
    count = 0
    names = []

    def __init__(self,name):
        self.number = Class.count
        self.name = name
        Class.count += 1
        Class.names.append(name)

l=[]
l.append(Class("uno"))
l.append(Class("duo"))
print l
print l[0].number, l[0].name
print l[1].number, l[1].name
print Class.count, Class.names

Run the code above and you get:-

[<__main__.Class instance at 0x6311b2c>, 
<__main__.Class instance at 0x63117ec>]
0 uno
1 duo
2 ['uno', 'duo']

How to copy folders to docker image from Dockerfile?

the simplest way:

sudo docker cp path/on/your/machine adam_ubuntu:/root/path_in_container

Note putting into the root path if you are copying something that needs to be picked up by the root using ~.

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

How to compile LEX/YACC files on Windows?

I was having the same problem, it has a very simple solution.
Steps for executing the 'Lex' program:

  1. Tools->'Lex File Compiler'
  2. Tools->'Lex Build'
  3. Tools->'Open CMD'
  4. Then in command prompt type 'name_of_file.exe' example->'1.exe'
  5. Then entering the whole input press Ctrl + Z and press Enter.

Example

Class Not Found Exception when running JUnit test

I faced the same problem and I was able to fix it using @slomek's answer but the issue resurfaced after that.

I finally fixed it by adding my project's output folder to the JUnit test's run configuration. Steps are:

  • Find your project's output folder from Project properties -> Java Build Path -> Default output folder
    • Usually this is <project-folder>/bin
  • Go to Run -> Run Configurations...
  • Click on the unit test's run configuration and click on the Classpath tab
  • Explicitly add your project's output folder under User Entries - even if the project is already included there
    • Click on Advanced -> Add folder to add the output folder

This issue might be due to weird project setup in Eclipse - e.g. source folder with nested maven projects imported as a single project/folder (at least that was how my project was setup).

The executable was signed with invalid entitlements

I also spent several hours fighting with this as well. The fix is real simple. Edit your Entitlements.plist file in the root of your project's directory. Find the line that says <key>get-task-allow</key>. Underneath it should be <false/>. Change that to <true/>.

Android getText from EditText field

Try out this will solve ur problem ....

EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();

How to test if a string is basically an integer in quotes using Ruby

Ruby 2.6.0 enables casting to an integer without raising an exception, and will return nil if the cast fails. And since nil mostly behaves like false in Ruby, you can easily check for an integer like so:

if Integer(my_var, exception: false)
  # do something if my_var can be cast to an integer
end

How to sort the letters in a string alphabetically in Python

You can do:

>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

  • With Jenkins CLI you do not have to reload everything - you just can load the job (update-job command). You can't use tokens with CLI, AFAIK - you have to use password or password file.

  • Token name for user can be obtained via http://<jenkins-server>/user/<username>/configure - push on 'Show API token' button.

  • Here's a link on how to use API tokens (it uses wget, but curl is very similar).

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

Avoid using

RETURN

statement when you are using

BEGIN TRY
    ... 
END TRY

BEGIN CATCH
    ...
END CATCH

and

BEGIN, COMMIT & ROLLBACK

statements in SQL stored procedures

Truncating a table in a stored procedure

All DDL statements in Oracle PL/SQL should use Execute Immediate before the statement. Hence you should use:

execute immediate 'truncate table schema.tablename';

Certificate has either expired or has been revoked

A simple "Clean" (Shift(?)+Command(?)+K) solved to me

Copy existing project with a new name in Android Studio

Go to the source folder where your project is.

  1. Copy the project and past and change the name.
  2. Open Android Studio and refresh.
  3. Go to ->Settings.gradle.
  4. Include ':your new project name '

How to create a List with a dynamic object type

Just use dynamic as the argument:

var list = new List<dynamic>();

MySQL Error #1133 - Can't find any matching row in the user table

To expound on Stephane's answer.

I got this error when I tried to grant remote connections privileges of a particular database to a root user on MySQL server by running the command:

USE database_name;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';

This gave an error:

ERROR 1133 (42000): Can't find any matching row in the user table

Here's how I fixed it:

First, confirm that your MySQL server allows for remote connections. Use your preferred text editor to open the MySQL server configuration file:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Scroll down to the bind-address line and ensure that is either commented out or replaced with 0.0.0.0 (to allow all remote connections) or replaced with Ip-Addresses that you want remote connections from.

Once you make the necessary changes, save and exit the configuration file. Apply the changes made to the MySQL config file by restarting the MySQL service:

sudo systemctl restart mysql

Next, log into the MySQL server console on the server it was installed:

mysql -u root -p

Enter your mysql user password

Check the hosts that the user you want has access to already. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| localhost |
+-----------+

Next, I ran the command below which is similar to the previous one that was throwing errors, but notice that I added a password to it this time:

USE database_name;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'my-password';

Note: % grants a user remote access from all hosts on a network. You can specify the Ip-Address of the individual hosts that you want to grant the user access from using the command - GRANT ALL PRIVILEGES ON *.* TO 'root'@'Ip-Address' IDENTIFIED BY 'my-password';

Afterwhich I checked the hosts that the user now has access to. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| %         |
| localhost |
+-----------+

Finally, you can try connecting to the MySQL server from another server using the command:

mysql -u username -h mysql-server-ip-address -p

Where u represents user, h represents mysql-server-ip-address and p represents password. So in my case it was:

mysql -u root -h 34.69.261.158 -p

Enter your mysql user password

You should get this output depending on your MySQL server version:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Resources: How to Allow Remote Connections to MySQL

That's all.

I hope this helps

Converting string to byte array in C#

The following approach will work only if the chars are 1 byte. (Default unicode will not work since it is 2 bytes)

public static byte[] ToByteArray(string value)
{            
    char[] charArr = value.ToCharArray();
    byte[] bytes = new byte[charArr.Length];
    for (int i = 0; i < charArr.Length; i++)
    {
        byte current = Convert.ToByte(charArr[i]);
        bytes[i] = current;
    }

    return bytes;
}

Keeping it simple

"Could not find or load main class" Error while running java program using cmd prompt

I was getting the exact same error for forgetting to remove the .class extension when running the JAVA class. So instead of this:

java myClass.class

One should do this:

java myClass

no overload for matches delegate 'system.eventhandler'

You need to change public void klik(PaintEventArgs pea, EventArgs e) to public void klik(object sender, System.EventArgs e) because there is no Click event handler with parameters PaintEventArgs pea, EventArgs e.

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

I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.

 $(this).siblings(':not(.closedTab)');

Concat all strings inside a List<string> using LINQ

You can simply use:

List<string> items = new List<string>() { "foo", "boo", "john", "doe" };

Console.WriteLine(string.Join(",", items));

Happy coding!

Is there a limit on an Excel worksheet's name length?

Renaming a worksheet manually in Excel, you hit a limit of 31 chars, so I'd suggest that that's a hard limit.

cout is not a member of std

I had a similar issue and it turned out that i had to add an extra entry in cmake to include the files.

Since i was also using the zmq library I had to add this to the included libraries as well.

Android: disabling highlight on listView click

Nothing helps me but this:

transparent_drawable.xml:

<?xml version="1.0" encoding="utf-8"?>    
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#00000000"/>
</shape>

layout.xml:

android:listSelector="@drawable/transparent_drawable"

Reflection generic get field value

You are calling get with the wrong argument.

It should be:

Object value = field.get(object);

JavaScript string encryption and decryption?

The existing answers which leverage SJCL, CryptoJS, and/or WebCrypto aren't necessarily wrong but they're not as safe as you might initially suspect. Generally you want to use libsodium. First I'll explain why, then how.

Why Not SJCL, CryptoJS, WebCrypto, etc.?

Short answer: In order for your encryption to actually be secure, these libraries expect you to make too many choices e.g. the block cipher mode (CBC, CTR, GCM; if you can't tell which of the three I just listed is secure to use and under what constraints, you shouldn't be burdened with this sort of choice at all).

Unless your job title is cryptography engineer, the odds are stacked against you implementing it securely.

Why to Avoid CryptoJS?

CryptoJS offers a handful of building blocks and expects you to know how to use them securely. It even defaults to CBC mode (archived).

Why is CBC mode bad?

Read this write-up on AES-CBC vulnerabilities.

Why to Avoid WebCrypto?

WebCrypto is a potluck standard, designed by committee, for purposes that are orthogonal to cryptography engineering. Specifically, WebCrypto was meant to replace Flash, not provide security.

Why to Avoid SJCL?

SJCL's public API and documentation begs users to encrypt data with a human-remembered password. This is rarely, if ever, what you want to do in the real world.

Additionally: Its default PBKDF2 round count is roughly 86 times as small as you want it to be. AES-128-CCM is probably fine.

Out of the three options above, SJCL is the least likely to end in tears. But there are better options available.

Why is Libsodium Better?

You don't need to choose between a menu of cipher modes, hash functions, and other needless options. You'll never risk screwing up your parameters and removing all security from your protocol.

Instead, libsodium just gives you simple options tuned for maximum security and minimalistic APIs.

  • crypto_box() / crypto_box_open() offer authenticated public-key encryption.
    • The algorithm in question combines X25519 (ECDH over Curve25519) and XSalsa20-Poly1305, but you don't need to know (or even care) about that to use it securely
  • crypto_secretbox() / crypto_secretbox_open() offer shared-key authenticated encryption.
    • The algorithm in question is XSalsa20-Poly1305, but you don't need to know/care

Additionally, libsodium has bindings in dozens of popular programming languages, so it's very likely that libsodium will just work when trying to interoperate with another programming stack. Also, libsodium tends to be very fast without sacrificing security.

How to Use Libsodium in JavaScript?

First, you need to decide one thing:

  1. Do you just want to encrypt/decrypt data (and maybe still somehow use the plaintext in database queries securely) and not worry about the details? Or...
  2. Do you need to implement a specific protocol?

If you selected the first option, get CipherSweet.js.

The documentation is available online. EncryptedField is sufficient for most use cases, but the EncryptedRow and EncryptedMultiRows APIs may be easier if you have a lot of distinct fields you want to encrypt.

With CipherSweet, you don't need to even know what a nonce/IV is to use it securely.

Additionally, this handles int/float encryption without leaking facts about the contents through ciphertext size.

Otherwise, you'll want sodium-plus, which is a user-friendly frontend to various libsodium wrappers. Sodium-Plus allows you to write performant, asynchronous, cross-platform code that's easy to audit and reason about.

To install sodium-plus, simply run...

npm install sodium-plus

There is currently no public CDN for browser support. This will change soon. However, you can grab sodium-plus.min.js from the latest Github release if you need it.

_x000D_
_x000D_
const { SodiumPlus } = require('sodium-plus');_x000D_
let sodium;_x000D_
_x000D_
(async function () {_x000D_
    if (!sodium) sodium = await SodiumPlus.auto();_x000D_
    let plaintext = 'Your message goes here';_x000D_
    let key = await sodium.crypto_secretbox_keygen();_x000D_
    let nonce = await sodium.randombytes_buf(24);_x000D_
    let ciphertext = await sodium.crypto_secretbox(_x000D_
        plaintext,_x000D_
        nonce,_x000D_
        key    _x000D_
    );_x000D_
    console.log(ciphertext.toString('hex'));_x000D_
_x000D_
    let decrypted = await sodium.crypto_secretbox_open(_x000D_
        ciphertext,_x000D_
        nonce,_x000D_
        key_x000D_
    );_x000D_
_x000D_
    console.log(decrypted.toString());_x000D_
})();
_x000D_
_x000D_
_x000D_

The documentation for sodium-plus is available on Github.

If you'd like a step-by-step tutorial, this dev.to article has what you're looking for.

Checkout one file from Subversion

Use svn cat or svn export.

For that, you don't need to fetch the working directory, but you will not be able to commit any changes you make. If you need to make changes and commit them, you need a working directory, but you don't have to fetch it completely. Checkout the revision where the directory was still/almost empty, and then use 'svn cat' to extract the file from HEAD.

How to implement a SQL like 'LIKE' operator in java?

Yes, this could be done with a regular expression. Keep in mind that Java's regular expressions have different syntax from SQL's "like". Instead of "%", you would have ".*", and instead of "?", you would have ".".

What makes it somewhat tricky is that you would also have to escape any characters that Java treats as special. Since you're trying to make this analogous to SQL, I'm guessing that ^$[]{}\ shouldn't appear in the regex string. But you will have to replace "." with "\\." before doing any other replacements. (Edit: Pattern.quote(String) escapes everything by surrounding the string with "\Q" and "\E", which will cause everything in the expression to be treated as a literal (no wildcards at all). So you definitely don't want to use it.)

Furthermore, as Dave Webb says, you also need to ignore case.

With that in mind, here's a sample of what it might look like:

public static boolean like(String str, String expr) {
    expr = expr.toLowerCase(); // ignoring locale for now
    expr = expr.replace(".", "\\."); // "\\" is escaped to "\" (thanks, Alan M)
    // ... escape any other potentially problematic characters here
    expr = expr.replace("?", ".");
    expr = expr.replace("%", ".*");
    str = str.toLowerCase();
    return str.matches(expr);
}

Printing without newline (print 'a',) prints a space, how to remove?

You can suppress the space by printing an empty string to stdout between the print statements.

>>> import sys
>>> for i in range(20):
...   print 'a',
...   sys.stdout.write('')
... 
aaaaaaaaaaaaaaaaaaaa

However, a cleaner solution is to first build the entire string you'd like to print and then output it with a single print statement.

Docker error : no space left on device

I went to the docker settings and changed the image space available. It reached the limit while creating the new image with docker build. So I just increased the amount available.

Image from MacOS docker dashboard

printf not printing on console

As others have pointed out, output can be buffered within your program before a console or shell has a chance to see it.

On unix-like systems, including macs, stdout has line-based buffering by default. This means that your program empties its stdout buffer as soon as it sees a newline.

However, on windows, newlines are no longer special, and full buffering is used. Windows doesn't support line buffering at all; see the msdn page on setvbuf.

So on windows, a good approach is to completely shut off stdout buffering like so:

setvbuf (stdout, NULL, _IONBF, 0);

JWT authentication for ASP.NET Web API

Here's a very minimal and secure implementation of a Claims based Authentication using JWT token in an ASP.NET Core Web API.

first of all, you need to expose an endpoint that returns a JWT token with claims assigned to a user:

 /// <summary>
        /// Login provides API to verify user and returns authentication token.
        /// API Path:  api/account/login
        /// </summary>
        /// <param name="paramUser">Username and Password</param>
        /// <returns>{Token: [Token] }</returns>
        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login([FromBody] UserRequestVM paramUser, CancellationToken ct)
        {

            var result = await UserApplication.PasswordSignInAsync(paramUser.Email, paramUser.Password, false, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                UserRequestVM request = new UserRequestVM();
                request.Email = paramUser.Email;


                ApplicationUser UserDetails = await this.GetUserByEmail(request);
                List<ApplicationClaim> UserClaims = await this.ClaimApplication.GetListByUser(UserDetails);

                var Claims = new ClaimsIdentity(new Claim[]
                                {
                                    new Claim(JwtRegisteredClaimNames.Sub, paramUser.Email.ToString()),
                                    new Claim(UserId, UserDetails.UserId.ToString())
                                });


                //Adding UserClaims to JWT claims
                foreach (var item in UserClaims)
                {
                    Claims.AddClaim(new Claim(item.ClaimCode, string.Empty));
                }

                var tokenHandler = new JwtSecurityTokenHandler();
                  // this information will be retrived from you Configuration
                //I have injected Configuration provider service into my controller
                var encryptionkey = Configuration["Jwt:Encryptionkey"];
                var key = Encoding.ASCII.GetBytes(encryptionkey);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Issuer = Configuration["Jwt:Issuer"],
                    Subject = Claims,

                // this information will be retrived from you Configuration
                //I have injected Configuration provider service into my controller
                    Expires = DateTime.UtcNow.AddMinutes(Convert.ToDouble(Configuration["Jwt:ExpiryTimeInMinutes"])),

                    //algorithm to sign the token
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)

                };

                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                return Ok(new
                {
                    token = tokenString
                });
            }

            return BadRequest("Wrong Username or password");
        }

now you need to Add Authentication to your services in your ConfigureServices inside your startup.cs to add JWT authentication as your default authentication service like this:

services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
             .AddJwtBearer(cfg =>
             {
                 cfg.RequireHttpsMetadata = false;
                 cfg.SaveToken = true;
                 cfg.TokenValidationParameters = new TokenValidationParameters()
                 {
                     //ValidateIssuerSigningKey = true,
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Encryptionkey"])),
                     ValidateAudience = false,
                     ValidateLifetime = true,
                     ValidIssuer = configuration["Jwt:Issuer"],
                     //ValidAudience = Configuration["Jwt:Audience"],
                     //IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Key"])),
                 };
             });

now you can add policies to your authorization services like this:

services.AddAuthorization(options =>
            {
                options.AddPolicy("YourPolicyNameHere",
                                policy => policy.RequireClaim("YourClaimNameHere"));
            });

ALTERNATIVELY, You can also (not necessary) populate all of your claims from your database as this will only run once on your application startup and add them to policies like this:

  services.AddAuthorization(async options =>
            {
                var ClaimList = await claimApplication.GetList(applicationClaim);
                foreach (var item in ClaimList)
                {                        
                    options.AddPolicy(item.ClaimCode, policy => policy.RequireClaim(item.ClaimCode));                       
                }
            });

now you can put the Policy filter on any of the methods that you want to be authorized like this:

 [HttpPost("update")]
        [Authorize(Policy = "ACC_UP")]
        public async Task<IActionResult> Update([FromBody] UserRequestVM requestVm, CancellationToken ct)
        {
//your logic goes here
}

Hope this helps

How to create a function in SQL Server

You can use stuff in place of replace for avoiding the bug that Hamlet Hakobyan has mentioned

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250)) 
RETURNS VARCHAR(250) 
AS BEGIN
   DECLARE @Work VARCHAR(250)
   SET @Work = @Input

   --SET @Work = REPLACE(@Work, 'www.', '')
   SET @Work = Stuff(@Work,1,4, '')
   SET @Work = REPLACE(@Work, '.com', '')

   RETURN @work 
END

c# Image resizing to different size while preserving aspect ratio

// This allows us to resize the image. It prevents skewed images and 
// also vertically long images caused by trying to maintain the aspect 
// ratio on images who's height is larger than their width

public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)

{
    System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

    // Prevent using images internal thumbnail
    FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
    FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

    if (OnlyResizeIfWider)
    {
        if (FullsizeImage.Width <= NewWidth)
        {
            NewWidth = FullsizeImage.Width;
        }
    }

    int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
    if (NewHeight > MaxHeight)
    {
        // Resize with height instead
        NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
        NewHeight = MaxHeight;
    }

    System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

    // Clear handle to original file so that we can overwrite it if necessary
    FullsizeImage.Dispose();

    // Save resized picture
    NewImage.Save(NewFile);
}

Preserve Line Breaks From TextArea When Writing To MySQL

Two solutions for this:

  1. PHP function nl2br():

    e.g.,

    echo nl2br("This\r\nis\n\ra\nstring\r");
    
    // will output
    This<br />
    is<br />
    a<br />
    string<br />
    
  2. Wrap the input in <pre></pre> tags.

    See: W3C Wiki - HTML/Elements/pre

How do you clear your Visual Studio cache on Windows Vista?

I experienced this today. The value in Config was the updated one but the application would return the older value, stop and starting the solution did nothing.

So I cleared the .Net Temp folder.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

It shouldn't create bugs but to be safe close your solution down first. Clear the Temporary ASP.NET Files then load up your solution.

My issue was sorted.

Java SecurityException: signer information does not match

This happens when classes belonging to the same package are loaded from different JAR files, and those JAR files have signatures signed with different certificates - or, perhaps more often, at least one is signed and one or more others are not (which includes classes loaded from directories since those AFAIK cannot be signed).

So either make sure all JARs (or at least those which contain classes from the same packages) are signed using the same certificate, or remove the signatures from the manifest of JAR files with overlapping packages.

Critical t values in R

The code you posted gives the critical value for a one-sided test (Hence the answer to you question is simply:

abs(qt(0.25, 40)) # 75% confidence, 1 sided (same as qt(0.75, 40))
abs(qt(0.01, 40)) # 99% confidence, 1 sided (same as qt(0.99, 40))

Note that the t-distribution is symmetric. For a 2-sided test (say with 99% confidence) you can use the critical value

abs(qt(0.01/2, 40)) # 99% confidence, 2 sided

Add jars to a Spark Job - spark-submit

Another approach in spark 2.1.0 is to use --conf spark.driver.userClassPathFirst=true during spark-submit which changes the priority of dependency load, and thus the behavior of the spark-job, by giving priority to the jars the user is adding to the class-path with the --jars option.

In Typescript, How to check if a string is Numeric

I would choose an existing and already tested solution. For example this from rxjs in typescript:

function isNumeric(val: any): val is number | string {
  // parseFloat NaNs numeric-cast false positives (null|true|false|"")
  // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  // subtraction forces infinities to NaN
  // adding 1 corrects loss of precision from parseFloat (#15100)
  return !isArray(val) && (val - parseFloat(val) + 1) >= 0;
}

rxjs/isNumeric.ts

Without rxjs isArray() function and with simplefied typings:

function isNumeric(val: any): boolean {
  return !(val instanceof Array) && (val - parseFloat(val) + 1) >= 0;
}

You should always test such functions with your use cases. If you have special value types, this function may not be your solution. You can test the function here.

Results are:

enum         : CardTypes.Debit   : true
decimal      : 10                : true
hexaDecimal  : 0xf10b            : true
binary       : 0b110100          : true
octal        : 0o410             : true
stringNumber : '10'              : true

string       : 'Hello'           : false
undefined    : undefined         : false
null         : null              : false
function     : () => {}          : false
array        : [80, 85, 75]      : false
turple       : ['Kunal', 2018]   : false
object       : {}                : false

As you can see, you have to be careful, if you use this function with enums.

Disabling user input for UITextfield in swift

Try this:

Swift 2.0:

textField.userInteractionEnabled = false

Swift 3.0:

textField.isUserInteractionEnabled = false

Or in storyboard uncheck "User Interaction Enabled"

enter image description here

How to generate List<String> from SQL query?

If you would like to query all columns

List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
    cn.Open();
    MySqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        list_users.Add(new Users(dr));
    }
}
catch { /* error */ }
finally { cn.Close(); }

The User's constructor would do all the "dr.GetString(i)"

Cast Int to enum in Java

If you want to give your integer values, you can use a structure like below

public enum A
{
        B(0),
        C(10),
        None(11);
        int id;
        private A(int i){id = i;}

        public int GetID(){return id;}
        public boolean IsEmpty(){return this.equals(A.None);}
        public boolean Compare(int i){return id == i;}
        public static A GetValue(int _id)
        {
            A[] As = A.values();
            for(int i = 0; i < As.length; i++)
            {
                if(As[i].Compare(_id))
                    return As[i];
            }
            return A.None;
        }
}

Replace image src location using CSS

You can use a background image

_x000D_
_x000D_
.application-title img {_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
  box-sizing:border-box;_x000D_
  padding-left: 200px;_x000D_
  /*width of the image*/_x000D_
  background: url(http://lorempixel.com/200/200/city/2) left top no-repeat;_x000D_
}
_x000D_
<div class="application-title">_x000D_
  <img src="http://lorempixel.com/200/200/city/1/">_x000D_
</div><br />_x000D_
Original Image: <br />_x000D_
_x000D_
<img src="http://lorempixel.com/200/200/city/1/">
_x000D_
_x000D_
_x000D_

get path for my .exe

in visualstudio 2008 you could use this code :

   var _assembly = System.Reflection.Assembly
               .GetExecutingAssembly().GetName().CodeBase;

   var _path = System.IO.Path.GetDirectoryName(_assembly) ;

How to set a cell to NaN in a pandas dataframe

You can try these snippets.

In [16]:mydata = {'x' : [10, 50, 18, 32, 47, 20], 'y' : ['12', '11', 'N/A', '13', '15', 'N/A']}
In [17]:df=pd.DataFrame(mydata)

In [18]:df.y[df.y=="N/A"]=np.nan

Out[19]:df 
    x    y
0  10   12
1  50   11
2  18  NaN
3  32   13
4  47   15
5  20  NaN

How to make all controls resize accordingly proportionally when window is maximized?

Well, it's fairly simple to do.

On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.

Here's the code:

private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            myCanvas.Width = e.NewSize.Width;
            myCanvas.Height = e.NewSize.Height;

            double xChange = 1, yChange = 1;

            if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width/e.PreviousSize.Width);

            if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

            foreach (FrameworkElement fe in myCanvas.Children )
            {   
                /*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */            
                if (fe is Grid == false)
                {
                    fe.Height = fe.ActualHeight * yChange;
                    fe.Width = fe.ActualWidth * xChange;

                    Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
                    Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);

                }
            }
        }

how to configure config.inc.php to have a loginform in phpmyadmin

First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php) will display an identification form, asking for a login and password.

To get that form, you should not use :

$cfg['Servers'][$i]['auth_type'] = 'config';

But you should use :

$cfg['Servers'][$i]['auth_type'] = 'cookie';

(At least, that's what I have on a server which prompts for login/password, using a form)


For more informations, you can take a look at the documentation :

'config' authentication ($auth_type = 'config') is the plain old way: username and password are stored in config.inc.php.

'cookie' authentication mode ($auth_type = 'cookie') as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Inserting data into a temporary table

All the above mentioned answers will almost fullfill the purpose. However, You need to drop the temp table after all the operation on it. You can follow-

INSERT INTO #TempTable (ID, Date, Name) SELECT id, date, name FROM physical_table;

IF OBJECT_ID('tempdb.dbo.#TempTable') IS NOT NULL DROP TABLE #TempTable;

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

I found that if the value passed is a string type, it must be followed by 'px' (i.e. 90px), where if the value is an integer, it will append the px automatically. the width and height properties are more forgiving (either type works).

var x = "90";
var y = "120"
$(selector).css( { left: x, top: y } )        //doesn't work
$(selector).css( { left: x + "px", top: y + "px" } )        //does work

x = 90;
y = 120;
$(selector).css( { left: x, top: y } )        //does work

How can I check if string contains characters & whitespace, not just whitespace?

I've used the following method to detect if a string contains only whitespace. It also matches empty strings.

if (/^\s*$/.test(myStr)) {
  // the string contains only whitespace
}

How to Identify Microsoft Edge browser via CSS?

More accurate for Edge (do not include latest IE 15) is:

@supports (display:-ms-grid) { ... }

@supports (-ms-ime-align:auto) { ... } works for all Edge versions (currently up to IE15).

How can I get a favicon to show up in my django app?

Just copy your favicon on: /yourappname/mainapp(ex:core)/static/mainapp(ex:core)/img

Then go to your mainapp template(ex:base.html) and just copy this, after {% load static %} because you must load first the statics.

<link href="{% static 'core/img/favi_x.png' %}" rel="shortcut icon" type="image/png" />

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

I was getting this error attempting to run "php artisan migrate" on Windows with a virtual box / vagrant / homestead installation.

The documentation said I had to run this command on the virtual machine.

This worked!!!

make sure to do it inside your current project folder.

Download single files from GitHub

You can use the V3 API to get a raw file like this (you'll need an OAuth token):

curl -H 'Authorization: token INSERTACCESSTOKENHERE' -H 'Accept: application/vnd.github.v3.raw' -O -L https://api.github.com/repos/*owner*/*repo*/contents/*path*

All of this has to go on one line. The -O option saves the file in the current directory. You can use -o filename to specify a different filename.

To get the OAuth token follow the instructions here: https://help.github.com/articles/creating-an-access-token-for-command-line-use

I've written this up as a gist as well: https://gist.github.com/madrobby/9476733

What is lexical scope?

Lets try the shortest possible definition:

Lexical Scoping defines how variable names are resolved in nested functions: inner functions contain the scope of parent functions even if the parent function has returned.

That is all there is to it!

scp from Linux to Windows

Here is the solution to copy files from Linux to Windows using SCP without password by ssh:

  1. Install sshpass in Linux machine to skip password prompt

  2. Script

    sshpass -p 'xxxxxxx' scp /home/user1/*.* [email protected]:/d/test/

Details:

sshpass -p 'password' scp /source_path/*.* windowsusername@windowsMachine_ip:/destination_drive/subfolder/

How to differ sessions in browser-tabs?

You can use link-rewriting to append a unique identifier to all your URLs when starting at a single page (e.g. index.html/jsp/whatever). The browser will use the same cookies for all your tabs so everything you put in cookies will not be unique.

WPF binding to Listbox selectedItem

Inside the DataTemplate you're working in the context of a Rule, that's why you cannot bind to SelectedRule.Name -- there is no such property on a Rule. To bind to the original data context (which is your ViewModel) you can write:

<TextBlock Text="{Binding ElementName=lbRules, Path=DataContext.SelectedRule.Name}" />

UPDATE: regarding the SelectedItem property binding, it looks perfectly valid, I tried the same on my machine and it works fine. Here is my full test app:

XAML:

<Window x:Class="TestWpfApplication.ListBoxSelectedItem"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ListBoxSelectedItem" Height="300" Width="300"
    xmlns:app="clr-namespace:TestWpfApplication">
    <Window.DataContext>
        <app:ListBoxSelectedItemViewModel/>
    </Window.DataContext>
    <ListBox ItemsSource="{Binding Path=Rules}" SelectedItem="{Binding Path=SelectedRule, Mode=TwoWay}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="Name:" />
                    <TextBox Text="{Binding Name}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>

Code behind:

namespace TestWpfApplication
{
    /// <summary>
    /// Interaction logic for ListBoxSelectedItem.xaml
    /// </summary>
    public partial class ListBoxSelectedItem : Window
    {
        public ListBoxSelectedItem()
        {
            InitializeComponent();
        }
    }


    public class Rule
    {
        public string Name { get; set; }
    }

    public class ListBoxSelectedItemViewModel
    {
        public ListBoxSelectedItemViewModel()
        {
            Rules = new ObservableCollection<Rule>()
            {
                new Rule() { Name = "Rule 1"},
                new Rule() { Name = "Rule 2"},
                new Rule() { Name = "Rule 3"},
            };
        }

        public ObservableCollection<Rule> Rules { get; private set; }

        private Rule selectedRule;
        public Rule SelectedRule
        {
            get { return selectedRule; }
            set
            {
                selectedRule = value;
            }
        }
    }
}

Add text at the end of each line

If you'd like to add text at the end of each line in-place (in the same file), you can use -i parameter, for example:

sed -i'.bak' 's/$/:80/' foo.txt

However -i option is non-standard Unix extension and may not be available on all operating systems.

So you can consider using ex (which is equivalent to vi -e/vim -e):

ex +"%s/$/:80/g" -cwq foo.txt

which will add :80 to each line, but sometimes it can append it to blank lines.

So better method is to check if the line actually contain any number, and then append it, for example:

ex  +"g/[0-9]/s/$/:80/g" -cwq foo.txt

If the file has more complex format, consider using proper regex, instead of [0-9].

Regular expression - starting and ending with a character string

Example: ajshdjashdjashdlasdlhdlSTARTasdasdsdaasdENDaknsdklansdlknaldknaaklsdn

1) START\w*END return: STARTasdasdsdaasdEND - will give you words between START and END

2) START\d*END return: START12121212END - will give you numbers between START and END

3) START\d*_\d*END return: START1212_1212END - will give you numbers between START and END having _

How to change the color of winform DataGridview header?

If you want to change a color to single column try this:

 dataGridView1.EnableHeadersVisualStyles = false;
 dataGridView1.Columns[0].HeaderCell.Style.BackColor = Color.Magenta;
 dataGridView1.Columns[1].HeaderCell.Style.BackColor = Color.Yellow;

How to create virtual column using MySQL SELECT?

Try this one if you want to create a virtual column "age" within a select statement:

select brand, name, "10" as age from cars...

tsconfig.json: Build:No inputs were found in config file

I had existing tsconfig files for 4 existing projects in my solution. After upgrading to vs2017 I experienced this problem. It was fixed by adding the (supposedly default) include and exclude sections to the files, as described by NicoJuicy.

How to get post slug from post in WordPress?

You can retrieve it from the post object like so:

global $post;
$post->post_name;

How do I format a String in an email so Outlook will print the line breaks?

I've just been fighting with this today. Let's call the behavior of removing the extra line breaks "continuation." A little experimenting finds the following behavior:

  • Every message starts with continuation off.
  • Lines less than 40 characters long do not trigger continuation, but if continuation is on, they will have their line breaks removed.
  • Lines 40 characters or longer turn continuation on. It remains on until an event occurs to turn it off.
  • Lines that end with a period, question mark, exclamation point or colon turn continuation off. (Outlook assumes it's the end of a sentence?)
  • Lines that turn continuation off will start with a line break, but will turn continuation back on if they are longer than 40 characters.
  • Lines that start or end with a tab turn continuation off.
  • Lines that start with 2 or more spaces turn continuation off.
  • Lines that end with 3 or more spaces turn continuation off.

Please note that I tried all of this with Outlook 2007. YMMV.
So if possible, end all bullet items with a sentence-terminating punctuation mark, a tab, or even three spaces.

How to get every first element in 2 dimensional list

use zip

columns = zip(*rows) #transpose rows to columns
print columns[0] #print the first column
#you can also do more with the columns
print columns[1] # or print the second column
columns.append([7,7,7]) #add a new column to the end
backToRows = zip(*columns) # now we are back to rows with a new column
print backToRows

you can also use numpy

a = numpy.array(a)
print a[:,0]

Edit: zip object is not subscriptable. It need to be converted to list to access as list:

column = list(zip(*row))

JAXB Exception: Class not known to this context

I had the same exception on Tomcat.. I found another problem - when i use wsimport over maven plugin to generate stubs for more then 1 WSDLs - class ObjectFactory (stubs references to this class) contains methods ONLY for one wsdl. So you should merge all methods in one ObjectFactory class (for each WSDL) or generate each wsdl stubs in different directories (there will be separates ObjectFactory classes). It solves problem for me with this exception..J

How to use Visual Studio Code as Default Editor for Git

You need to use command:

git config --global core.editor "'C:\Program Files\Microsoft VS Code\code.exe' -n -w"

Make sure you can start your editor from Git Bash

If you want to use Code.exe with short path, you can do this by adding the following line to your .bash_profile:

alias vscode="C:/Program\ Files/Microsoft\ VS\ Code/Code.exe"

And now, you can call it using only vscode command(or whatever you named it)

Some additional info:

Setup will add Visual Studio Code to your %PATH%, so from the console you can type 'code' to open VS Code on that folder. You will need to restart your console after the installation for the change to the %PATH% environmental variable to take effect.

bootstrap 3 navbar collapse button not working

Just my 2 cents, had:

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

at the end of body, wasn't working, had to add crossorigin="anonymous" and now it's working, Bootstrap version 3.3.6. ...

How can I set the background color of <option> in a <select> element?

_x000D_
_x000D_
select.list1 option.option2
{
    background-color: #007700;
}
_x000D_
<select class="list1">
  <option value="1">Option 1</option>
  <option value="2" class="option2">Option 2</option>
</select>
_x000D_
_x000D_
_x000D_

Abort trap 6 error in C

Try this:

void drawInitialNim(int num1, int num2, int num3){
    int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function. 

    int i, j, k;

    for(i=0; i<num1; i++)
        board[0][i] = 'O';
    for(i=0; i<num2; i++)
        board[1][i] = 'O';
    for(i=0; i<num3; i++)
        board[2][i] = 'O';

    for (j=0; j<3;j++) {
        for (k=0; k<50; k++) {
            if(board[j][k] != 0)
                printf("%c", board[j][k]);
        }
        printf("\n");
    }
}

How can we stop a running java process through Windows cmd?

I like this one.

wmic process where "name like '%java%'" delete

You can actually kill a process on a remote machine the same way.

wmic /node:computername /user:adminuser /password:password process where "name like '%java%'" delete

wmic is awesome!

Open URL in Java to get the content

String url_open ="http://javadl.sun.com/webapps/download/AutoDL?BundleId=76860";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url_open));

Spring mvc @PathVariable

@PathVariable used to fetch the value from URL

for example: To get some question

www.stackoverflow.com/questions/19803731

Here some question id is passed as a parameter in URL

Now to fetch this value in controller all you have to do is just to pass @PathVariable in the method parameter

@RequestMapping(value = " /questions/{questionId}", method=RequestMethod.GET)
    public String getQuestion(@PathVariable String questionId){
    //return question details
}

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable. It uses the Trim function to remove both types of spaces and means before and after spaces of string.

SELECT LTRIM(RTRIM(REVERSE(' NEXT LEVEL EMPLOYEE ')))

HTML Script tag: type or language (or omit both)?

The type attribute is used to define the MIME type within the HTML document. Depending on what DOCTYPE you use, the type value is required in order to validate the HTML document.

The language attribute lets the browser know what language you are using (Javascript vs. VBScript) but is not necessarily essential and, IIRC, has been deprecated.

Dropping Unique constraint from MySQL table

The indexes capable of placing a unique key constraint on a table are PRIMARY and UNIQUE indexes.

To remove the unique key constraint on a column but keep the index, you could remove and recreate the index with type INDEX.

Note that it is a good idea for all tables to have an index marked PRIMARY.

Differences in boolean operators: & vs && and | vs ||

I know there's a lot of answers here, but they all seem a bit confusing. So after doing some research from the Java oracle study guide, I've come up with three different scenarios of when to use && or &. The three scenarios are logical AND, bitwise AND, and boolean AND.

Logical AND: Logical AND (aka Conditional AND) uses the && operator. It's short-circuited meaning: if the left operand is false, then the right operand will not be evaluated.
Example:

int x = 0;
if (false && (1 == ++x) {
    System.out.println("Inside of if");
}
System.out.println(x); // "0"

In the above example the value printed to the console of x will be 0, because the first operand in the if statement is false, hence java has no need to compute (1 == ++x) therefore x will not be computed.

Bitwise AND: Bitwise AND uses the & operator. It's used to preform a bitwise operation on the value. It's much easier to see what's going on by looking at operation on binary numbers ex:

int a = 5;     //                    5 in binary is 0101
int b = 12;    //                   12 in binary is 1100
int c = a & b; // bitwise & preformed on a and b is 0100 which is 4

As you can see in the example, when the binary representations of the numbers 5 and 12 are lined up, then a bitwise AND preformed will only produce a binary number where the same digit in both numbers have a 1. Hence 0101 & 1100 == 0100. Which in decimal is 5 & 12 == 4.

Boolean AND: Now the boolean AND operator behaves similarly and differently to both the bitwise AND and logical AND. I like to think of it as preforming a bitwise AND between two boolean values (or bits), therefore it uses & operator. The boolean values can be the result of a logical expression too.

It returns either a true or false value, much like the logical AND, but unlike the logical AND it is not short-circuited. The reason being, is that for it to preform that bitwise AND, it must know the value of both left and right operands. Here's an ex:

int x = 0;
if (false & (1 == ++x) {
    System.out.println("Inside of if");
}
System.out.println(x); //"1"

Now when that if statement is ran, the expression (1 == ++x) will be executed, even though the left operand is false. Hence the value printed out for x will be 1 because it got incremented.

This also applies to Logical OR (||), bitwise OR (|), and boolean OR (|) Hope this clears up some confusion.

Simple division in Java - is this a bug or a feature?

You're using integer division.

Try 7.0/10 instead.

How can I capture the right-click event in JavaScript?

I think that you are looking for something like this:

   function rightclick() {
    var rightclick;
    var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert(rightclick); // true or false, you can trap right click here by if comparison
}

(http://www.quirksmode.org/js/events_properties.html)

And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >

Regex that matches integers in between whitespace or start/end of string only

This just allow positive integers.

^[0-9]*[1-9][0-9]*$

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

How do I draw a shadow under a UIView?

I use this as part of my utils. With this we can not only set shadow but also can get a rounded corner for any UIView. Also you could set what color shadow you prefer. Normally black is preferred but sometimes, when the background is non-white you might want something else. Here's what I use -

in utils.m
+ (void)roundedLayer:(CALayer *)viewLayer 
              radius:(float)r 
              shadow:(BOOL)s
{
    [viewLayer setMasksToBounds:YES];
    [viewLayer setCornerRadius:r];        
    [viewLayer setBorderColor:[RGB(180, 180, 180) CGColor]];
    [viewLayer setBorderWidth:1.0f];
    if(s)
    {
        [viewLayer setShadowColor:[RGB(0, 0, 0) CGColor]];
        [viewLayer setShadowOffset:CGSizeMake(0, 0)];
        [viewLayer setShadowOpacity:1];
        [viewLayer setShadowRadius:2.0];
    }
    return;
}

To use this we need to call this - [utils roundedLayer:yourview.layer radius:5.0f shadow:YES];

How can I get the last 7 characters of a PHP string?

It would be better to have a check before getting the string.

$newstring = substr($dynamicstring, -7);

if characters are greater then 7 return last 7 characters else return the provided string.

or do this if you need to return message or error if length is less then 7

$newstring = (strlen($dynamicstring)>7)?substr($dynamicstring, -7):"message";

substr documentation

Difference between SRC and HREF

You should remember when to use everyone and that is it
the href is used with links

<a href="#"></a>
<link rel="stylesheet" href="style.css" />

the src is used with scripts and images

<img src="the_image_link" />
<script type="text/javascript" src="" />

the url is used generally in CSS to include something, for exemple to add a background image

selector { background-image: url('the_image_link'); } 

REST API - Bulk Create or Update in single request

In a project I worked at we solved this problem by implement something we called 'Batch' requests. We defined a path /batch where we accepted json in the following format:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 5,
         binder: 8
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      }
   },
]

The response have the status code 207 (Multi-Status) and looks like this:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
      status: 200
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         error: {
            msg: 'A document with doc_number 5 already exists'
            ...
         }
      },
      status: 409
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      },
      status: 200
   },
]

You could also add support for headers in this structure. We implemented something that proved useful which was variables to use between requests in a batch, meaning we can use the response from one request as input to another.

Facebook and Google have similar implementations:
https://developers.google.com/gmail/api/guides/batch
https://developers.facebook.com/docs/graph-api/making-multiple-requests

When you want to create or update a resource with the same call I would use either POST or PUT depending on the case. If the document already exist, do you want the entire document to be:

  1. Replaced by the document you send in (i.e. missing properties in request will be removed and already existing overwritten)?
  2. Merged with the document you send in (i.e. missing properties in request will not be removed and already existing properties will be overwritten)?

In case you want the behavior from alternative 1 you should use a POST and in case you want the behavior from alternative 2 you should use PUT.

http://restcookbook.com/HTTP%20Methods/put-vs-post/

As people already suggested you could also go for PATCH, but I prefer to keep API's simple and not use extra verbs if they are not needed.

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just after your Page_Load add this:

public override void VerifyRenderingInServerForm(Control control)
{
    //base.VerifyRenderingInServerForm(control);
}

Note that I don't do anything in the function.

EDIT: Tim answered the same thing. :) You can also find the answer Here

Best equivalent VisualStudio IDE for Mac to program .NET/C#

Coming from someone who has tried a number of "C# IDEs" on the Mac, your best bet is to install a virtual desktop with Windows and Visual Studio. It really is the best development IDE out there for .NET, nothing even comes close.

On a related note: I hate XCode.


Update: Use Xamarin Studio. It's solid.

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

What does the "More Columns than Column Names" error mean?

It uses commas as separators. So you can either set sep="," or just use read.csv:

x <- read.csv(file="http://www.irs.gov/file_source/pub/irs-soi/countyinflow1011.csv")
dim(x)
## [1] 113593      9

The error is caused by spaces in some of the values, and unmatched quotes. There are no spaces in the header, so read.table thinks that there is one column. Then it thinks it sees multiple columns in some of the rows. For example, the first two lines (header and first row):

State_Code_Dest,County_Code_Dest,State_Code_Origin,County_Code_Origin,State_Abbrv,County_Name,Return_Num,Exmpt_Num,Aggr_AGI
00,000,96,000,US,Total Mig - US & For,6973489,12948316,303495582

And unmatched quotes, for example on line 1336 (row 1335) which will confuse read.table with the default quote argument (but not read.csv):

01,089,24,033,MD,Prince George's County,13,30,1040

How to set width of mat-table column in angular?

Here's an alternative way of tackling the problem:

Instead of trying to "fix it in post" why don't you truncate the description before the table needs to try and fit it into its columns? I did it like this:

<ng-container matColumnDef="description">
   <th mat-header-cell *matHeaderCellDef> {{ 'Parts.description' | translate }} </th>
            <td mat-cell *matCellDef="let element">
                {{(element.description.length > 80) ? ((element.description).slice(0, 80) + '...') : element.description}}
   </td>
</ng-container>

So I first check if the array is bigger than a certain length, if Yes then truncate and add '...' otherwise pass the value as is. This enables us to still benefit from the auto-spacing the table does :)

enter image description here

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

I have run through this. My case was more involved. The project was packaged fine from maven command line.

Couple of things I made. 1. One class has many imports that confused eclipse. Cleaning them fixed part of the problem 2. One case was about a Setter, pressing F3 navigating to that Setter although eclipse complained it is not there. So I simply retyped it and it worked fine (even for all other Setters)

I am still struggling with Implicit super constructor Item() is undefined for default constructor. Must define an explicit constructor"

Removing duplicate objects with Underscore for Javascript

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
var bar = _.map(_.groupBy(foo, function (f) { 
        return JSON.stringify(f); 
    }), function (gr) { 
        return gr[0]; 
    }
);

Lets break this down. First lets group the array items by their stringified value

var grouped = _.groupBy(foo, function (f) { 
    return JSON.stringify(f); 
});

grouped looks like:

{
    '{ "a" : "1" }' = [ { "a" : "1" } { "a" : "1" } ],
    '{ "b" : "2" }' = [ { "b" : "2" } ]
}

Then lets grab the first element from each group

var bar = _.map(grouped, function(gr)
    return gr[0]; 
});

bar looks like: [ { "a" : "1" }, { "b" : "2" } ]

Put it all together:

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
var bar = _.map(_.groupBy(foo, function (f) { 
        return JSON.stringify(f); 
    }), function (gr) { 
        return gr[0]; 
    }
);

Including JavaScript class definition from another file in Node.js

Instead of myFile.js write your files like myFile.mjs. This extension comes with all the goodies of es6, but I mean I recommend you to you webpack and Babel

About "*.d.ts" in TypeScript

The "d.ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.

Rather than rewriting jquery or underscore or whatever in typescript, you can instead write the d.ts file, which contains only the type annotations. Then from your typescript code you get the typescript benefits of static type checking while still using a pure JS library.

Get Time from Getdate()

You can use the datapart to maintain time date type and you can compare it to another time.
Check below example:

declare @fromtime time = '09:30'
declare @totime time
SET @totime=CONVERT(TIME, CONCAT(DATEPART(HOUR, GETDATE()),':', DATEPART(MINUTE, GETDATE())))
if @fromtime <= @totime 
begin print 'true' end
else begin print 'no' end

adb command not found

Mac users just open /Users/(USERNAME)/.bash_profile this file in a editor.
and add this line to add path.

export PATH="/Users/myuser/Library/Android/sdk/platform-tools":$PATH

this is the default path if you install adb via studio. and dont forget to change the username in this line.

Assign a synthesizable initial value to a reg in Verilog

The always @* would never trigger as no Right hand arguments change. Why not use a wire with assign?

module top (
    input wire clk,
    output wire [7:0] led   
);

wire [7:0] data_reg ; 
assign data_reg   = 8'b10101011;
assign led        = data_reg;

endmodule

If you actually want a flop where you can change the value, the default would be in the reset clause.

module top
(
    input        clk,
    input        rst_n,
    input  [7:0] data,
    output [7:0] led   
 );

reg [7:0] data_reg ; 
always @(posedge clk or negedge rst_n) begin
  if (!rst_n)
    data_reg <= 8'b10101011;
  else
    data_reg <= data ; 
end

assign led = data_reg;

endmodule

Hope this helps

Convert a String of Hex into ASCII in Java

To this case, I have a hexadecimal data format into an int array and I want to convert them on String.

int[] encodeHex = new int[] { 0x48, 0x65, 0x6c, 0x6c, 0x6f }; // Hello encode
for (int i = 0; i < encodeHex.length; i++) {
   System.out.print((char) (encodeHex[i]));
}

Have nginx access_log and error_log log to STDOUT and STDERR of master process

If the question is docker related... the official nginx docker images do this by making softlinks towards stdout/stderr

RUN ln -sf /dev/stdout /var/log/nginx/access.log && ln -sf /dev/stderr /var/log/nginx/error.log

REF: https://microbadger.com/images/nginx

How do you test that a Python function throws an exception?

You can use context manager to run the faulty function and assert it raises the exception with a certain message using assertRaisesMessage

with self.assertRaisesMessage(SomeException,'Some error message e.g 404 Not Found'):
    faulty_funtion()

Loop until a specific user input

As an alternative to @Mark Byers' approach, you can use while True:

guess = 50     # this should be outside the loop, I think
while True:    # infinite loop
    n = raw_input("\n\nTrue, False or Correct?: ")
    if n == "Correct":
        break  # stops the loop
    elif n == "True":
        # etc.

The program can't start because MSVCR110.dll is missing from your computer

This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. Download it fromMicrosoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Visit the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679#

Prevent the keyboard from displaying on activity start

//to hide the soft keyboard
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

How to tell if tensorflow is using gpu acceleration from inside python shell?

if you are using tensorflow 2.x use:

sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))

Use RSA private key to generate public key?

here in this code first we are creating RSA key which is private but it has pair of its public key as well so to get your actual public key we simply do this

openssl rsa -in mykey.pem -pubout > mykey.pub

hope you get it for more info check this

Why are #ifndef and #define used in C++ header files?

Those are called #include guards.

Once the header is included, it checks if a unique value (in this case HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page.

When the code is included again, the first ifndef fails, resulting in a blank file.

That prevents double declaration of any identifiers such as types, enums and static variables.

Mean filter for smoothing images in Matlab

and the convolution is defined through a multiplication in transform domain:

conv2(x,y) = fftshift(ifft2(fft2(x).*fft2(y)))

if one channel is considered... for more channels this has to be done every channel

Drawing an SVG file on a HTML5 canvas

You can easily draw simple svgs onto a canvas by:

  1. Assigning the source of the svg to an image in base64 format
  2. Drawing the image onto a canvas

Note: The only drawback of the method is that it cannot draw images embedded in the svg. (see demo)

Demonstration:

(Note that the embedded image is only visible in the svg)

_x000D_
_x000D_
var svg = document.querySelector('svg');_x000D_
var img = document.querySelector('img');_x000D_
var canvas = document.querySelector('canvas');_x000D_
_x000D_
// get svg data_x000D_
var xml = new XMLSerializer().serializeToString(svg);_x000D_
_x000D_
// make it base64_x000D_
var svg64 = btoa(xml);_x000D_
var b64Start = 'data:image/svg+xml;base64,';_x000D_
_x000D_
// prepend a "header"_x000D_
var image64 = b64Start + svg64;_x000D_
_x000D_
// set it as the source of the img element_x000D_
img.src = image64;_x000D_
_x000D_
// draw the image onto the canvas_x000D_
canvas.getContext('2d').drawImage(img, 0, 0);
_x000D_
svg, img, canvas {_x000D_
  display: block;_x000D_
}
_x000D_
SVG_x000D_
_x000D_
<svg height="40">_x000D_
  <rect width="40" height="40" style="fill:rgb(255,0,255);" />_x000D_
  <image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>_x000D_
</svg>_x000D_
<hr/><br/>_x000D_
_x000D_
IMAGE_x000D_
<img/>_x000D_
<hr/><br/>_x000D_
   _x000D_
CANVAS_x000D_
<canvas></canvas>_x000D_
<hr/><br/>
_x000D_
_x000D_
_x000D_

What is this CSS selector? [class*="span"]

It selects all elements where the class name contains the string "span" somewhere. There's also ^= for the beginning of a string, and $= for the end of a string. Here's a good reference for some CSS selectors.

I'm only familiar with the bootstrap classes spanX where X is an integer, but if there were other selectors that ended in span, it would also fall under these rules.

It just helps to apply blanket CSS rules.

python encoding utf-8

Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python

Simplest way to merge ES6 Maps/Sets?

To merge the sets in the array Sets, you can do

var Sets = [set1, set2, set3];

var merged = new Set([].concat(...Sets.map(set => Array.from(set))));

It is slightly mysterious to me why the following, which should be equivalent, fails at least in Babel:

var merged = new Set([].concat(...Sets.map(Array.from)));

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

I wrote my self a helper method to get patterns for this.

public static String getPattern(int month) {
    String first = "MMMM dd";
    String last = ", yyyy";
    String pos = (month == 1 || month == 21 || month == 31) ? "'st'" : (month == 2 || month == 22) ? "'nd'" : (month == 3 || month == 23) ? "'rd'" : "'th'";
    return first + pos + last;
}

and then we can call it as

LocalDate localDate = LocalDate.now();//For reference
int month = localDate.getDayOfMonth();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(getPattern(month));
String date = localDate.format(formatter);
System.out.println(date);

the output is

December 12th, 2018

How to resize the jQuery DatePicker control

To get this to work in Safari 5.1 with Rails 3.1, I had to add:

.ui-datepicker, .ui-datepicker a{
 font-size:10px;
}

Difference between @Mock and @InjectMocks

@Mock creates a mock. @InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock (or @Spy) annotations into this instance.

Note you must use @RunWith(MockitoJUnitRunner.class) or Mockito.initMocks(this) to initialize these mocks and inject them (JUnit 4).

With JUnit 5, you must use @ExtendWith(MockitoExtension.class).

@RunWith(MockitoJUnitRunner.class) // JUnit 4
// @ExtendWith(MockitoExtension.class) for JUnit 5
public class SomeManagerTest {

    @InjectMocks
    private SomeManager someManager;

    @Mock
    private SomeDependency someDependency; // this will be injected into someManager
 
     // tests...

}

What is the path for the startup folder in windows 2008 server

SHGetKnownFolderPath:

Retrieves the full path of a known folder identified by the folder's KNOWNFOLDERID.

And, FOLDERID_CommonStartup:

Default Path %ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp

There are also managed equivalents, but you haven't told us what you're programming in.

Node JS Error: ENOENT

"/tmp/test.jpg" is not the correct path – this path starts with / which is the root directory.

In unix, the shortcut to the current directory is .

Try this "./tmp/test.jpg"

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

How do you get the selected value of a Spinner?

To get the selected value of a spinner you can follow this example.

Create a nested class that implements AdapterView.OnItemSelectedListener. This will provide a callback method that will notify your application when an item has been selected from the Spinner.

Within "onItemSelected" method of that class, you can get the selected item:

public class YourItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        String selected = parent.getItemAtPosition(pos).toString();
    }

    public void onNothingSelected(AdapterView parent) {
        // Do nothing.
    }
}

Finally, your ItemSelectedListener needs to be registered in the Spinner:

spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

Shell script "for" loop syntax

If the seq command available on your system:

for i in `seq 2 $max`
do
  echo "output: $i"
done

If not, then use poor man's seq with perl:

seq=`perl -e "\$,=' ';print 2..$max"`
for i in $seq
do
  echo "output: $i"
done

Watch those quote marks.

DevTools failed to load SourceMap: Could not load content for chrome-extension

I resolved this by clearing App Data.

Cypress documentation admits that App Data can get corrupted:

Cypress maintains some local application data in order to save user preferences and more quickly start up. Sometimes this data can become corrupted. You may fix an issue you have by clearing this app data.

  1. Open Cypress via cypress open
  2. Go to File -> View App Data
  3. This will take you to the directory in your file system where your App Data is stored. If you cannot open Cypress, search your file system for a directory named cy whose content should look something like this:

       production
            all.log
            browsers
            bundles
            cache
            projects
            proxy
            state.json

  1. Delete everything in the cy folder
  2. Close Cypress and open it up again

Source: https://docs.cypress.io/guides/references/troubleshooting.html#To-clear-App-Data

Generate PDF from HTML using pdfMake in Angularjs

I know its not relevant to this post but might help others converting HTML to PDF on client side. This is a simple solution if you use kendo. It also preserves the css (most of the cases).

_x000D_
_x000D_
var generatePDF = function() {_x000D_
  kendo.drawing.drawDOM($("#formConfirmation")).then(function(group) {_x000D_
    kendo.drawing.pdf.saveAs(group, "Converted PDF.pdf");_x000D_
  });_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <!-- Latest compiled and minified CSS -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Optional theme -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <!-- Latest compiled and minified JavaScript -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <script src="//kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <br/>_x000D_
  <button class="btn btn-primary" onclick="generatePDF()"><i class="fa fa-save"></i> Save as PDF</button>_x000D_
  <br/>_x000D_
  <br/>_x000D_
  <div id="formConfirmation">_x000D_
_x000D_
    <div class="container theme-showcase" role="main">_x000D_
      <!-- Main jumbotron for a primary marketing message or call to action -->_x000D_
      <div class="jumbotron">_x000D_
        <h1>Theme example</h1>_x000D_
        <p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Buttons</h1>_x000D_
      </div>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-lg btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-lg btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-lg btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-lg btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-lg btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-lg btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-lg btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-sm btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-sm btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-sm btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-sm btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-sm btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-sm btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-sm btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-xs btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-xs btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-xs btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-xs btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-xs btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-xs btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-xs btn-link">Link</button>_x000D_
      </p>_x000D_
      <div class="page-header">_x000D_
        <h1>Tables</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-md-6">_x000D_
          <table class="table">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-striped">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-bordered">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td rowspan="2">1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@TwBootstrap</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td colspan="2">Larry the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-condensed">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td colspan="2">Larry the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Thumbnails</h1>_x000D_
      </div>_x000D_
      <img data-src="holder.js/200x200" class="img-thumbnail" alt="A generic square placeholder image with a white border around it, making it resemble a photograph taken with an old instant camera">_x000D_
      <div class="page-header">_x000D_
        <h1>Labels</h1>_x000D_
      </div>_x000D_
      <h1>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h1>_x000D_
      <h2>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h2>_x000D_
      <h3>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h3>_x000D_
      <h4>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h4>_x000D_
      <h5>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h5>_x000D_
      <h6>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h6>_x000D_
      <p>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </p>_x000D_
      <div class="page-header">_x000D_
        <h1>Badges</h1>_x000D_
      </div>_x000D_
      <p>_x000D_
        <a href="#">Inbox <span class="badge">42</span></a>_x000D_
      </p>_x000D_
      <ul class="nav nav-pills" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages <span class="badge">3</span></a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <div class="page-header">_x000D_
        <h1>Dropdown menus</h1>_x000D_
      </div>_x000D_
      <div class="dropdown theme-dropdown clearfix">_x000D_
        <a id="dropdownMenu1" href="#" class="sr-only dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">_x000D_
          <li class="active"><a href="#">Action</a>_x000D_
          </li>_x000D_
          <li><a href="#">Another action</a>_x000D_
          </li>_x000D_
          <li><a href="#">Something else here</a>_x000D_
          </li>_x000D_
          <li role="separator" class="divider"></li>_x000D_
          <li><a href="#">Separated link</a>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Navs</h1>_x000D_
      </div>_x000D_
      <ul class="nav nav-tabs" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <ul class="nav nav-pills" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <div class="page-header">_x000D_
        <h1>Navbars</h1>_x000D_
      </div>_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a>_x000D_
              </li>_x000D_
              <li><a href="#about">About</a>_x000D_
              </li>_x000D_
              <li><a href="#contact">Contact</a>_x000D_
              </li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="#">Action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Another action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Something else here</a>_x000D_
                  </li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li class="dropdown-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">One more separated link</a>_x000D_
                  </li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!--/.nav-collapse -->_x000D_
        </div>_x000D_
      </nav>_x000D_
      <nav class="navbar navbar-inverse">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a>_x000D_
              </li>_x000D_
              <li><a href="#about">About</a>_x000D_
              </li>_x000D_
              <li><a href="#contact">Contact</a>_x000D_
              </li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="#">Action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Another action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Something else here</a>_x000D_
                  </li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li class="dropdown-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">One more separated link</a>_x000D_
                  </li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!--/.nav-collapse -->_x000D_
        </div>_x000D_
      </nav>_x000D_
      <div class="page-header">_x000D_
        <h1>Alerts</h1>_x000D_
      </div>_x000D_
      <div class="alert alert-success" role="alert">_x000D_
        <strong>Well done!</strong> You successfully read this important alert message._x000D_
      </div>_x000D_
      <div class="alert alert-info" role="alert">_x000D_
        <strong>Heads up!</strong> This alert needs your attention, but it's not super important._x000D_
      </div>_x000D_
      <div class="alert alert-warning" role="alert">_x000D_
        <strong>Warning!</strong> Best check yo self, you're not looking too good._x000D_
      </div>_x000D_
      <div class="alert alert-danger" role="alert">_x000D_
        <strong>Oh snap!</strong> Change a few things up and try submitting again._x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Progress bars</h1>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"><span class="sr-only">60% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"><span class="sr-only">40% Complete (success)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"><span class="sr-only">20% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete (warning)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"><span class="sr-only">80% Complete (danger)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-success" style="width: 35%"><span class="sr-only">35% Complete (success)</span>_x000D_
        </div>_x000D_
        <div class="progress-bar progress-bar-warning" style="width: 20%"><span class="sr-only">20% Complete (warning)</span>_x000D_
        </div>_x000D_
        <div class="progress-bar progress-bar-danger" style="width: 10%"><span class="sr-only">10% Complete (danger)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>List groups</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-sm-4">_x000D_
          <ul class="list-group">_x000D_
            <li class="list-group-item">Cras justo odio</li>_x000D_
            <li class="list-group-item">Dapibus ac facilisis in</li>_x000D_
            <li class="list-group-item">Morbi leo risus</li>_x000D_
            <li class="list-group-item">Porta ac consectetur ac</li>_x000D_
            <li class="list-group-item">Vestibulum at eros</li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="list-group">_x000D_
            <a href="#" class="list-group-item active">_x000D_
              Cras justo odio_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">Dapibus ac facilisis in</a>_x000D_
            <a href="#" class="list-group-item">Morbi leo risus</a>_x000D_
            <a href="#" class="list-group-item">Porta ac consectetur ac</a>_x000D_
            <a href="#" class="list-group-item">Vestibulum at eros</a>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="list-group">_x000D_
            <a href="#" class="list-group-item active">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Panels</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-default">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-primary">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-success">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-info">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-warning">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-danger">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
      </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Git diff -w ignore whitespace only at start & end of lines

For end of line use:

git diff --ignore-space-at-eol

Instead of what are you using currently:

git diff -w (--ignore-all-space)

For start of line... you are out of luck if you want a built in solution.

However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

With a React Native running in the emulator,
Press ctrl+m (for Linux, I suppose it's the same for Windows and ?+m for Mac OS X) or run the following in terminal:

adb shell input keyevent 82

How to get Printer Info in .NET?

This should work.

using System.Drawing.Printing;

...

PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "The printer name"; // Load the appropriate printer's setting

After that, the various properties of PrinterSettings can be read.

Note that ps.isValid() can see if the printer actually exists.

Edit: One additional comment. Microsoft recommends you use a PrintDocument and modify its PrinterSettings rather than creating a PrinterSettings directly.

How to get the instance id from within an ec2 instance?

In the question you have mentioned the user as root, one thing I should mention is that the instance ID is not dependent on the user.

For Node developers,

var meta  = new AWS.MetadataService();

meta.request("/latest/meta-data/instance-id", function(err, data){
    console.log(data);
});

How to test an Internet connection with bash?

I've written scripts before that simply use telnet to connect to port 80, then transmit the text:

HTTP/1.0 GET /index.html

followed by two CR/LF sequences.

Provided you get back some form of HTTP response, you can generally assume the site is functioning.

jQuery AJAX submit form

I know this is a jQuery related question, but now days with JS ES6 things are much easier. Since there is no pure javascript answer, I thought I could add a simple pure javascript solution to this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.

const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input"); 
let formData = new FormData(); 
for (let input of formInputs) {
    formData.append(input.name, input.value); 
}

fetch(form.action,
    {
        method: form.method,
        body: formData
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error.message))
    .finally(() => console.log("Done"));

Extract code country from phone number [libphonenumber]

Use a try catch block like below:

try { 

const phoneNumber = this.phoneUtil.parseAndKeepRawInput(value, this.countryCode);

}catch(e){}

pandas dataframe convert column type to string or categorical

Prior answers focused on nominal data (e.g. unordered). If there is a reason to impose order for an ordinal variable, then one would use:

# Transform to category
df['zipcode_category'] = df['zipcode_category'].astype('category')

# Add ordered category
df['zipcode_ordered'] = df['zipcode_category']

# Setup the ordering
df.zipcode_ordered.cat.set_categories(
    new_categories = [90211, 90210], ordered = True, inplace = True
)

# Output IDs
df['zipcode_ordered_id'] = df.zipcode_ordered.cat.codes
print(df)
#  zipcode_category zipcode_ordered  zipcode_ordered_id
#            90210           90210                   1
#            90211           90211                   0

More details on setting ordered categories can be found at the pandas website:

https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#sorting-and-order

Spark - repartition() vs coalesce()

Repartition: Shuffle the data into a NEW number of partitions.

Eg. Initial data frame is partitioned in 200 partitions.

df.repartition(500): Data will be shuffled from 200 partitions to new 500 partitions.

Coalesce: Shuffle the data into existing number of partitions.

df.coalesce(5): Data will be shuffled from remaining 195 partitions to 5 existing partitions.

How to add hamburger menu in bootstrap

CSS only (no icon sets) Codepen

_x000D_
_x000D_
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
   <!-- <a class="navbar-brand" href="#">_x000D_
      <img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
      Bootstrap_x000D_
      </a> -->_x000D_
   <!-- https://stackoverflow.com/questions/26317679 -->_x000D_
   <a class="nav-link" href="#">_x000D_
      <div id="navBars">_x000D_
         <input type="checkbox" /><span></span>_x000D_
         <span></span>_x000D_
         <span></span>_x000D_
      </div>_x000D_
   </a>_x000D_
   <!-- /26317679 -->_x000D_
   <div class="collapse navbar-collapse" id="navbarNav">_x000D_
      <ul class="navbar-nav">_x000D_
         <li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
         <li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
      </ul>_x000D_
   </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Hide options in a select list using jQuery

This works in Firefox 3.0, but not in MSIE 8, nor in Opera 9.62:

jQuery('#destinations').children('option[value="1"]').hide();
jQuery('#destinations').children('option[value="1"]').css('display','none');

But rather hiding an option, one can simply disable it:

jQuery('#destinations').val('2'); 
jQuery('#destinations').children('option[value="1"]').attr('disabled','disabled');

The first of the the two lines above is for Firefox and pass focus to the 2nd option (assuming it has value="2"). If we omit it, the option is disabled, but the still displays the "enabled" option before we drop it down. Hence, we pass focus to another option to avoid this.

Confirm deletion using Bootstrap 3 modal box

You need the modal in your HTML. When the delete button is clicked it popup the modal. It's also important to prevent the click of that button from submitting the form. When the confirmation is clicked the form will submit.

_x000D_
_x000D_
   _x000D_
_x000D_
 $('button[name="remove_levels"]').on('click', function(e) {_x000D_
      var $form = $(this).closest('form');_x000D_
      e.preventDefault();_x000D_
      $('#confirm').modal({_x000D_
          backdrop: 'static',_x000D_
          keyboard: false_x000D_
      })_x000D_
      .on('click', '#delete', function(e) {_x000D_
          $form.trigger('submit');_x000D_
        });_x000D_
      $("#cancel").on('click',function(e){_x000D_
       e.preventDefault();_x000D_
       $('#confirm').modal.model('hide');_x000D_
      });_x000D_
    });
_x000D_
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>_x000D_
<form action="#" method="POST">_x000D_
  <button class='btn btn-danger btn-xs' type="submit" name="remove_levels" value="delete"><span class="fa fa-times"></span> delete</button>_x000D_
</form>_x000D_
_x000D_
<div id="confirm" class="modal">_x000D_
  <div class="modal-body">_x000D_
    Are you sure?_x000D_
  </div>_x000D_
  <div class="modal-footer">_x000D_
    <button type="button" data-dismiss="modal" class="btn btn-primary" id="delete">Delete</button>_x000D_
    <button type="button" data-dismiss="modal" class="btn">Cancel</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Chart.js v2 - hiding grid lines

options: {
    scales: {
        xAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }],
        yAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }]
    }
}

Fixed Table Cell Width

for FULLSCREEN width table:

  • table width MUST be 100%

  • if need N colunms, then THs MUST be N+1

example for 3 columns:

_x000D_
_x000D_
table.fixed {_x000D_
      table-layout: fixed;_x000D_
      width: 100%;_x000D_
    }_x000D_
    table.fixed td {_x000D_
      overflow: hidden;_x000D_
    }
_x000D_
  <table class="fixed">_x000D_
      <col width=20 />_x000D_
      <col width=20 />_x000D_
      <col width=20 />_x000D_
    <tr>_x000D_
      <th>1</th>_x000D_
      <th>2</th>_x000D_
      <th>3</th>_x000D_
      <th>FREE</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>text111111111</td>_x000D_
      <td>text222222222</td>_x000D_
      <td>text3333333</td>_x000D_
    </tr>_x000D_
  </table>
_x000D_
_x000D_
_x000D_

How to add a column in TSQL after a specific column?

This is absolutely possible. Although you shouldn't do it unless you know what you are dealing with. Took me about 2 days to figure it out. Here is a stored procedure where i enter: ---database name (schema name is "_" for readability) ---table name ---column ---column data type (column added is always null, otherwise you won't be able to insert) ---the position of the new column.

Since I'm working with tables from SAM toolkit (and some of them have > 80 columns) , the typical variable won't be able to contain the query. That forces the need of external file. Now be careful where you store that file and who has access on NTFS and network level.

Cheers!

USE [master]
GO
/****** Object:  StoredProcedure [SP_Set].[TrasferDataAtColumnLevel]    Script Date: 8/27/2014 2:59:30 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [SP_Set].[TrasferDataAtColumnLevel]
(
    @database varchar(100),
    @table varchar(100),
    @column varchar(100),
    @position int,
    @datatype varchar(20)    
)
AS
BEGIN
set nocount on
exec  ('
declare  @oldC varchar(200), @oldCDataType varchar(200), @oldCLen int,@oldCPos int
create table Test ( dummy int)
declare @columns varchar(max) = ''''
declare @columnVars varchar(max) = ''''
declare @columnsDecl varchar(max) = ''''
declare @printVars varchar(max) = ''''

DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR 
select column_name, data_type, character_maximum_length, ORDINAL_POSITION  from ' + @database + '.INFORMATION_SCHEMA.COLUMNS where table_name = ''' + @table + '''
OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos WHILE @@FETCH_STATUS = 0 BEGIN

if(@oldCPos = ' + @position + ')
begin
    exec(''alter table Test add [' + @column + '] ' + @datatype + ' null'')
end

if(@oldCDataType != ''timestamp'')
begin

    set @columns += @oldC + '' , '' 
    set @columnVars += ''@'' + @oldC + '' , ''

    if(@oldCLen is null)
    begin
        if(@oldCDataType != ''uniqueidentifier'')
        begin
            set @printVars += '' print convert('' + @oldCDataType + '',@'' + @oldC + '')'' 
            set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', '' 
            exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
        end
        else
        begin
            set @printVars += '' print convert(varchar(50),@'' + @oldC + '')'' 
            set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', '' 
            exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
        end
    end
    else
    begin 
        if(@oldCLen < 0)
        begin
            set @oldCLen = 4000
        end
        set @printVars += '' print @'' + @oldC 
        set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + ''('' + convert(character,@oldCLen) + '') , '' 
        exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + ''('' + @oldCLen + '') null'')
    end
end

if exists (select column_name from INFORMATION_SCHEMA.COLUMNS where table_name = ''Test'' and column_name = ''dummy'')
begin
    alter table Test drop column dummy
end

FETCH NEXT FROM MY_CURSOR INTO  @oldC, @oldCDataType, @oldCLen, @oldCPos END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR

set @columns = reverse(substring(reverse(@columns), charindex('','',reverse(@columns)) +1, len(@columns)))
set @columnVars = reverse(substring(reverse(@columnVars), charindex('','',reverse(@columnVars)) +1, len(@columnVars)))
set @columnsDecl = reverse(substring(reverse(@columnsDecl), charindex('','',reverse(@columnsDecl)) +1, len(@columnsDecl)))
set @columns = replace(replace(REPLACE(@columns, ''       '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnVars = replace(replace(REPLACE(@columnVars, ''       '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnsDecl = replace(replace(REPLACE(@columnsDecl, ''  '', ''''), char(9) + char(9),'' ''),char(9), '''')
set @printVars = REVERSE(substring(reverse(@printVars), charindex(''+'',reverse(@printVars))+1, len(@printVars))) 

create table query (id int identity(1,1), string varchar(max))

insert into query values  (''declare '' + @columnsDecl + ''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR '')

insert into query values   (''select '' + @columns + '' from ' + @database + '._.' + @table + ''')

insert into query values  (''OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' WHILE @@FETCH_STATUS = 0 BEGIN '')

insert into query values   (@printVars )

insert into query values   ( '' insert into Test ('')
insert into query values   (@columns) 
insert into query values   ( '') values ( '' + @columnVars + '')'')

insert into query values  (''FETCH NEXT FROM MY_CURSOR INTO  '' + @columnVars + '' END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR'')

declare @path varchar(100) = ''C:\query.sql''
declare @query varchar(500) = ''bcp "select string from query order by id" queryout '' + @path + '' -t, -c -S  '' + @@servername +  '' -T''

exec master..xp_cmdshell @query

set @query  = ''sqlcmd -S '' + @@servername + '' -i '' + @path

EXEC xp_cmdshell  @query

set @query = ''del ''  + @path

exec xp_cmdshell @query

drop table ' + @database + '._.' + @table + '

select * into ' + @database + '._.' + @table + ' from Test 

drop table query
drop table Test  ')

END

don't fail jenkins build if execute shell fails

The following works for mercurial by only committing if there are changes. So the build only fails if the commit fails.

hg id | grep "+" || exit 0
hg commit -m "scheduled commit"

How to find out what the date was 5 days ago?

find out what the date was 5 days ago from today in php

$date = strtotime(date("Y-m-d", strtotime("-5 day")));

find out what the date was n days ago from today in php

$date = strtotime(date("Y-m-d", strtotime("-n day")));

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

mysql $link generally means, the resource object of the established mysqli connection to query the database.

So there are two ways of solving this problem

mysqli_query();

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql"); 
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));

Or, Using mysql_query() (This is now obselete)

$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");        
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());

As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .

How eliminate the tab space in the column in SQL Server 2008

See it might be worked -------

UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space

UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline

UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab

Thanks Subroto

javascript: calculate x% of a number

This is what I would do:

// num is your number
// amount is your percentage
function per(num, amount){
  return num*amount/100;
}

...
<html goes here>
...

alert(per(10000, 35.8));

Maven: Command to update repository after adding dependency to POM

Right, click on the project. Go to Maven -> Update Project.

The dependencies will automatically be installed.

How do I check if a given string is a legal/valid file name under Windows?

I suggest just use the Path.GetFullPath()

string tagetFileFullNameToBeChecked;
try
{
  Path.GetFullPath(tagetFileFullNameToBeChecked)
}
catch(AugumentException ex)
{
  // invalid chars found
}

How to Force New Google Spreadsheets to refresh and recalculate?

Quick, but manual


Updating NOW(), TODAY(), RAND(), or RANDBETWEEN() formulas

Press Backspace ? or Del on any empty cell to immediately trigger a recalculation of formulas depending on NOW(), TODAY(), RAND(), or RANDBETWEEN() (in all Sheets of the whole Spreadsheet, as usual).

(If no empty cell is at hand, you can delete a filled cell instead and then undo that with Ctrl+z.)

INDIRECT() formulas are unfortunately not updated like this by default.

Updating INDIRECT() formulas

You can update a (range of) cells of INDIRECT() formulas by pasting the range on itself:

  1. Select cell/ range
  2. Ctrl+C
  3. Ctrl+V

You can use Ctrl+A to select the whole current Sheet in step 1.. But for large Sheets then the other 2 operations can take several seconds each.
A trick to know when the process of copying a large range has finished: Copy some single cell before copying your range: The single cell losing its dotted border will be your notification of the large copy finishing.

MySQL Trigger - Storing a SELECT in a variable

`CREATE TRIGGER `category_before_ins_tr` BEFORE INSERT ON `category`
  FOR EACH ROW
BEGIN
    **SET @tableId= (SELECT id FROM dummy LIMIT 1);**

END;`;

How to hide 'Back' button on navigation bar on iPhone?

hide back button with bellow code...

[self.navigationItem setHidesBackButton:YES animated:YES];

or

[self.navigationItem setHidesBackButton:YES];

Also if you have custom UINavigationBar then try bellow code

self.navigationItem.leftBarButtonItem = nil;

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

HTML/CSS: how to put text both right and left aligned in a paragraph

Ok what you probably want will be provide to you by result of:

  1. in CSS:

    div { column-count: 2; }

  2. in html:

    <div> some text, bla bla bla </div>

In CSS you make div to split your paragraph on to column, you can make them 3, 4...

If you want to have many differend paragraf like that, then put id or class in your div:

Accessing elements of Python dictionary by index

You can't rely on order of dictionaries, but you may try this:

mydict['Apple'].items()[0][0]

If you want the order to be preserved you may want to use this: http://www.python.org/dev/peps/pep-0372/#ordered-dict-api

c# search string in txt file

I worked a little bit the method that Rawling posted here to find more than one line in the same file until the end. This is what worked for me:

                foreach (var line in File.ReadLines(pathToFile))
                {
                    if (line.Contains("CustomerEN") && current == null)
                    {
                        current = new List<string>();
                        current.Add(line);
                    }
                    else if (line.Contains("CustomerEN") && current != null)
                    {
                        current.Add(line);
                    }
                }
                string s = String.Join(",", current);
                MessageBox.Show(s);

How can I call the 'base implementation' of an overridden virtual method?

You can't do it by C#, but you can edit MSIL.

IL code of your Main method:

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] class MsilEditing.A a)
    L_0000: nop 
    L_0001: newobj instance void MsilEditing.B::.ctor()
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: callvirt instance void MsilEditing.A::X()
    L_000d: nop 
    L_000e: ret 
}

You should change opcode in L_0008 from callvirt to call

L_0008: call instance void MsilEditing.A::X()

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

It is a problem with Java InputStream. When the stream is read once the file offset position counter is moved to the end of file. On the subsequent read by using the same stream you'll get this error. So you have to close and reopen the stream again or call inputStream.reset() to reset the offset counter to its initial position.

What is the standard way to add N seconds to datetime.time in Python?

You can use full datetime variables with timedelta, and by providing a dummy date then using time to just get the time value.

For example:

import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time())

results in the two values, three seconds apart:

11:34:59
11:35:02

You could also opt for the more readable

b = a + datetime.timedelta(seconds=3)

if you're so inclined.


If you're after a function that can do this, you can look into using addSecs below:

import datetime

def addSecs(tm, secs):
    fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
    fulldate = fulldate + datetime.timedelta(seconds=secs)
    return fulldate.time()

a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)

This outputs:

 09:11:55.775695
 09:16:55

How do I deal with installing peer dependencies in Angular CLI?

You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.

ng update @angular/cli @angular/core --force

For a full list of options, check the docs: https://angular.io/cli/update

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

Type.GetType("namespace.a.b.ClassName") returns null

Type.GetType("namespace.qualified.TypeName") only works when the type is found in either mscorlib.dll or the currently executing assembly.

If neither of those things are true, you'll need an assembly-qualified name:

Type.GetType("namespace.qualified.TypeName, Assembly.Name")

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

Jquery checking success of ajax post

The documentation is here: http://docs.jquery.com/Ajax/jQuery.ajax

But, to summarize, the ajax call takes a bunch of options. the ones you are looking for are error and success.

You would call it like this:

$.ajax({
  url: 'mypage.html',
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});

I have shown the success and error function taking no arguments, but they can receive arguments.

The error function can take three arguments: XMLHttpRequest, textStatus, and errorThrown.

The success function can take two arguments: data and textStatus. The page you requested will be in the data argument.

How to add an object to an array

The way I made object creator with auto list:

var list = [];

function saveToArray(x) {
    list.push(x);
};

function newObject () {
    saveToArray(this);
};

Grep regex NOT containing string

grep matches, grep -v does the inverse. If you need to "match A but not B" you usually use pipes:

grep "${PATT}" file | grep -v "${NOTPATT}"