Programs & Examples On #Gcj

GCJ is the GNU compiler for the Java programming language. It can compile Java source code to Java bytecode, or directly to native code.

Java command not found on Linux

You can add one of the Java path to PATH variable using the following command.

export PATH=$PATH:/usr/java/jre1.6.0_24/bin/

You can add this line to .bashrc file in your home directory. Adding this to .bashrc will ensure everytime you open bash it will be PATH variable is updated.

Ambiguous overload call to abs(double)

Use fabs() instead of abs(), it's the same but for floats instead of integers.

Session variables not working php

Maybe it helps others, myself I had

session_regenerate_id(false);

I removed it and all ok!

after login was ok... ouch!

onMeasure custom view explanation

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:

  • EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
  • AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
  • UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.

The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.

Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!

Generally, if you are overriding View and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 100;
    int desiredHeight = 100;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;
    }

    //MUST CALL THIS
    setMeasuredDimension(width, height);
}

Hope that Helps.

How to write a UTF-8 file with Java?

Since Java 7 you can do the same with Files.newBufferedWriter a little more succinctly:

Path logFile = Paths.get("/tmp/example.txt");
try (BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8)) {
    writer.write("Hello World!");
    // ...
}

What does `dword ptr` mean?

The dword ptr part is called a size directive. This page explains them, but it wasn't possible to direct-link to the correct section.

Basically, it means "the size of the target operand is 32 bits", so this will bitwise-AND the 32-bit value at the address computed by taking the contents of the ebp register and subtracting four with 0.

Print out the values of a (Mat) matrix in OpenCV C++

See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0); rather than just 0,0

Or better still with the C++ interface:

cv::Mat M;
cout << "M = " << endl << " "  << M << endl << endl;

How to convert image file data in a byte array to a Bitmap?

The answer of Uttam didnt work for me. I just got null when I do:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:

//Create bitmap with width, height, and 4 bytes color (RGBA)    
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);

Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options

Getting Current date, time , day in laravel

use DateTime;

$now = new DateTime();

Read SQL Table into C# DataTable

Here, give this a shot (this is just a pseudocode)

using System;
using System.Data;
using System.Data.SqlClient;


public class PullDataTest
{
    // your data table
    private DataTable dataTable = new DataTable();

    public PullDataTest()
    {
    }

    // your method to pull data from database to datatable   
    public void PullData()
    {
        string connString = @"your connection string here";
        string query = "select * from table";

        SqlConnection conn = new SqlConnection(connString);        
        SqlCommand cmd = new SqlCommand(query, conn);
        conn.Open();

        // create data adapter
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        // this will query your database and return the result to your datatable
        da.Fill(dataTable);
        conn.Close();
        da.Dispose();
    }
}

MVC 4 - how do I pass model data to a partial view?

Three ways to pass model data to partial view (there may be more)

This is view page

Method One Populate at view

@{    
    PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
    ctry1.CountryName="India";
    ctry1.ID=1;    

    PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
    ctry2.CountryName="Africa";
    ctry2.ID=2;

    List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}

Method Two Pass Through ViewBag

@{
    var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}

Method Three pass through model

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

enter image description here

Adding a guideline to the editor in Visual Studio

Without the need to edit any registry keys, the Productivity Power Tools extension (available for all versions of visual studio) provides guideline functionality.

Once installed just right click while in the editor window and choose the add guide line option. Note that the guideline will always be placed on the column where your editing cursor is currently at, regardless of where you right click in the editor window.

enter image description here

To turn off go to options and find Productivity Power Tools and in that section turn off Column Guides. A reboot will be necessary.

enter image description here

SVN Error - Not a working copy

I just got "not a working copy", and for me the reason was the Automouter on Unix. Just a fresh "cd /path/to/work/directory" did the trick.

repaint() in Java

Simply write :

frame.validate();
frame.repaint();

That will do .

Regards

How to retrieve the last autoincremented ID from a SQLite table?

I've had issues with using SELECT last_insert_rowid() in a multithreaded environment. If another thread inserts into another table that has an autoinc, last_insert_rowid will return the autoinc value from the new table.

Here's where they state that in the doco:

If a separate thread performs a new INSERT on the same database connection while the sqlite3_last_insert_rowid() function is running and thus changes the last insert rowid, then the value returned by sqlite3_last_insert_rowid() is unpredictable and might not equal either the old or the new last insert rowid.

That's from sqlite.org doco

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

I got this message when I tried to git clone a repo that was not mine. The fix was to fork and then clone.

Extract month and year from a zoo::yearmon object

Use the format() method for objects of class "yearmon". Here is your example date (properly created!)

date1 <- as.yearmon("Mar 2012", "%b %Y")

Then we can extract the date parts as required:

> format(date1, "%b") ## Month, char, abbreviated
[1] "Mar"
> format(date1, "%Y") ## Year with century
[1] "2012"
> format(date1, "%m") ## numeric month
[1] "03"

These are returned as characters. Where appropriate, wrap in as.numeric() if you want the year or numeric month as a numeric variable, e.g.

> as.numeric(format(date1, "%m"))
[1] 3
> as.numeric(format(date1, "%Y"))
[1] 2012

See ?yearmon and ?strftime for details - the latter explains the placeholder characters you can use.

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I had this problem too and couldn't solve it without using VBA.

In my case I had a table with numbers that I wanted to be formatted and a corresponding table next to it with the desired formatting values.

i.e. While column F contains the values I want to format, the desired formatting for each cell is captured in column Z, expressed as "RED", "AMBER" or "GREEN."

Quick solution below. Manually select the range to which to apply the conditional formatting and then run the macro.

   Sub ConditionalFormatting()
For Each Cell In Selection.Cells
With Cell
    'clean
    .FormatConditions.Delete

    'green rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""GREEN"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .Color = -11489280
        .TintAndShade = 0
    End With
    .FormatConditions(1).StopIfTrue = False

    'amber rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""AMBER"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = -0.249946592608417
    End With
    .FormatConditions(1).StopIfTrue = False

    'red rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""RED"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .Color = -16776961
        .TintAndShade = 0
    End With
    .FormatConditions(1).StopIfTrue = False
End With

Next Cell

End Sub

Get DOM content of cross-domain iframe

If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.

Read the DOM with JavaScript in iframe and send it via postMessage to the top window.

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

Just right click on the ConstrainLayout and select the "convert view" and then "RelativeLayout":

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

You can automatically encode into Json, your complex entity with:

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new 
JsonEncoder()));
$json = $serializer->serialize($entity, 'json');

Add an object to an Array of a custom class

If you want to use an array, you have to keep a counter which contains the number of cars in the garage. Better use an ArrayList instead of array:

List<Car> garage = new ArrayList<Car>();
garage.add(redCar);

Swift UIView background color opacity

You can set background color of view to the UIColor with alpha, and not affect view.alpha:

view.backgroundColor = UIColor(white: 1, alpha: 0.5)

or

view.backgroundColor = UIColor.red.withAlphaComponent(0.5)

How to convert a GUID to a string in C#?

Here are examples of output from each of the format specifiers:

N: cd26ccf675d64521884f1693c62ed303
D: cd26ccf6-75d6-4521-884f-1693c62ed303
B: {cd26ccf6-75d6-4521-884f-1693c62ed303}
P: (cd26ccf6-75d6-4521-884f-1693c62ed303)
X: {0xcd26ccf6,0x75d6,0x4521,{0x88,0x4f,0x16,0x93,0xc6,0x2e,0xd3,0x03}}

The default is D.

Run this yourself.

How can I do an UPDATE statement with JOIN in SQL Server?

Simplified update query using JOIN-ing multiple tables.

   UPDATE
        first_table ft
        JOIN second_table st ON st.some_id = ft.some_id
        JOIN third_table tt  ON tt.some_id = st.some_id
        .....
    SET
        ft.some_column = some_value
    WHERE ft.some_column = 123456 AND st.some_column = 123456

Note - first_table, second_table, third_table and some_column like 123456 are demo table names, column names and ids. Replace them with the valid names.

difference between new String[]{} and new String[] in java

1.THE USE OF {}:

It initialize the array with the values { }

2.The difference between String array=new String[]; and String array=new String[]{};

String array=new String[]; and String array=new String[]{}; both are invalid statement in java.

It will gives you an error that you are trying to assign String array to String datatype. More specifically error is like this Type mismatch: cannot convert from String[] to String

3.String array=new String[10]{}; got error why?

Wrong because you are defining an array of length 10 ([10]), then defining an array of length String[10]{} 0

How do you use variables in a simple PostgreSQL script?

For the official CLI client "psql" see here. And "pgAdmin3" 1.10 (still in beta) has "pgScript".

Is it possible to cast a Stream in Java 8?

Late to the party, but I think it is a useful answer.

flatMap would be the shortest way to do it.

Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())

If o is a Client then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream<Client>.

How to check if type of a variable is string?

you can do:

var = 1
if type(var) == int:
   print('your variable is an integer')

or:

var2 = 'this is variable #2'
if type(var2) == str:
    print('your variable is a string')
else:
    print('your variable IS NOT a string')

hope this helps!

Best way to require all files from a directory in ruby?

Dir[File.join(__dir__, "/app/**/*.rb")].each do |file|
  require file
end

This will work recursively on your local machine and a remote (Like Heroku) which does not use relative paths.

How to get the current time in Python

The following is what I use to get the time without having to format. Some people don't like the split method, but it is useful here:

from time import ctime
print ctime().split()[3]

It will print in HH:MM:SS format.

SQL Server - find nth occurrence in a string

You can look for the four underscore in this way:

create table #test
( t varchar(50) );

insert into #test values 
( 'abc_1_2_3_4.gif'),
('zzz_12_3_3_45.gif');

declare @t varchar(50);
declare @t_aux varchar(50);
declare @t1 int;
declare @t2 int;
declare @t3 int;
declare @t4 int;

DECLARE t_cursor CURSOR
    FOR SELECT t FROM #test
OPEN t_cursor
FETCH NEXT FROM t_cursor into @t;?
set @t1 = charindex( '_', @t )
set @t2 = charindex( '_', @t , @t1+1)
set @t3 = charindex( '_', @t , @t2+1)
set @t4 = charindex( '_', @t , @t3+1)

select @t1, @t2, t3, t4

--do a loop to iterate over all table

you can test it here.

Or in this simple way:

select 
  charindex( '_', t ) as first,
  charindex( '_', t, charindex( '_', t ) + 1 ) as second,
  ...
from 
  #test

How do I call a JavaScript function on page load?

You have to call the function you want to be called on load (i.e., load of the document/page). For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.

Try the code below:

<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {
        yourFunction();
    });
    function yourFunction(){
      //some code
    }
</script>

How to check if there exists a process with a given pid in Python?

Combining Giampaolo Rodolà's answer for POSIX and mine for Windows I got this:

import os
if os.name == 'posix':
    def pid_exists(pid):
        """Check whether pid exists in the current process table."""
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
else:
    def pid_exists(pid):
        import ctypes
        kernel32 = ctypes.windll.kernel32
        SYNCHRONIZE = 0x100000

        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if process != 0:
            kernel32.CloseHandle(process)
            return True
        else:
            return False

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null.

Given your statement:

