Programs & Examples On #Custom type

org.hibernate.MappingException: Unknown entity

In case if you get this exception in SpringBoot application even though the entities are annotated with Entity annotation, it might be due to the spring not aware of where to scan for entities

To explicitly specify the package, add below

@SpringBootApplication
@EntityScan({"model.package.name"})
public class SpringBootApp {...}

note: If you model classes resides in the same or sub packages of SpringBootApplication annotated class, no need to explicitly declare the EntityScan, by default it will scan

Breaking up long strings on multiple lines in Ruby without stripping newlines

I had this problem when I try to write a very long url, the following works.

image_url = %w(
    http://minio.127.0.0.1.xip.io:9000/
    bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
    28ed3774-b234-4de2-9a11-7d657707f79c?
    X-Amz-Algorithm=AWS4-HMAC-SHA256&
    X-Amz-Credential=ABABABABABABABABA
    %2Fus-east-1%2Fs3%2Faws4_request&
    X-Amz-Date=20170702T000940Z&
    X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
    X-Amz-Signature=ABABABABABABABABABABAB
    ABABABABABABABABABABABABABABABABABABA
).join

Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.

Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.

How can I restore the MySQL root user’s full privileges?

GRANT ALL ON *.* TO 'user'@'localhost' with GRANT OPTION;

Just log in from root using the respective password if any and simply run the above command to whatever the user is.

For example:

GRANT ALL ON *.* TO 'root'@'%' with GRANT OPTION;

LINQ .Any VS .Exists - What's the difference?

Additionally, this will only work if Value is of type bool. Normally this is used with predicates. Any predicate would be generally used find whether there is any element satisfying a given condition. Here you're just doing a map from your element i to a bool property. It will search for an "i" whose Value property is true. Once done, the method will return true.

How to normalize a NumPy array to within a certain range?

A simple solution is using the scalers offered by the sklearn.preprocessing library.

scaler = sk.MinMaxScaler(feature_range=(0, 250))
scaler = scaler.fit(X)
X_scaled = scaler.transform(X)
# Checking reconstruction
X_rec = scaler.inverse_transform(X_scaled)

The error X_rec-X will be zero. You can adjust the feature_range for your needs, or even use a standart scaler sk.StandardScaler()

Access a global variable in a PHP function

You need to pass the variable into the function:

$data = 'My data';

function menugen($data)
{
    echo $data;
}

How to get a barplot with several variables side by side grouped by a factor

Using reshape2 and dplyr. Your data:

df <- read.table(text=
"tea                coke            beer             water           gender
14.55              26.50793651     22.53968254      40              1
24.92997199        24.50980392     26.05042017      24.50980393     2
23.03732304        30.63063063     25.41827542      20.91377091     1   
225.51781276       24.6064623      24.85501243      50.80645161     1
24.53662842        26.03706973     25.24271845      24.18358341     2", header=TRUE)

Getting data into correct form:

library(reshape2)
library(dplyr)
df.melt <- melt(df, id="gender")
bar <- group_by(df.melt, variable, gender)%.%summarise(mean=mean(value))

Plotting:

library(ggplot2)
ggplot(bar, aes(x=variable, y=mean, fill=factor(gender)))+
  geom_bar(position="dodge", stat="identity")

enter image description here

Calculate a Running Total in SQL Server

Update, if you are running SQL Server 2012 see: https://stackoverflow.com/a/10309947

The problem is that the SQL Server implementation of the Over clause is somewhat limited.

Oracle (and ANSI-SQL) allow you to do things like:

 SELECT somedate, somevalue,
  SUM(somevalue) OVER(ORDER BY somedate 
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) 
          AS RunningTotal
  FROM Table

SQL Server gives you no clean solution to this problem. My gut is telling me that this is one of those rare cases where a cursor is the fastest, though I will have to do some benchmarking on big results.

The update trick is handy but I feel its fairly fragile. It seems that if you are updating a full table then it will proceed in the order of the primary key. So if you set your date as a primary key ascending you will probably be safe. But you are relying on an undocumented SQL Server implementation detail (also if the query ends up being performed by two procs I wonder what will happen, see: MAXDOP):

Full working sample:

drop table #t 
create table #t ( ord int primary key, total int, running_total int)

insert #t(ord,total)  values (2,20)
-- notice the malicious re-ordering 
insert #t(ord,total) values (1,10)
insert #t(ord,total)  values (3,10)
insert #t(ord,total)  values (4,1)

declare @total int 
set @total = 0
update #t set running_total = @total, @total = @total + total 

select * from #t
order by ord 

ord         total       running_total
----------- ----------- -------------
1           10          10
2           20          30
3           10          40
4           1           41

You asked for a benchmark this is the lowdown.

The fastest SAFE way of doing this would be the Cursor, it is an order of magnitude faster than the correlated sub-query of cross-join.

The absolute fastest way is the UPDATE trick. My only concern with it is that I am not certain that under all circumstances the update will proceed in a linear way. There is nothing in the query that explicitly says so.

Bottom line, for production code I would go with the cursor.

Test data:

create table #t ( ord int primary key, total int, running_total int)

set nocount on 
declare @i int
set @i = 0 
begin tran
while @i < 10000
begin
   insert #t (ord, total) values (@i,  rand() * 100) 
    set @i = @i +1
end
commit

Test 1:

SELECT ord,total, 
    (SELECT SUM(total) 
        FROM #t b 
        WHERE b.ord <= a.ord) AS b 
FROM #t a

-- CPU 11731, Reads 154934, Duration 11135 

Test 2:

SELECT a.ord, a.total, SUM(b.total) AS RunningTotal 
FROM #t a CROSS JOIN #t b 
WHERE (b.ord <= a.ord) 
GROUP BY a.ord,a.total 
ORDER BY a.ord

-- CPU 16053, Reads 154935, Duration 4647

Test 3:

DECLARE @TotalTable table(ord int primary key, total int, running_total int)

DECLARE forward_cursor CURSOR FAST_FORWARD 
FOR 
SELECT ord, total
FROM #t 
ORDER BY ord


OPEN forward_cursor 

DECLARE @running_total int, 
    @ord int, 
    @total int
SET @running_total = 0

FETCH NEXT FROM forward_cursor INTO @ord, @total 
WHILE (@@FETCH_STATUS = 0)
BEGIN
     SET @running_total = @running_total + @total
     INSERT @TotalTable VALUES(@ord, @total, @running_total)
     FETCH NEXT FROM forward_cursor INTO @ord, @total 
END

CLOSE forward_cursor
DEALLOCATE forward_cursor

SELECT * FROM @TotalTable

-- CPU 359, Reads 30392, Duration 496

Test 4:

declare @total int 
set @total = 0
update #t set running_total = @total, @total = @total + total 

select * from #t

-- CPU 0, Reads 58, Duration 139

How does internationalization work in JavaScript?

Some of it is native, the rest is available through libraries.

For example Datejs is a good international date library.

For the rest, it's just about language translation, and JavaScript is natively Unicode compatible (as well as all major browsers).

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

You need to decode data from input string into unicode, before using it, to avoid encoding problems.

field.text = data.decode("utf8")

What is the correct syntax of ng-include?

For those trouble shooting, it is important to know that ng-include requires the url path to be from the app root directory and not from the same directory where the partial.html lives. (whereas partial.html is the view file that the inline ng-include markup tag can be found).

For example:

Correct: div ng-include src=" '/views/partials/tabSlides/add-more.html' ">

Incorrect: div ng-include src=" 'add-more.html' ">

What does O(log n) mean exactly?

First I recommend you to read following book;

Algorithms (4th Edition)

Here is some functions and their expected complexities. Numbers are indicating statement execution frequencies.

Here is some functions and their expected complexities

Following Big-O Complexity Chart also taken from bigocheatsheet Big-O Complexity Chart

Lastly very simple showcase there is shows how it is calculated;

Anatomy of a program’s statement execution frequencies.

Analyzing the running time of a program (example).

Analyzing the running time of a program

Importing CSV with line breaks in Excel 2007

None of the suggested solutions worked for me.

What actually works (with any encoding):

Copy/paste the data from the csv-file (open in a text editor), then perform "text to columns" --> data gets transformed incorrectly.

The next stap is to go to the nearest empty column or empty worksheet and copy/paste again (same thing what you already have in your clipboard) --> automagically works now.

Should methods in a Java interface be declared with or without a public access modifier?

People will learn your interface from code completion in their IDE or in Javadoc, not from reading the source. So there's no point in putting "public" in the source - nobody's reading the source.

remove item from array using its name / value

Try this.(IE8+)

//Define function
function removeJsonAttrs(json,attrs){
    return JSON.parse(JSON.stringify(json,function(k,v){
        return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);

How to fix 'sudo: no tty present and no askpass program specified' error?

This error may also arise when you are trying to run a terminal command (that requires root password) from some non-shell script, eg sudo ls (in backticks) from a Ruby program. In this case, you can use Expect utility (http://en.wikipedia.org/wiki/Expect) or its alternatives.
For example, in Ruby to execute sudo ls without getting sudo: no tty present and no askpass program specified, you can run this:

require 'ruby_expect'

exp = RubyExpect::Expect.spawn('sudo ls', :debug => true)
exp.procedure do
    each do
        expect "[sudo] password for _your_username_:" do
            send _your_password_
        end
    end
end

[this uses one of the alternatives to Expect TCL extension: ruby_expect gem].

What is Bootstrap?

Bootstrap is the world’s most popular and widely used open-source framework for developing with HTML, CSS, and JS. It is a front end framework of HTML. Bootstrap helps in building responsive websites or web applications and a 12-column grid system that helps dynamically adjust the website to a suitable screen resolution. The current version of bootstrap is 4.3.1 and the bootstrap team has also officially announced Bootstrap 5 version and changes like removing jquery from bootstrap. Some of the crucial reasons why bootstrap framework is most preferable are

  • It is easy to use

  • Bootstrap has a big community support

  • Customizations can be done easily

  • It increases development speed

  • Responsiveness

    For more details, you can check the official website: https://getbootstrap.com/

Source: https://vmokshagroup.com/blog/bootstrap-advantages/

What does {0} mean when found in a string in C#?

You are printing a formatted string. The {0} means to insert the first parameter following the format string; in this case the value associated with the key "rtf".

For String.Format, which is similar, if you had something like

//            Format string                    {0}           {1}
String.Format("This {0}.  The value is {1}.",  "is a test",  42 ) 

you'd create a string "This is a test. The value is 42".

You can also use expressions, and print values out multiple times:

//            Format string              {0} {1}  {2}
String.Format("Fib: {0}, {0}, {1}, {2}", 1,  1+1, 1+2) 

yielding "Fib: 1, 1, 2, 3"

See more at http://msdn.microsoft.com/en-us/library/txafckwd.aspx, which talks about composite formatting.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

You haven't put the shared library in a location where the loader can find it. look inside the /usr/local/opencv and /usr/local/opencv2 folders and see if either of them contains any shared libraries (files beginning in lib and usually ending in .so). when you find them, create a file called /etc/ld.so.conf.d/opencv.conf and write to it the paths to the folders where the libraries are stored, one per line.

for example, if the libraries were stored under /usr/local/opencv/libopencv_core.so.2.4 then I would write this to my opencv.conf file:

/usr/local/opencv/

Then run

sudo ldconfig -v

If you can't find the libraries, try running

sudo updatedb && locate libopencv_core.so.2.4

in a shell. You don't need to run updatedb if you've rebooted since compiling OpenCV.

References:

About shared libraries on Linux: http://www.eyrie.org/~eagle/notes/rpath.html

About adding the OpenCV shared libraries: http://opencv.willowgarage.com/wiki/InstallGuide_Linux

Where is the web server root directory in WAMP?

If you use Bitnami installer for wampstack, go to:

c:/Bitnami/wampstack-5.6.24-0/apache/conf (of course your version number may be different)

Open the file: httpd.conf in a text editor like Visual Studio code or Notepad ++

Do a search for "DocumentRoot". See image.

Screenshot

You will be able to change the directory in this file.

How to convert CharSequence to String?

You can directly use String.valueOf()

String.valueOf(charSequence)

Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

Access to the path is denied

I had the same problem but I fixed it by saving the file in a different location and then copying the file and pasting it in the location where I wanted it to be. I used the option to replace the the existing file and that did the trick for me. I know this is not the most efficient way but it works and takes less than 15 seconds.

Error using eclipse for Android - No resource found that matches the given name

One general solution to such tiny errors is that you close eclipse and start is again.. 3 irritating problems were solved.. its the problem with eclipse.. some times it didn resolve "R.id", the it didn find @string/somebutton, and then again some random thing... if nothing logical comes in your mind, try this, n conjure d result.. :)

How to get to Model or Viewbag Variables in a Script Tag

You can do this way, providing Json or Any other variable:

1) For exemple, in the controller, you can use Json.NET to provide Json to the ViewBag:

ViewBag.Number = 10;
ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." });

2) In the View, put the script like this at the bottom of the page.

<script type="text/javascript">
    var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag
    alert("Number is: " + number);
    var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag
    alert("Text is: " + model.Text);
</script> 

What are the performance characteristics of sqlite with very large database files?

I've created SQLite databases up to 3.5GB in size with no noticeable performance issues. If I remember correctly, I think SQLite2 might have had some lower limits, but I don't think SQLite3 has any such issues.

According to the SQLite Limits page, the maximum size of each database page is 32K. And the maximum pages in a database is 1024^3. So by my math that comes out to 32 terabytes as the maximum size. I think you'll hit your file system's limits before hitting SQLite's!

Auto refresh page every 30 seconds

Use setInterval instead of setTimeout. Though in this case either will be fine but setTimeout inherently triggers only once setInterval continues indefinitely.

<script language="javascript">
setInterval(function(){
   window.location.reload(1);
}, 30000);
</script>

Creating a search form in PHP to search a database?

Are you sure, that specified database and table exists? Did you try to look at your database using any database client? For example command-line MySQL client bundled with MySQL server. Or if you a developer newbie, there are dozens of a GUI and web interface clients (HeidiSQL, MySQL Workbench, phpMyAdmin and many more). So first check, if your table creation script was successful and had created what it have to.

BTW why do you have a script for creating the database structure? It's usualy a nonrecurring operation, so write the script to do this is unneeded. It's useful only in case of need of repeatedly creating and manipulating the database structure on the fly.

Python - Passing a function into another function

A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.

In your example, equate the variable rules to one of your functions, leaving off the parentheses and the mention of the argument. Then in your game() function, invoke rules( v ) with the parentheses and the v parameter.

if puzzle == type1:
    rules = Rule1
else:
    rules = Rule2

def Game(listA, listB, rules):
    if rules( v ) == True:
        do...
    else:
        do...

EPPlus - Read Excel Table

Not sure why but none of the above solution work for me. So sharing what worked:

public void readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
            }
        }
    }
}

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

