Programs & Examples On #Apacheds

ApacheDS is an extensible and embeddable directory server entirely written in Java

Echoing the last command run in Bash?

After reading the answer from Gilles, I decided to see if the $BASH_COMMAND var was also available (and the desired value) in an EXIT trap - and it is!

So, the following bash script works as expected:

#!/bin/bash

exit_trap () {
  local lc="$BASH_COMMAND" rc=$?
  echo "Command [$lc] exited with code [$rc]"
}

trap exit_trap EXIT
set -e

echo "foo"
false 12345
echo "bar"

The output is

foo
Command [false 12345] exited with code [1]

bar is never printed because set -e causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345 passed to false is just there to show that the arguments to the failed command are captured as well (the false command ignores any arguments passed to it)

Show DialogFragment with animation growing from a point

Being DialogFragment a wrapper for the Dialog class, you should set a theme to your base Dialog to get the animation you want:

public class CustomDialogFragment extends DialogFragment implements OnEditorActionListener
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) 
    {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) 
    {
        // Set a theme on the dialog builder constructor!
        AlertDialog.Builder builder = 
            new AlertDialog.Builder( getActivity(), R.style.MyCustomTheme );

        builder  
        .setTitle( "Your title" )
        .setMessage( "Your message" )
        .setPositiveButton( "OK" , new DialogInterface.OnClickListener() 
            {      
              @Override
              public void onClick(DialogInterface dialog, int which) {
              dismiss();                  
            }
        });
        return builder.create();
    }
}

Then you just need to define the theme that will include your desired animation. In styles.xml add your custom theme:

<style name="MyCustomTheme" parent="@android:style/Theme.Panel">
    <item name="android:windowAnimationStyle">@style/MyAnimation.Window</item>
</style>

<style name="MyAnimation.Window" parent="@android:style/Animation.Activity"> 
    <item name="android:windowEnterAnimation">@anim/anim_in</item>
    <item name="android:windowExitAnimation">@anim/anim_out</item>
</style>    

Now add the animation files in the res/anim folder:

( the android:pivotY is the key )

anim_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/linear_interpolator"
        android:fromXScale="0.0"
        android:toXScale="1.0"
        android:fromYScale="0.0"
        android:toYScale="1.0"
        android:fillAfter="false"
        android:startOffset="200"
        android:duration="200" 
        android:pivotX = "50%"
        android:pivotY = "-90%"
    />
    <translate
        android:fromYDelta="50%"
        android:toYDelta="0"
        android:startOffset="200"
        android:duration="200"
    />
</set>

anim_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/linear_interpolator"
        android:fromXScale="1.0"
        android:toXScale="0.0"
        android:fromYScale="1.0"
        android:toYScale="0.0"
        android:fillAfter="false"
        android:duration="200" 
        android:pivotX = "50%"        
        android:pivotY = "-90%"        
    />
    <translate
        android:fromYDelta="0"
        android:toYDelta="50%"
        android:duration="200"
    />
</set>

Finally, the tricky thing here is to get your animation grow from the center of each row. I suppose the row is filling the screen horizontally so, on one hand the android:pivotX value will be static. On the other hand, you can't modify the android:pivotY value programmatically.

What I suggest is, you define several animations each of which having a different percentage value on the android:pivotY attribute (and several themes referencing those animations). Then, when the user taps the row, calculate the Y position in percentage of the row on the screen. Knowing the position in percentage, assign a theme to your dialog that has the appropriate android:pivotY value.

It is not a perfect solution but could do the trick for you. If you don't like the result, then I would suggest forgetting the DialogFragment and animating a simple View growing from the exact center of the row.

Good luck!

How to reference static assets within vue javascript

Having a default structure of folders generated by Vue CLI such as src/assets you can place your image there and refer this from HTML as follows <img src="../src/assets/img/logo.png"> as well (works automatically without any changes on deployment too).

Cluster analysis in R: determine the optimal number of clusters

In order to determine optimal k-cluster in clustering methods. I usually using Elbow method accompany by Parallel processing to avoid time-comsuming. This code can sample like this:

Elbow method

elbow.k <- function(mydata){
dist.obj <- dist(mydata)
hclust.obj <- hclust(dist.obj)
css.obj <- css.hclust(dist.obj,hclust.obj)
elbow.obj <- elbow.batch(css.obj)
k <- elbow.obj$k
return(k)
}

Running Elbow parallel

no_cores <- detectCores()
    cl<-makeCluster(no_cores)
    clusterEvalQ(cl, library(GMD))
    clusterExport(cl, list("data.clustering", "data.convert", "elbow.k", "clustering.kmeans"))
 start.time <- Sys.time()
 elbow.k.handle(data.clustering))
 k.clusters <- parSapply(cl, 1, function(x) elbow.k(data.clustering))
    end.time <- Sys.time()
    cat('Time to find k using Elbow method is',(end.time - start.time),'seconds with k value:', k.clusters)

It works well.

pandas groupby sort descending order

Similar to one of the answers above, but try adding .sort_values() to your .groupby() will allow you to change the sort order. If you need to sort on a single column, it would look like this:

df.groupby('group')['id'].count().sort_values(ascending=False)

ascending=False will sort from high to low, the default is to sort from low to high.

*Careful with some of these aggregations. For example .size() and .count() return different values since .size() counts NaNs.

What is the difference between size and count in pandas?

Joda DateTime to Timestamp conversion

//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));               
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));

File URL "Not allowed to load local resource" in the Internet Browser

Follow the below steps,

  1. npm install -g http-server, install the http-server in angular project.
  2. Go to file location which needs to be accessed and open cmd prompt, use cmd http-server ./
  3. Access any of the paths with port number in browser(ex: 120.0.0.1:8080) 4.now in your angular application use the path "http://120.0.0.1:8080/filename" Worked fine for me

How to get the first non-null value in Java?

Object coalesce(Object... objects)
{
    for(Object o : object)
        if(o != null)
            return o;
    return null;
}

How to go back last page

Maybe you'd like to check if the previous point of history is within your app. For example, if you enter directly to your app and do location.back() (by pressing a <- back button in a toolbar for example), you'd be back to your browser's main page, instead of going somewhere else within your app.

This is how I check for this:

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-foo',
  template: ''
})
export class FooComponent {

  private readonly canGoBack: boolean;

  constructor(
    private readonly route: ActivatedRoute,
    private readonly router: Router,
    private readonly location: Location
  ) {
    // This is where the check is done. Make sure to do this
    // here in the constructor, otherwise `getCurrentNavigation()`
    // will return null. 
    this.canGoBack = !!(this.router.getCurrentNavigation()?.previousNavigation);
  }

  goBack(): void {
    if (this.canGoBack) {
      // We can safely go back to the previous location as
      // we know it's within our app.
      this.location.back();
    } else {
      // There's no previous navigation.
      // Here we decide where to go. For example, let's say the
      // upper level is the index page, so we go up one level.
      this.router.navigate(['..'], {relativeTo: this.route});
    }
  }

}

We check if the navigation that loaded the current route has a previous sibling. This has to be done in the constructor, while the navigation process is still active.

This doesn't come without caveats though:

  • canGoBack will be false even if the previous location is actually within our app but the page was refreshed.
  • The user might want to "go back" to the previous page (where the goBack() ocurred) by clicking the browser's back button, but since the app went back on history instead of pushing a new location, the user will be going back even further and might get confused.

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

Rename Pandas DataFrame Index

df.index.rename('new name', inplace=True)

Is the only one that does the job for me (pandas 0.22.0).
Without the inplace=True, the name of the index is not set in my case.

500 Internal Server Error for php file not for html

It was changing the line endings (from Windows CRLF to Unix LF) in the .htaccess file that fixed it for me.

setAttribute('display','none') not working

Try this:

setAttribute("hidden", true);

how to draw a rectangle in HTML or CSS?

To mimic the rectangle with fixed position on facebook, try something like this:

<div id="rectangle"></div>

CSS

#rectangle {
    width:100%;
    height:60px;
    background:#00f;
    position:fixed;
    top:0;
    left:0;
}

How do I skip an iteration of a `foreach` loop?

Another approach is to filter using LINQ before the loop executes:

foreach ( int number in numbers.Where(n => n >= 0) )
{
    // process number
}

How do you delete all text above a certain line

:1,.d deletes lines 1 to current.
:1,.-1d deletes lines 1 to above current.

(Personally I'd use dgg or kdgg like the other answers, but TMTOWTDI.)

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

I could also just add that I knew everything about the syntax change between Python2.7 and Python3, and my code was correctly written as print("string") and even print(f"string")...

But after some time of debugging I realized that my bash script was calling python like:

python file_name.py

which had the effect of calling my python script by default using python2.7 which gave the error. So I changed my bash script to:

python3 file_name.py

which of coarse uses python3 to run the script which fixed the error.

How can I list all collections in the MongoDB shell?

For MongoDB 3.0 deployments using the WiredTiger storage engine, if you run db.getCollectionNames() from a version of the mongo shell before 3.0 or a version of the driver prior to 3.0 compatible version, db.getCollectionNames() will return no data, even if there are existing collections.

For further details, please refer to this.

getFilesDir() vs Environment.getDataDirectory()

Environment returns user data directory. And getFilesDir returns application data directory.

Passive Link in Angular 2 - <a href=""> equivalent

I am using this workaround with css:

/*** Angular 2 link without href ***/
a:not([href]){
    cursor: pointer; 
    -webkit-user-select: none; 
    -moz-user-select: none; 
    user-select: none
}

html

<a [routerLink]="/">My link</a>

Hope this helps

Console.log(); How to & Debugging javascript

I like to add these functions in the head.

window.log=function(){if(this.console){console.log(Array.prototype.slice.call(arguments));}};
jQuery.fn.log=function (msg){console.log("%s: %o", msg,this);return this;};

Now log won't break IE I can enable it or disable it in one place I can log inline

$(".classname").log(); //show an array of all elements with classname class

How to get the previous URL in JavaScript?

If anyone is coming from React-world, I ended up solving my use-case using a combination of history-library, useEffect and localStorage

When user selects new project:

  function selectProject(customer_id: string, project_id: string){
    const projectUrl = `/customer/${customer_id}/project/${project_id}`
    localStorage.setItem("selected-project", projectUrl)
    history.push(projectUrl)
  }

When user comes back from another website. If there's something in localStorage, send him there.

  useEffect(() => {
    const projectUrl = localStorage.getItem("selected-project")
    if (projectUrl) {
      history.push(projectUrl)
    }
  }, [history])

When user has exited a project, empty localStorage

  const selectProject = () => {
    localStorage.removeItem("selected-project")
    history.push("/")
  }

JavaFX: How to get stage from controller during initialization?

All you need is to give the AnchorPane an ID, and then you can get the Stage from that.

@FXML private AnchorPane ap;
Stage stage = (Stage) ap.getScene().getWindow();

From here, you can add in the Listener that you need.

Edit: As stated by EarthMind below, it doesn't have to be the AnchorPane element; it can be any element that you've defined.

Generating an MD5 checksum of a file

You can use hashlib.md5()

Note that sometimes you won't be able to fit the whole file in memory. In that case, you'll have to read chunks of 4096 bytes sequentially and feed them to the md5 method:

import hashlib
def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

Note: hash_md5.hexdigest() will return the hex string representation for the digest, if you just need the packed bytes use return hash_md5.digest(), so you don't have to convert back.

How to send HTML-formatted email?

Best way to send html formatted Email

This code will be in "Customer.htm"

    <table>
    <tr>
        <td>
            Dealer's Company Name
        </td>
        <td>
            :
        </td>
        <td>
            #DealerCompanyName#
        </td>
    </tr>
</table>

Read HTML file Using System.IO.File.ReadAllText. get all HTML code in string variable.

string Body = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("EmailTemplates/Customer.htm"));

Replace Particular string to your custom value.

Body = Body.Replace("#DealerCompanyName#", _lstGetDealerRoleAndContactInfoByCompanyIDResult[0].CompanyName);

call SendEmail(string Body) Function and do procedure to send email.

 public static void SendEmail(string Body)
        {
            MailMessage message = new MailMessage();
            message.From = new MailAddress(Session["Email"].Tostring());
            message.To.Add(ConfigurationSettings.AppSettings["RequesEmail"].ToString());
            message.Subject = "Request from " + SessionFactory.CurrentCompany.CompanyName + " to add a new supplier";
            message.IsBodyHtml = true;
            message.Body = Body;

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.UseDefaultCredentials = true;

            smtpClient.Host = ConfigurationSettings.AppSettings["SMTP"].ToString();
            smtpClient.Port = Convert.ToInt32(ConfigurationSettings.AppSettings["PORT"].ToString());
            smtpClient.EnableSsl = true;
            smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings["USERNAME"].ToString(), ConfigurationSettings.AppSettings["PASSWORD"].ToString());
            smtpClient.Send(message);
        }

