Programs & Examples On #Forgot password

This tag refers to a situation in which you cannot access a protected system, file, database, etc. you would normally have access to because you cannot remember the password used to protect it.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Upgrading MySQL fixed it for me. On RHEL-based servers, just run:

sudo yum upgrade mysql-server

I forgot the password I entered during postgres installation

The pg_hba.conf (C:\Program Files\PostgreSQL\9.3\data) file has changed since these answers were given. What worked for me, in Windows, is to open the file and change the METHOD from md5 to trust:

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust

Then, using pgAdmin III, I logged in using no password and changed user postgres' password by going to File -> Change Password

Xcode 6 Storyboard the wrong size?

On your storyboard page, go to File Inspector and uncheck 'Use Size Classes'. This should shrink your view controller to regular IPhone size you were familiar with. Note that using 'size classes' will let you design your project across many devices. Once you uncheck this the Xcode will give you a warning dialogue as follows. This should be self-explainatory.

"Disabling size classes will limit this document to storing data for a single device family. The data for the size class best representing the targeted device will be retained, and all other data will be removed. In addition, segues will be converted to their non-adaptive equivalents."

Update records using LINQ

I assume person_id is the primary key of Person table, so here's how you update a single record:

Person result = (from p in Context.Persons
              where p.person_id == 5
              select p).SingleOrDefault();

result.is_default = false;

Context.SaveChanges();

and here's how you update multiple records:

List<Person> results = (from p in Context.Persons
                        where .... // add where condition here
                        select p).ToList();

foreach (Person p in results)
{
    p.is_default = false;
}

Context.SaveChanges();

How to add Drop-Down list (<select>) programmatically?

const countryResolver = (data = [{}]) => {
    const countrySelecter = document.createElement('select');
    countrySelecter.className = `custom-select`;
    countrySelecter.id = `countrySelect`;
    countrySelecter.setAttribute("aria-label", "Example select with button addon");

    let opt = document.createElement("option");
    opt.text = "Select language";
    opt.disabled = true;
    countrySelecter.add(opt, null);
    let i = 0;
    for (let item of data) {
        let opt = document.createElement("option");
        opt.value = item.Id;
        opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
        countrySelecter.add(opt, null);
    }
    return countrySelecter;
};

What characters are forbidden in Windows and Linux directory names?

Let's keep it simple and answer the question, first.

  1. The forbidden printable ASCII characters are:

    • Linux/Unix:

      / (forward slash)
      
    • Windows:

      < (less than)
      > (greater than)
      : (colon - sometimes works, but is actually NTFS Alternate Data Streams)
      " (double quote)
      / (forward slash)
      \ (backslash)
      | (vertical bar or pipe)
      ? (question mark)
      * (asterisk)
      
  2. Non-printable characters

    If your data comes from a source that would permit non-printable characters then there is more to check for.

    • Linux/Unix:

      0 (NULL byte)
      
    • Windows:

      0-31 (ASCII control characters)
      

    Note: While it is legal under Linux/Unix file systems to create files with control characters in the filename, it might be a nightmare for the users to deal with such files.

  3. Reserved file names

    The following filenames are reserved:

    • Windows:

      CON, PRN, AUX, NUL 
      COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9
      LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9
      

      (both on their own and with arbitrary file extensions, e.g. LPT1.txt).

  4. Other rules

    • Windows:

      Filenames cannot end in a space or dot.

not finding android sdk (Unity)

  1. Delete android sdk "tools" folder : [Your Android SDK root]/tools -> tools

  2. Download SDK Tools: http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip

  3. Extract that to Android SDK root

  4. Build your project

After that it didn't work for me yet, I had to

  1. Go to the Java archives (http://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html)

  2. Search for the jdk-8u131 release.

  3. Accept the Licence Agreement,make an account and download the release.

  4. Install it and define it as JDK path in Unity.

source : https://www.reddit.com/r/Unity3D/comments/77azfb/i_cant_get_unity_to_build_run_my_game/

TSQL How do you output PRINT in a user defined function?

Use extended procedure xp_cmdshell to run a shell command. I used it to print output to a file:

exec xp_cmdshell 'echo "mytextoutput" >> c:\debuginfo.txt'

This creates the file debuginfo.txt if it does not exist. Then it adds the text "mytextoutput" (without quotation marks) to the file. Any call to the function will write an additional line.

You may need to enable this db-server property first (default = disabled), which I realize may not be to the liking of dba's for production environments though.

Difference between map, applymap and apply methods in Pandas

Probably simplest explanation the difference between apply and applymap:

apply takes the whole column as a parameter and then assign the result to this column

applymap takes the separate cell value as a parameter and assign the result back to this cell.

NB If apply returns the single value you will have this value instead of the column after assigning and eventually will have just a row instead of matrix.

How to write inside a DIV box with javascript

You can use one of the following methods:

document.getElementById('log').innerHTML = "text";

document.getElementById('log').innerText = "text";

document.getElementById('log').textContent = "text";

For Jquery:

$("#log").text("text");

$("#log").html("text");

Is there a kind of Firebug or JavaScript console debug for Android?

I have recently written a tool for showing console logs in a movable/resizable "window" (actually a div). It provides similar functionality to Firebug's console but you can see it over your page on a tablet. Tablet/Smartphone/Phablet Debug Console

What difference does .AsNoTracking() make?

AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers).

This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.

For these cases the "key" can be set to any non-nullable column but then AsNoTracking() must be used with every query else records (duplicate by key) will be skipped.

Date Comparison using Java

If you're set on using Java Dates rather than, say, JodaTime, use a java.text.DateFormat to convert the string to a Date, then compare the two using .equals:

I almost forgot: You need to zero out the hours, minutes, seconds, and milliseconds on the current date before comparing them. I used a Calendar object below to do it.

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

// Other code here
    String toDate;
    //toDate = "05/11/2010";

    // Value assigned to toDate somewhere in here

    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
    Calendar currDtCal = Calendar.getInstance();

    // Zero out the hour, minute, second, and millisecond
    currDtCal.set(Calendar.HOUR_OF_DAY, 0);
    currDtCal.set(Calendar.MINUTE, 0);
    currDtCal.set(Calendar.SECOND, 0);
    currDtCal.set(Calendar.MILLISECOND, 0);

    Date currDt = currDtCal.getTime();

    Date toDt;
    try {
        toDt = df.parse(toDate);
    } catch (ParseException e) {
        toDt = null;
        // Print some error message back to the user
    }

    if (currDt.equals(toDt)) {
        // They're the same date
    }

Check substring exists in a string in C

And here is how to report the position of the first character off the found substring:

Replace this line in the above code:

printf("%s",substring,"\n");

with:

printf("substring %s was found at position %d \n", substring,((int) (substring - mainstring)));

UIImageView - How to get the file name of the image assigned?

Nope. No way to do that natively. You're going to have to subclass UIImageView, and add an imageFileName property (which you set when you set the image).

Importing Excel into a DataTable Quickly

 class DataReader
    {
        Excel.Application xlApp;
        Excel.Workbook xlBook;
        Excel.Range xlRange;
        Excel.Worksheet xlSheet;
        public DataTable GetSheetDataAsDataTable(String filePath, String sheetName)
        {
            DataTable dt = new DataTable();
            try
            {
                xlApp = new Excel.Application();
                xlBook = xlApp.Workbooks.Open(filePath);
                xlSheet = xlBook.Worksheets[sheetName];
                xlRange = xlSheet.UsedRange;
                DataRow row=null;
                for (int i = 1; i <= xlRange.Rows.Count; i++)
                {
                    if (i != 1)
                        row = dt.NewRow();
                    for (int j = 1; j <= xlRange.Columns.Count; j++)
                    {
                        if (i == 1)
                            dt.Columns.Add(xlRange.Cells[1, j].value);
                        else
                            row[j-1] = xlRange.Cells[i, j].value;
                    }
                    if(row !=null)
                        dt.Rows.Add(row);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                xlBook.Close();
                xlApp.Quit();
            }
            return dt;
        }
    }

MongoDB: How to query for records where field is null or not set?

Seems you can just do single line:

{ "sent_at": null }

jQuery: Wait/Delay 1 second without executing code

jQuery's delay function is meant to be used with effects and effect queues, see the delay docs and the example therein:

$('#foo').slideUp(300).delay(800).fadeIn(400);

If you want to observe a variable for changes, you could do something like

(function() {
    var observerInterval = setInterval(function() {
        if (/* check for changes here */) {
           clearInterval(observerInterval);
           // do something here
        }
    }, 1000);
})();

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

In my case, I was using MySQL workbench and I faced the same issue while dropping one of my columns in a table. I could not find the name of the foreign key. I followed the following steps to resolve the issue:

  1. Rt. click on your schema and select 'schema inspector'. This gives you various tables, columns, indexes, ect.

  2. Go to the tab named 'Indexes' and search the name of the column under the column named 'Column'. Once found check the name of the table for this record under the column name 'Table'. If it matches the name of the table you want, then note down the name of the foreign key from the column named 'Name'.

  3. Now execute the query : ALTER table tableNamexx DROP KEY foreignKeyName;

  4. Now you can execute the drop statement which shall execute successfully.

How to add Action bar options menu in Android Fragments

in AndroidManifest.xml set theme holo like this:

<activity
android:name="your Fragment or activity"
android:label="@string/xxxxxx"
android:theme="@android:style/Theme.Holo" >

SQL Server datetime LIKE select?

You could use the DATEPART() function

SELECT * FROM record 
WHERE  (DATEPART(yy, register_date) = 2009
AND    DATEPART(mm, register_date) = 10
AND    DATEPART(dd, register_date) = 10)

I find this way easy to read, as it ignores the time component, and you don't have to use the next day's date to restrict your selection. You can go to greater or lesser granularity by adding extra clauses, using the appropriate DatePart code, e.g.

AND    DATEPART(hh, register_date) = 12)

to get records made between 12 and 1.

Consult the MSDN DATEPART docs for the full list of valid arguments.

Calling Member Functions within Main C++

If you want to make your code work as above, the function printInformation() needs to be declared and implemented as a static function.

If, on the other hand, it is supposed to print information about a specific object, you need to create the object first.

How to transition to a new view controller with code only using Swift

Always use nibName file otherwise your preloaded content of Xib will not show .

vc : ViewController =  ViewController(nibName: "ViewController", bundle: nil) //change this to your class name

 self.presentViewController(vc, animated: true, completion: nil)

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

Please check following snippet

_x000D_
_x000D_
 /* DEBUG */_x000D_
.lwb-col {_x000D_
    transition: box-shadow 0.5s ease;_x000D_
}_x000D_
.lwb-col:hover{_x000D_
    box-shadow: 0 15px 30px -4px rgba(136, 155, 166, 0.4);_x000D_
 _x000D_
}_x000D_
_x000D_
_x000D_
.lwb-col--link {_x000D_
    font-weight: 500;_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
}_x000D_
.lwb-col--link::after{_x000D_
    border-bottom: 2px solid;_x000D_
    bottom: -3px;_x000D_
    content: "";_x000D_
    display: block;_x000D_
    left: 0;_x000D_
    position: absolute;_x000D_
    width: 100%;_x000D_
    color: #E5E9EC;_x000D_
_x000D_
}_x000D_
.lwb-col--link::before{_x000D_
    border-bottom: 2px solid;_x000D_
    bottom: -3px;_x000D_
    content: "";_x000D_
    display: block;_x000D_
    left: 0;_x000D_
    position: absolute;_x000D_
    width: 100%;_x000D_
    color: #57B0FB;_x000D_
    transform: scaleX(0);_x000D_
    _x000D_
_x000D_
}_x000D_
.lwb-col:hover .lwb-col--link::before {_x000D_
    border-color: #57B0FB;_x000D_
    display: block;_x000D_
    z-index: 2;_x000D_
    transition: transform 0.3s;_x000D_
    transform: scaleX(1);_x000D_
    transform-origin: left center;_x000D_
}
_x000D_
<div class="lwb-col">_x000D_
  <h2>Webdesign</h2>_x000D_
  <p>Steigern Sie Ihre Bekanntheit im Web mit individuellem &amp; professionellem Webdesign. Organisierte Codestruktur, sowie perfekte SEO Optimierung und jahrelange Erfahrung sprechen für uns.</p>_x000D_
<span class="lwb-col--link">Mehr erfahren</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

CSV new-line character seen in unquoted field error

It'll be good to see the csv file itself, but this might work for you, give it a try, replace:

file_read = csv.reader(self.file)

with:

file_read = csv.reader(self.file, dialect=csv.excel_tab)

Or, open a file with universal newline mode and pass it to csv.reader, like:

reader = csv.reader(open(self.file, 'rU'), dialect=csv.excel_tab)

Or, use splitlines(), like this:

def read_file(self):
    with open(self.file, 'r') as f:
        data = [row for row in csv.reader(f.read().splitlines())]
    return data

Get the row(s) which have the max value in groups using groupby

Realizing that "applying" "nlargest" to groupby object works just as fine:

Additional advantage - also can fetch top n values if required:

In [85]: import pandas as pd

In [86]: df = pd.DataFrame({
    ...: 'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
    ...: 'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
    ...: 'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
    ...: 'count' : [3,2,5,8,10,1,2,2,7]
    ...: })

## Apply nlargest(1) to find the max val df, and nlargest(n) gives top n values for df:
In [87]: df.groupby(["sp", "mt"]).apply(lambda x: x.nlargest(1, "count")).reset_index(drop=True)
Out[87]:
   count  mt   sp  val
0      3  S1  MM1    a
1      5  S3  MM1   cb
2      8  S3  MM2   mk
3     10  S4  MM2   bg
4      7  S2  MM4  uyi

CSS/Javascript to force html table row on a single line

As cletus said, you should use white-space: nowrap to avoid the line wrapping, and overflow:hidden to hide the overflow. However, in order for a text to be considered overflow, you should set the td/th width, so in case the text requires more than the specified width, it will be considered an overflow, and will be hidden.

Also, if you give a sample web page, responders can provide an updated page with the fix you like.

Simple logical operators in Bash

Here is the code for the short version of if-then-else statement:

( [ $a -eq 1 ] || [ $b -eq 2 ] ) && echo "ok" || echo "nok"

Pay attention to the following:

  1. || and && operands inside if condition (i.e. between round parentheses) are logical operands (or/and)

  2. || and && operands outside if condition mean then/else

Practically the statement says:

if (a=1 or b=2) then "ok" else "nok"

Combine multiple JavaScript files into one JS file

You can use the Closure-compiler as orangutancloud suggests. It's worth pointing out that you don't actually need to compile/minify the JavaScript, it ought to be possible to simply concatenate the JavaScript text files into a single text file. Just join them in the order they're normally included in the page.

Git Diff with Beyond Compare

The Beyond Compare support page is a bit brief.

Check my diff.external answer for more (regarding the exact syntax)

Extract:

$ git config --global diff.external <path_to_wrapper_script>

at the command prompt, replacing with the path to "git-diff-wrapper.sh", so your ~/.gitconfig contains

-->8-(snip)--
[diff]
    external = <path_to_wrapper_script>
--8<-(snap)--

Be sure to use the correct syntax to specify the paths to the wrapper script and diff tool, i.e. use forward slashed instead of backslashes. In my case, I have

[diff]
    external = c:/Documents and Settings/sschuber/git-diff-wrapper.sh

in .gitconfig and

"d:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat

in the wrapper script.


Note: you can also use git difftool.

Arduino Tools > Serial Port greyed out

sudo arduino is the only way I get the Arduino IDE working (serial port and upload) on ubuntu 12.04 (64) Indeed the serial port to use is /dev/ttyACM0 in my case too. The other two (ttyS4 and ttyS0) gave an error when trying to upload to Uno. Have fun

ADB No Devices Found

Normally SDB will download the driver in the **android-sdk-windows\extras\google\usb_driver** path

Here are the steps that worked for me:

  1. Enable USB debugging.
  2. Do to device manager, right click on ADB device and click update driver software.
  3. Select "Browse my computer for Driver Software"
  4. Select "Let me pick from list of Device drivers on my computer"
  5. Click on "Have Disk" option.
  6. Select the driver path **android-sdk-windows\extras\google\usb_driver** (path of sdk) 7.Select 1st driver out of list of drivers shown.

And hopefully, it will work.

How to run iPhone emulator WITHOUT starting Xcode?

The easiest way is to use Spotlight Search. Just click CMD+Space and type in search Simulator. Just like this:

enter image description here

And in few seconds emulated device will be loaded:

enter image description here

To switch to another device you can use menu under Hardware -> Device

There are few different cool instruments you can use under Hardware menu, such as orientation change, gestures, buttons, FaceID, keyboard or audio inputs.

How to replace comma with a dot in the number (or any replacement)

After replacing the character, you need to be asign to the variable.

var tt = "88,9827";
tt = tt.replace(/,/g, '.')
alert(tt)

In the alert box it will shows 88.9827

Transparent ARGB hex value

Just use this :

android:background="#00FFFFFF"

it will do your work.

How can I access an internal class from an external assembly?

Well, you can't. Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.

Add ripple effect to my button with button background color?

When you use android:background, you are replacing much of the styling and look and feel of a button with a blank color.

Update: As of the version 23.0.0 release of AppCompat, there is a new Widget.AppCompat.Button.A colored style which uses your theme's colorButtonNormal for the disabled color and colorAccent for the enabled color.

This allows you apply it to your button directly via

<Button
 ...
style="@style/Widget.AppCompat.Button.Colored" />

You can use a drawable in your v21 directory for your background such as:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
<item android:drawable="?attr/colorPrimary"/>
</ripple>

This will ensure your background color is ?attr/colorPrimary and has the default ripple animation using the default ?attr/colorControlHighlight (which you can also set in your theme if you'd like).

Note: you'll have to create a custom selector for less than v21:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/primaryPressed"            android:state_pressed="true"/>
<item android:drawable="@color/primaryFocused" android:state_focused="true"/>
<item android:drawable="@color/primary"/>
</selector>

Detect iPad users using jQuery?

I use this:

//http://detectmobilebrowsers.com/ + tablets
(function(a) {
    if(/android|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(ad|hone|od)|iris|kindle|lge |maemo|meego.+mobile|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|playbook|silk/i.test(a)
    ||
    /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))
    {
        window.location="yourNewIndex.html"
    }
})(navigator.userAgent||navigator.vendor||window.opera);

How to remove all files from directory without removing directory in Node.js

Building on @Waterscroll's response, if you want to use async and await in node 8+:

const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';

async function toRun() {
  try {
    const files = await readdir(directory);
    const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
    return Promise.all(unlinkPromises);
  } catch(err) {
    console.log(err);
  }
}

toRun();

How do you import a large MS SQL .sql file?

Hope this help you!

sqlcmd -u UserName -s <ServerName\InstanceName> -i U:\<Path>\script.sql

Docker command can't connect to Docker daemon

For Ubuntu 16.04

Inside file /lib/systemd/system/docker.service change:

ExecStart=/usr/bin/dockerd fd://

with:

ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375

Inside file /etc/init.d/docker change:

DOCKER_OPTS=

with:

DOCKER_OPTS="-H tcp://0.0.0.0:2375"

and then restart your computer.

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Use This

$users = DB::table('users')
                    ->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();

Full screen background image in an activity

If you have bg.png as your background image then simply:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"/>
</RelativeLayout>

Center the content inside a column in Bootstrap 4

<div class="container">
    <div class="row justify-content-center">
        <div class="col-3 text-center">
            Center text goes here
        </div>
    </div>
</div>

I have used justify-content-center class instead of mx-auto as in this answer.

check at https://jsfiddle.net/sarfarazk/4fsp4ywh/

jQuery - Sticky header that shrinks when scrolling down

I did an upgraded version of jezzipin's answer (and I'm animating padding top instead of height but you still get the point.

 /**
 * ResizeHeaderOnScroll
 *
 * @constructor
 */
var ResizeHeaderOnScroll = function()
{
    this.protocol           = window.location.protocol;
    this.domain             = window.location.host;
};

ResizeHeaderOnScroll.prototype.init    = function()
{
    if($(document).scrollTop() > 0)
    {
        $('header').data('size','big');
    } else {
        $('header').data('size','small');
    }

    ResizeHeaderOnScroll.prototype.checkScrolling();

    $(window).scroll(function(){
        ResizeHeaderOnScroll.prototype.checkScrolling();
    });
};

ResizeHeaderOnScroll.prototype.checkScrolling    = function()
{
    if($(document).scrollTop() > 0)
    {
        if($('header').data('size') == 'big')
        {
            $('header').data('size','small');
            $('header').stop().animate({
                paddingTop:'1em',
                paddingBottom:'1em'
            },200);
        }
    }
    else
      {
        if($('header').data('size') == 'small')
        {
            $('header').data('size','big');
            $('header').stop().animate({
                paddingTop:'3em'
            },200);
        }  
      }
}

$(document).ready(function(){
    var resizeHeaderOnScroll = new ResizeHeaderOnScroll();
    resizeHeaderOnScroll.init()
})

"Default Activity Not Found" on Android Studio upgrade

nothing till here helped me and Android Studio made this problem with all my apps that were running before already - so I knew - it does not has to do with my code.

NOW I SOLVED IT:

You need to reset Android Studio: Just go to C:\Users\yourusername\androidStudio3.2 (or similar) and delete this directory.

This guy shows you exactly how to do it in his video in an older version: https://www.youtube.com/watch?v=AwZEliSPGwU&t

PHP Get URL with Parameter

Here's probably what you are looking for: php-get-url-query-string. You can combine it with other suggested $_SERVER parameters.

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

This will do it.

SET DATEFIRST 1;

-- YOUR QUERY

Examples

-- Sunday is first day of week
set datefirst 7; 
select DATEPART(dw,getdate()) as weekday


-- Monday is first day of week
set datefirst 1;
select DATEPART(dw,getdate()) as weekday

Default keystore file does not exist?

You must be providing the wrong path to the debug.keystore file.

Follow these steps to get the correct path and complete your command:

  1. In eclipse, click the Window menu -> Preferences -> Expand Android -> Build
  2. In the right panel, look for: Default debug keystore:
  3. Select the entire box next to the label specified in Step 2

And finally, use the path you just copied from Step 3 to construct your command:

For example, in my case, it would be:

C:\Program Files\Java\jre7\bin>keytool -list -v -keystore "C:\Users\Siddharth Lele.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

UPDATED:

If you had already followed the steps mentioned above, the only other solution is to delete the debug.keystore and let Eclipse recreate it for you.

Step 1: Go to the path where your keystore is stored. In your case, C:\Users\Suresh\.android\debug.keystore

Step 2: Close and restart Eclipse.

Step 3 (Optional): You may need to clean your project before the debug.keystore is created again.

Source: http://www.coderanch.com/t/440920/Security/KeyTool-genkeypair-exception-Keystore-file

You can refer to this for the part about deleting your debug.keystore file: "Debug certificate expired" error in Eclipse Android plugins

ojdbc14.jar vs. ojdbc6.jar

Actually, ojdbc14.jar doesn't really say anything about the real version of the driver (see JDBC Driver Downloads), except that it predates Oracle 11g. In such situation, you should provide the exact version.

Anyway, I think you'll find some explanation in What is going on with DATE and TIMESTAMP? In short, they changed the behavior in 9.2 drivers and then again in 11.1 drivers.

This might explain the differences you're experiencing (and I suggest using the most recent version i.e. the 11.2 drivers).

Android - SMS Broadcast receiver

intent.getAction().equals(SMS_RECEIVED)

I have tried it out successfully.

Removing Spaces from a String in C?

Easiest and most efficient don't usually go together...

Here's a possible solution:

void remove_spaces(char* s) {
    const char* d = s;
    do {
        while (*d == ' ') {
            ++d;
        }
    } while (*s++ = *d++);
}

jQuery: how to scroll to certain anchor/div on page load?

i achieve it like this..

if(location.pathname == '/registration')
{
$('html, body').animate({ scrollTop: $('#registration').offset().top - 40}, 1000);
}

Can Json.NET serialize / deserialize to / from a stream?

The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:

public static object DeserializeFromStream(Stream stream)
{
    var serializer = new JsonSerializer();

    using (var sr = new StreamReader(stream))
    using (var jsonTextReader = new JsonTextReader(sr))
    {
        return serializer.Deserialize(jsonTextReader);
    }
}

Documentation: Deserialize JSON from a file stream

DateTime.TryParse issue with dates of yyyy-dd-MM format

If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.

If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime format strings at runtime.

Where can I set path to make.exe on Windows?

I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly.

For anyone else finding this issue, I fixed it by moving the environment variable higher than others!

Automatically scroll down chat div

I prefer to use Vanilla JS

let chatWrapper = document.querySelector('#chat-messages');
chatWrapper.scrollTo(0, chatWrapper.offsetHeight );

where element.scrollTo(x-coord, y-coord)

How can I render repeating React elements?

This is, imo, the most elegant way to do it (with ES6). Instantiate you empty array with 7 indexes and map in one line:

Array.apply(null, Array(7)).map((i)=>
<Somecomponent/>
)

kudos to https://php.quicoto.com/create-loop-inside-react-jsx/

Using Mysql WHERE IN clause in codeigniter

try this:

return $this->db->query("
     SELECT * FROM myTable 
     WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B') 
     AND code!='B'
     ")->result_array();

Is not active record but is codeigniter's way http://codeigniter.com/user_guide/database/examples.html see Standard Query With Multiple Results (Array Version) section

JQuery - Storing ajax response into global variable

IMO you can store this data in global variable. But it will be better to use some more unique name or use namespace:

MyCompany = {};

...
MyCompany.cachedData = data;

And also it's better to use json for these purposes, data in json format is usually much smaller than the same data in xml format.

java.net.SocketTimeoutException: Read timed out under Tomcat

I have the same issue. The java.net.SocketTimeoutException: Read timed out error happens on Tomcat under Mac 11.1, but it works perfectly in Mac 10.13. Same Tomcat folder, same WAR file. Have tried setting timeout values higher, but nothing I do works. If I run the same SpringBoot code in a regular Java application (outside Tomcat 9.0.41 (tried other versions too), then it works also.

Mac 11.1 appears to be interfering with Tomcat.

As another test, if I copy the WAR file to an AWS EC2 instance, it works fine there too.

Spent several days trying to figure this out, but cannot resolve.

Suggestions very welcome! :)

How do I use CMake?

Regarding CMake 3.13.3, platform Windows, and IDE Visual Studio 2017, I suggest this guide. In brief I suggest:
1. Download cmake > unzip it > execute it.
2. As example download GLFW > unzip it > create inside folder Build.
3. In cmake Browse "Source" > Browse "Build" > Configure and Generate.
4. In Visual Studio 2017 Build your Solution.
5. Get the binaries.
Regards.

How to skip to next iteration in jQuery.each() util?

By 'return non-false', they mean to return any value which would not work out to boolean false. So you could return true, 1, 'non-false', or whatever else you can think up.

What is the "assert" function?

Take a look at

assert() example program in C++

Many compilers offer an assert() macro. The assert() macro returns TRUE if its parameter evaluates TRUE and takes some kind of action if it evaluates FALSE. Many compilers will abort the program on an assert() that fails; others will throw an exception

One powerful feature of the assert() macro is that the preprocessor collapses it into no code at all if DEBUG is not defined. It is a great help during development, and when the final product ships there is no performance penalty nor increase in the size of the executable version of the program.

Eg

#include <stdio.h>
#include <assert.h>

void analyze (char *, int);

int main(void)
{
   char *string = "ABC";
   int length = 3;

   analyze(string, length);
   printf("The string %s is not null or empty, "
          "and has length %d \n", string, length);
}

void analyze(char *string, int length)
{
   assert(string != NULL);     /* cannot be NULL */
   assert(*string != '\0');    /* cannot be empty */
   assert(length > 0);         /* must be positive */
}

/****************  Output should be similar to  ******************
The string ABC is not null or empty, and has length 3

Android get image path from drawable as string

I think you cannot get it as String but you can get it as int by get resource id:

int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());

how to pass list as parameter in function

You need to do it like this,

void Yourfunction(List<DateTime> dates )
{

}

What is the default scope of a method in Java?

The default scope is "default". It's weird--see these references for more info.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

I got this same error when installing to an actual device. More information and a solution to loading the missing libraries to the device can be found at the following site:

Fixing the INSTALL_FAILED_MISSING_SHARED_LIBRARY Error

To set this up correctly, there are 2 key files that need to be copied to the system:

com.google.android.maps.xml

com.google.android.maps.jar

These files are located in the any of these google app packs:

http://android.d3xt3...0120-signed.zip

http://goo-inside.me...0120-signed.zip

http://android.local...0120-signed.zip

These links no longer work, but you can find the files in the android sdk if you have Google Maps API v1

After unzipping any of these files, you want to copy the files to your system, like-ah-so:

adb remount

adb push system/etc/permissions/com.google.android.maps.xml /system/etc/permissions

adb push system/framework/com.google.android.maps.jar /system/framework

adb reboot

Make xargs execute the command once for each line of input

In your example, the point of piping the output of find to xargs is that the standard behavior of find's -exec option is to execute the command once for each found file. If you're using find, and you want its standard behavior, then the answer is simple - don't use xargs to begin with.

Git Symlinks in Windows

I just tried with Git 2.30.0 (released 2020-12-28).

This is NOT a full answer but a few useful tidbits nonetheless. (Feel free to cannibalize for your own answer.)

There's a documentation link when installing Git for Windows

enter image description here

This link takes you here: https://github.com/git-for-windows/git/wiki/Symbolic-Links

And this is quite a longish discussion.

Also symbolic links keep popping up in the release notes. As of 2.30.0 this here is still listed as a "Known issue":

On Windows 10 before 1703, or when Developer Mode is turned off, special permissions are required when cloning repositories with symbolic links, therefore support for symbolic links is disabled by default. Use git clone -c core.symlinks=true <URL> to enable it, see details here.

Are multi-line strings allowed in JSON?

This is a really old question, but I came across this on a search and I think I know the source of your problem.

JSON does not allow "real" newlines in its data; it can only have escaped newlines. See the answer from @YOU. According to the question, it looks like you attempted to escape line breaks in Python two ways: by using the line continuation character ("\") or by using "\n" as an escape.

But keep in mind: if you are using a string in python, special escaped characters ("\t", "\n") are translated into REAL control characters! The "\n" will be replaced with the ASCII control character representing a newline character, which is precisely the character that is illegal in JSON. (As for the line continuation character, it simply takes the newline out.)

So what you need to do is to prevent Python from escaping characters. You can do this by using a raw string (put r in front of the string, as in r"abc\ndef", or by including an extra slash in front of the newline ("abc\\ndef").

Both of the above will, instead of replacing "\n" with the real newline ASCII control character, will leave "\n" as two literal characters, which then JSON can interpret as a newline escape.

Encrypt Password in Configuration Files?

See what is available in Jetty for storing password (or hashes) in configuration files, and consider if the OBF encoding might be useful for you. Then see in the source how it is done.

http://www.eclipse.org/jetty/documentation/current/configuring-security-secure-passwords.html

Java: How to check if object is null?

DIY

private boolean isNull(Object obj) {
    return obj == null;
}

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (isNull(drawable)) {
    drawable = getRandomDrawable();
}

Google API for location, based on user IP address

Here's a script that will use the Google API to acquire the users postal code and populate an input field.

function postalCodeLookup(input) {
    var head= document.getElementsByTagName('head')[0],
        script= document.createElement('script');
    script.src= '//maps.googleapis.com/maps/api/js?sensor=false';
    head.appendChild(script);
    script.onload = function() {
        if (navigator.geolocation) {
            var a = input,
                fallback = setTimeout(function () {
                    fail('10 seconds expired');
                }, 10000);

            navigator.geolocation.getCurrentPosition(function (pos) {
                clearTimeout(fallback);
                var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
                new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
                    if (status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
                        var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
                        if (zip) {
                            a.value = zip[1];
                        } else fail('Unable to look-up postal code');
                    } else {
                        fail('Unable to look-up geolocation');
                    }
                });
            }, function (err) {
                fail(err.message);
            });
        } else {
            alert('Unable to find your location.');
        }
        function fail(err) {
            console.log('err', err);
            a.value('Try Again.');
        }
    };
}

You can adjust accordingly to acquire different information. For more info, check out the Google Maps API documentation.

How to make the python interpreter correctly handle non-ASCII characters in string operations?

#!/usr/bin/env python
# -*- coding: utf-8 -*-

s = u"6Â 918Â 417Â 712"
s = s.replace(u"Â", "") 
print s

This will print out 6 918 417 712

Why does make think the target is up to date?

EDIT: This only applies to some versions of make - you should check your man page.

You can also pass the -B flag to make. As per the man page, this does:

-B, --always-make Unconditionally make all targets.

So make -B test would solve your problem if you were in a situation where you don't want to edit the Makefile or change the name of your test folder.

Do AJAX requests retain PHP Session info?

put your session() auth in all server side pages accepting an ajax request:

if(require_once("auth.php")) {

//run json code

}

// do nothing otherwise

that's about the only way I've ever done it.

How do I get the path of the Python script I am running in?

7.2 of Dive Into Python: Finding the Path.

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

AJAX POST and Plus Sign ( + ) -- How to Encode?

If you have to do a curl in php, you should use urlencode() from PHP but individually!

strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+")

If you do urlencode(strPOST), you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!

Example 1

$strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+") will give Item1=Value1&Item2=%2B

Example 2

$strPOST = urlencode("Item1=" . $Value1 . "&Item2=+") will give Item1%3DValue1%26Item2%3D%2B

Example 1 is the good way to prepare string for POST in curl

Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!

LINUX: Link all files from one to another directory

The posted solutions will not link any hidden files. To include them, try this:

cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib not /mnt/usr/lib), you could do this:

cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

how to call a function from another function in Jquery

wrap you shared code into another function:

<script>
  function myFun () {
      //do something
  }

  $(document).ready(function(){
    //Load City by State
    $(document).on('change', '#billing_state_id', function() {
       myFun ();
    });   
    $(document).on('click', '#click_me', function() {
       //do something
       myFun();
    });   
  });
</script>

Subtracting 2 lists in Python

If you plan on performing more than simple one liners, it would be better to implement your own class and override the appropriate operators as they apply to your case.

Taken from Mathematics in Python:

class Vector:

  def __init__(self, data):
    self.data = data

  def __repr__(self):
    return repr(self.data)  

  def __add__(self, other):
    data = []
    for j in range(len(self.data)):
      data.append(self.data[j] + other.data[j])
    return Vector(data)  

x = Vector([1, 2, 3])    
print x + x

How to redirect both stdout and stderr to a file

You can do it like that 2>&1:

 command > file 2>&1

Styling Password Fields in CSS

When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)

SCSS styles

@font-face {
  font-family: 'pass';
  font-style: normal;
  font-weight: 400;
  src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}

input.password {
  font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
  font-size: 18px;
  &::-webkit-input-placeholder {
    transform: scale(0.77);
    transform-origin: 0 50%;
  }
  &::-moz-placeholder {
    font-size: 14px;
    opacity: 1;
  }
  &:-ms-input-placeholder {
    font-size: 14px;
    font-family: 'Roboto', Helvetica, Arial, sans-serif;
  }

After that, I got identical display input[password]

How to select a radio button by default?

XHTML solution:

<input type="radio" name="imgsel" value="" checked="checked" />

Please note, that the actual value of checked attribute does not actually matter; it's just a convention to assign "checked". Most importantly, strings like "true" or "false" don't have any special meaning.

If you don't aim for XHTML conformance, you can simplify the code to:

<input type="radio" name="imgsel" value="" checked>

Breaking out of a for loop in Java

You can use:

for (int x = 0; x < 10; x++) {
  if (x == 5) { // If x is 5, then break it.
    break;
  }
}

Is there something like Codecademy for Java

Check out CodingBat! It really helped me learn java way back when (although it used to be JavaBat back then). It's a lot like Codecademy.

How to find the mime type of a file in python?

This seems to be very easy

>>> from mimetypes import MimeTypes
>>> import urllib 
>>> mime = MimeTypes()
>>> url = urllib.pathname2url('Upload.xml')
>>> mime_type = mime.guess_type(url)
>>> print mime_type
('application/xml', None)

Please refer Old Post

Update - In python 3+ version, it's more convenient now:

import mimetypes
print(mimetypes.guess_type("sample.html"))

Calculate distance between two points in google maps V3

If you want to calculate it yourself, then you can use the Haversine formula:

var rad = function(x) {
  return x * Math.PI / 180;
};

var getDistance = function(p1, p2) {
  var R = 6378137; // Earth’s mean radius in meter
  var dLat = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
    Math.sin(dLong / 2) * Math.sin(dLong / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d; // returns the distance in meter
};

What does file:///android_asset/www/index.html mean?

If someone uses AndroidStudio make sure that the assets folder is placed in

  1. app/src/main/assets

    directory.

How to vertically align into the center of the content of a div with defined width/height?

This could also be done using display: flex with only a few lines of code. Here is an example:

.container {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
}

Live Demo

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

tl;dr

Use only modern java.time classes. Never use the terrible legacy classes such as SimpleDateFormat, Date, or java.sql.Timestamp.

ZonedDateTime                    // Represent a moment as perceived in the wall-clock time used by the people of a particular region ( a time zone).
.now(                            // Capture the current moment.
    ZoneId.of( "Africa/Tunis" )  // Specify the time zone using proper Continent/Region name. Never use 3-4 character pseudo-zones such as PDT, EST, IST. 
)                                // Returns a `ZonedDateTime` object. 
.format(                         // Generate a `String` object containing text representing the value of our date-time object. 
    DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" )
)                                // Returns a `String`. 

Or use the JVM’s current default time zone.

ZonedDateTime
.now( ZoneId.systemDefault() )
.format( DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" ) )

java.time & JDBC 4.2

The modern approach uses the java.time classes as seen above.

If your JDBC driver complies with JDBC 4.2, you can directly exchange java.time objects with the database. Use PreparedStatement::setObject and ResultSet::getObject.

Use java.sql only for drivers before JDBC 4.2

If your JDBC driver does not yet comply with JDBC 4.2 for support of java.time types, you must fall back to using the java.sql classes.

Storing data.

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;  // Capture the current moment in UTC.
myPreparedStatement.setObject( … , odt ) ;

Retrieving data.

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

The java.sql types, such as java.sql.Timestamp, should only be used for transfer in and out of the database. Immediately convert to java.time types in Java 8 and later.

java.time.Instant

A java.sql.Timestamp maps to a java.time.Instant, a moment on the timeline in UTC. Notice the new conversion method toInstant added to the old class.

java.sql.Timestamp ts = myResultSet.getTimestamp( … );
Instant instant = ts.toInstant(); 

Time Zone

Apply the desired/expected time zone (ZoneId) to get a ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Formatted Strings

Use a DateTimeFormatter to generate your string. The pattern codes are similar to those of java.text.SimpleDateFormat but not exactly, so read the doc carefully.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" );
String output = zdt.format( formatter );

This particular format is ambiguous as to its exact meaning as it lacks any indication of offset-from-UTC or time zone.

ISO 8601

If you have any say in the matter, I suggest you consider using standard ISO 8601 formats rather than rolling your own. The standard format is quite similar to yours. For example:
2016-02-20T03:26:32+05:30.

The java.time classes use these standard formats by default, so no need to specify a pattern. The ZonedDateTime class extends the standard format by appending the name of the time zone (a wise improvement).

String output = zdt.toString(); // Example: 2007-12-03T10:15:30+01:00[Europe/Paris]

Convert to java.sql

You can convert from java.time back to java.sql.Timestamp. Extract an Instant from the ZonedDateTime.

New methods have been added to the old classes to facilitate converting to/from java.time classes.

java.sql.Timestamp ts = java.sql.Timestamp.from( zdt.toInstant() );

Table of date-time types in Java (both legacy and modern) and in standard SQL


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to set text color in submit button?

Use this CSS:

color: red;

that's all.

ImportError: No module named matplotlib.pyplot

If you using Anaconda3

Just put

conda install -c conda-forge matplotlib

Nullable type as a generic parameter possible?

This may be a dead thread, but I tend to use the following:

public static T? GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : struct 
{
    return reader[columnName] as T?;
}

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

Sublime Text 2 Code Formatting

A similar option in Sublime Text is the built in Edit->Line->Reindent. You can put this code in Preferences -> Key Bindings User:

{ "keys": ["alt+shift+f"], "command": "reindent"} 

I use alt+shift+f because I'm a Netbeans user.

To format your code, select all by pressing ctrl+a and "your key combination". Excuse me for my bad english.


Or if you don't want to select all before formatting, add an argument to the command instead:

{ "keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false} }

(as per comment by @Supr below)

Get domain name from given url

I made a small treatment after the URI object creation

 if (url.startsWith("http:/")) {
        if (!url.contains("http://")) {
            url = url.replaceAll("http:/", "http://");
        }
    } else {
        url = "http://" + url;
    }
    URI uri = new URI(url);
    String domain = uri.getHost();
    return domain.startsWith("www.") ? domain.substring(4) : domain;

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

Output on Windows 7 (64-bit)

SpecialFolder.CommonApplicationData: C:\ProgramData 
SpecialFolder.CommonDesktopDirectory: C:\Users\Public\Desktop
SpecialFolder.CommonStartMenu: C:\ProgramData\Microsoft\Windows\Start Menu
SpecialFolder.CommonPrograms: C:\ProgramData\Microsoft\Windows\Start Menu\Programs
SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files
SpecialFolder.CommonProgramFilesX86: C:\Program Files (x86)\Common Files
SpecialFolder.CommonStartup: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
SpecialFolder.ProgramFiles: C:\Program Files
SpecialFolder.ProgramFilesX86: C:\Program Files (x86)
SpecialFolder.System: C:\Windows\system32
SpecialFolder.SystemX86: C:\Windows\SysWOW64

Output on Windows XP

SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data
SpecialFolder.CommonDesktopDirectory: C:\Documents and Settings\All Users\Desktop
SpecialFolder.CommonPrograms: C:\Documents and Settings\All Users\Start Menu\Programs
SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files
SpecialFolder.CommonProgramFilesX86:
SpecialFolder.CommonStartMenu: C:\Documents and Settings\All Users\Start Menu
SpecialFolder.CommonStartup: C:\Documents and Settings\All Users\Start Menu\Programs\Startup
SpecialFolder.ProgramFiles: C:\Program Files
SpecialFolder.ProgramFilesX86:
SpecialFolder.System: C:\WINDOWS\system32
SpecialFolder.SystemX86: C:\WINDOWS\system32

Using Composer's Autoload

In my opinion, Sergiy's answer should be the selected answer for the given question. I'm sharing my understanding.

I was looking to autoload my package files using composer which I have under the dir structure given below.

<web-root>
    |--------src/
    |           |--------App/
    |           |
    |           |--------Test/
    |
    |---------library/
    |
    |---------vendor/
    |           |
    |           |---------composer/
    |           |           |---------autoload_psr4.php
    |           |           
    |           |----------autoload.php
    |
    |-----------composer.json
    |

I'm using psr-4 autoloading specification.

Had to add below lines to the project's composer.json. I intend to place my class files inside src/App , src/Test and library directory.

"autoload": {
        "psr-4": {
            "OrgName\\AppType\\AppName\\": ["src/App", "src/Test", "library/"]
        }
    } 

This is pretty much self explaining. OrgName\AppType\AppName is my intended namespace prefix. e.g for class User in src/App/Controller/Provider/User.php -

namespace OrgName\AppType\AppName\Controller\Provider; // namespace declaration

use OrgName\AppType\AppName\Controller\Provider\User; // when using the class

Also notice "src/App", "src/Test" .. are from your web-root that is where your composer.json is. Nothing to do with the vendor dir. take a look at vendor/autoload.php

Now if composer is installed properly all that is required is #composer update

After composer update my classes loaded successfully. What I observed is that composer is adding a line in vendor/composer/autoload_psr4.php

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
    'OrgName\\AppType\\AppName\\' => array($baseDir . '/src/App', $baseDir . '/src/Test', $baseDir . '/library'),
);

This is how composer maps. For psr-0 mapping is in vendor/composer/autoload_classmap.php

Getting A File's Mime Type In Java

Unfortunately,

mimeType = file.toURL().openConnection().getContentType();

does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.

However, you have this:

mimeType= URLConnection.guessContentTypeFromName(file.getName());

and also the following, which has the advantage of going beyond mere use of file extension, and takes a peek at content

InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
 //...close stream

However, as suggested by the comment above, the built-in table of mime-types is quite limited, not including, for example, MSWord and PDF. So, if you want to generalize, you'll need to go beyond the built-in libraries, using, e.g., Mime-Util (which is a great library, using both file extension and content).

Multi-Column Join in Hibernate/JPA Annotations

This worked for me . In my case 2 tables foo and boo have to be joined based on 3 different columns.Please note in my case ,in boo the 3 common columns are not primary key

i.e., one to one mapping based on 3 different columns

@Entity
@Table(name = "foo")
public class foo implements Serializable
{
    @Column(name="foocol1")
    private String foocol1;
    //add getter setter
    @Column(name="foocol2")
    private String foocol2;
    //add getter setter
    @Column(name="foocol3")
    private String foocol3;
    //add getter setter
    private Boo boo;
    private int id;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "brsitem_id", updatable = false)
    public int getId()
    {
        return this.id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    @OneToOne
    @JoinColumns(
    {
        @JoinColumn(updatable=false,insertable=false, name="foocol1", referencedColumnName="boocol1"),
        @JoinColumn(updatable=false,insertable=false, name="foocol2", referencedColumnName="boocol2"),
        @JoinColumn(updatable=false,insertable=false, name="foocol3", referencedColumnName="boocol3")
    }
    )
    public Boo getBoo()
    {
        return boo;
    }
    public void setBoo(Boo boo)
    {
        this.boo = boo;
    }
}





@Entity
@Table(name = "boo")
public class Boo implements Serializable
{
    private int id;
    @Column(name="boocol1")
    private String boocol1;
    //add getter setter
    @Column(name="boocol2")
    private String boocol2;
    //add getter setter
    @Column(name="boocol3")
    private String boocol3;
    //add getter setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "item_id", updatable = false)
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
}

How to initialize all members of an array to the same value?

If you mean in parallel, I think the comma operator when used in conjunction with an expression can do that:

a[1]=1, a[2]=2, ..., a[indexSize]; 

or if you mean in a single construct, you could do that in a for loop:

for(int index = 0, value = 10; index < sizeof(array)/sizeof(array[0]); index++, value--)
  array[index] = index;

//Note the comma operator in an arguments list is not the parallel operator described above;

You can initialize an array decleration:

array[] = {1, 2, 3, 4, 5};

You can make a call to malloc/calloc/sbrk/alloca/etc to allocate a fixed region of storage to an object:

int *array = malloc(sizeof(int)*numberOfListElements/Indexes);

and access the members by:

*(array + index)

Etc.

C# List of objects, how do I get the sum of a property

Another alternative:

myPlanetsList.Select(i => i.Moons).Sum();

How can you remove all documents from a collection with Mongoose?

MongoDB shell version v4.2.6
Node v14.2.0

Assuming you have a Tour Model: tourModel.js

const mongoose = require('mongoose');

const tourSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'A tour must have a name'],
    unique: true,
    trim: true,
  },
  createdAt: {
    type: Date,
    default: Date.now(),
  },
});
const Tour = mongoose.model('Tour', tourSchema);

module.exports = Tour;

Now you want to delete all tours at once from your MongoDB, I also providing connection code to connect with the remote cluster. I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.

const mongoose = require('mongoose');
const Tour = require('./../../models/tourModel');
const conStr = 'mongodb+srv://lord:<PASSWORD>@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority';
const DB = conStr.replace('<PASSWORD>','ADUSsaZEKESKZX');
mongoose.connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
  })
  .then((con) => {
    console.log(`DB connection successful ${con.path}`);
  });

const deleteAllData = async () => {
  try {
    await Tour.deleteMany();
    console.log('All Data successfully deleted');
  } catch (err) {
    console.log(err);
  }
};

"Could not find a part of the path" error message

There can be one of the two cause for this error:

  1. Path is not correct - but it is less likely as CreateDirectory should create any path unless path itself is not valid, read invalid characters
  2. Account through which your application is running don't have rights to create directory at path location, like if you are trying to create directory on shared drive with not enough privileges etc

How to rollback just one step using rake db:migrate

Other people have already answered you how to rollback, but you also asked how you could identify the version number of a migration.

  • rake db:migrate:status gives a list of your migrations version, name and status (up or down)
  • Your can also find the migration file, which contain a timestamp in the filename, that is the version number. Migrations are located in folder: /db/migrate

What's the difference between integer class and numeric class in R

To quote the help page (try ?integer), bolded portion mine:

Integer vectors exist so that data can be passed to C or Fortran code which expects them, and so that (small) integer data can be represented exactly and compactly.

Note that current implementations of R use 32-bit integers for integer vectors, so the range of representable integers is restricted to about +/-2*10^9: doubles can hold much larger integers exactly.

Like the help page says, R's integers are signed 32-bit numbers so can hold between -2147483648 and +2147483647 and take up 4 bytes.

R's numeric is identical to an 64-bit double conforming to the IEEE 754 standard. R has no single precision data type. (source: help pages of numeric and double). A double can store all integers between -2^53 and 2^53 exactly without losing precision.

We can see the data type sizes, including the overhead of a vector (source):

> object.size(1:1000)
4040 bytes
> object.size(as.numeric(1:1000))
8040 bytes

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.


Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginscript</string>
   <key>ProgramArguments</key>
   <array><string>/path/to/executable/script.sh</string></array>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

How to listen to the window scroll event in a VueJS component?

I've been in the need for this feature many times, therefore I've extracted it into a mixin. It can be used like this:

import windowScrollPosition from 'path/to/mixin.js'

new Vue({
  mixins: [ windowScrollPosition('position') ]
})

This creates a reactive position property (can be named whatever we like) on the Vue instance. The property contains the window scroll position as an [x,y] array.

Feel free to play around with this CodeSandbox demo.

Here's the code of the mixin. It's thoroughly commentated, so it should not be too hard to get an idea how it works:

function windowScrollPosition(propertyName) {
  return {
    data() {
      return {
        // Initialize scroll position at [0, 0]
        [propertyName]: [0, 0]
      }
    },
    created() {
      // Only execute this code on the client side, server sticks to [0, 0]
      if (!this.$isServer) {
        this._scrollListener = () => {
          // window.pageX/YOffset is equivalent to window.scrollX/Y, but works in IE
          // We round values because high-DPI devies can provide some really nasty subpixel values
          this[propertyName] = [
            Math.round(window.pageXOffset),
            Math.round(window.pageYOffset)
          ]
        }

        // Call listener once to detect initial position
        this._scrollListener()

        // When scrolling, update the position
        window.addEventListener('scroll', this._scrollListener)
      }
    },
    beforeDestroy() {
      // Detach the listener when the component is gone
      window.removeEventListener('scroll', this._scrollListener)
    }
  }
}

Merge PDF files

I used pdf unite on the linux terminal by leveraging subprocess (assumes one.pdf and two.pdf exist on the directory) and the aim is to merge them to three.pdf

 import subprocess
 subprocess.call(['pdfunite one.pdf two.pdf three.pdf'],shell=True)

django - get() returned more than one topic

I had same problem and solution was obj = ClassName.objects.filter()

JavaScript Loading Screen while page loads

You can wait until the body is ready:

_x000D_
_x000D_
function onReady(callback) {_x000D_
  var intervalId = window.setInterval(function() {_x000D_
    if (document.getElementsByTagName('body')[0] !== undefined) {_x000D_
      window.clearInterval(intervalId);_x000D_
      callback.call(this);_x000D_
    }_x000D_
  }, 1000);_x000D_
}_x000D_
_x000D_
function setVisible(selector, visible) {_x000D_
  document.querySelector(selector).style.display = visible ? 'block' : 'none';_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
  setVisible('.page', true);_x000D_
  setVisible('#loading', false);_x000D_
});
_x000D_
body {_x000D_
  background: #FFF url("https://i.imgur.com/KheAuef.png") top left repeat-x;_x000D_
  font-family: 'Alex Brush', cursive !important;_x000D_
}_x000D_
_x000D_
.page    { display: none; padding: 0 0.5em; }_x000D_
.page h1 { font-size: 2em; line-height: 1em; margin-top: 1.1em; font-weight: bold; }_x000D_
.page p  { font-size: 1.5em; line-height: 1.275em; margin-top: 0.15em; }_x000D_
_x000D_
#loading {_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  z-index: 100;_x000D_
  width: 100vw;_x000D_
  height: 100vh;_x000D_
  background-color: rgba(192, 192, 192, 0.5);_x000D_
  background-image: url("https://i.stack.imgur.com/MnyxU.gif");_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>_x000D_
<link href="https://fonts.googleapis.com/css?family=Alex+Brush" rel="stylesheet">_x000D_
<div class="page">_x000D_
  <h1>The standard Lorem Ipsum passage</h1>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
<div id="loading"></div>
_x000D_
_x000D_
_x000D_

Here is a JSFiddle that demonstrates this technique.

What is the mouse down selector in CSS?

I figured out that this behaves like a mousedown event:

button:active:hover {}

Twitter bootstrap hide element on small devices

<div class="small hidden-xs">
    Some Content Here
</div>

This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.

This answer satisfies the question in the OP title (which is how I found this Q/A).

How to query a MS-Access Table from MS-Excel (2010) using VBA

The Provider piece must be Provider=Microsoft.ACE.OLEDB.12.0 if your target database is ACCDB format. Provider=Microsoft.Jet.OLEDB.4.0 only works for the older MDB format.

You shouldn't even need Access installed if you're running 32 bit Windows. Jet 4 is included as part of the operating system. If you're using 64 bit Windows, Jet 4 is not included, but you still wouldn't need Access itself installed. You can install the Microsoft Access Database Engine 2010 Redistributable. Make sure to download the matching version (AccessDatabaseEngine.exe for 32 bit Windows, or AccessDatabaseEngine_x64.exe for 64 bit).

You can avoid the issue about which ADO version reference by using late binding, which doesn't require any reference.

Dim conn As Object
Set conn = CreateObject("ADODB.Connection")

Then assign your ConnectionString property to the conn object. Here is a quick example which runs from a code module in Excel 2003 and displays a message box with the row count for MyTable. It uses late binding for the ADO connection and recordset objects, so doesn't require setting a reference.

Public Sub foo()
    Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\Access\webforums\whiteboard2003.mdb"
    strSql = "SELECT Count(*) FROM MyTable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.fields(0) & " rows in MyTable"
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub

If this answer doesn't resolve the problem, edit your question to show us the full connection string you're trying to use and the exact error message you get in response for that connection string.

Eclipse projects not showing up after placing project files in workspace/projects

Even I had also observed the similar problem. I had closed my eclipse project because of some reason and on restart some of my file added were not visible in explorer even though corresponding file were existing.

Following solution worked for me: Select whole workspace (Ctrl+A) ==> Righ click and press Refresh.

how to write an array to a file Java

Just loop over the elements in your array.

Ex:

for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here

How do I UPDATE from a SELECT in SQL Server?

I was using INSERT SELECT Before, for those who want to use new stuff i will put this solution that works similar but much shorter:

UPDATE table1                                     //table that's going to be updated
LEFT JOIN                                         //type of join
table2 AS tb2                                     //second table and rename for easy
ON
tb2.filedToMatchTables = table1.fieldToMatchTables//fileds to connect both tables
SET   
fieldFromTable1 = tb2.fieldFromTable2;            //field to be updated on table1

field1FromTable1 = tb2.field1FromTable2,          //This is in the case you need to
field1FromTable1 = tb2.field1FromTable2,          //update more than one field
field1FromTable1 = tb2.field1FromTable2;          //remember to put ; at the end

Linq select objects in list where exists IN (A,B,C)

Just be careful, .Contains() will match any substring including the string that you do not expect. For eg. new[] { "A", "B", "AA" }.Contains("A") will return you both A and AA which you might not want. I have been bitten by it.

.Any() or .Exists() is safer choice

Excel VBA function to print an array to the workbook

As others have suggested, you can directly write a 2-dimensional array into a Range on sheet, however if your array is single-dimensional then you have two options:

  1. Convert your 1D array into a 2D array first, then print it on sheet (as a Range).
  2. Convert your 1D array into a string and print it in a single cell (as a String).

Here is an example depicting both options:

Sub PrintArrayIn1Cell(myArr As Variant, cell As Range)
    cell = Join(myArr, ",")
End Sub
Sub PrintArrayAsRange(myArr As Variant, cell As Range)
    cell.Resize(UBound(myArr, 1), UBound(myArr, 2)) = myArr
End Sub
Sub TestPrintArrayIntoSheet()  '2dArrayToSheet
    Dim arr As Variant
    arr = Split("a  b  c", "  ")

    'Printing in ONE-CELL: To print all array-elements as a single string separated by comma (a,b,c):
    PrintArrayIn1Cell arr, [A1]

    'Printing in SEPARATE-CELLS: To print array-elements in separate cells:
    Dim arr2D As Variant
    arr2D = Application.WorksheetFunction.Transpose(arr) 'convert a 1D array into 2D array
    PrintArrayAsRange arr2D, Range("B1:B3")
End Sub

Note: Transpose will render column-by-column output, to get row-by-row output transpose it again - hope that makes sense.

HTH

Null vs. False vs. 0 in PHP

One interesting fact about NULL in PHP: If you set a var equal to NULL, it is the same as if you had called unset() on it.

NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0, "0", "", and false.

Conditionally Remove Dataframe Rows with R

Logic index:

d<-d[!(d$A=="B" & d$E==0),]

Add new field to every document in a MongoDB collection

Pymongo 3.9+

update() is now deprecated and you should use replace_one(), update_one(), or update_many() instead.

In my case I used update_many() and it solved my issue:

db.your_collection.update_many({}, {"$set": {"new_field": "value"}}, upsert=False, array_filters=None)

From documents

update_many(filter, update, upsert=False, array_filters=None, bypass_document_validation=False, collation=None, session=None)


filter: A query that matches the documents to update.

update: The modifications to apply.

upsert (optional): If True, perform an insert if no documents match the filter.

bypass_document_validation (optional): If True, allows the write to opt-out of document level validation. Default is False.

collation (optional): An instance of Collation. This option is only supported on MongoDB 3.4 and above.

array_filters (optional): A list of filters specifying which array elements an update should apply. Requires MongoDB 3.6+.

session (optional): a ClientSession.

Disable password authentication for SSH

The one-liner to disable SSH password authentication:

sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config && service ssh restart

set height of imageview as matchparent programmatically

For Kotlin Users

val params = mImageView?.layoutParams as FrameLayout.LayoutParams
params.width = FrameLayout.LayoutParams.MATCH_PARENT
params.height = FrameLayout.LayoutParams.MATCH_PARENT
mImageView?.layoutParams = params

Here I used FrameLayout.LayoutParams since my views( ImageView) parent is FrameLayout

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

How to for each the hashmap?

You can iterate over a HashMap (and many other collections) using an iterator, e.g.:

HashMap<T,U> map = new HashMap<T,U>();

...

Iterator it = map.values().iterator();

while (it.hasNext()) {
    System.out.println(it.next());
}

Selecting only numeric columns from a data frame

Filter() from the base package is the perfect function for that use-case: You simply have to code:

Filter(is.numeric, x)

It is also much faster than select_if():

library(microbenchmark)
microbenchmark(
    dplyr::select_if(mtcars, is.numeric),
    Filter(is.numeric, mtcars)
)

returns (on my computer) a median of 60 microseconds for Filter, and 21 000 microseconds for select_if (350x faster).

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

I use Android Studio 3.0 and encounter this problem. And I'm sure app's build.gradle is OK.

Go to Run -> Edit Configurations -> Profiling, and disable "Enable advanced profiling".

This works for me. Reference answer

Set opacity of background image without affecting child elements

This will work with every browser

div {
 -khtml-opacity:.50; 
 -moz-opacity:.50; 
 -ms-filter:"alpha(opacity=50)";
  filter:alpha(opacity=50);
  filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
  opacity:.50; 
}

If you don't want transparency to affect the entire container and its children, check this workaround. You must have an absolutely positioned child with a relatively positioned parent.

Check demo at http://www.impressivewebs.com/css-opacity-that-doesnt-affect-child-elements/

How to add target="_blank" to JavaScript window.location?

_x000D_
_x000D_
    var linkGo = function(item) {_x000D_
      $(item).on('click', function() {_x000D_
        var _$this = $(this);_x000D_
        var _urlBlank = _$this.attr("data-link");_x000D_
        var _urlTemp = _$this.attr("data-url");_x000D_
        if (_urlBlank === "_blank") {_x000D_
          window.open(_urlTemp, '_blank');_x000D_
        } else {_x000D_
          // cross-origin_x000D_
          location.href = _urlTemp;_x000D_
        }_x000D_
      });_x000D_
    };_x000D_
_x000D_
    linkGo(".button__main[data-link]");
_x000D_
.button{cursor:pointer;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<span class="button button__main" data-link="" data-url="https://stackoverflow.com/">go stackoverflow</span>
_x000D_
_x000D_
_x000D_

Convert array of JSON object strings to array of JS objects

If you have a JS array of JSON objects:

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');

See the speed tests for browser comparisons.


If you have a single JSON string representing an array of objects:

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = JSON.parse(s);

If you have an array of objects:

// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];

…and you want JSON representation for it, then:

// JSON string representing an array of objects
var json = JSON.stringify(s);

…or if you want a JavaScript array of JSON strings, then:

// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);

// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);

Python: How to get stdout after running os.system?

I had to use os.system, since subprocess was giving me a memory error for larger tasks. Reference for this problem here. So, in order to get the output of the os.system command I used this workaround:

import os

batcmd = 'dir'
result_code = os.system(batcmd + ' > output.txt')
if os.path.exists('output.txt'):
    fp = open('output.txt', "r")
    output = fp.read()
    fp.close()
    os.remove('output.txt')
    print(output)

document.body.appendChild(i)

If your script is inside head tag in html file, try to put it inside body tag. CreateElement while script is inside head tag will give you a null warning

<head>
  <title></title>
</head>

<body>
  <h1>Game</h1>
  <script type="text/javascript" src="script.js"></script>
</body>

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

  1. Go to Sql Server Management Studio >
  2. Object Explorer >
  3. Databases >
  4. Choose and expand your Database.
  5. Under your database right click on "Database Diagrams" and select "New Database Diagram".
  6. It will a open a new window. Choose tables to include in ER-Diagram (to select multiple tables press "ctrl" or "shift" button and select tables).
  7. Click add.
  8. Wait for it to complete. Done!

You can save generated diagram for future use.

screenshot

send/post xml file using curl command line

Powershell + Curl + Zimbra SOAP API

${my_xml} = @"
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">
  <soapenv:Body>
   <GetFolderRequest xmlns=\"urn:zimbraMail\">
    <folder>
       <path>Folder Name</path>
    </folder>
   </GetFolderRequest>
  </soapenv:Body>
</soapenv:Envelope>
"@

${my_curl} = "c:\curl.exe"
${cookie} = "c:\cookie.txt"

${zimbra_soap_url} = "https://zimbra:7071/service/admin/soap"
${curl_getfolder_args} = "-b", "${cookie}",
            "--header", "Content-Type: text/xml;charset=UTF-8",
            "--silent",
            "--data-raw", "${my_xml}",
            "--url", "${zimbra_soap_url}"

[xml]${my_response} = & ${my_curl} ${curl_getfolder_args}
${my_response}.Envelope.Body.GetFolderResponse.folder.id

Why do I get a warning icon when I add a reference to an MEF plugin project?

One of the reasons to get this annoying yellow triangle is that you are adding a reference to a project twice, meaning:

  • Reference one: MyProjectOne (which contains already a reference to MyProjectTwo)
  • Reference two: MyProjectTwo

By deleting the Reference two, the yellow triangle will disappear.

Deleting an object in java?

Your C++ is showing.

There is no delete in java, and all objects are created on the heap. The JVM has a garbage collector that relies on reference counts.

Once there are no more references to an object, it becomes available for collection by the garbage collector.

myObject = null may not do it; for example:

Foo myObject = new Foo(); // 1 reference
Foo myOtherObject = myObject; // 2 references
myObject = null; // 1 reference

All this does is set the reference myObject to null, it does not affect the object myObject once pointed to except to simply decrement the reference count by 1. Since myOtherObject still refers to that object, it is not yet available to be collected.

C# Create New T()

Just for completion, the best solution here is often to require a factory function argument:

T GetObject<T>(Func<T> factory)
{  return factory(); }

and call it something like this:

string s = GetObject(() => "result");

You can use that to require or make use of available parameters, if needed.

Redraw datatables after using ajax to refresh the table content?

Use this:

var table = $(selector).dataTables();
table.api().draw(false);

or

var table = $(selector).DataTables();
table.draw(false);

OR is not supported with CASE Statement in SQL Server

CASE
  WHEN ebv.db_no = 22978 OR 
       ebv.db_no = 23218 OR
       ebv.db_no = 23219
  THEN 'WECS 9500' 
  ELSE 'WECS 9520' 
END as wecs_system 

How do I run a docker instance from a DockerFile?

While other answers were usable, this really helped me, so I am putting it also here.

From the documentation:

Instead of specifying a context, you can pass a single Dockerfile in the URL or pipe the file in via STDIN. To pipe a Dockerfile from STDIN:

$ docker build - < Dockerfile

With Powershell on Windows, you can run:

Get-Content Dockerfile | docker build -

When the build is done, run command:

docker image ls

You will see something like this:

REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
<none>                     <none>              123456789        39 seconds ago      422MB

Copy your actual IMAGE ID and then run

docker run 123456789

Where the number at the end is the actual Image ID from previous step

If you do not want to remember the image id, you can tag your image by

docker tag 123456789 pavel/pavel-build

Which will tag your image as pavel/pavel-build

Move branch pointer to different commit without checkout

Just to enrich the discussion, if you want to move myBranch branch to your current commit, just omit the second argument after -f

Example:

git branch -f myBranch


I generally do this when I rebase while in a Detached HEAD state :)

Whats the CSS to make something go to the next line in the page?

There are two options that I can think of, but without more details, I can't be sure which is the better:

#elementId {
    display: block;
}

This will force the element to a 'new line' if it's not on the same line as a floated element.

#elementId {
     clear: both;
}

This will force the element to clear the floats, and move to a 'new line.'

In the case of the element being on the same line as another that has position of fixed or absolute nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.

Formatting a Date String in React Native

function getParsedDate(date){
  date = String(date).split(' ');
  var days = String(date[0]).split('-');
  var hours = String(date[1]).split(':');
  return [parseInt(days[0]), parseInt(days[1])-1, parseInt(days[2]), parseInt(hours[0]), parseInt(hours[1]), parseInt(hours[2])];
}
var date = new Date(...getParsedDate('2016-01-04 10:34:23'));
console.log(date);

Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

... as described in the resource:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

AngularJS: How to clear query parameters in the URL?

I can replace all query parameters with this single line: $location.search({});
Easy to understand and easy way to clear them out.

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

I've managed to find a CSS workaround to preventing bouncing of the viewport. The key was to wrap the content in 3 divs with -webkit-touch-overflow:scroll applied to them. The final div should have a min-height of 101%. In addition, you should explicitly set fixed widths/heights on the body tag representing the size of your device. I've added a red background on the body to demonstrate that it is the content that is now bouncing and not the mobile safari viewport.

Source code below and here is a plunker (this has been tested on iOS7 GM too). http://embed.plnkr.co/NCOFoY/preview

If you intend to run this as a full-screen app on iPhone 5, modify the height to 1136px (when apple-mobile-web-app-status-bar-style is set to 'black-translucent' or 1096px when set to 'black'). 920x is the height of the viewport once the chrome of mobile safari has been taken into account).

<!doctype html>
<html>

<head>
    <meta name="viewport" content="initial-scale=0.5,maximum-scale=0.5,minimum-scale=0.5,user-scalable=no" />
    <style>
        body { width: 640px; height: 920px; overflow: hidden; margin: 0; padding: 0; background: red; }
        .no-bounce { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
        .no-bounce > div { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
        .no-bounce > div > div { width: 100%; min-height: 101%; font-size: 30px; }
        p { display: block; height: 50px; }
    </style>
</head>

<body>

    <div class="no-bounce">
        <div>
            <div>
                <h1>Some title</h1>
                <p>item 1</p>
                <p>item 2</p>
                <p>item 3</p>
                <p>item 4</p>
                <p>item 5</p>
                <p>item 6</p>
                <p>item 7</p>
                <p>item 8</p>
                <p>item 9</p>
                <p>item 10</p>
                <p>item 11</p>
                <p>item 12</p>
                <p>item 13</p>
                <p>item 14</p>
                <p>item 15</p>
                <p>item 16</p>
                <p>item 17</p>
                <p>item 18</p>
                <p>item 19</p>
                <p>item 20</p>
            </div>
        </div>
    </div>

</body>

</html>

python: sys is not defined

You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:

try:
    import datetime
    import foo
    import sys
except ImportError:
    pass

Let's say foo doesn't exist. Then only datetime will be imported.

What you can do is import the sys module at the beginning of the file, before the try/except statement:

import sys
try:
    import numpy as np
    import pyfits as pf
    import scipy.ndimage as nd
    import pylab as pl
    import os
    import heapq
    from scipy.optimize import leastsq

except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

Javascript validation: Block special characters

A few of the options are deprecated as of today. So watch out for those.

If you try <input onkeypress="blockSpecialCharacters(event)" />, an IDE like WebStorm will slash out event and tell you:

Deprecated symbol used, consults docs for better alternative

Then when you get to the JavaScript, console.log(e.keyCode) will also give keyCode and say:

Deprecated symbol used, consults docs for better alternative

Anyways I did it using jQuery.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

<input id="theInput" />

<script>
    function blockSpecialCharacters(e) {
            let key = e.key;
            let keyCharCode = key.charCodeAt(0);

            // 0-9
            if(keyCharCode >= 48 && keyCharCode <= 57) {
                return key;
            }
            // A-Z
            if(keyCharCode >= 65 && keyCharCode <= 90) {
                return key;
            }
            // a-z
            if(keyCharCode >= 97 && keyCharCode <= 122) {
                return key;
            }

            return false;
    }

    $('#theInput').keypress(function(e) {
        blockSpecialCharacters(e);
    });
</script>

input[type='text'] CSS selector does not apply to default-type text inputs?

To be compliant with all browsers you should always declare the input type.

Some browsers will assume default type as 'text', but this isn't a good practice.

Python: find position of element in array

There is a built in method for doing this:

numpy.where()

You can find out more about it in the excellent detailed documentation.

HTML table with fixed headers?

Additional to @Daniel Waltrip answer. Table need to enclose with div position: relative in order to work with position:sticky . So I would like to post my sample code here.

CSS

/* Set table width/height as you want.*/
div.freeze-header {
  position: relative;
  max-height: 150px;
  max-width: 400px;
  overflow:auto;
}

/* Use position:sticky to freeze header on top*/
div.freeze-header > table > thead > tr > th {
  position: sticky;
  top: 0;
  background-color:yellow;
}

/* below is just table style decoration.*/
div.freeze-header > table {
  border-collapse: collapse;
}

div.freeze-header > table td {
  border: 1px solid black;
}

HTML

<html>
<body>
  <div>
   other contents ...
  </div>
  <div>
   other contents ...
  </div>
  <div>
   other contents ...
  </div>

  <div class="freeze-header">
    <table>
       <thead>
         <tr>
           <th> header 1 </th>
           <th> header 2 </th>
           <th> header 3 </th>
           <th> header 4 </th>
           <th> header 5 </th>
           <th> header 6 </th>
           <th> header 7 </th>
           <th> header 8 </th>
           <th> header 9 </th>
           <th> header 10 </th>
           <th> header 11 </th>
           <th> header 12 </th>
           <th> header 13 </th>
           <th> header 14 </th>
           <th> header 15 </th>
          </tr>
       </thead>
       <tbody>
         <tr>
           <td> data 1 </td>
           <td> data 2 </td>
           <td> data 3 </td>
           <td> data 4 </td>
           <td> data 5 </td>
           <td> data 6 </td>
           <td> data 7 </td>
           <td> data 8 </td>
           <td> data 9 </td>
           <td> data 10 </td>
           <td> data 11 </td>
           <td> data 12 </td>
           <td> data 13 </td>
           <td> data 14 </td>
           <td> data 15 </td>
          </tr>         
         <tr>
           <td> data 1 </td>
           <td> data 2 </td>
           <td> data 3 </td>
           <td> data 4 </td>
           <td> data 5 </td>
           <td> data 6 </td>
           <td> data 7 </td>
           <td> data 8 </td>
           <td> data 9 </td>
           <td> data 10 </td>
           <td> data 11 </td>
           <td> data 12 </td>
           <td> data 13 </td>
           <td> data 14 </td>
           <td> data 15 </td>
          </tr>         
         <tr>
           <td> data 1 </td>
           <td> data 2 </td>
           <td> data 3 </td>
           <td> data 4 </td>
           <td> data 5 </td>
           <td> data 6 </td>
           <td> data 7 </td>
           <td> data 8 </td>
           <td> data 9 </td>
           <td> data 10 </td>
           <td> data 11 </td>
           <td> data 12 </td>
           <td> data 13 </td>
           <td> data 14 </td>
           <td> data 15 </td>
          </tr>         
         <tr>
           <td> data 1 </td>
           <td> data 2 </td>
           <td> data 3 </td>
           <td> data 4 </td>
           <td> data 5 </td>
           <td> data 6 </td>
           <td> data 7 </td>
           <td> data 8 </td>
           <td> data 9 </td>
           <td> data 10 </td>
           <td> data 11 </td>
           <td> data 12 </td>
           <td> data 13 </td>
           <td> data 14 </td>
           <td> data 15 </td>
          </tr>         
         <tr>
           <td> data 1 </td>
           <td> data 2 </td>
           <td> data 3 </td>
           <td> data 4 </td>
           <td> data 5 </td>
           <td> data 6 </td>
           <td> data 7 </td>
           <td> data 8 </td>
           <td> data 9 </td>
           <td> data 10 </td>
           <td> data 11 </td>
           <td> data 12 </td>
           <td> data 13 </td>
           <td> data 14 </td>
           <td> data 15 </td>
          </tr>         
         <tr>
           <td> data 1 </td>
           <td> data 2 </td>
           <td> data 3 </td>
           <td> data 4 </td>
           <td> data 5 </td>
           <td> data 6 </td>
           <td> data 7 </td>
           <td> data 8 </td>
           <td> data 9 </td>
           <td> data 10 </td>
           <td> data 11 </td>
           <td> data 12 </td>
           <td> data 13 </td>
           <td> data 14 </td>
           <td> data 15 </td>
          </tr>         
         <tr>
           <td> data 1 </td>
           <td> data 2 </td>
           <td> data 3 </td>
           <td> data 4 </td>
           <td> data 5 </td>
           <td> data 6 </td>
           <td> data 7 </td>
           <td> data 8 </td>
           <td> data 9 </td>
           <td> data 10 </td>
           <td> data 11 </td>
           <td> data 12 </td>
           <td> data 13 </td>
           <td> data 14 </td>
           <td> data 15 </td>
          </tr>         
         <tr>
           <td> data 1 </td>
           <td> data 2 </td>
           <td> data 3 </td>
           <td> data 4 </td>
           <td> data 5 </td>
           <td> data 6 </td>
           <td> data 7 </td>
           <td> data 8 </td>
           <td> data 9 </td>
           <td> data 10 </td>
           <td> data 11 </td>
           <td> data 12 </td>
           <td> data 13 </td>
           <td> data 14 </td>
           <td> data 15 </td>
          </tr>         
       </tbody>
    </table>
  </div>
</body>
</html>

Demo

enter image description here

Java: parse int value from a char

That's probably the best from the performance point of view, but it's rough:

String element = "el5";
String s;
int x = element.charAt(2)-'0';

It works if you assume your character is a digit, and only in languages always using Unicode, like Java...

get the data of uploaded file in javascript

you can use the new HTML 5 file api to read file contents

https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

but this won't work on every browser so you probably need a server side fallback.

Oracle 11g Express Edition for Windows 64bit?

Some of more advanced Oracle database features such as session trace do not work properly in Oracle 11g XE 32-bit if installed on Windows 64-bit system. I needed session trace on Windows 7 64-bit.

Apart from that it works well for me in multiple production MS Windows 64-bit systems: Windows Server 2008 R2 and Windows Server 2003 R2.

How to simulate a button click using code?

you can do it this way

private Button btn;
btn = (Button)findViewById(R.id.button2);
btn.performClick();

What is the difference between the operating system and the kernel?

Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.

If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.

The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.

So the ultimate difference is:

  1. Kernel is responsible for Hardware level interactions at some specific range. But the OS is like hardware level interaction with full scope of computer.
  2. Kernel triggers SystemCalls to tell the OS that this resource is available at this point of time. The OS is responsible to handle those system calls in order to utilize the resource.

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

Reactive forms - disabled attribute

I found that I needed to have a default value, even if it was an empty string for it to work. So this:

this.registerForm('someName', {
  firstName: new FormControl({disabled: true}),
});

...had to become this:

this.registerForm('someName', {
  firstName: new FormControl({value: '', disabled: true}),
});

See my question (which I don't believe is a duplicate): Passing 'disabled' in form state object to FormControl constructor doesn't work

Storing JSON in database vs. having a new column for each key

Basically, the first model you are using is called as document-based storage. You should have a look at popular NoSQL document-based database like MongoDB and CouchDB. Basically, in document based db's, you store data in json files and then you can query on these json files.

The Second model is the popular relational database structure.

If you want to use relational database like MySql then i would suggest you to only use second model. There is no point in using MySql and storing data as in the first model.

To answer your second question, there is no way to query name like 'foo' if you use first model.

Plot correlation matrix using pandas

Try this function, which also displays variable names for the correlation matrix:

def plot_corr(df,size=10):
    '''Function plots a graphical correlation matrix for each pair of columns in the dataframe.

    Input:
        df: pandas DataFrame
        size: vertical and horizontal size of the plot'''

    corr = df.corr()
    fig, ax = plt.subplots(figsize=(size, size))
    ax.matshow(corr)
    plt.xticks(range(len(corr.columns)), corr.columns);
    plt.yticks(range(len(corr.columns)), corr.columns);

Bootstrap 3: Using img-circle, how to get circle from non-square image?

the problem mainly is because the width have to be == to the height, and in the case of bs, the height is set to auto so here is a fix for that in js instead

function img_circle() {
    $('.img-circle').each(function() {
        $w = $(this).width();
        $(this).height($w);
    });
}

$(document).ready(function() {
    img_circle();
});

$(window).resize(function() {
    img_circle();
});

How to animate button in android?

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class HeightAnimation extends Animation {
    protected final int originalHeight;
    protected final View view;
    protected float perValue;

    public HeightAnimation(View view, int fromHeight, int toHeight) {
        this.view = view;
        this.originalHeight = fromHeight;
        this.perValue = (toHeight - fromHeight);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        view.getLayoutParams().height = (int) (originalHeight + perValue * interpolatedTime);
        view.requestLayout();
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

uss to:

HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), viewPager.getHeight() - otherView.getHeight());
heightAnim.setDuration(1000);
view.startAnimation(heightAnim);

AngularJS. How to call controller function from outside of controller component

I use to work with $http, when a want to get some information from a resource I do the following:

angular.module('services.value', [])

.service('Value', function($http, $q) {

var URL = "http://localhost:8080/myWeb/rest/";

var valid = false;

return {
    isValid: valid,
    getIsValid: function(callback){
        return $http.get(URL + email+'/'+password, {cache: false})
                    .success(function(data){
            if(data === 'true'){ valid = true; }
        }).then(callback);
    }}
    });

And the code in the controller:

angular.module('controllers.value', ['services.value'])

.controller('ValueController', function($scope, Value) {
    $scope.obtainValue = function(){
        Value.getIsValid(function(){$scope.printValue();});
    }

    $scope.printValue = function(){
        console.log("Do it, and value is " Value.isValid);
    }
}

I send to the service what function have to call in the controller

Read a variable in bash with a default value

You can use parameter expansion, e.g.

read -p "Enter your name [Richard]: " name
name=${name:-Richard}
echo $name

Including the default value in the prompt between brackets is a fairly common convention

What does the :-Richard part do? From the bash manual:

${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

Also worth noting that...

In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

So if you use webpath=${webpath:-~/httpdocs} you will get a result of /home/user/expanded/path/httpdocs not ~/httpdocs, etc.

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

Download a div in a HTML page as pdf using javascript

AFAIK there is no native jquery function that does this. Best option would be to process the conversion on the server. How you do this depends on what language you are using (.net, php etc.). You can pass the content of the div to the function that handles the conversion, which would return a pdf to the user.

Bypass invalid SSL certificate errors when calling web services in .Net

Like Jason S's answer:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

I put this in my Main and look to my app.config and test if (ConfigurationManager.AppSettings["IgnoreSSLCertificates"] == "True") before calling that line of code.

PHP Array to JSON Array using json_encode();

I want to add to Michael Berkowski's answer that this can also happen if the array's order is reversed, in which case it's a bit trickier to observe the issue, because in the json object, the order will be ordered ascending.

For example:

[
    3 => 'a',
    2 => 'b',
    1 => 'c',
    0 => 'd'
]

Will return:

{
    0: 'd',
    1: 'c',
    2: 'b',
    3: 'a'
}

So the solution in this case, is to use array_reverse before encoding it to json

Jquery href click - how can I fire up an event?

It doesn't because the href value is not sign_up.It is #sign_up. Try like below, You need to add "#" to indicate the id of the href value.

$('a[href="#sign_up"]').click(function(){
  alert('Sign new href executed.'); 
}); 

DEMO: http://jsfiddle.net/pnGbP/

How to get the url parameters using AngularJS

I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.

Check out the Angular seed project. Within the app.js you'll find an example for the route provider. To use params simply append them like this:

$routeProvider.when('/view1/:param1/:param2', {
    templateUrl: 'partials/partial1.html',    
    controller: 'MyCtrl1'
});

Then in your controller inject $routeParams:

.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
  var param1 = $routeParams.param1;
  var param2 = $routeParams.param2;
  ...
}]);

With this approach you can use params with a url such as: "http://www.example.com/view1/param1/param2"

How can I link to a specific glibc version?

Setup 1: compile your own glibc without dedicated GCC and use it

Since it seems impossible to do just with symbol versioning hacks, let's go one step further and compile glibc ourselves.

This setup might work and is quick as it does not recompile the whole GCC toolchain, just glibc.

But it is not reliable as it uses host C runtime objects such as crt1.o, crti.o, and crtn.o provided by glibc. This is mentioned at: https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location Those objects do early setup that glibc relies on, so I wouldn't be surprised if things crashed in wonderful and awesomely subtle ways.

For a more reliable setup, see Setup 2 below.

Build glibc and install locally:

export glibc_install="$(pwd)/glibc/build/install"

git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
mkdir build
cd build
../configure --prefix "$glibc_install"
make -j `nproc`
make install -j `nproc`

Setup 1: verify the build

test_glibc.c

#define _GNU_SOURCE
#include <assert.h>
#include <gnu/libc-version.h>
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>

atomic_int acnt;
int cnt;

int f(void* thr_data) {
    for(int n = 0; n < 1000; ++n) {
        ++cnt;
        ++acnt;
    }
    return 0;
}

int main(int argc, char **argv) {
    /* Basic library version check. */
    printf("gnu_get_libc_version() = %s\n", gnu_get_libc_version());

    /* Exercise thrd_create from -pthread,
     * which is not present in glibc 2.27 in Ubuntu 18.04.
     * https://stackoverflow.com/questions/56810/how-do-i-start-threads-in-plain-c/52453291#52453291 */
    thrd_t thr[10];
    for(int n = 0; n < 10; ++n)
        thrd_create(&thr[n], f, NULL);
    for(int n = 0; n < 10; ++n)
        thrd_join(thr[n], NULL);
    printf("The atomic counter is %u\n", acnt);
    printf("The non-atomic counter is %u\n", cnt);
}

Compile and run with test_glibc.sh:

#!/usr/bin/env bash
set -eux
gcc \
  -L "${glibc_install}/lib" \
  -I "${glibc_install}/include" \
  -Wl,--rpath="${glibc_install}/lib" \
  -Wl,--dynamic-linker="${glibc_install}/lib/ld-linux-x86-64.so.2" \
  -std=c11 \
  -o test_glibc.out \
  -v \
  test_glibc.c \
  -pthread \
;
ldd ./test_glibc.out
./test_glibc.out

The program outputs the expected:

gnu_get_libc_version() = 2.28
The atomic counter is 10000
The non-atomic counter is 8674

Command adapted from https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location but --sysroot made it fail with:

cannot find /home/ciro/glibc/build/install/lib/libc.so.6 inside /home/ciro/glibc/build/install

so I removed it.

ldd output confirms that the ldd and libraries that we've just built are actually being used as expected:

+ ldd test_glibc.out
        linux-vdso.so.1 (0x00007ffe4bfd3000)
        libpthread.so.0 => /home/ciro/glibc/build/install/lib/libpthread.so.0 (0x00007fc12ed92000)
        libc.so.6 => /home/ciro/glibc/build/install/lib/libc.so.6 (0x00007fc12e9dc000)
        /home/ciro/glibc/build/install/lib/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007fc12f1b3000)