run the below command in command prompt

tnsping Datasource

This should give a response like below

C:>tnsping *******

TNS Ping Utility for *** Windows: Version *** - Production on *****

Copyright (c) 1997, 2014, Oracle. All rights reserved.

Used parameter files: c:\oracle*****

Used **** to resolve the alias Attempting to contact (description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))))** OK (**** msec)

Add the text 'Datasource=' in beginning and credentials at the end. the final string should be

Data Source=(description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))));User Id=;Password=;**

Use this as the connection string to connect to oracle db.

How to see full query from SHOW PROCESSLIST

If one want to keep getting updated processes (on the example, 2 seconds) on a shell session without having to manually interact with it use:

watch -n 2 'mysql -h 127.0.0.1 -P 3306 -u some_user -psome_pass some_database -e "show full processlist;"'

The only bad thing about the show [full] processlist is that you can't filter the output result. On the other hand, issuing the SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST open possibilities to remove from the output anything you don't want to see:

SELECT * from INFORMATION_SCHEMA.PROCESSLIST
WHERE DB = 'somedatabase'
AND COMMAND <> 'Sleep'
AND HOST NOT LIKE '10.164.25.133%' \G

Can you find all classes in a package using reflection?

Based on @Staale's answer, and in an attempt not to rely on third party libraries, I would implement the File System approach by inspecting first package physical location with:

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
...
Class<?>[] foundClasses = new Class<?>[0];
final ArrayList<Class<?>> foundClassesDyn = new ArrayList<Class<?>>();

new java.io.File(
    klass.getResource(
        "/" + curPackage.replace( "." , "/")
    ).getFile()
).listFiles(
    new java.io.FileFilter() {
        public boolean accept(java.io.File file) {
            final String classExtension = ".class";

            if ( file.isFile()
                && file.getName().endsWith(classExtension)
                // avoid inner classes
                && ! file.getName().contains("$") )
            {
                try {
                    String className = file.getName();
                    className = className.substring(0, className.length() - classExtension.length());
                    foundClassesDyn.add( Class.forName( curPackage + "." + className ) );
                } catch (ClassNotFoundException e) {
                    e.printStackTrace(System.out);
                }
            }

            return false;
        }
    }
);

foundClasses = foundClassesDyn.toArray(foundClasses);

How to make an installer for my C# application?

Why invent wheels yourself while there is a car ready for you? I just find this tools super easy and intuitive to use: Advanced Installer. This one minute video should be enough to impress you. Here is the illustrative user guide.

A hex viewer / editor plugin for Notepad++?

According to some comments on Super User it still works :) It just should be copied back to the plugins folder (if it's in the disabled folder) or downloaded from Plugins Central. I have downloaded it a few minutes ago and succeeded in using it.

Of course, be warned: this plugin COULD be unstable in some situations - that's why it was disabled.

How can I make a time delay in Python?

Delays are done with the time library, specifically the time.sleep() function.

To just make it wait for a second:

from time import sleep
sleep(1)

This works because by doing:

from time import sleep

You extract the sleep function only from the time library, which means you can just call it with:

sleep(seconds)

Rather than having to type out

time.sleep()

Which is awkwardly long to type.

With this method, you wouldn't get access to the other features of the time library and you can't have a variable called sleep. But you could create a variable called time.

Doing from [library] import [function] (, [function2]) is great if you just want certain parts of a module.

You could equally do it as:

import time
time.sleep(1)

and you would have access to the other features of the time library like time.clock() as long as you type time.[function](), but you couldn't create the variable time because it would overwrite the import. A solution to this to do

import time as t

which would allow you to reference the time library as t, allowing you to do:

t.sleep()

This works on any library.

Hide Twitter Bootstrap nav collapse on click

_x000D_
_x000D_
$('.nav a').click(function () {_x000D_
    $('.navbar-collapse').collapse('hide');_x000D_
});
_x000D_
_x000D_
_x000D_

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

How to hide columns in HTML table?

You can also do what vs dev suggests programmatically by assigning the style with Javascript by iterating through the columns and setting the td element at a specific index to have that style.

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How to add label in chart.js for pie chart

For those using newer versions Chart.js, you can set a label by setting the callback for tooltips.callbacks.label in options.

Example of this would be:

var chartOptions = {
    tooltips: {
        callbacks: {
            label: function (tooltipItem, data) {
                return 'label';
            }
        }
    }
}

Response.Redirect to new window

You can also use the following code to open new page in new tab.

<asp:Button ID="Button1" runat="server" Text="Go" 
  OnClientClick="window.open('yourPage.aspx');return false;" 
  onclick="Button3_Click" />

And just call Response.Redirect("yourPage.aspx"); behind button event.

Decompile .smali files on an APK

dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/

Which is better, return value or out parameter?

There is no real difference. Out parameters are in C# to allow method return more then one value, that's all.

However There are some slight differences , but non of them are really important:

Using out parameter will enforce you to use two lines like:

int n;
GetValue(n);

while using return value will let you do it in one line:

int n = GetValue();

Another difference (correct only for value types and only if C# doesn't inline the function) is that using return value will necessarily make a copy of the value when the function return, while using OUT parameter will not necessarily do so.

How to Remove Array Element and Then Re-Index Array?

array_splice($array, array_search(array_value, $array), 1);

Passing string to a function in C - with or without pointers?

The accepted convention of passing C-strings to functions is to use a pointer:

void function(char* name)

When the function modifies the string you should also pass in the length:

void function(char* name, size_t name_length)

Your first example:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

Your second example:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

char functionname(char *string)

See also this question for more details on array arguments in C.

NameError: name 'datetime' is not defined

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)

jQuery scroll() detect when user stops scrolling

This should work:

var Timer;
$('.Scroll_Table_Div').on("scroll",function() 
{
    // do somethings

    clearTimeout(Timer);
    Timer = setTimeout(function()
    {
        console.log('scrolling is stop');
    },50);
});

Create sequence of repeated values, in sequence?

For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
         x .groups
     <dbl> <fct>  
 1  0.891  1      
 2 -1.13   1      
 3 -0.500  1      
 4 -1.12   1      
 5 -0.0187 1      
 6  0.420  2      
 7 -0.449  2      
 8  0.365  2      
 9  0.526  2      
10  0.466  2      
# … with 17 more rows

There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z") the grouping factor would be c(1,1,2,3,3).

Rails: How to reference images in CSS within Rails 4

Don't know why, but only thing that worked for me was using asset_path instead of image_path, even though my images are under the assets/images/ directory:

Example:

app/assets/images/mypic.png

In Ruby:

asset_path('mypic.png')

In .scss:

url(asset-path('mypic.png'))

UPDATE:

Figured it out- turns out these asset helpers come from the sass-rails gem (which I had installed in my project).

Why is exception.printStackTrace() considered bad practice?

Printing the exception's stack trace in itself doesn't constitute bad practice, but only printing the stace trace when an exception occurs is probably the issue here -- often times, just printing a stack trace is not enough.

Also, there's a tendency to suspect that proper exception handling is not being performed if all that is being performed in a catch block is a e.printStackTrace. Improper handling could mean at best an problem is being ignored, and at worst a program that continues executing in an undefined or unexpected state.

Example

Let's consider the following example:

try {
  initializeState();

} catch (TheSkyIsFallingEndOfTheWorldException e) {
  e.printStackTrace();
}

continueProcessingAssumingThatTheStateIsCorrect();

Here, we want to do some initialization processing before we continue on to some processing that requires that the initialization had taken place.

In the above code, the exception should have been caught and properly handled to prevent the program from proceeding to the continueProcessingAssumingThatTheStateIsCorrect method which we could assume would cause problems.

In many instances, e.printStackTrace() is an indication that some exception is being swallowed and processing is allowed to proceed as if no problem every occurred.

Why has this become a problem?

Probably one of the biggest reason that poor exception handling has become more prevalent is due to how IDEs such as Eclipse will auto-generate code that will perform a e.printStackTrace for the exception handling:

try {
  Thread.sleep(1000);
} catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

(The above is an actual try-catch auto-generated by Eclipse to handle an InterruptedException thrown by Thread.sleep.)

For most applications, just printing the stack trace to standard error is probably not going to be sufficient. Improper exception handling could in many instances lead to an application running in a state that is unexpected and could be leading to unexpected and undefined behavior.

Most popular screen sizes/resolutions on Android phones

Another alternative to see popular android resolutions or aspect ratios is Unity statistics:

LATEST UNITY STATISTICS (on 2019.06 return http503) web arhive

Top on 2017-01:

Display Resolutions:

  • 1280 x 720: 28.9%
  • 1920 x 1080: 21.4%
  • 800 x 480: 10.3%
  • 854 x 480: 9.7%
  • 960 x 540: 8.9%
  • 1024 x 600: 7.8%
  • 1280 x 800: 5.0%
  • 2560 x 1440: 2.4%
  • 480 x 320: 1.2%
  • 1920 x 1200: 0.8%
  • 1024 x 768: 0.8%

Display Aspect Ratios:

  • 16:9: 72.4%
  • 5:3: 18.2%
  • 16:10: 6.2%
  • 4:3: 1.7%
  • 3:2: 1.2%
  • 5:4: 0.1%

What is the height of iPhone's onscreen keyboard?

version note: this is no longer value in iOS 9 & 10, as they support custom keyboard sizes.

This depends on the model and the QuickType bar:

enter image description here

http://www.idev101.com/code/User_Interface/sizes.html

Where can I find the default timeout settings for all browsers?

I managed to find network.http.connect.timeout for much older versions of Mozilla:

This preference was one of several added to allow low-level tweaking of the HTTP networking code. After a portion of the same code was significantly rewritten in 2001, the preference ceased to have any effect (as noted in all.js as early as September 2001).

Currently, the timeout is determined by the system-level connection establishment timeout. Adding a way to configure this value is considered low-priority.

It would seem that network.http.connect.timeout hasn't done anything for some time.

I also saw references to network.http.request.timeout, so I did a Google search. The results include lots of links to people recommending that others include it in about:config in what appears to be a mistaken belief that it actually does something, since the same search turns up this about:config entries article:

Pref removed (unused). Previously: HTTP-specific network timeout. Default value is 120.

The same page includes additional information about network.http.connect.timeout:

Pref removed (unused). Previously: determines how long to wait for a response until registering a timeout. Default value is 30.

Disclaimer: The information on the MozillaZine Knowledge Base may be incorrect, incomplete or out-of-date.

<strong> vs. font-weight:bold & <em> vs. font-style:italic

HTML represents meaning; CSS represents appearance. How you mark up text in a document is not determined by how that text appears on screen, but simply what it means. As another example, some other HTML elements, like headings, are styled font-weight: bold by default, but they are marked up using <h1><h6>, not <strong> or <b>.

In HTML5, you use <strong> to indicate important parts of a sentence, for example:

<p><strong>Do not touch.</strong> Contains <strong>hazardous</strong> materials.

And you use <em> to indicate linguistic stress, for example:

<p>A Gentleman: I suppose he does. But there's no point in asking.
<p>A Lady: Why not?
<p>A Gentleman: Because he doesn't row.
<p>A Lady: He doesn't <em>row</em>?
<p>A Gentleman: No. He <em>doesn't</em> row.
<p>A Lady: Ah. I see what you mean.

These elements are semantic elements that just happen to have bold and italic representations by default, but you can style them however you like. For example, in the <em> sample above, you could represent stress emphasis in uppercase instead of italics, but the functional purpose of the <em> element remains the same — to change the context of a sentence by emphasizing specific words or phrases over others:

em {
    font-style: normal;
    text-transform: uppercase;
}

Note that the original answer (below) applied to HTML standards prior to HTML5, in which <strong> and <em> had somewhat different meanings, <b> and <i> were purely presentational and had no semantic meaning whatsoever. Like <strong> and <em> respectively, they have similar presentational defaults but may be styled differently.


You use <strong> and <em> to indicate intense emphasis and normal emphasis respectively.

Or think of it this way: font-weight: bold is closer to <b> than <strong>, and font-style: italic is closer to <i> than <em>. These visual styles are purely visual: tools like screen readers aren't going to understand what bold and italic mean, but some screen readers are able to read <strong> and <em> text in a more emphasized tone.

dplyr mutate with conditional values

It looks like derivedFactor from the mosaic package was designed for this. In this example, it would look something like:

library(mosaic)
myfile <- mutate(myfile, V5 = derivedFactor(
    "1" = (V1==1 & V2!=4),
    "2" = (V2==4 & V3!=1),
    .method = "first",
    .default = 0
    ))

(If you want the outcome to be numeric instead of a factor, wrap the derivedFactor with an as.numeric.)

Note that the .default option combined with .method = "first" sets the "else" condition -- this approach is described in the help file for derivedFactor.

How to prevent auto-closing of console after the execution of batch file

Add cmd.exe as a new line below the code you want to execute:

c:\Python27\python D:\code\simple_http_server.py

cmd.exe

How to use external ".js" files

I hope this helps someone here: I encountered an issue where I needed to use JavaScript to manipulate some dynamically generated elements. After including the code to my external .js file which I had referenced to between the <script> </script> tags at the head section and it was working perfectly, nothing worked again from the script.Tried using developer tool on FF and it returned null value for the variable holding the new element. I decided to move my script tag to the bottom of the html file just before the </body> tag and bingo every part of the script started to respond fine again.

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

SonarQube documentation recommends adding static keyword to the class declaration.

That is, change public class FilePathHelper to public static class FilePathHelper.

Alternatively you can add a private or protected constructor.

public class FilePathHelper
{
    // private or protected constructor
    // because all public fields and methods are static
    private FilePathHelper() {
    }
}

Directory index forbidden by Options directive

If you've been doing performance tuning, you might have removed mod_dir. Try putting it back and that might fix your issue.

alternatives to REPLACE on a text or ntext datatype

IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

For SQL Server 2005+:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

How does one parse XML files?

If you're processing a large amount of data (many megabytes) then you want to be using XmlReader to stream parse the XML.

Anything else (XPathNavigator, XElement, XmlDocument and even XmlSerializer if you keep the full generated object graph) will result in high memory usage and also a very slow load time.

Of course, if you need all the data in memory anyway, then you may not have much choice.

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

Serialize and Deserialize Json and Json Array in Unity

IF you are using Vector3 this is what i did

1- I create a class Name it Player

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Player
{
    public Vector3[] Position;

}

2- then i call it like this

if ( _ispressed == true)
        {
            Player playerInstance = new Player();
            playerInstance.Position = newPos;
            string jsonData = JsonUtility.ToJson(playerInstance);

            reference.Child("Position" + Random.Range(0, 1000000)).SetRawJsonValueAsync(jsonData);
            Debug.Log(jsonData);
            _ispressed = false;
        }

3- and this is the result

"Position":[ {"x":-2.8567452430725099,"y":-2.4323320388793947,"z":0.0}]}