How can I enable the Windows Server Task Scheduler History recording?

I have another possible answer for those wondering why event log entries are not showing up in the History tab of Task Scheduler for certain tasks, even though All Task History is enabled, the events for those tasks are viewable in the Event Log, and all other tasks show history just fine. In my case, I had created 13 new tasks. For 5 of them, events showed fine under History, but for the other 8, the History tab was completely blank. I even verified these tasks were enabled for history individually (and logging events) using Mick Wood's post about using the Event Viewer.

Then it hit me. I suddenly realized what all 8 had in common that the other 5 did not. They all had an ampersand (&) character in the event name. I created them by exporting the first task I created, "Sync E to N", renaming the exported file name, editing the XML contents, and then importing the new task. Windows Explorer happily let me rename the task, for example, to "Sync C to N & T", and Task Scheduler happily let me import it. However, with that pesky "&" in the name, it could not retrieve its history from the event log. When I deleted the original event, renamed the xml file to "Sync C to N and T", and imported it, voila, there were all of the log entries in the History tab in Task Scheduler.

Python: Removing list element while iterating over list

Another way of doing so is:

while i<len(your_list):
    if #condition :
        del your_list[i]
    else:
        i+=1

So, you delete the elements side by side while checking

Bootstrap 3 - How to load content in modal body via AJAX?

I guess you're searching for this custom function. It takes a data-toggle attribute and creates dynamically the necessary div to place the remote content. Just place the data-toggle="ajaxModal" on any link you want to load via AJAX.

The JS part:

$('[data-toggle="ajaxModal"]').on('click',
              function(e) {
                $('#ajaxModal').remove();
                e.preventDefault();
                var $this = $(this)
                  , $remote = $this.data('remote') || $this.attr('href')
                  , $modal = $('<div class="modal" id="ajaxModal"><div class="modal-body"></div></div>');
                $('body').append($modal);
                $modal.modal({backdrop: 'static', keyboard: false});
                $modal.load($remote);
              }
            );

Finally, in the remote content, you need to put the entire structure to work.

<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
            <a href="#" class="btn btn-white" data-dismiss="modal">Close</a>
            <a href="#" class="btn btn-primary">Button</a>
            <a href="#" class="btn btn-primary">Another button...</a>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

The FailedPreconditionError arises because the program is attempting to read a variable (named "Variable_1") before it has been initialized. In TensorFlow, all variables must be explicitly initialized, by running their "initializer" operations. For convenience, you can run all of the variable initializers in the current session by executing the following statement before your training loop:

tf.initialize_all_variables().run()

Note that this answer assumes that, as in the question, you are using tf.InteractiveSession, which allows you to run operations without specifying a session. For non-interactive uses, it is more common to use tf.Session, and initialize as follows:

init_op = tf.initialize_all_variables()

sess = tf.Session()
sess.run(init_op)

Maven error "Failure to transfer..."

for mac

I removed all the old failed downloads of maven there were several versions of maven also on my mac

find ~/.m2 -name "*.lastUpdated" -exec grep -q "Could not transfer" {} ; -print -exec rm {} ;

after that, I simply updated my eclipse by

help -> check for updates

and the problem resolved for me

the main reason for this problem is the failed old updates does not allow you to download archetype so if you try to build project in any archetype of maven it gets failed

What is the difference between persist() and merge() in JPA and Hibernate?

This is coming from JPA. In a very simple way:

  • persist(entity) should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).

  • merge(entity) should be used, to put entity back to persistence context if the entity was detached and was changed.

How to change Apache Tomcat web server port number

1) Locate server.xml in {Tomcat installation folder}\ conf \ 2) Find following similar statement

       <!-- Define a non-SSL HTTP/1.1 Connector on port 8180 -->
      <Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

For example

<Connector port="8181" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Edit and save the server.xml file. Restart Tomcat. Done

Further reference: http://www.mkyong.com/tomcat/how-to-change-tomcat-default-port/

Update Top 1 record in table sql server

UPDATE TX_Master_PCBA
SET TIMESTAMP2 = '2013-12-12 15:40:31.593',
G_FIELD='0000'
WHERE TIMESTAMP2 IN 
(
   SELECT TOP 1 TIMESTAMP2
   FROM TX_Master_PCBA WHERE SERIAL_NO='0500030309'
   ORDER BY TIMESTAMP2 DESC   -- You need to decide what column you want to sort on
)

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

You could use a recursive scalar function:-

set nocount on

create table location (
    id int,
    name varchar(50),
    parent int
)
insert into location values
    (1,'france',null),
    (2,'paris',1),
    (3,'belleville',2),
    (4,'lyon',1),
    (5,'vaise',4),
    (6,'united kingdom',null),
    (7,'england',6),
    (8,'manchester',7),
    (9,'fallowfield',8),
    (10,'withington',8)
go
create function dbo.breadcrumb(@child int)
returns varchar(1024)
as begin
    declare @returnValue varchar(1024)=''
    declare @parent int
    select @returnValue+=' > '+name,@parent=parent
    from location
    where id=@child
    if @parent is not null
        set @returnValue=dbo.breadcrumb(@parent)+@returnValue
    return @returnValue
end
go

declare @location int=1
while @location<=10 begin
    print dbo.breadcrumb(@location)+' >'
    set @location+=1
end

produces:-

 > france >
 > france > paris >
 > france > paris > belleville >
 > france > lyon >
 > france > lyon > vaise >
 > united kingdom >
 > united kingdom > england >
 > united kingdom > england > manchester >
 > united kingdom > england > manchester > fallowfield >
 > united kingdom > england > manchester > withington >

Call js-function using JQuery timer

function run() {
    window.setTimeout(
         "run()",
         1000
    );
}

Add text at the end of each line

