Programs & Examples On #Tablecellrenderer

TableCellRenderer is a Java Swing interface that defines the method required by any object that would like to be a renderer for cells in a JTable.

Change the background color of a row in a JTable

This is basically as simple as repainting the table. I haven't found a way to selectively repaint just one row/column/cell however.

In this example, clicking on the button changes the background color for a row and then calls repaint.

public class TableTest {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Color[] rowColors = new Color[] {
                randomColor(), randomColor(), randomColor()
        };
        final JTable table = new JTable(3, 3);
        table.setDefaultRenderer(Object.class, new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus,
                    int row, int column) {
                JPanel pane = new JPanel();
                pane.setBackground(rowColors[row]);
                return pane;
            }
        });
        frame.setLayout(new BorderLayout());

        JButton btn = new JButton("Change row2's color");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                rowColors[1] = randomColor();
                table.repaint();
            }
        });

        frame.add(table, BorderLayout.NORTH);
        frame.add(btn, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    private static Color randomColor() {
        Random rnd = new Random();
        return new Color(rnd.nextInt(256),
                rnd.nextInt(256), rnd.nextInt(256));
    }
}

Returning data from Axios API

The issue is that the original axiosTest() function isn't returning the promise. Here's an extended explanation for clarity:

function axiosTest() {
    // create a promise for the axios request
    const promise = axios.get(url)

    // using .then, create a new promise which extracts the data
    const dataPromise = promise.then((response) => response.data)

    // return it
    return dataPromise
}

// now we can use that data from the outside!
axiosTest()
    .then(data => {
        response.json({ message: 'Request received!', data })
    })
    .catch(err => console.log(err))

The function can be written more succinctly:

function axiosTest() {
    return axios.get(url).then(response => response.data)
}

Or with async/await:

async function axiosTest() {
    const response = await axios.get(url)
    return response.data
}

How to use OR condition in a JavaScript IF statement?

here is my example:

if(userAnswer==="Yes"||"yes"||"YeS"){
 console.log("Too Bad!");   
}

This says that if the answer is Yes yes or YeS than the same thing will happen

Execution failed for task ':app:compileDebugAidl': aidl is missing

I had a similar error with a fresh install of Android Studio 1.2.1.1 attempting to build a new blank app for API 22: Android 5.1 (Lollipop).

I fixed it by simply changing the Build Tools Version from "23.0.0 rc1" to "22.0.1" and then rebuilding.

On Windows, F4 opens the Project Structure and the Build Tools Version can be set in the Modules > app section: enter image description here

I think all this does is change the setting in the build.gradle file in the app but I didn't want to change that manually just in case it does something more.

Representing Directory & File Structure in Markdown Syntax

As already recommended, you can use tree. But for using it together with restructured text some additional parameters were required.

The standard tree output will not be printed if your're using pandoc to produce pdf.

tree --dirsfirst --charset=ascii /path/to/directory will produce a nice ASCII tree that can be integrated into your document like this:

.. code::
.
|-- ContentStore
|   |-- de-DE
|   |   |-- art.mshc
|   |   |-- artnoloc.mshc
|   |   |-- clientserver.mshc
|   |   |-- noarm.mshc
|   |   |-- resources.mshc
|   |   `-- windowsclient.mshc
|   `-- en-US
|       |-- art.mshc
|       |-- artnoloc.mshc
|       |-- clientserver.mshc
|       |-- noarm.mshc
|       |-- resources.mshc
|       `-- windowsclient.mshc
`-- IndexStore
    |-- de-DE
    |   |-- art.mshi
    |   |-- artnoloc.mshi
    |   |-- clientserver.mshi
    |   |-- noarm.mshi
    |   |-- resources.mshi
    |   `-- windowsclient.mshi
    `-- en-US
        |-- art.mshi
        |-- artnoloc.mshi
        |-- clientserver.mshi
        |-- noarm.mshi
        |-- resources.mshi
        `-- windowsclient.mshi

Send multipart/form-data files with angular using $http

In angular 9, Before tried 'Content-Type': undefined, but it is not worked for me then I tried the below code and It works like charms for a file object

const request = this.http.post(url, data, {
      headers: {
        'Content-Type': 'file'
      },
    });

How to submit form on change of dropdown list?

Just ask assistance of JavaScript.

<select onchange="this.form.submit()">
    ...
</select>

See also:

Double border with different color

You can use outline with outline offset

<div class="double-border"></div>
.double-border{
background-color:#ccc;
outline: 1px solid #f00;
outline-offset: 3px;
}

What is the difference between declarative and imperative paradigm in programming?

declarative program is just a data for its some more-or-less "universal" imperative implementation/vm.

pluses: specifying just a data, in some hardcoded (and checked) format, is simpler and less error-prone than specifying variant of some imperative algorithm directly. some complex specifications just cant be written directly, only in some DSL form. best and freq used in DSLs data structures is sets and tables. because you not have dependencies between elements/rows. and when you havent dependencies you have freedom to modify and ease of support. (compare for example modules with classes - with modules you happy and with classes you have fragile base class problem) all goods of declarativeness and DSL follows immediately from benefits of that data structures (tables and sets). another plus - you can change implementation of declarative language vm, if DSL is more-or-less abstract (well designed). make parallel implementation, for example. or port it to other os etc. all good specifed modular isolating interfaces or protocols gives you such freedom and easyness of support.

minuses: you guess right. generic (and parameterized by DSL) imperative algorithm/vm implementation may be slower and/or memory hungry than specific one. in some cases. if that cases is rare - just forget about it, let it be slow. if it's frequient - you always can extend your DSL/vm for that case. somewhere slowing down all other cases, sure...

P.S. Frameworks is half-way between DSL and imperative. and as all halfway solutions ... they combines deficiences, not benefits. they not so safe AND not so fast :) look at jack-of-all-trades haskell - it's halfway between strong simple ML and flexible metaprog Prolog and... what a monster it is. you can look at Prolog as a Haskell with boolean-only functions/predicates. and how simple its flexibility is against Haskell...

Get epoch for a specific date using Javascript

Some answers does not explain the side effects of variations in the timezone for JavaScript Date object. So you should consider this answer if this is a concern for you.

Method 1: Machine's timezone dependent

By default, JavaScript returns a Date considering the machine's timezone, so getTime() result varies from computer to computer. You can check this behavior running:

new Date(1970, 0, 1, 0, 0, 0, 0).getTime()
    // Since 1970-01-01 is Epoch, you may expect ZERO
    // but in fact the result varies based on computer's timezone

This is not a problem if you really want the time since Epoch considering your timezone. So if you want to get time since Epoch for the current Date or even a specified Date based on the computer's timezone, you're free to continue using this method.

// Seconds since Epoch (Unix timestamp format)

new Date().getTime() / 1000             // local Date/Time since Epoch in seconds
new Date(2020, 11, 1).getTime() / 1000  // time since Epoch to 2020-12-01 00:00 (local timezone) in seconds

// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)

new Date().getTime()                    // local Date/Time since Epoch in milliseconds
new Date(2020,  0, 2).getTime()         // time since Epoch to 2020-01-02 00:00 (local timezone) in milliseconds

// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)

Method 2: Machine's timezone independent

However, if you want to get ride of variations in timezone and get time since Epoch for a specified Date in UTC (that is, timezone independent), you need to use Date.UTC method or shift the date from your timezone to UTC:

Date.UTC(1970,  0, 1)
    // should be ZERO in any computer, since it is ZERO the difference from Epoch

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()  // difference in milliseconds between your timezone and UTC
    (new Date(1970,  0, 1).getTime() - timezone_diff)
    // should be ZERO in any computer, since it is ZERO the difference from Epoch

So, using this method (or, alternatively, subtracting the difference), the result should be:

// Seconds since Epoch (Unix timestamp format)

Date.UTC(2020,  0, 1) / 1000  // time since Epoch to 2020-01-01 00:00 UTC in seconds

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()
    (new Date(2020,  0, 1).getTime() - timezone_diff) / 1000  // time since Epoch to 2020-01-01 00:00 UTC in seconds
    (new Date(2020, 11, 1).getTime() - timezone_diff) / 1000  // time since Epoch to 2020-12-01 00:00 UTC in seconds

// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)

Date.UTC(2020,  0, 2)   // time since Epoch to 2020-01-02 00:00 UTC in milliseconds

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()
    (new Date(2020,  0, 2).getTime() - timezone_diff)         // time since Epoch to 2020-01-02 00:00 UTC in milliseconds

// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)

IMO, unless you know what you're doing (see note above), you should prefer Method 2, since it is machine independent.


End note

Although the recomendations in this answer, and since Date.UTC does not work without a specified date/time, you may be inclined in using the alternative approach and doing something like this:

const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date().getTime() - timezone_diff)  // <-- !!! new Date() without arguments
    // means "local Date/Time subtracted by timezone since Epoch" (?)

This does not make any sense and it is probably WRONG (you are modifying the date). Be aware of not doing this. If you want to get time since Epoch from the current date AND TIME, you are most probably OK using Method 1.

Configure hibernate to connect to database via JNDI Datasource

Apparently, you did it right. But here is a list of things you'll need with examples from a working application:

1) A context.xml file in META-INF, specifying your data source:

<Context>
    <Resource 
        name="jdbc/DsWebAppDB" 
        auth="Container" 
        type="javax.sql.DataSource" 
        username="sa" 
        password="" 
        driverClassName="org.h2.Driver" 
        url="jdbc:h2:mem:target/test/db/h2/hibernate" 
        maxActive="8" 
        maxIdle="4"/>
</Context>

2) web.xml which tells the container that you are using this resource:

<resource-env-ref>
    <resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

3) Hibernate configuration which consumes the data source. In this case, it's a persistence.xml, but it's similar in hibernate.cfg.xml

<persistence-unit name="dswebapp">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
        <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
    </properties>
</persistence-unit>

Sorted array list in Java

It might be a bit too heavyweight for you, but GlazedLists has a SortedList that is perfect to use as the model of a table or JList

Switching a DIV background image with jQuery

Mine is animated:

$(this).animate({
    opacity: 0
}, 100, function() {
    // Callback
    $(this).css("background-image", "url(" + new_img + ")").promise().done(function(){
        // Callback of the callback :)
        $(this).animate({
            opacity: 1
        }, 600)
    });    
});

PHP isset() with multiple parameters

Use the php's OR (||) logical operator for php isset() with multiple operator e.g

if (isset($_POST['room']) || ($_POST['cottage']) || ($_POST['villa'])) {

}

PHP, display image with Header()

The best solution would be to read in the file, then decide which kind of image it is and send out the appropriate header

$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));

switch( $file_extension ) {
    case "gif": $ctype="image/gif"; break;
    case "png": $ctype="image/png"; break;
    case "jpeg":
    case "jpg": $ctype="image/jpeg"; break;
    case "svg": $ctype="image/svg+xml"; break;
    default:
}

header('Content-type: ' . $ctype);

(Note: the correct content-type for JPG files is image/jpeg)

Setting TIME_WAIT TCP

TIME_WAIT might not be the culprit.

int listen(int sockfd, int backlog);

According to Unix Network Programming Volume1, backlog is defined to be the sum of completed connection queue and incomplete connection queue.

Let's say the backlog is 5. If you have 3 completed connections (ESTABLISHED state), and 2 incomplete connections (SYN_RCVD state), and there is another connect request with SYN. The TCP stack just ignores the SYN packet, knowing it'll be retransmitted some other time. This might be causing the degradation.

At least that's what I've been reading. ;)

In SQL Server, what does "SET ANSI_NULLS ON" mean?

https://docs.microsoft.com/en-us/sql/t-sql/statements/set-ansi-nulls-transact-sql

When SET ANSI_NULLS is ON, a SELECT statement that uses WHERE column_name = NULL returns zero rows even if there are null values in column_name. A SELECT statement that uses WHERE column_name <> NULL returns zero rows even if there are nonnull values in column_name.

For e.g

DECLARE @TempVariable VARCHAR(10)
SET @TempVariable = NULL

SET ANSI_NULLS ON
SELECT 'NO ROWS IF SET ANSI_NULLS ON' where    @TempVariable = NULL
-- IF ANSI_NULLS ON , RETURNS ZERO ROWS


SET ANSI_NULLS OFF
SELECT 'THERE WILL BE A ROW IF ANSI_NULLS OFF' where    @TempVariable =NULL
-- IF ANSI_NULLS OFF , THERE WILL BE ROW !

Resolve Javascript Promise outside function scope

I liked @JonJaques answer but I wanted to take it a step further.

If you bind then and catch then the Deferred object, then it fully implements the Promise API and you can treat it as promise and await it and such.

_x000D_
_x000D_
class DeferredPromise {_x000D_
  constructor() {_x000D_
    this._promise = new Promise((resolve, reject) => {_x000D_
      // assign the resolve and reject functions to `this`_x000D_
      // making them usable on the class instance_x000D_
      this.resolve = resolve;_x000D_
      this.reject = reject;_x000D_
    });_x000D_
    // bind `then` and `catch` to implement the same interface as Promise_x000D_
    this.then = this._promise.then.bind(this._promise);_x000D_
    this.catch = this._promise.catch.bind(this._promise);_x000D_
    this[Symbol.toStringTag] = 'Promise';_x000D_
  }_x000D_
}_x000D_
_x000D_
const deferred = new DeferredPromise();_x000D_
console.log('waiting 2 seconds...');_x000D_
setTimeout(() => {_x000D_
  deferred.resolve('whoa!');_x000D_
}, 2000);_x000D_
_x000D_
async function someAsyncFunction() {_x000D_
  const value = await deferred;_x000D_
  console.log(value);_x000D_
}_x000D_
_x000D_
someAsyncFunction();
_x000D_
_x000D_
_x000D_

Base table or view not found: 1146 Table Laravel 5

I also had this problem when doing migration => after performing php artisan migrate:refresh --seed command

"Base table or view not found: 1146 Table posts do not exist" and I solved it, I was using "soft deletes" in a separate migration file, and my original migration for "posts" table which was responsible for creating the "posts" table was performing after the "soft deletes" migration in the database\migration folder, I simply needed to rename the "posts" migration file name and put it before "softdeletes" migration to perform sooner. the do the migration again => php artisan migrate:refresh --seed it's done.

Delete files older than 15 days using PowerShell

Another way is to subtract 15 days from the current date and compare CreationTime against that value:

$root  = 'C:\root\folder'
$limit = (Get-Date).AddDays(-15)

Get-ChildItem $root -Recurse | ? {
  -not $_.PSIsContainer -and $_.CreationTime -lt $limit
} | Remove-Item

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

Embedding JavaScript engine into .NET

V8.NET is a new kid on the block (as of April 2013) that more closely wraps the native V8 engine functionality. It allows for more control over the implementation.

How can I customize the tab-to-space conversion factor?

That is lonefy.vscode-js-css-html-formatter to blame. Disable it, and install HookyQR.beautify.

Now on save your tabs wouldn't be converted.

get current page from url

Try this:

path.Substring(path.LastIndexOf("/");

Using Position Relative/Absolute within a TD?

This trick also suitable, but in this case align properties (middle, bottom etc.) won't be working.

<td style="display: block; position: relative;">
</td>

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

It seems that you've omitted the value attribute in HTML markup.

Add it there as <input value="" ... >.

What are the differences between .gitignore and .gitkeep?

.gitkeep isn’t documented, because it’s not a feature of Git.

Git cannot add a completely empty directory. People who want to track empty directories in Git have created the convention of putting files called .gitkeep in these directories. The file could be called anything; Git assigns no special significance to this name.

There is a competing convention of adding a .gitignore file to the empty directories to get them tracked, but some people see this as confusing since the goal is to keep the empty directories, not ignore them; .gitignore is also used to list files that should be ignored by Git when looking for untracked files.

How to pass model attributes from one Spring MVC controller to another controller?

I had same problem.

With RedirectAttributes after refreshing page, my model attributes from first controller have been lost. I was thinking that is a bug, but then i found solution. In first controller I add attributes in ModelMap and do this instead of "redirect":

return "forward:/nameOfView";

This will redirect to your another controller and also keep model attributes from first one.

I hope this is what are you looking for. Sorry for my English

How to import local packages in go?

If you are using Go 1.5 above, you can try to use vendoring feature. It allows you to put your local package under vendor folder and import it with shorter path. In your case, you can put your common and routers folder inside vendor folder so it would be like

myapp/
--vendor/
----common/
----routers/
------middleware/
--main.go

and import it like this

import (
    "common"
    "routers"
    "routers/middleware"
)

This will work because Go will try to lookup your package starting at your project’s vendor directory (if it has at least one .go file) instead of $GOPATH/src.

FYI: You can do more with vendor, because this feature allows you to put "all your dependency’s code" for a package inside your own project's directory so it will be able to always get the same dependencies versions for all builds. It's like npm or pip in python, but you need to manually copy your dependencies to you project, or if you want to make it easy, try to look govendor by Daniel Theophanes

For more learning about this feature, try to look up here

Understanding and Using Vendor Folder by Daniel Theophanes

Understanding Go Dependency Management by Lucas Fernandes da Costa

I hope you or someone else find it helpfully

Given a DateTime object, how do I get an ISO 8601 date in string format?

DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.

EDIT: To get the additional Z at the end as the OP requires, use "o" instead of "s".

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

In addition to others' proposals, there is another option to handle that issue.

If your application should behave the same in case of lack of "href" attribute, as in case of it being empty, just replace this:

var theHref = $(obj.mainImg_select).attr('href');

with this:

var theHref = $(obj.mainImg_select).attr('href') || '';

which will treat empty string ('') as the default, if the attribute has not been found.

But it really depends, on how you want to handle undefined "href" attribute. This answer assumes you will want to handle it as if it was empty string.

Centering controls within a form in .NET (Winforms)?

It involves eyeballing it (well I suppose you could get out a calculator and calculate) but just insert said control on the form and then remove any anchoring (anchor = None).

When should I use File.separator and when File.pathSeparator?

java.io.File class contains four static separator variables. For better understanding, Let's understand with the help of some code

  1. separator: Platform dependent default name-separator character as String. For windows, it’s ‘\’ and for unix it’s ‘/’
  2. separatorChar: Same as separator but it’s char
  3. pathSeparator: Platform dependent variable for path-separator. For example PATH or CLASSPATH variable list of paths separated by ‘:’ in Unix systems and ‘;’ in Windows system
  4. pathSeparatorChar: Same as pathSeparator but it’s char

Note that all of these are final variables and system dependent.

Here is the java program to print these separator variables. FileSeparator.java

import java.io.File;

public class FileSeparator {

    public static void main(String[] args) {
        System.out.println("File.separator = "+File.separator);
        System.out.println("File.separatorChar = "+File.separatorChar);
        System.out.println("File.pathSeparator = "+File.pathSeparator);
        System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
    }

}

Output of above program on Unix system:

File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :

Output of the program on Windows system:

File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;

To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.

Here is the code snippet showing how to use separators correctly.

//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");

How to check if input date is equal to today's date?

There is a simpler solution

if (inputDate.getDate() === todayDate.getDate()) {
   // do stuff
}

like that you don't loose the time attached to inputDate if any

No value accessor for form control

If you get this issue, then either

  • the formControlName is not located on the value accessor element.
  • or you're not importing the module for that element.

Unit tests vs Functional tests

Unit testing is usually done by developers. The objective of doing the same is to make sure their code works properly. General rule of thumb is to cover all the paths in code using unit testing.

Functional Testing: This is a good reference. Functional Testing Explanation

I am not able launch JNLP applications using "Java Web Start"?

In my case, Netbeans automatically creates a .jnlp file that doesn't work and my problem was due to an accidental overwriting of the launch.jnlp file on the server (by the inadequate and incorrect version from Netbeans). This caused a mismatch between the local .jnlp file and the remote .jnlp file, resulting in Java Web Start just quitting after "Verifying application."

So no one else has to waste an hour finding a bug that should be communicated adequately (but isn't) by Java WS.

CSS rotation cross browser with jquery.animate()

Thanks yckart! Great contribution. I fleshed out your plugin a bit more. Added startAngle for full control and cross-browser css.

$.fn.animateRotate = function(startAngle, endAngle, duration, easing, complete){
    return this.each(function(){
        var elem = $(this);

        $({deg: startAngle}).animate({deg: endAngle}, {
            duration: duration,
            easing: easing,
            step: function(now){
                elem.css({
                  '-moz-transform':'rotate('+now+'deg)',
                  '-webkit-transform':'rotate('+now+'deg)',
                  '-o-transform':'rotate('+now+'deg)',
                  '-ms-transform':'rotate('+now+'deg)',
                  'transform':'rotate('+now+'deg)'
                });
            },
            complete: complete || $.noop
        });
    });
};

How to change the button color when it is active using bootstrap?

CSS has different pseudo selector by which you can achieve such effect. In your case you can use

:active : if you want background color only when the button is clicked and don't want to persist.

:focus: if you want background color untill the focus is on the button.

button:active{
    background:olive;
}

and

button:focus{
    background:olive;
}

JsFiddle Example

P.S.: Please don't give the number in Id attribute of html elements.

How to set border on jPanel?

Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:

public GoBoard(){
    this.linien = 9;
    this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
}

public GoBoard(int pLinien){
    this.linien = pLinien;

}

If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:

// default constructor
public GoBoard(){
    this(9);  // calls other constructor
}

public GoBoard(int pLinien){
    this.linien = pLinien;
    this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
}

edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,

class GoTest {
   private static final int JB_WIDTH = 400;
   private static final int JB_HEIGHT = JB_WIDTH;

   private static void initGui() {
      JFrame frame = new JFrame("GoBoard");
      GoBoard jboard = new GoBoard();
      jboard.setLayout(new BorderLayout(10, 10));

      JPanel holdingPanel = new JPanel(new BorderLayout());
      int eb = 20;
      holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
      holdingPanel.add(jboard, BorderLayout.CENTER);
      frame.add(holdingPanel, BorderLayout.CENTER);
      jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      //!! frame.setSize(400, 400);
      frame.pack();
      frame.setVisible(true);
   }

// .... etc....

Disabling buttons on react native

this native-base there is solution:

<Button
    block
    disabled={!learnedWordsByUser.length}
    style={{ marginTop: 10 }}
    onPress={learnedWordsByUser.length && () => {
      onFlipCardsGenerateNewWords(learnedWordsByUser)
      onFlipCardsBtnPress()
    }}
>
    <Text>Let's Review</Text>
</Button>

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Return string Input with parse.string

As you see in an error UseCalls.java:27: error: cannot find symbol return String.parseString(input); there is no method parseString in String class. There is no need to parse it as long as JOptionPane.showInputDialog(prompt); already returns a string.

Problem with converting int to string in Linq to entities

With EF v4 you can use SqlFunctions.StringConvert. There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this:

var items = from c in contacts
            select new ListItem
            {
                Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(),
                Text = c.Name
            };

How to clear the cache in NetBeans

The cache is C:\Users\userName\AppData\Local\NetBeans\Cache\, and then the version name of the folder will specify the correct cache.

You can also do this: Close the IDE. Instead, of deleting files and risking everything, rename this cache folder. Now start the IDE. Once it starts, a new cache folder will be created since the folder is not found. Now you can delete the renamed folder safely.

TypeError: 'list' object is not callable in python

Close the current interpreter using exit() command and reopen typing python to start your work. And do not name a list as list literally. Then you will be fine.

How do I rename a local Git branch?

Here are three steps: A command that you can call inside your terminal and change branch name.

git branch -m old_branch new_branch         # Rename branch locally
git push origin :old_branch                 # Delete the old branch
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote

If you need more: step-by-step, How To Change Git Branch Name is a good article about that.

how to convert a string to date in mysql?

Here's another two examples.

To output the day, month, and year, you can use:

select STR_TO_DATE('14/02/2015', '%d/%m/%Y');

Which produces:

2015-02-14

To also output the time, you can use:

select STR_TO_DATE('14/02/2017 23:38:12', '%d/%m/%Y %T');

Which produces:

2017-02-14 23:38:12

Most recent previous business day in Python

timeboard package does this.

Suppose your date is 04 Sep 2017. In spite of being a Monday, it was a holiday in the US (the Labor Day). So, the most recent business day was Friday, Sep 1.

>>> import timeboard.calendars.US as US
>>> clnd = US.Weekly8x5()
>>> clnd('04 Sep 2017').rollback().to_timestamp().date()
datetime.date(2017, 9, 1)

In UK, 04 Sep 2017 was the regular business day, so the most recent business day was itself.

>>> import timeboard.calendars.UK as UK
>>> clnd = UK.Weekly8x5()
>>> clnd('04 Sep 2017').rollback().to_timestamp().date()
datetime.date(2017, 9, 4)

DISCLAIMER: I am the author of timeboard.

Get specific ArrayList item

Time to familiarize yourself with the ArrayList API and more:

ArrayList at Java 6 API Documentation

For your immediate question:

mainList.get(3);

Get pixel's RGB using PIL

Yes, this way:

im = Image.open('image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))

print(r, g, b)
(65, 100, 137)

The reason you were getting a single value before with pix[1, 1] is because GIF pixels refer to one of the 256 values in the GIF color palette.

See also this SO post: Python and PIL pixel values different for GIF and JPEG and this PIL Reference page contains more information on the convert() function.

By the way, your code would work just fine for .jpg images.

Simple Popup by using Angular JS

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

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

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

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

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

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

    </div>
  </div>

</div>

</body>
</html>

Format telephone and credit card numbers in AngularJS

You also can check input mask formatter.

This is a directive and it's called ui-mask and also it's a part of angular-ui.utils library.

Here is working: Live example

For the time of writing this post there aren't any examples of using this directive, so I've made a very simple example to demonstrate how this thing works in practice.

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)

I had exactly this issue in a recent project which really is a pain in the rear. I finally found it's because the Python we used in Docker has encoding "ansi_x3.4-1968" instead of "utf-8". So if anyone out there using Docker and got this error, following these steps may thoroughly solve your problem.

  1. create a file and name it default_locale in the same directory of your Dockerfile, put this line in it,

    environment=LANG="es_ES.utf8", LC_ALL="es_ES.UTF-8", LC_LANG="es_ES.UTF-8"

  2. add these to your Dockerfile,

    RUN apt-get clean && apt-get update && apt-get install -y locales

    RUN locale-gen en_CA.UTF-8

    COPY ./default_locale /etc/default/locale

    RUN chmod 0755 /etc/default/locale

    ENV LC_ALL=en_CA.UTF-8

    ENV LANG=en_CA.UTF-8

    ENV LANGUAGE=en_CA.UTF-8

This thoroughly solved my issue when I built and run my Docker again, hopefully this solve your issue also.

How to send custom headers with requests in Swagger UI?

Also it's possible to use attribute [FromHeader] for web methods parameters (or properties in a Model class) which should be sent in custom headers. Something like this:

[HttpGet]
public ActionResult Products([FromHeader(Name = "User-Identity")]string userIdentity)

At least it works fine for ASP.NET Core 2.1 and Swashbuckle.AspNetCore 2.5.0.

source command not found in sh shell

$ls -l `which sh`
/bin/sh -> dash

$sudo dpkg-reconfigure dash #Select "no" when you're asked
[...]

$ls -l `which sh`
/bin/sh -> bash

Then it will be OK

Using number_format method in Laravel

This should work :

<td>{{ number_format($Expense->price, 2) }}</td>

Get first letter of a string from column

.str.get

This is the simplest to specify string methods

# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df

        A    B
0     xyz  123
1     abc  456
2  foobar  789

df.dtypes

A    object
B     int64
dtype: object

For string (read:object) type columns, use

df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)

.str handles NaNs by returning NaN as the output.

For non-numeric columns, an .astype conversion is required beforehand, as shown in @Ed Chum's answer.

# Note that this won't work well if the data has NaNs. 
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

List Comprehension and Indexing

There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.

# For string columns
df['C'] = [x[0] for x in df['A']]

# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

If your data has NaNs, then you will need to handle this appropriately with an if/else in the list comprehension,

df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2

        A      B
0     xyz  123.0
1     NaN  456.0
2  foobar    NaN

# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]

# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]

        A      B    C    D
0     xyz  123.0    x    1
1     NaN  456.0  NaN    4
2  foobar    NaN    f  NaN

Let's do some timeit tests on some larger data.

df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True) 

%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])

%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])

12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

List comprehensions are 4x faster.

JavaScript - Use variable in string match

for me anyways, it helps to see it used. just made this using the "re" example:

var analyte_data = 'sample-'+sample_id;
var storage_keys = $.jStorage.index();
var re = new RegExp( analyte_data,'g');  
for(i=0;i<storage_keys.length;i++) { 
    if(storage_keys[i].match(re)) {
        console.log(storage_keys[i]);
        var partnum = storage_keys[i].split('-')[2];
    }
}

How to run bootRun with spring profile via gradle task

I wanted it simple just to be able to call gradle bootRunDev like you without having to do any extra typing..

This worked for me - by first configuring it the bootRun in my task and then right after it running bootRun which worked fine for me :)

task bootRunDev {
    bootRun.configure {
        systemProperty "spring.profiles.active", 'Dev'
    }
}

bootRunDev.finalizedBy bootRun

Return value from exec(@sql)

Was playing with this today... I beleive you can also use @@ROWCOUNT, like this:

DECLARE @SQL VARCHAR(50)
DECLARE @Rowcount INT
SET @SQL = 'SELECT 1 UNION SELECT 2'
EXEC(@SQL)
SET @Rowcount = @@ROWCOUNT
SELECT @Rowcount

Then replace the 'SELECT 1 UNION SELECT 2' with your actual select without the count. I'd suggest just putting 1 in your select, like this:

SELECT 1
FROM dbo.Comm_Services
WHERE....
....

(as opposed to putting SELECT *)

Hope that helps.

Replacing few values in a pandas dataframe column with another value

loc function can be used to replace multiple values, Documentation for it : loc

df.loc[df['BrandName'].isin(['ABC', 'AB'])]='A'

any tool for java object to object mapping?

ModelMapper is another library worth checking out. ModelMapper's design is different from other libraries in that it:

  • Automatically maps object models by intelligently matching source and destination properties
  • Provides a refactoring safe mapping API that uses actual code to map fields and methods rather than using strings
  • Utilizes convention based configuration for simple handling of custom scenarios

Check out the ModelMapper site for more info:

http://modelmapper.org

How to calculate mean, median, mode and range from a set of numbers

As already pointed out by Nico Huysamen, finding multiple mode in Java 1.8 can be done alternatively as below.

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

public static void mode(List<Integer> numArr) {
    Map<Integer, Integer> freq = new HashMap<Integer, Integer>();;
    Map<Integer, List<Integer>> mode = new HashMap<Integer, List<Integer>>();

    int modeFreq = 1; //record the highest frequence
    for(int x=0; x<numArr.size(); x++) { //1st for loop to record mode
        Integer curr = numArr.get(x); //O(1)
        freq.merge(curr, 1, (a, b) -> a + b); //increment the frequency for existing element, O(1)
        int currFreq = freq.get(curr); //get frequency for current element, O(1)

        //lazy instantiate a list if no existing list, then
        //record mapping of frequency to element (frequency, element), overall O(1)
        mode.computeIfAbsent(currFreq, k -> new ArrayList<>()).add(curr);

        if(modeFreq < currFreq) modeFreq = currFreq; //update highest frequency
    }
    mode.get(modeFreq).forEach(x -> System.out.println("Mode = " + x)); //pretty print the result //another for loop to return result
}

Happy coding!

Xcode: Could not locate device support files

I have Xcode 10.1 and I can not run my application on my device with 12.2 iOS version.

The easiest solution for me was:

  1. Go with finder at Xcode location
  2. Right Click -> Show Package Contents
  3. Contents -> Developer -> Platforms -> iPhoneOS.platform -> DeviceSupport
  4. Here you find a list of supported version. Choose the most recent one and copy(In my case was 12.1 (16B91))
  5. Paste in the same folder(DeviceSupport) and call it with the version you need.(In my case was 12.2 (16E227))
  6. Close Xcode if you have it open
  7. Reconnect device if it was connected
  8. Open Xcode and build

If this trick does not working, you have to get the versions from the new Xcode version.

But you can try, saves a lot of time. Good luck!

EDIT: Or you can download your needed device support from here: https://github.com/iGhibli/iOS-DeviceSupport/tree/master/DeviceSupport

PHPmailer sending HTML CODE

just you need to pass true as an argument to IsHTML() function.

How do I validate a date in rails?

If you want Rails 3 or Ruby 1.9 compatibility try the date_validator gem.

ImportError: No module named 'selenium'

If you are using Anaconda or Spyder in windows, install selenium by this code in cmd:

conda install selenium

If you are using Pycharm IDE in windows, install selenium by this code in cmd:

pip install selenium

How to add number of days to today's date?

I found that JavaScript can return a correct date when you use new Date(nYear, nMonth, nDate); with the over days of that month. Try to see the result of a dDate variable when you use this:

var dDate = new Date(2012, 0, 34); // the result is 3 Feb 2012


I have a SkipDate function to share:

    function DaysOfMonth(nYear, nMonth) {
        switch (nMonth) {
            case 0:     // January
                return 31; break;
            case 1:     // February
                if ((nYear % 4) == 0) {
                    return 29;
                }
                else {
                    return 28;
                };
                break;
            case 2:     // March
                return 31; break;
            case 3:     // April
                return 30; break;
            case 4:     // May
                return 31; break;
            case 5:     // June
                return 30; break;
            case 6:     // July
                return 31; break;
            case 7:     // August
                return 31; break;
            case 8:     // September
                return 30; break;
            case 9:     // October
                return 31; break;
            case 10:     // November
                return 30; break;
            case 11:     // December
                return 31; break;
        }
    };

    function SkipDate(dDate, skipDays) {
        var nYear = dDate.getFullYear();
        var nMonth = dDate.getMonth();
        var nDate = dDate.getDate();
        var remainDays = skipDays;
        var dRunDate = dDate;

        while (remainDays > 0) {
            remainDays_month = DaysOfMonth(nYear, nMonth) - nDate;
            if (remainDays > remainDays_month) {
                remainDays = remainDays - remainDays_month - 1;
                nDate = 1;
                if (nMonth < 11) { nMonth = nMonth + 1; }
                else {
                    nMonth = 0;
                    nYear = nYear + 1;
                };
            }
            else {
                nDate = nDate + remainDays;
                remainDays = 0;
            };
            dRunDate = Date(nYear, nMonth, nDate);
        }
        return new Date(nYear, nMonth, nDate);
    };

Permission denied error while writing to a file in Python

I've had the same issue using the cmd (windows command line) like this

C:\Windows\System32> "G:\my folder\myProgram.py"

Where inside the python file something like this

myfile = open('myOutput.txt', 'w')

The error was that when you don't use a full path, python would use your current directory, and because the default directory on cmd is

C:\Windows\System32 

that won't work, as it seems to be write-protected and needs permission & confirmation form an administrator

Instead, you should use full paths, for example:

myfile = open('G:\my folder\myOutput.txt', 'w')

Why does git say "Pull is not possible because you have unmerged files"?

If you want to pull down a remote branch to run locally (say for reviewing or testing purposes), and when you $ git pull you get local merge conflicts:

$ git checkout REMOTE-BRANCH
$ git pull  (you get local merge conflicts)
$ git reset --hard HEAD (discards local conflicts, and resets to remote branch HEAD)
$ git pull (now get remote branch updates without local conflicts)

Self-reference for cell, column and row in worksheet functions

I don't see the need for Indirect, especially for conditional formatting.

The simplest way to self-reference a cell, row or column is to refer to it normally, e.g., "=A1" in cell A1, and make the reference partly or completely relative. For example, in a conditional formatting formula for checking whether there's a value in the first column of various cells' rows, enter the following with A1 highlighted and copy as necessary. The conditional formatting will always refer to column A for the row of each cell:

= $A1 <> ""

Regex Until But Not Including

The explicit way of saying "search until X but not including X" is:

(?:(?!X).)*

where X can be any regular expression.

In your case, though, this might be overkill - here the easiest way would be

[^z]*

This will match anything except z and therefore stop right before the next z.

So .*?quick[^z]* will match The quick fox jumps over the la.

However, as soon as you have more than one simple letter to look out for, (?:(?!X).)* comes into play, for example

(?:(?!lazy).)* - match anything until the start of the word lazy.

This is using a lookahead assertion, more specifically a negative lookahead.

.*?quick(?:(?!lazy).)* will match The quick fox jumps over the.

Explanation:

(?:        # Match the following but do not capture it:
 (?!lazy)  # (first assert that it's not possible to match "lazy" here
 .         # then match any character
)*         # end of group, zero or more repetitions.

Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: \bfox\b will only match the complete word fox but not the fox in foxy.

Note

If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending (?s) to the regex, but that doesn't work in all regex engines (notably JavaScript).

Alternative solution:

In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a ? to the * quantifier, it will try to match as few characters as possible from the current position:

.*?(?=(?:X)|$)

will match any number of characters, stopping right before X (which can be any regex) or the end of the string (if X doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around X in order to reliably isolate it from the alternation)

PSQLException: current transaction is aborted, commands ignored until end of transaction block

Try this COMMIT;

I run that in pgadmin4. It may help. It has to do with the previous command stopping prematurely

How do I download a tarball from GitHub using cURL?

with a specific dir:

cd your_dir && curl -L https://download.calibre-ebook.com/3.19.0/calibre-3.19.0-x86_64.txz | tar zx

How to declare global variables in Android?

If some variables are stored in sqlite and you must use them in most activities in your app. then Application maybe the best way to achieve it. Query the variables from database when application started and store them in a field. Then you can use these variables in your activities.

So find the right way, and there is no best way.

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

It might be old but in my case, it was because of docker. Hope it will help others.

How to change the remote repository for a git submodule?

What worked for me (on Windows, using git version 1.8.3.msysgit.0):

  • Update .gitmodules with the URL to the new repository
  • Remove the corresponding line from the ".git/config" file
  • Delete the corresponding directory in the ".git/modules/external" directory (".git/modules" for recent git versions)
  • Delete the checked out submodule directory itself (unsure if this is necessary)
  • Run git submodule init and git submodule update
  • Make sure the checked out submodule is at the correct commit, and commit that, since it's likely that the hash will be different

After doing all that, everything is in the state I would expect. I imagine other users of the repository will have similar pain when they come to update though - it would be wise to explain these steps in your commit message!

Maven: Failed to retrieve plugin descriptor error

I had the same issue in Windows

and it worked since my proxy configuration in settings.xml file was changed

So locate and edit the file inside the \conf folder, for example : C:\Program Files\apache-maven-3.2.5\conf

<proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>jorgesys</username>
      <password>supercalifragilisticoespialidoso</password>
      <host>proxyjorgesys</host>
      <port>8080</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>
  • In my case i had to chage from port 80 to 8080
  • If you can´t edit this file that is located inside /program files you can make a copy, edit the file and replace the file located into /program files folder.

How do I concatenate two strings in Java?

In Java, the concatenation symbol is "+", not ".".

Mac OS X - EnvironmentError: mysql_config not found

brew install mysql added mysql to /usr/local/Cellar/..., so I needed to add :/usr/local/Cellar/ to my $PATH and then which mysql_config worked!

How can one use multi threading in PHP applications

I know this is an old question but for people searching, there is a PECL extension written in C that gives PHP multi-threading capability now, it's located here https://github.com/krakjoe/pthreads

What's the difference between deadlock and livelock?

I just planned to share some knowledge.

Deadlocks A set of threads/processes is deadlocked, if each thread/process in the set is waiting for an event that only another process in the set can cause.

The important thing here is another process is also in the same set. that means another process also blocked and no one can proceed.

Deadlocks occur when processes are granted exclusive access to resources.

These four conditions should be satisfied to have a deadlock.

  1. Mutual exclusion condition (Each resource is assigned to 1 process)
  2. Hold and wait condition (Process holding resources and at the same time it can ask other resources).
  3. No preemption condition (Previously granted resources can not forcibly be taken away) #This condition depends on the application
  4. Circular wait condition (Must be a circular chain of 2 or more processes and each is waiting for resource held by the next member of the chain) # It will happen dynamically

If we found these conditions then we can say there may be occurred a situation like a deadlock.

LiveLock

Each thread/process is repeating the same state again and again but doesn't progress further. Something similar to a deadlock since the process can not enter the critical section. However in a deadlock, processes are wait without doing anything but in livelock, the processes are trying to proceed but processes are repeated to the same state again and again.

(In a deadlocked computation there is no possible execution sequence which succeeds. but In a livelocked computation, there are successful computations, but there are one or more execution sequences in which no process enters its critical section.)

Difference from deadlock and livelock

When deadlock happens, No execution will happen. but in livelock, some executions will happen but those executions are not enough to enter the critical section.

SQL Server: IF EXISTS ; ELSE

I know its been a while since the original post but I like using CTE's and this worked for me:

WITH cte_table_a
AS
(
    SELECT [id] [id]
    , MAX([value]) [value]
    FROM table_a
    GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN  cte_table_a
ON table_b.id = cte_table_a.id

Using multiple .cpp files in c++ program?

In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h" to your main.cpp file.

In second.h you just declare like this void yourFunction(); In second.cpp you implement it like

void yourFunction() { 
   doSomethng(); 
}

Don't forget to #include "second.h" also in the beginning of second.cpp

Hope this helps:)

Node.js check if path is file or directory

The answers above check if a filesystem contains a path that is a file or directory. But it doesn't identify if a given path alone is a file or directory.

The answer is to identify directory-based paths using "/." like --> "/c/dos/run/." <-- trailing period.

Like a path of a directory or file that has not been written yet. Or a path from a different computer. Or a path where both a file and directory of the same name exists.

// /tmp/
// |- dozen.path
// |- dozen.path/.
//    |- eggs.txt
//
// "/tmp/dozen.path" !== "/tmp/dozen.path/"
//
// Very few fs allow this. But still. Don't trust the filesystem alone!

// Converts the non-standard "path-ends-in-slash" to the standard "path-is-identified-by current "." or previous ".." directory symbol.
function tryGetPath(pathItem) {
    const isPosix = pathItem.includes("/");
    if ((isPosix && pathItem.endsWith("/")) ||
        (!isPosix && pathItem.endsWith("\\"))) {
        pathItem = pathItem + ".";
    }
    return pathItem;
}
// If a path ends with a current directory identifier, it is a path! /c/dos/run/. and c:\dos\run\.
function isDirectory(pathItem) {
    const isPosix = pathItem.includes("/");
    if (pathItem === "." || pathItem ==- "..") {
        pathItem = (isPosix ? "./" : ".\\") + pathItem;
    }
    return (isPosix ? pathItem.endsWith("/.") || pathItem.endsWith("/..") : pathItem.endsWith("\\.") || pathItem.endsWith("\\.."));
} 
// If a path is not a directory, and it isn't empty, it must be a file
function isFile(pathItem) {
    if (pathItem === "") {
        return false;
    }
    return !isDirectory(pathItem);
}

Node version: v11.10.0 - Feb 2019

Last thought: Why even hit the filesystem?

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

How to delete an instantiated object Python?

What do you mean by delete? In Python, removing a reference (or a name) can be done with the del keyword, but if there are other names to the same object that object will not be deleted.

--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

compared to:

--> test = 5
--> other is test  # check that both name refer to the exact same object
True
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)
5

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

Try putting the following in the environment variables for the scheme under run(debug)

OS_ACTIVITY_MODE = disable

Reordering Chart Data Series

Select a series and look in the formula bar. The last argument is the plot order of the series. You can edit this formula just like any other, right in the formula bar.

For example, select series 4, then change the 4 to a 3.

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

Get type of a generic parameter in Java with reflection

Use:

Class<?> typeOfTheList = aListWithTypeSpiderMan.toArray().getClass().getComponentType();

Getting Date or Time only from a DateTime Object

You can also use DateTime.Now.ToString("yyyy-MM-dd") for the date, and DateTime.Now.ToString("hh:mm:ss") for the time.

Already defined in .obj - no double inclusions

You probably don't want to do this:

#include "client.cpp"

A *.cpp file will have been compiled by the compiler as part of your build. By including it in other files, it will be compiled again (and again!) in every file in which you include it.

Now here's the thing: You are guarding it with #ifndef SOCKET_CLIENT_CLASS, however, each file that has #include "client.cpp" is built independently and as such will find SOCKET_CLIENT_CLASS not yet defined. Therefore it's contents will be included, not #ifdef'd out.

If it contains any definitions at all (rather than just declarations) then these definitions will be repeated in every file where it's included.

How do I configure git to ignore some files locally?

Update: Consider using git update-index --skip-worktree [<file>...] instead, thanks @danShumway! See Borealid's explanation on the difference of the two options.


Old answer:

If you need to ignore local changes to tracked files (we have that with local modifications to config files), use git update-index --assume-unchanged [<file>...].

Counting DISTINCT over multiple columns

Here's a shorter version without the subselect:

SELECT COUNT(DISTINCT DocumentId, DocumentSessionId) FROM DocumentOutputItems

It works fine in MySQL, and I think that the optimizer has an easier time understanding this one.

Edit: Apparently I misread MSSQL and MySQL - sorry about that, but maybe it helps anyway.

How to generate access token using refresh token through google drive API?

Just posting my answer in case it helps anyone as I spent an hour to figure it out :)

First of all two very helpful link related to google api and fetching data from any of google services:

https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php

https://developers.google.com/identity/protocols/OAuth2WebServer

Furthermore, when using the following method:

$client->setAccessToken($token)

The $token needs to be the full object returned by the google when making authorization request, not the only access_token which you get inside the object so if you get the object lets say:

{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}

then you need to give:

$client->setAccessToken('{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}')

Not

$client->setAccessToken('xyz')

And then even if your access_token is expired, google will refresh it itself by using the refresh_token in the access_token object.

Java image resize, maintain aspect ratio

Translated from here:

Dimension getScaledDimension(Dimension imageSize, Dimension boundary) {

    double widthRatio = boundary.getWidth() / imageSize.getWidth();
    double heightRatio = boundary.getHeight() / imageSize.getHeight();
    double ratio = Math.min(widthRatio, heightRatio);

    return new Dimension((int) (imageSize.width  * ratio),
                         (int) (imageSize.height * ratio));
}

You can also use imgscalr to resize images while maintaining aspect ratio:

BufferedImage resizeMe = ImageIO.read(new File("orig.jpg"));
Dimension newMaxSize = new Dimension(255, 255);
BufferedImage resizedImg = Scalr.resize(resizeMe, Method.QUALITY,
                                        newMaxSize.width, newMaxSize.height);

Get the first element of each tuple in a list in Python

Use a list comprehension:

res_list = [x[0] for x in rows]

Below is a demonstration:

>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>

Alternately, you could use unpacking instead of x[0]:

res_list = [x for x,_ in rows]

Below is a demonstration:

>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>

Both methods practically do the same thing, so you can choose whichever you like.

Which .NET Dependency Injection frameworks are worth looking into?

Spring.Net is quite solid, but the documentation took some time to wade through. Autofac is good, and while .Net 2.0 is supported, you need VS 2008 to compile it, or else use the command line to build your app.

javac: invalid target release: 1.8

if you are going to step down, then change your project's source to 1.7 as well,

right click on your Project -> Properties -> Sources window 

and set 1.7 here

note: however I would suggest you to figure out why it doesn't work on 1.8

CASE in WHERE, SQL Server

A few ways:

-- Do the comparison, OR'd with a check on the @Country=0 case
WHERE (a.Country = @Country OR @Country = 0)

-- compare the Country field to itself
WHERE a.Country = CASE WHEN @Country > 0 THEN @Country ELSE a.Country END

Or, use a dynamically generated statement and only add in the Country condition if appropriate. This should be most efficient in the sense that you only execute a query with the conditions that actually need to apply and can result in a better execution plan if supporting indices are in place. You would need to use parameterised SQL to prevent against SQL injection.

How can I use NSError in my iPhone App?

Objective-C

NSError *err = [NSError errorWithDomain:@"some_domain"
                                   code:100
                               userInfo:@{
                                           NSLocalizedDescriptionKey:@"Something went wrong"
                               }];

Swift 3

let error = NSError(domain: "some_domain",
                      code: 100,
                  userInfo: [NSLocalizedDescriptionKey: "Something went wrong"])

How to delete an SVN project from SVN repository

The correct sentence is: svnadmin deltify $PATH. do not forghet to delet the project or repository from the file svn-acl (if you use it). if you simply delete the folder of repository you may corrupt the svn directory depending on how your svn is configured in your environment.

jquery json to string?

I use

$.param(jsonObj)

which gets me the string.

jQuery - adding elements into an array

Try this, at the end of the each loop, ids array will contain all the hexcodes.

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});

Lining up labels with radio buttons in bootstrap

This is all nicely lined up including the field label. Lining up the field label was the tricky part.

enter image description here

HTML Code:

<div class="form-group">
    <label class="control-label col-md-5">Create a</label>
    <div class="col-md-7">
        <label class="radio-inline control-label">
            <input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
        </label>
        <label class="radio-inline control-label">
            <input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
        </label>
    </div>
</div>

CSHTML / Razor Code:

<div class="form-group">
    @Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
    <div class="col-md-7">
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
        </label>
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
        </label>
    </div>
</div>

PHP append one array to another (not array_push or +)

Another way to do this in PHP 5.6+ would be to use the ... token

$a = array('a', 'b');
$b = array('c', 'd');

array_push($a, ...$b);

// $a is now equals to array('a','b','c','d');

This will also work with any Traversable

$a = array('a', 'b');
$b = new ArrayIterator(array('c', 'd'));

array_push($a, ...$b);

// $a is now equals to array('a','b','c','d');

A warning though:

  • in PHP versions before 7.3 this will cause a fatal error if $b is an empty array or not traversable e.g. not an array
  • in PHP 7.3 a warning will be raised if $b is not traversable

Join String list elements with a delimiter in one step

If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.

Cannot attach the file *.mdf as database

You already have an old copy of that database installed in Server Explorer. So its a simple naming collision in the Server Object Explorer / SQL server. You likely created the same database Catalog Name already before you decided to move it to the Apps_Data folder. So that Database name already exists and just needs to be deleted.

Just go into Visual Studio > View > SQL Server Object Explorer and delete the old database name and its connection. Retry your app again and it should install the .mdf file in App_Data and create the same exact database again in the Server Explorer.

Rails :include vs. :joins

'joins' just used to join tables and when you called associations on joins then it will again fire query (it mean many query will fire)

lets suppose you have tow model, User and Organisation
User has_many organisations
suppose you have 10 organisation for a user 
@records= User.joins(:organisations).where("organisations.user_id = 1")
QUERY will be 
 select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1

it will return all records of organisation related to user
and @records.map{|u|u.organisation.name}
it run QUERY like 
select * from organisations where organisations.id = x then time(hwo many organisation you have)

total number of SQL is 11 in this case

But with 'includes' will eager load the included associations and add them in memory(load all associations on first load) and not fire query again

when you get records with includes like @records= User.includes(:organisations).where("organisations.user_id = 1") then query will be

select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1
and 


 select * from organisations where organisations.id IN(IDS of organisation(1, to 10)) if 10 organisation
and when you run this 

@records.map{|u|u.organisation.name} no query will fire

How do I tell if .NET 3.5 SP1 is installed?

Take a look at this article which shows the registry keys you need to look for and provides a .NET library that will do this for you.

First, you should to determine if .NET 3.5 is installed by looking at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install, which is a DWORD value. If that value is present and set to 1, then that version of the Framework is installed.

Look at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP, which is a DWORD value which indicates the Service Pack level (where 0 is no service pack).

To be correct about things, you really need to ensure that .NET Fx 2.0 and .NET Fx 3.0 are installed first and then check to see if .NET 3.5 is installed. If all three are true, then you can check for the service pack level.

How do I sort arrays using vbscript?

This is a vbscript implementation of merge sort.

'@Function Name: Sort
'@Author: Lewis Gordon
'@Creation Date: 4/26/12
'@Description: Sorts a given array either in ascending or descending order, as specified by the
'                order parameter.  This array is then returned at the end of the function.
'@Prerequisites:  An array must be allocated and have all its values inputted.
'@Parameters:
'    $ArrayToSort:  This is the array that is being sorted.
'    $Order:  This is the sorting order that the array will be sorted in.  This parameter 
'                can either    be "ASC" or "DESC" or ascending and descending, respectively.
'@Notes:  This uses merge sort under the hood.  Also, this function has only been tested for
'            integers and strings in the array.  However, this should work for any data type that
'            implements the greater than and less than comparators.  This function also requires
'            that the merge function is also present, as it is needed to complete the sort.
'@Examples:
'    Dim i
'    Dim TestArray(50)
'    Randomize
'    For i=0 to UBound(TestArray)
'        TestArray(i) = Int((100 - 0 + 1) * Rnd + 0)
'    Next
'    MsgBox Join(Sort(TestArray, "DESC"))
'
'@Return value:  This function returns a sorted array in the specified order.
'@Change History: None

'The merge function.
Public Function Merge(LeftArray, RightArray, Order)
    'Declared variables
    Dim FinalArray
    Dim FinalArraySize
    Dim i
    Dim LArrayPosition
    Dim RArrayPosition

    'Variable initialization
    LArrayPosition = 0
    RArrayPosition = 0

    'Calculate the expected size of the array based on the two smaller arrays.
    FinalArraySize = UBound(LeftArray) + UBound(RightArray) + 1
    ReDim FinalArray(FinalArraySize)

    'This should go until we need to exit the function.
    While True

        'If we are done with all the values in the left array.  Add the rest of the right array
        'to the final array.
        If LArrayPosition >= UBound(LeftArray)+1 Then
            For i=RArrayPosition To UBound(RightArray)
                FinalArray(LArrayPosition+i) = RightArray(i)
            Next
            Merge = FinalArray
            Exit Function

        'If we are done with all the values in the right array.  Add the rest of the left array
        'to the final array.
        ElseIf RArrayPosition >= UBound(RightArray)+1 Then
            For i=LArrayPosition To UBound(LeftArray)
                FinalArray(i+RArrayPosition) = LeftArray(i)
            Next
            Merge = FinalArray
            Exit Function

        'For descending, if the current value of the left array is greater than the right array 
        'then add it to the final array.  The position of the left array will then be incremented
        'by one.
        ElseIf LeftArray(LArrayPosition) > RightArray(RArrayPosition) And UCase(Order) = "DESC" Then
            FinalArray(LArrayPosition+RArrayPosition) = LeftArray(LArrayPosition)
            LArrayPosition = LArrayPosition + 1

        'For ascending, if the current value of the left array is less than the right array 
        'then add it to the final array.  The position of the left array will then be incremented
        'by one.
        ElseIf LeftArray(LArrayPosition) < RightArray(RArrayPosition) And UCase(Order) = "ASC" Then
            FinalArray(LArrayPosition+RArrayPosition) = LeftArray(LArrayPosition)
            LArrayPosition = LArrayPosition + 1

        'For anything else that wasn't covered, add the current value of the right array to the
        'final array.
        Else
            FinalArray(LArrayPosition+RArrayPosition) = RightArray(RArrayPosition)
            RArrayPosition = RArrayPosition + 1
        End If
    Wend
End Function

'The main sort function.
Public Function Sort(ArrayToSort, Order)
    'Variable declaration.
    Dim i
    Dim LeftArray
    Dim Modifier
    Dim RightArray

    'Check to make sure the order parameter is okay.
    If Not UCase(Order)="ASC" And Not UCase(Order)="DESC" Then
        Exit Function
    End If
    'If the array is a singleton or 0 then it is sorted.
    If UBound(ArrayToSort) <= 0 Then
        Sort = ArrayToSort
        Exit Function
    End If

    'Setting up the modifier to help us split the array effectively since the round
    'functions aren't helpful in VBScript.
    If UBound(ArrayToSort) Mod 2 = 0 Then
        Modifier = 1
    Else
        Modifier = 0
    End If

    'Setup the arrays to about half the size of the main array.
    ReDim LeftArray(Fix(UBound(ArrayToSort)/2))
    ReDim RightArray(Fix(UBound(ArrayToSort)/2)-Modifier)

    'Add the first half of the values to one array.
    For i=0 To UBound(LeftArray)
        LeftArray(i) = ArrayToSort(i)
    Next

    'Add the other half of the values to the other array.
    For i=0 To UBound(RightArray)
        RightArray(i) = ArrayToSort(i+Fix(UBound(ArrayToSort)/2)+1)
    Next

    'Merge the sorted arrays.
    Sort = Merge(Sort(LeftArray, Order), Sort(RightArray, Order), Order)
End Function

Example of a strong and weak entity types

A data object that can exist without depending upon the existence of another data object is known as Strong Data Object.

What is an HttpHandler in ASP.NET

An HttpHandler (or IHttpHandler) is basically anything that is responsible for serving content. An ASP.NET page (aspx) is a type of handler.

You might write your own, for example, to serve images etc from a database rather than from the web-server itself, or to write a simple POX service (rather than SOAP/WCF/etc)

Maven is not working in Java 8 when Javadoc tags are incomplete

So, save yourself some hours that I didn't and try this if it seems not to work:

 <additionalJOption>-Xdoclint:none</additionalJOption>

The tag is changed for newer versions.

Bootstrap get div to align in the center

When I align elements in center I use the bootstrap class text-center:

<div class="text-center">Centered content goes here</div>

ng-change not working on a text input

ng-change requires ng-model,

<input type="text" name="abc" class="color" ng-model="someName" ng-change="myStyle={color:'green'}">

Internet Explorer 11 detection

A pretty safe & concise way to detect IE 11 only is

if(window.msCrypto) {
    // I'm IE11 for sure
}

or something like this

var IE11= !!window.msCrypto;

msCrypto is a prefixed version of the window.crypto object and only implemented in IE 11.
https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto

How to generate the "create table" sql statement for an existing table in postgreSQL

Dean Toader Just excellent! I'd modify your code a little, to show all constraints in the table and to make possible to use regexp mask in table name.

CREATE OR REPLACE FUNCTION public.generate_create_table_statement(p_table_name character varying)
  RETURNS SETOF text AS
$BODY$
DECLARE
    v_table_ddl   text;
    column_record record;
    table_rec record;
    constraint_rec record;
    firstrec boolean;
BEGIN
    FOR table_rec IN
        SELECT c.relname FROM pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                WHERE relkind = 'r'
                AND relname~ ('^('||p_table_name||')$')
                AND n.nspname <> 'pg_catalog'
                AND n.nspname <> 'information_schema'
                AND n.nspname !~ '^pg_toast'
                AND pg_catalog.pg_table_is_visible(c.oid)
          ORDER BY c.relname
    LOOP

        FOR column_record IN 
            SELECT 
                b.nspname as schema_name,
                b.relname as table_name,
                a.attname as column_name,
                pg_catalog.format_type(a.atttypid, a.atttypmod) as column_type,
                CASE WHEN 
                    (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                     FROM pg_catalog.pg_attrdef d
                     WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) IS NOT NULL THEN
                    'DEFAULT '|| (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
                                  FROM pg_catalog.pg_attrdef d
                                  WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)
                ELSE
                    ''
                END as column_default_value,
                CASE WHEN a.attnotnull = true THEN 
                    'NOT NULL'
                ELSE
                    'NULL'
                END as column_not_null,
                a.attnum as attnum,
                e.max_attnum as max_attnum
            FROM 
                pg_catalog.pg_attribute a
                INNER JOIN 
                 (SELECT c.oid,
                    n.nspname,
                    c.relname
                  FROM pg_catalog.pg_class c
                       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                  WHERE c.relname = table_rec.relname
                    AND pg_catalog.pg_table_is_visible(c.oid)
                  ORDER BY 2, 3) b
                ON a.attrelid = b.oid
                INNER JOIN 
                 (SELECT 
                      a.attrelid,
                      max(a.attnum) as max_attnum
                  FROM pg_catalog.pg_attribute a
                  WHERE a.attnum > 0 
                    AND NOT a.attisdropped
                  GROUP BY a.attrelid) e
                ON a.attrelid=e.attrelid
            WHERE a.attnum > 0 
              AND NOT a.attisdropped
            ORDER BY a.attnum
        LOOP
            IF column_record.attnum = 1 THEN
                v_table_ddl:='CREATE TABLE '||column_record.schema_name||'.'||column_record.table_name||' (';
            ELSE
                v_table_ddl:=v_table_ddl||',';
            END IF;

            IF column_record.attnum <= column_record.max_attnum THEN
                v_table_ddl:=v_table_ddl||chr(10)||
                         '    '||column_record.column_name||' '||column_record.column_type||' '||column_record.column_default_value||' '||column_record.column_not_null;
            END IF;
        END LOOP;

        firstrec := TRUE;
        FOR constraint_rec IN
            SELECT conname, pg_get_constraintdef(c.oid) as constrainddef 
                FROM pg_constraint c 
                    WHERE conrelid=(
                        SELECT attrelid FROM pg_attribute
                        WHERE attrelid = (
                            SELECT oid FROM pg_class WHERE relname = table_rec.relname
                        ) AND attname='tableoid'
                    )
        LOOP
            v_table_ddl:=v_table_ddl||','||chr(10);
            v_table_ddl:=v_table_ddl||'CONSTRAINT '||constraint_rec.conname;
            v_table_ddl:=v_table_ddl||chr(10)||'    '||constraint_rec.constrainddef;
            firstrec := FALSE;
        END LOOP;
        v_table_ddl:=v_table_ddl||');';
        RETURN NEXT v_table_ddl;
    END LOOP;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION public.generate_create_table_statement(character varying)
  OWNER TO postgres;

Now you can, for example, make the following query

SELECT * FROM generate_create_table_statement('.*');

which results like this:

CREATE TABLE public.answer (                                                                        
     id integer DEFAULT nextval('answer_id_seq'::regclass) NOT NULL,                               
     questionid integer  NOT NULL,                                                                  
     title character varying  NOT NULL,                                                             
     defaultvalue character varying  NULL,                                                          
     valuetype integer  NOT NULL,                                                                   
     isdefault boolean  NULL,                                                                       
     minval double precision  NULL,                                                                 
     maxval double precision  NULL,                                                                 
     followminmax integer DEFAULT 0 NOT NULL,                                                       
CONSTRAINT answer_pkey                                                                              
     PRIMARY KEY (id),                                                                              
CONSTRAINT answer_questionid_fkey                                                                  
     FOREIGN KEY (questionid) REFERENCES question(id) ON UPDATE RESTRICT ON DELETE RESTRICT,       
CONSTRAINT answer_valuetype_fkey                                                                   
     FOREIGN KEY (valuetype) REFERENCES answervaluetype(id) ON UPDATE RESTRICT ON DELETE RESTRICT);

for each user table.

npm install vs. update - what's the difference?

The difference between npm install and npm update handling of package versions specified in package.json:

{
  "name":          "my-project",
  "version":       "1.0",                             // install   update
  "dependencies":  {                                  // ------------------
    "already-installed-versionless-module":  "*",     // ignores   "1.0" -> "1.1"
    "already-installed-semver-module":       "^1.4.3" // ignores   "1.4.3" -> "1.5.2"
    "already-installed-versioned-module":    "3.4.1"  // ignores   ignores
    "not-yet-installed-versionless-module":  "*",     // installs  installs
    "not-yet-installed-semver-module":       "^4.2.1" // installs  installs
    "not-yet-installed-versioned-module":    "2.7.8"  // installs  installs
  }
}

Summary: The only big difference is that an already installed module with fuzzy versioning ...

  • gets ignored by npm install
  • gets updated by npm update

Additionally: install and update by default handle devDependencies differently

  • npm install will install/update devDependencies unless --production flag is added
  • npm update will ignore devDependencies unless --dev flag is added

Why use npm install at all?

Because npm install does more when you look besides handling your dependencies in package.json. As you can see in npm install you can ...

  • manually install node-modules
  • set them as global (which puts them in the shell's PATH) using npm install -g <name>
  • install certain versions described by git tags
  • install from a git url
  • force a reinstall with --force

SSIS Connection Manager Not Storing SQL Password

Check the text contents of the connection manager file itself, the password field might be configured in the Project.params file, in which case entering the password into the connection manager window will cause it to not save.

How to get the current loop index when using Iterator?

You can use ListIterator to do the counting:

final List<String> list = Arrays.asList("zero", "one", "two", "three");

for (final ListIterator<String> it = list.listIterator(); it.hasNext();) {
    final String s = it.next();
    System.out.println(it.previousIndex() + ": " + s);
}

Updating property value in properties file without deleting other values

You can use Apache Commons Configuration library. The best part of this is, it won't even mess up the properties file and keeps it intact (even comments).

Javadoc

PropertiesConfiguration conf = new PropertiesConfiguration("propFile.properties");
conf.setProperty("key", "value");
conf.save();    

How do I vertical center text next to an image in html/css?

Does "pure HTML/CSS" exclude the use of tables? Because they will easily do what you want:

<table>
    <tr>
        <td valign="top"><img src="myImage.jpg" alt="" /></td>
        <td valign="middle">This is my text!</td>
    </tr>
</table>

Flame me all you like, but that works (and works in old, janky browsers).

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

How about:

(Updated)

$("#column_select").change(function () {
    $("#layout_select")
        .find("option")
        .show()
        .not("option[value*='" + this.value + "']").hide();

    $("#layout_select").val(
        $("#layout_select").find("option:visible:first").val());

}).change();

(assuming the third option should have a value col3)

Example: http://jsfiddle.net/cL2tt/

Notes:

  • Use the .change() event to define an event handler that executes when the value of select#column_select changes.
  • .show() all options in the second select.
  • .hide() all options in the second select whose value does not contain the value of the selected option in select#column_select, using the attribute contains selector.

How to call same method for a list of objects?

Starting in Python 2.6 there is a operator.methodcaller function.

So you can get something more elegant (and fast):

from operator import methodcaller

map(methodcaller('method_name'), list_of_objects)

C++ style cast from unsigned char * to const char *

unsigned char* is basically a byte array and should be used to represent raw data rather than a string generally. A unicode string would be represented as wchar_t*

According to the C++ standard a reinterpret_cast between unsigned char* and char* is safe as they are the same size and have the same construction and constraints. I try to avoid reintrepret_cast even more so than const_cast in general.

If static cast fails with what you are doing you may want to reconsider your design because frankly if you are using C++ you may want to take advantage of what the "plus plus" part offers and use string classes and STL (aka std::basic_string might work better for you)

How do I do a not equal in Django queryset filtering?

results = Model.objects.filter(a = True).exclude(x = 5)
Generetes this sql:
select * from tablex where a != 0 and x !=5
The sql depends on how your True/False field is represented, and the database engine. The django code is all you need though.

Python: call a function from string name

You can use a dictionary too.

def install():
    print "In install"

methods = {'install': install}

method_name = 'install' # set by the command line options
if method_name in methods:
    methods[method_name]() # + argument list of course
else:
    raise Exception("Method %s not implemented" % method_name)

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

(Edit: Forget my previous babble...)

Ok, there might be situations where you would go either to the model or to some other url... But I don't really think this belongs in the model, the view (or maybe the model) sounds more apropriate.

About the routes, as far as I know the routes is for the actions in controllers (wich usually "magically" uses a view), not directly to views. The controller should handle all requests, the view should present the results and the model should handle the data and serve it to the view or controller. I've heard a lot of people here talking about routes to models (to the point I'm allmost starting to beleave it), but as I understand it: routes goes to controllers. Of course a lot of controllers are controllers for one model and is often called <modelname>sController (e.g. "UsersController" is the controller of the model "User").

If you find yourself writing nasty amounts of logic in a view, try to move the logic somewhere more appropriate; request and internal communication logic probably belongs in the controller, data related logic may be placed in the model (but not display logic, which includes link tags etc.) and logic that is purely display related would be placed in a helper.

Twitter bootstrap float div right

You can assign the class name like text-center, left or right. The text will align accordingly to these class name. You don't need to make extra class name separately. These classes are built in BootStrap 3 and bootstrap 4.

Bootstrap 3

v3 Text Alignment Docs

<p class="text-left">Left aligned text.</p>
<p class="text-center">Center aligned text.</p>
<p class="text-right">Right aligned text.</p>
<p class="text-justify">Justified text.</p>
<p class="text-nowrap">No wrap text.</p>

Bootstrap 4

v4 Text Alignment Docs

<p class="text-xs-left">Left aligned text on all viewport sizes.</p>
<p class="text-xs-center">Center aligned text on all viewport sizes.</p>
<p class="text-xs-right">Right aligned text on all viewport sizes.</p>

<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
<p class="text-md-left">Left aligned text on viewports sized MD (medium) or wider.</p>
<p class="text-lg-left">Left aligned text on viewports sized LG (large) or wider.</p>
<p class="text-xl-left">Left aligned text on viewports sized XL (extra-large) or wider.</p>

Get the string within brackets in Python

You can use

import re

s = re.search(r"\[.*?]", string)
if s:
    print(s.group(0))

Create ArrayList from array

There is another option if your goal is to generate a fixed list at runtime, which is as simple as it is effective:

static final ArrayList<Element> myList = generateMyList();

private static ArrayList<Element> generateMyList() {
  final ArrayList<Element> result = new ArrayList<>();
  result.add(new Element(1));
  result.add(new Element(2));
  result.add(new Element(3));
  result.add(new Element(4));
  return result;
}


The benefit of using this pattern is, that the list is for once generated very intuitively and therefore is very easy to modify even with large lists or complex initialization, while on the other hand always contains the same Elements on every actual run of the program (unless you change it at a later point of course).

How to programmatically clear application data

you can clear SharedPreferences app-data with this

Editor editor = 
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();

and for clearing app db, this answer is correct -> Clearing Application database

Should ol/ul be inside <p> or outside?

The short answer is that ol elements are not legally allowed inside p elements.

To see why, let's go to the spec! If you can get comfortable with the HTML spec, it will answer many of your questions and curiosities. You want to know if an ol can live inside a p. So…

4.5.1 The p element:

Categories: Flow content, Palpable content.
Content model: Phrasing content.


4.5.5 The ol element:

Categories: Flow content.
Content model: Zero or more li and script-supporting elements.

The first part says that p elements can only contain phrasing content (which are “inline” elements like span and strong).

The second part says ols are flow content (“block” elements like p and div). So they can't be used inside a p.


ols and other flow content can be used in in some other elements like div:

4.5.13 The div element:

Categories: Flow content, Palpable content.
Content model: Flow content.

How to update and order by using ms sql

You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:

UPDATE  messages 
SET status=10 
WHERE ID in (SELECT TOP (10) Id 
             FROM Table 
             WHERE status=0 
             ORDER BY priority DESC);

How to change Jquery UI Slider handle

You also should set border:none to that css class.

Redirect to specified URL on PHP script completion?

You could always just use the tag to refresh the page - or maybe just drop the necessary javascript into the page at the end that would cause the page to redirect. You could even throw that in an onload function, so once its finished, the page is redirected

<?php

  echo $htmlHeader;
  while($stuff){
    echo $stuff;
  }
  echo "<script>window.location = 'http://www.yourdomain.com'</script>";
?>

JavaScript regex for alphanumeric string with length of 3-5 chars

add {3,5} to your expression which means length between 3 to 5

/^([a-zA-Z0-9_-]){3,5}$/

Regular Expression to reformat a US phone number in Javascript

Almost all of these have issues when the user tries to backspace over the delimiters, particularly from the middle of the string.

Here's a jquery solution that handles that, and also makes sure the cursor stays in the right place as you edit:

//format text input as phone number (nnn) nnn-nnnn
$('.myPhoneField').on('input', function (e){
    var $phoneField = e.target;
    var cursorPosition = $phoneField.selectionStart;
    var numericString = $phoneField.value.replace(/\D/g, '').substring(0, 10);

    // let user backspace over the '-'
    if (cursorPosition === 9 && numericString.length > 6) return;

    // let user backspace over the ') '
    if (cursorPosition === 5 && numericString.length > 3) return;
    if (cursorPosition === 4 && numericString.length > 3) return;

    var match = numericString.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
    if (match) {
        var newVal = '(' + match[1];
        newVal += match[2] ? ') ' + match[2] : '';
        newVal += match[3] ? '-' + match[3] : '';

        // to help us put the cursor back in the right place
        var delta = newVal.length - Math.min($phoneField.value.length, 14);      
        $phoneField.value = newVal;
        $phoneField.selectionEnd = cursorPosition + delta;
    } else {
        $phoneField.value = '';        
    }
})

assembly to compare two numbers

First a CMP (comparison) instruction is called then one of the following:

jle - jump to line if less than or equal to
jge - jump to line if greater than or equal to

The lowest assembler works with is bytes, not bits (directly anyway). If you want to know about bit logic you'll need to take a look at circuit design.

Get first word of string

This code should get you the first word,

var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');

 //Now i want to get the first word of every split-ed sting parts:

 for (var i=0;i<str1.length;i++)
 {
     //What to do here to get the first word :(
     var words = str1[i].split(" ");
     console.log(words[0]);
 }

Converting Python dict to kwargs?

** operator would be helpful here.

** operator will unpack the dict elements and thus **{'type':'Event'} would be treated as type='Event'

func(**{'type':'Event'}) is same as func(type='Event') i.e the dict elements would be converted to the keyword arguments.

FYI

* will unpack the list elements and they would be treated as positional arguments.

func(*['one', 'two']) is same as func('one', 'two')

E: Unable to locate package npm

in my jenkins/jenkins docker sudo always generates error:

bash: sudo: command not found

I needed update repo list with:

curl -sL https://deb.nodesource.com/setup_10.x | apt-get update

then,

 apt-get install nodejs

All the command line results like this:

root@76e6f92724d1:/# curl -sL https://deb.nodesource.com/setup_10.x | apt-get update
Ign:1 http://deb.debian.org/debian stretch InRelease
Get:2 http://security.debian.org/debian-security stretch/updates InRelease [94.3 kB]
Get:3 http://deb.debian.org/debian stretch-updates InRelease [91.0 kB]
Get:4 http://deb.debian.org/debian stretch Release [118 kB]
Get:5 http://security.debian.org/debian-security stretch/updates/main amd64 Packages [520 kB]
Get:6 http://deb.debian.org/debian stretch-updates/main amd64 Packages [27.9 kB]
Get:8 http://deb.debian.org/debian stretch Release.gpg [2410 B]
Get:9 http://deb.debian.org/debian stretch/main amd64 Packages [7083 kB]
Get:7 https://packagecloud.io/github/git-lfs/debian stretch InRelease [23.2 kB]
Get:10 https://packagecloud.io/github/git-lfs/debian stretch/main amd64 Packages [4675 B]
Fetched 7965 kB in 20s (393 kB/s)
Reading package lists... Done
root@76e6f92724d1:/#  apt-get install nodejs
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  libicu57 libuv1
The following NEW packages will be installed:
  libicu57 libuv1 nodejs
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 11.2 MB of archives.
After this operation, 45.2 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 libicu57 amd64 57.1-6+deb9u3 [7705 kB]
Get:2 http://deb.debian.org/debian stretch/main amd64 libuv1 amd64 1.9.1-3 [84.4 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 nodejs amd64 4.8.2~dfsg-1 [3440 kB]
Fetched 11.2 MB in 26s (418 kB/s)
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package libicu57:amd64.
(Reading database ... 12488 files and directories currently installed.)
Preparing to unpack .../libicu57_57.1-6+deb9u3_amd64.deb ...
Unpacking libicu57:amd64 (57.1-6+deb9u3) ...
Selecting previously unselected package libuv1:amd64.
Preparing to unpack .../libuv1_1.9.1-3_amd64.deb ...
Unpacking libuv1:amd64 (1.9.1-3) ...
Selecting previously unselected package nodejs.
Preparing to unpack .../nodejs_4.8.2~dfsg-1_amd64.deb ...
Unpacking nodejs (4.8.2~dfsg-1) ...
Setting up libuv1:amd64 (1.9.1-3) ...
Setting up libicu57:amd64 (57.1-6+deb9u3) ...
Processing triggers for libc-bin (2.24-11+deb9u4) ...
Setting up nodejs (4.8.2~dfsg-1) ...
update-alternatives: using /usr/bin/nodejs to provide /usr/bin/js (js) in auto mode

How to run Unix shell script from Java code?

Just the same thing that Solaris 5.10 it works like this ./batchstart.sh there is a trick I don´t know if your OS accept it use \\. batchstart.sh instead. This double slash may help.

How to add an image to the emulator gallery in android studio?

I had the same problem too. I used this code:

Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);

Using the ADM, add the images on the sdcard or anywhere.

And when you are in your vm and the selection screen shows up, browse using the top left dropdown seen in the image below.

look at 'open from'

Is there a method that calculates a factorial in Java?


public static long factorial(int number) {
    if (number < 0) {
        throw new ArithmeticException(number + " is negative");
    }
    long fact = 1;
    for (int i = 1; i <= number; ++i) {
        fact *= i;
    }
    return fact;
}

using recursion.


public static long factorial(int number) {
    if (number < 0) {
        throw new ArithmeticException(number + " is negative");
    }
    return number == 0 || number == 1 ? 1 : number * factorial(number - 1);
}

source

URL to load resources from the classpath in Java

Inspire by @Stephen https://stackoverflow.com/a/1769454/980442 and http://docstore.mik.ua/orelly/java/exp/ch09_06.htm

To use

new URL("classpath:org/my/package/resource.extension").openConnection()

just create this class into sun.net.www.protocol.classpath package and run it into Oracle JVM implementation to work like a charm.

package sun.net.www.protocol.classpath;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

public class Handler extends URLStreamHandler {

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        return Thread.currentThread().getContextClassLoader().getResource(u.getPath()).openConnection();
    }
}

In case you are using another JVM implementation set the java.protocol.handler.pkgs=sun.net.www.protocol system property.

FYI: http://docs.oracle.com/javase/7/docs/api/java/net/URL.html#URL(java.lang.String,%20java.lang.String,%20int,%20java.lang.String)

How to convert InputStream to FileInputStream

You need something like:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

PHP preg replace only allow numbers

You could also use T-Regx library:

pattern('\D')->remove($c)

T-Regx also:

  • Throws exceptions on fail (not false, null or warnings)
  • Has automatic delimiters (delimiters are not required!)
  • Has a lot cleaner api

Multiple submit buttons on HTML form – designate one button as default

My suggestion is don't fight this behaviour. You can effectively alter the order using floats. For example:

<p id="buttons">
<input type="submit" name="next" value="Next">
<input type="submit" name="prev" value="Previous">
</p>

with:

#buttons { overflow: hidden; }
#buttons input { float: right; }

will effectively reverse the order and thus the "Next" button will be the value triggered by hitting enter.

This kind of technique will cover many circumstances without having to resort to more hacky JavaScript methods.

How to set web.config file to show full error message

If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

How to extract the decision rules from scikit-learn decision-tree?

Here is my approach to extract the decision rules in a form that can be used in directly in sql, so the data can be grouped by node. (Based on the approaches of previous posters.)

The result will be subsequent CASE clauses that can be copied to an sql statement, ex.

SELECT COALESCE(*CASE WHEN <conditions> THEN > <NodeA>*, > *CASE WHEN <conditions> THEN <NodeB>*, > ....)NodeName,* > FROM <table or view>


import numpy as np

import pickle
feature_names=.............
features  = [feature_names[i] for i in range(len(feature_names))]
clf= pickle.loads(trained_model)
impurity=clf.tree_.impurity
importances = clf.feature_importances_
SqlOut=""

#global Conts
global ContsNode
global Path
#Conts=[]#
ContsNode=[]
Path=[]
global Results
Results=[]

def print_decision_tree(tree, feature_names, offset_unit=''    ''):    
    left      = tree.tree_.children_left
    right     = tree.tree_.children_right
    threshold = tree.tree_.threshold
    value = tree.tree_.value

    if feature_names is None:
        features  = [''f%d''%i for i in tree.tree_.feature]
    else:
        features  = [feature_names[i] for i in tree.tree_.feature]        

    def recurse(left, right, threshold, features, node, depth=0,ParentNode=0,IsElse=0):
        global Conts
        global ContsNode
        global Path
        global Results
        global LeftParents
        LeftParents=[]
        global RightParents
        RightParents=[]
        for i in range(len(left)): # This is just to tell you how to create a list.
            LeftParents.append(-1)
            RightParents.append(-1)
            ContsNode.append("")
            Path.append("")


        for i in range(len(left)): # i is node
            if (left[i]==-1 and right[i]==-1):      
                if LeftParents[i]>=0:
                    if Path[LeftParents[i]]>" ":
                        Path[i]=Path[LeftParents[i]]+" AND " +ContsNode[LeftParents[i]]                                 
                    else:
                        Path[i]=ContsNode[LeftParents[i]]                                   
                if RightParents[i]>=0:
                    if Path[RightParents[i]]>" ":
                        Path[i]=Path[RightParents[i]]+" AND not " +ContsNode[RightParents[i]]                                   
                    else:
                        Path[i]=" not " +ContsNode[RightParents[i]]                     
                Results.append(" case when  " +Path[i]+"  then ''" +"{:4d}".format(i)+ " "+"{:2.2f}".format(impurity[i])+" "+Path[i][0:180]+"''")

            else:       
                if LeftParents[i]>=0:
                    if Path[LeftParents[i]]>" ":
                        Path[i]=Path[LeftParents[i]]+" AND " +ContsNode[LeftParents[i]]                                 
                    else:
                        Path[i]=ContsNode[LeftParents[i]]                                   
                if RightParents[i]>=0:
                    if Path[RightParents[i]]>" ":
                        Path[i]=Path[RightParents[i]]+" AND not " +ContsNode[RightParents[i]]                                   
                    else:
                        Path[i]=" not "+ContsNode[RightParents[i]]                      
                if (left[i]!=-1):
                    LeftParents[left[i]]=i
                if (right[i]!=-1):
                    RightParents[right[i]]=i
                ContsNode[i]=   "( "+ features[i] + " <= " + str(threshold[i])   + " ) "

    recurse(left, right, threshold, features, 0,0,0,0)
print_decision_tree(clf,features)
SqlOut=""
for i in range(len(Results)): 
    SqlOut=SqlOut+Results[i]+ " end,"+chr(13)+chr(10)

Is an entity body allowed for an HTTP DELETE request?

Might be the below GitHUb url will help you, to get the answer. Actually, Application Server like Tomcat, Weblogic denying the HTTP.DELETE call with request payload. So keeping these all things in mind, I have added example in github,please have a look into that

https://github.com/ashish720/spring-examples

Not able to change TextField Border Color

The best and most effective solution is just adding theme in your main class and add input decoration like these.

theme: ThemeData(
    inputDecorationTheme: InputDecorationTheme(
        border: OutlineInputBorder(
           borderSide: BorderSide(color: Colors.pink)
        )
    ),
)

How to install a private NPM module without my own registry?

Can I just install an NPM package that sits on the local filesystem, or perhaps even from git?

Yes you can! From the docs https://docs.npmjs.com/cli/install

A package is:

  • a) a folder containing a program described by a package.json file
  • b) a gzipped tarball containing (a)
  • c) a url that resolves to (b)
  • d) a <name>@<version> that is published on the registry with (c)
  • e) a <name>@<tag> that points to (d)
  • f) a <name> that has a "latest" tag satisfying (e)
  • g) a <git remote url> that resolves to (b)

Isn't npm brilliant?

String replacement in Objective-C

The problem exists in old versions on the iOS. in the latest, the right-to-left works well. What I did, is as follows:

first I check the iOS version:

if (![self compareCurVersionTo:4 minor:3 point:0])

Than:

// set RTL on the start on each line (except the first)  
myUITextView.text = [myUITextView.text stringByReplacingOccurrencesOfString:@"\n"
                                                           withString:@"\u202B\n"];

load scripts asynchronously

for HTML5, you can use the 'prefetch'

<link rel="prefetch" href="/style.css" as="style" />

have a look at 'preload' for js.

<link rel="preload" href="used-later.js" as="script">

Is there an XSLT name-of element?

<xsl:value-of select="name(.)" /> : <xsl:value-of select="."/>

How to read a file into vector in C++?

Just to expand on juanchopanza's answer a bit...

for (int i=0; i=((Main.size())-1); i++) {
    cout << Main[i] << '\n';
}

does this:

  1. Create i and set it to 0.
  2. Set i to Main.size() - 1. Since Main is empty, Main.size() is 0, and i gets set to -1.
  3. Main[-1] is an out-of-bounds access. Kaboom.

Where can I find the Java SDK in Linux after installing it?

$ which java 

should give you something like

/usr/bin/java

SQL like search string starts with

Aside from using %, age of empires III to lower case is age of empires iii so your query should be:

select *
from games
where lower(title) like 'age of empires iii%'

Simple JavaScript Checkbox Validation

Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.

HTML:

<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />

JavaScript:

var alterDisabledState = function () {

var isMyCheckboxChecked = $('#myCheckbox').is(':checked');

     if (isMyCheckboxChecked) {
     $('myButton').removeAttr("disabled");
     } 
     else {
             $('myButton').attr("disabled", "disabled");
     }
}

Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.

what is the difference between GROUP BY and ORDER BY in sql

They have totally different meaning and aren't really related at all.

ORDER BY allows you to sort the result set according to different criteria, such as first sort by name from a-z, then sort by the price highest to lowest.

(ORDER BY name, price DESC)

GROUP BY allows you to take your result set, group it into logical groups and then run aggregate queries on those groups. You could for instance select all employees, group them by their workplace location and calculate the average salary of all employees of each workplace location.

Attach a body onload event with JS

Cross browser window.load event

function load(){}

window[ addEventListener ? 'addEventListener' : 'attachEvent' ]( addEventListener ? 'load' : 'onload', load )

List of foreign keys and the tables they reference in Oracle DB

Here is an another solution. Using sys's default views are so slow (approx 10s in my situation). This is much faster than that (approx. 0.5s).

SELECT
    CONST.NAME AS CONSTRAINT_NAME,
    RCONST.NAME AS REF_CONSTRAINT_NAME,

    OBJ.NAME AS TABLE_NAME,
    COALESCE(ACOL.NAME, COL.NAME) AS COLUMN_NAME,
    CCOL.POS# AS POSITION,

    ROBJ.NAME AS REF_TABLE_NAME,
    COALESCE(RACOL.NAME, RCOL.NAME) AS REF_COLUMN_NAME,
    RCCOL.POS# AS REF_POSITION
FROM SYS.CON$ CONST
INNER JOIN SYS.CDEF$ CDEF ON CDEF.CON# = CONST.CON#
INNER JOIN SYS.CCOL$ CCOL ON CCOL.CON# = CONST.CON#
INNER JOIN SYS.COL$ COL  ON (CCOL.OBJ# = COL.OBJ#) AND (CCOL.INTCOL# = COL.INTCOL#)
INNER JOIN SYS.OBJ$ OBJ ON CCOL.OBJ# = OBJ.OBJ#
LEFT JOIN SYS.ATTRCOL$ ACOL ON (CCOL.OBJ# = ACOL.OBJ#) AND (CCOL.INTCOL# = ACOL.INTCOL#)

INNER JOIN SYS.CON$ RCONST ON RCONST.CON# = CDEF.RCON#
INNER JOIN SYS.CCOL$ RCCOL ON RCCOL.CON# = RCONST.CON#
INNER JOIN SYS.COL$ RCOL  ON (RCCOL.OBJ# = RCOL.OBJ#) AND (RCCOL.INTCOL# = RCOL.INTCOL#)
INNER JOIN SYS.OBJ$ ROBJ ON RCCOL.OBJ# = ROBJ.OBJ#
LEFT JOIN SYS.ATTRCOL$ RACOL  ON (RCCOL.OBJ# = RACOL.OBJ#) AND (RCCOL.INTCOL# = RACOL.INTCOL#)

WHERE CONST.OWNER# = userenv('SCHEMAID')
  AND RCONST.OWNER# = userenv('SCHEMAID')
  AND CDEF.TYPE# = 4  /* 'R' Referential/Foreign Key */;

Curl : connection refused

127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.

WAMP/XAMPP is responding very slow over localhost

I don't know why, but closing my internet connection solved this problem for me.

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Laravel 5 - How to access image uploaded in storage within View?

You can run this command in your console to make link:

php artisan storage:link

Reference link

How do I check if PHP is connected to a database already?

before... (I mean somewhere in some other file you're not sure you've included)

$db = mysql_connect()

later...

if (is_resource($db)) {
// connected
} else {
$db = mysql_connect();
}

How to multiply values using SQL

You don't need to use GROUP BY but using it won't change the outcome. Just add an ORDER BY line at the end to sort your results.

SELECT player_name, player_salary, SUM(player_salary*1.1) AS NewSalary
FROM players
GROUP BY player_salary, player_name;
ORDER BY SUM(player_salary*1.1) DESC

Progress during large file copy (Copy-Item & Write-Progress?)

Trevor Sullivan has a write-up on how to add a command called Copy-ItemWithProgress to PowerShell on Robocopy.

How to iterate object keys using *ngFor

1.Create a custom pipe to get keys.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'keys'
})
export class KeysPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return Object.keys(value);
  }
}
  1. In angular template file, you can use *ngFor and iterate over your object object
<div class ="test" *ngFor="let key of Obj | keys">
    {{key}}
    {{Obj[key].property}
<div>

How to get the position of a character in Python?

>>> s="mystring"
>>> s.index("r")
4
>>> s.find("r")
4

"Long winded" way

>>> for i,c in enumerate(s):
...   if "r"==c: print i
...
4

to get substring,

>>> s="mystring"
>>> s[4:10]
'ring'

Using if elif fi in shell scripts

Use double brackets...

if [[ expression ]]

[Vue warn]: Cannot find element

I think sometimes stupid mistakes can give us this error.

<div id="#main"> <--- id with hashtag
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>

To

<div id="main"> <--- id without hashtag
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>

Bootstrap 3 Navbar with Logo

 <div class="navbar navbar-default navbar-fixed-top" role="navigation">
        <div class="container">
            <div class="navbar-header" >
               <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                   <span class="sr-only">Toggle navigation</span>
                   <span class="icon-bar"></span>
                   <span class="icon-bar"></span>
                   <span class="icon-bar"></span>

                   </button>
                <a class="navbar-brand" href="Default.aspx"> <span> <img alt="Logo" src="Images/shopify-bag.png"height="35" width="40"/></span> Shopping GO</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav navbar-right"></ul>

//Don't forgot to add bootstrap in head of your code.

Failed to load resource: net::ERR_INSECURE_RESPONSE

Try this code to watch for, and report, a possible net::ERR_INSECURE_RESPONSE

I was having this issue as well, using a self-signed certificate, which I have chosen not to save into the Chrome Settings. After accessing the https domain and accepting the certificate, the ajax call works fine. But once that acceptance has timed-out or before it has first been accepted, the jQuery.ajax() call fails silently: the timeout parameter does not seem help and the error() function never gets called.

As such, my code never receives a success() or error() call and therefore hangs. I believe this is a bug in jquery's handling of this error. My solution is to force the error() call after a specified timeout.

This code does assume a jquery ajax call of the form jQuery.ajax({url: required, success: optional, error: optional, others_ajax_params: optional}).

Note: You will likely want to change the function within the setTimeout to integrate best with your UI: rather than calling alert().

const MS_FOR_HTTPS_FAILURE = 5000;
$.orig_ajax = $.ajax;
$.ajax = function(params)
{
  var complete = false;
  var success = params.success;
  var error = params.error;
  params.success = function() {
    if(!complete) {
      complete = true;
      if(success) success.apply(this,arguments);
    }
  }
  params.error = function() {
    if(!complete) {
      complete = true;
      if(error) error.apply(this,arguments);
    }
  }
  setTimeout(function() {
    if(!complete) {
      complete = true;
      alert("Please ensure your self-signed HTTPS certificate has been accepted. "
        + params.url);
      if(params.error)
        params.error( {},
          "Connection failure",
          "Timed out while waiting to connect to remote resource. " +
          "Possibly could not authenticate HTTPS certificate." );
    }
  }, MS_FOR_HTTPS_FAILURE);

  $.orig_ajax(params);
}

Perform .join on value in array of objects

lets say the objects array is referenced by the variable users

If ES6 can be used then the easiest solution will be:

users.map(user => user.name).join(', ');

If not, and lodash can be used so :

 _.map(users, function(user) {
     return user.name;
 }).join(', ');

Add/remove HTML inside div using JavaScript

make a class for that button lets say :

`<input type="button" value="+" class="b1" onclick="addRow()">`

your js should look like this :

$(document).ready(function(){
  $('.b1').click(function(){
      $('div').append('<input type="text"..etc ');
  });
});

convert iso date to milliseconds in javascript

In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.

let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);

The output will be the only the time from isoDate which is,

15:27

Visual Studio : short cut Key : Duplicate Line

If you like eclipse style line (or block) duplicating using CTRL+ALT+UP or CTRL+UP+DOWN, below I post macros for this purpose:

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics

Public Module DuplicateLineModule
    Sub DuplicateLineDown()
        Dim selection As TextSelection = DTE.ActiveDocument.Selection
        Dim lineNumber As Integer
        Dim line As String

        If selection.IsEmpty Then
            selection.StartOfLine(0)
            selection.EndOfLine(True)
        Else
            Dim top As Integer = selection.TopLine
            Dim bottom As Integer = selection.BottomLine

            selection.MoveToDisplayColumn(top, 0)
            selection.StartOfLine(0)

            selection.MoveToDisplayColumn(bottom, 0, True)
            selection.EndOfLine(True)
        End If

        lineNumber = selection.TopLine
        line = selection.Text

        selection.MoveToDisplayColumn(selection.BottomLine, 0)
        selection.EndOfLine()
        selection.Insert(vbNewLine & line)
    End Sub
    Sub DuplicateLineUp()
        Dim selection As TextSelection = DTE.ActiveDocument.Selection
        Dim lineNumber As Integer
        Dim line As String

        If selection.IsEmpty Then
            selection.StartOfLine(0)
            selection.EndOfLine(True)
        Else
            Dim top As Integer = selection.TopLine
            Dim bottom As Integer = selection.BottomLine

            selection.MoveToDisplayColumn(top, 0)
            selection.StartOfLine(0)

            selection.MoveToDisplayColumn(bottom, 0, True)
            selection.EndOfLine(True)
        End If

        lineNumber = selection.BottomLine
        line = selection.Text

        selection.MoveToDisplayColumn(selection.BottomLine, 0)
        selection.Insert(vbNewLine & line)
        selection.MoveToDisplayColumn(lineNumber, 0)
    End Sub
End Module

Python 2.7.10 error "from urllib.request import urlopen" no module named request

from urllib.request import urlopen, Request

Should solve everything

MySQL Select Date Equal to Today

Sounds like you need to add the formatting to the WHERE:

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE DATE_FORMAT(users.signup_date, '%Y-%m-%d') = CURDATE()

See SQL Fiddle with Demo

Spring MVC: How to perform validation?

I would like to extend nice answer of Jerome Dalbert. I found very easy to write your own annotation validators in JSR-303 way. You are not limited to have "one field" validation. You can create your own annotation on type level and have complex validation (see examples below). I prefer this way because I don't need mix different types of validation (Spring and JSR-303) like Jerome do. Also this validators are "Spring aware" so you can use @Inject/@Autowire out of box.

Example of custom object validation:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { YourCustomObjectValidator.class })
public @interface YourCustomObjectValid {

    String message() default "{YourCustomObjectValid.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class YourCustomObjectValidator implements ConstraintValidator<YourCustomObjectValid, YourCustomObject> {

    @Override
    public void initialize(YourCustomObjectValid constraintAnnotation) { }

    @Override
    public boolean isValid(YourCustomObject value, ConstraintValidatorContext context) {

        // Validate your complex logic 

        // Mark field with error
        ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
        cvb.addNode(someField).addConstraintViolation();

        return true;
    }
}

@YourCustomObjectValid
public YourCustomObject {
}

Example of generic fields equality:

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { FieldsEqualityValidator.class })
public @interface FieldsEquality {

    String message() default "{FieldsEquality.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Name of the first field that will be compared.
     * 
     * @return name
     */
    String firstFieldName();

    /**
     * Name of the second field that will be compared.
     * 
     * @return name
     */
    String secondFieldName();

    @Target({ TYPE, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    public @interface List {
        FieldsEquality[] value();
    }
}




import java.lang.reflect.Field;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

public class FieldsEqualityValidator implements ConstraintValidator<FieldsEquality, Object> {

    private static final Logger log = LoggerFactory.getLogger(FieldsEqualityValidator.class);

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(FieldsEquality constraintAnnotation) {
        firstFieldName = constraintAnnotation.firstFieldName();
        secondFieldName = constraintAnnotation.secondFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null)
            return true;

        try {
            Class<?> clazz = value.getClass();

            Field firstField = ReflectionUtils.findField(clazz, firstFieldName);
            firstField.setAccessible(true);
            Object first = firstField.get(value);

            Field secondField = ReflectionUtils.findField(clazz, secondFieldName);
            secondField.setAccessible(true);
            Object second = secondField.get(value);

            if (first != null && second != null && !first.equals(second)) {
                    ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(firstFieldName).addConstraintViolation();

          ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(someField).addConstraintViolation(secondFieldName);

                return false;
            }
        } catch (Exception e) {
            log.error("Cannot validate fileds equality in '" + value + "'!", e);
            return false;
        }

        return true;
    }
}

@FieldsEquality(firstFieldName = "password", secondFieldName = "confirmPassword")
public class NewUserForm {

    private String password;

    private String confirmPassword;

}

Fast and simple String encrypt/decrypt in JAVA

Update

the library already have Java/Kotlin support, see github.


Original

To simplify I did a class to be used simply, I added it on Encryption library to use it you just do as follow:

Add the gradle library:

compile 'se.simbio.encryption:library:2.0.0'

and use it:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);

if you not want add the Encryption library you can just copy the following class to your project. If you are in an android project you need to import android Base64 in this class, if you are in a pure java project you need to add this class manually you can get it here

Encryption.java

package se.simbio.encryption;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * A class to make more easy and simple the encrypt routines, this is the core of Encryption library
 */
public class Encryption {

    /**
     * The Builder used to create the Encryption instance and that contains the information about
     * encryption specifications, this instance need to be private and careful managed
     */
    private final Builder mBuilder;

    /**
     * The private and unique constructor, you should use the Encryption.Builder to build your own
     * instance or get the default proving just the sensible information about encryption
     */
    private Encryption(Builder builder) {
        mBuilder = builder;
    }

    /**
     * @return an default encryption instance or {@code null} if occur some Exception, you can
     * create yur own Encryption instance using the Encryption.Builder
     */
    public static Encryption getDefault(String key, String salt, byte[] iv) {
        try {
            return Builder.getDefaultBuilder(key, salt, iv).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Encrypt a String
     *
     * @param data the String to be encrypted
     *
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     *
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
     */
    public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
    }

    /**
     * This is a sugar method that calls encrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     *
     * @param data the String to be encrypted
     *
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     */
    public String encryptOrNull(String data) {
        try {
            return encrypt(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This is a sugar method that calls encrypt method in background, it is a good idea to use this
     * one instead the default method because encryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     *
     * @param data     the String to be encrypted
     * @param callback the Callback to handle the results
     */
    public void encryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String encrypt = encrypt(data);
                    if (encrypt == null) {
                        callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data"));
                    }
                    callback.onSuccess(encrypt);
                } catch (Exception e) {
                    callback.onError(e);
                }
            }
        }).start();
    }

    /**
     * Decrypt a String
     *
     * @param data the String to be decrypted
     *
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     *
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
     */
    public String decrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        byte[] dataBytes = Base64.decode(data, mBuilder.getBase64Mode());
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
        return new String(dataBytesDecrypted);
    }

    /**
     * This is a sugar method that calls decrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     *
     * @param data the String to be decrypted
     *
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     */
    public String decryptOrNull(String data) {
        try {
            return decrypt(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This is a sugar method that calls decrypt method in background, it is a good idea to use this
     * one instead the default method because decryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     *
     * @param data     the String to be decrypted
     * @param callback the Callback to handle the results
     */
    public void decryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String decrypt = decrypt(data);
                    if (decrypt == null) {
                        callback.onError(new Exception("Decrypt return null, it normally occurs when you send a null data"));
                    }
                    callback.onSuccess(decrypt);
                } catch (Exception e) {
                    callback.onError(e);
                }
            }
        }).start();
    }

    /**
     * creates a 128bit salted aes key
     *
     * @param key encoded input key
     *
     * @return aes 128 bit salted key
     *
     * @throws NoSuchAlgorithmException     if no installed provider that can provide the requested
     *                                      by the Builder secret key type
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws InvalidKeySpecException      if the specified key specification cannot be used to
     *                                      generate a secret key
     * @throws NullPointerException         if the specified Builder secret key type is {@code null}
     */
    private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
        KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
        SecretKey tmp = factory.generateSecret(spec);
        return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
    }

    /**
     * takes in a simple string and performs an sha1 hash
     * that is 128 bits long...we then base64 encode it
     * and return the char array
     *
     * @param key simple inputted string
     *
     * @return sha1 base64 encoded representation
     *
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws NoSuchAlgorithmException     if the Builder digest algorithm is not available
     * @throws NullPointerException         if the Builder digest algorithm is {@code null}
     */
    private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
        messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
        return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
    }

    /**
     * When you encrypt or decrypt in callback mode you get noticed of result using this interface
     */
    public interface Callback {

        /**
         * Called when encrypt or decrypt job ends and the process was a success
         *
         * @param result the encrypted or decrypted String
         */
        void onSuccess(String result);

        /**
         * Called when encrypt or decrypt job ends and has occurred an error in the process
         *
         * @param exception the Exception related to the error
         */
        void onError(Exception exception);

    }

    /**
     * This class is used to create an Encryption instance, you should provide ALL data or start
     * with the Default Builder provided by the getDefaultBuilder method
     */
    public static class Builder {

        private byte[] mIv;
        private int mKeyLength;
        private int mBase64Mode;
        private int mIterationCount;
        private String mSalt;
        private String mKey;
        private String mAlgorithm;
        private String mKeyAlgorithm;
        private String mCharsetName;
        private String mSecretKeyType;
        private String mDigestAlgorithm;
        private String mSecureRandomAlgorithm;
        private SecureRandom mSecureRandom;
        private IvParameterSpec mIvParameterSpec;

        /**
         * @return an default builder with the follow defaults:
         * the default char set is UTF-8
         * the default base mode is Base64
         * the Secret Key Type is the PBKDF2WithHmacSHA1
         * the default salt is "some_salt" but can be anything
         * the default length of key is 128
         * the default iteration count is 65536
         * the default algorithm is AES in CBC mode and PKCS 5 Padding
         * the default secure random algorithm is SHA1PRNG
         * the default message digest algorithm SHA1
         */
        public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
            return new Builder()
                    .setIv(iv)
                    .setKey(key)
                    .setSalt(salt)
                    .setKeyLength(128)
                    .setKeyAlgorithm("AES")
                    .setCharsetName("UTF8")
                    .setIterationCount(1)
                    .setDigestAlgorithm("SHA1")
                    .setBase64Mode(Base64.DEFAULT)
                    .setAlgorithm("AES/CBC/PKCS5Padding")
                    .setSecureRandomAlgorithm("SHA1PRNG")
                    .setSecretKeyType("PBKDF2WithHmacSHA1");
        }

        /**
         * Build the Encryption with the provided information
         *
         * @return a new Encryption instance with provided information
         *
         * @throws NoSuchAlgorithmException if the specified SecureRandomAlgorithm is not available
         * @throws NullPointerException     if the SecureRandomAlgorithm is {@code null} or if the
         *                                  IV byte array is null
         */
        public Encryption build() throws NoSuchAlgorithmException {
            setSecureRandom(SecureRandom.getInstance(getSecureRandomAlgorithm()));
            setIvParameterSpec(new IvParameterSpec(getIv()));
            return new Encryption(this);
        }

        /**
         * @return the charset name
         */
        private String getCharsetName() {
            return mCharsetName;
        }

        /**
         * @param charsetName the new charset name
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setCharsetName(String charsetName) {
            mCharsetName = charsetName;
            return this;
        }

        /**
         * @return the algorithm
         */
        private String getAlgorithm() {
            return mAlgorithm;
        }

        /**
         * @param algorithm the algorithm to be used
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setAlgorithm(String algorithm) {
            mAlgorithm = algorithm;
            return this;
        }

        /**
         * @return the key algorithm
         */
        private String getKeyAlgorithm() {
            return mKeyAlgorithm;
        }

        /**
         * @param keyAlgorithm the keyAlgorithm to be used in keys
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKeyAlgorithm(String keyAlgorithm) {
            mKeyAlgorithm = keyAlgorithm;
            return this;
        }

        /**
         * @return the Base 64 mode
         */
        private int getBase64Mode() {
            return mBase64Mode;
        }

        /**
         * @param base64Mode set the base 64 mode
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setBase64Mode(int base64Mode) {
            mBase64Mode = base64Mode;
            return this;
        }

        /**
         * @return the type of aes key that will be created, on KITKAT+ the API has changed, if you
         * are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
         */
        private String getSecretKeyType() {
            return mSecretKeyType;
        }

        /**
         * @param secretKeyType the type of AES key that will be created, on KITKAT+ the API has
         *                      changed, if you are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecretKeyType(String secretKeyType) {
            mSecretKeyType = secretKeyType;
            return this;
        }

        /**
         * @return the value used for salting
         */
        private String getSalt() {
            return mSalt;
        }

        /**
         * @param salt the value used for salting
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSalt(String salt) {
            mSalt = salt;
            return this;
        }

        /**
         * @return the key
         */
        private String getKey() {
            return mKey;
        }

        /**
         * @param key the key.
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKey(String key) {
            mKey = key;
            return this;
        }

        /**
         * @return the length of key
         */
        private int getKeyLength() {
            return mKeyLength;
        }

        /**
         * @param keyLength the length of key
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKeyLength(int keyLength) {
            mKeyLength = keyLength;
            return this;
        }

        /**
         * @return the number of times the password is hashed
         */
        private int getIterationCount() {
            return mIterationCount;
        }

        /**
         * @param iterationCount the number of times the password is hashed
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIterationCount(int iterationCount) {
            mIterationCount = iterationCount;
            return this;
        }

        /**
         * @return the algorithm used to generate the secure random
         */
        private String getSecureRandomAlgorithm() {
            return mSecureRandomAlgorithm;
        }

        /**
         * @param secureRandomAlgorithm the algorithm to generate the secure random
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecureRandomAlgorithm(String secureRandomAlgorithm) {
            mSecureRandomAlgorithm = secureRandomAlgorithm;
            return this;
        }

        /**
         * @return the IvParameterSpec bytes array
         */
        private byte[] getIv() {
            return mIv;
        }

        /**
         * @param iv the byte array to create a new IvParameterSpec
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIv(byte[] iv) {
            mIv = iv;
            return this;
        }

        /**
         * @return the SecureRandom
         */
        private SecureRandom getSecureRandom() {
            return mSecureRandom;
        }

        /**
         * @param secureRandom the Secure Random
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecureRandom(SecureRandom secureRandom) {
            mSecureRandom = secureRandom;
            return this;
        }

        /**
         * @return the IvParameterSpec
         */
        private IvParameterSpec getIvParameterSpec() {
            return mIvParameterSpec;
        }

        /**
         * @param ivParameterSpec the IvParameterSpec
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIvParameterSpec(IvParameterSpec ivParameterSpec) {
            mIvParameterSpec = ivParameterSpec;
            return this;
        }

        /**
         * @return the message digest algorithm
         */
        private String getDigestAlgorithm() {
            return mDigestAlgorithm;
        }

        /**
         * @param digestAlgorithm the algorithm to be used to get message digest instance
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setDigestAlgorithm(String digestAlgorithm) {
            mDigestAlgorithm = digestAlgorithm;
            return this;
        }

    }

}    

Pandas every nth row

A solution I came up with when using the index was not viable ( possibly the multi-Gig .csv was too large, or I missed some technique that would allow me to reindex without crashing ).
Walk through one row at a time and add the nth row to a new dataframe.

import pandas as pd
from csv import DictReader

def make_downsampled_df(filename, interval):    
    with open(filename, 'r') as read_obj:
        csv_dict_reader = DictReader(read_obj)
        column_names = csv_dict_reader.fieldnames
        df = pd.DataFrame(columns=column_names)
    
        for index, row in enumerate(csv_dict_reader):
            if index % interval == 0:
               print(str(row))
               df = df.append(row, ignore_index=True)

    return df

Notice: Undefined offset: 0 in

This answer helped me https://stackoverflow.com/a/18880670/1821607 The reason of crush — index 0 wasn't set. Simple $array = $array + array(null) did the trick. Or you should check whether array element on index 0 is set via isset($array[0]). The second variant is the best approach for me.

How to grant remote access permissions to mysql server for user?

This grants root access with the same password from any machine in *.example.com:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%.example.com' 
    IDENTIFIED BY 'some_characters' 
    WITH GRANT OPTION;
FLUSH PRIVILEGES;

If name resolution is not going to work, you may also grant access by IP or subnet:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.%'
    IDENTIFIED BY 'some_characters'  
    WITH GRANT OPTION;
FLUSH PRIVILEGES;

MySQL GRANT syntax docs.