How to split comma separated string using JavaScript?

_x000D_
_x000D_
var result;_x000D_
result = "1,2,3".split(","); _x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

More info on W3Schools describing the String Split function.

Read from file in eclipse

There's nothing wrong with your code, the following works fine for me when I have the file.txt in the user.dir directory.

import java.io.File;
import java.util.Scanner;

public class testme {
    public static void main(String[] args) {
        System.out.println(System.getProperty("user.dir"));
        File file = new File("file.txt");
        try {
            Scanner scanner = new Scanner(file);
        } catch (Exception e) {
        System.out.println(e);
        }
    }
}

Don't trust Eclipse with where it says the file is. Go out to the actual filesystem with Windows Explorer or equivalent and check.

Based on your edit, I think we need to see your import statements as well.

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

How to send POST in angularjs with multiple params?

Here is the direct solution:

// POST api/<controller>
[HttpPost, Route("postproducts/{product1}/{product2}")]
public void PostProducts([FromUri]Product product, Product product2)
{
    Product productOne = product; 
    Product productTwo = product2; 
}

$scope.url = 'http://localhost:53263/api/Products/' +
                 $scope.product + '/' + $scope.product2
$http.post($scope.url)
    .success(function(response) {
        alert("success") 
    })
    .error(function() { alert("fail") });
};

If you are sane you do this:

var $scope.products.product1 = product1;
var $scope.products.product2 = product2;

And then send products in the body (like a balla).

How to sort in mongoose?

This is how I got sort to work in mongoose 2.3.0 :)

// Find First 10 News Items
News.find({
    deal_id:deal._id // Search Filters
},
['type','date_added'], // Columns to Return
{
    skip:0, // Starting Row
    limit:10, // Ending Row
    sort:{
        date_added: -1 //Sort by Date Added DESC
    }
},
function(err,allNews){
    socket.emit('news-load', allNews); // Do something with the array of 10 objects
})

How to execute INSERT statement using JdbcTemplate class from Spring Framework

You can alternatively use NamedParameterJdbcTemplate (naming can be useful when you have many parameters)

Map<String, Object> params = new HashMap<>();
params.put("var1",value1); 
params.put("var2",value2); 
namedJdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (:var1, :var2)",
    params
);

Android TextView Text not getting wrapped

It is enough to use in your xml file.

android:singleLine="false".

Hope it will work.

All the best!

Angular2 dynamic change CSS property

Just use standard CSS variables:

Your global css (eg: styles.css)

body {
  --my-var: #000
}

In your component's css or whatever it is:

span {
  color: var(--my-var)
}

Then you can change the value of the variable directly with TS/JS by setting inline style to html element:

document.querySelector("body").style.cssText = "--my-var: #000";

Otherwise you can use jQuery for it:

$("body").css("--my-var", "#fff");

Currency format for display

Try the Currency Format Specifier ("C"). It automatically takes the current UI culture into account and displays currency values accordingly.

You can use it with either String.Format or the overloaded ToString method for a numeric type.

For example:

double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));

Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));

Console.WriteLine(value.ToString("C3", CultureInfo.CreateSpecificCulture("da-DK")));

// The example displays the following output on a system whose
// current culture is English (United States):
//       $12,345.68
//       $12,345.679
//       kr 12.345,679

Difference between break and continue in PHP?

break will exit the loop, while continue will start the next cycle of the loop immediately.

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

CURRENT_DATE/CURDATE() not working as default DATE value

declare your date column as NOT NULL, but without a default. Then add this trigger:

USE `ddb`;
DELIMITER $$
CREATE TRIGGER `default_date` BEFORE INSERT ON `dtable` FOR EACH ROW
if ( isnull(new.query_date) ) then
 set new.query_date=curdate();
end if;
$$
delimiter ;

Bootstrap modal: close current, open new

Problem with data-dismiss="modal" is it will shift your content to left

I am sharing what worked for me, problem statment was opening pop1 from pop2

JS CODE

var showPopup2 = false;
$('#popup1').on('hidden.bs.modal', function () {
    if (showPopup2) {
        $('#popup2').modal('show');
        showPopup2 = false;
    }
});

$("#popup2").click(function() {
    $('#popup1').modal('hide');
    showPopup2 = true;
});

What is the difference between Sessions and Cookies in PHP?

Cookies are used to identify sessions. Visit any site that is using cookies and pull up either Chrome inspect element and then network or FireBug if using Firefox.

You can see that there is a header sent to a server and also received called Cookie. Usually it contains some personal information (like an ID) that can be used on the server to identify a session. These cookies stay on your computer and your browser takes care of sending them to only the domains that are identified with it.

If there were no cookies then you would be sending a unique ID on every request via GET or POST. Cookies are like static id's that stay on your computer for some time.

A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session.save_path location and actually "see sessions". They are either files on the server filesystem or backed in a database.

Screenshot of a Cookie

Reading a date using DataReader

In my case I changed the datetime field in the SQL database to not allow null. SqlDataReader then allowed me to cast the value directly to a DateTime.

How to find text in a column and saving the row number where it is first found - Excel VBA

I'm not really familiar with all those parameters of the Find method; but upon shortening it, the following is working for me:

With WB.Sheets("ECM Overview")
    Set FindRow = .Range("A:A").Find(What:="ProjTemp", LookIn:=xlValues)
End With

And if you solely need the row number, you can use this after:

Dim FindRowNumber As Long
.....
FindRowNumber = FindRow.Row

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Saving a Excel File into .txt format without quotes

I just spent the better part of an afternoon on this

There are two common ways of writing to a file, the first being a direct file access "write" statement. This adds the quotes.

The second is the "ActiveWorkbook.SaveAs" or "ActiveWorksheet.SaveAs" which both have the really bad side effect of changing the filename of the active workbook.

The solution here is a hybrid of a few solutions I found online. It basically does this: 1) Copy selected cells to a new worksheet 2) Iterate through each cell one at a time and "print" it to the open file 3) Delete the temporary worksheet.

The function works on the selected cells and takes in a string for a filename or prompts for a filename.

Function SaveFile(myFolder As String) As String
tempSheetName = "fileWrite_temp"
SaveFile = "False"

Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long

Set myRange = Selection
'myRange.Select
Selection.Copy

'Ask user for folder to save text file to.
If myFolder = "prompt" Then
    myFolder = Application.GetSaveAsFilename(fileFilter:="XML Files (*.xml), *.xml, All Files (*), *")
End If
If myFolder = "False" Then
    End
End If

Open myFolder For Output As #2