Using a text editor, check for ^M (control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line.

sed -i 's|^M||g' ips.txt
sed -i 's|$|:80|g' ips.txt

Appending a line break to an output file in a shell script

Try:

echo "`date` User `whoami` started the script."$'\n' >> output.log

or just:

echo $'\n' >> output.log

SQL Add foreign key to existing column

If the table has already been created:

First do:

ALTER TABLE `table1_name` ADD UNIQUE( `column_name`);

Then:

ALTER TABLE `table1_name` ADD FOREIGN KEY (`column_name`) REFERENCES `table2_name`(`column_name`);

Clear text in EditText when entered

For Kotlin:

Create two extensions, one for EditText and one for TextView

EditText:

fun EditText.clear() { text.clear() }

TextView:

fun TextView.clear() { text = "" }

and use it like

myEditText.clear()

myTextView.clear()

How to get a specific output iterating a hash in Ruby?

hash.each do |key, array|
  puts "#{key}-----"
  puts array
end

Regarding order I should add, that in 1.8 the items will be iterated in random order (well, actually in an order defined by Fixnum's hashing function), while in 1.9 it will be iterated in the order of the literal.

How to generate unique ID with node.js

nanoid achieves exactly the same thing that you want.

Example usage:

const { nanoid } = require("nanoid")

console.log(nanoid())
//=> "n340M4XJjATNzrEl5Qvsh"

How to read a .properties file which contains keys that have a period character using Shell script

@fork2x

I have tried like this .Please review and update me whether it is right approach or not.

#/bin/sh
function pause(){
   read -p "$*"
}

file="./apptest.properties"


if [ -f "$file" ]
then
    echo "$file found."

dbUser=`sed '/^\#/d' $file | grep 'db.uat.user'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
dbPass=`sed '/^\#/d' $file | grep 'db.uat.passwd'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`

echo database user = $dbUser
echo database pass = $dbPass

else
    echo "$file not found."
fi

PHP PDO with foreach and fetch

A PDOStatement (which you have in $users) is a forward-cursor. That means, once consumed (the first foreach iteration), it won't rewind to the beginning of the resultset.

You can close the cursor after the foreach and execute the statement again:

$users       = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

$users->execute();

foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Or you could cache using tailored CachingIterator with a fullcache:

$users       = $dbh->query($sql);

$usersCached = new CachedPDOStatement($users);

foreach ($usersCached as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($usersCached as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

You find the CachedPDOStatement class as a gist. The caching itertor is probably more sane than storing the resultset into an array because it still offers all properties and methods of the PDOStatement object it has wrapped.

Where to get this Java.exe file for a SQL Developer installation

You need to install JAVA SDK and give the path upto bin directory which contains the java.exe file.

example - c:/programfiles/java/jdk/bin

How to set JFrame to appear centered, regardless of monitor resolution?

Use setLocationRelativeTo(null)

This method has a special effect when you pass it a null. According to the Javadoc:

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

This should be done after setting the size or calling pack(), but before setting it visible, like this:

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

How to write a PHP ternary operator

To be honest, a ternary operator would only make this worse, what i would suggest if making it simpler is what you are aiming at is:

$groups = array(1=>"Player", 2=>"Gamemaster", 3=>"God");
echo($groups[$result->group_id]);

and then a similar one for your vocations

$vocations = array(
  1=>"Sorcerer",
  2=>"Druid",
  3=>"Paladin",
  4=>"Knight",
  ....
);
echo($vocations[$result->vocation]);

With a ternary operator, you would end up with

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

Which as you can tell, only gets more complicated the more you add to it

How do I get my page title to have an icon?

Apparently you can use this trick.

<title> My title</title>

That icon-alike is actually a text.

How to restart kubernetes nodes?

If a node is so unhealthy that the master can't get status from it -- Kubernetes may not be able to restart the node. And if health checks aren't working, what hope do you have of accessing the node by SSH?

In this case, you may have to hard-reboot -- or, if your hardware is in the cloud, let your provider do it.

For example, the AWS EC2 Dashboard allows you to right-click an instance to pull up an "Instance State" menu -- from which you can reboot/terminate an unresponsive node.

Before doing this, you might choose to kubectl cordon node for good measure. And you may find kubectl delete node to be an important part of the process for getting things back to normal -- if the node doesn't automatically rejoin the cluster after a reboot.


Why would a node become unresponsive? Probably some resource has been exhausted in a way that prevents the host operating system from handling new requests in a timely manner. This could be disk, or network -- but the more insidious case is out-of-memory (OOM), which Linux handles poorly.

To help Kubernetes manage node memory safely, it's a good idea to do both of the following:

  • Reserve some memory for the system.
  • Be very careful with (avoid) opportunistic memory specifications for your pods. In other words, don't allow different values of requests and limits for memory.

The idea here is to avoid the complications associated with memory overcommit, because memory is incompressible, and both Linux and Kubernetes' OOM killers may not trigger before the node has already become unhealthy and unreachable.

Tell Ruby Program to Wait some amount of time

I find until very useful with sleep. example:

> time = Time.now
> sleep 2.seconds until Time.now > time + 10.seconds # breaks when true
# or something like
> sleep 1.seconds until !req.loading # suggested by ohsully

How to change file encoding in NetBeans?

The NetBeans documentation merely states a hierarchy for FileEncodingQuery (FEQ), suggesting that you can set encoding on a per-file basis:

Just for reference, this is the wiki-page regarding project-wide settings:

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

If you are trying to add a custom header on the request headers, you have to let the server know that specific header is allowed to take place. The place to do that is in the class that filters the requests. In the example shown below, the custom header name is "type":

public class CorsFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin",  request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, Authorization, type ");
        response.setHeader("Access-Control-Expose-Headers","Authorization");
    }
}

How to set background color of a button in Java GUI?

Check out JButton documentation. Take special attention to setBackground and setForeground methods inherited from JComponent.

Something like:

for(int i=1;i<=9;i++)
{
    JButton btn = new JButton(String.valueOf(i));
    btn.setBackground(Color.BLACK);
    btn.setForeground(Color.GRAY);
    p3.add(btn);
}

How to find the highest value of a column in a data frame in R?

Similar to colMeans, colSums, etc, you could write a column maximum function, colMax, and a column sort function, colSort.

colMax <- function(data) sapply(data, max, na.rm = TRUE)
colSort <- function(data, ...) sapply(data, sort, ...)

I use ... in the second function in hopes of sparking your intrigue.

Get your data:

dat <- read.table(h=T, text = "Ozone Solar.R Wind Temp Month Day
1     41     190  7.4   67     5   1
2     36     118  8.0   72     5   2
3     12     149 12.6   74     5   3
4     18     313 11.5   62     5   4
5     NA      NA 14.3   56     5   5
6     28      NA 14.9   66     5   6
7     23     299  8.6   65     5   7
8     19      99 13.8   59     5   8
9      8      19 20.1   61     5   9")

Use colMax function on sample data:

colMax(dat)
#  Ozone Solar.R    Wind    Temp   Month     Day 
#   41.0   313.0    20.1    74.0     5.0     9.0

To do the sorting on a single column,

sort(dat$Solar.R, decreasing = TRUE)
# [1] 313 299 190 149 118  99  19

and over all columns use our colSort function,

colSort(dat, decreasing = TRUE) ## compare with '...' above

Is it possible to make desktop GUI application in .NET Core?

If you are using .NET Core 3.0 and above, do the following steps and you are good to go: (I'm going to use .NET Core CLI, but you can use Visual Studio too):

  1. md MyWinFormsApp optional step
  2. cd MyWinFormsApp optional step
  3. dotnet new sln -n MyWinFormsApp optional step, but it's a good idea
  4. dotnet new winforms -n MyWinFormsApp I'm sorry, this is not optional
  5. dotnet sln add MyWinFormsApp do this if you did step #3

Okay, you can stop reading my answer and start adding code to the MyWinFormsApp project. But if you want to work with Form Designer, keep reading.

  1. Open up MyWinFormsApp.csproj file and change <TargetFramework>netcoreapp3.1<TargetFramework> to <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks> (if you are using netcoreapp3.0 don't worry. Change it to <TargetFrameworks>net472;netcoreapp3.0</TargetFrameworks>)
  2. Then add the following ItemGroup
  <ItemGroup Condition="'$(TargetFramework)' == 'net472'">
    <Compile Update="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Update="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
  </ItemGroup>

After doing these steps, this is what you should end up with:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net472'">
    <Compile Update="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Update="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
  </ItemGroup>

</Project>
  1. Open up file Program.cs and add the following preprocessor-if
#if NETCOREAPP3_1
    Application.SetHighDpiMode(HighDpiMode.SystemAware);
#endif

Now you can open the MyWinFormsApp project using Visual Studio 2019 (I think you can use Visual Studio 2017 too, but I'm not sure) and double click on Form1.cs and you should see this:

Enter image description here

Okay, open up Toolbox (Ctrl + W, X) and start adding controls to your application and make it pretty.

You can read more about designer at Windows Forms .NET Core Designer.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

I was getting the same error, found out it was due to some of the dependencies missing in my pom.xml like that of Spring JPA, Hibernate, Mysql or maybe Jackson. So make sure that dependencies are not missing in your pom.xml and check their version compatibility.

<!-- Jpa and hibernate -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>4.2.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>5.0.3.Final</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

Event binding on dynamically created elements?

As of jQuery 1.7 you should use jQuery.fn.on with the selector parameter filled:

$(staticAncestors).on(eventName, dynamicChild, function() {});

Explanation:

This is called event delegation and works as followed. The event is attached to a static parent (staticAncestors) of the element that should be handled. This jQuery handler is triggered every time the event triggers on this element or one of the descendant elements. The handler then checks if the element that triggered the event matches your selector (dynamicChild). When there is a match then your custom handler function is executed.


Prior to this, the recommended approach was to use live():

$(selector).live( eventName, function(){} );

However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:

$(selector).live( eventName, function(){} );

... can be replaced with the following on() signature:

$(document).on( eventName, selector, function(){} );

For example, if your page was dynamically creating elements with the class name dosomething you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document. Though bear in mind document may not be the most efficient option.

$(document).on('mouseover mouseout', '.dosomething', function(){
    // what you want to happen when mouseover and mouseout 
    // occurs on elements that match '.dosomething'
});

Any parent that exists at the time the event is bound is fine. For example

$('.buttons').on('click', 'button', function(){
    // do something here
});

would apply to

<div class="buttons">
    <!-- <button>s that are generated dynamically and added here -->
</div>

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

You can change the send line to this:

c.send(b'Thank you for connecting')

The b makes it bytes instead.

Restore the mysql database from .frm files

After much trial and error I was able to get this working based on user359187 answer and this blog post.

To get my old .frm and .ibd transferred to a new MySQL database after copying the files over and assigning MySQL ownership, the key for me was to then log into MySQL and connect to the new database then let MySQL do the work by importing the tablespace.

mysql> connect test;
mysql> ALTER TABLE t1 IMPORT TABLESPACE;

This will import the data using the copied .frm and .ibd files.

I had to run the Alter command for each table separately but this worked and I was able to recover the tables and data.

Spring Boot application.properties value not populating

This answer may or may not be applicable to your case ... Once I had a similar symptom and I double checked my code many times and all looked good but the @Value setting was still not taking effect. And then after doing File > Invalidate Cache / Restart with my IntelliJ (my IDE), the problem went away ...

This is very easy to try so may be worth a shot

jQuery form validation on button click

Within your click handler, the mistake is the .validate() method; it only initializes the plugin, it does not validate the form.

To eliminate the need to have a submit button within the form, use .valid() to trigger a validation check...

$('#btn').on('click', function() {
    $("#form1").valid();
});

jsFiddle Demo

.validate() - to initialize the plugin (with options) once on DOM ready.

.valid() - to check validation state (boolean value) or to trigger a validation test on the form at any time.

Otherwise, if you had a type="submit" button within the form container, you would not need a special click handler and the .valid() method, as the plugin would capture that automatically.

Demo without click handler


EDIT:

You also have two issues within your HTML...

<input id="field1" type="text" class="required">
  • You don't need class="required" when declaring rules within .validate(). It's redundant and superfluous.

  • The name attribute is missing. Rules are declared within .validate() by their name. The plugin depends upon unique name attributes to keep track of the inputs.

Should be...

<input name="field1" id="field1" type="text" />

Fastest way to extract frames using ffmpeg?

Output one image every minute, named img001.jpg, img002.jpg, img003.jpg, etc. The %03d dictates that the ordinal number of each output image will be formatted using 3 digits.

ffmpeg -i myvideo.avi -vf fps=1/60 img%03d.jpg

Change the fps=1/60 to fps=1/30 to capture a image every 30 seconds. Similarly if you want to capture a image every 5 seconds then change fps=1/60 to fps=1/5

SOURCE: https://trac.ffmpeg.org/wiki/Create a thumbnail image every X seconds of the video

Ruby: What is the easiest way to remove the first element from an array?

Use shift method

array.shift(n) => Remove first n elements from array 
array.shift(1) => Remove first element

https://ruby-doc.org/core-2.2.0/Array.html#method-i-shift

How can one use multi threading in PHP applications

How about pcntl_fork?

check our the manual page for examples: PHP pcntl_fork

<?php

    $pid = pcntl_fork();
    if ($pid == -1) {
        die('could not fork');
    } else if ($pid) {
        // we are the parent
        pcntl_wait($status); //Protect against Zombie children
    } else {
        // we are the child
    }

?>

How to set all elements of an array to zero or any same value?

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 };    // Will initialize all elements to 0
int myArray[10] = { 5 };    // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0
/************************************************************************************/
int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i;  // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
    myArray[i] = 5;
}
/************************************************************************************/
int myArray[10] = {[0 ... 9] = 5}; // This works only in GCC

Can't start Eclipse - Java was started but returned exit code=13

In my case, I have two different JDK that is IBM and Oracle JDK. I moved IBM JDK to the top of the Oracle JDK in environment variable then it worked. Note: I am going to use IBM JDK so I moved up.

SQL - Query to get server's IP address

You can get the[hostname]\[instancename] by:

SELECT @@SERVERNAME;

To get only the hostname when you have hostname\instance name format:

SELECT LEFT(ltrim(rtrim(@@ServerName)), Charindex('\', ltrim(rtrim(@@ServerName))) -1)

Alternatively as @GilM pointed out:

SELECT SERVERPROPERTY('MachineName')

You can get the actual IP address using this:

create Procedure sp_get_ip_address (@ip varchar(40) out)
as
begin
Declare @ipLine varchar(200)
Declare @pos int
set nocount on
          set @ip = NULL
          Create table #temp (ipLine varchar(200))
          Insert #temp exec master..xp_cmdshell 'ipconfig'
          select @ipLine = ipLine
          from #temp
          where upper (ipLine) like '%IP ADDRESS%'
          if (isnull (@ipLine,'***') != '***')
          begin 
                set @pos = CharIndex (':',@ipLine,1);
                set @ip = rtrim(ltrim(substring (@ipLine , 
               @pos + 1 ,
                len (@ipLine) - @pos)))
           end 
drop table #temp
set nocount off
end 
go

declare @ip varchar(40)
exec sp_get_ip_address @ip out
print @ip

Source of the SQL script.

Spring-boot default profile for integration tests

Come 2021 and Spring Boot 2.4 the solution I have found is to have 3 properties files

  • src/main/resources/application.yml - contains the application's default props
  • src/test/resources/application.yml - sets the profile to 'test', and imports properties from 'main'
  • src/test/resources/application-test.yml - contains test-specific profiles, which will override 'main'

Here is the content of src/test/resources/application.yml:

# for testing, set default profile to 'test'
spring.profiles.active: "test"
# and import the 'main' properties
spring.config.import: file:src/main/resources/application.yml

For example, if src/main/resources/application.yml has the content

ip-address: "10.7.0.1"
username: admin

and src/test/resources/application-test.yml has

ip-address: "999.999.999.999"
run-integration-test: true

Then (assuming there are no other profiles)...

when running tests,

profiles=test
--
ip-address=999.999.999.999
username=admin
run-integration-test=true

and when running the application normally

profiles=none
--
ip-address=10.7.0.1
username=admin
run-integration-test <undefined>

JavaFX Application Icon

stage.getIcons().add(new Image("/images/logo_only.png"));

It is good habit to make images folder in your src folder and get images from it.

How to validate a credit card number

These are my two cents.

Note #1: this is not a perfect validation method, but it is OK for my needs.
Note #2: IIN ranges can be changed (and will be), so it is a good idea to check this link to be sure that we are up to date.

function validateCCNum(ccnum)
{
    var ccCheckRegExp = /[^\d\s-]/;
    var isValid = !ccCheckRegExp.test(ccnum);
    var i;

    if (isValid) {
        var cardNumbersOnly = ccnum.replace(/[\s-]/g,"");
        var cardNumberLength = cardNumbersOnly.length;

        var arrCheckTypes = ['visa', 'mastercard', 'amex', 'discover', 'dinners', 'jcb'];
        for(i=0; i<arrCheckTypes.length; i++) {
            var lengthIsValid = false;
            var prefixIsValid = false;
            var prefixRegExp;

            switch (arrCheckTypes[i]) {
                case "mastercard":
                    lengthIsValid = (cardNumberLength === 16);
                    prefixRegExp = /5[1-5][0-9]|(2(?:2[2-9][^0]|2[3-9]|[3-6]|22[1-9]|7[0-1]|72[0]))\d*/;
                    break;

                case "visa":
                    lengthIsValid = (cardNumberLength === 16 || cardNumberLength === 13);
                    prefixRegExp = /^4/;
                    break;

                case "amex":
                    lengthIsValid = (cardNumberLength === 15);
                    prefixRegExp = /^3([47])/;
                    break;

                case "discover":
                    lengthIsValid = (cardNumberLength === 15 || cardNumberLength === 16);
                    prefixRegExp = /^(6011|5)/;
                    break;

                case "dinners":
                    lengthIsValid = (cardNumberLength === 14);
                    prefixRegExp = /^(300|301|302|303|304|305|36|38)/;
                    break;

                case "jcb":
                    lengthIsValid = (cardNumberLength === 15 || cardNumberLength === 16);
                    prefixRegExp = /^(2131|1800|35)/;
                    break;

                default:
                    prefixRegExp = /^$/;
            }

            prefixIsValid = prefixRegExp.test(cardNumbersOnly);
            isValid = prefixIsValid && lengthIsValid;

            // Check if we found a correct one
            if(isValid) {
                break;
            }
        }
    }

    if (!isValid) {
        return false;
    }

    // Remove all dashes for the checksum checks to eliminate negative numbers
    ccnum = ccnum.replace(/[\s-]/g,"");
    // Checksum ("Mod 10")
    // Add even digits in even length strings or odd digits in odd length strings.
    var checksum = 0;
    for (i = (2 - (ccnum.length % 2)); i <= ccnum.length; i += 2) {
        checksum += parseInt(ccnum.charAt(i - 1));
    }

    // Analyze odd digits in even length strings or even digits in odd length strings.
    for (i = (ccnum.length % 2) + 1; i < ccnum.length; i += 2) {
        var digit = parseInt(ccnum.charAt(i - 1)) * 2;
        if (digit < 10) {
            checksum += digit;
        } else {
            checksum += (digit - 9);
        }
    }

    return (checksum % 10) === 0;
}

Thanks to @Peter Mortensen for the comment :)

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

Inverse of matrix in R

Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 

Syntax behind sorted(key=lambda: ...)

Another usage of lambda and sorted is like the following:

Given the input array: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]

The line: people_sort = sorted(people, key = lambda x: (-x[0], x[1])) will give a people_sort list as [[7,0],[7,1],[6,1],[5,0],[5,2],[4,4]]

In this case, key=lambda x: (-x[0], x[1]) basically tells sorted to firstly sort the array based on the value of the first element of each of the instance(in descending order as the minus sign suggests), and then within the same subgroup, sort based on the second element of each of the instance(in ascending order as it is the default option).

Hope this is some useful information to you!

Can I set an unlimited length for maxJsonLength in web.config?

Just ran into this. I'm getting over 6,000 records. Just decided I'd just do some paging. As in, I accept a page number in my MVC JsonResult endpoint, which is defaulted to 0 so it's not necessary, like so:

public JsonResult MyObjects(int pageNumber = 0)

Then instead of saying:

return Json(_repository.MyObjects.ToList(), JsonRequestBehavior.AllowGet);

I say:

return Json(_repository.MyObjects.OrderBy(obj => obj.ID).Skip(1000 * pageNumber).Take(1000).ToList(), JsonRequestBehavior.AllowGet);

It's very simple. Then, in JavaScript, instead of this:

function myAJAXCallback(items) {
    // Do stuff here
}

I instead say:

var pageNumber = 0;
function myAJAXCallback(items) {
    if(items.length == 1000)
        // Call same endpoint but add this to the end: '?pageNumber=' + ++pageNumber
    }
    // Do stuff here
}

And append your records to whatever you were doing with them in the first place. Or just wait until all the calls finish and cobble the results together.

How to get an absolute file path in Python

import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))

Note that expanduser is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading ~/(the tilde refers to the user's home directory), and expandvars takes care of any other environment variables (like $HOME).

Bootstrap 3 Flush footer to bottom. not fixed

For a pure CSS solution, scroll after the 2nd <hr>. The first one is the initial answer (given back in 2016)


The major flaw of the solutions above is they have a fixed height for the footer.
And that just doesn't cut it in the real world, where people use a zillion number of devices and have this bad habit of rotating them when you least expect it and **Poof!** there goes your page content behind the footer!

In the real world, you need a function that calculates the height of the footer and dynamically adjusts the page content's padding-bottom to accommodate that height. And you need to run this tiny function on page load and resize events as well as on footer's DOMSubtreeModified (just in case your footer gets dynamically updated asynchronously or it contains animated elements that change size when interacted with).

Here's a proof of concept, using jQuery v3.0.0 and Bootstrap v4-alpha, but there is no reason why it shouldn't work on lower versions of each.

_x000D_
_x000D_
jQuery(document).ready(function($) {_x000D_
  $.fn.accomodateFooter = function() {_x000D_
    var footerHeight = $('footer').outerHeight();_x000D_
    $(this).css({_x000D_
      'padding-bottom': footerHeight + 'px'_x000D_
    });_x000D_
  }_x000D_
  $('footer').on('DOMSubtreeModified', function() {_x000D_
    $('body').accomodateFooter();_x000D_
  })_x000D_
  $(window).on('resize', function() {_x000D_
    $('body').accomodateFooter();_x000D_
  })_x000D_
  $('body').accomodateFooter();_x000D_
  window.addMoreContentToFooter = function() {_x000D_
    var f = $('footer');_x000D_
    f.append($('<p />', {_x000D_
        text: "Human give me attention meow flop over sun bathe licks your face wake up wander around the house making large amounts of noise jump on top of your human's bed and fall asleep again. Throwup on your pillow sun bathe. The dog smells bad jump around on couch, meow constantly until given food, so nap all day, yet hiss at vacuum cleaner."_x000D_
      }))_x000D_
      .append($('<hr />'));_x000D_
  }_x000D_
});
_x000D_
body {_x000D_
  min-height: 100vh;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background-color: rgba(0, 0, 0, .65);_x000D_
  color: white;_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  width: 100%;_x000D_
  padding: 1.5rem;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
footer hr {_x000D_
  border-top: 1px solid rgba(0, 0, 0, .42);_x000D_
  border-bottom: 1px solid rgba(255, 255, 255, .21);_x000D_
}
_x000D_
<link href="http://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">_x000D_
<link href="http://v4-alpha.getbootstrap.com/examples/starter-template/starter-template.css" rel="stylesheet">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.2.0/js/tether.min.js"></script>_x000D_
<script src="http://v4-alpha.getbootstrap.com/dist/js/bootstrap.min.js"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse fixed-top">_x000D_
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">_x000D_
        <span class="navbar-toggler-icon"></span>_x000D_
      </button>_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
_x000D_
  <div class="collapse navbar-collapse" id="navbarsExampleDefault">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link</a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link disabled" href="#">Disabled</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>_x000D_
        <div class="dropdown-menu" aria-labelledby="dropdown01">_x000D_
          <a class="dropdown-item" href="#">Action</a>_x000D_
          <a class="dropdown-item" href="#">Another action</a>_x000D_
          <a class="dropdown-item" href="#">Something else here</a>_x000D_
        </div>_x000D_
      </li>_x000D_
    </ul>_x000D_
    <form class="form-inline my-2 my-lg-0">_x000D_
      <input class="form-control mr-sm-2" type="text" placeholder="Search">_x000D_
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
    </form>_x000D_
  </div>_x000D_
</nav>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="starter-template">_x000D_
    <h1>Feed that footer - not a game (yet!)</h1>_x000D_
    <p class="lead">You will notice the body bottom padding is growing to accomodate the height of the footer as you feed it (so the page contents do not get covered by it).</p><button class="btn btn-warning" onclick="window.addMoreContentToFooter()">Feed that footer</button>_x000D_
    <hr />_x000D_
    <blockquote class="lead"><strong>Note:</strong> I used jQuery <code>v3.0.0</code> and Bootstrap <code>v4-alpha</code> but there is no reason why it shouldn't work with lower versions of each.</blockquote>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<footer>I am a footer with dynamic content._x000D_
  <hr />_x000D_
</footer>
_x000D_
_x000D_
_x000D_

Initially, I have posted this solution here but I realized it might help more people if posted under this question.

Note: I have purposefully wrapped the $([selector]).accomodateFooter() as a jQuery plugin, so it could be run on any DOM element, as in most layouts it is not the $('body')'s bottom-padding that needs adjusting, but some page wrapper element with position:relative (usually the immediate parent of the footer).


Later edit (3+ years after initial answer):

At this point I no longer consider acceptable using JavaScript for positioning a dynamic content footer at the bottom of the page. It can be achieved with CSS alone, using flexbox, lightning fast, cross-browser.

Here it is:

_x000D_
_x000D_
// Left this in so you could inject content into the footer and test it:_x000D_
// (but it's no longer sizing the footer)_x000D_
_x000D_
function addMoreContentToFooter() {_x000D_
  var f = $('footer');_x000D_
  f.append($('<p />', {_x000D_
      text: "Human give me attention meow flop over sun bathe licks your face wake up wander around the house making large amounts of noise jump on top of your human's bed and fall asleep again. Throwup on your pillow sun bathe. The dog smells bad jump around on couch, meow constantly until given food, so nap all day, yet hiss at vacuum cleaner."_x000D_
    }))_x000D_
    .append($('<hr />'));_x000D_
}
_x000D_
.wrapper {_x000D_
  min-height: 100vh;_x000D_
  padding-top: 54px;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
.wrapper>* {_x000D_
  flex-grow: 0;_x000D_
}_x000D_
_x000D_
.wrapper>main {_x000D_
  flex-grow: 1;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background-color: rgba(0, 0, 0, .65);_x000D_
  color: white;_x000D_
  width: 100%;_x000D_
  padding: 1.5rem;_x000D_
}_x000D_
_x000D_
footer hr {_x000D_
  border-top: 1px solid rgba(0, 0, 0, .42);_x000D_
  border-bottom: 1px solid rgba(255, 255, 255, .21);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="wrapper">_x000D_
  <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
_x000D_
  <div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown_x000D_
        </a>_x000D_
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">_x000D_
          <a class="dropdown-item" href="#">Action</a>_x000D_
          <a class="dropdown-item" href="#">Another action</a>_x000D_
          <div class="dropdown-divider"></div>_x000D_
          <a class="dropdown-item" href="#">Something else here</a>_x000D_
        </div>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
    <form class="form-inline my-2 my-lg-0">_x000D_
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">_x000D_
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
    </form>_x000D_
  </div>_x000D_
</nav>_x000D_
  <main>_x000D_
    <div class="container">_x000D_
      <div class="starter-template">_x000D_
        <h1>Feed that footer - not a game (yet!)</h1>_x000D_
        <p class="lead">Footer won't ever cover the body contents, as its not fixed. It's simply placed at the bottom when the page should be shorter using `min-height:100vh` on container and using flexbox to push it down.</p><button class="btn btn-warning" onclick="addMoreContentToFooter()">Feed that footer</button>_x000D_
        <hr />_x000D_
        <blockquote class="lead">_x000D_
          <strong>Note:</strong> This example uses current latest versions of jQuery (<code>3.4.1.slim</code>) and Bootstrap (<code>4.4.1</code>) (unlike the one above)._x000D_
        </blockquote>_x000D_
      </div>_x000D_
    </div>_x000D_
  </main>_x000D_
  <footer>I am a footer with dynamic content._x000D_
    <hr />_x000D_
  </footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I turn a List of Lists into a List in Java 8?

flatmap is better but there are other ways to achieve the same

List<List<Object>> listOfList = ... // fill

List<Object> collect = 
      listOfList.stream()
                .collect(ArrayList::new, List::addAll, List::addAll);

Is there a way to specify a max height or width for an image?

You can try this one

img{
    max-height:500px;
    max-width:500px;
    height:auto;
    width:auto;
}

This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px

You can check this post

Clear screen in shell

using windows 10 and pyhton3.5 i have tested many codes and nothing helped me more than this:

First define a simple function, this funtion will print 50 newlines;(the number 50 will depend on how many lines you can see on your screen, so you can change this number)

def cls(): print ("\n" * 50)

then just call it as many times as you want or need

cls()

How do I check if a Key is pressed on C++

As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:

The Code below checks if the key 'A' is down.

if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
    // Do stuff
}

In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx

if(GetKeyState(VK_SHIFT) & 0x8000)
{
    // Shift down
}

The low-order bit indicates if key is toggled.

SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;

Oh and also don't forget to

#include <Windows.h>

Remove a specific character using awk or sed

Using just awk you could do (I also shortened some of your piping):

strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'

I can't verify it for you because I don't know your exact input, but the following works:

echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'

See also this question on removing single quotes.

Fixed page header overlaps in-page anchors

I'm using @Jpsy's answer, but for performance reasons I'm only setting the timer if the hash is present in the URL.

$(function() {
      // Only set the timer if you have a hash
      if(window.location.hash) {
        setTimeout(delayedFragmentTargetOffset, 500);
      }
  });

function delayedFragmentTargetOffset(){
      var offset = $(':target').offset();
      if(offset){
          var scrollto = offset.top - 80; // minus fixed header height
          $('html, body').animate({scrollTop:scrollto}, 0);
          $(':target').highlight();
      }
  };

How to convert date to timestamp?

Split the string into its parts and provide them directly to the Date constructor:

Update:

_x000D_
_x000D_
var myDate = "26-02-2012";
myDate = myDate.split("-");
var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]);
console.log(newDate.getTime());
_x000D_
_x000D_
_x000D_

Why is Tkinter Entry's get function returning nothing?

You could also use a StringVar variable, even if it's not strictly necessary:

v = StringVar()

e = Entry(master, textvariable=v)
e.pack()

v.set("a default value")
s = v.get()

For more information, see this page on effbot.org.

how do I join two lists using linq or lambda expressions

The way to do this using the Extention Methods, instead of the linq query syntax would be like this:

var results = workOrders.Join(plans,
  wo => wo.WorkOrderNumber,
  p => p.WorkOrderNumber,
  (order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);

Android: Reverse geocoding - getFromLocation

It looks like there's two things happening here.

1) You've missed the new keyword from before calling the constructor.

2) The parameter you're passing in to the Geocoder constructor is incorrect. You're passing in a Locale where it's expecting a Context.

There are two Geocoder constructors, both of which require a Context, and one also taking a Locale:

Geocoder(Context context, Locale locale)
Geocoder(Context context)

Solution

Modify your code to pass in a valid Context and include new and you should be good to go.

Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());   
List<Address> myList = myLocation.getFromLocation(latPoint, lngPoint, 1);

Note

If you're still having problems it may be a permissioning issue. Geocoding implicitly uses the Internet to perform the lookups, so your application will require an INTERNET uses-permission tag in your manifest.

Add the following uses-permission node within the manifest node of your manifest.

<uses-permission android:name="android.permission.INTERNET" />

Are there any free Xml Diff/Merge tools available?

I wrote and released a Windows application that specifically solves the problem of comparing and merging XML files.

Project: Merge can perform two and three way comparisons and merges of any XML file (where two of the files are considered to be independent revisions of a common base file). You can instruct it to identify elements within the input files by attribute values, or the content of child elements, among other things.

It is fully controllable via the command line and can also generate text reports containing the differences between the files.

Project: Merge merging three XML files

How do I temporarily disable triggers in PostgreSQL?

SET session_replication_role = replica; 

It doesn't work with PostgreSQL 9.4 on my Linux machine if i change a table through table editor in pgAdmin and works if i change table through ordinary query. Manual changes in pg_trigger table also don't work without server restart but dynamic query like on postgresql.nabble.com ENABLE / DISABLE ALL TRIGGERS IN DATABASE works. It could be useful when you need some tuning.

For example if you have tables in a particular namespace it could be:

create or replace function disable_triggers(a boolean, nsp character varying) returns void as
$$
declare 
act character varying;
r record;
begin
    if(a is true) then
        act = 'disable';
    else
        act = 'enable';
    end if;

    for r in select c.relname from pg_namespace n
        join pg_class c on c.relnamespace = n.oid and c.relhastriggers = true
        where n.nspname = nsp
    loop
        execute format('alter table %I %s trigger all', r.relname, act); 
    end loop;
end;
$$
language plpgsql;

If you want to disable all triggers with certain trigger function it could be:

create or replace function disable_trigger_func(a boolean, f character varying) returns void as
$$
declare 
act character varying;
r record;
begin
    if(a is true) then
        act = 'disable';
    else
        act = 'enable';
    end if;

    for r in select c.relname from pg_proc p 
        join pg_trigger t on t.tgfoid = p.oid
        join pg_class c on c.oid = t.tgrelid
        where p.proname = f
    loop
        execute format('alter table %I %s trigger all', r.relname, act); 
    end loop;
end;
$$
language plpgsql;

PostgreSQL documentation for system catalogs


There are another control options of trigger firing process:

ALTER TABLE ... ENABLE REPLICA TRIGGER ... - trigger will fire in replica mode only.

ALTER TABLE ... ENABLE ALWAYS TRIGGER ... - trigger will fire always (obviously)

multi line comment vb.net in Visual studio 2010

The only way I could do it in VS 2010 IDE was to highlight the block of code and hit ctrl-E and then C

Looping from 1 to infinity in Python

def infinity():
    i=0
    while True:
        i+=1
        yield i


for i in infinity():
    if there_is_a_reason_to_break(i):
        break

In Angular, how to redirect with $location.path as $http.post success callback

There is simple answer in the official guide:

What does it not do?

It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.

Source: https://docs.angularjs.org/guide/$location

Concatenating null strings in Java

Why must it work?

The JLS 5, Section 15.18.1.1 JLS 8 § 15.18.1 "String Concatenation Operator +", leading to JLS 8, § 5.1.11 "String Conversion", requires this operation to succeed without failure:

...Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

How does it work?

Let's look at the bytecode! The compiler takes your code:

String s = null;
s = s + "hello";
System.out.println(s); // prints "nullhello"

and compiles it into bytecode as if you had instead written this:

String s = null;
s = new StringBuilder(String.valueOf(s)).append("hello").toString();
System.out.println(s); // prints "nullhello"

(You can do so yourself by using javap -c)

The append methods of StringBuilder all handle null just fine. In this case because null is the first argument, String.valueOf() is invoked instead since StringBuilder does not have a constructor that takes any arbitrary reference type.

If you were to have done s = "hello" + s instead, the equivalent code would be:

s = new StringBuilder("hello").append(s).toString();

where in this case the append method takes the null and then delegates it to String.valueOf().

Note: String concatenation is actually one of the rare places where the compiler gets to decide which optimization(s) to perform. As such, the "exact equivalent" code may differ from compiler to compiler. This optimization is allowed by JLS, Section 15.18.1.2:

To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

The compiler I used to determine the "equivalent code" above was Eclipse's compiler, ecj.

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

Two steps worked for me : - going Macintosh HD > Applications > Python3.7 folder - click on "Install Certificates.command"

How to redirect to another page in node.js

Ok, I'll try to help you using one my examples. First of all, you need to know I am using express for my application directory structure and for creating files like app.js in an automatically way. My login.html looks like:

...
<div class="form">
<h2>Login information</h2>
<form action="/login" method = "post">
  <input type="text" placeholder="E-Mail" name="email" required/>
  <input type="password" placeholder="Password" name="password" required/>
  <button>Login</button>
</form>

The important thing here is action="/login". This is the path I use in my index.js (for navigating between the views) which look like this:

app.post('/login', passport.authenticate('login', {
    successRedirect : '/home', 
    failureRedirect : '/login', 
    failureFlash : true
}));

app.get('/home', function(request, response) {
        response.render('pages/home');
});

This allows me to redirect to another page after a succesful login. There is a helpful tutorial you could check out for redirecting between pages:

http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/

To read a statement like <%= user.attributes.name %> let's have a look at a simple profile.html which has the following structure:

<div id = "profile">
<h3>Profilinformationen</h3>
    <form>
        <fieldset>
            <label id = "usernameLabel">Username:</label>
            <input type = "text" id="usernameText" value = "<%= user.user.username %>" />
            <br>
        </fieldset>
    </form>

To get the the attributes of the user variable, you have to initialize a user variable in your routing.js (called index.js in my case). This looks like

app.get('/profile', auth, function(request, response) {
    response.render('pages/profile', {
        user : request.user
    });
});

I am using mongoose for my object model:

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');
var role     = require('./role');

var userSchema = mongoose.Schema({
    user             : {
        username     : String,
        email        : String,
        password     : String
    }
});

Ask me anytime for further questions... Best regards, Nazar

Best way to overlay an ESRI shapefile on google maps?

Free "Export to KML" script for ArcGIS 9

Here is a list of available methods that someone found.

Also, it seems to me that the most efficient representation of a polygon layer is by using Google Maps API's polyline encoding, which significantly compresses lat-lng data. But getting into that format takes work: use ArcMap to export Shape as lat/lng coordinates, then convert into polylines using Google Maps API.

How to convert a string to a date in sybase

102 is the rule of thumb, convert (varchar, creat_tms, 102) > '2011'

What is the opposite of :hover (on mouse leave)?

You have misunderstood :hover; it says the mouse is over an item, rather than the mouse has just entered the item.

You could add animation to the selector without :hover to achieve the effect you want.

Transitions is a better option: http://jsfiddle.net/Cvx96/

What causes a TCP/IP reset (RST) flag to be sent?

RST is sent by the side doing the active close because it is the side which sends the last ACK. So if it receives FIN from the side doing the passive close in a wrong state, it sends a RST packet which indicates other side that an error has occured.

Why is null an object and what's the difference between null and undefined?

typeof null;      // object
typeof undefined; // undefined

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

var x = null;
var y;

x is declared & defined as null

y is declared but not defined. It is declared with no value so it is undefined.

z is not declared so would also be undefined if you attempted to use z.

How to avoid precompiled headers

You can create an empty project by selecting the "Empty Project" from the "General" group of Visual C++ projects (maybe that project template isn't included in Express?).

To fix the problem in the project you already have, open the project properties and navigate to:

Configuration Properties | C/C++ | Precompiled Headers

And choose "Not using Precompiled Headers" for the "Precompiled Header" option.

'was not declared in this scope' error

Here

{int y=((year-1)%100);int c=(year-1)/100;}

you declare and initialize the variables y, c, but you don't used them at all before they run out of scope. That's why you get the unused message.

Later in the function, y, c are undeclared, because the declarations you made only hold inside the block they were made in (the block between the braces {...}).

Android getActivity() is undefined

If you want to call your activity, just use this . You use the getActivity method when you are inside a fragment.

How to capture multiple repeated groups?

The key distinction is repeating a captured group instead of capturing a repeated group.

As you have already found out, the difference is that repeating a captured group captures only the last iteration. Capturing a repeated group captures all iterations.

In PCRE (PHP):

((?:\w+)+),?
Match 1, Group 1.    0-5      HELLO
Match 2, Group 1.    6-11     THERE
Match 3, Group 1.    12-20    BRUTALLY
Match 4, Group 1.    21-26    CRUEL
Match 5, Group 1.    27-32    WORLD

Since all captures are in Group 1, you only need $1 for substitution.

I used the following general form of this regular expression:

((?:{{RE}})+)

Example at regex101

Change Schema Name Of Table In SQL

In case, someone looking for lower version -

For SQL Server 2000:

sp_changeobjectowner @objname = 'dbo.Employess' , @newowner ='exe'

C++ How do I convert a std::chrono::time_point to long and back

time_point objects only support arithmetic with other time_point or duration objects.

You'll need to convert your long to a duration of specified units, then your code should work correctly.

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

How can I select records ONLY from yesterday?

to_char(tran_date, 'yyyy-mm-dd') = to_char(sysdate-1, 'yyyy-mm-dd')

Returning a value from callback function in Node.js

Example code for node.js - async function to sync function:

var deasync = require('deasync');

function syncFunc()
{
    var ret = null;
    asyncFunc(function(err, result){
        ret = {err : err, result : result}
    });

    while((ret == null))
    {
         deasync.runLoopOnce();
    }

    return (ret.err || ret.result);
}

Accessing Google Spreadsheets with C# using Google Data API

You can do what you're asking several ways:

  1. Using Google's spreadsheet C# library (as in Tacoman667's answer) to fetch a ListFeed which can return a list of rows (ListEntry in Google parlance) each of which has a list of name-value pairs. The Google spreadsheet API (http://code.google.com/apis/spreadsheets/code.html) documentation has more than enough information to get you started.

  2. Using the Google visualization API which lets you submit more sophisticated (almost like SQL) queries to fetch only the rows/columns you require.

  3. The spreadsheet contents are returned as Atom feeds so you can use XPath or SAX parsing to extract the contents of a list feed. There is an example of doing it this way (in Java and Javascript only though I'm afraid) at http://gqlx.twyst.co.za.

Using Java 8 to convert a list of objects into a string obtained from the toString() method

StringListName = ObjectListName.stream().map( m -> m.toString() ).collect( Collectors.toList() );

How to convert a Java object (bean) to key-value pairs (and vice versa)?

Lots of potential solutions, but let's add just one more. Use Jackson (JSON processing lib) to do "json-less" conversion, like:

ObjectMapper m = new ObjectMapper();
Map<String,Object> props = m.convertValue(myBean, Map.class);
MyBean anotherBean = m.convertValue(props, MyBean.class);

(this blog entry has some more examples)

You can basically convert any compatible types: compatible meaning that if you did convert from type to JSON, and from that JSON to result type, entries would match (if configured properly can also just ignore unrecognized ones).

Works well for cases one would expect, including Maps, Lists, arrays, primitives, bean-like POJOs.

Best way to call a JSON WebService from a .NET Console

WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:

using (var client = new WebClient())
{
    var json = client.DownloadString("http://example.com/json");
    var serializer = new JavaScriptSerializer();
    SomeModel model = serializer.Deserialize<SomeModel>(json);
    // TODO: do something with the model
}

There are also some REST client frameworks you may checkout such as RestSharp.

Memcached vs. Redis?

Memcached will be faster if you are interested in performance, just even because Redis involves networking (TCP calls). Also internally Memcache is faster.

Redis has more features as it was mentioned by other answers.

How to find a parent with a known class in jQuery?

You can use parents() to get all parents with the given selector.

Description: Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

But parent() will get just the first parent of the element.

Description: Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

jQuery parent() vs. parents()

And there is .parentsUntil() which I think will be the best.

Description: Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.

Keeping it simple and how to do multiple CTE in a query

You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts and the second is named ProductsOverTenDollars.

WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

Configuring diff tool with .gitconfig

Git offers a range of difftools pre-configured "out-of-the-box" (kdiff3, kompare, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge, diffuse, opendiff, p4merge and araxis), and also allows you to specify your own. To use one of the pre-configured difftools (for example, "vimdiff"), you add the following lines to your ~/.gitconfig:

[diff]
    tool = vimdiff

Now, you will be able to run "git difftool" and use your tool of choice.

Specifying your own difftool, on the other hand, takes a little bit more work, see How do I view 'git diff' output with my preferred diff tool/ viewer?

PHP XML Extension: Not installed

I solved this issue with commands bellow:

$ sudo apt-get install php7.3-intl

$ sudo /etc/init.d/php7.3-fpm restart

These commands works for me in homestead with php7.3

Is there a way to cast float as a decimal without rounding and preserving its precision?

Have you tried:

SELECT Cast( 2.555 as decimal(53,8))

This would return 2.55500000. Is that what you want?

UPDATE:

Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:

SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')

returns 8|7

You may be able to use this in your conversion process...

Enable IIS7 gzip

If you use YSlow with Firebug and analyse your page performance, YSlow will certainly tell you what artifacts on your page are not gzip'd!

How to Use UTF-8 Collation in SQL Server database?

Two UDF to deal with UTF-8 in T-SQL:

CREATE Function UcsToUtf8(@src nvarchar(MAX)) returns varchar(MAX) as
begin
    declare @res varchar(MAX)='', @pi char(8)='%[^'+char(0)+'-'+char(127)+']%', @i int, @j int
    select @i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0
    begin
        select @j=unicode(substring(@src,@i,1))
        if @j<0x800     select @res=@res+left(@src,@i-1)+char((@j&1984)/64+192)+char((@j&63)+128)
        else            select @res=@res+left(@src,@i-1)+char((@j&61440)/4096+224)+char((@j&4032)/64+128)+char((@j&63)+128)
        select @src=substring(@src,@i+1,datalength(@src)-1), @i=patindex(@pi,@src collate Latin1_General_BIN)
    end
    select @res=@res+@src
    return @res
end

CREATE Function Utf8ToUcs(@src varchar(MAX)) returns nvarchar(MAX) as
begin
    declare @i int, @res nvarchar(MAX)=@src, @pi varchar(18)
    select @pi='%[à-ï][€-¿][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0 select @res=stuff(@res,@i,3,nchar(((ascii(substring(@src,@i,1))&31)*4096)+((ascii(substring(@src,@i+1,1))&63)*64)+(ascii(substring(@src,@i+2,1))&63))), @src=stuff(@src,@i,3,'.'), @i=patindex(@pi,@src collate Latin1_General_BIN)
    select @pi='%[Â-ß][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0 select @res=stuff(@res,@i,2,nchar(((ascii(substring(@src,@i,1))&31)*64)+(ascii(substring(@src,@i+1,1))&63))), @src=stuff(@src,@i,2,'.'),@i=patindex(@pi,@src collate Latin1_General_BIN)
    return @res
end

How to get the path of the batch script in Windows?

That would be the %CD% variable.

@echo off
echo %CD%

%CD% returns the current directory the batch script is in.

Quickly create a large file on a Linux system

One approach: if you can guarantee unrelated applications won't use the files in a conflicting manner, just create a pool of files of varying sizes in a specific directory, then create links to them when needed.

For example, have a pool of files called:

  • /home/bigfiles/512M-A
  • /home/bigfiles/512M-B
  • /home/bigfiles/1024M-A
  • /home/bigfiles/1024M-B

Then, if you have an application that needs a 1G file called /home/oracle/logfile, execute a "ln /home/bigfiles/1024M-A /home/oracle/logfile".

If it's on a separate filesystem, you will have to use a symbolic link.

The A/B/etc files can be used to ensure there's no conflicting use between unrelated applications.

The link operation is about as fast as you can get.

String formatting in Python 3

Here are the docs about the "new" format syntax. An example would be:

"({:d} goals, ${:d})".format(self.goals, self.penalties)

If both goals and penalties are integers (i.e. their default format is ok), it could be shortened to:

"({} goals, ${})".format(self.goals, self.penalties)

And since the parameters are fields of self, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):

"({0.goals} goals, ${0.penalties})".format(self)

Explaining:

  • {} means just the next positional argument, with default format;
  • {0} means the argument with index 0, with default format;
  • {:d} is the next positional argument, with decimal integer format;
  • {0:d} is the argument with index 0, with decimal integer format.

There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:

"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)

"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)

"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'

"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'

"games: {:>3}".format(player1.games)  # 'games: 123'
"games: {:>3}".format(player2.games)  # 'games:   4'
"games: {:0>3}".format(player2.games) # 'games: 004'

Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).

Split a large pandas dataframe

Be aware that np.array_split(df, 3) splits the dataframe into 3 sub-dataframes, while the split_dataframe function defined in @elixir's answer, when called as split_dataframe(df, chunk_size=3), splits the dataframe every chunk_size rows.

Example:

With np.array_split:

df = pd.DataFrame([1,2,3,4,5,6,7,8,9,10,11], columns=['TEST'])
df_split = np.array_split(df, 3)

...you get 3 sub-dataframes:

df_split[0] # 1, 2, 3, 4
df_split[1] # 5, 6, 7, 8
df_split[2] # 9, 10, 11

With split_dataframe:

df_split2 = split_dataframe(df, chunk_size=3)

...you get 4 sub-dataframes:

df_split2[0] # 1, 2, 3
df_split2[1] # 4, 5, 6
df_split2[2] # 7, 8, 9
df_split2[3] # 10, 11

Hope I'm right, and that this is useful.

Is there a code obfuscator for PHP?

Obfuscation is only adding another layer of potential bugs and security vulnerabilities to your program. Please don't do it.

The kind of people who write obfuscation software usually seem very sketchy and non-skilled anyway.

If your code is "great", crackers will go through great lengths to spread it, regardless of whether or not it is obfuscated. If nobody knows/cares about your code, they probably won't, either.

How to run travis-ci locally

Travis-ci offers a new container-based infrastructure that uses docker. This can be very useful if you're trying to troubleshoot a travis-ci build by reproducing it locally. This is taken from Travis CI's documentation.

Troubleshooting Locally in a Docker Image

If you're having trouble tracking down the exact problem in a build it often helps to run the build locally. To do this you need to be using our container based infrastructure (ie, have sudo: false in your .travis.yml), and to know which Docker image you are using on Travis CI.

Running a Container Based Docker Image Locally

  1. Download and install the Docker Engine.
  2. Select an image from Docker Hub. If you're not using a language-specific image pick ci-ruby. Open a terminal and start an interactive Docker session using the image URL:

    docker run -it travisci/ubuntu-ruby:18.04 /bin/bash
    
  3. Switch to the travis user:

    su - travis
    
  4. Clone your git repository into the / folder of the image.
  5. Manually install any dependencies.
  6. Manually run your Travis CI build command.

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Why use getters and setters/accessors?

Getter and setter methods are accessor methods, meaning that they are generally a public interface to change private class members. You use getter and setter methods to define a property. You access getter and setter methods as properties outside the class, even though you define them within the class as methods. Those properties outside the class can have a different name from the property name in the class.

There are some advantages to using getter and setter methods, such as the ability to let you create members with sophisticated functionality that you can access like properties. They also let you create read-only and write-only properties.

Even though getter and setter methods are useful, you should be careful not to overuse them because, among other issues, they can make code maintenance more difficult in certain situations. Also, they provide access to your class implementation, like public members. OOP practice discourages direct access to properties within a class.

When you write classes, you are always encouraged to make as many as possible of your instance variables private and add getter and setter methods accordingly. This is because there are several times when you may not want to let users change certain variables within your classes. For example, if you have a private static method that tracks the number of instances created for a specific class, you don't want a user to modify that counter using code. Only the constructor statement should increment that variable whenever it's called. In this situation, you might create a private instance variable and allow a getter method only for the counter variable, which means users are able to retrieve the current value only by using the getter method, and they won't be able to set new values using the setter method. Creating a getter without a setter is a simple way of making certain variables in your class read-only.

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

Cleanest version specially good if you just want to get the .value from the element.

document.getElementById('elementsid') ? function_if_exists(); function_if_doesnt_exists();

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

I got that error when I was deleting some rows in the DB (in the loop), and the adding the new ones in the same table.

The solutions for me was, to dynamicaly create a new context in each loop iteration

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

UPDATE:

onActivityCreated() is deprecated from API Level 28.


onCreate():

The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView().
In this method, you can assign variables, get Intent extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity's onCreate() is not finished, and so trying to access the View hierarchy here may result in a crash.

onCreateView():

After the onCreate() is called (in the Fragment), the Fragment's onCreateView() is called. You can assign your View variables and do any graphical initialisations. You are expected to return a View from this method, and this is the main UI view, but if your Fragment does not use any layouts or graphics, you can return null (happens by default if you don't override).

onActivityCreated():

As the name states, this is called after the Activity's onCreate() has completed. It is called after onCreateView(), and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.


To sum up...
... they are all called in the Fragment but are called at different times.
The onCreate() is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View variables you want to use in onCreateView(). Afterwards, use onActivityCreated() to do any final initialisations you want to do once everything has completed.


If you want to view the official Android documentation, it can be found here:

There are also some slightly different, but less developed questions/answers here on Stack Overflow:

Timestamp Difference In Hours for PostgreSQL

The first things popping up

EXTRACT(EPOCH FROM current_timestamp-somedate)/3600

May not be pretty, but unblocks the road. Could be prettier if division of interval by interval was defined.

Edit: if you want it greater than zero either use abs or greatest(...,0). Whichever suits your intention.

Edit++: the reason why I didn't use age is that age with a single argument, to quote the documentation: Subtract from current_date (at midnight). Meaning you don't get an accurate "age" unless running at midnight. Right now it's almost 1am here:

select age(current_timestamp);
       age        
------------------
 -00:52:40.826309
(1 row)

Get sum of MySQL column in PHP

You can completely handle it in the MySQL query:

SELECT SUM(column_name) FROM table_name;

Using PDO (mysql_query is deprecated)

$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];

Or using mysqli:

$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes'); 
$row = mysqli_fetch_assoc($result); 
$sum = $row['value_sum'];

Display Last Saved Date on worksheet

This might be an alternative solution. Paste the following code into the new module:

Public Function ModDate()
ModDate = 
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm") 
End Function

Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.

Paste the following code into the cell where you want to display the last modification time:

=ModDate()

I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel

JQuery - Storing ajax response into global variable

You might find it easier storing the response values in a DOM element, as they are accessible globally:

<input type="hidden" id="your-hidden-control" value="replace-me" />

<script>
    $.getJSON( '/uri/', function( data ) {
        $('#your-hidden-control').val( data );
    } );
</script>

This has the advantage of not needing to set async to false. Clearly, whether this is appropriate depends on what you're trying to achieve.

Camera access through browser

As of 2015, it now just works.

<input type="file">

This will ask user for the upload of any file. On iOS 8.x this can be a camera video, camera photo, or a photo/video from Photo Library.

iOS/iPhone photo/video/file upload

<input type="file" accept="image/*">

This is as above, but limits the uploads to photos only from camera or library, no videos.

How do you properly use namespaces in C++?

To avoid saying everything Mark Ingram already said a little tip for using namespaces:

Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (*.cpp) this is normally no big problem - altough I prefer to use the "using namespace" directive on the function level.

I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I'd organize C++ programs mainly with header files / the file structure.

Sometimes namespaces are used in bigger C++ projects to hide implementation details.

Additional note to the using directive: Some people prefer using "using" just for single elements:

using std::cout;  
using std::endl;

Callback when CSS3 transition finishes

For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.

var cssAnimate = function(cssClass, callback) {
    var self = this;

    // Checks if correct animation has ended
    var setAnimationListener = function() {
        self.one(
            "webkitAnimationEnd oanimationend msAnimationEnd animationend",
            function(e) {
                if(
                    e.originalEvent.animationName == cssClass &&
                    e.target === e.currentTarget
                ) {
                    callback();
                } else {
                    setAnimationListener();
                }
            }
        );
    }

    self.addClass(cssClass);
    setAnimationListener();
}

I used it kinda like this

cssAnimate.call($("#something"), "fadeIn", function() {
    console.log("Animation is complete");
    // Remove animation class name?
});

Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/

And this seems handy: http://api.jqueryui.com/addClass/


Update

After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.

Reading inputStream using BufferedReader.readLine() is too slow

I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader's fault. Try measuring this:

InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing

I think you'll find it's almost exactly the same time as when you're parsing the text.

Note that you should also give InputStreamReader an appropriate encoding - the platform default encoding is almost certainly not what you should be using.

Check an integer value is Null in c#

Simply you can do this:

    public void CheckNull(int? item)
    {
        if (item != null)
        {
            //Do Something
        }

    }

Open CSV file via VBA (performance)

Sometimes all the solutions with Workbooks.open is not working no matter how many parameters are set. For me, the fastest solution was to change the List separator in Region & language settings. Region window / Additional settings... / List separator.

If csv is not opening in proper way You probly have set ',' as a list separator. Just change it to ';' and everything is solved. Just the easiest way when "everything is against You" :P

Why use the params keyword?

Another example

public IEnumerable<string> Tokenize(params string[] words)
{
  ...
}

var items = Tokenize(product.Name, product.FullName, product.Xyz)

What happened to Lodash _.pluck?

Or try pure ES6 nonlodash method like this

const reducer = (array, object) => {
  array.push(object.a)
  return array
}

var objects = [{ 'a': 1 }, { 'a': 2 }];
objects.reduce(reducer, [])

Specifying trust store information in spring boot application.properties

I have the same problem, I'll try to explain it a bit more in detail.

I'm using spring-boot 1.2.2-RELEASE and tried it on both Tomcat and Undertow with the same result.

Defining the trust-store in application.yml like:

server:
  ssl:
    trust-store: path-to-truststore...
    trust-store-password: my-secret-password...

Doesn't work, while:

$ java -Djavax.net.debug=ssl -Djavax.net.ssl.trustStore=path-to-truststore... -Djavax.net.ssl.trustStorePassword=my-secret-password... -jar build/libs/*.jar  

works perfectly fine.

The easiest way to see the difference at rutime is to enable ssl-debug in the client. When working (i.e. using -D flags) something like the following is written to the console (during processing of the first request):

trustStore is: path-to-truststore...
trustStore type is : jks
trustStore provider is :
init truststore
adding as trusted cert:
  Subject: C=..., ST=..., O=..., OU=..., CN=...
  Issuer:  C=..., ST=..., O=..., OU=..., CN=...
  Algorithm: RSA; Serial number: 0x4d2
  Valid from Wed Oct 16 17:58:35 CEST 2013 until Tue Oct 11 17:58:35 CEST 2033

Without the -D flags I get:

trustStore is: /Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/security/cacerts
trustStore type is : jks
trustStore provider is :
init truststore
adding as trusted cert: ... (one for each CA-cert in the defult truststore)

...and when performing a request I get the exception:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Hope it helps to understand the issue better!

Restricting JTextField input to Integers

Do not use a KeyListener for this as you'll miss much including pasting of text. Also a KeyListener is a very low-level construct and as such, should be avoided in Swing applications.

The solution has been described many times on SO: Use a DocumentFilter. There are several examples of this on this site, some written by me.

For example: using-documentfilter-filterbypass

Also for tutorial help, please look at: Implementing a DocumentFilter.

Edit

For instance:

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class DocFilter {
   public static void main(String[] args) {
      JTextField textField = new JTextField(10);

      JPanel panel = new JPanel();
      panel.add(textField);

      PlainDocument doc = (PlainDocument) textField.getDocument();
      doc.setDocumentFilter(new MyIntFilter());


      JOptionPane.showMessageDialog(null, panel);
   }
}

class MyIntFilter extends DocumentFilter {
   @Override
   public void insertString(FilterBypass fb, int offset, String string,
         AttributeSet attr) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.insert(offset, string);

      if (test(sb.toString())) {
         super.insertString(fb, offset, string, attr);
      } else {
         // warn the user and don't allow the insert
      }
   }

   private boolean test(String text) {
      try {
         Integer.parseInt(text);
         return true;
      } catch (NumberFormatException e) {
         return false;
      }
   }

   @Override
   public void replace(FilterBypass fb, int offset, int length, String text,
         AttributeSet attrs) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.replace(offset, offset + length, text);

      if (test(sb.toString())) {
         super.replace(fb, offset, length, text, attrs);
      } else {
         // warn the user and don't allow the insert
      }

   }

   @Override
   public void remove(FilterBypass fb, int offset, int length)
         throws BadLocationException {
      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.delete(offset, offset + length);

      if (test(sb.toString())) {
         super.remove(fb, offset, length);
      } else {
         // warn the user and don't allow the insert
      }

   }
}

Why is this important?

  • What if the user uses copy and paste to insert data into the text component? A KeyListener can miss this?
  • You appear to be desiring to check that the data can represent an int. What if they enter numeric data that doesn't fit?
  • What if you want to allow the user to later enter double data? In scientific notation?

PHP preg replace only allow numbers

You could also use T-Regx library:

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

T-Regx also:

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

Open mvc view in new window from controller

@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank",@class="edit"})

   script below will open the action view url in a new window

<script type="text/javascript">
    $(function (){
        $('a.edit').click(function () {
            var url = $(this).attr('href');
            window.open(url, "popupWindow", "width=600,height=800,scrollbars=yes");
            });
            return false;
        });   
</script>

How can I refresh a page with jQuery?

<i id="refresh" class="fa fa-refresh" aria-hidden="true"></i>

<script>
$(document).on('click','#refresh',function(){
   location.reload(true);
});
</script>

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

There are three ways to solve this issue.

  1. Ignore Precompiled Headers #1
    Steps: Project > Properties > Configuration Properties > C/C++ > Command Line > in the Additional Options box add /Y-. (Screenshot of Property Pages) > Ok > Remove #include "stdafx.h"
  2. Ignore Precompiled Headers #2
    Steps: File > New > Project > ... > In the Application Wizard Window click Next > Uncheck the Precompiled Header box > Finish > Remove #include "stdafx.h"
  3. Reinstall Visual Studio
    This also worked for me, because I realized that maybe there was something wrong with my Windows SDK. I was using Windows 10, but with Windows SDK 8.1. You may have this problem as well.
    Steps: Open Visual Studio Installer > Click on the three-lined Menu Bar > Uninstall > Restart your computer > Open Visual Studio Installer > Install what you want, but make sure you install only the latest Windows SDK 10, not multiple ones nor the 8.1.

    The first time I installed Visual Studio, I would get an error stating that I needed to install Windows SDK 8.1. So I did, through Visual Studio Installer's Modify option. Perhaps this was a problem because I was installed it after Visual Studio was already installed, or because I needed SDK 10 instead. Just to be safe I did a complete reinstall.

How to print matched regex pattern using awk?

Off topic, this can be done using the grep also, just posting it here in case if anyone is looking for grep solution

echo 'xxx yyy zzze ' | grep -oE 'yyy'

How to catch and print the full exception traceback without halting/exiting the program?

In addition to Aaron Hall's answer, if you are logging, but don't want to use logging.exception() (since it logs at the ERROR level), you can use a lower level and pass exc_info=True. e.g.

try:
    do_something_that_might_error()
except Exception:
    logging.info('General exception noted.', exc_info=True)

"cannot be used as a function error"

This line is the problem:

int estimatedPopulation (int currentPopulation,
                         float growthRate (birthRate, deathRate))

Make it:

int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)

instead and invoke the function with three arguments like

estimatePopulation( currentPopulation, birthRate, deathRate );

OR declare it with two arguments like:

int estimatedPopulation (int currentPopulation, float growthrt ) { ... }

and call it as

estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));

Edit:

Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate variable in the main() hides the function with the same name. So within main() you can only access grouthRate as float. On the other hand, outside of the main() you can only access that name as a function, since that automatic variable is only visible within the scope of main().

Just hope I didn't confuse you further :)

How to have the cp command create any necessary folders for copying a file to a destination

To expand upon Christian's answer, the only reliable way to do this would be to combine mkdir and cp:

mkdir -p /foo/bar && cp myfile "$_"

As an aside, when you only need to create a single directory in an existing hierarchy, rsync can do it in one operation. I'm quite a fan of rsync as a much more versatile cp replacement, in fact:

rsync -a myfile /foo/bar/ # works if /foo exists but /foo/bar doesn't.  bar is created.

Remove border from buttons

Try using: border:0; or border:none;

How to add button inside input

I found a great code for you:

HTML

<form class="form-wrapper cf">
    <input type="text" placeholder="Search here..." required>
    <button type="submit">Search</button>
</form>

CSS

/*Clearing Floats*/
.cf:before, .cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

.cf {
    zoom:1;
}    
/* Form wrapper styling */
.form-wrapper {
    width: 450px;
    padding: 15px;
    margin: 150px auto 50px auto;
    background: #444;
    background: rgba(0,0,0,.2);
    border-radius: 10px;
    box-shadow: 0 1px 1px rgba(0,0,0,.4) inset, 0 1px 0 rgba(255,255,255,.2);
}

/* Form text input */

.form-wrapper input {
    width: 330px;
    height: 20px;
    padding: 10px 5px;
    float: left;   
    font: bold 15px 'lucida sans', 'trebuchet MS', 'Tahoma';
    border: 0;
    background: #eee;
    border-radius: 3px 0 0 3px;     
}

.form-wrapper input:focus {
    outline: 0;
    background: #fff;
    box-shadow: 0 0 2px rgba(0,0,0,.8) inset;
}

.form-wrapper input::-webkit-input-placeholder {
   color: #999;
   font-weight: normal;
   font-style: italic;
}

.form-wrapper input:-moz-placeholder {
    color: #999;
    font-weight: normal;
    font-style: italic;
}

.form-wrapper input:-ms-input-placeholder {
    color: #999;
    font-weight: normal;
    font-style: italic;
}   

/* Form submit button */
.form-wrapper button {
    overflow: visible;
    position: relative;
    float: right;
    border: 0;
    padding: 0;
    cursor: pointer;
    height: 40px;
    width: 110px;
    font: bold 15px/40px 'lucida sans', 'trebuchet MS', 'Tahoma';
    color: #fff;
    text-transform: uppercase;
    background: #d83c3c;
    border-radius: 0 3px 3px 0;     
    text-shadow: 0 -1px 0 rgba(0, 0 ,0, .3);
}  

.form-wrapper button:hover {    
    background: #e54040;
}  

.form-wrapper button:active,
.form-wrapper button:focus {  
    background: #c42f2f;
    outline: 0;  
}

.form-wrapper button:before { /* left arrow */
    content: '';
    position: absolute;
    border-width: 8px 8px 8px 0;
    border-style: solid solid solid none;
    border-color: transparent #d83c3c transparent;
    top: 12px;
    left: -6px;
}

.form-wrapper button:hover:before {
    border-right-color: #e54040;
}

.form-wrapper button:focus:before,
.form-wrapper button:active:before {
        border-right-color: #c42f2f;
}     

.form-wrapper button::-moz-focus-inner { /* remove extra button spacing for Mozilla Firefox */
    border: 0;
    padding: 0;
}    

Demo: On fiddle Source: Speckyboy

Why can't I check if a 'DateTime' is 'Nothing'?

You can check this like below :

if varDate = "#01/01/0001#" then
       '  blank date. do something.
else
       ' Date is not blank. Do some other thing
end if

What is the largest TCP/IP network port number allowable for IPv4?

The port number is an unsigned 16-bit integer, so 65535.

Is it correct to use alt tag for an anchor link?

I'm surprised to see all answers stating the use of alt attribute in a tag is not valid. This is absolutely wrong.

Html does not block you using any attributes:

<a your-custom-attribute="value">Any attribute can be used</a>

If you ask if it is semantically correct to use alt attribute in a then I will say:

NO. It is used to set image description <img alt="image description" />.

It is a matter of what you'd do with the attributes. Here's an example:

_x000D_
_x000D_
a::after {_x000D_
  content: attr(color); /* attr can be used as content */_x000D_
  display: block;_x000D_
  color: white;_x000D_
  background-color: blue;_x000D_
  background-color: attr(color); /* This won't work */_x000D_
  display: none;_x000D_
}_x000D_
a:hover::after {_x000D_
  display: block;_x000D_
}_x000D_
[hidden] {_x000D_
  display: none;_x000D_
}
_x000D_
<a href="#" color="red">Hover me!</a>_x000D_
<a href="#" color="red" hidden>In some cases, it can be used to hide it!</a>
_x000D_
_x000D_
_x000D_

Again, if you ask if it is semantically correct to use custom attribute then I will say:

No. Use data-* attributes for its semantic use.


Oops, question was asked in 2013.

Proper MIME media type for PDF files

The standard MIME type is application/pdf. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.

MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.

The use of x-pdf predates the standardization of the MIME type for PDF. MIME types in the x- namespace are considered experimental, just as those in the vnd. namespace are considered vendor-specific. x-pdf might be used for compatibility with old software.

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

Had this error when I had deleted a table from the database. Solved it by right clicking on EDMX diagram, going to Properties, selecting the table from the list in the Properties window, and deleting it (using delete key) from the diagram.

Open a file with Notepad in C#

System.Diagnostics.Process.Start( "notepad.exe", "text.txt");

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

How to cut an entire line in vim and paste it?

Just three steps.


  1. Go to the start of the text, and press v
  2. Go to the end of the text, and press d
  3. Go to the place that you want to paste, and press p

Error:java: invalid source release: 8 in Intellij. What does it mean?

As Andreas mentioned all about:

Error:java: invalid source release: 8 in IntelliJ
Error:java: invalid source release: 13 in IntelliJ
Error:java: invalid source release: 14 in IntelliJ...

OR whatever version you are using in Java...

The problem will exist if you do not have it matching inside the below code:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

This 1.8 in my case, must be matching on your device through MAVEN project library, settings, preferences, project setting and SDK.

method in class cannot be applied to given types

I think you want something like this. The formatting is off, but it should give the essential information you want.

   import java.util.Scanner;
public class BookstoreCredit 
{

   public static void computeDiscount(String name, double gpa) 
   {
      double credits;
      credits = gpa * 10;
      System.out.println(name + " your GPA is " +
         gpa + " so your credit is $" + credits);
   
   }

   public static void main (String args[]) 
   {
      String studentName;
      double gradeAverage;
      Scanner inputDevice = new Scanner(System.in);
      System.out.println("Enter Student name: ");
      studentName = inputDevice.nextLine();
      System.out.println("Enter student GPA: ");
      gradeAverage = inputDevice.nextDouble();  
      
      computeDiscount(studentName, gradeAverage);
   }
}

Reactjs convert html string to jsx

This could have been solved by using the content put inside this block {[]} like this. Example could be referred below for better clarity.

{[
   'abc',
   <b>my bold</b>, 
   'some other text'
]} 

This would preserve the formatting for text under tags while the others would be printed as plain text.

How can I interrupt a running code in R with a keyboard command?

I know this is old, but I ran into the same issue. I'm on a Mac/Ubuntu and switch back and forth. What I have found is that just sending a simple interrupt signal to the main R process does exactly what you're looking for. I've ran scripts that went on for as long as 24 hours and the signal interrupt works very well. You should be able to run kill in terminal:

$ kill -2 pid

You can find the pid by running

$ps aux | grep exec/R

Not sure about Windows since I'm not ever on there, but I can't imagine there's not an option to do this as well in Command Prompt/Task Manager

Hope this helps!

Export query result to .csv file in SQL Server 2008

Yes, all these are possible when you have the direct access to the servers. But what if you have only access to the server from a web / application server? Well, the situation was this with us a long back and the solution was SQL Server Export to CSV.

Vue.js - How to properly watch for nested data

Another good approach and one that is a bit more elegant is as follows:

 watch:{
     'item.someOtherProp': function (newVal, oldVal){
         //to work with changes in someOtherProp
     },
     'item.prop': function(newVal, oldVal){
         //to work with changes in prop
     }
 }

(I learned this approach from @peerbolte in the comment here)

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:

SELECT employee_number,
       MAX(MAX(course_completion_date)) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

And as Teradata allows re-using an alias this also works:

SELECT employee_number,
       MAX(max_date) 
           OVER (PARTITION BY course_code) AS max_course_date,
       MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

Last element in .each() set

each passes into your function index and element. Check index against the length of the set and you're good to go:

var set = $('.requiredText');
var length = set.length;
set.each(function(index, element) {
      thisVal = $(this).val();
      if(parseInt(thisVal) !== 0) {
          console.log('Valid Field: ' + thisVal);
          if (index === (length - 1)) {
              console.log('Last field, submit form here');
          }
      }
});

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

your device older than minSDK , edit minSdkVersion in build.gradle

How to block until an event is fired in c#

You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:

ManualResetEvent oSignalEvent = new ManualResetEvent(false);

void SecondThread(){
    //DoStuff
    oSignalEvent.Set();
}

void Main(){
    //DoStuff
    //Call second thread
    System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
    oSecondThread.Start();

    oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
    oSignalEvent.Reset();
    //Do more stuff
}

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

What does \d+ mean in regular expression terms?

\d is called a character class and will match digits. It is equal to [0-9].

+ matches 1 or more occurrences of the character before.

So \d+ means match 1 or more digits.

Onclick event to remove default value in a text input field

<input name="Name" value="Enter Your Name" onfocus="freez(this)" onblur="freez(this)">


function freez(obj)
{
 if(obj.value=='')
 {
   obj.value='Enter Your Name';
 }else if(obj.value=='Enter Your Name')
 {
   obj.value='';
 }
} 

How to center an unordered list?

Let's say the list is:

<ul>
 <li>item1</li>
 <li>item2</li>
 <li>item3</li>
</ul>

For this example. If I understand correctly, you want the list items to be in the middle of the screen, but you want the text IN those list items to be centered to the left of the list item itself. Doing that is actually pretty easy. You just need some CSS:

ul {
    display: table; 
    margin: 0 auto;
    text-align: left;
}

And it works! Here is what is happening. First, we say we want to affect only unordered lists. Then, we do Rafael Herscovici's trick for centering the list items. Finally, we say to align the text to the left of the list items.

How to format a Java string with leading zero?

public class PaddingLeft {
    public static void main(String[] args) {
        String input = "Apple";
        String result = "00000000" + input;
        int length = result.length();
        result = result.substring(length - 8, length);
        System.out.println(result);
    }
}

Passing data from controller to view in Laravel

The best and easy way to pass single or multiple variables to view from controller is to use compact() method.

For passing single variable to view,

return view("user/regprofile",compact('students'));

For passing multiple variable to view,

return view("user/regprofile",compact('students','teachers','others'));

And in view, you can easily loop through the variable,

@foreach($students as $student)
   {{$student}}
@endforeach

How to set a JavaScript breakpoint from code in Chrome?

It is possible and there are many reasons you might want to do this. For example debugging a javascript infinite loop close to the start of the page loading, that stops the chrome developer toolset (or firebug) from loading correctly.

See section 2 of

http://www.laurencegellert.com/2012/05/the-three-ways-of-setting-breakpoints-in-javascript/

or just add a line containing the word debugger to your code at the required test point.

Reading a JSP variable from JavaScript

Assuming you are talking about JavaScript in an HTML document.

You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document.

You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS. If you just dump the data (as proposed by some other answers) you will find it falling over when the data contains new lines, quote characters and so on.

The simplest way to do this is to use a JSON library (there are a bunch listed at the bottom of http://json.org/ ) and then have the JSP output:

<script type="text/javascript">
    var myObject = <%= the string output by the JSON library %>;
</script>

This will give you an object that you can access like:

myObject.someProperty

in the JS.

update package.json version automatically

As an addition to npm version you can use the --no-git-tag-version flag if you want a version bump but no tag or a new commit:

npm --no-git-tag-version version patch

https://docs.npmjs.com/cli/version

Force Intellij IDEA to reread all maven dependencies

Go to File | Settings | Build, Execution, Deployment | Build Tools | Maven

Select "Always update snapshots"

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

In a VBA worksheet function UDF you use Application.Caller to get the range of cell(s) that contain the formula that called the UDF.

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

How to set fake GPS location on IOS real device

it seems with XCode 9.2 the way to import .gpx has changed, I tried the ways described here and did not do. The only way worked for me was to drag and drop the file .gpx to the project navigator window on the left. Then I can choose the country in the simulator item.

Hope this helps to someone.

wait until all threads finish their work in java

You do

for (Thread t : new Thread[] { th1, th2, th3, th4, th5 })
    t.join()

After this for loop, you can be sure all threads have finished their jobs.

rsync error: failed to set times on "/foo/bar": Operation not permitted

I had the same problem. For me the solution is to delete the remote file and let rsync create again.

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

The situation you describe is pretty fishy. Whenever you close your program's startup form, the entire application should quit automatically, including closing all other open forms. Make sure that you're closing the correct form, and you should not experience any problems.

The other possibility is that you've changed your project (using its Properties page) not to close until all open windows have been closed. In this mode, your application will not exit until the last remaining open form has been closed. If you've chosen this setting, you have to make sure that you call the Close method of all forms that you've shown during the course of application, not just the startup/main form.

The first setting is the default for a reason, and if you've changed it, you probably want to go fix it back.
It is by far the most intuitive model for normal applications, and it prevents exactly the situation you describe. For it to work properly, make sure that you have specified your main form as the "Startup form" (rather than a splash screen or log-in form).

The settings I'm talking about are highlighted here:

   Visual Studio Project Properties

But primarily, note that you should never have to call Application.Exit in a properly-designed application. If you find yourself having to do this in order for your program to close completely, then you are doing something wrong. Doing it is not a bad practice in itself, as long as you have a good reason. The other two answers fail to explain that, and thus I feel are incomplete at best.

How to output oracle sql result into a file in windows?

just to make the Answer 2 much easier, you can also define the folder where you can put your saved file

    spool /home/admin/myoutputfile.txt
    select * from table_name;
    spool off;

after that only with nano or vi myoutputfile.txt, you will see all the sql track.

hope is that help :)

Replace multiple strings with multiple other strings

by using prototype function we can replace easily by passing object with keys and values and replacable text

_x000D_
_x000D_
String.prototype.replaceAll=function(obj,keydata='key'){
 const keys=keydata.split('key');
 return Object.entries(obj).reduce((a,[key,val])=> a.replace(`${keys[0]}${key}${keys[1]}`,val),this)
}

const data='hids dv sdc sd ${yathin} ${ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'${key}'))
_x000D_
_x000D_
_x000D_

How can I stop redis-server?

MacOSX - It Worked :)

Step 1 : Find the previously Running Redis Server

ps auxx | grep redis-server

Step 2 : Kill the specific process by finding PID (Process ID) - Redis Sever

kill -9 PID

link_to method and click event in Rails

You can use link_to_function (removed in Rails 4.1):

link_to_function 'My link with obtrusive JavaScript', 'alert("Oh no!")'

Or, if you absolutely need to use link_to:

link_to 'Another link with obtrusive JavaScript', '#',
        :onclick => 'alert("Please no!")'

However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.

Instead, your Rails code should simply be something like this:

link_to 'Link with unobtrusive JavaScript',
        '/actual/url/in/case/javascript/is/broken',
        :id => 'my-link'

And assuming you're using the Prototype JS framework, JS like this in your application.js:

$('my-link').observe('click', function (event) {
  alert('Hooray!');
  event.stop(); // Prevent link from following through to its given href
});

Or if you're using jQuery:

$('#my-link').click(function (event) {
  alert('Hooray!');
  event.preventDefault(); // Prevent link from following its href
});

By using this third technique, you guarantee that the link will follow through to some other page—not just fail silently—if JavaScript is unavailable for the user. Remember, JS could be unavailable because the user has a poor internet connection (e.g., mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (i.e., developer error).

how to align img inside the div to the right?

<p>
  <img style="float: right; margin: 0px 15px 15px 0px;" src="files/styles/large_hero_desktop_1x/public/headers/Kids%20on%20iPad%20 %202400x880.jpg?itok=PFa-MXyQ" width="100" />
  Nunc pulvinar lacus id purus ultrices id sagittis neque convallis. Nunc vel libero orci. 
  <br style="clear: both;" />
</p>

How to comment multiple lines with space or indent

  • You can customize every short cut operation according to your habbit.

Just go to Tools > Options > Environment > Keyboard > Find the action you want to set key board short-cut and change according to keyboard habbit.

How to use a table type in a SELECT FROM statement?

Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:

CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);


CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;

In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.

How to upgrade scikit-learn package in anaconda

Following Worked for me for scikit-learn on Anaconda-Jupyter Notebook.

Upgrading my scikit-learn from 0.19.1 to 0.19.2 in anaconda installed on Ubuntu on Google VM instance:

Run the following commands in the terminal:

First, check existing available packages with versions by using:

conda list    

It will show different packages and their installed versions in the output. Here check for scikit-learn. e.g. for me, the output was:

scikit-learn              0.19.1           py36hedc7406_0  

Now I want to Upgrade to 0.19.2 July 2018 release i.e. latest available version.

conda config --append channels conda-forge
conda install scikit-learn=0.19.2

As you are trying to upgrade to 0.17 version try the following command:

conda install scikit-learn=0.17

Now check the required version of the scikit-learn is installed correctly or not by using:

conda list 

For me the Output was:

scikit-learn              0.19.2          py36_blas_openblasha84fab4_201  [blas_openblas]  conda-forge

Note: Don't use pip command if you are using Anaconda or Miniconda

I tried following commands:

!conda update conda 
!pip install -U scikit-learn

It will install the required packages also will show in the conda list but if you try to import that package it will not work.

On the website http://scikit-learn.org/stable/install.html it is mentioned as: Warning To upgrade or uninstall scikit-learn installed with Anaconda or conda you should not use the pip.

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I had the same problem with long-running scripts with the error messages "Premature end of script headers: index.php" and "Connection reset by peer: mod_fcgid: error reading data from FastCGI server" in error_log. After hours of testing this helps for me (CentOS 6, PHP-FPM 7, Plesk 12.5.30):

edit the config file:

/etc/httpd/conf.d/fcgid.conf

Set a higher running time. In my case 600 seconds

create the new entry:

FcgidBusyTimeout 600

adapt following entries:

FcgidIOTimeout 600

FcgidConnectTimeout 600

restart httpd:

service httpd restart

Best way to create unique token in Rails?

I think token should be handled just like password. As such, they should be encrypted in DB.

I'n doing something like this to generate a unique new token for a model:

key = ActiveSupport::KeyGenerator
                .new(Devise.secret_key)
                .generate_key("put some random or the name of the key")

loop do
  raw = SecureRandom.urlsafe_base64(nil, false)
  enc = OpenSSL::HMAC.hexdigest('SHA256', key, raw)

  break [raw, enc] unless Model.exist?(token: enc)
end