img1.ImageUrl = ConfigurationManager
                    .AppSettings
                    .Get("Url")
                    .Replace("###", randomString) 
                + Server.UrlEncode(
                      ((System.Web.UI.MobileControls.Form)Page
                      .FindControl("mobileForm"))
                      .Title);

I'm guessing either the call to AppSettings.Get("Url") is returning null because the value isn't found or the call to Page.FindControl("mobileForm") is returning null because the control isn't found.

You could easily break this out into multiple statements to solve the problem:

var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
                            as System.Web.UI.MobileControls.Form;

if(configUrl != null && mobileFormControl != null)
{
    img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}

How to compare two JSON have the same properties without order?

This code will verify the json independently of param object order.

_x000D_
_x000D_
var isEqualsJson = (obj1,obj2)=>{
    keys1 = Object.keys(obj1);
    keys2 = Object.keys(obj2);

    //return true when the two json has same length and all the properties has same value key by key
    return keys1.length === keys2.length && Object.keys(obj1).every(key=>obj1[key]==obj2[key]);
}

var obj1 = {a:1,b:2,c:3};
var obj2 = {a:1,b:2,c:3}; 

console.log("json is equals: "+ isEqualsJson(obj1,obj2));
alert("json is equals: "+ isEqualsJson(obj1,obj2));
_x000D_
_x000D_
_x000D_

Rename a table in MySQL

According to mysql docs: "to rename TEMPORARY tables, RENAME TABLE does not work. Use ALTER TABLE instead."

So this is the most portable method:

ALTER TABLE `old_name` RENAME `new_name`;

How can I convert ArrayList<Object> to ArrayList<String>?

With Java Generics Takes a list of X and returns a list of T that extends or implements X, Sweet!

    // the cast is is actually checked via the method API
@SuppressWarnings("unchecked")
public static <T extends X, X> ArrayList<T> convertToClazz(ArrayList<X> from, Class<X> inClazz, Class<T> outClazz) {
    ArrayList<T> to = new ArrayList<T>();
    for (X data : from) {
        to.add((T) data);
    }
    return to;
}

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

Adding a view controller as a subview in another view controller

This code will work for Swift 4.2.

let controller:SecondViewController = 
self.storyboard!.instantiateViewController(withIdentifier: "secondViewController") as! 
SecondViewController
controller.view.frame = self.view.bounds;
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)

Angular 2 change event - model changes

That's a known issue. Currently you have to use a workaround like shown in your question.

This is working as intended. When the change event is emitted ngModelChange (the (...) part of [(ngModel)] hasn't updated the bound model yet:

<input type="checkbox"  (ngModelChange)="myModel=$event" [ngModel]="mymodel">

See also

How to find the serial port number on Mac OS X?

Try this: ioreg -p IOUSB -l -b | grep -E "@|PortNum|USB Serial Number"

System.BadImageFormatException An attempt was made to load a program with an incorrect format

I was having problems with a new install of VS with an x64 project - for Visual Studio 2013, Visual Studio 2015 and Visual Studio 2017:

Tools
  -> Options
   -> Projects and Solutions
    -> Web Projects
     -> Check "Use the 64 bit version of IIS Express for web sites and projects"

Laravel Redirect Back with() Message

Laravel 5.8

Controller

return back()->with('error', 'Incorrect username or password.');

Blade

  @if (Session::has('error'))
       <div class="alert alert-warning" role="alert">
           {{Session::get('error')}}
       </div>
  @endif

jquery onclick change css background image

You need to use background-image instead of backgroundImage. For example:

$(function() {
  $('.home').click(function() {
    $(this).css('background-image', 'url(images/tabs3.png)');
  });
}):

PHP array printing using a loop

If you're debugging something and just want to see what's in there for your the print_f function formats the output nicely.

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

Saty described the differences between them. For your practice, you can use datetime in order to keep the output of NOW().

For example:

CREATE TABLE Orders
(
  OrderId int NOT NULL,
  ProductName varchar(50) NOT NULL,
  OrderDate datetime NOT NULL DEFAULT NOW(),
  PRIMARY KEY (OrderId)
)

You can read more at w3schools.

Scrolling a div with jQuery

I was looking for this same answer and I couldn't find anything that did exactly what I wanted so I created my own and posted it here:

http://seekieran.com/2011/03/jquery-scrolling-box/

Working Demo: http://jsbin.com/azoji3

Here is the important code:

function ScrollDown(){

  //var topVal = $('.up').parents(".container").find(".content").css("top").replace(/[^-\d\.]/g, '');
  var topVal = $(".content").css("top").replace(/[^-\d\.]/g, '');
    topVal = parseInt(topVal);
  console.log($(".content").height()+ " " + topVal);
  if(Math.abs(topVal) < ($(".content").height() - $(".container").height() + 60)){ //This is to limit the bottom of the scrolling - add extra to compensate for issues
  $('.up').parents(".container").find(".content").stop().animate({"top":topVal - 20  + 'px'},'slow');
    if (mouseisdown)
setTimeout(ScrollDown, 400);
  }

Recursion to make it happen:

 $('.dn').mousedown(function(event) {
    mouseisdown = true;
    ScrollDown();
}).mouseup(function(event) {
    mouseisdown = false;
});

Thanks to Jonathan Sampson for some code to start but it didn't work initially so I have heavily modified it. Any suggestions to improve it would be great here in either the comments or comments on the blog.

Convert string date to timestamp in Python

A lot of these answers don't bother to consider that the date is naive to begin with

To be correct, you need to make the naive date a timezone aware datetime first

import datetime
import pytz
# naive datetime
d = datetime.datetime.strptime('01/12/2011', '%d/%m/%Y')
>>> datetime.datetime(2011, 12, 1, 0, 0)

# add proper timezone
pst = pytz.timezone('America/Los_Angeles')
d = pst.localize(d)
>>> datetime.datetime(2011, 12, 1, 0, 0,
tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)

# convert to UTC timezone
utc = pytz.UTC
d = d.astimezone(utc)
>>> datetime.datetime(2011, 12, 1, 8, 0, tzinfo=<UTC>)

# epoch is the beginning of time in the UTC timestamp world
epoch = datetime.datetime(1970,1,1,0,0,0,tzinfo=pytz.UTC)
>>> datetime.datetime(1970, 1, 1, 0, 0, tzinfo=<UTC>)

# get the total second difference
ts = (d - epoch).total_seconds()
>>> 1322726400.0

Also:

Be careful, using pytz for tzinfo in a datetime.datetime DOESN'T WORK for many timezones. See datetime with pytz timezone. Different offset depending on how tzinfo is set

# Don't do this:
d = datetime.datetime(2011, 12, 1,0,0,0, tzinfo=pytz.timezone('America/Los_Angeles'))
>>> datetime.datetime(2011, 1, 12, 0, 0, 
tzinfo=<DstTzInfo 'America/Los_Angeles' LMT-1 day, 16:07:00 STD>)
# tzinfo in not PST but LMT here, with a 7min offset !!!

# when converting to UTC:
d = d.astimezone(pytz.UTC)
>>> datetime.datetime(2011, 1, 12, 7, 53, tzinfo=<UTC>)
# you end up with an offset

https://en.wikipedia.org/wiki/Local_mean_time

If Cell Starts with Text String... Formula

As of Excel 2019 you could do this. The "Error" at the end is the default.

SWITCH(LEFT(A1,1), "A", "Pick Up", "B", "Collect", "C", "Prepaid", "Error")

Microsoft Excel Switch Documentation

Laravel 5 route not defined, while it is?

The route() method, which is called when you do ['route' => 'someroute'] in a form opening, wants what's called a named route. You give a route a name like this:

Route::patch('/preferences/{id}',[
    'as' => 'user.preferences.update',
    'uses' => 'UserController@update'
]);

That is, you make the second argument of the route into an array, where you specify both the route name (the as), and also what to do when the route is hit (the uses).

Then, when you open the form, you call the route:

{!! Form::model(Auth::user(), [
    'method' => 'PATCH',
    'route' => ['user.preferences.update', Auth::user()->id]
]) !!}

Now, for a route without parameters, you could just do 'route' => 'routename', but since you have a parameter, you make an array instead and supply the parameters in order.

All that said, since you appear to be updating the current user's preferences, I would advise you to let the handling controller check the id of the currently logged-in user, and base the updating on that - there's no need to send in the id in the url and the route unless your users should need to update the preferences of other users as well. :)

How can I parse a string with a comma thousand separator to a number?

On modern browsers you can use the built in Intl.NumberFormat to detect the browser's number formatting and normalize the input to match.

_x000D_
_x000D_
function parseNumber(value, locales = navigator.languages) {
  const example = Intl.NumberFormat(locales).format('1.1');
  const cleanPattern = new RegExp(`[^-+0-9${ example.charAt( 1 ) }]`, 'g');
  const cleaned = value.replace(cleanPattern, '');
  const normalized = cleaned.replace(example.charAt(1), '.');

  return parseFloat(normalized);
}

const corpus = {
  '1.123': {
    expected: 1.123,
    locale: 'en-US'
  },
  '1,123': {
    expected: 1123,
    locale: 'en-US'
  },
  '2.123': {
    expected: 2123,
    locale: 'fr-FR'
  },
  '2,123': {
    expected: 2.123,
    locale: 'fr-FR'
  },
}


for (const candidate in corpus) {
  const {
    locale,
    expected
  } = corpus[candidate];
  const parsed = parseNumber(candidate, locale);

  console.log(`${ candidate } in ${ corpus[ candidate ].locale } == ${ expected }? ${ parsed === expected }`);
}
_x000D_
_x000D_
_x000D_

Their's obviously room for some optimization and caching but this works reliably in all languages.

How to create a cron job using Bash automatically without the interactive editor?

script function to add cronjobs. check duplicate entries,useable expressions * > "

cronjob_creator () {         
# usage: cronjob_creator '<interval>' '<command>'

  if [[ -z $1 ]] ;then
    printf " no interval specified\n"
elif [[ -z $2 ]] ;then
    printf " no command specified\n"
else
    CRONIN="/tmp/cti_tmp"
    crontab -l | grep -vw "$1 $2" > "$CRONIN"
    echo "$1 $2" >> $CRONIN
    crontab "$CRONIN"
    rm $CRONIN
fi
}

tested :

$ ./cronjob_creator.sh '*/10 * * * *' 'echo "this is a test" > export_file'
$ crontab  -l
$ */10 * * * * echo "this is a test" > export_file

source : my brain ;)

Best Java obfuscator?

First, you really need to keep in mind that it's never impossible to reverse-engineer something. Everything is hackable. A smart developer using a smart IDE can already get far enough.

Well, you can find here a list. ProGuard is pretty good. I've used it myself, but only to "minify" Java code.

This action could not be completed. Try Again (-22421)

For Xcode 8.3.2

i have resolved same issue

"This action could not be completed. Try Again (-22421)"

using following steps...

  1. Quit your xcode (if open)
  2. in Application Folder, Xcode 8.3.2 -->Show Package Contents -->Contents -->Application -->Application Loader (Show package contents) -->Contents -->itms -->bin -->iTMSTransporter (right click and Open with Terminal, it will auto start updating...) after updating open your project, rebuild your archive and upload it again..

For Xcode 9

issue

”This action could not be completed. Try Again (-22421)”