'This temporarily adds a sheet named "Test."
Sheets.Add.Name = tempSheetName
Sheets(tempSheetName).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

For i = 1 To LastRow
    For j = 1 To LastCol
        CellData = CellData + Trim(ActiveCell(i, j).Value) + "   "
    Next j

    Print #2, CellData; " "
    CellData = ""

Next i

Close #2

'Remove temporary sheet.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
'Indicate save action.
MsgBox "Text File Saved to: " & vbNewLine & myFolder
SaveFile = myFolder

End Function

What is the best way to give a C# auto-property an initial value?

In the constructor. The constructor's purpose is to initialized it's data members.

How do I load a file from resource folder?

Does the code work when not running the Maven-build jar, for example when running from your IDE? If so, make sure the file is actually included in the jar. The resources folder should be included in the pom file, in <build><resources>.

rejected master -> master (non-fast-forward)

I had this problem on a development machine. The dev branch was pushing fine but the the master branch gave me (while git pushing when being on the dev branch):

! [rejected]        master -> master (non-fast-forward)

So I tried:

git checkout master
git pull

Which gave me:

You asked me to pull without telling me which branch you
want to merge with, and 'branch.master.merge' in
your configuration file does not tell me, either.

I found out the master branch was missing from .git/config and added:

[branch "master"]
    remote = origin
    merge = refs/heads/master

Afterwards git push also worked fine on the dev branch.

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

Use Ant for running program with command line arguments

What I did in the end is make a batch file to extract the CLASSPATH from the ant file, then run java directly using this:

In my build.xml:

<target name="printclasspath">
    <pathconvert property="classpathProp" refid="project.class.path"/>
    <echo>${classpathProp}</echo>
</target>

In another script called 'run.sh':

export CLASSPATH=$(ant -q printclasspath | grep echo | cut -d \  -f 7):build
java "$@"

It's no longer cross-platform, but at least it's relatively easy to use, and one could provide a .bat file that does the same as the run.sh. It's a very short batch script. It's not like migrating the entire build to platform-specific batch files.

I think it's a shame there's not some option in ant whereby you could do something like:

ant -- arg1 arg2 arg3

mpirun uses this type of syntax; ssh also can use this syntax I think.

How to set downloading file name in ASP.NET Web API

Considering the previous answers, it is necessary to be careful with globalized characters.

Suppose the name of the file is: "Esdrújula prenda ñame - güena.jpg"

Raw result to download: "Esdrújula prenda ñame - güena.jpg" [Ugly]

HtmlEncode result to download: "Esdr&_250;jula prenda &_241;ame - g&_252;ena.jpg" [Ugly]

UrlEncode result to download: "Esdrújula+prenda+ñame+-+güena.jpg" [OK]

Then, you need almost always to use the UrlEncode over the file name. Moreover, if you set the content-disposition header as direct string, then you need to ensure surround with quotes to avoid browser compatibility issues.

Response.AddHeader("Content-Disposition", $"attachment; filename=\"{HttpUtility.UrlEncode(YourFilename)}\"");

or with class aid:

var cd = new ContentDisposition("attachment") { FileName = HttpUtility.UrlEncode(resultFileName) };
Response.AddHeader("Content-Disposition", cd.ToString());

The System.Net.Mime.ContentDisposition class takes care of quotes.

Android: adb: Permission Denied

The reason for "permission denied" is because your Android machine has not been correctly rooted. Did you see $ after you started adb shell? If you correctly rooted your machine, you would have seen # instead.

If you see the $, try entering Super User mode by typing su. If Root is enabled, you will see the # - without asking for password.

Echo tab characters in bash script

Use the verbatim keystroke, ^V (CTRL+V, C-v, whatever).

When you type ^V into the terminal (or in most Unix editors), the following character is taken verbatim. You can use this to type a literal tab character inside a string you are echoing.

Something like the following works:

echo "^V<tab>"     # CTRL+V, TAB

Bash docs (q.v., "quoted-insert")

quoted-insert (C-q, C-v) Add the next character that you type to the line verbatim. This is how to insert key sequences like C-q, for example.

side note: according to this, ALT+TAB should do the same thing, but we've all bound that sequence to window switching so we can't use it

tab-insert (M-TAB) Insert a tab character.

--

Note: you can use this strategy with all sorts of unusual characters. Like a carriage return:

echo "^V^M"        # CTRL+V, CTRL+M

This is because carriage return is ASCII 13, and M is the 13th letter of the alphabet, so when you type ^M, you get the 13th ASCII character. You can see it in action using ls^M, at an empty prompt, which will insert a carriage return, causing the prompt to act just like you hit return. When these characters are normally interpreted, verbatim gets you get the literal character.

Converting a Uniform Distribution to a Normal Distribution

Changing the distribution of any function to another involves using the inverse of the function you want.

In other words, if you aim for a specific probability function p(x) you get the distribution by integrating over it -> d(x) = integral(p(x)) and use its inverse: Inv(d(x)). Now use the random probability function (which have uniform distribution) and cast the result value through the function Inv(d(x)). You should get random values cast with distribution according to the function you chose.

This is the generic math approach - by using it you can now choose any probability or distribution function you have as long as it have inverse or good inverse approximation.

Hope this helped and thanks for the small remark about using the distribution and not the probability itself.

Is it possible to get the index you're sorting over in Underscore.js?

I think it's worth mentioning how the Underscore's _.each() works internally. The _.each(list, iteratee) checks if the passed list is an array object, or an object.

In the case that the list is an array, iteratee arguments will be a list element and index as in the following example:

var a = ['I', 'like', 'pancakes', 'a', 'lot', '.'];
_.each( a, function(v, k) { console.log( k + " " + v); });

0 I
1 like
2 pancakes
3 a
4 lot
5 .

On the other hand, if the list argument is an object the iteratee will take a list element and a key:

var o = {name: 'mike', lastname: 'doe', age: 21};
_.each( o, function(v, k) { console.log( k + " " + v); });

name mike
lastname doe
age 21

For reference this is the _.each() code from Underscore.js 1.8.3

_.each = _.forEach = function(obj, iteratee, context) {
   iteratee = optimizeCb(iteratee, context);
   var i, length;
   if (isArrayLike(obj)) {
      for (i = 0, length = obj.length; i < length; i++) {
         iteratee(obj[i], i, obj);
      }
   } else {
      var keys = _.keys(obj);
      for (i = 0, length = keys.length; i < length; i++) {
         iteratee(obj[keys[i]], keys[i], obj);
      }
   }
   return obj;
};

Python: tf-idf-cosine: to find document similarity

Let me give you another tutorial written by me. It answers your question, but also makes an explanation why we are doing some of the things. I also tried to make it concise.

So you have a list_of_documents which is just an array of strings and another document which is just a string. You need to find such document from the list_of_documents that is the most similar to document.

Let's combine them together: documents = list_of_documents + [document]

Let's start with dependencies. It will become clear why we use each of them.

from nltk.corpus import stopwords
import string
from nltk.tokenize import wordpunct_tokenize as tokenize
from nltk.stem.porter import PorterStemmer
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.spatial.distance import cosine

One of the approaches that can be uses is a bag-of-words approach, where we treat each word in the document independent of others and just throw all of them together in the big bag. From one point of view, it looses a lot of information (like how the words are connected), but from another point of view it makes the model simple.

In English and in any other human language there are a lot of "useless" words like 'a', 'the', 'in' which are so common that they do not possess a lot of meaning. They are called stop words and it is a good idea to remove them. Another thing that one can notice is that words like 'analyze', 'analyzer', 'analysis' are really similar. They have a common root and all can be converted to just one word. This process is called stemming and there exist different stemmers which differ in speed, aggressiveness and so on. So we transform each of the documents to list of stems of words without stop words. Also we discard all the punctuation.

porter = PorterStemmer()
stop_words = set(stopwords.words('english'))

modified_arr = [[porter.stem(i.lower()) for i in tokenize(d.translate(None, string.punctuation)) if i.lower() not in stop_words] for d in documents]

So how will this bag of words help us? Imagine we have 3 bags: [a, b, c], [a, c, a] and [b, c, d]. We can convert them to vectors in the basis [a, b, c, d]. So we end up with vectors: [1, 1, 1, 0], [2, 0, 1, 0] and [0, 1, 1, 1]. The similar thing is with our documents (only the vectors will be way to longer). Now we see that we removed a lot of words and stemmed other also to decrease the dimensions of the vectors. Here there is just interesting observation. Longer documents will have way more positive elements than shorter, that's why it is nice to normalize the vector. This is called term frequency TF, people also used additional information about how often the word is used in other documents - inverse document frequency IDF. Together we have a metric TF-IDF which have a couple of flavors. This can be achieved with one line in sklearn :-)

modified_doc = [' '.join(i) for i in modified_arr] # this is only to convert our list of lists to list of strings that vectorizer uses.
tf_idf = TfidfVectorizer().fit_transform(modified_doc)

Actually vectorizer allows to do a lot of things like removing stop words and lowercasing. I have done them in a separate step only because sklearn does not have non-english stopwords, but nltk has.

So we have all the vectors calculated. The last step is to find which one is the most similar to the last one. There are various ways to achieve that, one of them is Euclidean distance which is not so great for the reason discussed here. Another approach is cosine similarity. We iterate all the documents and calculating cosine similarity between the document and the last one:

l = len(documents) - 1
for i in xrange(l):
    minimum = (1, None)
    minimum = min((cosine(tf_idf[i].todense(), tf_idf[l + 1].todense()), i), minimum)
print minimum

Now minimum will have information about the best document and its score.

Format timedelta to string

If you happen to have IPython in your packages (you should), it has (up to now, anyway) a very nice formatter for durations (in float seconds). That is used in various places, for example by the %%time cell magic. I like the format it produces for short durations:

>>> from IPython.core.magics.execution import _format_time
>>> 
>>> for v in range(-9, 10, 2):
...     dt = 1.25 * 10**v
...     print(_format_time(dt))

1.25 ns
125 ns
12.5 µs
1.25 ms
125 ms
12.5 s
20min 50s
1d 10h 43min 20s
144d 16h 13min 20s
14467d 14h 13min 20s

Invalid column name sql error

Code To insert Data in Access Db using c#

Code:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace access_db_csharp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   public SqlConnection con = new SqlConnection(@"Place Your connection string");
            
           private void Savebutton_Click(object sender, EventArgs e)
    {
         SqlCommand cmd = new SqlCommand("insert into  Data (Name,PhoneNo,Address) values(@parameter1,@parameter2,@parameter3)",con);
                cmd.Parameters.AddWithValue("@parameter1", (textBox1.Text));
                cmd.Parameters.AddWithValue("@parameter2", textBox2.Text);
                cmd.Parameters.AddWithValue("@parameter3", (textBox4.Text));
                cmd.ExecuteNonQuery();

                }

    private void Form1_Load(object sender, EventArgs e)
    {
        con.ConnectionString = connectionstring;
        con.Open();
    }
}
}

How to JUnit test that two List<E> contain the same elements in the same order?

The equals() method on your List implementation should do elementwise comparison, so

assertEquals(argumentComponents, returnedComponents);

is a lot easier.

Java: String - add character n-times

for(int i = 0; i < n; i++) {
    existing_string += 'c';
}

but you should use StringBuilder instead, and save memory

int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
    builder.append(" append ");
}

System.out.println(builder.toString());

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

If you have the latest browsers window.orientation might not work. In that case use following code for getting angle -

var orientation = window.screen.orientation.angle;

This is still an experimental technology, you can check the browser compatibility here

Display calendar to pick a date in java

  1. Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.

  2. Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:

    TableModel datePicker = new DatePickerTable("01011999","12302000");
    
  3. Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:

    datePicker.interval = 15;
    
  4. Attach your table model into your JTable:

    JTable newtable = new JTable (datePicker);
    

    Your Java application now has a drop-down date selection dialog.

Function overloading in Javascript - Best practices

Function overloading in Javascript:

Function overloading is the ability of a programming language to create multiple functions of the same name with different implementations. when an overloaded function is called it will run function a specific implementation of that function appropriate to the context of the call. This context is usually the amount of arguments is receives, and it allows one function call to behave differently depending on context.