The gcc compilation debug output shows that my host runtime objects were used, which is bad as mentioned previously, but I don't know how to work around it, e.g. it contains:

COLLECT_GCC_OPTIONS=/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crt1.o

Setup 1: modify glibc

Now let's modify glibc with:

diff --git a/nptl/thrd_create.c b/nptl/thrd_create.c
index 113ba0d93e..b00f088abb 100644
--- a/nptl/thrd_create.c
+++ b/nptl/thrd_create.c
@@ -16,11 +16,14 @@
    License along with the GNU C Library; if not, see
    <http://www.gnu.org/licenses/>.  */

+#include <stdio.h>
+
 #include "thrd_priv.h"

 int
 thrd_create (thrd_t *thr, thrd_start_t func, void *arg)
 {
+  puts("hacked");
   _Static_assert (sizeof (thr) == sizeof (pthread_t),
                   "sizeof (thr) != sizeof (pthread_t)");

Then recompile and re-install glibc, and recompile and re-run our program:

cd glibc/build
make -j `nproc`
make -j `nproc` install
./test_glibc.sh

and we see hacked printed a few times as expected.

This further confirms that we actually used the glibc that we compiled and not the host one.

Tested on Ubuntu 18.04.

Setup 2: crosstool-NG pristine setup

This is an alternative to setup 1, and it is the most correct setup I've achieved far: everything is correct as far as I can observe, including the C runtime objects such as crt1.o, crti.o, and crtn.o.

In this setup, we will compile a full dedicated GCC toolchain that uses the glibc that we want.

The only downside to this method is that the build will take longer. But I wouldn't risk a production setup with anything less.

crosstool-NG is a set of scripts that downloads and compiles everything from source for us, including GCC, glibc and binutils.

Yes the GCC build system is so bad that we need a separate project for that.

This setup is only not perfect because crosstool-NG does not support building the executables without extra -Wl flags, which feels weird since we've built GCC itself. But everything seems to work, so this is only an inconvenience.

Get crosstool-NG and configure it:

git clone https://github.com/crosstool-ng/crosstool-ng
cd crosstool-ng
git checkout a6580b8e8b55345a5a342b5bd96e42c83e640ac5
export CT_PREFIX="$(pwd)/.build/install"
export PATH="/usr/lib/ccache:${PATH}"
./bootstrap
./configure --enable-local
make -j `nproc`
./ct-ng x86_64-unknown-linux-gnu
./ct-ng menuconfig

The only mandatory option that I can see, is making it match your host kernel version to use the correct kernel headers. Find your host kernel version with:

uname -a

which shows me:

4.15.0-34-generic

so in menuconfig I do:

  • Operating System
    • Version of linux

so I select:

4.14.71

which is the first equal or older version. It has to be older since the kernel is backwards compatible.

Now you can build with:

env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`

and now wait for about thirty minutes to two hours for compilation.

Setup 2: optional configurations

The .config that we generated with ./ct-ng x86_64-unknown-linux-gnu has:

CT_GLIBC_V_2_27=y

To change that, in menuconfig do:

  • C-library
  • Version of glibc

save the .config, and continue with the build.

Or, if you want to use your own glibc source, e.g. to use glibc from the latest git, proceed like this:

  • Paths and misc options
    • Try features marked as EXPERIMENTAL: set to true
  • C-library
    • Source of glibc
      • Custom location: say yes
      • Custom location
        • Custom source location: point to a directory containing your glibc source

where glibc was cloned as:

git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28

Setup 2: test it out

Once you have built he toolchain that you want, test it out with:

#!/usr/bin/env bash
set -eux
install_dir="${CT_PREFIX}/x86_64-unknown-linux-gnu"
PATH="${PATH}:${install_dir}/bin" \
  x86_64-unknown-linux-gnu-gcc \
  -Wl,--dynamic-linker="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib/ld-linux-x86-64.so.2" \
  -Wl,--rpath="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib" \
  -v \
  -o test_glibc.out \
  test_glibc.c \
  -pthread \
;
ldd test_glibc.out
./test_glibc.out

Everything seems to work as in Setup 1, except that now the correct runtime objects were used:

COLLECT_GCC_OPTIONS=/home/ciro/crosstool-ng/.build/install/x86_64-unknown-linux-gnu/bin/../x86_64-unknown-linux-gnu/sysroot/usr/lib/../lib64/crt1.o

Setup 2: failed efficient glibc recompilation attempt

It does not seem possible with crosstool-NG, as explained below.

If you just re-build;

env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`

then your changes to the custom glibc source location are taken into account, but it builds everything from scratch, making it unusable for iterative development.

If we do:

./ct-ng list-steps

it gives a nice overview of the build steps:

Available build steps, in order:
  - companion_tools_for_build
  - companion_libs_for_build
  - binutils_for_build
  - companion_tools_for_host
  - companion_libs_for_host
  - binutils_for_host
  - cc_core_pass_1
  - kernel_headers
  - libc_start_files
  - cc_core_pass_2
  - libc
  - cc_for_build
  - cc_for_host
  - libc_post_cc
  - companion_libs_for_target
  - binutils_for_target
  - debug
  - test_suite
  - finish
Use "<step>" as action to execute only that step.
Use "+<step>" as action to execute up to that step.
Use "<step>+" as action to execute from that step onward.

therefore, we see that there are glibc steps intertwined with several GCC steps, most notably libc_start_files comes before cc_core_pass_2, which is likely the most expensive step together with cc_core_pass_1.

In order to build just one step, you must first set the "Save intermediate steps" in .config option for the intial build:

  • Paths and misc options
    • Debug crosstool-NG
      • Save intermediate steps

and then you can try:

env -u LD_LIBRARY_PATH time ./ct-ng libc+ -j`nproc`

but unfortunately, the + required as mentioned at: https://github.com/crosstool-ng/crosstool-ng/issues/1033#issuecomment-424877536

Note however that restarting at an intermediate step resets the installation directory to the state it had during that step. I.e., you will have a rebuilt libc - but no final compiler built with this libc (and hence, no compiler libraries like libstdc++ either).

and basically still makes the rebuild too slow to be feasible for development, and I don't see how to overcome this without patching crosstool-NG.

Furthermore, starting from the libc step didn't seem to copy over the source again from Custom source location, further making this method unusable.

Bonus: stdlibc++

A bonus if you're also interested in the C++ standard library: How to edit and re-build the GCC libstdc++ C++ standard library source?

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

in my case, this error is raised due to sequence was not created..

CREATE SEQUENCE  J.SOME_SEQ  MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE ;

python: [Errno 10054] An existing connection was forcibly closed by the remote host

I know this is a very old question but it may be that you need to set the request headers. This solved it for me.

For example 'user-agent', 'accept' etc. here is an example with user-agent:

url = 'your-url-here'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}
r = requests.get(url, headers=headers)

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