has been Resolved in Xcode 9. Now, we can upload app through Xcode Organizer also.

https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW876

What does <value optimized out> mean in gdb?

From https://idlebox.net/2010/apidocs/gdb-7.0.zip/gdb_9.html

The values of arguments that were not saved in their stack frames are shown as `value optimized out'.

Im guessing you compiled with -O(somevalue) and are accessing variables a,b,c in a function where optimization has occurred.

Mean Squared Error in Numpy?

Just for kicks

mse = (np.linalg.norm(A-B)**2)/len(A)

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

From Twitter Bootstrap documentation:

  • small grid (= 768px) = .col-sm-*,
  • medium grid (= 992px) = .col-md-*,
  • large grid (= 1200px) = .col-lg-*.

PHP's array_map including keys

This is probably the shortest and easiest to reason about:

$states = array('az' => 'Arizona', 'al' => 'Alabama');

array_map(function ($short, $long) {
    return array(
        'short' => $short,
        'long'  => $long
    );
}, array_keys($states), $states);

// produces:
array(
     array('short' => 'az', 'long' => 'Arizona'), 
     array('short' => 'al', 'long' => 'Alabama')
)

Check if a key is down?

The following code is what I'm using:

var altKeyDownCount = 0;
window.onkeydown = function (e) {
    if (!e) e = window.event;
    if (e.altKey) {
        altKeyDownCount++;
        if (30 < altKeyDownCount) {
            $('.key').removeClass('hidden');
            altKeyDownCount = 0;
        }
        return false;
    }
}

window.onkeyup = function (e) {
    if (!e) e = window.event;
    altKeyDownCount = 0;
    $('.key').addClass('hidden');
}

When the user keeps holding down the Alt key for some time (about 2 seconds), a group of labels (class='key hidden') appears. When the Alt key is released, the labels disappear. jQuery and Bootstrap are both used.

How can I clear the SQL Server query cache?

Eight different ways to clear the plan cache

1. Remove all elements from the plan cache for the entire instance

DBCC FREEPROCCACHE;

Use this to clear the plan cache carefully. Freeing the plan cache causes, for example, a stored procedure to be recompiled instead of reused from the cache. This can cause a sudden, temporary decrease in query performance.

2. Flush the plan cache for the entire instance and suppress the regular completion message

"DBCC execution completed. If DBCC printed error messages, contact your system administrator."

DBCC FREEPROCCACHE WITH NO_INFOMSGS;

3. Flush the ad hoc and prepared plan cache for the entire instance

DBCC FREESYSTEMCACHE ('SQL Plans');

4. Flush the ad hoc and prepared plan cache for one resource pool

DBCC FREESYSTEMCACHE ('SQL Plans', 'LimitedIOPool');

5. Flush the entire plan cache for one resource pool

DBCC FREEPROCCACHE ('LimitedIOPool');

6. Remove all elements from the plan cache for one database (does not work in SQL Azure)

-- Get DBID from one database name first
DECLARE @intDBID INT;
SET @intDBID = (SELECT [dbid] 
                FROM master.dbo.sysdatabases 
                WHERE name = N'AdventureWorks2014');

DBCC FLUSHPROCINDB (@intDBID);

7. Clear plan cache for the current database

USE AdventureWorks2014;
GO
-- New in SQL Server 2016 and SQL Azure
ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;

8. Remove one query plan from the cache

USE AdventureWorks2014;
GO

-- Run a stored procedure or query
EXEC dbo.uspGetEmployeeManagers 9;

-- Find the plan handle for that query 
-- OPTION (RECOMPILE) keeps this query from going into the plan cache
SELECT cp.plan_handle, cp.objtype, cp.usecounts, 
DB_NAME(st.dbid) AS [DatabaseName]
FROM sys.dm_exec_cached_plans AS cp CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st 
WHERE OBJECT_NAME (st.objectid)
LIKE N'%uspGetEmployeeManagers%' OPTION (RECOMPILE); 

-- Remove the specific query plan from the cache using the plan handle from the above query 
DBCC FREEPROCCACHE (0x050011007A2CC30E204991F30200000001000000000000000000000000000000000000000000000000000000);
 

Source 1 2 3

What is the difference between a static and a non-static initialization code block

The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.

android - save image into gallery

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

CSS /JS to prevent dragging of ghost image?

You can use "Empty Img Element".
Empty Img Element - document.createElement("img")

[HTML Code]
<div id="hello" draggable="true">Drag!!!</div>
[JavaScript Code]
var block = document.querySelector('#hello');
block.addEventListener('dragstart', function(e){
    var img = document.createElement("img");
    e.dataTransfer.setDragImage(img, 0, 0);
})

What does the "static" modifier after "import" mean?

Very good exaple. npt tipical with MAth in wwww....

https://www.java2novice.com/java-fundamentals/static-import/

public class MyStaticMembClass {
 
    public static final int INCREMENT = 2;
     
    public static int incrementNumber(int number){
        return number+INCREMENT;
    }
}

in onother file inlude

import static com.java2novice.stat.imp.pac1.MyStaticMembClass.*;

JavaScript check if value is only undefined, null or false

Another solution:

Based on the document, Boolean object will return true if the value is not 0, undefined, null, etc. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

So

if(Boolean(val))
{
//executable...
}

Find all elements on a page whose element ID contains a certain text using jQuery

This selects all DIVs with an ID containing 'foo' and that are visible

$("div:visible[id*='foo']");

Google Drive as FTP Server

With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.

You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/

Shall we always use [unowned self] inside closure in Swift

There are some great answers here. But recent changes to how Swift implements weak references should change everyone's weak self vs. unowned self usage decisions. Previously, if you needed the best performance using unowned self was superior to weak self, as long as you could be certain that self would never be nil, because accessing unowned self is much faster than accessing weak self.

But Mike Ash has documented how Swift has updated the implementation of weak vars to use side-tables and how this substantially improves weak self performance.

https://mikeash.com/pyblog/friday-qa-2017-09-22-swift-4-weak-references.html

Now that there isn't a significant performance penalty to weak self, I believe we should default to using it going forward. The benefit of weak self is that it's an optional, which makes it far easier to write more correct code, it's basically the reason Swift is such a great language. You may think you know which situations are safe for the use of unowned self, but my experience reviewing lots of other developers code is, most don't. I've fixed lots of crashes where unowned self was deallocated, usually in situations where a background thread completes after a controller is deallocated.

Bugs and crashes are the most time-consuming, painful and expensive parts of programming. Do your best to write correct code and avoid them. I recommend making it a rule to never force unwrap optionals and never use unowned self instead of weak self. You won't lose anything missing the times force unwrapping and unowned self actually are safe. But you'll gain a lot from eliminating hard to find and debug crashes and bugs.

How to pass arguments and redirect stdin from a file to program run in gdb?

If you want to have bare run command in gdb to execute your program with redirections and arguments, you can use set args:

% gdb ./a.out
(gdb) set args arg1 arg2 <file
(gdb) run

I was unable to achieve the same behaviour with --args parameter, gdb fiercely escapes the redirections, i.e.

% gdb --args echo 1 2 "<file"
(gdb) show args
Argument list to give program being debugged when it is started is "1 2 \<file".
(gdb) run
...
1 2 <file
...

This one actually redirects the input of gdb itself, not what we really want here

% gdb --args echo 1 2 <file
zsh: no such file or directory: file

Handling data in a PHP JSON Object

You mean something like this?

<?php

$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

foreach ( $json_output->trends as $trend )
{
    echo "{$trend->name}\n";
}

CSS hover vs. JavaScript mouseover

EDIT: This answer no longer holds true. CSS is well supportedand Javascript (read: JScript) is now pretty much required for any web experience, and few folks disable javascript.

The original answer, as my opinion in 2009.

Off the top of my head:

With CSS, you may have issues with browser support.

With JScript, people can disable jscript (thats what I do).

I believe the preferred method is to do content in HTML, Layout with CSS, and anything dynamic in JScript. So in this instance, you would probably want to take the CSS approach.

How to implement a binary search tree in Python?

Here is a compact, object oriented, recursive implementation:

    class BTreeNode(object):
        def __init__(self, data):
            self.data = data
            self.rChild = None
            self.lChild = None

    def __str__(self):
        return (self.lChild.__str__() + '<-' if self.lChild != None else '') + self.data.__str__() + ('->' + self.rChild.__str__() if self.rChild != None else '')

    def insert(self, btreeNode):
        if self.data > btreeNode.data: #insert left
            if self.lChild == None:
                self.lChild = btreeNode
            else:
                self.lChild.insert(btreeNode)
        else: #insert right
            if self.rChild == None:
                self.rChild = btreeNode
            else:
                self.rChild.insert(btreeNode)


def main():
    btreeRoot = BTreeNode(5)
    print 'inserted %s:' %5, btreeRoot

    btreeRoot.insert(BTreeNode(7))
    print 'inserted %s:' %7, btreeRoot

    btreeRoot.insert(BTreeNode(3))
    print 'inserted %s:' %3, btreeRoot

    btreeRoot.insert(BTreeNode(1))
    print 'inserted %s:' %1, btreeRoot

    btreeRoot.insert(BTreeNode(2))
    print 'inserted %s:' %2, btreeRoot

    btreeRoot.insert(BTreeNode(4))
    print 'inserted %s:' %4, btreeRoot

    btreeRoot.insert(BTreeNode(6))
    print 'inserted %s:' %6, btreeRoot

The output of the above main() is:

inserted 5: 5
inserted 7: 5->7
inserted 3: 3<-5->7
inserted 1: 1<-3<-5->7
inserted 2: 1->2<-3<-5->7
inserted 4: 1->2<-3->4<-5->7
inserted 6: 1->2<-3->4<-5->6<-7

When saving, how can you check if a field has changed?

The optimal solution is probably one that does not include an additional database read operation prior to saving the model instance, nor any further django-library. This is why laffuste's solutions is preferable. In the context of an admin site, one can simply override the save_model-method, and invoke the form's has_changed method there, just as in Sion's answer above. You arrive at something like this, drawing on Sion's example setting but using changed_data to get every possible change:

class ModelAdmin(admin.ModelAdmin):
   fields=['name','mode']
   def save_model(self, request, obj, form, change):
     form.changed_data #output could be ['name']
     #do somethin the changed name value...
     #call the super method
     super(self,ModelAdmin).save_model(request, obj, form, change)
  • Override save_model:

https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model

  • Built-in changed_data-method for a Field:

https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.changed_data

Using a batch to copy from network drive to C: or D: drive

You are copying all files to a single file called TEST_BACKUP_FOLDER

try this:

md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER

Python-Requests close http connection

As discussed here, there really isn't such a thing as an HTTP connection and what httplib refers to as the HTTPConnection is really the underlying TCP connection which doesn't really know much about your requests at all. Requests abstracts that away and you won't ever see it.

The newest version of Requests does in fact keep the TCP connection alive after your request.. If you do want your TCP connections to close, you can just configure the requests to not use keep-alive.

s = requests.session()
s.config['keep_alive'] = False

How to Find Item in Dictionary Collection?

Sometimes you still need to use FirstOrDefault if you have to do different tests. If the Key component of your dictionnary is nullable, you can do this:

thisTag = _tags.FirstOrDefault(t => t.Key.SubString(1,1) == 'a');
if(thisTag.Key != null) { ... }

Using FirstOrDefault, the returned KeyValuePair's key and value will both be null if no match is found.

Remove Android App Title Bar

for Title Bar

requestWindowFeature(Window.FEATURE_NO_TITLE);

for fullscreen

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

Place this after

super.onCreate(savedInstanceState);

but before

setContentView(R.layout.xml);

This worked for me.try this

typesafe select onChange event using reactjs and typescript

In my case onChange event was typed as React.ChangeEvent:

onChange={ (e: React.ChangeEvent<HTMLSelectElement>) => {
           console.warn('onChange TextInput value: ' + e.target.value);
           } 
         }

Removing double quotes from a string in Java

You can just go for String replace method.-

line1 = line1.replace("\"", "");

Typing the Enter/Return key using Python and Selenium

For Selenium Remote Control with Java:

selenium.keyPress("elementID", "\13");

For Selenium WebDriver (a.k.a. Selenium 2) with Java:

driver.findElement(By.id("elementID")).sendKeys(Keys.ENTER);

Or,

driver.findElement(By.id("elementID")).sendKeys(Keys.RETURN);

Another way to press Enter in WebDriver is by using the Actions class:

Actions action = new Actions(driver);
action.sendKeys(driver.findElement(By.id("elementID")), Keys.ENTER).build().perform();

How to download Javadoc to read offline?

You can use something called Dash: Offline API Documentation for Mac. For Windows and Linux you have an alternative called Zeal.

Both of them are very similar. And you can get offline documentation for most of the APIs out there like Java, android, Angular, HTML5 etc .. almost everything.

I have also written a post on How to install Zeal on Ubuntu 14.04

Django: Redirect to previous page after login

You can also do this

<input type="hidden" name="text" value="{% url 'dashboard' %}" />

Passing data between controllers in Angular JS?

Solution without creating Service, using $rootScope:

To share properties across app Controllers you can use Angular $rootScope. This is another option to share data, putting it so that people know about it.

The preferred way to share some functionality across Controllers is Services, to read or change a global property you can use $rootscope.

var app = angular.module('mymodule',[]);
app.controller('Ctrl1', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = true;
}]);

app.controller('Ctrl2', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = false;
}]);

Using $rootScope in a template (Access properties with $root):

<div ng-controller="Ctrl1">
    <div class="banner" ng-show="$root.showBanner"> </div>
</div>

Append an empty row in dataframe using pandas

Assuming your df.index is sorted you can use:

df.loc[df.index.max() + 1] = None

It handles well different indexes and column types.

[EDIT] it works with pd.DatetimeIndex if there is a constant frequency, otherwise we must specify the new index exactly e.g:

df.loc[df.index.max() + pd.Timedelta(milliseconds=1)] = None

long example:

df = pd.DataFrame([[pd.Timestamp(12432423), 23, 'text_field']], 
                    columns=["timestamp", "speed", "text"],
                    index=pd.DatetimeIndex(start='2111-11-11',freq='ms', periods=1))
df.info()

<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 1 entries, 2111-11-11 to 2111-11-11 Freq: L Data columns (total 3 columns): timestamp 1 non-null datetime64[ns] speed 1 non-null int64 text 1 non-null object dtypes: datetime64[ns](1), int64(1), object(1) memory usage: 32.0+ bytes

df.loc[df.index.max() + 1] = None
df.info()

<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 2 entries, 2111-11-11 00:00:00 to 2111-11-11 00:00:00.001000 Data columns (total 3 columns): timestamp 1 non-null datetime64[ns] speed 1 non-null float64 text 1 non-null object dtypes: datetime64[ns](1), float64(1), object(1) memory usage: 64.0+ bytes

df.head()

                            timestamp                   speed      text
2111-11-11 00:00:00.000 1970-01-01 00:00:00.012432423   23.0    text_field
2111-11-11 00:00:00.001 NaT NaN NaN

How to catch exception output from Python subprocess.check_output()?

This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):

from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
    cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
    print(e.output.decode()) # print out the stdout messages up to the exception
    print(e) # To print out the exception message

Converting Varchar Value to Integer/Decimal Value in SQL Server

Table structure...very basic:

create table tabla(ID int, Stuff varchar (50));

insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');

Query:

SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla

Or, try this:

SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla

Working on SQLServer 2008

Datatables: Cannot read property 'mData' of undefined

Having <thead> and <tbody> with the same numbers of <th> and <td> solved my problem.

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

Since you are copying tha same data to all rows, you don't actually need to loop at all. Try this:

Sub ARRAYER()
    Dim Number_of_Sims As Long
    Dim rng As Range

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Number_of_Sims = 100000

    Set rng = Range("C4:G4")
    rng.Offset(1, 0).Resize(Number_of_Sims) = rng.Value

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

This thread is a bit older but here something I just came across:

Try this code:

$date = new DateTime();
$arr = ['date' => $date];

echo $date->format('Ymd') . '<br>';
mytest($arr);
echo $date->format('Ymd') . '<br>';

function mytest($params = []) {
    if (isset($params['date'])) {
        $params['date']->add(new DateInterval('P1D'));
    }
}

http://codepad.viper-7.com/gwPYMw

Note there is no amp for the $params parameter and still it changes the value of $arr['date']. This doesn't really match with all the other explanations here and what I thought until now.

If I clone the $params['date'] object, the 2nd outputted date stays the same. If I just set it to a string it doesn't effect the output either.

How to unnest a nested list

the first case can also be easily done as:

A=A[0]

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

Handling MySQL datetimes and timestamps in Java

BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.

Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.

When writing datetime value to sql db

    //Convert the time into UTC and build Timestamp object.
    Timestamp ts = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")));
    //use setTimestamp on preparedstatement
    preparedStatement.setTimestamp(1, ts);

When reading the value back from DB into java,

  1. Read it as it is in java.sql.Timestamp type.
  2. Decorate the DateTime value as time in UTC timezone using atZone method in LocalDateTime class.
  3. Then, change it to your desired timezone. Here I am changing it to Toronto timezone.

    ResultSet resultSet = preparedStatement.executeQuery();
    resultSet.next();
    Timestamp timestamp = resultSet.getTimestamp(1);
    ZonedDateTime timeInUTC = timestamp.toLocalDateTime().atZone(ZoneId.of("UTC"));
    LocalDateTime timeInToronto = LocalDateTime.ofInstant(timeInUTC.toInstant(), ZoneId.of("America/Toronto"));
    

Root password inside a Docker container

You can SSH in to docker container as root by using

docker exec -it --user root <container_id> /bin/bash

Then change root password using this

passwd root

Make sure sudo is installed check by entering

sudo

if it is not installed install it

apt-get install sudo

If you want to give sudo permissions for user dev you can add user dev to sudo group

usermod -aG sudo dev

Now you'll be able to run sudo level commands from your dev user while inside the container or else you can switch to root inside the container by using the password you set earlier.

To test it login as user dev and list the contents of root directory which is normally only accessible to the root user.

sudo ls -la /root

Enter password for dev

If your user is in the proper group and you entered the password correctly, the command that you issued with sudo should run with root privileges.

How to exclude records with certain values in sql select

SELECT  DISTINCT a.StoreID
FROM    tableName a
        LEFT JOIN tableName b 
          ON a.StoreID = b.StoreID AND b.ClientID = 5
WHERE   b.StoreID IS NULL

OUTPUT

+---------+
¦ STOREID ¦
¦---------¦
¦       3 ¦
+---------+

passing JSON data to a Spring MVC controller

You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.

In the Controller, you can use the javax.json to convert and manipulate this.

Download and add the .jar to the project libs and import the JsonObject.

To create an json object, you can use

JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();

To read it from String, you can use

JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

Best timing method in C?

gettimeofday will return time accurate to microseconds within the resolution of the system clock. You might also want to check out the High Res Timers project on SourceForge.

How to convert seconds to time format?

Sorry this is too late but maybe useful

function mediaTimeDeFormater($seconds)
{
    if (!is_numeric($seconds))
        throw new Exception("Invalid Parameter Type!");


    $ret = "";

    $hours = (string )floor($seconds / 3600);
    $secs = (string )$seconds % 60;
    $mins = (string )floor(($seconds - ($hours * 3600)) / 60);

    if (strlen($hours) == 1)
        $hours = "0" . $hours;
    if (strlen($secs) == 1)
        $secs = "0" . $secs;
    if (strlen($mins) == 1)
        $mins = "0" . $mins;

    if ($hours == 0)
        $ret = "$mins:$secs";
    else
        $ret = "$hours:$mins:$secs";

    return $ret;
}

echo mediaTimeDeFormater(216.064000);//3:36

SQL Server: Get data for only the past year

I, like @D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. @samjudson's answer provides that. @D.E. White's answer returns results for the prior calendar year.

My query is a bit different in that it works for the prior year up to and including the current date:

SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))

For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017

Spring Resttemplate exception handling

Another solution is the one described here at the end of this post by "enlian": http://springinpractice.com/2013/10/07/handling-json-error-object-responses-with-springs-resttemplate

try{
     restTemplate.exchange(...)
} catch(HttpStatusCodeException e){
     String errorpayload = e.getResponseBodyAsString();
     //do whatever you want
} catch(RestClientException e){
     //no response payload, tell the user sth else 
}

m2e lifecycle-mapping not found

I have opened a (trivial) bug for this at m2e. Vote for it if you want the warning message to be gone for good...

https://bugs.eclipse.org/bugs/show_bug.cgi?id=367870

how to use python2.7 pip instead of default pip

as noted here, this is what worked best for me:

sudo apt-get install python3 python3-pip python3-setuptools

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file = input.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {
            console.log(line);
        });
    };

    reader.onerror = (event) => {
        alert(event.target.error.name);
    };

    reader.readAsText(file);
}

How can I directly view blobs in MySQL Workbench

Perform three steps:

  1. Go to "WorkBench Preferences" --> Choose "SQL Editor" Under "Query Results": check "Treat BINARY/VARBINARY as nonbinary character string"

  2. Restart MySQL WorkBench.

  3. Now select SELECT SUBSTRING(BLOB<COLUMN_NAME>,1,2500) FROM <Table_name>;

Can you require two form fields to match with HTML5?

You can with regular expressions Input Patterns (check browser compatibility)

<input id="password" name="password" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 6 characters' : ''); if(this.checkValidity()) form.password_two.pattern = this.value;" placeholder="Password" required>

<input id="password_two" name="password_two" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Verify Password" required>

Convert Little Endian to Big Endian

Below is an other approach that was useful for me

convertLittleEndianByteArrayToBigEndianByteArray (byte littlendianByte[], byte bigEndianByte[], int ArraySize){
    int i =0;

    for(i =0;i<ArraySize;i++){
      bigEndianByte[i] = (littlendianByte[ArraySize-i-1] << 7 & 0x80) | (littlendianByte[ArraySize-i-1] << 5 & 0x40) |
                            (littlendianByte[ArraySize-i-1] << 3 & 0x20) | (littlendianByte[ArraySize-i-1] << 1 & 0x10) |
                            (littlendianByte[ArraySize-i-1] >>1 & 0x08) | (littlendianByte[ArraySize-i-1] >> 3 & 0x04) |
                            (littlendianByte[ArraySize-i-1] >>5 & 0x02) | (littlendianByte[ArraySize-i-1] >> 7 & 0x01) ;
    }
}

How do I catch a numpy warning like it's an exception (not just for testing)?

To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings('error')
    try:
        answer = 1 / 0
    except Warning as e:
        print('error found:', e)

You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.

How to get input text length and validate user in javascript

JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.

var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
    //red
    textBox.style.backgroundColor = "#FF0000";
}
else
{
    //green
    textBox.style.backgroundColor = "#00FF00";
}

How to make a promise from setTimeout

const setTimeoutAsync = (cb, delay) =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(cb());
    }, delay);
  });

We can pass custom 'cb fxn' like this one

Cannot access wamp server on local network

I know this is an old post BUT I have been having problems getting WAMP server seen on my windows 7 pro network for days, tried all of the solutions offered (including changing windows system files) but still not working. finally in pure desperation I put everything on the system back as it was and installed WAMP Server on a different drive (E:\WAMP ) in my case. The result was it worked perfectly first time with no editing configs or messing with the system. Other users may wish to try this before reaching the 'tear your hair out stage', it certainly saved my sanity or what I have left of it I hope this helps someone Dave

How to copy std::string into std::vector<char>?

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

Execute an action when an item on the combobox is selected

Not an answer to the original question, but an example to the how-to-make-reusable and working custom renderers without breaking MVC :-)

// WRONG
public class DataWrapper {
   final Data data;
   final String description;
   public DataWrapper(Object data, String description) {
       this.data = data;
       this.description = description;
   }
   ....
   @Override
   public String toString() {
       return description;
   } 
}
// usage
myModel.add(new DataWrapper(data1, data1.getName());

It is wrong in a MVC environment, because it is mixing data and view: now the model doesn't contain the data but a wrapper which is introduced for view reasons. That's breaking separation of concerns and encapsulation (every class interacting with the model needs to be aware of the wrapped data).

The driving forces for breaking of rules were:

  • keep functionality of the default KeySelectionManager (which is broken by a custom renderer)
  • reuse of the wrapper class (can be applied to any data type)

As in Swing a custom renderer is the small coin designed to accomodate for custom visual representation, a default manager which can't cope is ... broken. Tweaking design just to accommodate for such a crappy default is the wrong way round, kind of upside-down. The correct is, to implement a coping manager.

While re-use is fine, doing so at the price of breaking the basic architecture is not a good bargin.

We have a problem in the presentation realm, let's solve it in the presentation realm with the elements designed to solve exactly that problem. As you might have guessed, SwingX already has such a solution :-)

In SwingX, the provider of a string representation is called StringValue, and all default renderers take such a StringValue to configure themselves:

StringValue sv = new StringValue() {
     @Override
     public String getString(Object value) {
        if (value instanceof Data) {
            return ((Data) value).getSomeProperty();
        }
        return TO_STRING.getString(value);
     }
};
DefaultListRenderer renderer = new DefaultListRenderer(sv);

As the defaultRenderer is-a StringValue (implemented to delegate to the given), a well-behaved implementation of KeySelectionManager now can delegate to the renderer to find the appropriate item:

public BetterKeySelectionManager implements KeySelectionManager {

     @Override
     public int selectionForKey(char ch, ComboBoxModel model) {

         ....
         if (getCellRenderer() instance of StringValue) {
              String text = ((StringValue) getCellRenderer()).getString(model.getElementAt(row));
              ....
         } 
     }

}

Outlined the approach because it is easily implementable even without using SwingX, simply define implement something similar and use it:

  • some provider of a string representation
  • a custom renderer which is configurable by that provider and guarantees to use it in configuring itself
  • a well-behaved keySelectionManager with queries the renderer for its string represention

All except the string provider is reusable as-is (that is exactly one implemenation of the custom renderer and the keySelectionManager). There can be general implementations of the string provider, f.i. those formatting value or using bean properties via reflection. And all without breaking basic rules :-)

Jquery: Find Text and replace

How to change multiple "dogsss" to "dollsss":

$('#id1 p').each(function() {
var text = $(this).text();
// Use global flag i.e. g in the regex to replace all occurrences
$(this).text(text.replace(/dog/g, 'doll'));
});

https://jsfiddle.net/ashjpb9w/

Find non-ASCII characters in varchar columns using SQL Server

I've been running this bit of code with success

declare @UnicodeData table (
     data nvarchar(500)
)
insert into 
    @UnicodeData
values 
    (N'Horse?')
    ,(N'Dog')
    ,(N'Cat')

select
    data
from
    @UnicodeData 
where
    data collate LATIN1_GENERAL_BIN != cast(data as varchar(max))

Which works well for known columns.

For extra credit, I wrote this quick script to search all nvarchar columns in a given table for Unicode characters.

declare 
    @sql    varchar(max)    = ''
    ,@table sysname         = 'mytable' -- enter your table here

;with ColumnData as (
    select
        RowId               = row_number() over (order by c.COLUMN_NAME)
        ,c.COLUMN_NAME
        ,ColumnName         = '[' + c.COLUMN_NAME + ']'
        ,TableName          = '[' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME + ']' 
    from
        INFORMATION_SCHEMA.COLUMNS c
    where
        c.DATA_TYPE         = 'nvarchar'
        and c.TABLE_NAME    = @table
)
select
    @sql = @sql + 'select FieldName = ''' + c.ColumnName + ''',         InvalidCharacter = [' + c.COLUMN_NAME + ']  from ' + c.TableName + ' where ' + c.ColumnName + ' collate LATIN1_GENERAL_BIN != cast(' + c.ColumnName + ' as varchar(max)) '  +  case when c.RowId <> (select max(RowId) from ColumnData) then  ' union all ' else '' end + char(13)
from
    ColumnData c

-- check
-- print @sql
exec (@sql)

I'm not a fan of dynamic SQL but it does have its uses for exploratory queries like this.

Starting of Tomcat failed from Netbeans

None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!

They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.

Tip - if you right click on Applications > Netbeans and choose Show Package Contents Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules

How to see PL/SQL Stored Function body in Oracle

You can also use DBMS_METADATA:

select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY', 'PADCAMPAIGN') 
from dual

How do I set adaptive multiline UILabel text?

Programmatically in Swift 5 with Xcode 10.2

Building on top of @La masse's solution, but using autolayout to support rotation

Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)

label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
self.view.addSubview(label)
// SET AUTOLAYOUT ANCHORS
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// OPTIONALLY, YOU CAN USE THIS INSTEAD OF THE WIDTH ANCHOR (OR LEFT/RIGHT)
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)
label.text = "YOUR LONG TEXT GOES HERE"
label.sizeToFit()

If setting frame.width dynamically using UIScreen:

extension UIScreen {   // OPTIONAL IF USING A DYNAMIC FRAME WIDTH
    class func absoluteWidth() -> CGFloat {
        var width: CGFloat
        if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
            width = self.main.bounds.height // Landscape
        } else {
            width = self.main.bounds.width // Portrait
        }
        return width
    }
}

How do you create a UIImage View Programmatically - Swift

First create UIImageView then add image in UIImageView .

    var imageView : UIImageView
    imageView  = UIImageView(frame:CGRectMake(10, 50, 100, 300));
    imageView.image = UIImage(named:"image.jpg")
    self.view.addSubview(imageView)

Display / print all rows of a tibble (tbl_df)

As detailed out in the bookdown documentation, you could also use a paged table

mtcars %>% tbl_df %>% rmarkdown::paged_table()

This will paginate the data and allows to browse all rows and columns (unless configured to cap the rows). Example:

enter image description here

How to copy a row and insert in same table with a autoincrement field in MySQL?

Try this:

INSERT INTO test_table (SELECT null,txt FROM test_table)

Every time you run this query, This will insert all the rows again with new ids. values in your table and will increase exponentially.

I used a table with two columns i.e id and txt and id is auto increment.

How do I insert multiple checkbox values into a table?

I think this should work .. :)

<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>

How can I get Git to follow symlinks?

I used to add files beyond symlinks for quite some time now. This used to work just fine, without making any special arrangements. Since I updated to Git 1.6.1, this does not work any more.

You may be able to switch to Git 1.6.0 to make this work. I hope that a future version of Git will have a flag to git-add allowing it to follow symlinks again.

What does the CSS rule "clear: both" do?

I won't be explaining how the floats work here (in detail), as this question generally focuses on Why use clear: both; OR what does clear: both; exactly do...

I'll keep this answer simple, and to the point, and will explain to you graphically why clear: both; is required or what it does...

Generally designers float the elements, left or to the right, which creates an empty space on the other side which allows other elements to take up the remaining space.

Why do they float elements?

Elements are floated when the designer needs 2 block level elements side by side. For example say we want to design a basic website which has a layout like below...

enter image description here

Live Example of the demo image.

Code For Demo

_x000D_
_x000D_
/*  CSS:  */_x000D_
_x000D_
* { /* Not related to floats / clear both, used it for demo purpose only */_x000D_
    box-sizing: border-box;_x000D_
    -moz-box-sizing: border-box;_x000D_
    -webkit-box-sizing: border-box;_x000D_
}_x000D_
_x000D_
header, footer {_x000D_
    border: 5px solid #000;_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
aside {_x000D_
    float: left;_x000D_
    width: 30%;_x000D_
    border: 5px solid #000;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
section {_x000D_
    float: left;_x000D_
    width: 70%;_x000D_
    border: 5px solid #000;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
.clear {_x000D_
    clear: both;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<header>_x000D_
    Header_x000D_
</header>_x000D_
<aside>_x000D_
    Aside (Floated Left)_x000D_
</aside>_x000D_
<section>_x000D_
    Content (Floated Left, Can Be Floated To Right As Well)_x000D_
</section>_x000D_
<!-- Clearing Floating Elements-->_x000D_
<div class="clear"></div>_x000D_
<footer>_x000D_
    Footer_x000D_
</footer>
_x000D_
_x000D_
_x000D_

Note: You might have to add header, footer, aside, section (and other HTML5 elements) as display: block; in your stylesheet for explicitly mentioning that the elements are block level elements.

Explanation:

I have a basic layout, 1 header, 1 side bar, 1 content area and 1 footer.

No floats for header, next comes the aside tag which I'll be using for my website sidebar, so I'll be floating the element to left.

Note: By default, block level element takes up document 100% width, but when floated left or right, it will resize according to the content it holds.

  1. Normal Behavior Of Block Level Element
  2. Floated Behavior Of Block Level Element

So as you note, the left floated div leaves the space to its right unused, which will allow the div after it to shift in the remaining space.

  1. div's will render one after the other if they are NOT floated
  2. div will shift beside each other if floated left or right

Ok, so this is how block level elements behave when floated left or right, so now why is clear: both; required and why?

So if you note in the layout demo - in case you forgot, here it is..

I am using a class called .clear and it holds a property called clear with a value of both. So lets see why it needs both.

I've floated aside and section elements to the left, so assume a scenario, where we have a pool, where header is solid land, aside and section are floating in the pool and footer is solid land again, something like this..

Floated View

So the blue water has no idea what the area of the floated elements are, they can be bigger than the pool or smaller, so here comes a common issue which troubles 90% of CSS beginners: why the background of a container element is not stretched when it holds floated elements. It's because the container element is a POOL here and the POOL has no idea how many objects are floating, or what the length or breadth of the floated elements are, so it simply won't stretch.

  1. Normal Flow Of The Document
  2. Sections Floated To Left
  3. Cleared Floated Elements To Stretch Background Color Of The Container

(Refer [Clearfix] section of this answer for neat way to do this. I am using an empty div example intentionally for explanation purpose)

I've provided 3 examples above, 1st is the normal document flow where red background will just render as expected since the container doesn't hold any floated objects.

In the second example, when the object is floated to left, the container element (POOL) won't know the dimensions of the floated elements and hence it won't stretch to the floated elements height.

enter image description here

After using clear: both;, the container element will be stretched to its floated element dimensions.

enter image description here

Another reason the clear: both; is used is to prevent the element to shift up in the remaining space.

Say you want 2 elements side by side and another element below them... So you will float 2 elements to left and you want the other below them.

  1. div Floated left resulting in section moving into remaining space
  2. Floated div cleared so that the section tag will render below the floated divs

1st Example

enter image description here


2nd Example

enter image description here

Last but not the least, the footer tag will be rendered after floated elements as I've used the clear class before declaring my footer tags, which ensures that all the floated elements (left/right) are cleared up to that point.


Clearfix

Coming to clearfix which is related to floats. As already specified by @Elky, the way we are clearing these floats is not a clean way to do it as we are using an empty div element which is not a div element is meant for. Hence here comes the clearfix.

Think of it as a virtual element which will create an empty element for you before your parent element ends. This will self clear your wrapper element holding floated elements. This element won't exist in your DOM literally but will do the job.

To self clear any wrapper element having floated elements, we can use

.wrapper_having_floated_elements:after {  /* Imaginary class name */
  content: "";
  clear: both;
  display: table;
}

Note the :after pseudo element used by me for that class. That will create a virtual element for the wrapper element just before it closes itself. If we look in the dom you can see how it shows up in the Document tree.

Clearfix

So if you see, it is rendered after the floated child div where we clear the floats which is nothing but equivalent to have an empty div element with clear: both; property which we are using for this too. Now why display: table; and content is out of this answers scope but you can learn more about pseudo element here.

Note that this will also work in IE8 as IE8 supports :after pseudo.


Original Answer:

Most of the developers float their content left or right on their pages, probably divs holding logo, sidebar, content etc., these divs are floated left or right, leaving the rest of the space unused and hence if you place other containers, it will float too in the remaining space, so in order to prevent that clear: both; is used, it clears all the elements floated left or right.

Demonstration:

------------------ ----------------------------------
div1(Floated Left) Other div takes up the space here
------------------ ----------------------------------

Now what if you want to make the other div render below div1, so you'll use clear: both; so it will ensure you clear all floats, left or right

------------------
div1(Floated Left)
------------------
<div style="clear: both;"><!--This <div> acts as a separator--></div>
----------------------------------
Other div renders here now
----------------------------------

Check if a specific value exists at a specific key in any subarray of a multidimensional array

If you have to make a lot of "id" lookups and it should be really fast you should use a second array containing all the "ids" as keys:

$lookup_array=array();

foreach($my_array as $arr){
    $lookup_array[$arr['id']]=1;
}

Now you can check for an existing id very fast, for example:

echo (isset($lookup_array[152]))?'yes':'no';

First Or Create

firstOrCreate() checks for all the arguments to be present before it finds a match.

If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'abcd',
    'lastName' => 'efgh',
    'veristyName'=>'xyz',
]);

Then it check only the email

Initializing a list to a known number of elements in Python

This:

 lst = [8 for i in range(9)]

creates a list, elements are initialized 8

but this:

lst = [0] * 7

would create 7 lists which have one element

How do you get the logical xor of two variables in Python?

You can always use the definition of xor to compute it from other logical operations:

(a and not b) or (not a and b)

But this is a little too verbose for me, and isn't particularly clear at first glance. Another way to do it is:

bool(a) ^ bool(b)

The xor operator on two booleans is logical xor (unlike on ints, where it's bitwise). Which makes sense, since bool is just a subclass of int, but is implemented to only have the values 0 and 1. And logical xor is equivalent to bitwise xor when the domain is restricted to 0 and 1.

So the logical_xor function would be implemented like:

def logical_xor(str1, str2):
    return bool(str1) ^ bool(str2)

Credit to Nick Coghlan on the Python-3000 mailing list.

jQuery: selecting each td in a tr

You can simply do the following inside your TR loop:

$(this).find('td').each (function() {
  // do your cool stuff
});                          

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

How do I install the babel-polyfill library?

The Babel docs describe this pretty concisely:

Babel includes a polyfill that includes a custom regenerator runtime and core.js.

This will emulate a full ES6 environment. This polyfill is automatically loaded when using babel-node and babel/register.

Make sure you require it at the entry-point to your application, before anything else is called. If you're using a tool like webpack, that becomes pretty simple (you can tell webpack to include it in the bundle).

If you're using a tool like gulp-babel or babel-loader, you need to also install the babel package itself to use the polyfill.

Also note that for modules that affect the global scope (polyfills and the like), you can use a terse import to avoid having unused variables in your module:

import 'babel/polyfill';

What's the best way to generate a UML diagram from Python source code?

Epydoc is a tool to generate API documentation from Python source code. It also generates UML class diagrams, using Graphviz in fancy ways. Here is an example of diagram generated from the source code of Epydoc itself.

Because Epydoc performs both object introspection and source parsing it can gather more informations respect to static code analysers such as Doxygen: it can inspect a fair amount of dynamically generated classes and functions, but can also use comments or unassigned strings as a documentation source, e.g. for variables and class public attributes.

Change all files and folders permissions of a directory to 644/755

The shortest one I could come up with is:

chmod -R a=r,u+w,a+X /foo

which works on GNU/Linux, and I believe on Posix in general (from my reading of: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/chmod.html).

What this does is:

  1. Set file/directory to r__r__r__ (0444)
  2. Add w for owner, to get rw_r__r__ (0644)
  3. Set execute for all if a directory (0755 for dir, 0644 for file).

Importantly, the step 1 permission clears all execute bits, so step 3 only adds back execute bits for directories (never files). In addition, all three steps happen before a directory is recursed into (so this is not equivalent to e.g.

chmod -R a=r /foo
chmod -R u+w /foo
chmod -R a+X /foo

since the a=r removes x from directories, so then chmod can't recurse into them.)

Ansible: Set variable to file content

You can use lookups in Ansible in order to get the contents of a file, e.g.

user_data: "{{ lookup('file', user_data_file) }}"

Caveat: This lookup will work with local files, not remote files.

Here's a complete example from the docs:

- hosts: all
  vars:
     contents: "{{ lookup('file', '/etc/foo.txt') }}"
  tasks:
     - debug: msg="the value of foo.txt is {{ contents }}"

What's the difference between & and && in MATLAB?

&& and || are short circuit operators operating on scalars. & and | operate on arrays, and use short-circuiting only in the context of if or while loop expressions.

Add animated Gif image in Iphone UIImageView

You Can use https://github.com/Flipboard/FLAnimatedImage

#import "FLAnimatedImage.h"
NSData *dt=[NSData dataWithContentsOfFile:path];
imageView1 = [[FLAnimatedImageView alloc] init];
FLAnimatedImage *image1 = [FLAnimatedImage animatedImageWithGIFData:dt];
imageView1.animatedImage = image1;
imageView1.frame = CGRectMake(0, 5, 168, 80);
[self.view addSubview:imageView1];

Loop through an array php

Ok, I know there is an accepted answer but… for more special cases you also could use this one:

array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);

Or in a more un-complex way:

function printItem($n){
    echo $n['filename'];
    echo $n['filepath'];
}

array_map('printItem', $array);

This will allow you to manipulate the data in an easier way.

javac: file not found: first.java Usage: javac <options> <source files>

SET path of JRE as well

jre is nothing but responsible for execute the program

PATH Variable value:

C:\Program Files\Java\jdk1.8.0\bin;C:\Program Files\Java\jre\bin;.;

Return from lambda forEach() in java

The return there is returning from the lambda expression rather than from the containing method. Instead of forEach you need to filter the stream:

players.stream().filter(player -> player.getName().contains(name))
       .findFirst().orElse(null);

Here filter restricts the stream to those items that match the predicate, and findFirst then returns an Optional with the first matching entry.

This looks less efficient than the for-loop approach, but in fact findFirst() can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny() instead of findFirst() if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.

How do I check if there are duplicates in a flat list?

If the list contains unhashable items, you can use Alex Martelli's solution but with a list instead of a set, though it's slower for larger inputs: O(N^2).

def has_duplicates(iterable):
    seen = []
    for x in iterable:
        if x in seen:
            return True
        seen.append(x)
    return False

Evenly space multiple views within a container view

Many answers are not correct, but get many counts. Here I just write a solution programmatically, the three views are horizontal align, without using spacer views, but it only work when the widths of labels are known when used in storyboard.

NSDictionary *views = NSDictionaryOfVariableBindings(_redView, _yellowView, _blueView);

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|->=0-[_redView(40)]->=0-[_yellowView(40)]->=0-[_blueView(40)]->=0-|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:nil views:views]];

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_redView(60)]" options:0 metrics:nil views:views]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:_redView attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_yellowView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_redView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_yellowView attribute:NSLayoutAttributeLeading multiplier:0.5 constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_blueView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_yellowView attribute:NSLayoutAttributeLeading multiplier:1.5 constant:40]];

Uncaught SyntaxError: Unexpected token < On Chrome

Had the same error. My problem was caused from shifting around my project directory, and failing to adjust the path to my static files on the server to reflect the new path (i.e. was ./src/public but should have been ./public).

How to join two tables by multiple columns in SQL?

You should only need to do a single join:

SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
FROM Evaluation e
INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

How to remove all click event handlers using jQuery?

$('#saveBtn').off('click').on('click',function(){
   saveQuestion(id)
});

Use jquery's off and on

Is it possible to use std::string in a constexpr?

Since the problem is the non-trivial destructor so if the destructor is removed from the std::string, it's possible to define a constexpr instance of that type. Like this

struct constexpr_str {
    char const* str;
    std::size_t size;

    // can only construct from a char[] literal
    template <std::size_t N>
    constexpr constexpr_str(char const (&s)[N])
        : str(s)
        , size(N - 1) // not count the trailing nul
    {}
};

int main()
{
    constexpr constexpr_str s("constString");

    // its .size is a constexpr
    std::array<int, s.size> a;
    return 0;
}

how to pass value from one php page to another using session

Use something like this:

page1.php

<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>

Any other PHP page:

<?php
session_start();
echo $_SESSION['myValue'];
?>

A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.

You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.

The setting of the variable itself can be done in one of a number of ways:

$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];

And if you want to check if the variable is set before getting a potential error, use something like this:

if(!empty($_SESSION['myValue'])
{
    echo $_SESSION['myValue'];
}
else
{
    echo "Session not set yet.";
}

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

Use the class URLEncoder:

URLEncoder.encode(String s, String enc)

Where :

s - String to be translated.

enc - The name of a supported character encoding.

Standard charsets:

US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1

UTF-8 Eight-bit UCS Transformation Format

UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order

UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order

UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark

Example:

import java.net.URLEncoder;

String stringEncoded = URLEncoder.encode(
    "This text must be encoded! aeiou áéíóú ñ, peace!", "UTF-8");

Get the _id of inserted document in Mongo database in NodeJS

Mongo sends the complete document as a callbackobject so you can simply get it from there only.

for example

collection.save(function(err,room){
  var newRoomId = room._id;
  });

How to completely uninstall Android Studio on Mac?

You may also delete gradle file, if you don't use gradle any where else:

rm -Rfv ~/.gradle/

because .gradle folder contains cached artifacts that are no longer needed.

How to write into a file in PHP?

I use the following code to write files on my web directory.

write_file.html

<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>

write_file.php

<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);

// Show the msg, if the code string is empty
if (empty($cd))
    echo "Nothing to write";

// if the code string is not empty then open the target file and put form data in it
else
{
    $file = fopen("demo.php", "w");
    echo fwrite($file, $cd);

    // show a success msg 
    echo "data successfully entered";
    fclose($file);
}
?>

This is a working script. be sure to change the url in form action and the target file in fopen() function if you want to use it on your site.

Good luck.

Algorithm to generate all possible permutations of a list?

Wikipedia's answer for "lexicographic order" seems perfectly explicit in cookbook style to me. It cites a 14th century origin for the algorithm!

I've just written a quick implementation in Java of Wikipedia's algorithm as a check and it was no trouble. But what you have in your Q as an example is NOT "list all permutations", but "a LIST of all permutations", so wikipedia won't be a lot of help to you. You need a language in which lists of permutations are feasibly constructed. And believe me, lists a few billion long are not usually handled in imperative languages. You really want a non-strict functional programming language, in which lists are a first-class object, to get out stuff while not bringing the machine close to heat death of the Universe.

That's easy. In standard Haskell or any modern FP language:

-- perms of a list
perms :: [a] -> [ [a] ]
perms (a:as) = [bs ++ a:cs | perm <- perms as, (bs,cs) <- splits perm]
perms []     = [ [] ]

and

-- ways of splitting a list into two parts
splits :: [a] -> [ ([a],[a]) ]
splits []     = [ ([],[]) ]
splits (a:as) = ([],a:as) : [(a:bs,cs) | (bs,cs) <- splits as]

How to create exe of a console application

For .net core 2.1 console application, the following approaches worked for me:

1 - from CLI (after building the application and navigating to debug or release folders based on the build type specified):

dotnet appName.dll

2 - from Visual Studio

R.C solution and click publish
'Target location' -> 'configure' ->
   'Deployment Mode' = 'Self-Contained'
   'Target Runtime' = 'win-x64 or win-x86 depending on the OS'

References:

For an in depth explanation of all the deployment options available for .net core applications, checkout the following articles:

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

What worked for me is performing Refresh all Gradle projects from the Gradle toolbar from the right menu.

PFB the screenshot from Android Studio.

  1. Select Gradle toolbar from the right menu.
  2. Select the Refresh icon

This resolved the issue for me.

Screenshot from Android Studio

Deprecated: mysql_connect()

Adding a @ works for me!

I tested with error_reporting(E_ALL ^ E_DEPRECATED);

Getting Git to work with a proxy server - fails with "Request timed out"

As an alternative to using git config --global http.proxy address:port, you can set the proxy on the command line:

git -c "http.proxy=address:port" clone https://...

The advantage is the proxy is not persistently set. Under Bash you might set an alias:

alias git-proxy='git -c "http.proxy=address:port"'

Display Two <div>s Side-by-Side

I removed the float from the second div to make it work.

http://jsfiddle.net/rhEyM/2/

Copy/Paste from Excel to a web page

Maybe it would be better if you would read your excel file from PHP, and then either save it to a DB or do some processing on it.

here an in-dept tutorial on how to read and write Excel data with PHP:
http://www.ibm.com/developerworks/opensource/library/os-phpexcel/index.html

CSS Background Image Not Displaying

body { 
        background: url("../img/debut_dark.png") no-repeat center center fixed;
    }

Worked for me.

Python SQL query string formatting

Sorry for posting to such an old thread -- but as someone who also shares a passion for pythonic 'best', I thought I'd share our solution.

The solution is to build SQL statements using python's String Literal Concatenation (http://docs.python.org/), which could be qualified a somewhere between Option 2 and Option 4

Code Sample:

sql = ("SELECT field1, field2, field3, field4 "
       "FROM table "
       "WHERE condition1=1 "
       "AND condition2=2;")

Works as well with f-strings:

fields = "field1, field2, field3, field4"
table = "table"
conditions = "condition1=1 AND condition2=2"

sql = (f"SELECT {fields} "
       f"FROM {table} "
       f"WHERE {conditions};")

Pros:

  1. It retains the pythonic 'well tabulated' format, but does not add extraneous space characters (which pollutes logging).
  2. It avoids the backslash continuation ugliness of Option 4, which makes it difficult to add statements (not to mention white-space blindness).
  3. And further, it's really simple to expand the statement in VIM (just position the cursor to the insert point, and press SHIFT-O to open a new line).

Java check if boolean is null

A boolean cannot be null in java.

A Boolean, however, can be null.

If a boolean is not assigned a value (say a member of a class) then it will be false by default.

How to export data as CSV format from SQL Server using sqlcmd?

With PowerShell you can solve the problem neatly by piping Invoke-Sqlcmd into Export-Csv.

#Requires -Module SqlServer
Invoke-Sqlcmd -Query "SELECT * FROM DimDate;" `
              -Database AdventureWorksDW2012 `
              -Server localhost |
Export-Csv -NoTypeInformation `
           -Path "DimDate.csv" `
           -Encoding UTF8

SQL Server 2016 includes the SqlServer module, which contains the Invoke-Sqlcmd cmdlet, which you'll have even if you just install SSMS 2016. Prior to that, SQL Server 2012 included the old SQLPS module, which would change the current directory to SQLSERVER:\ when the module was first used (among other bugs) so for it, you'll need to change the #Requires line above to:

Push-Location $PWD
Import-Module -Name SQLPS
# dummy query to catch initial surprise directory change
Invoke-Sqlcmd -Query "SELECT 1" `
              -Database  AdventureWorksDW2012 `
              -Server localhost |Out-Null
Pop-Location
# actual Invoke-Sqlcmd |Export-Csv pipeline

To adapt the example for SQL Server 2008 and 2008 R2, remove the #Requires line entirely and use the sqlps.exe utility instead of the standard PowerShell host.

Invoke-Sqlcmd is the PowerShell equivalent of sqlcmd.exe. Instead of text it outputs System.Data.DataRow objects.

The -Query parameter works like the -Q parameter of sqlcmd.exe. Pass it a SQL query that describes the data you want to export.

The -Database parameter works like the -d parameter of sqlcmd.exe. Pass it the name of the database that contains the data to be exported.

The -Server parameter works like the -S parameter of sqlcmd.exe. Pass it the name of the server that contains the data to be exported.

Export-CSV is a PowerShell cmdlet that serializes generic objects to CSV. It ships with PowerShell.

The -NoTypeInformation parameter suppresses extra output that is not part of the CSV format. By default the cmdlet writes a header with type information. It lets you know the type of the object when you deserialize it later with Import-Csv, but it confuses tools that expect standard CSV.

The -Path parameter works like the -o parameter of sqlcmd.exe. A full path for this value is safest if you are stuck using the old SQLPS module.

The -Encoding parameter works like the -f or -u parameters of sqlcmd.exe. By default Export-Csv outputs only ASCII characters and replaces all others with question marks. Use UTF8 instead to preserve all characters and stay compatible with most other tools.

The main advantage of this solution over sqlcmd.exe or bcp.exe is that you don't have to hack the command to output valid CSV. The Export-Csv cmdlet handles it all for you.

The main disadvantage is that Invoke-Sqlcmd reads the whole result set before passing it along the pipeline. Make sure you have enough memory for the whole result set you want to export.

It may not work smoothly for billions of rows. If that's a problem, you could try the other tools, or roll your own efficient version of Invoke-Sqlcmd using System.Data.SqlClient.SqlDataReader class.

Validate IPv4 address in Java

the lib of apache-httpcomponents

// ipv4 is true
assertTrue(InetAddressUtils.isIPv4Address("127.0.0.1"));
// not detect the ipv6
assertFalse(InetAddressUtils.isIPv4Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));

maven lib (update Sep, 2019)

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

How can strings be concatenated?

you can also do this:

section = "C_type"
new_section = "Sec_%s" % section

This allows you not only append, but also insert wherever in the string:

section = "C_type"
new_section = "Sec_%s_blah" % section

Permission denied on accessing host directory in Docker

Try docker volume create.

mkdir -p /data1/Downloads
docker volume create --driver local --name hello --opt type=none --opt device=/data1/Downloads --opt o=uid=root,gid=root --opt o=bind
docker run -i -v hello:/Downloads ubuntu bash

Take a look at the document https://docs.docker.com/engine/reference/commandline/volume_create/

R Markdown - changing font size and font type in html output

I would definitely use html markers to achieve this. Just surround your text with <p></p> or <font></font> and add the desired attributes. See the following example:

<p style="font-family: times, serif; font-size:11pt; font-style:italic">
    Why did we use these specific parameters during the calculation of the fingerprints?
</p>

This will produce the following output

Font Output

compared to

Default Output

This would work with Jupyter Notebook as well as Typora, but I'm not sure if it is universal.

Lastly, be aware that the html marker overrides the font styling used by Markdown.

How to debug an apache virtual host configuration?

I recently had some issues with a VirtualHost. I used a2ensite to enable a host but before running a restart (which would kill the server on fail) I ran

apache2ctl -S

Which gives you some info about what's going on with your virtual hosts. It's not perfect, but it helps.

Unable to convert MySQL date/time value to System.DateTime

You can make the application fully compatible with the date and time that is used by MySql. When the application runs at runtime provide this code. First Go to the Application Events. In the list of tools

  1. Go to the project
  2. Project Properties
  3. Select the Application tab
  4. View Application Events

This will open a new file. This file contains code used at the start of the application.

Write this code in that new file:

 Partial Friend Class MyApplication

    Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
        My.Application.ChangeCulture("en")
        My.Application.ChangeUICulture("en")
        My.Application.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"
        My.Application.Culture.DateTimeFormat.LongDatePattern = "yyyy-MM-dd"
        My.Application.Culture.DateTimeFormat.LongTimePattern = "HH:mm:ss"
        My.Application.Culture.DateTimeFormat.ShortTimePattern = "HH:mm:ss"
    End Sub


End Class

ImportError: No module named 'MySQL'

My project was using pipenv. The following command worked for me:

pipenv install mysql-connector-python

Firebase onMessageReceived not called when app in background

you can try this in your main Activity , when in the background

   if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                Object value = getIntent().getExtras().get(key);
                Log.d(TAG, "Key: " + key + " Value: " + value);
            }
        }

Check the following project as reference

Import SQL file by command line in Windows 7

Try this it will work. Do not enter password it will ask one you execute the following cmd

C:\xampp\mysql\bin\mysql -u xxxxx -p -h localhost your_database_name < c:\yourfile.sql

ReferenceError: $ is not defined

Though my response is late, but it can still help.

lf you are using Spring Tool Suite and you still think that the JQuery file reference path is correct, then refresh your project whenever you modify the JQuery file.

You refresh by right-clicking on the project name -> refresh.

That's what solved mine.

T-SQL substring - separating first and last name

I think below query will be helpful to split FirstName and LastName from FullName even if there is only FirstName. For example: 'Philip John' can be split into Philip and John. But if there is only Philip, because of the charIndex of Space is 0, it will only give you ''.

Try the below one.

declare @FullName varchar(100)='Philp John'

Select  
    LTRIM(RTRIM(SUBSTRING(@FullName, 0, CHARINDEX(' ', @FullName+' ')))) As FirstName
,   LTRIM(RTRIM(SUBSTRING(@FullName, CHARINDEX(' ', @FullName+' ')+1, 8000)))As LastName

Hope this will help you. :)

Maximum number of threads in a .NET app?

I would recommend running ThreadPool.GetMaxThreads method in debug

ThreadPool.GetMaxThreads(out int workerThreadsCount, out int ioThreadsCount);

Docs and examples: https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadpool.getmaxthreads?view=netframework-4.8

Fitting iframe inside a div

Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/

Html:

<div id="content">
    <iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>

Relevant parts of CSS:

div#content {
    position: fixed;
    top: 80px;
    left: 40px;
    bottom: 25px;
    min-width: 200px;
    width: 40%;
    background: black;
}

div#content iframe {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100%;
    width: 100%;
}

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
    ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i

end sub

Stack Memory vs Heap Memory

In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.

The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)

The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.

Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.

Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.

Converting String to Cstring in C++

.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.

Integer division with remainder in JavaScript?

Here is a way to do this. (Personally I would not do it this way, but thought it was a fun way to do it for an example)

_x000D_
_x000D_
function intDivide(numerator, denominator) {
  return parseInt((numerator/denominator).toString().split(".")[0]);
}

let x = intDivide(4,5);
let y = intDivide(5,5);
let z = intDivide(6,5);
console.log(x);
console.log(y);
console.log(z);
_x000D_
_x000D_
_x000D_

Serializing list to JSON

You can use pure Python to do it:

import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'

Python - Using regex to find multiple matches and print them out

Do not use regular expressions to parse HTML.

But if you ever need to find all regexp matches in a string, use the findall function.

import re
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matches = re.findall('<form>(.*?)</form>', line, re.DOTALL)
print(matches)

# Output: ['Form 1', 'Form 2']

RS256 vs HS256: What's the difference?

There is a difference in performance.

Simply put HS256 is about 1 order of magnitude faster than RS256 for verification but about 2 orders of magnitude faster than RS256 for issuing (signing).

 640,251  91,464.3 ops/s
  86,123  12,303.3 ops/s (RS256 verify)
   7,046   1,006.5 ops/s (RS256 sign)

Don't get hung up on the actual numbers, just think of them with respect of each other.

[Program.cs]

class Program
{
    static void Main(string[] args)
    {
        foreach (var duration in new[] { 1, 3, 5, 7 })
        {
            var t = TimeSpan.FromSeconds(duration);

            byte[] publicKey, privateKey;

            using (var rsa = new RSACryptoServiceProvider())
            {
                publicKey = rsa.ExportCspBlob(false);
                privateKey = rsa.ExportCspBlob(true);
            }

            byte[] key = new byte[64];

            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(key);
            }

            var s1 = new Stopwatch();
            var n1 = 0;

            using (var hs256 = new HMACSHA256(key))
            {
                while (s1.Elapsed < t)
                {
                    s1.Start();
                    var hash = hs256.ComputeHash(privateKey);
                    s1.Stop();
                    n1++;
                }
            }

            byte[] sign;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(privateKey);

                sign = rsa.SignData(privateKey, "SHA256");
            }

            var s2 = new Stopwatch();
            var n2 = 0;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(publicKey);

                while (s2.Elapsed < t)
                {
                    s2.Start();
                    var success = rsa.VerifyData(privateKey, "SHA256", sign);
                    s2.Stop();
                    n2++;
                }
            }

            var s3 = new Stopwatch();
            var n3 = 0;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(privateKey);

                while (s3.Elapsed < t)
                {
                    s3.Start();
                    rsa.SignData(privateKey, "SHA256");
                    s3.Stop();
                    n3++;
                }
            }

            Console.WriteLine($"{s1.Elapsed.TotalSeconds:0} {n1,7:N0} {n1 / s1.Elapsed.TotalSeconds,9:N1} ops/s");
            Console.WriteLine($"{s2.Elapsed.TotalSeconds:0} {n2,7:N0} {n2 / s2.Elapsed.TotalSeconds,9:N1} ops/s");
            Console.WriteLine($"{s3.Elapsed.TotalSeconds:0} {n3,7:N0} {n3 / s3.Elapsed.TotalSeconds,9:N1} ops/s");

            Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n2 / s2.Elapsed.TotalSeconds),9:N1}x slower (verify)");
            Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n3 / s3.Elapsed.TotalSeconds),9:N1}x slower (issue)");

            // RS256 is about 7.5x slower, but it can still do over 10K ops per sec.
        }
    }
}

Execute php file from another php

exec('wget http://<url to the php script>') worked for me.

It enable me to integrate two php files that were designed as web pages and run them as code to do work without affecting the calling page

Find intersection of two nested lists?

# Problem:  Given c1 and c2:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
# how do you get c3 to be [[13, 32], [7, 13, 28], [1, 6]] ?

Here's one way to set c3 that doesn't involve sets:

c3 = []
for sublist in c2:
    c3.append([val for val in c1 if val in sublist])

But if you prefer to use just one line, you can do this:

c3 = [[val for val in c1 if val in sublist]  for sublist in c2]

It's a list comprehension inside a list comprehension, which is a little unusual, but I think you shouldn't have too much trouble following it.

What's wrong with nullable columns in composite primary keys?

Primary keys are for uniquely identifying rows. This is done by comparing all parts of a key to the input.

Per definition, NULL cannot be part of a successful comparison. Even a comparison to itself (NULL = NULL) will fail. This means a key containing NULL would not work.

Additonally, NULL is allowed in a foreign key, to mark an optional relationship.(*) Allowing it in the PK as well would break this.


(*)A word of caution: Having nullable foreign keys is not clean relational database design.

If there are two entities A and B where A can optionally be related to B, the clean solution is to create a resolution table (let's say AB). That table would link A with B: If there is a relationship then it would contain a record, if there isn't then it would not.

How does setTimeout work in Node.JS?

setTimeout is a kind of Thread, it holds a operation for a given time and execute.

setTimeout(function,time_in_mills);

in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.

setTimeout(function(){console.log('your name')},3000);

Key point to remember is, what ever you want to do by using the setTimeout method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:

setTimeout(function(){yourOtherMethod(parameter);},3000);

How To: Best way to draw table in console app (C#)

Use String.Format with alignment values.

For example:

String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);

To create one formatted row.

Parsing query strings on Android

public static Map <String, String> parseQueryString (final URL url)
        throws UnsupportedEncodingException
{
    final Map <String, String> qps = new TreeMap <String, String> ();
    final StringTokenizer pairs = new StringTokenizer (url.getQuery (), "&");
    while (pairs.hasMoreTokens ())
    {
        final String pair = pairs.nextToken ();
        final StringTokenizer parts = new StringTokenizer (pair, "=");
        final String name = URLDecoder.decode (parts.nextToken (), "ISO-8859-1");
        final String value = URLDecoder.decode (parts.nextToken (), "ISO-8859-1");
        qps.put (name, value);
    }
    return qps;
}

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

Add a label= to each of your plot() calls, and then call legend(loc='upper left').

Consider this sample (tested with Python 3.8.0):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()

enter image description here Slightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html

How do I create directory if it doesn't exist to create a file?

var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));

var file = new FileInfo(filePath);

file.Directory.Create(); If the directory already exists, this method does nothing.

var sw = new StreamWriter(filePath, true);

sw.WriteLine(Enter your message here);

sw.Close();

Django DB Settings 'Improperly Configured' Error

On Django 1.9, I tried django-admin runserver and got the same error, but when I used python manage.py runserver I got the intended result. This may solve this error for a lot of people!

Saving to CSV in Excel loses regional date format

Although keeping this in mind http://xkcd.com/1179/

In the end I decided to use the format YYYYMMDD in all CSV files, which doesn't convert to date in Excel, but can be read by all our applications correctly.

Why is the parent div height zero when it has floated children

I'm not sure this is a right way but I solved it by adding display: inline-block; to the wrapper div.

#wrapper{
    display: inline-block;
    /*border: 1px black solid;*/
    width: 75%;
    min-width: 800px;
}

.content{
    text-align: justify; 
    float: right; 
    width: 90%;
}

.lbar{
    text-align: justify; 
    float: left; 
    width: 10%;
}

Textarea Auto height

I see that this is answered already, but I believe I have a simple jQuery solution ( jQuery is not even really needed; I just enjoy using it ):

I suggest counting the line breaks in the textarea text and setting the rows attribute of the textarea accordingly.

var text = jQuery('#your_textarea').val(),
    // look for any "\n" occurences
    matches = text.match(/\n/g),
    breaks = matches ? matches.length : 2;

jQuery('#your_textarea').attr('rows',breaks + 2);

What is the pythonic way to detect the last element in a 'for' loop?

I will provide with a more elegant and robust way as follows, using unpacking:

def mark_last(iterable):
    try:
        *init, last = iterable
    except ValueError:  # if iterable is empty
        return

    for e in init:
        yield e, True
    yield last, False

Test:

for a, b in mark_last([1, 2, 3]):
    print(a, b)

The result is:

1 True
2 True
3 False

How to run single test method with phpunit?

You Can try this i am able to run single Test cases

phpunit tests/{testfilename}

Eg:

phpunit tests/StackoverflowTest.php

If you want to run single Test cases in Laravel 5.5 Try

vendor/bin/phpunit tests/Feature/{testfilename} 

vendor/bin/phpunit tests/Unit/{testfilename} 

Eg:

vendor/bin/phpunit tests/Feature/ContactpageTest.php 

vendor/bin/phpunit tests/Unit/ContactpageTest.php

How to Get JSON Array Within JSON Object?

JSONObject jsonObj = new JSONObject(jsonString);

JSONArray jArray = jsonObj.getJSONArray("data");
int length = jArray.length();

   for(int i=0; i<length; i++)
      {
        JSONObject jObj = jArray.getJSONObject(i);
        String id = jObj.optString("id");
        String name=jObj.optString("name");

        JSONArray ingredientArray = jObj.getJSONArray("Ingredients");
        int size = ingredientArray.length();
        ArrayList<String> Ingredients = new ArrayList<>();

            for(int j=0; j<size; j++)
               {
                    JSONObject json = ja.getJSONObject(j);
                    Ingredients.add(json.optString("name"));
                }


       }

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

How to find which version of TensorFlow is installed in my system?

If you have installed via pip, just run the following

$ pip show tensorflow
Name: tensorflow
Version: 1.5.0
Summary: TensorFlow helps the tensors flow

How to disable text selection highlighting

Try to insert these rows into the CSS and call the "disHighlight" at class property:

.disHighlight {
    user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -webkit-touch-callout: none;
    -o-user-select: none;
    -moz-user-select: none;
}