Javascript doesn't have built-in function overloading. However, this behaviour can be emulated in many ways. Here is a convenient simple one:

_x000D_
_x000D_
function sayHi(a, b) {_x000D_
  console.log('hi there ' + a);_x000D_
  if (b) { console.log('and ' + b) } // if the parameter is present, execute the block_x000D_
}_x000D_
_x000D_
sayHi('Frank', 'Willem');
_x000D_
_x000D_
_x000D_

In scenarios where you don't know how many arguments you will be getting you can use the rest operator which is three dots .... It will convert the remainder of the arguments into an array. Beware of browser compatibilty though. Here is an example:

_x000D_
_x000D_
function foo (a, ...b) {_x000D_
  console.log(b);_x000D_
}_x000D_
_x000D_
foo(1,2,3,4);_x000D_
foo(1,2);
_x000D_
_x000D_
_x000D_

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

/*first of all, and this might be the problem amongst junior devs out there, like myself: make sure to use "lambda" >>>> "`" and not "'" in your fetch method! */

``` const response = await fetch(https://api....);

/plus, the following article is highly recommended: https://developer.edamam.com/api/faq/

The system cannot find the file specified in java

First Create folder same as path which you Specified. after then create File

File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");

if(!file.exists())
{
    dir.mkdir();
    file.createNewFile();
    System.out.println("File,Folder Created.);
}

import module from string variable

The __import__ function can be a bit hard to understand.

If you change

i = __import__('matplotlib.text')

to

i = __import__('matplotlib.text', fromlist=[''])

then i will refer to matplotlib.text.

In Python 2.7 and Python 3.1 or later, you can use importlib:

import importlib

i = importlib.import_module("matplotlib.text")

Some notes

  • If you're trying to import something from a sub-folder e.g. ./feature/email.py, the code will look like importlib.import_module("feature.email")

  • You can't import anything if there is no __init__.py in the folder with file you are trying to import

How should I unit test multithreaded code?

Have a look at my related answer at

Designing a Test class for a custom Barrier

It's biased towards Java but has a reasonable summary of the options.

In summary though (IMO) its not the use of some fancy framework that will ensure correctness but how you go about designing you multithreaded code. Splitting the concerns (concurrency and functionality) goes a huge way towards raising confidence. Growing Object Orientated Software Guided By Tests explains some options better than I can.

Static analysis and formal methods (see, Concurrency: State Models and Java Programs) is an option but I've found them to be of limited use in commercial development.

Don't forget that any load/soak style tests are rarely guaranteed to highlight problems.

Good luck!

Limit to 2 decimal places with a simple pipe

Currency pipe uses the number one internally for number formatting. So you can use it like this:

{{ number | number : '1.2-2'}}

Access Session attribute on jstl

You don't need the jsp:useBean to set the model if you already have a controller which prepared the model.

Just access it plain by EL:

<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>

or by JSTL <c:out> tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:

<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>

See also:


Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.

session.setAttribute("questions", questions);

and alter EL accordingly to use ${questions}.

Also note that you don't have any JSTL tag in your code. It's all plain JSP.

Create file path from variables

You want the path.join() function from os.path.

>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'

This builds your path with os.sep (instead of the less portable '/') and does it more efficiently (in general) than using +.

However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:

start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
    os.makedirs (final_path)

Java correct way convert/cast object to Double



Also worth mentioning -- if you were forced to use an older Java version prior to 1.5, and you are trying to use Collections, you won't be able to parameterize the collection with a type such as Double.

You'll have to manually "box" to the class Double when adding new items, and "unbox" to the primitive double by parsing and casting, doing something like this:

LinkedList lameOldList = new LinkedList();
lameOldList.add( new Double(1.2) );
lameOldList.add( new Double(3.4) );
lameOldList.add( new Double(5.6) );

double total = 0.0;
for (int i = 0, len = lameOldList.size(); i < len; i++) {
  total += Double.valueOf( (Double)lameOldList.get(i) );
}


The old-school list will contain only type Object and so has to be cast to Double.

Also, you won't be able to iterate through the list with an enhanced-for-loop in early Java versions -- only with a for-loop.

PHP code to convert a MySQL query to CSV

If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)

These functions setup the headers:

function setExcelContentType() {
    if(headers_sent())
        return false;

    header('Content-type: application/vnd.ms-excel');
    return true;
}

function setDownloadAsHeader($filename) {
    if(headers_sent())
        return false;

    header('Content-disposition: attachment; filename=' . $filename);
    return true;
}

This one sends a CSV to a stream using a mysql result

function csvFromResult($stream, $result, $showColumnHeaders = true) {
    if($showColumnHeaders) {
        $columnHeaders = array();
        $nfields = mysql_num_fields($result);
        for($i = 0; $i < $nfields; $i++) {
            $field = mysql_fetch_field($result, $i);
            $columnHeaders[] = $field->name;
        }
        fputcsv($stream, $columnHeaders);
    }

    $nrows = 0;
    while($row = mysql_fetch_row($result)) {
        fputcsv($stream, $row);
        $nrows++;
    }

    return $nrows;
}

This one uses the above function to write a CSV to a file, given by $filename

function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
    $fp = fopen($filename, 'w');
    $rc = csvFromResult($fp, $result, $showColumnHeaders);
    fclose($fp);
    return $rc;
}

And this is where the magic happens ;)

function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
    setExcelContentType();
    setDownloadAsHeader($asFilename);
    return csvFileFromResult('php://output', $result, $showColumnHeaders);
}

For example:

$result = mysql_query("SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'");
csvToExcelDownloadFromResult($result);

Angular 4 setting selected option in Dropdown

Here is my example:

<div class="form-group">
    <label for="contactMethod">Contact method</label>
    <select 
        name="contactMethod" 
        id="contactMethod" 
        class="form-control"
        [(ngModel)]="contact.contactMethod">
        <option *ngFor="let method of contactMethods" [value]="method.id">{{ method.label }}</option>
    </select>
</div>

And in component you must get values from select:

contactMethods = [
    { id: 1, label: "Email" },
    { id: 2, label: "Phone" }
]

So, if you want select to have a default value selected (and proabbly you want that):

contact = {
    firstName: "CFR",
    comment: "No comment",
    subscribe: true,
    contactMethod: 2 // this id you'll send and get from backend
}

Raw SQL Query without DbSet - Entity Framework Core

You can execute raw sql in EF Core - Add this class to your project. This will allow you to execute raw SQL and get the raw results without having to define a POCO and a DBSet. See https://github.com/aspnet/EntityFramework/issues/1862#issuecomment-220787464 for original example.

using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.EntityFrameworkCore
{
    public static class RDFacadeExtensions
    {
        public static RelationalDataReader ExecuteSqlQuery(this DatabaseFacade databaseFacade, string sql, params object[] parameters)
        {
            var concurrencyDetector = databaseFacade.GetService<IConcurrencyDetector>();

            using (concurrencyDetector.EnterCriticalSection())
            {
                var rawSqlCommand = databaseFacade
                    .GetService<IRawSqlCommandBuilder>()
                    .Build(sql, parameters);

                return rawSqlCommand
                    .RelationalCommand
                    .ExecuteReader(
                        databaseFacade.GetService<IRelationalConnection>(),
                        parameterValues: rawSqlCommand.ParameterValues);
            }
        }

        public static async Task<RelationalDataReader> ExecuteSqlQueryAsync(this DatabaseFacade databaseFacade, 
                                                             string sql, 
                                                             CancellationToken cancellationToken = default(CancellationToken),
                                                             params object[] parameters)
        {

            var concurrencyDetector = databaseFacade.GetService<IConcurrencyDetector>();

            using (concurrencyDetector.EnterCriticalSection())
            {
                var rawSqlCommand = databaseFacade
                    .GetService<IRawSqlCommandBuilder>()
                    .Build(sql, parameters);

                return await rawSqlCommand
                    .RelationalCommand
                    .ExecuteReaderAsync(
                        databaseFacade.GetService<IRelationalConnection>(),
                        parameterValues: rawSqlCommand.ParameterValues,
                        cancellationToken: cancellationToken);
            }
        }
    }
}

Here's an example of how to use it:

// Execute a query.
using(var dr = await db.Database.ExecuteSqlQueryAsync("SELECT ID, Credits, LoginDate FROM SamplePlayer WHERE " +
                                                          "Name IN ('Electro', 'Nitro')"))
{
    // Output rows.
    var reader = dr.DbDataReader;
    while (reader.Read())
    {
        Console.Write("{0}\t{1}\t{2} \n", reader[0], reader[1], reader[2]);
    }
}

How to set width and height dynamically using jQuery

I tried below code its worked for fine

var modWidth = 250;
var modHeight = 150;

example below :-

$( "#ContainerId .sDashboard li" ).width( modWidth ).height(modHeight);

Using an integer as a key in an associative array in JavaScript

Use an object - with an integer as the key - rather than an array.

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

If

width = img.width;
height = img.height;
var ctx = canvas.getContext('2d');

Then you can use these transformations to turn the image to orientation 1

From orientation:

  1. ctx.transform(1, 0, 0, 1, 0, 0);
  2. ctx.transform(-1, 0, 0, 1, width, 0);
  3. ctx.transform(-1, 0, 0, -1, width, height);
  4. ctx.transform(1, 0, 0, -1, 0, height);
  5. ctx.transform(0, 1, 1, 0, 0, 0);
  6. ctx.transform(0, 1, -1, 0, height, 0);
  7. ctx.transform(0, -1, -1, 0, height, width);
  8. ctx.transform(0, -1, 1, 0, 0, width);

Before drawing the image on ctx

How do you create a dictionary in Java?

There's an Abstract Class Dictionary

http://docs.oracle.com/javase/6/docs/api/java/util/Dictionary.html

However this requires implementation.

Java gives us a nice implementation called a Hashtable

http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html

Method with a bool return

     public bool roomSelected()
    {
        int a = 0;
        foreach (RadioButton rb in GroupBox1.Controls)
        {
            if (rb.Checked == true)
            {
                a = 1;
            }
        }
        if (a == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

this how I solved my problem

Gmail: 530 5.5.1 Authentication Required. Learn more at

Derp! I signed into the account and there was a "Suspicious login attempt" warning message at the top of the page. After clicking the warning and authorizing the access, everything works.

Downgrade npm to an older version

Just need to add version of which you want

upgrade or downgrade

npm install -g npm@version

Example if you want to downgrade from npm 5.6.0 to 4.6.1 then,

npm install -g [email protected]

It is tested on linux

What is the maximum length of a Push Notification alert text?

For regular remote notifications, the maximum size is 4KB (4096 bytes) https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html

###iOS the size limit is 256 bytes, but since the introduction of iOS 8 has changed to 2kb!

https://forums.aws.amazon.com/ann.jspa?annID=2626

With iOS 8, Apple introduced new features that enable some rich new use cases for mobile push notifications — interactive push notifications, third party widgets, and larger (2 KB) payloads. Today, we are pleased to announce support for the new mobile push capabilities announced with iOS 8. We are publishing a new iOS 8 Sample App that demonstrates how these new features can be implemented with SNS, and have also implemented support for larger 2KB payloads.

ls command: how can I get a recursive full-path listing, one line per file?

With having the freedom of using all possible ls options:

find -type f | xargs ls -1

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

How do I set a ViewModel on a window in XAML using DataContext property?

There is also this way of specifying the viewmodel:

using Wpf = System.Windows;

public partial class App : Wpf.Application //your skeleton app already has this.
{
    protected override void OnStartup( Wpf.StartupEventArgs e ) //you need to add this.
    {
        base.OnStartup( e );
        MainWindow = new MainView();
        MainWindow.DataContext = new MainViewModel( e.Args );
        MainWindow.Show();
    }
}

<Rant>

All of the solutions previously proposed require that MainViewModel must have a parameterless constructor.

Microsoft is under the impression that systems can be built using parameterless constructors. If you are also under that impression, go ahead and use some of the other solutions.

For those that know that constructors must have parameters, and therefore the instantiation of objects cannot be left in the hands of magic frameworks, the proper way of specifying the viewmodel is the one I showed above.

</Rant>

how to fetch data from database in Hibernate

Let me quote this:

Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name.

As far as I can see you are using the table name.

So it should be like this:

Query query = session.createQuery("from Employee");

json.dumps vs flask.jsonify

The jsonify() function in flask returns a flask.Response() object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.dumps() method will just return an encoded string, which would require manually adding the MIME type header.

See more about the jsonify() function here for full reference.

Edit: Also, I've noticed that jsonify() handles kwargs or dictionaries, while json.dumps() additionally supports lists and others.

How to use apply a custom drawable to RadioButton?

Give your radiobutton a custom style:

<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:button">@drawable/custom_btn_radio</item>
</style>

custom_btn_radio.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_on" />
    <item android:state_checked="false" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_off" />

    <item android:state_checked="true" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_on_pressed" />
    <item android:state_checked="false" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_off_pressed" />

    <item android:state_checked="true" android:state_focused="true"
          android:drawable="@drawable/btn_radio_on_selected" />
    <item android:state_checked="false" android:state_focused="true"
          android:drawable="@drawable/btn_radio_off_selected" />

    <item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
    <item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>

Replace the drawables with your own.

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Statistics: combinations in Python

That's probably as fast as you can do it in pure python for reasonably large inputs:

def choose(n, k):
    if k == n: return 1
    if k > n: return 0
    d, q = max(k, n-k), min(k, n-k)
    num =  1
    for n in xrange(d+1, n+1): num *= n
    denom = 1
    for d in xrange(1, q+1): denom *= d
    return num / denom

java comparator, how to sort by integer?

If you have access to the Java 8 Comparable API, Comparable.comparingToInt() may be of use. (See Java 8 Comparable Documentation).

For example, a Comparator<Dog> to sort Dog instances descending by age could be created with the following:

Comparable.comparingToInt(Dog::getDogAge).reversed();

The function take a lambda mapping T to Integer, and creates an ascending comparator. The chained function .reversed() turns the ascending comparator into a descending comparator.

Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.

Tomcat 7: How to set initial heap size correctly?

You might no need to having export, just add this line in catalina.sh :

CATALINA_OPTS="-Xms512M -Xmx1024M"

How do you specify table padding in CSS? ( table, not cell padding )

Funny, I was doing precisely this yesterday. You just need this in your css file

.ablock table td {
     padding:5px;
}

then wrap the table in a suitable div

<div class="ablock ">
<table>
  <tr>
    <td>

Looking for a short & simple example of getters/setters in C#

Getters and Setters in C# are something that simplifies the code.

private string name = "spots";

public string Name
{
    get { return name; }
    set { name = value; }
}

And calling it (assume we have a person obj with a name property):

Console.WriteLine(Person.Name); //prints "spots"
Person.Name = "stops";
Console.Writeline(Person.Name); //prints "stops"

This simplifies your code. Where in Java you might have to have two methods, one to Get() and one to Set() the property, in C# it is all done in one spot. I usually do this at the start of my classes:

public string foobar {get; set;}

This creates a getter and setter for my foobar property. Calling it is the same way as shown before. Somethings to note are that you don't have to include both get and set. If you don't want the property being modified, don't include set!

Is there a wikipedia API just for retrieve content summary?

This is the code I'm using right now for a website I'm making that needs to get the leading paragraphs / summary / section 0 of off Wikipedia articles, and it's all done within the browser (client side javascript) thanks to the magick of JSONP! --> http://jsfiddle.net/gautamadude/HMJJg/1/

It uses the Wikipedia API to get the leading paragraphs (called section 0) in HTML like so: http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Stack_Overflow&prop=text&section=0&callback=?

It then strips the HTML and other undesired data, giving you a clean string of an article summary, if you want you can, with a little tweaking, get a "p" html tag around the leading paragraphs but right now there is just a newline character between them.

Code:

var url = "http://en.wikipedia.org/wiki/Stack_Overflow";
var title = url.split("/").slice(4).join("/");

//Get Leading paragraphs (section 0)
$.getJSON("http://en.wikipedia.org/w/api.php?format=json&action=parse&page=" + title + "&prop=text&section=0&callback=?", function (data) {
    for (text in data.parse.text) {
        var text = data.parse.text[text].split("<p>");
        var pText = "";

        for (p in text) {
            //Remove html comment
            text[p] = text[p].split("<!--");
            if (text[p].length > 1) {
                text[p][0] = text[p][0].split(/\r\n|\r|\n/);
                text[p][0] = text[p][0][0];
                text[p][0] += "</p> ";
            }
            text[p] = text[p][0];

            //Construct a string from paragraphs
            if (text[p].indexOf("</p>") == text[p].length - 5) {
                var htmlStrip = text[p].replace(/<(?:.|\n)*?>/gm, '') //Remove HTML
                var splitNewline = htmlStrip.split(/\r\n|\r|\n/); //Split on newlines
                for (newline in splitNewline) {
                    if (splitNewline[newline].substring(0, 11) != "Cite error:") {
                        pText += splitNewline[newline];
                        pText += "\n";
                    }
                }
            }
        }
        pText = pText.substring(0, pText.length - 2); //Remove extra newline
        pText = pText.replace(/\[\d+\]/g, ""); //Remove reference tags (e.x. [1], [4], etc)
        document.getElementById('textarea').value = pText
        document.getElementById('div_text').textContent = pText
    }
});

python: SyntaxError: EOL while scanning string literal

(Assuming you don't have/want line breaks in your string...)

How long is this string really?

I suspect there is a limit to how long a line read from a file or from the commandline can be, and because the end of the line gets choped off the parser sees something like s1="some very long string.......... (without an ending ") and thus throws a parsing error?

You can split long lines up in multiple lines by escaping linebreaks in your source like this:

s1="some very long string.....\
...\
...."

How do I reset a jquery-chosen select option with jQuery?

The new Chosen libraries don't use the liszt. I used the following:

document.getElementById('autoship_option').selectedIndex = 0;
$("#autoship_option").trigger("chosen:updated");

Pandas - Get first row value of a given column

In a general way, if you want to pick up the first N rows from the J column from pandas dataframe the best way to do this is:

data = dataframe[0:N][:,J]

RE error: illegal byte sequence on Mac OS X

You simply have to pipe an iconv command before the sed command. Ex with file.txt input :

iconv -f ISO-8859-1 -t UTF8-MAC file.txt | sed 's/something/àéèêçùû/g' | .....

-f option is the 'from' codeset and -t option is the 'to' codeset conversion.

Take care of case, web pages usually show lowercase like that < charset=iso-8859-1"/> and iconv uses uppercase. You have list of iconv supported codesets in you system with command iconv -l

UTF8-MAC is modern OS Mac codeset for conversion.

Count textarea characters

    $(document).ready(function(){ 
    $('#characterLeft').text('140 characters left');
    $('#message').keydown(function () {
        var max = 140;
        var len = $(this).val().length;
        if (len >= max) {
            $('#characterLeft').text('You have reached the limit');
            $('#characterLeft').addClass('red');
            $('#btnSubmit').addClass('disabled');            
        } 
        else {
            var ch = max - len;
            $('#characterLeft').text(ch + ' characters left');
            $('#btnSubmit').removeClass('disabled');
            $('#characterLeft').removeClass('red');            
        }
    });    
});

How to set an image as a background for Frame in Swing GUI of java?

if you are using netbeans you can add a jlabel to the frame and through properties change its icon to your image and remove the text. then move the jlabel to the bottom of the Jframe or any content pane through navigator

jQuery datepicker, onSelect won't work

No comma after the last property.

Semicolon after alert(date);

Case on datepicker (not datePicker)

Check your other uppercase / lowercase for the properties.

$(function() {
    $('.date-pick').datepicker( {
        onSelect: function(date) {
            alert(date);
        },
        selectWeek: true,
        inline: true,
        startDate: '01/01/2000',
        firstDay: 1
    });
});

How to extract text from the PDF document?

I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :

https://gist.github.com/smalot/6183152

Hope it helps everone

Save PHP array to MySQL?

check out the implode function, since the values are in an array, you want to put the values of the array into a mysql query that inserts the values into a table.

$query = "INSERT INto hardware (specifications) VALUES (".implode(",",$specifications).")";

If the values in the array are text values, you will need to add quotes

$query = "INSERT INto hardware (specifications) VALUES ("'.implode("','",$specifications)."')";

mysql_query($query);

Also, if you don't want duplicate values, switch the "INto" to "IGNORE" and only unique values will be inserted into the table.

Date only from TextBoxFor()

I use Globalize so work with many date formats so use the following:

@Html.TextBoxFor(m => m.DateOfBirth, "{0:d}")

This will automatically adjust the date format to the browser's locale settings.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

All of the above seem to work when spliced in, but gobyexample's signals page has a really clean and complete example of signal capturing. Worth adding to this list.

How to efficiently build a tree from a flat structure?

Here is java solution of the answer by Mehrdad Afshari.

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

public class Tree {

    Iterator<Node> buildTreeAndGetRoots(List<MyObject> actualObjects) {
        Map<Integer, Node> lookup = new HashMap<>();
        actualObjects.forEach(x -> lookup.put(x.id, new Node(x)));
        //foreach (var item in lookup.Values)
        lookup.values().forEach(item ->
                {
                    Node proposedParent;
                    if (lookup.containsKey(item.associatedObject.parentId)) {
                        proposedParent = lookup.get(item.associatedObject.parentId);
                        item.parent = proposedParent;
                        proposedParent.children.add(item);
                    }
                }
        );
        //return lookup.values.Where(x =>x.Parent ==null);
        return lookup.values().stream().filter(x -> x.parent == null).iterator();
    }

}

class MyObject { // The actual object
    public int parentId;
    public int id;
}

class Node {
    public List<Node> children = new ArrayList<Node>();
    public Node parent;
    public MyObject associatedObject;

    public Node(MyObject associatedObject) {
        this.associatedObject = associatedObject;
    }
}

How do you POST to a page using the PHP header() function?

There is a good class that does what you want. It can be downloaded at: http://sourceforge.net/projects/snoopy/

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
       foreach($row['rooms'] as $k) {
             echo $k['boards']['board_id'];
             echo $k['boards']['price'];
       }
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

How do I get an apk file from an Android device?

No Root and no ADB tools required method. Install MyAppSharer app from the play store.

PHPMailer AddAddress()

foreach ($all_address as $aa) {
    $mail->AddAddress($aa); 
}

Could you explain STA and MTA?

STA (Single Threaded Apartment) is basically the concept that only one thread will interact with your code at a time. Calls into your apartment are marshaled via windows messages (using a non-visible) window. This allows calls to be queued and wait for operations to complete.

MTA (Multi Threaded Apartment) is where many threads can all operate at the same time and the onus is on you as the developer to handle the thread security.

There is a lot more to learn about threading models in COM, but if you are having trouble understanding what they are then I would say that understanding what the STA is and how it works would be the best starting place because most COM objects are STA’s.

Apartment Threads, if a thread lives in the same apartment as the object it is using then it is an apartment thread. I think this is only a COM concept because it is only a way of talking about the objects and threads they interact with…

Taking screenshot on Emulator from Android Studio

Long Press on Power button, then you will have the option for the screenshot. Power Button Emulator

Option for screenshot in emulator

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

Value is not null, but DBNull.Value.

object value = cmd.ExecuteScalar();
if(value == DBNull.Value)

symfony 2 No route found for "GET /"

I have also tried that error , I got it right by just adding /hello/any name because it is path that there must be an hello/name

example : instead of just putting http://localhost/app_dev.php

put it like this way http://localhost/name_of_your_project/web/app_dev.php/hello/ai

it will display Hello Ai . I hope I answer your question.

How can I call a shell command in my Perl script?

Examples

  1. `ls -l`;
  2. system("ls -l");
  3. exec("ls -l");

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:

SELECT * FROM match WHERE id NOT IN 
    ( SELECT id FROM email WHERE id IS NOT NULL) ;

SELECT
    m.*
FROM
    match m
    LEFT OUTER JOIN email e ON
        m.id = e.id
        AND e.id IS NOT NULL
WHERE
    e.id IS NULL

The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

How to debug SSL handshake using cURL?

curl -iv https://your.domain.io

That will give you cert and header output if you do not wish to use openssl command.

How can I echo a newline in a batch file?

This worked for me, no delayed expansion necessary:

@echo off
(
echo ^<html^> 
echo ^<body^>
echo Hello
echo ^</body^>
echo ^</html^>
)
pause

It writes output like this:

<html>
<body>
Hello
</body>
</html>
Press any key to continue . . .

How to detect IE11?

I'm using a simpler method:

The navigator global object has a property touchpoints, in Internet Exlorer 11 is called msMaxTouchPoints tho.

So if you look for:

navigator.msMaxTouchPoints !== void 0 

You will find Internet Explorer 11.

How do I push a local Git branch to master branch in the remote?

$ git push origin develop:master

or, more generally

$ git push <remote> <local branch name>:<remote branch to push into>

Get startup type of Windows service using PowerShell

As far as I know there is no “native” PowerShell way of getting this information. And perhaps it is rather the .NET limitation than PowerShell.

Here is the suggestion to add this functionality to the version next:

https://connect.microsoft.com/PowerShell/feedback/details/424948/i-would-like-to-see-the-property-starttype-added-to-get-services

The WMI workaround is also there, just in case. I use this WMI solution for my tasks and it works.

Importing Maven project into Eclipse

Since Eclipse Neon which contains Eclipse Maven Integration (m2e) 1.7, the preferred way is one of the following ways:

  • File > Projects from File System... - This works for Eclipse projects (containing the file .project) as well as for non-Eclipse projects that only contain the file pom.xml.
  • If importing from a Git repository, in the Git Repositories view right-click the repository node, one folder or multiple selected folders in the Working Tree and choose Import Projects.... This opens the same dialog, but you don't have to select the directory.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

The IEnumerable<T> interface does not include an indexer, you're probably confusing it with IList<T>

If the object really is an IList<T> (e.g. List<T> or an array T[]), try making the reference to it of type IList<T> too.

Otherwise, you can use myEnumerable.ElementAt(index) which uses the Enumerable.ElementAt extension method. This should work for all IEnumerable<T>s . Note that unless the (run-time) object implements IList<T>, this will cause all of the first index + 1 items to be enumerated, with all but the last being discarded.

EDIT: As an explanation, IEnumerable<T> is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable<T> must support all these cases, indexers are excluded from its definition.

PHP file_get_contents() and setting request headers

Here is what worked for me (Dominic was just one line short).

$url = "";

$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n" .  // check function.stream-context-create on php.net
              "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad 
  )
);

$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);

Celery Received unregistered task of type (run example)

What worked for me, was to add explicit name to celery task decorator. I changed my task declaration from @app.tasks to @app.tasks(name='module.submodule.task')

Here is an example

# test_task.py
@celery.task
def test_task():
    print("Celery Task  !!!!")

# test_task.py
@celery.task(name='tasks.test.test_task')
def test_task():
    print("Celery Task  !!!!")

Importing .py files in Google Colab

Below are the steps that worked for me

  1. Mount your google drive in google colab

    from google.colab import drive drive.mount('/content/drive')

  2. Insert the directory

    import sys sys.path.insert(0,’/content/drive/My Drive/ColabNotebooks’)

  3. check the current directory path

    %cd drive/MyDrive/ColabNotebooks %pwd

  4. Import your module or file

    import my_module

  5. If you get the following error 'Name Null is not defined' then do the following

    5.1 Download my_module.ipynb from colab as my_module.py file (file->Download .py)

    5.2 Upload the *.py file to drive/MyDrive/ColabNotebooks in Google drive

    5.3 import my_module will work now

Reference: https://medium.com/analytics-vidhya/importing-your-own-python-module-or-python-file-into-colab-3e365f0a35ec

https://github.com/googlecolab/colabtools/issues/1358

Button Listener for button in fragment in android

    //sure run it i will also test it
//we make a class that extends with the fragment
    public class Example_3_1 extends Fragment  implements OnClickListener
    {
       View vi;
        EditText t;
        EditText t1;
        Button bu;
 // that are by defult function of fragment extend class
     @Override
       public View onCreateView(LayoutInflater inflater,ViewGroup container,BundlesavedInstanceState) 
       {        
           vi=inflater.inflate(R.layout.example_3_1, container, false);// load the xml file 
           bu=(Button) vi.findViewById(R.id.button1);// get button id from example_3_1 xml file
           bu.setOnClickListener(this); //on button appay click listner
           t=(EditText) vi.findViewById(R.id.editText1);// id get from example_3_1 xml file
           t1=(EditText) vi.findViewById(R.id.editText2);
          return vi; // return the view object,that set the xml file  example_3_1 xml file
       }
       @Override
       public void onClick(View v)//on button click that called
       {

          switch(v.getId())// on run time get id what button os click and get id
          {
          case R.id.button1:        // it mean if button1 click then this work
           t.setText("UMTien");     //set text 
           t1.setText("programming");
           break;
          }
    }     }

How to count number of unique values of a field in a tab-delimited text file?

You can make use of cut, sort and uniq commands as follows:

cat input_file | cut -f 1 | sort | uniq

gets unique values in field 1, replacing 1 by 2 will give you unique values in field 2.

Avoiding UUOC :)

cut -f 1 input_file | sort | uniq

EDIT:

To count the number of unique occurences you can make use of wc command in the chain as:

cut -f 1 input_file | sort | uniq | wc -l

JQuery html() vs. innerHTML

To answer your question:

.html() will just call .innerHTML after doing some checks for nodeTypes and stuff. It also uses a try/catch block where it tries to use innerHTML first and if that fails, it'll fallback gracefully to jQuery's .empty() + append()

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

SQL how to check that two tables has exactly the same data?

I wrote this to compare the results of a pretty nasty view I ported from Oracle to SQL Server. It creates a pair of temp tables, #DataVariances and #SchemaVariances, with differences in (you guessed it) the data in the tables and the schema of the tables themselves.

It requires both tables have a primary key, but you could drop it into tempdb with an identity column if the source tables don't have one.

declare @TableA_ThreePartName nvarchar(max) = ''
declare @TableB_ThreePartName nvarchar(max) = ''
declare @KeyName nvarchar(max) = ''

/***********************************************************************************************

    Script to compare two tables and return differneces in schema and data.

    Author: Devin Lamothe       2017-08-11

***********************************************************************************************/
set nocount on

-- Split three part name into database/schema/table
declare @Database_A nvarchar(max) = (
    select  left(@TableA_ThreePartName,charindex('.',@TableA_ThreePartName) - 1))
declare @Table_A nvarchar(max) = (
    select  right(@TableA_ThreePartName,len(@TableA_ThreePartName) - charindex('.',@TableA_ThreePartName,len(@Database_A) + 2)))
declare @Schema_A nvarchar(max) = (
    select  replace(replace(@TableA_ThreePartName,@Database_A + '.',''),'.' + @Table_A,''))

declare @Database_B nvarchar(max) = (
    select  left(@TableB_ThreePartName,charindex('.',@TableB_ThreePartName) - 1))
declare @Table_B nvarchar(max) = (
    select  right(@TableB_ThreePartName,len(@TableB_ThreePartName) - charindex('.',@TableB_ThreePartName,len(@Database_B) + 2)))
declare @Schema_B nvarchar(max) = (
    select  replace(replace(@TableB_ThreePartName,@Database_B + '.',''),'.' + @Table_B,''))

-- Get schema for both tables
declare @GetTableADetails nvarchar(max) = '
    use [' + @Database_A +']
        select  COLUMN_NAME
             ,  DATA_TYPE
          from  INFORMATION_SCHEMA.COLUMNS
         where  TABLE_NAME = ''' + @Table_A + '''
           and  TABLE_SCHEMA = ''' + @Schema_A + '''
    '
create table #Table_A_Details (
    ColumnName nvarchar(max)
,   DataType nvarchar(max)
)
insert into #Table_A_Details
exec (@GetTableADetails)

declare @GetTableBDetails nvarchar(max) = '
    use [' + @Database_B +']
        select  COLUMN_NAME
             ,  DATA_TYPE
          from  INFORMATION_SCHEMA.COLUMNS
         where  TABLE_NAME = ''' + @Table_B + '''
           and  TABLE_SCHEMA = ''' + @Schema_B + '''
    '
create table #Table_B_Details (
    ColumnName nvarchar(max)
,   DataType nvarchar(max)
)
insert into #Table_B_Details
exec (@GetTableBDetails)


-- Get differences in table schema
            select  ROW_NUMBER() over (order by
                        a.ColumnName
                    ,   b.ColumnName) as RowKey
                 ,  a.ColumnName as A_ColumnName
                 ,  a.DataType as A_DataType
                 ,  b.ColumnName as B_ColumnName
                 ,  b.DataType as B_DataType
              into  #FieldList
              from  #Table_A_Details a
   full outer join  #Table_B_Details b
                on  a.ColumnName = b.ColumnName
             where  a.ColumnName is null
                or  b.ColumnName is null
                or  a.DataType <> b.DataType

        drop table  #Table_A_Details
        drop table  #Table_B_Details

            select  coalesce(A_ColumnName,B_ColumnName) as ColumnName
                 ,  A_DataType
                 ,  B_DataType
              into  #SchemaVariances
              from  #FieldList

-- Get differences in table data
declare @LastColumn int = (select max(RowKey) from #FieldList)
declare @RowNumber int = 1
declare @ThisField nvarchar(max)
declare @TestSql nvarchar(max)



create table #DataVariances (
    TableKey            nvarchar(max)
,   FieldName           nvarchar(max)
,   TableA_Value        nvarchar(max)
,   TableB_Value        nvarchar(max)
)

delete from #FieldList where A_DataType in ('varbinary','image') or B_DataType in ('varbinary','image') 

while @RowNumber <= @LastColumn begin
    set @TestSql = '
        select  coalesce(a.[' + @KeyName + '],b.[' + @KeyName + ']) as TableKey
             ,  ''' + @ThisField + ''' as FieldName
             ,  a.[' + @ThisField + '] as [TableA_Value]
             ,  b.[' + @ThisField + '] as [TableB_Value]
          from  [' + @Database_A + '].[' + @Schema_A + '].[' + @Table_A + '] a 
    inner join  [' + @Database_B + '].[' + @Schema_B + '].[' + @Table_B + '] b
            on  a.[' + @KeyName + '] = b.[' + @KeyName + ']
         where  ltrim(rtrim(a.[' + @ThisField + '])) <> ltrim(rtrim(b.[' + @ThisField + ']))
            or (a.[' + @ThisField + '] is null and  b.[' + @ThisField + '] is not null)
            or (a.[' + @ThisField + '] is not null and  b.[' + @ThisField + '] is null)
'

insert into #DataVariances
exec (@TestSql)

set @RowNumber = @RowNumber + 1
set @ThisField = (select coalesce(A_ColumnName,B_ColumnName) from #FieldList a where RowKey = @RowNumber)

end

drop table #FieldList

print 'Query complete.  Select from #DataVariances to verify data integrity or #SchemaVariances to verify schemas match.  Data types varbinary and image are not checked.'

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

SO So So simple solution , go to c:/Users/user_name/.ssh/ and delete all pub / private key pairs , this way heroku will generate keys for you.

Conda: Installing / upgrading directly from github

There's better support for this now through conda-env. You can, for example, now do:

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"

It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml file.

If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml), then run the command: conda env update -f environment.yml.

It's more likely that you would want to create a new environment:

conda env create -f environment.yml (changed as supposed in the comments)

Reverting to a specific commit based on commit id with Git?

If you want to force the issue, you can do:

git reset --hard c14809fafb08b9e96ff2879999ba8c807d10fb07

send you back to how your git clone looked like at the time of the checkin

What is tail recursion?

A function is tail recursive if each recursive case consists only of a call to the function itself, possibly with different arguments. Or, tail recursion is recursion with no pending work. Note that this is a programming-language independent concept.

Consider the function defined as:

g(a, b, n) = a * b^n

A possible tail-recursive formulation is:

g(a, b, n) | n is zero = a
           | n is odd  = g(a*b, b,   n-1)
           | otherwise = g(a,   b*b, n/2)

If you examine each RHS of g(...) that involves a recursive case, you'll find that the whole body of the RHS is a call to g(...), and only that. This definition is tail recursive.

For comparison, a non-tail-recursive formulation might be:

g'(a, b, n) = a * f(b, n)
f(b, n) | n is zero = 1
        | n is odd  = f(b, n-1) * b
        | otherwise = f(b, n/2) ^ 2

Each recursive case in f(...) has some pending work that needs to happen after the recursive call.

Note that when we went from g' to g, we made essential use of associativity (and commutativity) of multiplication. This is not an accident, and most cases where you will need to transform recursion to tail-recursion will make use of such properties: if we want to eagerly do some work rather than leave it pending, we have to use something like associativity to prove that the answer will be the same.

Tail recursive calls can be implemented with a backwards jump, as opposed to using a stack for normal recursive calls. Note that detecting a tail call, or emitting a backwards jump is usually straightforward. However, it is often hard to rearrange the arguments such that the backwards jump is possible. Since this optimization is not free, language implementations can choose not to implement this optimization, or require opt-in by marking recursive calls with a 'tailcall' instruction and/or choosing a higher optimization setting.

Some languages (e.g. Scheme) do, however, require all implementations to optimize tail-recursive functions, maybe even all calls in tail position.

Backwards jumps are usually abstracted as a (while) loop in most imperative languages, and tail-recursion, when optimized to a backwards jump, is isomorphic to looping.

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

Another thing that worked for me was to make the instance variable Long in place of long


I had my primary key variable long id; changing it to Long id; worked

All the best

New lines (\r\n) are not working in email body

You need to use a <br> because your Content-Type is text/html.

It works without the Content-Type header because then your e-mail will be interpreted as plain text. If you really want to use \n you should use Content-Type: text/plain but then you'll lose any markup.

Also check out similar question here.

MS SQL compare dates?

Use the DATEDIFF function with a datepart of day.

SELECT ...
FROM ...
WHERE DATEDIFF(day, date1, date2) >= 0

Note that if you want to test that date1 <= date2 then you need to test that DATEDIFF(day, date1, date2) >= 0, or alternatively you could test DATEDIFF(day, date2, date1) <= 0.

Set the default value in dropdownlist using jQuery

if your wanting to use jQuery for this, try the following code.

$('select option[value="1"]').attr("selected",true);

Updated:

Following a comment from Vivek, correctly pointed out steven spielberg wanted to select the option via its Text value.

Here below is the updated code.

$('select option:contains("it\'s me")').prop('selected',true);

You need to use the :contains(text) selector to find via the containing text.

Also jQuery prop offeres better support for Internet Explorer when getting and setting attributes.

A working example on JSFiddle

how to kill hadoop jobs

Simply forcefully kill the process ID, the hadoop job will also be killed automatically . Use this command:

kill -9 <process_id> 

eg: process ID no: 4040 namenode

username@hostname:~$ kill -9 4040

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

This might sound stupid, but, in the first problem presented to you, you would have to see all the remaining numbers in the bag to actually add them up to find the missing number using that equation.

So, since you get to see all the numbers, just look for the number that's missing. The same goes for when two numbers are missing. Pretty simple I think. No point in using an equation when you get to see the numbers remaining in the bag.

Regex number between 1 and 100

There are many options how to write a regex pattern for that

  • ^(?:(?!0)\d{1,2}|100)$
  • ^(?:[1-9]\d?|100)$
  • ^(?!0)(?=100$|..$|.$)\d+$

Header and footer in CodeIgniter

I tried almost all the answers proposed on this page and many other stuff. The best option I finally keeped on all my websites is the following architecture:

A single view

I display only one view in the browser. Here is my main view (/views/page.php):

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <?= $header ?? '' ?>
    </head>
    <body>
        <div style="width:1200px">
                <?= $content ?? '' ?>
        </div> 
    </body>
</html>

Controllers deal with multiple views

Of course, I had several views but they are concatenated to build the $header and the $content variables. Here is my controller:

$data['header'] = $this->load->view('templates/google-analytics', '', TRUE)
                 .$this->load->view('templates/javascript', '', TRUE)
                 .$this->load->view('templates/css', '', TRUE);


$data['content'] = $this->load->view('templates/navbar', '', TRUE)
                  .$this->load->view('templates/alert', $myData, TRUE)
                  .$this->load->view('home/index', $myData, TRUE)
                  .$this->load->view('home/footer', '', TRUE)
                  .$this->load->view('templates/modal-login', '', TRUE);

$this->load->view('templates/page', $data);
  • Look how beautiful and clear is the source code.
  • You no longer have HTML markup opened in one view and closed in another.
  • Each view is now dedicated to one and only one stuff.
  • Look how views are concatenated: method chaining pattern, or should we say: concatanated chaining pattern!
  • You can add optional parts (for example a third $javascript variable at the end of the body)
  • I frequently extend CI_Controller to overload $this->load->view with extra parameters dedicated to my application to keep my controllers clean.
  • If you are always loading the same views on several pages (this is finally the answer to the question), two options depending on your needs:
    • load views in views
    • extend CI_Controller or CI_Loader

I'm so proud of this architecture...

How to start new line with space for next line in Html.fromHtml for text view in android

use <br/> tag

Example:

<string name="copyright"><b>@</b> 2014 <br/>
Corporation.<br/>
<i>All rights reserved.</i></string>

python pandas: apply a function with arguments to a series

Steps:

  1. Create a dataframe
  2. Create a function
  3. Use the named arguments of the function in the apply statement.

Example

x=pd.DataFrame([1,2,3,4])  

def add(i1, i2):  
    return i1+i2

x.apply(add,i2=9)

The outcome of this example is that each number in the dataframe will be added to the number 9.

    0
0  10
1  11
2  12
3  13

Explanation:

The "add" function has two parameters: i1, i2. The first parameter is going to be the value in data frame and the second is whatever we pass to the "apply" function. In this case, we are passing "9" to the apply function using the keyword argument "i2".

In Java, what is the best way to determine the size of an object?

There is also the Memory Measurer tool (formerly at Google Code, now on GitHub), which is simple and published under the commercial-friendly Apache 2.0 license, as discussed in a similar question.

It, too, requires a command-line argument to the java interpreter if you want to measure memory byte consumption, but otherwise seems to work just fine, at least in the scenarios I have used it.

Transparent ARGB hex value

Just came across this and the short code for transparency is simply #00000000.

OpenCV with Network Cameras

I just do it like this:

CvCapture *capture = cvCreateFileCapture("rtsp://camera-address");

Also make sure this dll is available at runtime else cvCreateFileCapture will return NULL

opencv_ffmpeg200d.dll

The camera needs to allow unauthenticated access too, usually set via its web interface. MJPEG format worked via rtsp but MPEG4 didn't.

hth

Si

Clear back stack using fragments

I got this working this way:

public void showHome() {
    getHandler().post(new Runnable() {
        @Override
        public void run() {
            final FragmentManager fm = getSupportFragmentManager();
            while (fm.getBackStackEntryCount() > 0) {
                fm.popBackStackImmediate();
            }
        }
    });
}

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

When you do not provide mapDispatchToProps as a second argument, like this:

export default connect(mapStateToProps)(Checkbox)

then you are automatically getting the dispatch to component's props, so you can just:

class SomeComp extends React.Component {
  constructor(props, context) {
    super(props, context);
  }
  componentDidMount() {
    this.props.dispatch(ACTION GOES HERE);
  }
....

without any mapDispatchToProps

INSERT INTO vs SELECT INTO

Select into creates new table for you at the time and then insert records in it from the source table. The newly created table has the same structure as of the source table.If you try to use select into for a existing table it will produce a error, because it will try to create new table with the same name. Insert into requires the table to be exist in your database before you insert rows in it.

How to specify function types for void (not Void) methods in Java8?

You are trying to use the wrong interface type. The type Function is not appropriate in this case because it receives a parameter and has a return value. Instead you should use Consumer (formerly known as Block)

The Function type is declared as

interface Function<T,R> {
  R apply(T t);
}

However, the Consumer type is compatible with that you are looking for:

interface Consumer<T> {
   void accept(T t);
}

As such, Consumer is compatible with methods that receive a T and return nothing (void). And this is what you want.

For instance, if I wanted to display all element in a list I could simply create a consumer for that with a lambda expression:

List<String> allJedi = asList("Luke","Obiwan","Quigon");
allJedi.forEach( jedi -> System.out.println(jedi) );

You can see above that in this case, the lambda expression receives a parameter and has no return value.

Now, if I wanted to use a method reference instead of a lambda expression to create a consume of this type, then I need a method that receives a String and returns void, right?.

I could use different types of method references, but in this case let's take advantage of an object method reference by using the println method in the System.out object, like this:

Consumer<String> block = System.out::println

Or I could simply do

allJedi.forEach(System.out::println);

The println method is appropriate because it receives a value and has a return type void, just like the accept method in Consumer.

So, in your code, you need to change your method signature to somewhat like:

public static void myForEach(List<Integer> list, Consumer<Integer> myBlock) {
   list.forEach(myBlock);
}

And then you should be able to create a consumer, using a static method reference, in your case by doing:

myForEach(theList, Test::displayInt);

Ultimately, you could even get rid of your myForEach method altogether and simply do:

theList.forEach(Test::displayInt);

About Functions as First Class Citizens

All been said, the truth is that Java 8 will not have functions as first-class citizens since a structural function type will not be added to the language. Java will simply offer an alternative way to create implementations of functional interfaces out of lambda expressions and method references. Ultimately lambda expressions and method references will be bound to object references, therefore all we have is objects as first-class citizens. The important thing is the functionality is there since we can pass objects as parameters, bound them to variable references and return them as values from other methods, then they pretty much serve a similar purpose.

What's the idiomatic syntax for prepending to a short python list?

In my opinion, the most elegant and idiomatic way of prepending an element or list to another list, in Python, is using the expansion operator * (also called unpacking operator),

# Initial list
l = [4, 5, 6]

# Modification
l = [1, 2, 3, *l]

Where the resulting list after the modification is [1, 2, 3, 4, 5, 6]

I also like simply combining two lists with the operator +, as shown,

# Prepends [1, 2, 3] to l
l = [1, 2, 3] + l

# Prepends element 42 to l
l = [42] + l

I don't like the other common approach, l.insert(0, value), as it requires a magic number. Moreover, insert() only allows prepending a single element, however the approach above has the same syntax for prepending a single element or multiple elements.

Start ssh-agent on login

The accepted solution have following drawbacks:

  • it is complicated to maintain;
  • it evaluates storage file which may lead to errors or security breach;
  • it starts agent but doesn't stop it which is close equivalent to leaving the key in ignition.

If your keys do not require to type password, I suggest following solution. Add the following to your .bash_profile very end (edit key list to your needs):

exec ssh-agent $BASH -s 10<&0 << EOF
    ssh-add ~/.ssh/your_key1.rsa \
            ~/.ssh/your_key2.rsa &> /dev/null
    exec $BASH <&10-
EOF

It have following advantages:

  • much simpler solution;
  • agent session ends when bash session ends.

It have possible disadvantages:

  • interactive ssh-add command will influence only one session, which is in fact an issue only in very untypical circumstances;
  • unusable if typing password is required;
  • started shell becomes non-login (which doesn't influence anything AFAIK).

Note that several ssh-agent processes is not a disadvantage, because they don't take more memory or CPU time.

What is the difference between the kernel space and the user space?

Trying to give a very simplified explanation

Virtual Memory is divided into kernel space and the user space. Kernel space is that area of virtual memory where kernel processes will run and user space is that area of virtual memory where user processes will be running.

This division is required for memory access protections.

Whenever a bootloader starts a kernel after loading it to a location in RAM, (on an ARM based controller typically)it needs to make sure that the controller is in supervisor mode with FIQ's and IRQ's disabled.