Format number to always show 2 decimal places

RegExp - alternative approach

On input you have string (because you use parse) so we can get result by using only string manipulations and integer number calculations

_x000D_
_x000D_
let toFix2 = (n) => n.replace(/(-?)(\d+)\.(\d\d)(\d+)/, (_,s,i,d,r)=> {
  let k= (+r[0]>=5)+ +d - (r==5 && s=='-');
  return s + (+i+(k>99)) + "." + ((k>99)?"00":(k>9?k:"0"+k));
})


// TESTs

console.log(toFix2("1"));
console.log(toFix2("1.341"));
console.log(toFix2("1.345"));
console.log(toFix2("1.005"));
_x000D_
_x000D_
_x000D_

Explanation

  • s is sign, i is integer part, d are first two digits after dot, r are other digits (we use r[0] value to calc rounding)
  • k contains information about last two digits (represented as integer number)
  • if r[0] is >=5 then we add 1 to d - but in case when we have minus number (s=='-') and r is exact equal to 5 then in this case we substract 1 (for compatibility reasons - in same way Math.round works for minus numbers e.g Math.round(-1.5)==-1)
  • after that if last two digits k are greater than 99 then we add one to integer part i

tsc is not recognized as internal or external command

The problem is that tsc is not in your PATH if installed locally.

