Programs & Examples On #Rich text editor

A rich-text editor allows to edit, enter and format content in a web browser with rich markup and styles close to its final appearance.

How do you make a div follow as you scroll?

You can use the fixed CSS position property to accomplish this. There is a basic tutorial on this here.

EDIT: However, this approach is NOT supported in IE versions < IE7, and only in IE7 if it is in standards mode. This is discussed in a little more detail here.

There is also a hack, explained here, that shows how to accomplish fixed positioning in IE6 without affecting absolute positioning. What version of IE are you targeting your website for?

Get method arguments using Spring AOP?

Yes, the value of any argument can be found using getArgs

@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) {

   Object[] signatureArgs = thisJoinPoint.getArgs();
   for (Object signatureArg: signatureArgs) {
      System.out.println("Arg: " + signatureArg);
      ...
   }
}

Unable to set data attribute using jQuery Data() API

As mentioned, the .data() method won't actually set the value of the data- attribute, nor will it read updated values if the data- attribute changes.

My solution was to extend jQuery with a .realData() method that actually corresponds to the current value of the attribute:

// Alternative to .data() that updates data- attributes, and reads their current value.
(function($){
  $.fn.realData = function(name,value) {
      if (value === undefined) {
        return $(this).attr('data-'+name);
      } else {
        $(this).attr('data-'+name,value);
      }
  };
})(jQuery);

NOTE: Sure you could just use .attr(), but from my experience, most developers (aka me) make the mistake of viewing .attr() and .data() as interchangeable, and often substitute one for the other without thinking. It might work most of the time, but it's a great way to introduce bugs, especially when dealing with any sort of dynamic data binding. So by using .realData(), I can be more explicit about the intended behavior.

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Adding an arbitrary line to a matplotlib plot in ipython notebook

Rather than abusing plot or annotate, which will be inefficient for many lines, you can use matplotlib.collections.LineCollection:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")

# Takes list of lines, where each line is a sequence of coordinates
l1 = [(70, 100), (70, 250)]
l2 = [(70, 90), (90, 200)]
lc = LineCollection([l1, l2], color=["k","blue"], lw=2)

plt.gca().add_collection(lc)

plt.show()

Figure with two lines plotted via LineCollection

It takes a list of lines [l1, l2, ...], where each line is a sequence of N coordinates (N can be more than two).

The standard formatting keywords are available, accepting either a single value, in which case the value applies to every line, or a sequence of M values, in which case the value for the ith line is values[i % M].

How to create a box when mouse over text in pure CSS?

Exactly what they said, it will work.

In the parent element stablish a max-height.

I'm taking sandeep example and adding the max-height and if required you can add max-width property. The text will stay where It should stay (If possible, in some cases you will need to change some values to make it stay in there)

span{
    background: none repeat scroll 0 0 #F8F8F8;
    border: 5px solid #DFDFDF;
    color: #717171;
    font-size: 13px;
    height: 30px;
    letter-spacing: 1px;
    line-height: 30px;
    margin: 0 auto;
    position: relative;
    text-align: center;
    text-transform: uppercase;
    top: -80px;
    left:-30px;
    display:none;
    padding:0 20px;
}

span:after{
    content:'';
    position:absolute;
    bottom:-10px;
    width:10px;
    height:10px;
    border-bottom:5px solid #dfdfdf;
    border-right:5px solid #dfdfdf;
    background:#f8f8f8;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
     transform:rotate(45deg);
}

p{
    margin:100px;
    float:left;
    position:relative;
    cursor:pointer;
    max-height: 10px;
}

p:hover span{
    display:block;
}

max-height in the p paragraph, second to last one, last line.

Test it before rating it useless.

How to get row from R data.frame

x[r,]

where r is the row you're interested in. Try this, for example:

#Add your data
x <- structure(list(A = c(5,    3.5, 3.25, 4.25,  1.5 ), 
                    B = c(4.25, 4,   4,    4.5,   4.5 ),
                    C = c(4.5,  2.5, 4,    2.25,  3   )
               ),
               .Names    = c("A", "B", "C"),
               class     = "data.frame",
               row.names = c(NA, -5L)
     )

#The vector your result should match
y<-c(A=5, B=4.25, C=4.5)

#Test that the items in the row match the vector you wanted
x[1,]==y

This page (from this useful site) has good information on indexing like this.

Convert javascript array to string

Here's an example using underscore functions.

var exampleArray = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var finalArray = _.compact(_.pluck(exampleArray,"name")).join(",");

Final output would be "moe,larry,curly"

Plain Old CLR Object vs Data Transfer Object

I think a DTO can be a POCO. DTO is more about the usage of the object while POCO is more of the style of the object (decoupled from architectural concepts).

One example where a POCO is something different than DTO is when you're talking about POCO's inside your domain model/business logic model, which is a nice OO representation of your problem domain. You could use the POCO's throughout the whole application, but this could have some undesirable side effect such a knowledge leaks. DTO's are for instance used from the Service Layer which the UI communicates with, the DTO's are flat representation of the data, and are only used for providing the UI with data, and communicating changes back to the service layer. The service layer is in charge of mapping the DTO's both ways to the POCO domain objects.

Update Martin Fowler said that this approach is a heavy road to take, and should only be taken if there is a significant mismatch between the domain layer and the user interface.

How to export all data from table to an insertable sql format?

Command to get the database backup from linux machine terminal.

sqlcmd -S localhost -U SA -Q "BACKUP DATABASE [demodb] TO DISK = N'/var/opt/mssql/data/demodb.bak' WITH NOFORMAT, NOINIT, NAME = 'demodb-full', SKIP, NOREWIND, NOUNLOAD, STATS = 10"

Backup and restore SQL Server databases on Linux

What is cURL in PHP?

The cURL extension to PHP is designed to allow you to use a variety of web resources from within your PHP script.

Angular - Can't make ng-repeat orderBy work

the built-in orderBy filter will no longer work when iterating an object. It’s ignored due to the way that object fields are stored. You need create a custom filter

yourApp.filter('orderObjectBy', function() {
  return function(items, field, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      return (a[field] > b[field] ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
});

<ul>
<li ng-repeat="item in items | orderObjectBy:'color':true">{{ item.color }}</li>
</ul>

Can you detect "dragging" in jQuery?

For some reason, the above solutions were not working for me. I went with the following:

$('#container').on('mousedown', function(e) {
    $(this).data('p0', { x: e.pageX, y: e.pageY });
}).on('mouseup', function(e) {
    var p0 = $(this).data('p0'),
        p1 = { x: e.pageX, y: e.pageY },
        d = Math.sqrt(Math.pow(p1.x - p0.x, 2) + Math.pow(p1.y - p0.y, 2));

    if (d < 4) {
        alert('clicked');
    }
})

You can tweak the distance limit to whatever you please, or even take it all the way to zero.

How do I start PowerShell from Windows Explorer?

In Windows Explorer, just go to the Address Bar at the top (keyboard shortcuts: Alt+D or Ctrl+L) and type powershell or powershell_ise and press Enter. A PowerShell command window opens with the current directory.

How to escape double quotes in a title attribute

This variant -

_x000D_
_x000D_
<a title="Some &quot;text&quot;">Hover me</a>
_x000D_
_x000D_
_x000D_

Is correct and it works as expected - you see normal quotes in rendered page.

How to identify all stored procedures referring a particular table

The query below works only when searching for dependencies on a table and not those on a column:

EXEC sp_depends @objname = N'TableName';

However, the following query is the best option if you want to search for all sorts of dependencies, it does not miss any thing. It actually gives more information than required.

 select distinct
        so.name
        --, text 
  from 
       sysobjects so, 
       syscomments sc 
  where 
     so.id = sc.id 
     and lower(text) like '%organizationtypeid%'
  order by so.name

call a function in success of datatable ajax call

You can use this:

"drawCallback": function(settings) {
   console.log(settings.json);
   //do whatever  
},

Updates were rejected because the tip of your current branch is behind its remote counterpart

This is how I solved my problem

Let's assume the upstream branch is the one that you forked from and origin is your repo and you want to send an MR/PR to the upstream branch.

You already have let's say about 4 commits and you are getting Updates were rejected because the tip of your current branch is behind.

Here is what I did

First, squash all your 4 commits

git rebase -i HEAD~4

You'll get a list of commits with pick written on them. (opened in an editor)

example

pick fda59df commit 1
pick x536897 commit 2
pick c01a668 commit 3
pick c011a77 commit 4

to

pick fda59df commit 1
squash x536897 commit 2
squash c01a668 commit 3
squash c011a77 commit 4

After that, you can save your combined commit

Next

You'll need to stash your commit

Here's how

git reset --soft HEAD~1
git stash

now rebase with your upstream branch

git fetch upstream beta && git rebase upstream/beta

Now pop your stashed commit

git stash pop

commit these changes and push them

git add -A
git commit -m "[foo] - foobar commit"
git push origin fix/#123 -f

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

  1. Go to Setting/Apps/ Search for your app and uninstall...
  2. open command prompt and "adb uninstall "

It´s worked for me

Default property value in React component using TypeScript

You can use the spread operator to re-assign props with a standard functional component. The thing I like about this approach is that you can mix required props with optional ones that have a default value.

interface MyProps {
   text: string;
   optionalText?: string;
}

const defaultProps = {
   optionalText = "foo";
}

const MyComponent = (props: MyProps) => {
   props = { ...defaultProps, ...props }
}

Getting a machine's external IP address with Python

If you are not interested in hitting any url to get public ip, I think following code can help you to get public ip using python of your machine

import os
externalIP  = os.popen("ifconfig | grep 'inet' | cut -d: -f2 | awk '{print $2}' | sed -n 3p").readline()
print externalIP

sed -n 3p line varies as per the network you are using for connecting device.

I was facing same issue, I was needed public ip of iot device which is hitting my server. but public ip is totally different in ifconfig command and ip i am getting in server from request object. after this I am adding extra param into my request to send ip of device to my server.

hope this is helpful

Does MySQL foreign_key_checks affect the entire database?

As explained by Ron, there are two variables, local and global. The local variable is always used, and is the same as global upon connection.

SET FOREIGN_KEY_CHECKS=0;
SET GLOBAL FOREIGN_KEY_CHECKS=0;

SHOW Variables WHERE Variable_name='foreign_key_checks'; # always shows local variable

When setting the GLOBAL variable, the local one isn't changed for any existing connections. You need to reconnect or set the local variable too.

Perhaps unintuitive, MYSQL does not enforce foreign keys when FOREIGN_KEY_CHECKS are re-enabled. This makes it possible to create an inconsistent database even though foreign keys and checks are on.

If you want your foreign keys to be completely consistent, you need to add the keys while checking is on.

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // checkbox status is checked.
                if (isChecked) {
                        //password is visible
 PasswordField.setTransformationMethod(HideReturnsTransformationMethod.getInstance());     
                } else {
                        //password gets hided
             passwordField.setTransformationMethod(PasswordTransformationMethod.getInstance());       
                }
            }
        });

iOS9 Untrusted Enterprise Developer with no option to trust

Do it like this:

Enter image description here

Go to Settings -> General -> Profiles - tap on your Profile - tap on the Trust button.

but iOS10 has a little change,

Users should go to Settings - General - Device Management - tap on your Profile - tap on Trust button.

enter image description here

Reference: iOS10AdaptationTips

Make elasticsearch only return certain fields?

Here is another solution, now using a match expression

Source filtering allows to control how the _source field is returned with every hit.

Tested with Elastiscsearch version 5.5

The keyword includes defines the specifics fields.

GET /my_indice/my_indice_type/_search
{
  "_source": {
    "includes": [
      "my_especific_field"
    ]
  },
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "_id": "%my_id_here_without_percent%"
          }
        }
      ]
    }
  }
}

How to start and stop android service from a adb shell?

I can start service through

am startservice com.xxx/.service.XXXService

but i don't know how to stop it yet.

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

You need to put SongsTableSeeder into file SongsTableSeeder.php in the same directory where you have your DatabaseSeeder.php file.

And you need to run in your console:

composer dump-autoload

to generate new class map and then run:

php artisan db:seed

I've just tested it. It is working without a problem in Laravel 5

Executing Javascript from Python

One more solution as PyV8 seems to be unmaintained and dependent on the old version of libv8.

PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.

pip install py-mini-racer

from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
""")
ctx.call("escramble_758")

And yes, you have to replace document.write with return as others suggested

How to "select distinct" across multiple data frame columns in pandas?

You can use the drop_duplicates method to get the unique rows in a DataFrame:

In [29]: df = pd.DataFrame({'a':[1,2,1,2], 'b':[3,4,3,5]})

In [30]: df
Out[30]:
   a  b
0  1  3
1  2  4
2  1  3
3  2  5

In [32]: df.drop_duplicates()
Out[32]:
   a  b
0  1  3
1  2  4
3  2  5

You can also provide the subset keyword argument if you only want to use certain columns to determine uniqueness. See the docstring.

IsNothing versus Is Nothing

VB is full of things like that trying to make it both "like English" and comfortable for people who are used to languages that use () and {} a lot. And on the other side, as you already probably know, most of the time you can use () with function calls if you want to, but don't have to.

I prefer IsNothing()... but I use C and C#, so that's just what is comfortable. And I think it's more readable. But go with whatever feels more comfortable to you.

Oracle - How to create a materialized view with FAST REFRESH and JOINS

The key checks for FAST REFRESH includes the following:

1) An Oracle materialized view log must be present for each base table.
2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition.
3) If there are outer joins, unique constraints must be placed on the join columns of the inner table.

No 3 is easy to miss and worth highlighting here

Drop unused factor levels in a subsetted data frame

Unfortunately factor() doesn't seem to work when using rxDataStep of RevoScaleR. I do it in two steps: 1) Convert to character and store in temporary external data frame (.xdf). 2) Convert back to factor and store in definitive external data frame. This eliminates any unused factor levels, without loading all the data into memory.

# Step 1) Converts to character, in temporary xdf file:
rxDataStep(inData = "input.xdf", outFile = "temp.xdf", transforms = list(VAR_X = as.character(VAR_X)), overwrite = T)
# Step 2) Converts back to factor:
rxDataStep(inData = "temp.xdf", outFile = "output.xdf", transforms = list(VAR_X = as.factor(VAR_X)), overwrite = T)

How can I check if a directory exists in a Bash shell script?

Shorter form:

# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"

npm - how to show the latest version of a package

There is also another easy way to check the latest version without going to NPM if you are using VS Code.

In package.json file check for the module you want to know the latest version. Remove the current version already present there and do CTRL + space or CMD + space(mac).The VS code will show the latest versions

image shows the latest versions of modules in vscode

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I'm using EasyPHP in making my Thesis about Content Management System. So far, this tool is very good and easy to use.

How do I populate a JComboBox with an ArrayList?

i think that is the solution

ArrayList<table> libel = new ArrayList<table>();
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();

String hql = "FROM table ";

org.hibernate.Query query = s.createQuery(hql);
libel= (ArrayList<table>) query.list();
Iterator it = libel.iterator();
while(it.hasNext()) {
table cat = (table) it.next();

cat.getLibCat();//table colonm getter


combobox.addItem(cat.getLibCat());
}
s.getTransaction().commit();
s.close();
sf.close();
} catch (Exception e) {
System.out.println("Exception in getSelectedData::"+e.getMessage());

Error in plot.window(...) : need finite 'xlim' values

The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA) values. Here's an example:

> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf

In your example this means that in your line plot(costs,pseudor2,type="l"), costs is completely NA. You have to figure out why this is, but that's the explanation of your error.


From comments:

Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.

stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x))

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to echo in PHP, HTML tags

There isn't any need to use echo, sir. Just use the tag <plaintext>:

<plaintext>
    <div>
        <h3><a href="#">First</a></h3>
        <div>Lorem ipsum dolor sit amet.</div>
    </div>

Get HTML inside iframe using jQuery

Try this code:

$('#iframe').contents().find("html").html();

This will return all the html in your iframe. Instead of .find("html") you can use any selector you want eg: .find('body'),.find('div#mydiv').

Purpose of #!/usr/bin/python3 shebang

This line helps find the program executable that will run the script. This shebang notation is fairly standard across most scripting languages (at least as used on grown-up operating systems).

An important aspect of this line is specifying which interpreter will be used. On many development-centered Linux distributions, for example, it is normal to have several versions of python installed at the same time.

Python 2.x and Python 3 are not 100% compatible, so this difference can be very important. So #! /usr/bin/python and #! /usr/bin/python3 are not the same (and neither are quite the same as #! /usr/bin/env python3 as noted elsewhere on this page.

java SSL and cert keystore

SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.

The specific keys you have to set are below:

javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.

javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).

javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes, /, in place of backslashes, \.

If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):

  1. $JAVA_HOME/lib/security/jssecacerts
  2. $JAVA_HOME/lib/security/cacerts

javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by javax.net.ssl.trustStore.

javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.

javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.

How to remove square brackets from list in Python?

if you have numbers in list, you can use map to apply str to each element:

print ', '.join(map(str, LIST))

^ map is C code so it's faster than str(i) for i in LIST

How do I compile a Visual Studio project from the command-line?

I know of two ways to do it.

Method 1
The first method (which I prefer) is to use msbuild:

msbuild project.sln /Flags...

Method 2
You can also run:

vcexpress project.sln /build /Flags...

The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.

Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).

So, the end result might be:

os.system("msbuild project.sln /p:Configuration=Debug")

You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).

How to cast/convert pointer to reference in C++

foo(*ob);

You don't need to cast it because it's the same Object type, you just need to dereference it.

How-to turn off all SSL checks for postman for a specific site

There is an option in Postman if you download it from https://www.getpostman.com instead of the chrome store (most probably it has been introduced in the new versions and the chrome one will be updated later) not sure about the old ones.

In the settings, turn off the SSL certificate verification option enter image description here

Be sure to remember to reactivate it afterwards, this is a security feature.

If you really want to use the chrome app, you could always add an exception to chrome for the url: Enter the url you would like to open in the chrome browser, you'll get a warning with a link at the bottom of the page to add an exception, which if you do, it will also allow postman to access your url. But the first option of using the postman stand-alone app is much better.

I hope this can help.

jQuery animated number counter from zero to value

You can get the element itself in .each(), try this instead of using this

$('.Count').each(function (index, value) {
    jQuery({ Counter: 0 }).animate({ Counter: value.text() }, {
        duration: 1000,
        easing: 'swing',
        step: function () {
            value.text(Math.ceil(this.Counter));
        }
    });
});

The object 'DF__*' is dependent on column '*' - Changing int to double

Solution :

open database table -> expand table -> expand constraints and see this

screenshot

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

Cross browser compatible JS solution:

_x000D_
_x000D_
var e = document.getElementById('elem');_x000D_
var spin = false;_x000D_
_x000D_
var spinner = function(){_x000D_
e.classList.toggle('running', spin);_x000D_
if (spin) setTimeout(spinner, 2000);_x000D_
}_x000D_
_x000D_
e.onmouseover = function(){_x000D_
spin = true;_x000D_
spinner();_x000D_
};_x000D_
_x000D_
e.onmouseout = function(){_x000D_
spin = false;_x000D_
};
_x000D_
body { _x000D_
height:300px; _x000D_
}_x000D_
#elem {_x000D_
position:absolute;_x000D_
top:20%;_x000D_
left:20%;_x000D_
width:0; _x000D_
height:0;_x000D_
border-style: solid;_x000D_
border-width: 75px;_x000D_
border-color: red blue green orange;_x000D_
border-radius: 75px;_x000D_
}_x000D_
_x000D_
#elem.running {_x000D_
animation: spin 2s linear 0s infinite;_x000D_
}_x000D_
_x000D_
@keyframes spin { _x000D_
100% { transform: rotate(360deg); } _x000D_
}
_x000D_
<div id="elem"></div>
_x000D_
_x000D_
_x000D_

How do I make a JAR from a .java file?

Simply with command line:

javac MyApp.java
jar -cf myJar.jar MyApp.class

Sure IDEs avoid using command line terminal

Xampp localhost/dashboard

Here's what's actually happening localhost means that you want to open htdocs. First it will search for any file named index.php or index.html. If one of those exist it will open the file. If neither of those exist then it will open all folder/file inside htdocs directory which is what you want.

So, the simplest solution is to rename index.php or index.html to index2.php etc.

mySQL :: insert into table, data from another table?

for whole row

insert into xyz select * from xyz2 where id="1";

for selected column

insert into xyz(t_id,v_id,f_name) select t_id,v_id,f_name from xyz2 where id="1";

How can I show the table structure in SQL Server query?

Another way is,

mysql > SHOW CREATE TABLE my_db.my_table;

You should get the table name and create table sql

Spring Boot Adding Http Request Interceptors

You might also consider using the open source SpringSandwich library which lets you directly annotate in your Spring Boot controllers which interceptors to apply, much in the same way you annotate your url routes.

That way, no typo-prone Strings floating around -- SpringSandwich's method and class annotations easily survive refactoring and make it clear what's being applied where. (Disclosure: I'm the author).

http://springsandwich.com/

Android: How to open a specific folder via Intent and show its content in a file browser?

Intent chooser = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getDownloadCacheDirectory().getPath().toString());
chooser.addCategory(Intent.CATEGORY_OPENABLE);
chooser.setDataAndType(uri, "*/*");
// startActivity(chooser);
try {
startActivityForResult(chooser, SELECT_FILE);
}
catch (android.content.ActivityNotFoundException ex)
{
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}

In code above, if setDataAndType is "*/*" a builtin file browser is opened to pick any file, if I set "text/plain" Dropbox is opened. I have Dropbox, Google Drive installed. If I uninstall Dropbox only "*/*" works to open file browser. This is Android 4.4.2. I can download contents from Dropbox and for Google Drive, by getContentResolver().openInputStream(data.getData()).

Convert ascii value to char

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

Add alternating row color to SQL Server Reporting services report

Go to the table row's BackgroundColor property and choose "Expression..."

Use this expression:

= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")

This trick can be applied to many areas of the report.

And in .NET 3.5+ You could use:

= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")

Not looking for rep--I just researched this question myself and thought I'd share.

Read user input inside a loop

It looks like you read twice, the read inside the while loop is not needed. Also, you don't need to invoke the cat command:

while read input
do
    echo $input
done < filename

Why can't I use the 'await' operator within the body of a lock statement?

Basically it would be the wrong thing to do.

There are two ways this could be implemented:

  • Keep hold of the lock, only releasing it at the end of the block.
    This is a really bad idea as you don't know how long the asynchronous operation is going to take. You should only hold locks for minimal amounts of time. It's also potentially impossible, as a thread owns a lock, not a method - and you may not even execute the rest of the asynchronous method on the same thread (depending on the task scheduler).

  • Release the lock in the await, and reacquire it when the await returns
    This violates the principle of least astonishment IMO, where the asynchronous method should behave as closely as possible like the equivalent synchronous code - unless you use Monitor.Wait in a lock block, you expect to own the lock for the duration of the block.

So basically there are two competing requirements here - you shouldn't be trying to do the first here, and if you want to take the second approach you can make the code much clearer by having two separated lock blocks separated by the await expression:

// Now it's clear where the locks will be acquired and released
lock (foo)
{
}
var result = await something;
lock (foo)
{
}

So by prohibiting you from awaiting in the lock block itself, the language is forcing you to think about what you really want to do, and making that choice clearer in the code that you write.

Excel Define a range based on a cell value

Based on answer by @Cici I give here a more generic solution:

=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))

In Italian version of Excel:

=SOMMA(INDIRETTO(CONCATENA(B1;C1)):INDIRETTO(CONCATENA(B2;C2)))

Where B1-C2 cells hold these values:

  • A, 1
  • A, 5

You can change these valuese to change the final range at wish.


Splitting the formula in parts:

  • SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
  • CONCATENATE(B1,C1) - result is A1
  • INDIRECT(CONCATENATE(B1,C1)) - result is reference to A1

Hence:

=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))

results in

=SUM(A1:A5)


I'll write down here a couple of SEO keywords for Italian users:

  • come creare dinamicamente l'indirizzo di un intervallo in excel
  • formula per definire un intervallo di celle in excel.

Con la formula indicata qui sopra basta scrivere nelle caselle da B1 a C2 gli estremi dell'intervallo per vedelo cambiare dentro la formula stessa.

Differences between Oracle JDK and OpenJDK

According to the oracle blog, Oracle JDK Releases for Java 11 and Later

Starting with Java 11, Oracle will provide JDK releases under the open source GNU General Public License v2, with the Classpath Exception (GPLv2+CPE), and under a commercial license for those using the Oracle JDK as part of an Oracle product or service, or who do not wish to use open source software. This combination of using an open source license and a commercial license replaces the historical “BCL” license, which had a combination of free and paid commercial terms.

Different builds will be provided for each license, but these builds are functionally identical aside from some cosmetic and packaging differences, described in detail below.

From the BCL to the GPL

The Binary Code License for Oracle Java SE technologies (“BCL”) has been the primary license for Oracle Java SE technologies for well over a decade. The BCL permits use without license fees under certain conditions. To simplify things going forward, Oracle started providing open source licensed OpenJDK builds as of Java 9, using the same license model as the Linux platform. If you are used to getting Oracle Java SE binaries for free, you can simply continue doing so with Oracle’s OpenJDK builds available at jdk.java.net. If you are used to getting Oracle Java SE binaries as part of a commercial product or service from Oracle, then you can continue to get Oracle JDK releases through My Oracle Support (MOS), and other locations.

Functionally identical and interchangeable...

Oracle’s BCL-licensed JDK historically contained “commercial features” that were not available in OpenJDK builds. As promised, however, over the past year Oracle has contributed these features to the OpenJDK Community, including:

From Java 11 forward, therefore, Oracle JDK builds and OpenJDK builds will be essentially identical.

...yet with some cosmetic and packaging differences

There do remain a small number of differences, some intentional and cosmetic, and some simply because more time to discuss with OpenJDK contributors is warranted.

  • Oracle JDK 11 emits a warning when using the -XX:+UnlockCommercialFeatures option, whereas in OpenJDK builds this option results in an error. This option was never part of OpenJDK and it would not make sense to add it now, since there are no commercial features in OpenJDK. This difference remains in order to make it easier for users of Oracle JDK 10 and earlier releases to migrate to Oracle JDK 11 and later.
  • Oracle JDK 11 can be configured to provide usage log data to the “Advanced Management Console” tool, which is a separate commercial Oracle product. We will work with other OpenJDK contributors to discuss how such usage data may be useful in OpenJDK in future releases, if at all. This difference remains primarily to provide a consistent experience to Oracle customers until such decisions are made.
  • The javac --release command behaves differently for the Java 9 and Java 10 targets, since in those releases the Oracle JDK contained some additional modules that were not part of corresponding OpenJDK releases:
    • javafx.base
    • javafx.controls
    • javafx.fxml
    • javafx.graphics
    • javafx.media
    • javafx.web
    • java.jnlp
    • jdk.jfr
    • jdk.management.cmm
    • jdk.management.jfr
    • jdk.management.resource
    • jdk.packager.services
    • jdk.snmp

This difference remains in order to provide a consistent experience for specific kinds of legacy use. These modules are either now available separately as part of OpenJFX, are now in both OpenJDK and the Oracle JDK because they were commercial features which Oracle contributed to OpenJDK (e.g., Flight Recorder), or were removed from Oracle JDK 11 (e.g., JNLP).

  • The output of the java --version and java -fullversion commands will distinguish Oracle JDK builds from OpenJDK builds, so that support teams can diagnose any issues that may exist. Specifically, running java --version with an Oracle JDK 11 build results in:

java 11 2018-09-25

Java(TM) SE Runtime Environment 18.9 (build 11+28)

Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11+28, mixed mode)

And for an OpenJDK 11 build:

openjdk version "11" 2018-09-25

OpenJDK Runtime Environment 18.9 (build 11+28)

OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)

  • The Oracle JDK has always required third party cryptographic providers to be signed by a known certificate. The cryptography framework in OpenJDK has an open cryptographic interface, meaning it does not restrict which providers can be used. Oracle JDK 11 will continue to require a valid signature, and Oracle OpenJDK builds will continue to allow the use of either a valid signature or unsigned third party crypto provider.
  • Oracle JDK 11 will continue to include installers, branding and JRE packaging for an experience consistent with legacy desktop uses. Oracle OpenJDK builds are currently available as zip and tar.gz files, while alternative distribution formats are being considered.

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

I would add mnoGoSearch to the list. Extremely performant and flexible solution, which works as Google : indexer fetches data from multiple sites, You could use basic criterias, or invent Your own hooks to have maximal search quality. Also it could fetch the data directly from the database.

The solution is not so known today, but it feets maximum needs. You could compile and install it or on standalone server, or even on Your principal server, it doesn't need so much ressources as Solr, as it's written in C and runs perfectly even on small servers.

In the beginning You need to compile it Yourself, so it requires some knowledge. I made a tiny script for Debian, which could help. Any adjustments are welcome.

As You are using Django framework, You could use or PHP client in the middle, or find a solution in Python, I saw some articles.

And, of course mnoGoSearch is open source, GNU GPL.

$.widget is not a function

May be include Jquery Widget first, then Draggable? I guess that will solve the problem.....

Getting input values from text box

// NOTE: Using "this.pass" and "this.name" will create a global variable even though it is inside the function, so be weary of your naming convention

function submit()
{
    var userPass = document.getElementById("pass").value;
    var userName = document.getElementById("user").value;
    this.pass = userPass;
    this.name = userName; 
    alert("whatever you want to display"); 
}

Get the item doubleclick event of listview

You can get the ListView first, and then get the Selected ListViewItem. I have an example for ListBox, but ListView should be similar.

private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        ListBox box = sender as ListBox;
        if (box == null) {
            return;
        }
        MyInfo info = box.SelectedItem as MyInfo;
        if (info == null)
            return;
        /* your code here */
        }
        e.Handled = true;
    }

Keyboard shortcut to comment lines in Sublime Text 2

In the "Preferences->Key Bindings - User"

[
   { "keys": ["ctrl+7"], "command": "toggle_comment", "args": { "block": false } },
   { "keys": ["ctrl+shift+7"], "command": "toggle_comment", "args": { "block": true } }
]

Just paste it, these are will work great !

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

How to convert a hex string to hex number

Use int function with second parameter 16, to convert a hex string to an integer. Finally, use hex function to convert it back to a hexadecimal number.

print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4

Instead you could directly do

print hex(int("0xAD4", 16) + 0x200) # 0xcd4

Invalid attempt to read when no data is present

I just had this error, I was calling dr.NextResult() instead of dr.Read().

How do I pass a variable by reference?

Here is the simple (I hope) explanation of the concept pass by object used in Python.
Whenever you pass an object to the function, the object itself is passed (object in Python is actually what you'd call a value in other programming languages) not the reference to this object. In other words, when you call:

def change_me(list):
   list = [1, 2, 3]

my_list = [0, 1]
change_me(my_list)

The actual object - [0, 1] (which would be called a value in other programming languages) is being passed. So in fact the function change_me will try to do something like:

[0, 1] = [1, 2, 3]

which obviously will not change the object passed to the function. If the function looked like this:

def change_me(list):
   list.append(2)

Then the call would result in:

[0, 1].append(2)

which obviously will change the object. This answer explains it well.

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

Make a link in the Android browser start up my app?

I apologize for promoting myself, but I have a jQuery plugin to launch native apps from web links https://github.com/eusonlito/jquery.applink

You can use it easy:

<script>
$('a[data-applink]').applink();
</script>

<a href="https://facebook.com/me" data-applink="fb://profile">My Facebook Profile</a>

Convert canvas to PDF

So for today, jspdf-1.5.3. To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this. We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.

  // Download button
  $("#download-image").on('click', function () {
    let width = __CANVAS.width; 
    let height = __CANVAS.height;

    //set the orientation
    if(width > height){
      pdf = new jsPDF('l', 'px', [width, height]);
    }
    else{
      pdf = new jsPDF('p', 'px', [height, width]);
    }
    //then we get the dimensions from the 'pdf' file itself
    width = pdf.internal.pageSize.getWidth();
    height = pdf.internal.pageSize.getHeight();
    pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
    pdf.save("download.pdf");
  });

Learnt about switching orientations from here: https://github.com/MrRio/jsPDF/issues/476

How to make a WPF window be on top of all other windows of my app (not system wide)?

Just learning C# and ran across similar situation. but found a solution that I think may help. You may have figured this a long time ago. this will be from starting a new project but you can use it in any.

1) Start new project.

2) go to Project, then New Windows form, then select Windows Form and name Splash.

3) set size, background, text, etc as desired.

4) Under Properties of the Splash.cs form set Start Position: CenterScreen and TopMost: true

5) form1 add "using System.Threading;"

6) form1 under class add "Splash splashscreen = new Splash();"

7) form1 add "splashscreen.Show();" and "Application.DoEvents();"

8) form1 Under Events>>Focus>>Activated add "Thread.Sleep(4000); splashscreen.Close();"

9) Splash.cs add under "Public Splash" add "this.BackColor = Color.Aqua;" /can use any color

10) This is the code for Form1.cs

public partial class Form1 : Form
{
    Splash splashscreen = new Splash();
    public Form1()
    {
        InitializeComponent();
        splashscreen.Show();
        Application.DoEvents();

    }

    private void Form1_Activated(object sender, EventArgs e)
    {
        Thread.Sleep(4000);
        splashscreen.Close();
    }
}

11) this is the code on Splash.cs

public partial class Splash : Form
{
    public Splash()
    {
        InitializeComponent();
        this.BackColor = Color.Aqua;
    }
}

12) I found that if you do NOT do something in the splash then the screen will not stay on the top for the time the first form needs to activate. The Thread count will disappear the splash after x seconds, so your program is normal.

Android- create JSON Array and JSON Object

JSONObject jsonResult = new JSONObject();
try {
  jsonResult.put("clave", "valor");
  jsonResult.put("username", "iesous");
  jsonResult.put("password", "1234");

} catch (JSONException e) {
  // TODO Auto-generated catch block
 e.printStackTrace();
}

Log.d("DEV","jsonResult->"+jsonResult);

Debug JavaScript in Eclipse

It's possible to debug JavaScript by setting breakpoints in Eclipse using the AJAX Tools Framework.

Creating executable files in Linux

Make file executable:

chmod +x file

Find location of perl:

which perl

This should return something like

/bin/perl sometimes /usr/local/bin

Then in the first line of your script add:

#!"path"/perl with path from above e.g.

#!/bin/perl

Then you can execute the file

./file

There may be some issues with the PATH, so you may want to change that as well ...

Increasing nesting function calls limit

Personally I would suggest this is an error as opposed to a setting that needs adjusting. In my code it was because I had a class that had the same name as a library within one of my controllers and it seemed to trip it up.

Output errors and see where this is being triggered.

PRINT statement in T-SQL

The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.

Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.

It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

How to swap String characters in Java?

This has been answered a few times but here's one more just for fun :-)

public class Tmp {
    public static void main(String[] args) {
        System.out.println(swapChars("abcde", 0, 1));
    }
    private static String swapChars(String str, int lIdx, int rIdx) {
        StringBuilder sb = new StringBuilder(str);
        char l = sb.charAt(lIdx), r = sb.charAt(rIdx);
        sb.setCharAt(lIdx, r);
        sb.setCharAt(rIdx, l);
        return sb.toString();
    }
}

What is the proper way to comment functions in Python?

I would go a step further than just saying "use a docstring". Pick a documentation generation tool, such as pydoc or epydoc (I use epydoc in pyparsing), and use the markup syntax recognized by that tool. Run that tool often while you are doing your development, to identify holes in your documentation. In fact, you might even benefit from writing the docstrings for the members of a class before implementing the class.

How do I declare and use variables in PL/SQL like I do in T-SQL?

Revised Answer

If you're not calling this code from another program, an option is to skip PL/SQL and do it strictly in SQL using bind variables:

var myname varchar2(20);

exec :myname := 'Tom';

SELECT *
FROM   Customers
WHERE  Name = :myname;

In many tools (such as Toad and SQL Developer), omitting the var and exec statements will cause the program to prompt you for the value.


Original Answer

A big difference between T-SQL and PL/SQL is that Oracle doesn't let you implicitly return the result of a query. The result always has to be explicitly returned in some fashion. The simplest way is to use DBMS_OUTPUT (roughly equivalent to print) to output the variable:

DECLARE
   myname varchar2(20);
BEGIN
     myname := 'Tom';

     dbms_output.print_line(myname);
END;

This isn't terribly helpful if you're trying to return a result set, however. In that case, you'll either want to return a collection or a refcursor. However, using either of those solutions would require wrapping your code in a function or procedure and running the function/procedure from something that's capable of consuming the results. A function that worked in this way might look something like this:

CREATE FUNCTION my_function (myname in varchar2)
     my_refcursor out sys_refcursor
BEGIN
     open my_refcursor for
     SELECT *
     FROM   Customers
     WHERE  Name = myname;

     return my_refcursor;
END my_function;

PHP cURL, extract an XML response

Just add header('Content-type: application/xml'); before your echo of the XML response and you will see an XML page.

Export javascript data to CSV file without server interaction

See adeneo's answer, but to make this work in Excel in all countries you should add "SEP=," to the first line of the file. This will set the standard separator in Excel and will not show up in the actual document

var csvString = "SEP=, \n" + csvRows.join("\r\n");

How do I draw a grid onto a plot in Python?

To show a grid line on every tick, add

plt.grid(True)

For example:

import matplotlib.pyplot as plt

points = [
    (0, 10),
    (10, 20),
    (20, 40),
    (60, 100),
]

x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))

plt.scatter(x, y)
plt.grid(True)

plt.show()

enter image description here


In addition, you might want to customize the styling (e.g. solid line instead of dashed line), add:

plt.rc('grid', linestyle="-", color='black')

For example:

import matplotlib.pyplot as plt

points = [
    (0, 10),
    (10, 20),
    (20, 40),
    (60, 100),
]

x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))

plt.rc('grid', linestyle="-", color='black')
plt.scatter(x, y)
plt.grid(True)

plt.show()

enter image description here

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

Android Calling JavaScript functions in WebView

public void run(final String scriptSrc) { 
        webView.post(new Runnable() {
            @Override
            public void run() { 
                webView.loadUrl("javascript:" + scriptSrc); 
            }
        }); 
    }

Combine Multiple child rows into one row MYSQL

What you want is called a pivot, and it's not directly supported in MySQL, check this answer out for the options you've got:

How to pivot a MySQL entity-attribute-value schema

How to connect mySQL database using C++

I had to include -lmysqlcppconn to my build in order to get it to work.

How do I do a case-insensitive string comparison?

Assuming ASCII strings:

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

C - The %x format specifier

The format string attack on printf you mentioned isn't specific to the "%x" formatting - in any case where printf has more formatting parameters than passed variables, it will read values from the stack that do not belong to it. You will get the same issue with %d for example. %x is useful when you want to see those values as hex.

As explained in previous answers, %08x will produce a 8 digits hex number, padded by preceding zeros.

Using the formatting in your code example in printf, with no additional parameters:

printf ("%08x %08x %08x %08x");

Will fetch 4 parameters from the stack and display them as 8-digits padded hex numbers.

How can I get my Android device country code without using GPS?

To get country code

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

public String makeServiceCall() {
    String response = null;
    String reqUrl = "https://ipinfo.io/country";
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

Passing parameters to a Bash function

A simple example that will clear both during executing script or inside script while calling a function.

#!/bin/bash
echo "parameterized function example"
function print_param_value(){
    value1="${1}" # $1 represent first argument
    value2="${2}" # $2 represent second argument
    echo "param 1 is  ${value1}" # As string
    echo "param 2 is ${value2}"
    sum=$(($value1+$value2)) # Process them as number
    echo "The sum of two value is ${sum}"
}
print_param_value "6" "4" # Space-separated value
# You can also pass parameters during executing the script
print_param_value "$1" "$2" # Parameter $1 and $2 during execution

# Suppose our script name is "param_example".
# Call it like this:
#
# ./param_example 5 5
#
# Now the parameters will be $1=5 and $2=5

ReCaptcha API v2 Styling

You can recreate recaptcha , wrap it in a container and only let the checkbox visible. My main problem was that I couldn't take the full width so now it expands to the container width. The only problem is the expiration you can see a flick but as soon it happens I reset it.

See this demo http://codepen.io/alejandrolechuga/pen/YpmOJX

enter image description here

_x000D_
_x000D_
function recaptchaReady () {_x000D_
  grecaptcha.render('myrecaptcha', {_x000D_
  'sitekey': '6Lc7JBAUAAAAANrF3CJaIjt7T9IEFSmd85Qpc4gj',_x000D_
  'expired-callback': function () {_x000D_
    grecaptcha.reset();_x000D_
    console.log('recatpcha');_x000D_
  }_x000D_
});_x000D_
}
_x000D_
.recaptcha-wrapper {_x000D_
    height: 70px;_x000D_
  overflow: hidden;_x000D_
  background-color: #F9F9F9;_x000D_
  border-radius: 3px;_x000D_
  box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);_x000D_
  -webkit-box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);_x000D_
  -moz-box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);_x000D_
  height: 70px;_x000D_
  position: relative;_x000D_
  margin-top: 17px;_x000D_
  border: 1px solid #d3d3d3;_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.recaptcha-info {_x000D_
  background-size: 32px;_x000D_
  height: 32px;_x000D_
  margin: 0 13px 0 13px;_x000D_
  position: absolute;_x000D_
  right: 8px;_x000D_
  top: 9px;_x000D_
  width: 32px;_x000D_
  background-image: url(https://www.gstatic.com/recaptcha/api2/logo_48.png);_x000D_
  background-repeat: no-repeat;_x000D_
}_x000D_
.rc-anchor-logo-text {_x000D_
  color: #9b9b9b;_x000D_
  cursor: default;_x000D_
  font-family: Roboto,helvetica,arial,sans-serif;_x000D_
  font-size: 10px;_x000D_
  font-weight: 400;_x000D_
  line-height: 10px;_x000D_
  margin-top: 5px;_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  right: 10px;_x000D_
  top: 37px;_x000D_
}_x000D_
.rc-anchor-checkbox-label {_x000D_
  font-family: Roboto,helvetica,arial,sans-serif;_x000D_
  font-size: 14px;_x000D_
  font-weight: 400;_x000D_
  line-height: 17px;_x000D_
  left: 50px;_x000D_
  top: 26px;_x000D_
  position: absolute;_x000D_
  color: black;_x000D_
}_x000D_
.rc-anchor .rc-anchor-normal .rc-anchor-light {_x000D_
  border: none;_x000D_
}_x000D_
.rc-anchor-pt {_x000D_
  color: #9b9b9b;_x000D_
  font-family: Roboto,helvetica,arial,sans-serif;_x000D_
  font-size: 8px;_x000D_
  font-weight: 400;_x000D_
  right: 10px;_x000D_
  top: 53px;_x000D_
  position: absolute;_x000D_
  a:link {_x000D_
    color: #9b9b9b;_x000D_
    text-decoration: none;_x000D_
  }_x000D_
}_x000D_
_x000D_
g-recaptcha {_x000D_
  // transform:scale(0.95);_x000D_
  // -webkit-transform:scale(0.95);_x000D_
  // transform-origin:0 0;_x000D_
  // -webkit-transform-origin:0 0;_x000D_
_x000D_
}_x000D_
_x000D_
.g-recaptcha {_x000D_
  width: 41px;_x000D_
_x000D_
  /* border: 1px solid red; */_x000D_
  height: 38px;_x000D_
  overflow: hidden;_x000D_
  float: left;_x000D_
  margin-top: 16px;_x000D_
  margin-left: 6px;_x000D_
  _x000D_
    > div {_x000D_
    width: 46px;_x000D_
    height: 30px;_x000D_
    background-color:  #F9F9F9;_x000D_
    overflow: hidden;_x000D_
    border: 1px solid red;_x000D_
    transform: translate3d(-8px, -19px, 0px);_x000D_
  }_x000D_
  div {_x000D_
    border: 0;_x000D_
  }_x000D_
}
_x000D_
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaReady&&render=explicit'></script>_x000D_
_x000D_
<div class="recaptcha-wrapper">_x000D_
  <div id="myrecaptcha" class="g-recaptcha"></div>_x000D_
          <div class="rc-anchor-checkbox-label">I'm not a Robot.</div>_x000D_
        <div class="recaptcha-info"></div>_x000D_
        <div class="rc-anchor-logo-text">reCAPTCHA</div>_x000D_
        <div class="rc-anchor-pt">_x000D_
          <a href="https://www.google.com/intl/en/policies/privacy/" target="_blank">Privacy</a>_x000D_
          <span aria-hidden="true" role="presentation"> - </span>_x000D_
          <a href="https://www.google.com/intl/en/policies/terms/" target="_blank">Terms</a>_x000D_
        </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Activate a virtualenv with a Python script

It turns out that, yes, the problem is not simple, but the solution is.

First I had to create a shell script to wrap the "source" command. That said I used the "." instead, because I've read that it's better to use it than source for Bash scripts.

#!/bin/bash
. /path/to/env/bin/activate

Then from my Python script I can simply do this:

import os
os.system('/bin/bash --rcfile /path/to/myscript.sh')

The whole trick lies within the --rcfile argument.

When the Python interpreter exits it leaves the current shell in the activated environment.

Win!

Bubble Sort Homework

idk if this might help you after 9 years... its a simple bubble sort program

    l=[1,6,3,7,5,9,8,2,4,10]

    for i in range(1,len(l)):
        for j in range (i+1,len(l)):
            if l[i]>l[j]:
                l[i],l[j]=l[j],l[i]

How do I determine whether an array contains a particular value in Java?

ObStupidAnswer (but I think there's a lesson in here somewhere):

enum Values {
    AB, BC, CD, AE
}

try {
    Values.valueOf(s);
    return true;
} catch (IllegalArgumentException exc) {
    return false;
}

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

Runnable with a parameter?

theView.post(new Runnable() {
    String str;
    @Override                            
    public void run() {
        par.Log(str);                              
    }
    public Runnable init(String pstr) {
        this.str=pstr;
        return(this);
    }
}.init(str));

Create init function that returns object itself and initialize parameters with it.

Adding an external directory to Tomcat classpath

In Tomcat 6, the CLASSPATH in your environment is ignored. In setclasspath.bat you'll see

set CLASSPATH=%JAVA_HOME%\lib\tools.jar

then in catalina.bat, it's used like so

%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS% 
-Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" 
-Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" 
-Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%

I don't see any other vars that are included, so I think you're stuck with editing setclasspath.bat and changing how CLASSPATH is built. For Tomcat 6.0.20, this change was on like 74 of setclasspath.bat

set CLASSPATH=C:\app_config\java_app;%JAVA_HOME%\lib\tools.jar

Execution failed for task :':app:mergeDebugResources'. Android Studio

Try clean project...

If it doesn't work... Then... Goto build.gradle in project section

Try downgrading the gradle version

From...

dependencies {
    classpath 'com.android.tools.build:gradle:1.5.0'
}

To...

dependencies {
    classpath 'com.android.tools.build:gradle:1.2.0'
}

Then gradle.properties, add this

 org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m

Sync it... Clean/Rebuild... It worked for me... So, I am sharing...

How can strip whitespaces in PHP's variable?

You can do it by using ereg_replace

 $str = 'This Is New Method Ever';
 $newstr = ereg_replace([[:space:]])+', '',  trim($str)):
 echo $newstr
 // Result - ThisIsNewMethodEver

How to add jQuery code into HTML Page

  1. Create a file for the jquery eg uploadfuntion.js.
  2. Save that file in the same folder as website or in subfolder.
  3. In head section of your html page paste: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

and then the reference to your script eg: <script src="uploadfuntion.js"> </script>

4.Lastly you should ensure there are elements that match the selectors in the code.

Opening Chrome From Command Line

you can create batch file and insert into it the bellow line:

cmd /k start chrome "http://yourWebSite.com

after that you do just double click on this batch file.

How can I get the file name from request.FILES?

request.FILES['filename'].name

From the request documentation.

If you don't know the key, you can iterate over the files:

for filename, file in request.FILES.iteritems():
    name = request.FILES[filename].name

How to calculate the running time of my program?

Use System.currentTimeMillis() or System.nanoTime() if you want even more precise reading. Usually, milliseconds is precise enough if you need to output the value to the user. Moreover, System.nanoTime() may return negative values, thus it may be possible that, if you're using that method, the return value is not correct.

A general and wide use would be to use milliseconds :

long start = System.currentTimeMillis();

... 


long end = System.currentTimeMillis();

NumberFormat formatter = new DecimalFormat("#0.00000");
System.out.print("Execution time is " + formatter.format((end - start) / 1000d) + " seconds");

Note that nanoseconds are usually used to calculate very short and precise program executions, such as unit testing and benchmarking. Thus, for overall program execution, milliseconds are preferable.

Best Timer for using in a Windows service

Either one should work OK. In fact, System.Threading.Timer uses System.Timers.Timer internally.

Having said that, it's easy to misuse System.Timers.Timer. If you don't store the Timer object in a variable somewhere, then it is liable to be garbage collected. If that happens, your timer will no longer fire. Call the Dispose method to stop the timer, or use the System.Threading.Timer class, which is a slightly nicer wrapper.

What problems have you seen so far?

Cross-Origin Read Blocking (CORB)

have you tried changing the dataType in your ajax request from jsonp to json? that fixed it in my case.

How to install PHP intl extension in Ubuntu 14.04

May be universe repository is disabled, here is your package in it

Enable it

sudo add-apt-repository universe

Update

sudo apt-get update

And install

sudo apt-get install php5-intl

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

find . -name \*.cc -print0 -or -name \*.h -print0 | xargs -0 grep "hello".

Check the manual pages for find and xargs for details.

TLS 1.2 not working in cURL

TLS 1.1 and TLS 1.2 are supported since OpenSSL 1.0.1

Forcing TLS 1.1 and 1.2 are only supported since curl 7.34.0

You should consider an upgrade.

Styling input buttons for iPad and iPhone

You may be looking for

-webkit-appearance: none;

Install a module using pip for specific python version

I had Python 2.7 installed via chocolatey on Windows and found pip2.7.exe in C:\tools\python2\Scripts.

Using this executable instead of the pip command installed the correct module for me (requests for Python 2.7).

Cannot find pkg-config error

if you have this error :

configure: error: Either a previously installed pkg-config or "glib-2.0 >= 2.16" could not be found. Please set GLIB_CFLAGS and GLIB_LIBS to the correct values or pass --with-internal-glib to configure to use the bundled copy.

Instead of do this command :

$ ./configure && make install

Do that :

./configure --with-internal-glib && make install

How to avoid the "Circular view path" exception with Spring MVC test

In my case, I was trying out Kotlin + Spring boot and I got into the Circular View Path issue. All the suggestions I got online could not help, until I tried the below:

Originally I had annotated my controller using @Controller

import org.springframework.stereotype.Controller

I then replaced @Controller with @RestController

import org.springframework.web.bind.annotation.RestController

And it worked.

How do I print colored output to the terminal in Python?

I suggest sty. It's similar to colorama, but less verbose and it supports 8bit and 24bit colors. You can also extend the color register with your own colors.

Examples:

from sty import fg, bg, ef, rs

foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs

# Add custom colors:

from sty import Style, RgbFg

fg.orange = Style(RgbFg(255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs

print(foo, bar, baz, qux, qui, buf, sep='\n')

enter image description here

Demo:

enter image description here

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

I was getting the same error on a restored database when I tried to insert a new record using the EntityFramework. It turned out that the Indentity/Seed was screwing things up.

Using a reseed command fixed it.

DBCC CHECKIDENT ('[Prices]', RESEED, 4747030);GO

Failed to execute 'createObjectURL' on 'URL':

UPDATE

Consider avoiding createObjectURL() method, while browsers are disabling support for it. Just attach MediaStream object directly to the srcObject property of HTMLMediaElement e.g. <video> element.

const mediaStream = new MediaStream();
const video = document.getElementById('video-player');
video.srcObject = mediaStream;

However, if you need to work with MediaSource, Blob or File, you have to create a URL with URL.createObjectURL() and assign it to HTMLMediaElement.src.

Read more details here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject


Older Answer

I experienced same error, when I passed to createObjectURL raw data:

window.URL.createObjectURL(data)

It has to be Blob, File or MediaSource object, not data itself. This worked for me:

var binaryData = [];
binaryData.push(data);
window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"}))

Check also the MDN for more info: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

Variable is accessed within inner class. Needs to be declared final

    public class ConfigureActivity extends Activity {

        EditText etOne;
        EditText etTwo;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_configure);

            Button btnConfigure = findViewById(R.id.btnConfigure1);   
            btnConfigure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            configure();
                        }
                    });
    }

    public  void configure(){
            String one = etOne.getText().toString();
            String two = etTwo.getText().toString();
    }
}

Can't compare naive and aware datetime.now() <= challenge.datetime_end

You are trying to set the timezone for date_time which already has a timezone. Use replace and astimezone functions.

local_tz = pytz.timezone('Asia/Kolkata')

current_time = datetime.now().replace(tzinfo=pytz.utc).astimezone(local_tz)

'Field required a bean of type that could not be found.' error spring restful API using mongodb

In my case i have just put the Class MyprojectApplication in a package(com.example.start) with the same level of model, controller,service packages.

Format a Go string without printing?

I came to this page specifically looking for a way to format an error string. So if someone needs help with the same, you want to use the fmt.Errorf() function.

The method signature is func Errorf(format string, a ...interface{}) error. It returns the formatted string as a value that satisfies the error interface.

You can look up more details in the documentation - https://golang.org/pkg/fmt/#Errorf.

Regex to check with starts with http://, https:// or ftp://

You need a whole input match here.

System.out.println(test.matches("^(http|https|ftp)://.*$")); 

Edit:(Based on @davidchambers's comment)

System.out.println(test.matches("^(https?|ftp)://.*$")); 

restrict edittext to single line

Use android:maxLines="1" and android:inputType="text"

You forgot the android:maxLines attribute. And refer for android:inputType With your example, below will give this result:

<EditText 
    android:id="@+id/searchbox"  
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:inputType="text"
    android:scrollHorizontally="true"
    android:ellipsize="end"
    android:layout_weight="1"
    android:layout_marginTop="2dp"
    android:drawablePadding="10dp"
    android:background="@drawable/edittext"
    android:drawableLeft="@drawable/folder_full"
    android:drawableRight="@drawable/search"
    android:paddingLeft="15dp"
    android:hint="search...">
</EditText>

NameError: global name is not defined

Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:

import module

over

from module import function/class

Decompile .smali files on an APK

My recommendation is Virtuous Ten Studio. The tool is free but they suggest a donation. It combines all the necessary steps (unpacking APK, baksmaliing, decompiling, etc.) into one easy-to-use UI-based import process. Within five minutes you should have Java source code, less than it takes to figure out the command line options of one of the above mentioned tools.

Decompiling smali to Java is an inexact process, especially if the smali artifacts went through an obfuscator. You can find several decompilers on the web but only some of them are still maintained. Some will give you better decompiled code than others. Read "better" as in "more understandable" than others. Don't expect that the reverse-engineered Java code will compile out of the box. Virtuous Ten Studio comes with multiple free Java decompilers built-in so you can easily try out different decompilers (the "Generate Java source" step) to see which one gives you the best results, saving you the time to find those decompilers yourself and figure out how to use them. Amongst them is CFR, which is one of the few free and still maintained decompilers.

As output you receive, amongst other things, a folder structure that contains all the decompiled Java source code. You can then import this into IntelliJ IDEA or Eclipse for further editing, analysis (e.g. Go to definition, Find usages), etc.

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

What is the best way to create and populate a numbers table?

I know this thread is old and answered, but there is a way to squeeze a little extra performance out of Method 7:

Instead of this (essentially method 7 but with some ease of use polish):

DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM sys.objects s1       --use sys.columns if you don't get enough rows returned to generate all the numbers you need
    CROSS JOIN sys.objects s2 --use sys.co
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'

Try this:

DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM        (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T32]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T64]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T128]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T256]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T512]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T1024]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2048]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4096]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8192]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16384]
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'

On my server this takes ~10 ms as opposed to the ~16-20 ms when selecting from sys.objects. It also has the added benefit of not being dependent on how many objects are in sys.objects. While it's pretty safe, it's technically a dependency and the other one goes faster anyway. I think the speed boost is down to using BITs if you change:

DECLARE @BIT AS BIT = 0

to:

DECLARE @BIT AS BIGINT = 0

It adds ~8-10 ms to the total time on my server. That said, when you scale up to 1,000,000 records BIT vs BIGINT doesn't appreciably affect my query anymore, but it still runs around ~680ms vs ~730ms from sys.objects.

Adding form action in html in laravel

Form Post Action :

<form method="post" action="{{url('login')}}" accept-charset="UTF-8">

Change your Route : In Routes -> Web.php

Route::post('login','WelcomeController@log_in');

How to zip a file using cmd line?

If you are using Ubuntu Linux:

  1. Install zip

    sudo apt-get install zip
    
  2. Zip your folder:

    zip -r {filename.zip} {foldername}
    

If you are using Microsoft Windows:

Windows does not come with a command-line zip program, despite Windows Explorer natively supporting Zip files since the Plus! pack for Windows 98.

I recommend the open-source 7-Zip utility which includes a command-line executable and supports many different archive file types, especially its own *.7z format which offers superior compression ratios to traditional (PKZIP) *.zip files:

  1. Download 7-Zip from the 7-Zip home page

  2. Add the path to 7z.exe to your PATH environment variable. See this QA: How to set the path and environment variables in Windows

  3. Open a new command-prompt window and use this command to create a PKZIP *.zip file:

    7z a -tzip {yourfile.zip} {yourfolder}
    

Cross-platform Java:

If you have the Java JDK installed then you can use the jar utility to create Zip files, as *.jar files are essentially just renamed *.zip (PKZIP) files:

jar -cfM {yourfile.zip} {yourfolder}

Explanation: * -c compress * -f specify filename * -M do not include a MANIFEST file

Specify JDK for Maven to use

compile:compile has a user property that allows you to specify a path to the javac.

Note that this user property only works when fork is true which is false by default.

$ mvn -Dmaven.compiler.fork=true -Dmaven.compiler.executable=/path/to/the/javac compile

You might have to double quote the value if it contains spaces.

> mvn -Dmaven.compiler.fork=true -Dmaven.compiler.executable="C:\...\javac" compile

See also Maven custom properties precedence.

How can I monitor the thread count of a process on linux?

$ ps H p pid-id

H - Lists all the individual threads in a process

or

$cat /proc/pid-id/status

pid-id is the Process ID

eg.. (Truncated the below output)

root@abc:~# cat /proc/8443/status
Name:   abcdd
State:  S (sleeping)
Tgid:   8443
VmSwap:        0 kB
Threads:    4
SigQ:   0/256556
SigPnd: 0000000000000000

How do I detect a click outside an element?

For touch devices like iPad and iPhone we can use this code:

$(document).on('touchstart', function (event) {
    var container = $("YOUR CONTAINER SELECTOR");

    if (!container.is(e.target) &&            // If the target of the click isn't the container...
        container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

How to make a gap between two DIV within the same column

#firstDropContainer{
float: left; 
width: 40%; 
margin-right: 1.5em; 

}

#secondDropContainer{
float: left; 
width: 40%;
margin-bottom: 1em;
}



<div id="mainDrop">
    <div id="firstDropContainer"></div>
    <div id="secondDropContainer"></div>
</div>

Note: Adjust the width of the divs based on your req. 

Font Awesome & Unicode

I found that this worked

content: "\f2d7" !important;
font-family: FontAwesome !important;

It didn't seem to work without the !important for me.

Here's a tutorial on how to change social icons with Unicodes https://www.youtube.com/watch?v=-jgDs2agkE0&feature=youtu.be

How do you delete an ActiveRecord object?

It's destroy and destroy_all methods, like

user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)

Alternatively you can use delete and delete_all which won't enforce :before_destroy and :after_destroy callbacks or any dependent association options.

User.delete_all(condition: 'value') will allow you to delete records without a primary key

Note: from @hammady's comment, user.destroy won't work if User model has no primary key.

Note 2: From @pavel-chuchuva's comment, destroy_all with conditions and delete_all with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html

Test file upload using HTTP PUT method

curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"

How to print Boolean flag in NSLog?

Booleans are nothing but integers only, they are just type casted values like...

typedef signed char     BOOL; 

#define YES (BOOL)1
#define NO (BOOL)0

BOOL value = YES; 
NSLog(@"Bool value: %d",value);

If output is 1,YES otherwise NO

Looping over a list in Python

Here is the solution I was looking for. If you would like to create List2 that contains the difference of the number elements in List1.

list1 = [12, 15, 22, 54, 21, 68, 9, 73, 81, 34, 45]
list2 = []
for i in range(1, len(list1)):
  change = list1[i] - list1[i-1]
  list2.append(change)

Note that while len(list1) is 11 (elements), len(list2) will only be 10 elements because we are starting our for loop from element with index 1 in list1 not from element with index 0 in list1

Purge or recreate a Ruby on Rails database

In Rails 6 there is a convenient way for resetting DB and planting seeds again:

rails db:seed:replant # Truncates tables of each database for current environment and loads the seeds

https://weblog.rubyonrails.org/2019/3/15/this-week-in-rails-security-fixes-bulk-insert-and-upsert-seeds-replanting/

How to pick a new color for each plotted line within a figure in matplotlib?

I don't know if you can automatically change the color, but you could exploit your loop to generate different colors:

for i in range(20):
   ax1.plot(x, y, color = (0, i / 20.0, 0, 1)

In this case, colors will vary from black to 100% green, but you can tune it if you want.

See the matplotlib plot() docs and look for the color keyword argument.

If you want to feed a list of colors, just make sure that you have a list big enough and then use the index of the loop to select the color

colors = ['r', 'b', ...., 'w']

for i in range(20):
   ax1.plot(x, y, color = colors[i])

How to run server written in js with Node.js

Just try

node server

from cmd prompt in that directory

how to get html content from a webview?

above given methods are for if you have an web url ,but if you have an local html then you can have also html by this code

AssetManager mgr = mContext.getAssets();
             try {
InputStream in = null;              
if(condition)//you have a local html saved in assets
                            {
                            in = mgr.open(mFileName,AssetManager.ACCESS_BUFFER);
                           }
                            else if(condition)//you have an url
                            {
                            URL feedURL = new URL(sURL);
                  in = feedURL.openConnection().getInputStream();}

                            // here you will get your html
                 String sHTML = streamToString(in);
                 in.close();

                 //display this html in the browser or web view              


             } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             }
        public static String streamToString(InputStream in) throws IOException {
            if(in == null) {
                return "";
            }

            Writer writer = new StringWriter();
            char[] buffer = new char[1024];

            try {
                Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));

                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }

            } finally {

            }

            return writer.toString();
        }

HTML embedded PDF iframe

Iframe

<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>

Object

<object data="your_url_to_pdf" type="application/pdf">
  <embed src="your_url_to_pdf" type="application/pdf" />
</object>

Java Spring - How to use classpath to specify a file location?

From an answer of @NimChimpsky in similar question:

Resource resource = new ClassPathResource("storedProcedures.sql");
InputStream resourceInputStream = resource.getInputStream();

Using ClassPathResource and interface Resource. And make sure you are adding the resources directory correctly (adding /src/main/resources/ into the classpath).

Note that Resource have a method to get a java.io.File so you can also use:

Resource resource = new ClassPathResource("storedProcedures.sql");
FileReader fr = new FileReader(resource.getFile());

Any way to generate ant build.xml file automatically from Eclipse?

If all you need is the classpath entries, I do something like the following to use the eclipse build path.

<xmlproperty file=".classpath" collapseAttributes="true" delimiter=";" />

Then set that value in the path

<path id="eclipse.classpath">
    <pathelement path="${classpath.classpathentry.path}"/>
</path>


<target name="compile" depends="init">

    <javac srcdir="${src}" destdir="${build}" updatedProperty="compiled">
        <classpath refid="eclipse.classpath"/>
    </javac>
</target>

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

For my case the issue was that the types were not getting added to package.json file under devDependencies to fix it I ran npm install --save-dev @types/react-redux note the --save-dev

PHP Warning: Invalid argument supplied for foreach()

This means that you are doing a foreach on something that is not an array.

Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.

Then fix the one where it isn't an array.

How to reproduce this error:

<?php
$skipper = "abcd";
foreach ($skipper as $item){       //the warning happens on this line.
    print "ok";
}
?>

Make sure $skipper is an array.

"java.lang.OutOfMemoryError : unable to create new native Thread"

your JBoss configuration has some issues, /opt/jrockit-jdk1.6/bin/java -Xms512m -Xmx512m Xms and Xmx are limiting your JBoss memory usage, to the configured value, so from the 8Gb you have the server is only ussing 512M + some extra for his own purpose, increase that number, remember to leave some free for the OS and other stuff running there and may be you get it running despite de unsavoury code. Fixing the code would be nice too, if you can.

Compare two date formats in javascript/jquery

This is already in :

Age from Date of Birth using JQuery

or alternatively u can use Date.parse() as in

var date1 = new Date("10/25/2011");
var date2 = new Date("09/03/2010");
var date3 = new Date(Date.parse(date1) - Date.parse(date2));

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

Using REQUIRES_NEW is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED - it will create a new transaction.

That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional, it will create a new transaction.

So, with that in mind, if using REQUIRES_NEW makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.

On rollback - using REQUIRES_NEW will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.

Python slice first and last element in list

I found this might do this:

list[[0,-1]]

Import a module from a relative path

Simply you can use: from Desktop.filename import something

Example:

given that the file is name test.py in directory Users/user/Desktop , and will import everthing.

the code:

from Desktop.test import *

But make sure you make an empty file called "__init__.py" in that directory

Angular 6 Material mat-select change method removed

For:

1) mat-select (selectionChange)="myFunction()" works in angular as:

sample.component.html

 <mat-select placeholder="Select your option" [(ngModel)]="option" name="action" 
      (selectionChange)="onChange()">
     <mat-option *ngFor="let option of actions" [value]="option">
       {{option}}
     </mat-option>
 </mat-select>

sample.component.ts

actions=['A','B','C'];
onChange() {
  //Do something
}

2) Simple html select (change)="myFunction()" works in angular as:

sample.component.html

<select (change)="onChange()" [(ngModel)]="regObj.status">
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>

sample.component.ts

onChange() {
  //Do something
}

data.map is not a function

this.$http.get('https://pokeapi.co/api/v2/pokemon')
.then(response => {
   if(response.status === 200)
   {
      this.usuarios = response.data.results.map(usuario => {
      return { name: usuario.name, url: usuario.url, captched: false } })
          }
    })
.catch( error => { console.log("Error al Cargar los Datos: " + error ) } )

Modulo operator in Python

Same thing you'd expect from normal modulo .. e.g. 7 % 4 = 3, 7.3 % 4.0 = 3.3

Beware of floating point accuracy issues.

File upload from <input type="file">

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input name="file" type="file" (change)="onChange($event)"/>
    </div>
  `,
  providers: [ UploadService ]
})
export class AppComponent {
  file: File;
  onChange(event: EventTarget) {
        let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
        let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
        let files: FileList = target.files;
        this.file = files[0];
        console.log(this.file);
    }

   doAnythingWithFile() {
   }

}

Duplicate AssemblyVersion Attribute

My error was that I was also referencing another file in my project, which was also containing a value for the attribute "AssemblyVersion". I removed that attribute from one of the file and it is now working properly.

The key is to make sure that this value is not declared more than once in any file in your project.

How to Populate a DataTable from a Stored Procedure

Use the SqlDataAdapter, this would simplify everything.

//Your code to this point
DataTable dt = new DataTable();

using(var cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
  using(var da = new SqlDataAdapter(cmd))
  {
      da.Fill(dt):
  }
}

and your DataTable will have the information you are looking for, so long as your stored proceedure returns a data set (cursor).

Convert a byte array to integer in Java and vice versa

A basic implementation would be something like this:

public class Test {
    public static void main(String[] args) {
        int[] input = new int[] { 0x1234, 0x5678, 0x9abc };
        byte[] output = new byte[input.length * 2];

        for (int i = 0, j = 0; i < input.length; i++, j+=2) {
            output[j] = (byte)(input[i] & 0xff);
            output[j+1] = (byte)((input[i] >> 8) & 0xff);
        }

        for (int i = 0; i < output.length; i++)
            System.out.format("%02x\n",output[i]);
    }
}

In order to understand things you can read this WP article: http://en.wikipedia.org/wiki/Endianness

The above source code will output 34 12 78 56 bc 9a. The first 2 bytes (34 12) represent the first integer, etc. The above source code encodes integers in little endian format.

How to convert an entire MySQL database characterset and collation to UTF-8?

Before proceeding, ensure that you: Have completed a full database backup!

Step 1: Database Level Changes

  • Identifying the Collation and Character set of your database

    SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM 
    information_schema.SCHEMATA S
    WHERE schema_name = 'your_database_name'
    AND
    (DEFAULT_CHARACTER_SET_NAME != 'utf8'
        OR
     DEFAULT_COLLATION_NAME not like 'utf8%');
    
  • Fixing the collation for the database

    ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
    

Step 2: Table Level Changes

  • Identifying Database Tables with the incorrect character set or collation

    SELECT CONCAT(
    'ALTER TABLE ',  table_name, ' CHARACTER SET utf8 COLLATE utf8_general_ci;  ', 
    'ALTER TABLE ',  table_name, ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  ')
    FROM information_schema.TABLES AS T, information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` AS C
    WHERE C.collation_name = T.table_collation
    AND T.table_schema = 'your_database_name'
    AND
    (C.CHARACTER_SET_NAME != 'utf8'
        OR
     C.COLLATION_NAME not like 'utf8%')
    
  • Adjusting table columns' collation and character set

Capture upper sql output and run it. (like following)

ALTER TABLE rma CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
ALTER TABLE rma_history CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_history CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
ALTER TABLE rma_products CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_products CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
ALTER TABLE rma_report_period CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_report_period CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
ALTER TABLE rma_reservation CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_reservation CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
ALTER TABLE rma_supplier_return CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_supplier_return CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
ALTER TABLE rma_supplier_return_history CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_supplier_return_history CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
ALTER TABLE rma_supplier_return_product CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_supplier_return_product CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; 

refer to: https://confluence.atlassian.com/display/CONFKB/How+to+Fix+the+Collation+and+Character+Set+of+a+MySQL+Database

Change values of select box of "show 10 entries" of jquery datatable

If you want to use 'lengthMenu' together with buttons(copy, export), you have to use this option dom: 'lBfrtip'. Here https://datatables.net/reference/option/dom you can find meaning of each symbol. For example, if you will use like this 'Bfrtip', lengthMenu will not appears.

Variable used in lambda expression should be final or effectively final

if it is not necessary to modify the variable than a general workaround for this kind of problem would be to extract the part of code which use lambda and use final keyword on method-parameter.

Deck of cards JAVA

There are many errors in your code, for example you are not really calling your deck by just typing deck in your Shuffle method. You can only call it by typing theCard.deck

I have changed your shuffle method:

public void Shuffle(){
    for (int i = 0; i < theCard.deck.length; i++) {
        int index = (int)(Math.random()*theCard.deck.length );
        int temp = theCard.deck[i];
        theCard.deck[i] = theCard.deck[index];
        theCard.deck[index] = temp;
        remainingCards--;
    }
}

Also, as it is said you have structural problem. You should name classes as you understand in real life, for example, when you say card, it is only one card, when you say deck it is supposed to be 52+2 cards. In this way your code would be more understandable.

How to execute a program or call a system command from Python

I'd recommend using the subprocess module instead of os.system because it does shell escaping for you and is therefore much safer.

subprocess.call(['ping', 'localhost'])

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

Intent emailIntent = new Intent(Intent.ACTION_SENDTO, 
    Uri.fromParts("mailto", "[email protected]", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, text);
startActivity(Intent.createChooser(emailIntent, "Send email..."));

How to deal with persistent storage (e.g. databases) in Docker

Docker 1.9.0 and above

Use volume API

docker volume create --name hello
docker run -d -v hello:/container/path/for/volume container_image my_command

This means that the data-only container pattern must be abandoned in favour of the new volumes.

Actually the volume API is only a better way to achieve what was the data-container pattern.

If you create a container with a -v volume_name:/container/fs/path Docker will automatically create a named volume for you that can:

  1. Be listed through the docker volume ls
  2. Be identified through the docker volume inspect volume_name
  3. Backed up as a normal directory
  4. Backed up as before through a --volumes-from connection

The new volume API adds a useful command that lets you identify dangling volumes:

docker volume ls -f dangling=true

And then remove it through its name:

docker volume rm <volume name>

As @mpugach underlines in the comments, you can get rid of all the dangling volumes with a nice one-liner:

docker volume rm $(docker volume ls -f dangling=true -q)
# Or using 1.13.x
docker volume prune

Docker 1.8.x and below

The approach that seems to work best for production is to use a data only container.

The data only container is run on a barebones image and actually does nothing except exposing a data volume.

Then you can run any other container to have access to the data container volumes:

docker run --volumes-from data-container some-other-container command-to-execute
  • Here you can get a good picture of how to arrange the different containers.
  • Here there is a good insight on how volumes work.

In this blog post there is a good description of the so-called container as volume pattern which clarifies the main point of having data only containers.

Docker documentation has now the DEFINITIVE description of the container as volume/s pattern.

Following is the backup/restore procedure for Docker 1.8.x and below.

BACKUP:

sudo docker run --rm --volumes-from DATA -v $(pwd):/backup busybox tar cvf /backup/backup.tar /data
  • --rm: remove the container when it exits
  • --volumes-from DATA: attach to the volumes shared by the DATA container
  • -v $(pwd):/backup: bind mount the current directory into the container; to write the tar file to
  • busybox: a small simpler image - good for quick maintenance
  • tar cvf /backup/backup.tar /data: creates an uncompressed tar file of all the files in the /data directory

RESTORE:

# Create a new data container
$ sudo docker run -v /data -name DATA2 busybox true
# untar the backup files into the new container?s data volume
$ sudo docker run --rm --volumes-from DATA2 -v $(pwd):/backup busybox tar xvf /backup/backup.tar
data/
data/sven.txt
# Compare to the original container
$ sudo docker run --rm --volumes-from DATA -v `pwd`:/backup busybox ls /data
sven.txt

Here is a nice article from the excellent Brian Goff explaining why it is good to use the same image for a container and a data container.

How do I add a ToolTip to a control?

ToolTip in C# is very easy to add to almost all UI controls. You don't need to add any MouseHover event for this.

This is how to do it-

  1. Add a ToolTip object to your form. One object is enough for the entire form. ToolTip toolTip = new ToolTip();

  2. Add the control to the tooltip with the desired text.

    toolTip.SetToolTip(Button1,"Click here");

Combine or merge JSON on node.js without jQuery

You can also use this lightweight npm package called absorb

It is 27 lines of code, 1kb and uses recursion to perform deep object merges.

var absorb = require('absorb');
var obj1, obj2;

obj1 = { foo: 123, bar: 456 };
obj2 = { bar: 123, key: 'value' }

absorb(obj1, obj2);

console.log(obj1); // Output: { foo: 123, bar: 123, key: 'value' }

You can also use it to make a clone or only transfer values if they don't exist in the source object, how to do this is detailed in the link provided.

Iterate over a Javascript associative array in sorted order

You cannot iterate over them directly, but you can find all the keys and then just sort them.

var a = new Array();
a['b'] = 1;
a['z'] = 1;
a['a'] = 1;    

function keys(obj)
{
    var keys = [];

    for(var key in obj)
    {
        if(obj.hasOwnProperty(key))
        {
            keys.push(key);
        }
    }

    return keys;
}

keys(a).sort(); // ["a", "b", "z"]

However there is no need to make the variable 'a' an array. You are really just using it as an object and should create it like this:

var a = {};
a["key"] = "value";

find filenames NOT ending in specific extensions on Unix?

$ find . -name \*.exe -o -name \*.dll -o -print

The first two -name options have no -print option, so they skipped. Everything else is printed.

Complexities of binary tree traversals

T(n) = 2T(n/2)+ c

T(n/2) = 2T(n/4) + c => T(n) = 4T(n/4) + 2c + c

similarly T(n) = 8T(n/8) + 4c+ 2c + c

....

....

last step ... T(n) = nT(1) + c(sum of powers of 2 from 0 to h(height of tree))

so Complexity is O(2^(h+1) -1)

but h = log(n)

so, O(2n - 1) = O(n)

IF a == true OR b == true statement

check this Twig Reference.

You can do it that simple:

{% if (a or b) %}
    ...
{% endif %}

How to use if statements in LESS

There is a way to use guards for individual (or multiple) attributes.

@debug: true;

header {
    /* guard for attribute */
    & when (@debug = true) {
        background-color: yellow;
    }
    /* guard for nested class */
    #title when (@debug = true) {
        background-color: orange;
    }
}

/* guard for class */
article when (@debug = true) {
    background-color: red;
}

/* and when debug is off: */
article when not (@debug = true) {
    background-color: green;
}

...and with Less 1.7; compiles to:

header {
    background-color: yellow;
}
header #title {
    background-color: orange;
}
article {
    background-color: red;
}

Using jq to parse and display multiple fields in a json serially

While both of the above answers work well if key,value are strings, I had a situation to append a string and integer (jq errors using the above expressions)

Requirement: To construct a url out below json

pradeep@seleniumframework>curl http://192.168.99.103:8500/v1/catalog/service/apache-443 | jq .[0]
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   251  100   251    0     0   155k      0 --:--:-- --:--:-- --:--:--  245k
{
  "Node": "myconsul",
  "Address": "192.168.99.103",
  "ServiceID": "4ce41e90ede4:compassionate_wozniak:443",
  "ServiceName": "apache-443",
  "ServiceTags": [],
  "ServiceAddress": "",
  "ServicePort": 1443,
  "ServiceEnableTagOverride": false,
  "CreateIndex": 45,
  "ModifyIndex": 45
}

Solution:

curl http://192.168.99.103:8500/v1/catalog/service/apache-443 |
jq '.[0] | "http://" + .Address + ":" + "\(.ServicePort)"'

Create Log File in Powershell

A function that takes these principles a little further.

  1. Add's timestamps - can't have a log without timestamps.
  2. Add's a level (uses INFO by default) meaning you can highlight big issues.
  3. Allows for optional console output. If you don't set a log destination, it simply pumps it out.

    Function Write-Log {
        [CmdletBinding()]
        Param(
        [Parameter(Mandatory=$False)]
        [ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")]
        [String]
        $Level = "INFO",
    
        [Parameter(Mandatory=$True)]
        [string]
        $Message,
    
        [Parameter(Mandatory=$False)]
        [string]
        $logfile
        )
    
        $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
        $Line = "$Stamp $Level $Message"
        If($logfile) {
            Add-Content $logfile -Value $Line
        }
        Else {
            Write-Output $Line
        }
    }
    

How to disable anchor "jump" when loading a page?

This will work with bootstrap v3

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  if ($('.nav-tabs').length) {_x000D_
    var hash = window.location.hash;_x000D_
    var hashEl = $('ul.nav a[href="' + hash + '"]');_x000D_
    hash && hashEl.tab('show');_x000D_
_x000D_
    $('.nav-tabs a').click(function(e) {_x000D_
      e.preventDefault();_x000D_
      $(this).tab('show');_x000D_
      window.location.hash = this.hash;_x000D_
    });_x000D_
_x000D_
    // Change tab on hashchange_x000D_
    window.addEventListener('hashchange', function() {_x000D_
      var changedHash = window.location.hash;_x000D_
      changedHash && $('ul.nav a[href="' + changedHash + '"]').tab('show');_x000D_
    }, false);_x000D_
  }_x000D_
});
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>_x000D_
<div class="container">_x000D_
<ul class="nav nav-tabs">_x000D_
  <li class="active"><a data-toggle="tab" href="#home">Home</a></li>_x000D_
  <li><a data-toggle="tab" href="#menu1">Menu 1</a></li>_x000D_
</ul>_x000D_
_x000D_
<div class="tab-content">_x000D_
  <div id="home" class="tab-pane fade in active">_x000D_
    <h3>HOME</h3>_x000D_
    <p>Some content.</p>_x000D_
  </div>_x000D_
  <div id="menu1" class="tab-pane fade">_x000D_
    <h3>Menu 1</h3>_x000D_
    <p>Some content in menu 1.</p>_x000D_
  </div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add a new line of text to an existing file in Java?

You can use the FileWriter(String fileName, boolean append) constructor if you want to append data to file.

Change your code to this:

output = new BufferedWriter(new FileWriter(my_file_name, true));

From FileWriter javadoc:

Constructs a FileWriter object given a file name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

phpMyAdmin on MySQL 8.0

I solved my problem basically with András answer:

1- Log in to MySQL console with root user:

root@9532f0da1a2a:/# mysql -u root -pPASSWORD

And type the root's password to auth.

2- I created a new user:

mysql> CREATE USER 'user'@'hostname' IDENTIFIED BY 'password';

3- Grant all privileges to the new user:

mysql> GRANT ALL PRIVILEGES ON *.* To 'user'@'hostname';

4- Change the Authentication Plugin with the password:

mysql> ALTER USER user IDENTIFIED WITH mysql_native_password BY 'PASSWORD';

Now, phpmyadmin works fine logging the new user.

Convert PEM to PPK file format

I'm rather shocked that this has not been answered since the solution is very simple.

As mentioned in previous posts, you would not want to convert it using C#, but just once. This is easy to do with PuTTYGen.

  1. Download your .pem from AWS
  2. Open PuTTYgen
  3. Click "Load" on the right side about 3/4 down
  4. Set the file type to *.*
  5. Browse to, and Open your .pem file
  6. PuTTY will auto-detect everything it needs, and you just need to click "Save private key" and you can save your ppk key for use with PuTTY

Enjoy!

Which UUID version to use?

If you want a random number, use a random number library. If you want a unique identifier with effectively 0.00...many more 0s here...001% chance of collision, you should use UUIDv1. See Nick's post for UUIDv3 and v5.

UUIDv1 is NOT secure. It isn't meant to be. It is meant to be UNIQUE, not un-guessable. UUIDv1 uses the current timestamp, plus a machine identifier, plus some random-ish stuff to make a number that will never be generated by that algorithm again. This is appropriate for a transaction ID (even if everyone is doing millions of transactions/s).

To be honest, I don't understand why UUIDv4 exists... from reading RFC4122, it looks like that version does NOT eliminate possibility of collisions. It is just a random number generator. If that is true, than you have a very GOOD chance of two machines in the world eventually creating the same "UUID"v4 (quotes because there isn't a mechanism for guaranteeing U.niversal U.niqueness). In that situation, I don't think that algorithm belongs in a RFC describing methods for generating unique values. It would belong in a RFC about generating randomness. For a set of random numbers:

chance_of_collision = 1 - (set_size! / (set_size - tries)!) / (set_size ^ tries)

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

// The answer that I was looking for when searching
public void Answer()
{
    IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
    // Assign to empty list so we can use later
    IEnumerable<YourClass> second = new List<YourClass>();

    if (IwantToUseSecondList)
    {
        second = this.GetSecondIEnumerableList();  
    }
    IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);
}

Filtering Pandas DataFrames on dates

If the dates are in the index then simply:

df['20160101':'20160301']

How to use local docker images with Minikube?

One approach is to build the image locally and then do:

docker save imageNameGoesHere | pv | (eval $(minikube docker-env) && docker load)

minikube docker-env might not return the correct info running under a different user / sudo. Instead you can run sudo -u yourUsername minikube docker-env.

It should return something like:

export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.99.100:2376"
export DOCKER_CERT_PATH="/home/chris/.minikube/certs"
export DOCKER_API_VERSION="1.23"
# Run this command to configure your shell:
# eval $(minikube docker-env)

compareTo() vs. equals()

equals() checks whether two strings are equal or not.It gives boolean value. compareTo() checks whether string object is equal to,greater or smaller to the other string object.It gives result as : 1 if string object is greater 0 if both are equal -1 if string is smaller than other string

eq:

String a = "Amit";
String b = "Sumit";
String c = new String("Amit");
System.out.println(a.equals(c));//true
System.out.println(a.compareTo(c)); //0
System.out.println(a.compareTo(b)); //1

Simple check for SELECT query empty result

IF EXISTS(SELECT * FROM service s WHERE s.service_id = ?)
 BEGIN
   --DO STUFF HERE

 END

Where does MySQL store database files on Windows and what are the names of the files?

MYSQL 8.0:

Search my.ini in disk, we will find this folder:

C:\ProgramData\MySQL\MySQL Server 8.0
It's ProgramData, not Program file

Data is in sub-folder: \Data.

Each database owns a folder, each table is file, each index is 1+ files.

Here is a sample database sakila: enter image description here

How to store JSON object in SQLite database

There is no data types for that.. You need to store it as VARCHAR or TEXT only.. jsonObject.toString();

How to "grep" for a filename instead of the contents of a file?

The easiest way is

find . | grep test

here find will list all the files in the (.) ie current directory, recursively. And then it is just a simple grep. all the files which name has "test" will appeared.

you can play with grep as per your requirement. Note : As the grep is generic string classification, It can result in giving you not only file names. but if a path has a directory ('/xyz_test_123/other.txt') would also comes to the result set. cheers

How do I tell Gradle to use specific JDK version?

If you are executing using gradle wrapper, you can run the command with JDK path like following

./gradlew -Dorg.gradle.java.home=/jdk_path_directory

Requery a subform from another form?

Just discovered that if the source table for a subform is updated using adodb, it takes a while until the requery can find the updated information.

In my case, I was adding some records with 'dbconn.execute "sql" ' and wondered why the requery command in vba doesn't seem to work. When I was debugging, the requery worked. Added a 2-3 second wait in the code before requery just to test made a difference.

But changing to 'currentdb.execute "sql" ' fixed the problem immediately.

Find the number of downloads for a particular app in apple appstore

found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:

d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)

What are SP (stack) and LR in ARM?

SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.

When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.

There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.

The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.

Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).

If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.

Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.

Traditional (well not all the way back to the beginning) arm syntax:

...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...

stm is store multiple you can save more than one register at a time, up to all of them in one instruction.

db means decrement before, this is a downward moving stack from high addresses to lower addresses.

You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.

The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.

Then in the brackets { } list the registers you want to save, comma separated.

ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm

So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.

Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:

void myfun ( void )
{
   int somedata;
}

In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.

A global variable would not be found on the stack.

Going back...

Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.

...
bl myfun
    <--- the return from my fun returns here
...


myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
   <---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.

So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.

ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use

push {r5,r6}
...
pop {r5,r6}

in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).

No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.

push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}

assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.

The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.

If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.

sorry for the very long post, hope it is useful.

find without recursion

I believe you are looking for -maxdepth 1.