You should modify your .vscode/tasks.json to include full path to tsc.

The line to change is probably equal to "command": "tsc".

You should change it to "command": "node" and add the following to your args: "args": ["${workspaceRoot}\\node_modules\\typescript\\bin\\tsc"] (on Windows).

This will instruct VSCode to:

  1. Run NodeJS (it should be installed globally).
  2. Pass your local Typescript installation as the script to run.

(that's pretty much what tsc executable does)

Are you sure you don't want to install Typescript globally? It should make things easier, especially if you're just starting to use it.

how to implement Pagination in reactJs

Please see this code sample in codesandbox

https://codesandbox.io/s/pagino-13pit

enter image description here

import Pagino from "pagino";
import { useState, useMemo } from "react";

export default function App() {
  const [pages, setPages] = useState([]);

  const pagino = useMemo(() => {
    const _ = new Pagino({
      showFirst: false,
      showLast: false,
      onChange: (page, count) => setPages(_.getPages())
    });

    _.setCount(10);

    return _;
  }, []);

  const hanglePaginoNavigation = (type) => {
    if (typeof type === "string") {
      pagino[type]?.();
      return;
    }

    pagino.setPage(type);
  };

  return (
    <div>
      <h1>Page: {pagino.page}</h1>
      <ul>
        {pages.map((page) => (
          <button key={page} onClick={() => hanglePaginoNavigation(page)}>
            {page}
          </button>
        ))}
      </ul>
    </div>
  );
}

Conditional Logic on Pandas DataFrame

Just compare the column with that value:

In [9]: df = pandas.DataFrame([1,2,3,4], columns=["data"])

In [10]: df
Out[10]: 
   data
0     1
1     2
2     3
3     4

In [11]: df["desired"] = df["data"] > 2.5
In [11]: df
Out[12]: 
   data desired
0     1   False
1     2   False
2     3    True
3     4    True

How to list all properties of a PowerShell object

The most succinct way to do this is:

Get-WmiObject -Class win32_computersystem -Property *

case-insensitive matching in xpath?

matches() is an XPATH 2.0 function that allows for case-insensitive regex matching.

One of the flags is i for case-insensitive matching.

The following XPATH using the matches() function with the case-insensitive flag:

//CD[matches(@title,'empire burlesque','i')]

Wget output document and headers to STDOUT

This worked for me for printing response with header:

wget --server-response http://www.example.com/

Remove HTML Tags in Javascript with Regex

This is a solution for HTML tag and &nbsp etc and you can remove and add conditions to get the text without HTML and you can replace it by any.

convertHtmlToText(passHtmlBlock)
{
   str = str.toString();
  return str.replace(/<[^>]*(>|$)|&nbsp;|&zwnj;|&raquo;|&laquo;|&gt;/g, 'ReplaceIfYouWantOtherWiseKeepItEmpty');
}

save a pandas.Series histogram plot to file

Use the Figure.savefig() method, like so:

ax = s.hist()  # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')

It doesn't have to end in pdf, there are many options. Check out the documentation.

Alternatively, you can use the pyplot interface and just call the savefig as a function to save the most recently created figure:

import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf')  # saves the current figure

Setting PHP tmp dir - PHP upload not working

In my case, it was the open_basedir which was defined. I commented it out (default) and my issue was resolved. I can now set the upload directory anywhere.

How to pad a string to a fixed length with spaces in Python?

I know this is a bit of an old question, but I've ended up making my own little class for it.

Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:

class consolePrinter():
'''
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
    if overwriteFlag:
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    return

Which then is called via:

consolePrinter.writeline("text here", True) 

If you want to overwrite the previous line, or

consolePrinter.writeline("text here",False)

if you don't.

Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.

'const int' vs. 'int const' as function parameters in C++ and C

This isn't a direct answer but a related tip. To keep things straight, I always use the convection "put const on the outside", where by "outside" I mean the far left or far right. That way there is no confusion -- the const applies to the closest thing (either the type or the *). E.g.,



int * const foo = ...; // Pointer cannot change, pointed to value can change
const int * bar = ...; // Pointer can change, pointed to value cannot change
int * baz = ...; // Pointer can change, pointed to value can change
const int * const qux = ...; // Pointer cannot change, pointed to value cannot change

What's the difference between "git reset" and "git checkout"?

One simple use case when reverting change:
1. Use reset if you want to undo staging of a modified file.
2. Use checkout if you want to discard changes to unstaged file/s.

Can I multiply strings in Java to repeat sequences?

with Dollar:

String s = "123" + $("0").repeat(3); // 123000

Parsing CSV files in C#, with header

I have written TinyCsvParser for .NET, which is one of the fastest .NET parsers around and highly configurable to parse almost any CSV format.

It is released under MIT License:

You can use NuGet to install it. Run the following command in the Package Manager Console.

PM> Install-Package TinyCsvParser

Usage

Imagine we have list of Persons in a CSV file persons.csv with their first name, last name and birthdate.

FirstName;LastName;BirthDate
Philipp;Wagner;1986/05/12
Max;Musterman;2014/01/02

The corresponding domain model in our system might look like this.

private class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
}

When using TinyCsvParser you have to define the mapping between the columns in the CSV data and the property in you domain model.

private class CsvPersonMapping : CsvMapping<Person>
{

    public CsvPersonMapping()
        : base()
    {
        MapProperty(0, x => x.FirstName);
        MapProperty(1, x => x.LastName);
        MapProperty(2, x => x.BirthDate);
    }
}

And then we can use the mapping to parse the CSV data with a CsvParser.

namespace TinyCsvParser.Test
{
    [TestFixture]
    public class TinyCsvParserTest
    {
        [Test]
        public void TinyCsvTest()
        {
            CsvParserOptions csvParserOptions = new CsvParserOptions(true, new[] { ';' });
            CsvPersonMapping csvMapper = new CsvPersonMapping();
            CsvParser<Person> csvParser = new CsvParser<Person>(csvParserOptions, csvMapper);

            var result = csvParser
                .ReadFromFile(@"persons.csv", Encoding.ASCII)
                .ToList();

            Assert.AreEqual(2, result.Count);

            Assert.IsTrue(result.All(x => x.IsValid));

            Assert.AreEqual("Philipp", result[0].Result.FirstName);
            Assert.AreEqual("Wagner", result[0].Result.LastName);

            Assert.AreEqual(1986, result[0].Result.BirthDate.Year);
            Assert.AreEqual(5, result[0].Result.BirthDate.Month);
            Assert.AreEqual(12, result[0].Result.BirthDate.Day);

            Assert.AreEqual("Max", result[1].Result.FirstName);
            Assert.AreEqual("Mustermann", result[1].Result.LastName);

            Assert.AreEqual(2014, result[1].Result.BirthDate.Year);
            Assert.AreEqual(1, result[1].Result.BirthDate.Month);
            Assert.AreEqual(1, result[1].Result.BirthDate.Day);
        }
    }
}

User Guide

A full User Guide is available at:

PHP date() with timezone?

U can just add, timezone difference to unix timestamp. Example for Moscow (UTC+3)

echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);

Best way to check for null values in Java?

If you control the API being called, consider using Guava's Optional class

More info here. Change your method to return an Optional<Boolean> instead of a Boolean.

This informs the calling code that it must account for the possibility of null, by calling one of the handy methods in Optional

$(form).ajaxSubmit is not a function

Drupal 8

Drupal 8 does not include JS-libraries to pages automaticly. So most probably if you meet this error you need to attach 'core/jquery.form' library to your page (or form). Add something like this to your render array:

$form['#attached']['library'][] = 'core/jquery.form';