Programs & Examples On #Meeting request

jQuery changing font family and font size

Full working solution :

HTML:

<form id="myform">
    <button>erase</button>
    <select id="fs"> 
        <option value="Arial">Arial</option>
        <option value="Verdana ">Verdana </option>
        <option value="Impact ">Impact </option>
        <option value="Comic Sans MS">Comic Sans MS</option>
    </select>

    <select id="size">
        <option value="7">7</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
    </select>
</form>

<br/>

<textarea class="changeMe">Text into textarea</textarea>
<div id="container" class="changeMe">
    <div id="float">
        <p>
            Text into container
        </p>
    </div>
</div>

jQuery:

$("#fs").change(function() {
    //alert($(this).val());
    $('.changeMe').css("font-family", $(this).val());

});

$("#size").change(function() {
    $('.changeMe').css("font-size", $(this).val() + "px");
});

Fiddle here: http://jsfiddle.net/AaT9b/

Remove property for all objects in array

For my opinion this is the simplest variant

array.map(({good}) => ({good}))

How to amend a commit without changing commit message (reusing the previous one)?

To extend on the accepted answer, you can also do:

git commit --amend --no-edit -a

to add the currently changed files.

Python, how to read bytes from file and save it?

Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:

file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode

data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file

failed to push some refs to [email protected]

If you want to push commit on git repository, plz make sure you have merged all commit from other branches.

After merging if you are unable to push commit, Use the push command with -f

git push -f origin branch-name

Where origin is the name of your remote repo.

jQuery adding 2 numbers from input fields

Use this code for adding two numbers by using jquery

<!DOCTYPE html>
    <html lang="en-US">
    <head>
        <title>HTML Tutorial</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <meta charset="windows-1252">
    <script>

    $(document).ready(function(){
        $("#submit").on("click", function(){
        var a = parseInt($('#a').val());
        var b = parseInt($('#b').val());
           var sum = a + b;
            alert(sum);
        })
    })
    </script>
    </head>
    <body>
       <input type="text" id="a" name="option">
       <input type="text" id="b" name="task">
    <input id="submit" type="button" value="press me">

    </body>

    </html>

When should I use git pull --rebase?

One practice case is when you are working with Bitbucket PR. There is PR open.

Then you decide to rebase the PR remote branch on the latest Master branch. This will change the commit's ids of your PR.

Then you want to add a new commit to the PR branch.

Since you have rebased the remote branch using GUI first you to sync the local branch on PC with the remote branch.

In this case git pull --rebase works like magic.

After git pull --rebase your remote branch and local branch has same history with same commit ids.

Now you can nicely push a new commit without using force or anything.

Optimum way to compare strings in JavaScript?

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B"
  • "A" == "B"
  • "A" > "B"

And therefore you can make your own function that checks strings the same way as the strcmp().

So this would be the function that does the same:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

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

So the way I would solve this problem is to make sure the two datetimes are in the right timezone.

I can see that you are using datetime.now() which will return the systems current time, with no tzinfo set.

tzinfo is the information attached to a datetime to let it know what timezone it is in. If you are using naive datetime you need to be consistent through out your system. I would highly recommend only using datetime.utcnow()

seeing as somewhere your are creating datetime that have tzinfo associated with them, what you need to do is make sure those are localized (has tzinfo associated) to the correct timezone.

Take a look at Delorean, it makes dealing with this sort of thing much easier.

Sort matrix according to first column in R

The accepted answer works like a charm unless you're applying it to a vector. Since a vector is non-recursive, you'll get an error like this

$ operator is invalid for atomic vectors

You can use [ in that case

foo[order(foo["V1"]),]

Check if a string contains a substring in SQL Server 2005, using a stored procedure

You can just use wildcards in the predicate (after IF, WHERE or ON):

@mainstring LIKE '%' + @substring + '%'

or in this specific case

' ' + @mainstring + ' ' LIKE '% ME[., ]%'

(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).

How to Deserialize XML document

For Beginners

I found the answers here to be very helpful, that said I still struggled (just a bit) to get this working. So, in case it helps someone I'll spell out the working solution:

XML from Original Question. The xml is in a file Class1.xml, a path to this file is used in the code to locate this xml file.

I used the answer by @erymski to get this working, so created a file called Car.cs and added the following:

using System.Xml.Serialization;  // Added

public class Car
{
    public string StockNumber { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
}

[XmlRootAttribute("Cars")]
public class CarCollection
{
    [XmlElement("Car")]
    public Car[] Cars { get; set; }
}

The other bit of code provided by @erymski ...

using (TextReader reader = new StreamReader(path))
{
  XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
  return (CarCollection) serializer.Deserialize(reader);
}

... goes into your main program (Program.cs), in static CarCollection XCar() like this:

using System;
using System.IO;
using System.Xml.Serialization;

namespace ConsoleApp2
{
    class Program
    {

        public static void Main()
        {
            var c = new CarCollection();

            c = XCar();

            foreach (var k in c.Cars)
            {
                Console.WriteLine(k.Make + " " + k.Model + " " + k.StockNumber);
            }
            c = null;
            Console.ReadLine();

        }
        static CarCollection XCar()
        {
            using (TextReader reader = new StreamReader(@"C:\Users\SlowLearner\source\repos\ConsoleApp2\ConsoleApp2\Class1.xml"))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
                return (CarCollection)serializer.Deserialize(reader);
            }
        }
    }
}

Hope it helps :-)

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Correct expression is

"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"

Extracting date from a string in Python

If you know the position of the date object in the string (for example in a log file), you can use .split()[index] to extract the date without fully knowing the format.

For example:

>>> string = 'monkey 2010-07-10 love banana'
>>> date = string.split()[1]
>>> date
'2010-07-10'

VARCHAR to DECIMAL

You are missing the fact that 6.999,50 is not a valid decimal. You can't have a comma and a decimal point in a decimal value surely? What number is it supposed to be?

Assuming your locale specifies . as grouping and , as decimal separator: To remove the grouping digits:

SELECT CONVERT(decimal(11,2), REPLACE('6.999,50', '.', ''))

will yield 6999,50 as a decimal

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

How to make <a href=""> link look like a button?

you can easily wrap a button with a link like so <a href="#"> <button>my button </button> </a>

Convert named list to vector with values only

purrr::flatten_*() is also a good option. the flatten_* functions add thin sanity checks and ensure type safety.

myList <- list('A'=1, 'B'=2, 'C'=3)

purrr::flatten_dbl(myList)
## [1] 1 2 3

Does a foreign key automatically create an index?

Not to my knowledge. A foreign key only adds a constraint that the value in the child key also be represented somewhere in the parent column. It's not telling the database that the child key also needs to be indexed, only constrained.

convert a JavaScript string variable to decimal/money

Yes -- parseFloat.

parseFloat(document.getElementById(amtid4).innerHTML);

For formatting numbers, use toFixed:

var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);

num is now a string with the number formatted with two decimal places.

Displaying standard DataTables in MVC

While I tried the approach above, it becomes a complete disaster with mvc. Your controller passing a model and your view using a strongly typed model become too difficult to work with.

Get your Dataset into a List ..... I have a repository pattern and here is an example of getting a dataset from an old school asmx web service private readonly CISOnlineSRVDEV.ServiceSoapClient _ServiceSoapClient;

    public Get_Client_Repository()
        : this(new CISOnlineSRVDEV.ServiceSoapClient())
    {

    }
    public Get_Client_Repository(CISOnlineSRVDEV.ServiceSoapClient serviceSoapClient)
    {
        _ServiceSoapClient = serviceSoapClient;
    }


    public IEnumerable<IClient> GetClient(IClient client)
    {
        // ****  Calling teh web service with passing in the clientId and returning a dataset
        DataSet dataSet = _ServiceSoapClient.get_clients(client.RbhaId,
                                                        client.ClientId,
                                                        client.AhcccsId,
                                                        client.LastName,
                                                        client.FirstName,
                                                        "");//client.BirthDate.ToString());  //TODO: NEED TO FIX

        // USE LINQ to go through the dataset to make it easily available for the Model to display on the View page
        List<IClient> clients = (from c in dataSet.Tables[0].AsEnumerable()
                                 select new Client()
                                 {
                                     RbhaId = c[5].ToString(),
                                     ClientId = c[2].ToString(),
                                     AhcccsId = c[6].ToString(),
                                     LastName = c[0].ToString(), // Add another field called   Sex M/F  c[4]
                                     FirstName = c[1].ToString(),
                                     BirthDate = c[3].ToDateTime()  //extension helper  ToDateTime()
                                 }).ToList<IClient>();

        return clients;

    }

Then in the Controller I'm doing this

IClient client = (IClient)TempData["Client"];

// Instantiate and instance of the repository 
var repository = new Get_Client_Repository();
// Set a model object to return the dynamic list from repository method call passing in the parameter data
var model = repository.GetClient(client);

// Call the View up passing in the data from the list
return View(model);

Then in the View it is easy :

@model IEnumerable<CISOnlineMVC.DAL.IClient>

@{
    ViewBag.Title = "CLIENT ALL INFORMATION";
}

<h2>CLIENT ALL INFORMATION</h2>

<table>
    <tr>
        <th></th>
        <th>Last Name</th>
        <th>First Name</th>
        <th>Client ID</th>
        <th>DOB</th>
        <th>Gender</th>
        <th>RBHA ID</th>
        <th>AHCCCS ID</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Select", "ClientDetails", "Cis", new { id = item.ClientId }, null) |
        </td>
        <td>
            @item.LastName
        </td>
        <td>
            @item.FirstName
        </td>
         <td>
            @item.ClientId
        </td>
         <td>
            @item.BirthDate
        </td>
         <td>
            Gender @* ADD in*@
        </td>
         <td>
            @item.RbhaId
        </td>
         <td>
            @item.AhcccsId
        </td>
    </tr>
}

</table>

How to use Boost in Visual Studio 2010

Download boost from: http://www.boost.org/users/download/ e.g. by svn

  • Windows -> tortoise (the simplest way)

After that : cmd -> go to boost directory ("D:\boostTrunk" - where You checkout or download and extract package): command : bootstrap

we created bjam.exe in ("D:\boostTrunk") After that : command : bjam toolset=msvc-10.0 variant=debug,release threading=multi link=static (It will take some time ~20min.)

After that: Open Visual studio 2010 -> create empty project -> go to project properties -> set:

Project properties VS 2010

Paste this code and check if it is working?

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/regex.hpp>

using namespace std;

struct Hello 
{
    Hello(){ 
        cout << "Hello constructor" << endl;
    }

    ~Hello(){
        cout << "Hello destructor" << endl;
        cin.get();
    }
};


int main(int argc, char**argv)
{
    //Boost regex, compiled library
    boost::regex regex("^(Hello|Bye) Boost$");
    boost::cmatch helloMatches;
    boost::regex_search("Hello Boost", helloMatches, regex);
    cout << "The word between () is: " << helloMatches[1] << endl;

    //Boost shared pointer, header only library
    boost::shared_ptr<Hello> sharedHello(new Hello);

    return 0;
}

Resources : https://www.youtube.com/watch?v=5AmwIwedTCM

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

This comment from verybadbug under question helped me:

ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load

After that we need restart Apache:

sudo service apache2 restart

How do I use sudo to redirect output to a location I don't have permission to write to?

Yet another variation on the theme:

sudo bash <<EOF
ls -hal /root/ > /root/test.out
EOF

Or of course:

echo 'ls -hal /root/ > /root/test.out' | sudo bash

They have the (tiny) advantage that you don't need to remember any arguments to sudo or sh/bash

Spring Boot and how to configure connection details to MongoDB?

In a maven project create a file src/main/resources/application.yml with the following content:

spring.profiles: integration
# use local or embedded mongodb at localhost:27017
---
spring.profiles: production
spring.data.mongodb.uri: mongodb://<user>:<passwd>@<host>:<port>/<dbname>

Spring Boot will automatically use this file to configure your application. Then you can start your spring boot application either with the integration profile (and use your local MongoDB)

java -jar -Dspring.profiles.active=integration your-app.jar

or with the production profile (and use your production MongoDB)

java -jar -Dspring.profiles.active=production your-app.jar

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

I find, if the data is imported, you may need to use the trim command on top of it, to get your details. =LEFT(TRIM(B2),8) In my case, I was using it to find a IP range. 10.3.44.44 with mask 255.255.255.0, so response is: 10.3.44 Kind of handy.

How can I maintain fragment state when added to the back stack?

My problem was similar but I overcame me without keeping the fragment alive. Suppose you have an activity that has 2 fragments - F1 and F2. F1 is started initially and lets say in contains some user info and then upon some condition F2 pops on asking user to fill in additional attribute - their phone number. Next, you want that phone number to pop back to F1 and complete signup but you realize all previous user info is lost and you don't have their previous data. The fragment is recreated from scratch and even if you saved this information in onSaveInstanceState the bundle comes back null in onActivityCreated.

Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Bundle args = getArguments();

    // this will be null the first time F1 is created. 
    // it will be populated once you replace fragment and provide bundle data
    if (args != null) {
        if (args.get("your_info") != null) {
            // do what you want with restored information
        }
    }
}

So following on with my example: before I display F2 I save user data in the instance variable using a callback. Then I start F2, user fills in phone number and presses save. I use another callback in activity, collect this information and replace my fragment F1, this time it has bundle data that I can use.

@Override
public void onPhoneAdded(String phone) {
        //replace fragment
        F1 f1 = new F1 ();
        Bundle args = new Bundle();
        yourInfo.setPhone(phone);
        args.putSerializable("you_info", yourInfo);
        f1.setArguments(args);

        getFragmentManager().beginTransaction()
                .replace(R.id.fragmentContainer, f1).addToBackStack(null).commit();

    }
}

More information about callbacks can be found here: https://developer.android.com/training/basics/fragments/communicating.html

Getting the last n elements of a vector. Is there a better way than using the length() function?

You can do exactly the same thing in R with two more characters:

x <- 0:9
x[-5:-1]
[1] 5 6 7 8 9

or

x[-(1:5)]

WCF Exception: Could not find a base address that matches scheme http for the endpoint

In my case the binding name in under protocol mapping did not match the binding name on the endpoint. They match in the example below.

<endpoint address="" binding="basicHttpsBinding" contract="serviceName" />

and

    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    

UIButton title text color

Besides de color, my problem was that I was setting the text using textlabel

bt.titleLabel?.text = title

and I solved changing to:

bt.setTitle(title, for: .normal)

What is the Java equivalent for LINQ?

Java LINQ to SQL implementation. Provides full language integration and larger feature set compared to .NET LINQ.

How to use RANK() in SQL Server

Change:

RANK() OVER (PARTITION BY ContenderNum ORDER BY totals ASC) AS xRank

to:

RANK() OVER (ORDER BY totals DESC) AS xRank

Have a look at this example:

SQL Fiddle DEMO

You might also want to have a look at the difference between RANK (Transact-SQL) and DENSE_RANK (Transact-SQL):

RANK (Transact-SQL)

If two or more rows tie for a rank, each tied rows receives the same rank. For example, if the two top salespeople have the same SalesYTD value, they are both ranked one. The salesperson with the next highest SalesYTD is ranked number three, because there are two rows that are ranked higher. Therefore, the RANK function does not always return consecutive integers.

DENSE_RANK (Transact-SQL)

Returns the rank of rows within the partition of a result set, without any gaps in the ranking. The rank of a row is one plus the number of distinct ranks that come before the row in question.

how to mysqldump remote db from local machine

As I haven't seen it at serverfault yet, and the answer is quite simple:

Change:

ssh -f -L3310:remote.server:3306 [email protected] -N

To:

ssh -f -L3310:localhost:3306 [email protected] -N

And change:

mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name

To:

mysqldump -P 3310 -h 127.0.0.1 -u mysql_user -p database_name table_name

(do not use localhost, it's one of these 'special meaning' nonsense that probably connects by socket rather then by port)

edit: well, to elaborate: if host is set to localhost, a configured (or default) --socket option is assumed. See the manual for which option files are sought / used. Under Windows, this can be a named pipe.

How to find Google's IP address?

If all you are trying to do is find the IP address that corresponds to a domain name, like google.com, this is very easy on every machine connected to the Internet.

Simply run the ping command from any command prompt. Typing something like

ping google.com

will give you (among other things) that information.

What is Model in ModelAndView from Spring MVC?

ModelAndView: The name itself explains it is data structure which contains Model and View data.

Map() model=new HashMap(); 
model.put("key.name", "key.value");
new ModelAndView("view.name", model);

// or as follows

ModelAndView mav = new ModelAndView();
mav.setViewName("view.name");
mav.addObject("key.name", "key.value");

if model contains only single value, we can write as follows:

ModelAndView("view.name","key.name", "key.value");

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

I faced the same error today, using React with Typescript and a back-end using Java Spring boot, if you have a hand on your back-end you can simply add a configuration file for the CORS.

For the below example I set allowed origin to * to allow all but you can be more specific and only set url like http://localhost:3000.

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class AppCorsConfiguration {
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

How to install lxml on Ubuntu

For Ubuntu 14.04

sudo apt-get install python-lxml

worked for me.

When should I use a table variable vs temporary table in sql server?

Your question shows you have succumbed to some of the common misconceptions surrounding table variables and temporary tables.

I have written quite an extensive answer on the DBA site looking at the differences between the two object types. This also addresses your question about disk vs memory (I didn't see any significant difference in behaviour between the two).

Regarding the question in the title though as to when to use a table variable vs a local temporary table you don't always have a choice. In functions, for example, it is only possible to use a table variable and if you need to write to the table in a child scope then only a #temp table will do (table-valued parameters allow readonly access).

Where you do have a choice some suggestions are below (though the most reliable method is to simply test both with your specific workload).

  1. If you need an index that cannot be created on a table variable then you will of course need a #temporary table. The details of this are version dependant however. For SQL Server 2012 and below the only indexes that could be created on table variables were those implicitly created through a UNIQUE or PRIMARY KEY constraint. SQL Server 2014 introduced inline index syntax for a subset of the options available in CREATE INDEX. This has been extended since to allow filtered index conditions. Indexes with INCLUDE-d columns or columnstore indexes are still not possible to create on table variables however.

  2. If you will be repeatedly adding and deleting large numbers of rows from the table then use a #temporary table. That supports TRUNCATE (which is more efficient than DELETE for large tables) and additionally subsequent inserts following a TRUNCATE can have better performance than those following a DELETE as illustrated here.

  3. If you will be deleting or updating a large number of rows then the temp table may well perform much better than a table variable - if it is able to use rowset sharing (see "Effects of rowset sharing" below for an example).
  4. If the optimal plan using the table will vary dependent on data then use a #temporary table. That supports creation of statistics which allows the plan to be dynamically recompiled according to the data (though for cached temporary tables in stored procedures the recompilation behaviour needs to be understood separately).
  5. If the optimal plan for the query using the table is unlikely to ever change then you may consider a table variable to skip the overhead of statistics creation and recompiles (would possibly require hints to fix the plan you want).
  6. If the source for the data inserted to the table is from a potentially expensive SELECT statement then consider that using a table variable will block the possibility of this using a parallel plan.
  7. If you need the data in the table to survive a rollback of an outer user transaction then use a table variable. A possible use case for this might be logging the progress of different steps in a long SQL batch.
  8. When using a #temp table within a user transaction locks can be held longer than for table variables (potentially until the end of transaction vs end of statement dependent on the type of lock and isolation level) and also it can prevent truncation of the tempdb transaction log until the user transaction ends. So this might favour the use of table variables.
  9. Within stored routines, both table variables and temporary tables can be cached. The metadata maintenance for cached table variables is less than that for #temporary tables. Bob Ward points out in his tempdb presentation that this can cause additional contention on system tables under conditions of high concurrency. Additionally, when dealing with small quantities of data this can make a measurable difference to performance.

Effects of rowset sharing

DECLARE @T TABLE(id INT PRIMARY KEY, Flag BIT);

CREATE TABLE #T (id INT PRIMARY KEY, Flag BIT);

INSERT INTO @T 
output inserted.* into #T
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), 0
FROM master..spt_values v1, master..spt_values v2

SET STATISTICS TIME ON

/*CPU time = 7016 ms,  elapsed time = 7860 ms.*/
UPDATE @T SET Flag=1;

/*CPU time = 6234 ms,  elapsed time = 7236 ms.*/
DELETE FROM @T

/* CPU time = 828 ms,  elapsed time = 1120 ms.*/
UPDATE #T SET Flag=1;

/*CPU time = 672 ms,  elapsed time = 980 ms.*/
DELETE FROM #T

DROP TABLE #T

How to do the equivalent of pass by reference for primitives in Java

public static void main(String[] args) {
    int[] toyNumber = new int[] {5};
    NewClass temp = new NewClass();
    temp.play(toyNumber);
    System.out.println("Toy number in main " + toyNumber[0]);
}

void play(int[] toyNumber){
    System.out.println("Toy number in play " + toyNumber[0]);
    toyNumber[0]++;
    System.out.println("Toy number in play after increement " + toyNumber[0]);
}

Effective way to find any file's Encoding

The following codes are my Powershell codes to determinate if some cpp or h or ml files are encodeding with ISO-8859-1(Latin-1) or UTF-8 without BOM, if neither then suppose it to be GB18030. I am a Chinese working in France and MSVC saves as Latin-1 on french computer and saves as GB on Chinese computer so this helps me avoid encoding problem when do source file exchanges between my system and my colleagues.

The way is simple, if all characters are between x00-x7E, ASCII, UTF-8 and Latin-1 are all the same, but if I read a non ASCII file by UTF-8, we will find the special character ? show up, so try to read with Latin-1. In Latin-1, between \x7F and \xAF is empty, while GB uses full between x00-xFF so if I got any between the two, it's not Latin-1

The code is written in PowerShell, but uses .net so it's easy to be translated into C# or F#

$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
foreach($i in Get-ChildItem .\ -Recurse -include *.cpp,*.h, *.ml) {
    $openUTF = New-Object System.IO.StreamReader -ArgumentList ($i, [Text.Encoding]::UTF8)
    $contentUTF = $openUTF.ReadToEnd()
    [regex]$regex = '?'
    $c=$regex.Matches($contentUTF).count
    $openUTF.Close()
    if ($c -ne 0) {
        $openLatin1 = New-Object System.IO.StreamReader -ArgumentList ($i, [Text.Encoding]::GetEncoding('ISO-8859-1'))
        $contentLatin1 = $openLatin1.ReadToEnd()
        $openLatin1.Close()
        [regex]$regex = '[\x7F-\xAF]'
        $c=$regex.Matches($contentLatin1).count
        if ($c -eq 0) {
            [System.IO.File]::WriteAllLines($i, $contentLatin1, $Utf8NoBomEncoding)
            $i.FullName
        } 
        else {
            $openGB = New-Object System.IO.StreamReader -ArgumentList ($i, [Text.Encoding]::GetEncoding('GB18030'))
            $contentGB = $openGB.ReadToEnd()
            $openGB.Close()
            [System.IO.File]::WriteAllLines($i, $contentGB, $Utf8NoBomEncoding)
            $i.FullName
        }
    }
}
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

Things possible in IntelliJ that aren't possible in Eclipse?

Data flow analysis : inter-procedural backward flow analysis and forward flow analysis, as described here. My experiences are based on Community Edition, which does data flow analysis fairly well. It has failed (refused to do anything) in few cases when code is very complex.

How store a range from excel into a Range variable?

When you use a Range object, you cannot simply use the following syntax:

Dim myRange as Range
myRange = Range("A1")  

You must use the set keyword to assign Range objects:

Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

    Dim dataTable As Range
    Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    Set getData = dataTable

End Function

Sub main()
    Dim test As Range

    Set test = getData(ActiveSheet, 1, 3, 2, 5)
    test.select

End Sub

Note that every time a range is declared I use the Set keyword.


You can also allow your getData function to return a Range object instead of a Variant although this is unrelated to the problem you are having.

How to use OrderBy with findAll in Spring Data

Yes you can sort using query method in Spring Data.

Ex:ascending order or descending order by using the value of the id field.

Code:

  public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public findAllByOrderByIdAsc();   
}

alternative solution:

    @Repository
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDAO studentDao;

    @Override
    public List<Student> findAll() {
        return studentDao.findAll(orderByIdAsc());
    }
private Sort orderByIdAsc() {
    return new Sort(Sort.Direction.ASC, "id")
                .and(new Sort(Sort.Direction.ASC, "name"));
}
}

Spring Data Sorting: Sorting

Cannot instantiate the type List<Product>

Interfaces can not be directly instantiated, you should instantiate classes that implements such Interfaces.

Try this:

NameValuePair[] params = new BasicNameValuePair[] {
        new BasicNameValuePair("param1", param1),
        new BasicNameValuePair("param2", param2),
};

Select from where field not equal to Mysql Php

Or can also insert the statement inside bracket.

SELECT * FROM tablename WHERE NOT (columnA = 'x')

how to open a url in python

On window

import os
os.system("start \"\" https://example.com")

On macOS

import os
os.system("open \"\" https://example.com")

On Linux

import os
os.system("xdg-open \"\" https://example.com")

Cross-Platform

import webbrowser

webbrowser.open('https://example.com')

Export to xls using angularjs

We need a JSON file which we need to export in the controller of angularjs and we should be able to call from the HTML file. We will look at both. But before we start, we need to first add two files in our angular library. Those two files are json-export-excel.js and filesaver.js. Moreover, we need to include the dependency in the angular module. So the first two steps can be summarised as follows -

1) Add json-export.js and filesaver.js in your angular library.

2) Include the dependency of ngJsonExportExcel in your angular module.

      var myapp = angular.module('myapp', ['ngJsonExportExcel'])

Now that we have included the necessary files we can move on to the changes which need to be made in the HTML file and the controller. We assume that a json is being created on the controller either manually or by making a call to the backend.

HTML :

Current Page as Excel
All Pages as Excel 

In the application I worked, I brought paginated results from the backend. Therefore, I had two options for exporting to excel. One for the current page and one for all data. Once the user selects an option, a call goes to the controller which prepares a json (list). Each object in the list forms a row in the excel.

Read more at - https://www.oodlestechnologies.com/blogs/Export-to-excel-using-AngularJS

Get original URL referer with PHP?

Store it either in a cookie (if it's acceptable for your situation), or in a session variable.

session_start();

if ( !isset( $_SESSION["origURL"] ) )
    $_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];

How does RewriteBase work in .htaccess

RewriteBase is only applied to the target of a relative rewrite rule.

  • Using RewriteBase like this...

    RewriteBase /folder/
    RewriteRule a\.html b.html
    
  • is essentially the same as...

    RewriteRule a\.html /folder/b.html
    
  • But when the .htaccess file is inside /folder/ then this also points to the same target:

    RewriteRule a\.html b.html
    

Although the docs imply always using a RewriteBase, Apache usually detects it correctly for paths under the DocumentRoot unless:

  • You are using Alias directives

  • You are using .htaccess rewrite rules to perform HTTP redirects (rather than just silent rewriting) to relative URLs

In these cases, you may find that you need to specify the RewriteBase.

However, since it's a confusing directive, it's generally better to simply specify absolute (aka 'root relative') URIs in your rewrite targets. Other developers reading your rules will grasp these more easily.



Quoting from Jon Lin's excellent in-depth answer here:

In an htaccess file, mod_rewrite works similar to a <Directory> or <Location> container. and the RewriteBase is used to provide a relative path base.

For example, say you have this folder structure:

DocumentRoot
|-- subdir1
`-- subdir2
    `-- subsubdir

So you can access:

  • http://example.com/ (root)
  • http://example.com/subdir1 (subdir1)
  • http://example.com/subdir2 (subdir2)
  • http://example.com/subdir2/subsubdir (subsubdir)

The URI that gets sent through a RewriteRule is relative to the directory containing the htaccess file. So if you have:

RewriteRule ^(.*)$ - 
  • In the root htaccess, and the request is /a/b/c/d, then the captured URI ($1) is a/b/c/d.
  • If the rule is in subdir2 and the request is /subdir2/e/f/g then the captured URI is e/f/g.
  • If the rule is in the subsubdir, and the request is /subdir2/subsubdir/x/y/z, then the captured URI is x/y/z.

The directory that the rule is in has that part stripped off of the URI. The rewrite base has no affect on this, this is simply how per-directory works.

What the rewrite base does do, is provide a URL-path base (not a file-path base) for any relative paths in the rule's target. So say you have this rule:

RewriteRule ^foo$ bar.php [L]

The bar.php is a relative path, as opposed to:

RewriteRule ^foo$ /bar.php [L]

where the /bar.php is an absolute path. The absolute path will always be the "root" (in the directory structure above). That means that regardless of whether the rule is in the "root", "subdir1", "subsubdir", etc. the /bar.php path always maps to http://example.com/bar.php.

But the other rule, with the relative path, it's based on the directory that the rule is in. So if

RewriteRule ^foo$ bar.php [L]

is in the "root" and you go to http://example.com/foo, you get served http://example.com/bar.php. But if that rule is in the "subdir1" directory, and you go to http://example.com/subdir1/foo, you get served http://example.com/subdir1/bar.php. etc. This sometimes works and sometimes doesn't, as the documentation says, it's supposed to be required for relative paths, but most of the time it seems to work. Except when you are redirecting (using the R flag, or implicitly because you have http://host in your rule's target). That means this rule:

RewriteRule ^foo$ bar.php [L,R]

if it's in the "subdir2" directory, and you go to http://example.com/subdir2/foo, mod_rewrite will mistake the relative path as a file-path instead of a URL-path and because of the R flag, you'll end up getting redirected to something like: http://example.com/var/www/localhost/htdocs/subdir1. Which is obviously not what you want.

This is where RewriteBase comes in. The directive tells mod_rewrite what to append to the beginning of every relative path. So if I have:

RewriteBase /blah/
RewriteRule ^foo$ bar.php [L]

in "subsubdir", going to http://example.com/subdir2/subsubdir/foo will actually serve me http://example.com/blah/bar.php. The "bar.php" is added to the end of the base. In practice, this example is usually not what you want, because you can't have multiple bases in the same directory container or htaccess file.

In most cases, it's used like this:

RewriteBase /subdir1/
RewriteRule ^foo$ bar.php [L]

where those rules would be in the "subdir1" directory and

RewriteBase /subdir2/subsubdir/
RewriteRule ^foo$ bar.php [L]

would be in the "subsubdir" directory.

This partly allows you to make your rules portable, so you can drop them in any directory and only need to change the base instead of a bunch of rules. For example if you had:

RewriteEngine On
RewriteRule ^foo$ /subdir1/bar.php [L]
RewriteRule ^blah1$ /subdir1/blah.php?id=1 [L]
RewriteRule ^blah2$ /subdir1/blah2.php [L]
...

such that going to http://example.com/subdir1/foo will serve http://example.com/subdir1/bar.php etc. And say you decided to move all of those files and rules to the "subsubdir" directory. Instead of changing every instance of /subdir1/ to /subdir2/subsubdir/, you could have just had a base:

RewriteEngine On
RewriteBase /subdir1/
RewriteRule ^foo$ bar.php [L]
RewriteRule ^blah1$ blah.php?id=1 [L]
RewriteRule ^blah2$ blah2.php [L]
...

And then when you needed to move those files and the rules to another directory, just change the base:

RewriteBase /subdir2/subsubdir/

and that's it.

difference between @size(max = value ) and @min(value) @max(value)

From the documentation I get the impression that in your example it would be intended to use:

@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)

Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. Supported data types:

BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

geom_smooth() what are the methods available?

Sometimes it's asking the question that makes the answer jump out. The methods and extra arguments are listed on the ggplot2 wiki stat_smooth page.

Which is alluded to on the geom_smooth() page with:

"See stat_smooth for examples of using built in model fitting if you need some more flexible, this example shows you how to plot the fits from any model of your choosing".

It's not the first time I've seen arguments in examples for ggplot graphs that aren't specifically in the function. It does make it tough to work out the scope of each function, or maybe I am yet to stumble upon a magic explicit list that says what will and will not work within each function.

Adding maven nexus repo to my pom.xml

From the Apache Maven site

<project>
  ...
  <repositories>
    <repository>
      <id>my-internal-site</id>
      <url>http://myserver/repo</url>
    </repository>
  </repositories>
  ...
</project>

"The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml." - Apache Maven site - settings reference

<servers>
    <server>
        <id>server001</id>
        <username>my_login</username>
        <password>my_password</password>
        <privateKey>${user.home}/.ssh/id_dsa</privateKey>
        <passphrase>some_passphrase</passphrase>
        <filePermissions>664</filePermissions>
        <directoryPermissions>775</directoryPermissions>
        <configuration></configuration>
    </server>
</servers>

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Your code is correct. Kindly mark small correction.

#rightcolumn {
     width: 750px;
     background-color: #777;
     display: block;
     **float: left;(wrong)**
     **float: right; (corrected)**
     border: 1px solid white;
}

How long do browsers cache HTTP 301s?

To solve the issue for a localhost address I changed the port number the site ran under. This worked on Chrome version 73.0.3683.86.

Is there a good Valgrind substitute for Windows?

Definitely Purify! I've used that to analyze some massive code bases (>3,000 kSLOC) and found it to be excellent.

You might like to look at this list at Wikipedia.

By the way, I've found memwatch to be useful. Thanks Johan!

Transfer data from one HTML file to another

I use this to set Profile image on each page.

On first page set value as:

localStorage.setItem("imageurl", "ur image url");

or on second page get value as :

var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);

Where can I set environment variables that crontab will use?

Another way - inspired by this this answer - to "inject" variables is the following (fcron example):

%daily 00 12 \
    set -a; \
    . /path/to/file/containing/vars; \
    set +a; \
    /path/to/script/using/vars

From help set:

-a Mark variables which are modified or created for export.

Using + rather than - causes these flags to be turned off.

So everything in between set - and set + gets exported to env and is then available for other scripts, etc. Without using set the variables get sourced but live in set only.

Aside from that it's also useful to pass variables when a program requires a non-root account to run but you'd need some variables inside that other user's environment. Below is an example passing in nullmailer vars to format the e-mail header:

su -s /bin/bash -c "set -a; \
                    . /path/to/nullmailer-vars; \
                    set +a; \
                    /usr/sbin/logcheck" logcheck

How can I execute a python script from an html button?

It is discouraged and problematic yet doable. What you need is a custom URI scheme ie. You need to register and configure it on your machine and then hook an url with that scheme to the button.

URI scheme is the part before :// in an URI. Standard URI schemes are for example https or ftp or file. But there are custom like fx. mongodb. What you need is your own e.g. mypythonscript. It can be configured to exec the script or even just python with the script name in the params etc. It is of course a tradeoff between flexibility and security.

You can find more details in the links:

https://support.shotgunsoftware.com/hc/en-us/articles/219031308-Launching-applications-using-custom-browser-protocols

https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx

EDIT: Added more details about what an custom scheme is.

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

<system.diagnostics>
    <sources>
        <source name="sourceName" switchName="switchName">
            <listeners>
                <add
                    name="textWriterTraceListener"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="tracelog.txt" />
            </listeners>
        </source>
    </sources>

    <switches>
        <add name="switchName" value="Verbose" />
    </switches>
</system.diagnostics>

Select all where [first letter starts with B]

SELECT author FROM lyrics WHERE author LIKE 'B%';

Make sure you have an index on author, though!

How to declare Global Variables in Excel VBA to be visible across the Workbook

You can do the following to learn/test the concept:

  1. Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module

  2. In newly added Module1 add the declaration; Public Global1 As String

  3. in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:

Sub setMe()
      Global1 = "Hello"
End Sub
  1. in Worksheet VBA Module Sheet2(Sheet2) put the code snippet:
Sub showMe()
    Debug.Print (Global1)
End Sub
  1. Run in sequence Sub setMe() and then Sub showMe() to test the global visibility/accessibility of the var Global1

Hope this will help.

Execution order of events when pressing PrimeFaces p:commandButton

I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:

        <p:pickList id="formPickList" 
                    value="#{mediaDetail.availableMedia}" 
                    converter="MediaPicklistConverter" 
                    widgetVar="formsPicklistWidget" 
                    var="mediaFiles" 
                    itemLabel="#{mediaFiles.mediaTitle}" 
                    itemValue="#{mediaFiles}" >
            <f:facet name="sourceCaption">Available Media</f:facet>
            <f:facet name="targetCaption">Chosen Media</f:facet>
        </p:pickList>

        <p:commandButton id="viewStream_btn" 
                         value="Stream chosen media" 
                         icon="fa fa-download"
                         ajax="true"
                         action="#{mediaDetail.prepareStreams}"                                              
                         update=":streamDialogPanel"
                         oncomplete="PF('streamingDialog').show()"
                         styleClass="ui-priority-primary"
                         style="margin-top:5px" >
            <p:ajax process="formPickList"  />
        </p:commandButton>

The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.

As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.

The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" /> bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.

Happy coding!

Removing Spaces from a String in C?

Easiest and most efficient don't usually go together...

Here's a possible solution:

void remove_spaces(char* s) {
    const char* d = s;
    do {
        while (*d == ' ') {
            ++d;
        }
    } while (*s++ = *d++);
}

Reload .profile in bash shell script (in unix)?

Try this:

cd 
source .bash_profile

Set the space between Elements in Row Flutter

You can use Spacers if all you want is a little bit of spacing between items in a row. The example below centers 2 Text widgets within a row with some spacing between them.

Spacer creates an adjustable, empty spacer that can be used to tune the spacing between widgets in a Flex container, like Row or Column.

In a row, if we want to put space between two widgets such that it occupies all remaining space.

    widget = Row (
    children: <Widget>[
      Spacer(flex: 20),
      Text(
        "Item #1",
      ),
      Spacer(),  // Defaults to flex: 1
      Text(
        "Item #2",
      ),
      Spacer(flex: 20),
    ]
  );

SQL: how to use UNION and order by a specific select?

@Adrien's answer is not working. It gives an ORA-01791.

The correct answer (for the question that is asked) should be:

select id
from 
 (SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
  UNION ALL
  SELECT id, 1 as ordered FROM b -- returns 2,1
  )
group by id
order by min(ordered)

Explanation:

  1. The "UNION ALL" is combining the 2 sets. A "UNION" is wastefull because the 2 sets could not be the same, because the ordered field is different.
  2. The "group by" is then eliminating duplicates
  3. The "order by min (ordered)" is assuring the elements of table b are first

This solves all the cases, even when table b has more or different elements then table a

Easy way to build Android UI?

This is an old question, that unfortunately even several years on doesn't have a good solution. I've just ported an app from iOS (Obj C) to Android. The biggest problem was not the back end code (for many/most folks, if you can code in Obj C you can code in Java) but porting the native interfaces. What Todd said above, UI layout is still a complete pain. In my experience, the fastest wat to develop a reliable UI that supports multiple formats etc is in good 'ol HTML.

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

System.String (with capital S) is already nullable, you do not need to declare it as such.

(string? myStr) is wrong.

Get width/height of SVG element

I'm using Firefox, and my working solution is very close to obysky. The only difference is that the method you call in an svg element will return multiple rects and you need to select the first one.

var chart = document.getElementsByClassName("chart")[0];
var width = chart.getClientRects()[0].width;
var height = chart.getClientRects()[0].height;

How do Python's any and all functions work?

The concept is simple:

M =[(1, 1), (5, 6), (0, 0)]

1) print([any(x) for x in M])
[True, True, False] #only the last tuple does not have any true element

2) print([all(x) for x in M])
[True, True, False] #all elements of the last tuple are not true

3) print([not all(x) for x in M])
[False, False, True] #NOT operator applied to 2)

4) print([any(x)  and not all(x) for x in M])
[False, False, False] #AND operator applied to 1) and 3)
# if we had M =[(1, 1), (5, 6), (1, 0)], we could get [False, False, True]  in 4)
# because the last tuple satisfies both conditions: any of its elements is TRUE 
#and not all elements are TRUE 

How to set character limit on the_content() and the_excerpt() in wordpress

You could use a Wordpress filter callback function. In your theme's directory, locate or create a file called functions.php and add the following in:

<?php   
  add_filter("the_content", "plugin_myContentFilter");

  function plugin_myContentFilter($content)
  {
    // Take the existing content and return a subset of it
    return substr($content, 0, 300);
  }
?>

The plugin_myContentFilter() is a function you provide that will be called each time you request the content of a post type like posts/pages via the_content(). It provides you with the content as an input, and will use whatever you return from the function for subsequent output or other filter functions.

You can also use add_filter() for other functions like the_excerpt() to provide a callback function whenever the excerpt is requested.

See the Wordpress filter reference docs for more details.

How to make a launcher

Just develop a normal app and then add a couple of lines to the app's manifest file.

First you need to add the following attribute to your activity:

            android:launchMode="singleTask"

Then add two categories to the intent filter :

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.HOME" />

The result could look something like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dummy.app"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="11"
            android:targetSdkVersion="19" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.dummy.app.MainActivity"
                android:launchMode="singleTask"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.HOME" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

It's that simple!

Why doesn't java.io.File have a close method?

A BufferedReader can be opened and closed but a File is never opened, it just represents a path in the filesystem.

Input type DateTime - Value format?

This was a good waste of an hour of my time. For you eager beavers, the following format worked for me:

<input type="datetime-local" name="to" id="to" value="2014-12-08T15:43:00">

The spec was a little confusing to me, it said to use RFC 3339, but on my PHP server when I used the format DATE_RFC3339 it wasn't initializing my hmtl input :( PHP's constant for DATE_RFC3339 is "Y-m-d\TH:i:sP" at the time of writing, it makes sense that you should get rid of the timezone info (we're using datetime-LOCAL, folks). So the format that worked for me was:

"Y-m-d\TH:i:s"

I would've thought it more intuitive to be able to set the value of the datepicker as the datepicker displays the date, but I'm guessing the way it is displayed differs across browsers.

Pass an array of integers to ASP.NET Web API?

You may try this code for you to take comma separated values / an array of values to get back a JSON from webAPI

 public class CategoryController : ApiController
 {
     public List<Category> Get(String categoryIDs)
     {
         List<Category> categoryRepo = new List<Category>();

         String[] idRepo = categoryIDs.Split(',');

         foreach (var id in idRepo)
         {
             categoryRepo.Add(new Category()
             {
                 CategoryID = id,
                 CategoryName = String.Format("Category_{0}", id)
             });
         }
         return categoryRepo;
     }
 }

 public class Category
 {
     public String CategoryID { get; set; }
     public String CategoryName { get; set; }
 } 

Output :

[
{"CategoryID":"4","CategoryName":"Category_4"}, 
{"CategoryID":"5","CategoryName":"Category_5"}, 
{"CategoryID":"3","CategoryName":"Category_3"} 
]

Get output parameter value in ADO.NET

Create the SqlParamObject which would give you control to access methods on the parameters

:

SqlParameter param = new SqlParameter();

SET the Name for your paramter (it should b same as you would have declared a variable to hold the value in your DataBase)

: param.ParameterName = "@yourParamterName";

Clear the value holder to hold you output data

: param.Value = 0;

Set the Direction of your Choice (In your case it should be Output)

: param.Direction = System.Data.ParameterDirection.Output;

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

How to plot all the columns of a data frame in R

Unfortunately, ggplot2 does not offer a way to do this (easily) without transforming your data into long format. You can try to fight it but it will just be easier to do the data transformation. Here all the methods, including melt from reshape2, gather from tidyr, and pivot_longer from tidyr: Reshaping data.frame from wide to long format

Here's a simple example using pivot_longer:

> df <- data.frame(time = 1:5, a = 1:5, b = 3:7)
> df
  time a b
1    1 1 3
2    2 2 4
3    3 3 5
4    4 4 6
5    5 5 7

> df_wide <- df %>% pivot_longer(c(a, b), names_to = "colname", values_to = "val")
> df_wide
# A tibble: 10 x 3
    time colname   val
   <int> <chr>   <int>
 1     1 a           1
 2     1 b           3
 3     2 a           2
 4     2 b           4
 5     3 a           3
 6     3 b           5
 7     4 a           4
 8     4 b           6
 9     5 a           5
10     5 b           7

As you can see, pivot_longer puts the selected column names in whatever is specified by names_to (default "name"), and puts the long values into whatever is specified by values_to (default "value"). If I'm ok with the default names, I can use use df %>% pivot_longer(c("a", "b")).

Now you can plot as normal, ex.

ggplot(df_wide, aes(x = time, y = val, color = colname)) + geom_line()

enter image description here

How to specify the default error page in web.xml?

You can also specify <error-page> for exceptions using <exception-type>, eg below:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorpages/exception.html</location>
</error-page>

Or map a error code using <error-code>:

<error-page>
    <error-code>404</error-code>
    <location>/errorpages/404error.html</location>
</error-page>

How do I install Python OpenCV through Conda?

You can install OpenCV by running these commands in the Anaconda command prompt:

conda config --add channels conda-forge

conda install libopencv opencv py-opencv

Source:

https://github.com/conda-forge/opencv-feedstock

How to select multiple files with <input type="file">?

HTML5 has provided new attribute multiple for input element whose type attribute is file. So you can select multiple files and IE9 and previous versions does not support this.

NOTE: be carefull with the name of the input element. when you want to upload multiple file you should use array and not string as the value of the name attribute.

ex:

input type="file" name="myPhotos[]" multiple="multiple"

and if you are using php then you will get the data in $_FILES and use var_dump($_FILES) and see output and do processing Now you can iterate over and do the rest

Is there a 'foreach' function in Python 3?

Look at this article. The iterator object nditer from numpy package, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

Example:

import random
import numpy as np

ptrs = np.int32([[0, 0], [400, 0], [0, 400], [400, 400]])

for ptr in np.nditer(ptrs, op_flags=['readwrite']):
    # apply random shift on 1 for each element of the matrix
    ptr += random.choice([-1, 1])

print(ptrs)

d:\>python nditer.py
[[ -1   1]
 [399  -1]
 [  1 399]
 [399 401]]

UTF-8 output from PowerShell

Set the [Console]::OuputEncoding as encoding whatever you want, and print out with [Console]::WriteLine.

If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)

Get form data in ReactJS

There are a few ways to do this:

1) Get values from array of form elements by index

handleSubmit = (event) => {
  event.preventDefault();
  console.log(event.target[0].value)
}

2) Using name attribute in html

handleSubmit = (event) => {
  event.preventDefault();
  console.log(event.target.elements.username.value) // from elements property
  console.log(event.target.username.value)          // or directly
}

<input type="text" name="username"/>

3) Using refs

handleSubmit = (event) => {
  console.log(this.inputNode.value)
}

<input type="text" name="username" ref={node => (this.inputNode = node)}/>

Full example

class NameForm extends React.Component {
  handleSubmit = (event) => {
    event.preventDefault()
    console.log(event.target[0].value)
    console.log(event.target.elements.username.value)
    console.log(event.target.username.value)
    console.log(this.inputNode.value)
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input
            type="text"
            name="username"
            ref={node => (this.inputNode = node)}
          />
        </label>
        <button type="submit">Submit</button>
      </form>
    )
  }
}

How to check if a string contains a substring in Bash

I like sed.

substr="foo"
nonsub="$(echo "$string" | sed "s/$substr//")"
hassub=0 ; [ "$string" != "$nonsub" ] && hassub=1

Edit, Logic:

  • Use sed to remove instance of substring from string

  • If new string differs from old string, substring exists

Cannot set property 'innerHTML' of null

Let us first try to understand the root cause as to why it is happening in first place.

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?

The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the script tags (present in head section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded. The scripts present in head tag are trying to access an element having id hello even before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.

How can you make it work as before?

You want to show the "hi" message on the page as soon as the user lands on your page for the first time. So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the hello id element is accessible/available. It is achievable in two ways:

  1. Reorder your scripts: This way your scripts get fired only after the DOM containing your hello id element is already loaded. You can achieve it by simply moving the script tag after all the DOM elements i.e. at the bottom where body tag is ending. Since rendering happens from top to bottom so your scripts get executed in the end and you face no error.

_x000D_
_x000D_
    <!DOCTYPE HTML>_x000D_
    <html>_x000D_
    <head>_x000D_
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
    <title>Untitled Document</title>_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
    <div id="hello"></div>_x000D_
    _x000D_
    <script type ="text/javascript">_x000D_
        what();_x000D_
        function what(){_x000D_
            document.getElementById('hello').innerHTML = 'hi';_x000D_
        };_x000D_
    </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

  1. Use event hooking: Browser's rendering engine provides an event based hook through window.onload event which gives you the hint that browser has finished loading the DOM. So by the time when this event gets fired, you can be rest assured that your element with hello id already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail. So you do something like below code snippet. Please note that in this case, your script works even though it is present at the top of your HTML document inside the head tag.

_x000D_
_x000D_
<!DOCTYPE HTML>_x000D_
        <html>_x000D_
        <head>_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
        <title>Untitled Document</title>_x000D_
        <script type ="text/javascript">_x000D_
            window.onload = function() {_x000D_
            what();_x000D_
            function what(){_x000D_
                document.getElementById('hello').innerHTML = 'hi';_x000D_
            };_x000D_
        }_x000D_
        </script>_x000D_
        </head>_x000D_
        _x000D_
        <body>_x000D_
        <div id="hello"></div>_x000D_
        </body>_x000D_
        </html>
_x000D_
_x000D_
_x000D_

Refresh Page C# ASP.NET

Call Page_load function:

Page_Load(sender, e);

How can I slice an ArrayList out of an ArrayList in Java?

In Java, it is good practice to use interface types rather than concrete classes in APIs.

Your problem is that you are using ArrayList (probably in lots of places) where you should really be using List. As a result you created problems for yourself with an unnecessary constraint that the list is an ArrayList.

This is what your code should look like:

List input = new ArrayList(...);

public void doSomething(List input) {
   List inputA = input.subList(0, input.size()/2);
   ...
}

this.doSomething(input);

Your proposed "solution" to the problem was/is this:

new ArrayList(input.subList(0, input.size()/2))

That works by making a copy of the sublist. It is not a slice in the normal sense. Furthermore, if the sublist is big, then making the copy will be expensive.


If you are constrained by APIs that you cannot change, such that you have to declare inputA as an ArrayList, you might be able to implement a custom subclass of ArrayList in which the subList method returns a subclass of ArrayList. However:

  1. It would be a lot of work to design, implement and test.
  2. You have now added significant new class to your code base, possibly with dependencies on undocumented aspects (and therefore "subject to change") aspects of the ArrayList class.
  3. You would need to change relevant places in your codebase where you are creating ArrayList instances to create instances of your subclass instead.

The "copy the array" solution is more practical ... bearing in mind that these are not true slices.

How can I give eclipse more memory than 512M?

I've had a lot of problems trying to get Eclipse to accept as much memory as I'd like it to be able to use (between 2 and 4 gigs for example).

Open eclipse.ini in the Eclipse installation directory. You should be able to change the memory sizes after -vmargs up to 1024 without a problem up to some maximum value that's dependent on your system. Here's that section on my Linux box:

-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=512m
-Xms512m
-Xmx1024m

And here's that section on my Windows box:

-vmargs
-Xms256m
-Xmx1024m

But, I've failed at setting it higher than 1024 megs. If anybody knows how to make that work, I'd love to know.

EDIT: 32bit version of juno seems to not accept more than Xmx1024m where the 64 bit version accept 2048.

EDIT: Nick's post contains some great links that explain two different things:

  • The problem is largely dependent on your system and the amount of contiguous free memory available, and
  • By using javaw.exe (on Windows), you may be able to get a larger allocated block of memory.

I have 8 gigs of Ram and can't set -Xmx to more than 1024 megs of ram, even when a minimal amount of programs are loaded and both windows/linux report between 4 and 5 gigs of free ram.

git add, commit and push commands in one?

Since the question doesn't specify which shell, here's the eshell version based on the earlier answers. This goes in the eshell alias file, which might be in ~/.emacs.d/eshell/alias I've added the first part z https://github.com/rupa/z/ which let's you quickly cd to a directory, so that this can be run no matter what your current directory is.

alias census z cens; git add .; git commit -m "fast"; git push

Clearing coverage highlighting in Eclipse

I have used the Open Clover Tool for the code coverage, I have also been searching this for a long time. Its pretty straightforward, in the Coverage Explorer tab, you can find three square buttons which says the code lines you wanted to display, click on hide the coverage square box and its gone. Last button in the image below: enter image description here

Sending email with gmail smtp with codeigniter email library

You need to enable SSL in your PHP config. Load up php.ini and find a line with the following:

;extension=php_openssl.dll

Uncomment it. :D

(by removing the semicolon from the statement)

extension=php_openssl.dll

Send a ping to each IP on a subnet

Not all machines have nmap available, but it's a wonderful tool for any network discovery, and certainly better than iterating through independent ping commands.

$ nmap -n -sP 10.0.0.0/24

Starting Nmap 4.20 ( http://insecure.org ) at 2009-02-02 07:41 CST
Host 10.0.0.1 appears to be up.
Host 10.0.0.10 appears to be up.
Host 10.0.0.104 appears to be up.
Host 10.0.0.124 appears to be up.
Host 10.0.0.125 appears to be up.
Host 10.0.0.129 appears to be up.
Nmap finished: 256 IP addresses (6 hosts up) scanned in 2.365 seconds

Error inflating when extending a class

I had this error plaguing me for the past few hours. Turns out, I had added the custom view lib as a module in Android Studio, but I had neglected to add it as a dependency in app's build.gradle.

dependencies {
    ...
    compile project(':gifview')
}

Truncate (not round off) decimal numbers in javascript

var a = 5.467;
var truncated = Math.floor(a * 100) / 100; // = 5.46

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

CR LF notepad++ removal

View -> Show Symbol -> uncheck Show End of Line.

How to set default value to the input[type="date"]

$date=date("Y-m-d");
echo"$date";
echo"<br>SELECT DATE: <input type='date'  name='date'  id='datepicker' 
value='$date' required >";

Get img thumbnails from Vimeo?

For those still wanting a way to get the thumbnail via URL only, just like Youtube, I built a small application that fetches it with just the Vimeo ID.

https://vumbnail.com/358629078.jpg

Just plug in your video ID and it will pull it and cache it for 28 days so it serves fast.

Here are a couple of examples in HTML:

_x000D_
_x000D_
Simple Image Example

<img src="https://vumbnail.com/358629078.jpg" />


<br>
<br>


Modern Responsive Image Example

<img srcset="https://vumbnail.com/358629078.jpg 640w, https://vumbnail.com/358629078_large.jpg 640w, https://vumbnail.com/358629078_medium.jpg 200w, https://vumbnail.com/358629078_small.jpg 100w" sizes="(max-width: 640px) 100vw, 640px" src="https://vumbnail.com/358629078.jpg" />
_x000D_
_x000D_
_x000D_

If you want to spin up your own you can do so here.

Repo

Getting the difference between two repositories

In repo_a:

git remote add -f b path/to/repo_b.git
git remote update
git diff master remotes/b/master
git remote rm b

Git keeps prompting me for a password

Step 1: check your current configuration

cat .git/config

You will get:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/path_to_your_git.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[user]
    name = your_username
    email = your_email
[branch "master-staging"]
    remote = origin
    merge = refs/heads/master-staging

Step 2: remove your remote origin

git remote rm origin

Step 3: add remote origin back with your username and password

git remote add origin https://your_git_username:[email protected]/path_to_your_git.git

How to detect control+click in Javascript from an onclick div attribute?

Try this:

var control = false;
$(document).on('keyup keydown', function(e) {
  control = e.ctrlKey;
});

$('div#1').on('click', function() {
  if (control) {
    // control-click
  } else {
    // single-click
  }
});

And the right-click triggers a contextmenu event, so:

$('div#1').on('contextmenu', function() {
  // right-click handler
})

how to get vlc logs?

I found the following command to run from command line:

vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt

Postgresql SELECT if string contains

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || "tag_name" || '%';

tag_name should be in quotation otherwise it will give error as tag_name doest not exist

Stop and Start a service via batch or cmd file?

I have created my personal batch file for this, mine is a little different but feel free to modify as you see fit. I created this a little while ago because I was bored and wanted to make a simple way for people to be able to input ending, starting, stopping, or setting to auto. This BAT file simply requests that you input the service name and it will do the rest for you. I didn't realize that he was looking for something that stated any error, I must have misread that part. Though typically this can be done by inputting >> output.txt on the end of the line.

The %var% is just a way for the user to be able to input their own service into this, instead of having to go modify the bat file every time that you want to start/stop a different service.

If I am wrong, anyone can feel free to correct me on this.

@echo off
set /p c= Would you like to start a service [Y/N]?
  if /I "%c%" EQU "Y" goto :1
  if /I "%c%" EQU "N" goto :2
    :1  
    set /p var= Service name: 
:2 
set /p c= Would you like to stop a service [Y/N]?
  if /I "%c%" EQU "Y" goto :3
  if /I "%c%" EQU "N" goto :4
    :3  
    set /p var1= Service name:
:4
set /p c= Would you like to disable a service [Y/N]?
  if /I "%c%" EQU "Y" goto :5
  if /I "%c%" EQU "N" goto :6
    :5  
    set /p var2= Service name:
:6 
set /p c= Would you like to set a service to auto [Y/N]?
  if /I "%c%" EQU "Y" goto :7
  if /I "%c%" EQU "N" goto :10
    :7  
    set /p var3= Service name:
:10
sc start %var%
sc stop %var1%
sc config %var2% start=disabled
sc config %var3% start=auto

Applying a single font to an entire website with CSS

* { font-family: Algerian; }

The universal selector * refers to any element.

Undo git update-index --assume-unchanged <file>

If you are using Git Extensions, then follow below steps:

  1. Go to commit window.
  2. Click on the dropdown named Working directory changes.
  3. Select Show assummed-unchanged files option.
  4. Right click on the file you want to unassumme.
  5. Select Do no assumme unchanged.

You are done.

Get docker container id from container name

In Linux:

sudo docker ps -aqf "name=containername"

Or in OS X, Windows:

docker ps -aqf "name=containername"

where containername is your container name.

To avoid getting false positives, as @llia Sidorenko notes, you can use regex anchors like so:

docker ps -aqf "name=^containername$"

explanation:

  • -q for quiet. output only the ID
  • -a for all. works even if your container is not running
  • -f for filter.
  • ^ container name must start with this string
  • $ container name must end with this string

Pass Additional ViewData to a Strongly-Typed Partial View

The easiest way to pass additional data is to add the data to the existing ViewData for the view as @Joel Martinez notes. However, if you don't want to pollute your ViewData, RenderPartial has a method that takes three arguments as well as the two-argument version you show. The third argument is a ViewDataDictionary. You can construct a separate ViewDataDictionary just for your partial containing just the extra data that you want to pass in.

How to pass in parameters when use resource service?

I suggest you to use provider. Provide is good when you want to configure it first before to use (against Service/Factory)

Something like:

.provider('Magazines', function() {

    this.url = '/';
    this.urlArray = '/';
    this.organId = 'Default';

    this.$get = function() {
        var url = this.url;
        var urlArray = this.urlArray;
        var organId = this.organId;

        return {
            invoke: function() {
                return ......
            }
        }
    };

    this.setUrl  = function(url) {
        this.url = url;
    };

   this.setUrlArray  = function(urlArray) {
        this.urlArray = urlArray;
    };

    this.setOrganId  = function(organId) {
        this.organId = organId;
    };
});

.config(function(MagazinesProvider){
    MagazinesProvider.setUrl('...');
    MagazinesProvider.setUrlArray('...');
    MagazinesProvider.setOrganId('...');
});

And now controller:

function MyCtrl($scope, Magazines) {        

        Magazines.invoke();

       ....

}

Clearing _POST array fully

It may appear to be overly awkward, but you're probably better off unsetting one element at a time rather than the entire $_POST array. Here's why: If you're using object-oriented programming, you may have one class use $_POST['alpha'] and another class use $_POST['beta'], and if you unset the array after first use, it will void its use in other classes. To be safe and not shoot yourself in the foot, just drop in a little method that will unset the elements that you've just used: For example:

private function doUnset()
{
    unset($_POST['alpha']);
    unset($_POST['gamma']);
    unset($_POST['delta']);
    unset($_GET['eta']);
    unset($_GET['zeta']);
}

Just call the method and unset just those superglobal elements that have been passed to a variable or argument. Then, the other classes that may need a superglobal element can still use them.

However, you are wise to unset the superglobals as soon as they have been passed to an encapsulated object.

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

While it might not be the best approach the closest equivalent I can think of that works is this with the support/compatibility library

getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();

or

getActivity().getFragmentManager().beginTransaction().remove(this).commit();

otherwise.

In addition you can use the backstack and pop it. However keep in mind that the fragment might not be on the backstack (depending on the fragmenttransaction that got it there..) or it might not be the last one that got onto the stack so popping the stack could remove the wrong one...

How to change the integrated terminal in visual studio code or VSCode

For OP's terminal Cmder there is an integration guide, also hinted in the VS Code docs.

If you want to use VS Code tasks and encounter problems after switch to Cmder, there is an update to @khernand's answer. Copy this into your settings.json file:

"terminal.integrated.shell.windows": "cmd.exe",

"terminal.integrated.env.windows": {
  "CMDER_ROOT": "[cmder_root]" // replace [cmder_root] with your cmder path
},
"terminal.integrated.shellArgs.windows": [
  "/k",
  "%CMDER_ROOT%\\vendor\\bin\\vscode_init.cmd" // <-- this is the relevant change
  // OLD: "%CMDER_ROOT%\\vendor\\init.bat"
],

The invoked file will open Cmder as integrated terminal and switch to cmd for tasks - have a look at the source here. So you can omit configuring a separate terminal in tasks.json to make tasks work.

Starting with VS Code 1.38, there is also "terminal.integrated.automationShell.windows" setting, which lets you set your terminal for tasks globally and avoids issues with Cmder.

"terminal.integrated.automationShell.windows": "cmd.exe"

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

There are two different certificates for two different provisioning profiles (development and distribution). You have to install BOTH certificates in keychain. In the iPhone Developer Program Portal:

Certificates -> Development -> Download Certificates -> Distribution -> Download

Double click both certificates. After that both certificates must appear in Keychain.

Redis command to get all available keys?

If your redis is a cluster,you can use this script

#!/usr/bin/env bash
redis_list=("172.23.3.19:7001,172.23.3.19:7002,172.23.3.19:7003,172.23.3.19:7004,172.23.3.19:7005,172.23.3.19:7006")

arr=($(echo "$redis_list" | tr ',' '\n'))

for info in ${arr[@]}; do
  echo "start :${info}"
  redis_info=($(echo "$info" | tr ':' '\n'))
  ip=${redis_info[0]}
  port=${redis_info[1]}
  echo "ip="${ip}",port="${port}
  redis-cli -c -h $ip -p $port set laker$port '?????'
  redis-cli -c -h $ip -p $port keys \*

done

echo "end"

Length of array in function argument

int arsize(int st1[]) {
    int i = 0;
    for (i; !(st1[i] & (1 << 30)); i++);
    return i;
}

This works for me :)

Sql Server : How to use an aggregate function like MAX in a WHERE clause

The correct way to use max in the having clause is by performing a self join first:

select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
  on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)

The following is how you would join with a subquery:

select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
                 from table1 t1_max
                 where t1.id = t1_max.id)

Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:

select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
  on t1.id = t2.id
join table2 t3
  on t1.id = t3.id


select a, b, c
from #dataset d
join #dataset d_max
  on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c

Sub query version:

select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
  on t1.id = t2.id
join table2 t3
  on t1.id = t3.id


select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
                from #dataset d_max
                where d.id = d_max.id)

How to change Named Range Scope

I found the solution! Just copy the sheet with your named variables. Then delete the original sheet. The copied sheet will now have the same named variables, but with a local scope (scope= the copied sheet).

However, I don't know how to change from local variables to global..

CSS content generation before or after 'input' elements

This is not due to input tags not having any content per-se, but that their content is outside the scope of CSS.

input elements are a special type called replaced elements, these do not support :pseudo selectors like :before and :after.

In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are <img>, <object>, <video> or form elements like <textarea> and <input>. Some elements, like <audio> or <canvas> are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.

Note that this is even referred to in the spec:

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML).

And more explicitly:

Replaced elements do not have ::before and ::after pseudo-elements

Get started with Latex on Linux

yum -y install texlive

was not enough for my centos distro to get the latex command.

This site https://gist.github.com/melvincabatuan/350f86611bc012a5c1c6 contains additional packages. In particular:

yum -y install texlive texlive-latex texlive-xetex

was enough but the author also points out these as well:

yum -y install texlive-collection-latex
yum -y install texlive-collection-latexrecommended
yum -y install texlive-xetex-def
yum -y install texlive-collection-xetex

Only if needed:

yum -y install texlive-collection-latexextra

How to parse JSON Array (Not Json Object) in Android

public static void main(String[] args) throws JSONException {
    String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";

    JSONArray jsonarray = new JSONArray(str);


    for(int i=0; i<jsonarray.length(); i++){
        JSONObject obj = jsonarray.getJSONObject(i);

        String name = obj.getString("name");
        String url = obj.getString("url");

        System.out.println(name);
        System.out.println(url);
    }   
}   

Output:

name1
url1
name2
url2

How to use UIPanGestureRecognizer to move object? iPhone/iPad

The Swift 2 version:

// start detecting pan gesture
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(TTAltimeterDetailViewController.panGestureDetected(_:)))
panGestureRecognizer.minimumNumberOfTouches = 1
self.chartOverlayView.addGestureRecognizer(panGestureRecognizer)

func panGestureDetected(panGestureRecognizer: UIPanGestureRecognizer) {
    print("pan gesture recognized")
}

SELECT max(x) is returning null; how can I make it return 0?

or:

SELECT coalesce(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1

Alter table add multiple columns ms sql

Alter table Hotels 
Add  
{ 
 HasPhotoInReadyStorage  bit, 
 HasPhotoInWorkStorage  bit, 
 HasPhotoInMaterialStorage bit, 
 HasHotelPhotoInReadyStorage  bit, 
 HasHotelPhotoInWorkStorage  bit, 
 HasHotelPhotoInMaterialStorage bit, 
 HasReporterData  bit, 
 HasMovieInReadyStorage  bit, 
 HasMovieInWorkStorage  bit, 
 HasMovieInMaterialStorage bit 
}; 

Above you are using {, }.

Also, you are missing commas:

ALTER TABLE Regions 
ADD ( HasPhotoInReadyStorage  bit, 
 HasPhotoInWorkStorage  bit, 
 HasPhotoInMaterialStorage bit <**** comma needed here
 HasText  bit); 

You need to remove the brackets and make sure all columns have a comma where necessary.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

We have an extension method to do exactly this in MoreLINQ. You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection.

In your case you'd do something like:

var item = items.MaxBy(x => x.Height);

This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as MaxBy):

  • It's O(n) unlike the previous accepted answer which finds the maximum value on every iteration (making it O(n^2))
  • The ordering solution is O(n log n)
  • Taking the Max value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion.
  • It's a lot simpler to read and understand than the aggregate version, and only evaluates the projection once per element

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

If you open /Users/{your name}/android sdks/tools/android (double click it), then click on "Android SDK Manager" menu and then "Preferences" and then you can change your proxy settings specifically for Android SDK Manager. These proxy settings also apply to "Android SDK Manager" if used within Eclipse.

Update date + one year in mysql

For multiple interval types use a nested construction as in:

 UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)

For updating a given date in the column date to 1 year + 1 day

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

How to get item count from DynamoDB?

I'm too late here but like to extend Daniel's answer about using aws cli to include filter expression.

Running

aws dynamodb scan \
    --table-name <tableName> \
    --filter-expression "#v = :num" \
    --expression-attribute-names '{"#v": "fieldName"}' \
    --expression-attribute-values '{":num": {"N": "123"}}' \
    --select "COUNT"

would give

{
    "Count": 2945,
    "ScannedCount": 7874,
    "ConsumedCapacity": null
}

That is, ScannedCount is total count and Count is the number of items which are filtered by given expression (fieldName=123).

How to iterate over the keys and values with ng-repeat in AngularJS?

we can follow below procedure to avoid display of key-values in alphabetical order.

Javascript

$scope.data = {
   "id": 2,
   "project": "wewe2012",
   "date": "2013-02-26",
   "description": "ewew",
   "eet_no": "ewew",
};
var array = [];
for(var key in $scope.data){
    var test = {};
    test[key]=$scope.data[key];
    array.push(test);
}
$scope.data = array;

HTML

<p ng-repeat="obj in data">
   <font ng-repeat="(key, value) in obj">
      {{key}} : {{value}}
   </font>
</p>

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

How to convert SecureString to System.String?

Use the System.Runtime.InteropServices.Marshal class:

String SecureStringToString(SecureString value) {
  IntPtr valuePtr = IntPtr.Zero;
  try {
    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
    return Marshal.PtrToStringUni(valuePtr);
  } finally {
    Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  }
}

If you want to avoid creating a managed string object, you can access the raw data using Marshal.ReadInt16(IntPtr, Int32):

void HandleSecureString(SecureString value) {
  IntPtr valuePtr = IntPtr.Zero;
  try {
    valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
    for (int i=0; i < value.Length; i++) {
      short unicodeChar = Marshal.ReadInt16(valuePtr, i*2);
      // handle unicodeChar
    }
  } finally {
    Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
  }
}

How can I get Eclipse to show .* files?

I'm using 64 bit Eclipse for PHP Devleopers Version: Helios Service Release 2

It cam with RSE..

None of the above solutions worked for me... What I did was similar to scubabble's answer, but after clicking the down arrow (view menu) in the top of the RSE package explorer I had to mouseover "Preferences" and click on "Remote Systems"

I then opened the "Remote Systems" nav tree in the left of the preferences window that came u and went to "Files"

Underneath a list of File types is a checkbox that was unchecked: "Show hidden files"

CHECK IT!

Detect Scroll Up & Scroll down in ListView

Those methods cannot be used to detect scrolling directions directly. There are many ways of getting the direction. A simple code(untested) for one such method is explained below :


public class ScrollTrackingListView extends ListView {

    private boolean readyForMeasurement = false;
    private Boolean isScrollable = null;
    private float prevDistanceToEnd = -1.0;
    private ScrollDirectionListener listener = null;

    public ScrollTrackingListView(Context context) {
        super(context);
        init();
    }

    public ScrollTrackingListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ScrollTrackingListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        ViewTreeObserver observer = getViewTreeObserver();
        observer.addOnGlobalLayoutListener(globalLayoutListener);
        setOnScrollListener(scrollListener);
    }

    private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener
            = new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            readyForMeasurement = true;
            calculateDistanceToEnd();
        }

    };

    public void registerScrollDirectionListener(ScrollDirectionListener listener) {
        scrollDirectionListener = listener;
    }

    public void unregisterScrollDirectionListener() {
        scrollDirectionListener = null;
    }

    private OnScrollListener scrollListener
            = new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {
            calculateDistanceToEnd();
        }

        @Override
        public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            // Do nothing
        }

    };

    private void calculateDistanceToEnd() {

        if (readyForMeasurement) {

            // I'm using the height of the layout, horizontal scrollbar and
            // content along with scroll down offset

            // computeVerticalScrollExtent is used to compute the length of the thumb within the scrollbar's track.
            // The length of the thumb is a function of the view height and the content length.
            int verticalScrollExtent = computeVerticalScrollExtent();
            int verticalScrollOffset = computeVerticalScrollOffset();
            int verticalScrollRange = computeVerticalScrollRange();
            int horizontalScrollBarHeight = getHorizontalScrollbarHeight();

            /**
             * 1. Let "R" represent the range of the vertical scrollbar. This corresponds to the length of the content
             * in the view.
             * 2. Let "E" represent the extent of the vertical scrollbar. The extent is a constant value and is
             * (probably) equal to a value proportional to the height of the view.
             * 3. Offset "o" represents the current position in the range that is visible to the user. It can take
             * values from "0 to E".
             *
             * Now the DistanceToEnd is calculated using these three values as follows :
             *
             * DistanceToEnd = (R - o) / E
             *
             * DistanceToEnd will hold the value in NumberOfScreenToEnd units.
             *
             */

            float distanceToEnd =
                    ((float)(verticalScrollRange - verticalScrollOffset))/((float)(verticalScrollExtent));

            if(prevDistanceToEnd == -1) {
                 prevDistanceToEnd = distanceToEnd;
            } else {
                 if(listener != null) {
                     if(distanceToEnd > prevDistanceToEnd) {
                        // User is scrolling up
                         listener.onScrollingUp();
                     } else {
                        // User is scrolling up
                         listener.onScrollingDown();
                    }
                 }
                 prevDistanceToEnd = distanceToEnd;
            }

            if(isScrollable == null) {
                // Check if the view height is less than a screen (i.e., no scrolling is enabled)
                if((horizontalScrollBarHeight + verticalScrollExtent) >= verticalScrollRange) {
                    isScrollable = Boolean.FALSE;
                } else {
                    isScrollable = Boolean.TRUE;
                }
            }

        }

    }

    public interface ScrollDirectionListener {

        public void onScrollingUp();

        public void onScrollingDown();

    }

}

The idea is to calculate the distanceToEnd. If distanceToEnd increases, the user is scrolling up and if it decreases, the user is scrolling down. That will also give you the exact distance to the end of the list.

If you are just trying to know whether the user is scrolling up or down you can override the onInterceptTouchEvent to detect the scrolling direction like below :

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mInitialX = event.getX();
                mInitialY = event.getY();
                return true;
            case MotionEvent.ACTION_MOVE:
                final float x = event.getX();
                final float y = event.getY();
                final float yDiff = y - mInitialY; // yDiff less than 0.0 implies scrolling down while yDiff greater than 0.0 implies scrolling up. If I try to add the less than or greater than symbols, the preview refuses to display it.
                if(yDiff less than 0.0) listener.onScrollingDown();
                else if(yDiff greater than 0.0) listener.onScrollingUp();
                break;
        }
        return super.onInterceptTouchEvent(event);
    }

Inserting data into a temporary table

Basic operation of Temporary table is given below, modify and use as per your requirements,

-- CREATE A TEMP TABLE

CREATE TABLE #MyTempEmployeeTable(tempUserID  varchar(MAX), tempUserName  varchar(MAX) )

-- INSERT VALUE INTO A TEMP TABLE

INSERT INTO #MyTempEmployeeTable(tempUserID,tempUserName) SELECT userid,username FROM users where userid =21

-- QUERY A TEMP TABLE [This will work only in same session/Instance, not in other user session instance]

SELECT * FROM #MyTempEmployeeTable

-- DELETE VALUE IN TEMP TABLE

DELETE FROM #MyTempEmployeeTable

-- DROP A TEMP TABLE

DROP TABLE #MyTempEmployeeTable

How to get a dependency tree for an artifact?

If you bother creating a sample project and adding your 3rd party dependency to that, then you can run the following in order to see the full hierarchy of the dependencies.

You can search for a specific artifact using this maven command:

mvn dependency:tree -Dverbose -Dincludes=[groupId]:[artifactId]:[type]:[version]

According to the documentation:

where each pattern segment is optional and supports full and partial * wildcards. An empty pattern segment is treated as an implicit wildcard.

Imagine you are trying to find 'log4j-1.2-api' jar file among different modules of your project:

mvn dependency:tree -Dverbose -Dincludes=org.apache.logging.log4j:log4j-1.2-api

more information can be found here.

Edit: Please note that despite the advantages of using verbose parameter, it might not be so accurate in some conditions. Because it uses Maven 2 algorithm and may give wrong results when used with Maven 3.

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

C language leaves compiler some freedom about the location of the structural elements in the memory:

  • memory holes may appear between any two components, and after the last component. It was due to the fact that certain types of objects on the target computer may be limited by the boundaries of addressing
  • "memory holes" size included in the result of sizeof operator. The sizeof only doesn't include size of the flexible array, which is available in C/C++
  • Some implementations of the language allow you to control the memory layout of structures through the pragma and compiler options

The C language provides some assurance to the programmer of the elements layout in the structure:

  • compilers required to assign a sequence of components increasing memory addresses
  • Address of the first component coincides with the start address of the structure
  • unnamed bit fields may be included in the structure to the required address alignments of adjacent elements

Problems related to the elements alignment:

  • Different computers line the edges of objects in different ways
  • Different restrictions on the width of the bit field
  • Computers differ on how to store the bytes in a word (Intel 80x86 and Motorola 68000)

How alignment works:

  • The volume occupied by the structure is calculated as the size of the aligned single element of an array of such structures. The structure should end so that the first element of the next following structure does not the violate requirements of alignment

p.s More detailed info are available here: "Samuel P.Harbison, Guy L.Steele C A Reference, (5.6.2 - 5.6.7)"

Unable to execute dex: method ID not in [0, 0xffff]: 65536

I've shared a sample project which solve this problem using custom_rules.xml build script and a few lines of code.

I used it on my own project and it is runs flawless on 1M+ devices (from android-8 to the latest android-19). Hope it helps.

https://github.com/mmin18/Dex65536

Get ID from URL with jQuery

Just because I can:

function pathName(url, a) {
   return (a = document.createElement('a'), a.href = url, a.pathname); //optionally, remove leading '/'
}

pathName("http://www.site.com/234234234") -> "/234234234"

SELECT * WHERE NOT EXISTS

You didn't join the table in your query.

Your original query will always return nothing unless there are no records at all in eotm_dyn, in which case it will return everything.

Assuming these tables should be joined on employeeID, use the following:

SELECT  *
FROM    employees e
WHERE   NOT EXISTS
        (
        SELECT  null 
        FROM    eotm_dyn d
        WHERE   d.employeeID = e.id
        )

You can join these tables with a LEFT JOIN keyword and filter out the NULL's, but this will likely be less efficient than using NOT EXISTS.

How to create a user in Django?

If you creat user normally, you will not be able to login as password creation method may b different You can use default signup form for that

from django.contrib.auth.forms import UserCreationForm

You can extend that also

from django.contrib.auth.forms import UserCreationForm

class UserForm(UserCreationForm):
    mobile = forms.CharField(max_length=15, min_length=10)
    email = forms.EmailField(required=True)
    class Meta:
        model = User
        fields = ['username', 'password', 'first_name', 'last_name', 'email', 'mobile' ]

Then in view use this class

class UserCreate(CreateView):
    form_class = UserForm
    template_name = 'registration/signup.html'
    success_url = reverse_lazy('list')

    def form_valid(self, form):
        user = form.save()

JavaScript associative array to JSON

You might want to push the object into the array

enter code here

var AssocArray = new Array();

AssocArray.push( "The letter A");

console.log("a = " + AssocArray[0]);

// result: "a = The letter A"

console.log( AssocArray[0]);

JSON.stringify(AssocArray);

What’s the best RESTful method to return total number of items in an object?

Alternative when you don't need actual items

Franci Penov's answer is certainly the best way to go so you always return items along with all additional metadata about your entities being requested. That's the way it should be done.

but sometimes returning all data doesn't make sense, because you may not need them at all. Maybe all you need is that metadata about your requested resource. Like total count or number of pages or something else. In such case you can always have URL query tell your service not to return items but rather just metadata like:

/api/members?metaonly=true
/api/members?includeitems=0

or something similar...

Disabling SSL Certificate Validation in Spring RestTemplate

Security: disable https/TLS certificate hostname check,the following code worked in spring boot rest template

*HttpsURLConnection.setDefaultHostnameVerifier(
        //SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
        // * @deprecated (4.4) Use {@link org.apache.http.conn.ssl.NoopHostnameVerifier}
        new NoopHostnameVerifier()
);*

How to update PATH variable permanently from Windows command line?

This Python-script[*] does exactly that:

"""
Show/Modify/Append registry env-vars (ie `PATH`) and notify Windows-applications to pickup changes.

First attempts to show/modify HKEY_LOCAL_MACHINE (all users), and 
if not accessible due to admin-rights missing, fails-back 
to HKEY_CURRENT_USER.
Write and Delete operations do not proceed to user-tree if all-users succeed.

Syntax: 
    {prog}                  : Print all env-vars. 
    {prog}  VARNAME         : Print value for VARNAME. 
    {prog}  VARNAME   VALUE : Set VALUE for VARNAME. 
    {prog}  +VARNAME  VALUE : Append VALUE in VARNAME delimeted with ';' (i.e. used for `PATH`). 
    {prog}  -VARNAME        : Delete env-var value. 

Note that the current command-window will not be affected, 
changes would apply only for new command-windows.
"""

import winreg
import os, sys, win32gui, win32con

def reg_key(tree, path, varname):
    return '%s\%s:%s' % (tree, path, varname) 

def reg_entry(tree, path, varname, value):
    return '%s=%s' % (reg_key(tree, path, varname), value)

def query_value(key, varname):
    value, type_id = winreg.QueryValueEx(key, varname)
    return value

def yield_all_entries(tree, path, key):
    i = 0
    while True:
        try:
            n,v,t = winreg.EnumValue(key, i)
            yield reg_entry(tree, path, n, v)
            i += 1
        except OSError:
            break ## Expected, this is how iteration ends.

def notify_windows(action, tree, path, varname, value):
    win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
    print("---%s %s" % (action, reg_entry(tree, path, varname, value)), file=sys.stderr)

def manage_registry_env_vars(varname=None, value=None):
    reg_keys = [
        ('HKEY_LOCAL_MACHINE', r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'),
        ('HKEY_CURRENT_USER', r'Environment'),
    ]
    for (tree_name, path) in reg_keys:
        tree = eval('winreg.%s'%tree_name)
        try:
            with winreg.ConnectRegistry(None, tree) as reg:
                with winreg.OpenKey(reg, path, 0, winreg.KEY_ALL_ACCESS) as key:
                    if not varname:
                        for regent in yield_all_entries(tree_name, path, key):
                            print(regent)
                    else:
                        if not value:
                            if varname.startswith('-'):
                                varname = varname[1:]
                                value = query_value(key, varname)
                                winreg.DeleteValue(key, varname)
                                notify_windows("Deleted", tree_name, path, varname, value)
                                break  ## Don't propagate into user-tree.
                            else:
                                value = query_value(key, varname)
                                print(reg_entry(tree_name, path, varname, value))
                        else:
                            if varname.startswith('+'):
                                varname = varname[1:]
                                value = query_value(key, varname) + ';' + value
                            winreg.SetValueEx(key, varname, 0, winreg.REG_EXPAND_SZ, value)
                            notify_windows("Updated", tree_name, path, varname, value)
                            break  ## Don't propagate into user-tree.
        except PermissionError as ex:
            print("!!!Cannot access %s due to: %s" % 
                    (reg_key(tree_name, path, varname), ex), file=sys.stderr)
        except FileNotFoundError as ex:
            print("!!!Cannot find %s due to: %s" % 
                    (reg_key(tree_name, path, varname), ex), file=sys.stderr)

if __name__=='__main__':
    args = sys.argv
    argc = len(args)
    if argc > 3:
        print(__doc__.format(prog=args[0]), file=sys.stderr)
        sys.exit()

    manage_registry_env_vars(*args[1:])

Below are some usage examples, assuming it has been saved in a file called setenv.py somewhere in your current path. Note that in these examples i didn't have admin-rights, so the changes affected only my local user's registry tree:

> REM ## Print all env-vars
> setenv.py
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
HKEY_CURRENT_USER\Environment:PATH=...
...

> REM ## Query env-var:
> setenv.py PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
!!!Cannot find HKEY_CURRENT_USER\Environment:PATH due to: [WinError 2] The system cannot find the file specified

> REM ## Set env-var:
> setenv.py PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo

> REM ## Append env-var:
> setenv.py +PATH D:\Bar
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo;D:\Bar

> REM ## Delete env-var:
> setenv.py -PATH
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Deleted HKEY_CURRENT_USER\Environment:PATH

[*] Adapted from: http://code.activestate.com/recipes/416087-persistent-environment-variables-on-windows/

How to call a parent method from child class in javascript?

Well in order to do this, you are not limited with the Class abstraction of ES6. Accessing the parent constructor's prototype methods is possible through the __proto__ property (I am pretty sure there will be fellow JS coders to complain that it's depreciated) which is depreciated but at the same time discovered that it is actually an essential tool for sub-classing needs (especially for the Array sub-classing needs though). So while the __proto__ property is still available in all major JS engines that i know, ES6 introduced the Object.getPrototypeOf() functionality on top of it. The super() tool in the Class abstraction is a syntactical sugar of this.

So in case you don't have access to the parent constructor's name and don't want to use the Class abstraction you may still do as follows;

function ChildObject(name) {
    // call the parent's constructor
    ParentObject.call(this, name);
    this.myMethod = function(arg) {
    //this.__proto__.__proto__.myMethod.call(this,arg);
    Object.getPrototypeOf(Object.getPrototypeOf(this)).myMethod.call(this,arg);
    }
}

Breaking out of a nested loop

Since I first saw break in C a couple of decades back, this problem has vexed me. I was hoping some language enhancement would have an extension to break which would work thus:

break; // our trusty friend, breaks out of current looping construct.
break 2; // breaks out of the current and it's parent looping construct.
break 3; // breaks out of 3 looping constructs.
break all; // totally decimates any looping constructs in force.

How do I find numeric columns in Pandas?

Simple one-line answer to create a new dataframe with only numeric columns:

df.select_dtypes(include=np.number)

If you want the names of numeric columns:

df.select_dtypes(include=np.number).columns.tolist()

Complete code:

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': range(7, 10),
                   'B': np.random.rand(3),
                   'C': ['foo','bar','baz'],
                   'D': ['who','what','when']})
df
#    A         B    C     D
# 0  7  0.704021  foo   who
# 1  8  0.264025  bar  what
# 2  9  0.230671  baz  when

df_numerics_only = df.select_dtypes(include=np.number)
df_numerics_only
#    A         B
# 0  7  0.704021
# 1  8  0.264025
# 2  9  0.230671

colnames_numerics_only = df.select_dtypes(include=np.number).columns.tolist()
colnames_numerics_only
# ['A', 'B']

Making a mocked method return an argument that was passed to it

I use something similar (basically it's the same approach). Sometimes it's useful to have a mock object return pre-defined output for certain inputs. That goes like this:

private Hashtable<InputObject,  OutputObject> table = new Hashtable<InputObject, OutputObject>();
table.put(input1, ouput1);
table.put(input2, ouput2);

...

when(mockObject.method(any(InputObject.class))).thenAnswer(
       new Answer<OutputObject>()
       {
           @Override
           public OutputObject answer(final InvocationOnMock invocation) throws Throwable
           {
               InputObject input = (InputObject) invocation.getArguments()[0];
               if (table.containsKey(input))
               {
                   return table.get(input);
               }
               else
               {
                   return null; // alternatively, you could throw an exception
               }
           }
       }
       );

Using an if statement to check if a div is empty

I've encountered this today and the accepted answers did not work for me. Here is how I did it.

if( $('#div-id *').length === 0 ) {
    // your code here...
}

My solution checks if there are any elements inside the div so it would still mark the div empty if there is only text inside it.

Failure [INSTALL_FAILED_INVALID_APK]

If you write android:extractNativeLibs="false" in AndroidManifest file. then change it to android:extractNativeLibs="true"

Find the day of a week

Let's say you additionally want the week to begin on Monday (instead of default on Sunday), then the following is helpful:

require(lubridate)
df$day = ifelse(wday(df$time)==1,6,wday(df$time)-2)

The result is the days in the interval [0,..,6].

If you want the interval to be [1,..7], use the following:

df$day = ifelse(wday(df$time)==1,7,wday(df$time)-1)

... or, alternatively:

df$day = df$day + 1

Changing Jenkins build number

For multibranch pipeline projects, do this in the script console:

def project = Jenkins.instance.getItemByFullName("YourMultibranchPipelineProjectName")    
project.getAllJobs().each{ item ->   
    
    if(item.name == 'jobName'){ // master, develop, feature/......
      
      item.updateNextBuildNumber(#Number);
      item.saveNextBuildNumber();
      
      println('new build: ' + item.getNextBuildNumber())
    }
}

How to efficiently remove duplicates from an array without using Set

This is not using Set, Map, List or any extra collection, only two arrays:

package arrays.duplicates;

import java.lang.reflect.Array;
import java.util.Arrays;

public class ArrayDuplicatesRemover<T> {

    public static <T> T[] removeDuplicates(T[] input, Class<T> clazz) {
        T[] output = (T[]) Array.newInstance(clazz, 0);
        for (T t : input) {
            if (!inArray(t, output)) {
                output = Arrays.copyOf(output, output.length + 1);
                output[output.length - 1] = t;
            }
        }
        return output;
    }

    private static <T> boolean inArray(T search, T[] array) {
        for (T element : array) {
            if (element.equals(search)) {
                return true;
            }
        }
        return false;
    }

}

And the main to test it

package arrays.duplicates;

import java.util.Arrays;

public class TestArrayDuplicates {

    public static void main(String[] args) {
        Integer[] array = {1, 1, 2, 2, 3, 3, 3, 3, 4};
        testArrayDuplicatesRemover(array);
    }

    private static void testArrayDuplicatesRemover(Integer[] array) {
        final Integer[] expectedResult = {1, 2, 3, 4};
        Integer[] arrayWithoutDuplicates = ArrayDuplicatesRemover.removeDuplicates(array, Integer.class);
        System.out.println("Array without duplicates is supposed to be: " + Arrays.toString(expectedResult));
        System.out.println("Array without duplicates currently is: " + Arrays.toString(arrayWithoutDuplicates));
        System.out.println("Is test passed ok?: " + (Arrays.equals(arrayWithoutDuplicates, expectedResult) ? "YES" : "NO"));
    }

}

And the output:

Array without duplicates is supposed to be: [1, 2, 3, 4]
Array without duplicates currently is: [1, 2, 3, 4]
Is test passed ok?: YES

How to assign an action for UIImageView object in Swift

Swift 4 Code


Step 1 In ViewdidLoad()

   let pictureTap = UITapGestureRecognizer(target: self, action: #selector(MyInfoTableViewController.imageTapped))
       userImageView.addGestureRecognizer(pictureTap)
       userImageView.isUserInteractionEnabled = true

Step 2 Add Following Function

@objc func imageTapped() {

        let imageView = userImageView
        let newImageView = UIImageView(image: imageView?.image)
        newImageView.frame = UIScreen.main.bounds
        newImageView.backgroundColor = UIColor.black
        newImageView.contentMode = .scaleAspectFit
        newImageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
        newImageView.addGestureRecognizer(tap)
        self.view.addSubview(newImageView)

        self.navigationController?.isNavigationBarHidden = true
        self.tabBarController?.tabBar.isHidden = true

    }

It's Tested And Working Properly

Image encryption/decryption using AES256 symmetric block ciphers

Warning: This answer contains code you should not use as it is insecure (using SHA1PRNG for key derivation and using AES in ECB mode)

Instead (as of 2016), use PBKDF2WithHmacSHA1 for key derivation and AES in CBC or GCM mode (GCM provides both privacy and integrity)

You could use functions like these:

private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(clear);
    return encrypted;
}

private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    return decrypted;
}

And invoke them like this:

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object   
byte[] b = baos.toByteArray();  

byte[] keyStart = "this is a key".getBytes();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();    

// encrypt
byte[] encryptedData = encrypt(key,b);
// decrypt
byte[] decryptedData = decrypt(key,encryptedData);

This should work, I use similar code in a project right now.

How to create custom spinner like border around the spinner with down triangle on the right side?

This is a simple one.

your_layout.xml

<android.support.v7.widget.AppCompatSpinner
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/spinner_background"
/>

In the drawable folder, spinner_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item><layer-list>
    <item>
        <shape>
            <solid
                android:color="@color/colorWhite">
            </solid>

            <corners android:radius="3dp" />

            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
            <stroke
                android:width="2dp"
                android:color="@color/colorDarkGrey"/>
        </shape>
    </item>
    <item >
        <bitmap android:gravity="bottom|right"
        android:src="@drawable/ic_arrow_drop_down_black_24dp" />
    </item>
  </layer-list></item>
</selector>

Preview:

Spinner example

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

following this link:

How To: Eclipse Maven install build jar with dependencies

i found out that this is not workable solution because the class loader doesn't load jars from within jars, so i think that i will unpack the dependencies inside the jar.

What is the default encoding of the JVM?

It's going to be locale-dependent. Different locale, different default encoding.

What is the difference between == and equals() in Java?

Also note that .equals() normally contains == for testing as this is the first thing you would wish to test for if you wanted to test if two objects are equal.

And == actually does look at values for primitive types, for objects it checks the reference.

Use -notlike to filter out multiple strings in PowerShell

Easiest way I find for multiple searches is to pipe them all (probably heavier CPU use) but for your example user:

Get-EventLog -LogName Security | where {$_.UserName -notlike "*user1"} |  where {$_.UserName -notlike "*user2"}

How to read all of Inputstream in Server Socket JAVA

You can read your BufferedInputStream like this. It will read data till it reaches end of stream which is indicated by -1.

inputS = new BufferedInputStream(inBS);
byte[] buffer = new byte[1024];    //If you handle larger data use a bigger buffer size
int read;
while((read = inputS.read(buffer)) != -1) {
    System.out.println(read);
    // Your code to handle the data
}

How to convert byte array to string

To convert the byte[] to string[], simply use the below line.

byte[] fileData; // Some byte array
//Convert byte[] to string[]
var table = (Encoding.Default.GetString(
                 fileData, 
                 0, 
                 fileData.Length - 1)).Split(new string[] { "\r\n", "\r", "\n" },
                                             StringSplitOptions.None);

What is the difference between a schema and a table and a database?

In a nutshell, a schema is the definition for the entire database, so it includes tables, views, stored procedures, indexes, primary and foreign keys, etc.

How do I launch a program from command line without opening a new cmd window?

In Windows 7+ the first quotations will be the title to the cmd window to open the program:

start "title" "C:\path\program.exe"

Formatting your command like the above will temporarily open a cmd window that goes away as fast as it comes up so you really never see it. It also allows you to open more than one program without waiting for the first one to close first.

Convert an image to grayscale in HTML/CSS

Following on from brillout.com's answer, and also Roman Nurik's answer, and relaxing somewhat the the 'no SVG' requirement, you can desaturate images in Firefox using only a single SVG file and some CSS.

Your SVG file will look like this:

<?xml version="1.0" encoding="UTF-8"?>
<svg version="1.1"
     baseProfile="full"
     xmlns="http://www.w3.org/2000/svg">
    <filter id="desaturate">
        <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0
                                             0.3333 0.3333 0.3333 0 0
                                             0.3333 0.3333 0.3333 0 0
                                             0      0      0      1 0"/>
    </filter>
</svg>

Save that as resources.svg, it can be reused from now on for any image you want to change to greyscale.

In your CSS you reference the filter using the Firefox specific filter property:

.target {
    filter: url(resources.svg#desaturate);
}

Add the MS proprietary ones too if you feel like it, apply that class to any image you want to convert to greyscale (works in Firefox >3.5, IE8).

edit: Here's a nice blog post which describes using the new CSS3 filter property in SalmanPK's answer in concert with the SVG approach described here. Using that approach you'd end up with something like:

img.desaturate{
    filter: gray; /* IE */
    -webkit-filter: grayscale(1); /* Old WebKit */
    -webkit-filter: grayscale(100%); /* New WebKit */
    filter: url(resources.svg#desaturate); /* older Firefox */
    filter: grayscale(100%); /* Current draft standard */
}

Further browser support info here.

Change output format for MySQL command line results to CSV

I wound up writing my own command-line tool to take care of this. It's similar to cut, except it knows what to do with quoted fields, etc. This tool, paired with @Jimothy's answer, allows me to get a headerless CSV from a remote MySQL server I have no filesystem access to onto my local machine with this command:

$ mysql -N -e "select people, places from things" | csvm -i '\t' -o ','
Bill,"Raleigh, NC"

csvmaster on github

Null or empty check for a string variable

Yes, that code does exactly that.

You can also use:

if (@value is null or @value = '')

Edit:

With the added information that @value is an int value, you need instead:

if (@value is null)

An int value can never contain the value ''.

What is the OR operator in an IF statement

|| is the conditional OR operator in C#

You probably had a hard time finding it because it's difficult to search for something whose name you don't know. Next time try doing a Google search for "C# Operators" and look at the logical operators.

Here is a list of C# operators.

My code is:

if (title == "User greeting" || "User name") {do stuff};

and my error is:

Error 1 Operator '||' cannot be applied to operands of type 'bool' and 'string' C:\Documents and Settings\Sky View Barns\My Documents\Visual Studio 2005\Projects\FOL Ministry\FOL Ministry\Downloader.cs 63 21 FOL Ministry

You need to do this instead:

if (title == "User greeting" || title == "User name") {do stuff};

The OR operator evaluates the expressions on both sides the same way. In your example, you are operating on the expression title == "User greeting" (a bool) and the expression "User name" (a string). These can't be combined directly without a cast or conversion, which is why you're getting the error.

In addition, it is worth noting that the || operator uses "short-circuit evaluation". This means that if the first expression evaluates to true, the second expression is not evaluated because it doesn't have to be - the end result will always be true. Sometimes you can take advantage of this during optimization.

One last quick note - I often write my conditionals with nested parentheses like this:

if ((title == "User greeting") || (title == "User name")) {do stuff};

This way I can control precedence and don't have to worry about the order of operations. It's probably overkill here, but it's especially useful when the logic gets complicated.

Where can I find my Facebook application id and secret key?

I had a hard time finding where it is so here the image depicting it in 2019.  the location of app secret and app id in 2019.

How to prevent text in a table cell from wrapping

I came to this question needing to prevent text wrapping at the hyphen.

This is how I did it:

<td><nobr>Table Text</nobr></td>

Reference:

How to prevent line break at hyphens on all browsers

Laravel - Route::resource vs Route::controller

RESTful Resource controller

A RESTful resource controller sets up some default routes for you and even names them.

Route::resource('users', 'UsersController');

Gives you these named routes:

Verb          Path                        Action  Route Name
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

And you would set up your controller something like this (actions = methods)

class UsersController extends BaseController {

    public function index() {}

    public function show($id) {}

    public function store() {}

}

You can also choose what actions are included or excluded like this:

Route::resource('users', 'UsersController', [
    'only' => ['index', 'show']
]);

Route::resource('monkeys', 'MonkeysController', [
    'except' => ['edit', 'create']
]);

API Resource controller

Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create and edit routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create nor edit methods.

Route::apiResource('users', 'UsersController');

RESTful Resource Controller documentation


Implicit controller

An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.

Route::controller('users', 'UserController');

Would lead you to set up the controller with a sort of RESTful naming scheme:

class UserController extends BaseController {

    public function getIndex()
    {
        // GET request to index
    }

    public function getShow($id)
    {
        // get request to 'users/show/{id}'
    }

    public function postStore()
    {
        // POST request to 'users/store'
    }

}

Implicit Controller documentation


It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes. I typically use RESTful Resource controllers in combination with explicit routes.

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

Here's an easy fix if you don't actually care about rendering the view.

Create a subclass of InternalResourceViewResolver which doesn't check for circular view paths:

public class StandaloneMvcTestViewResolver extends InternalResourceViewResolver {

    public StandaloneMvcTestViewResolver() {
        super();
    }

    @Override
    protected AbstractUrlBasedView buildView(final String viewName) throws Exception {
        final InternalResourceView view = (InternalResourceView) super.buildView(viewName);
        // prevent checking for circular view paths
        view.setPreventDispatchLoop(false);
        return view;
    }
}

Then set up your test with it:

MockMvc mockMvc;

@Before
public void setUp() {
    final MyController controller = new MyController();

    mockMvc =
            MockMvcBuilders.standaloneSetup(controller)
                    .setViewResolvers(new StandaloneMvcTestViewResolver())
                    .build();
}

How to make a 3D scatter plot in Python?

Use the following code it worked for me:

# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]

# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

plt.show()

while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.

Loop through each cell in a range of cells when given a Range object

To make a note on Dick's answer, this is correct, but I would not recommend using a For Each loop. For Each creates a temporary reference to the COM Cell behind the scenes that you do not have access to (that you would need in order to dispose of it).

See the following for more discussion:

How do I properly clean up Excel interop objects?

To illustrate the issue, try the For Each example, close your application, and look at Task Manager. You should see that an instance of Excel is still running (because all objects were not disposed of properly).

A cleaner way to handle this is to query the spreadsheet using ADO:

http://technet.microsoft.com/en-us/library/ee692882.aspx

jQuery Multiple ID selectors

That should work, you may need a space after the commas.

Also, the function you call afterwards must support an array of objects, and not just a singleton object.

ActiveXObject creation error " Automation server can't create object"

Well you can not run code from notepad so that means you are opening up the page from the file system. aka c:/foo/bar/hello.html

When you run the code from the asp.net page, you are running it from localhost. aka http://loalhost:1234/assdf.html

Each of these run in different security zones on IE.

Ignore .classpath and .project from Git

If the .project and .classpath are already committed, then they need to be removed from the index (but not the disk)

git rm --cached .project
git rm --cached .classpath

Then the .gitignore would work (and that file can be added and shared through clones).
For instance, this gitignore.io/api/eclipse file will then work, which does include:

# Eclipse Core      
.project

# JDT-specific (Eclipse Java Development Tools)     
.classpath

Note that you could use a "Template Directory" when cloning (make sure your users have an environment variable $GIT_TEMPLATE_DIR set to a shared folder accessible by all).
That template folder can contain an info/exclude file, with ignore rules that you want enforced for all repos, including the new ones (git init) that any user would use.


As commented by Abdollah

When you change the index, you need to commit the change and push it.
Then the file is removed from the repository. So the newbies cannot checkout the files .classpath and .project from the repo.

Visual Studio opens the default browser instead of Internet Explorer

In Visual Studio 2010 the default browser gets reset often (just about every time an IDE setting is changed or even after restarting Visual Studio). There is now a default browser selector extension for 2010 to help combat this:

!!!Update!!! It appears that the WoVS Default Browser Switcher is no longer available for free according to @Cory. You might try Default Browser Changer instead but I have not tested it. If you already have the WoVS plugin I would recommend backing it up so that you can install it later.

The following solution may no longer work:

WoVS Default Browser Switcher: http://visualstudiogallery.msdn.microsoft.com/en-us/bb424812-f742-41ef-974a-cdac607df921

WoVS Default Browser Switcher

Edit: This works with ASP.NET MVC applications as well.

Note: One negative side effect of installing this extension is that it seems to nag to be updated about once a month. This has caused some to uninstall it because, to them, its more bothersome then the problem it fixes. Regardless it is easily updated through the extension manager and I still find it very useful.

You will see the following error when starting VS:

The Default Browser Switcher beta bits have expired. Please use the Extension Manager or visit the VS Gallery to download updated bits.

Comparing HTTP and FTP for transferring files

One consideration is that FTP can use non-standard ports, which can make getting though firewalls difficult (especially if you're using SSL). HTTP is typically on a known port, so this is rarely a problem.

If you do decide to use FTP, make sure you read about Active and Passive FTP.

In terms of performance, at the end of the day they're both spewing files directly down TCP connections so should be about the same.

if checkbox is checked, do this

I would do :

$('#checkbox').on("change", function (e){ 

    if(this.checked){

      // Do one thing 

    }

    else{

     // Do some other thing

    }

});

See : https://www.w3schools.com/jsref/prop_checkbox_checked.asp

How to get address of a pointer in c/c++?

You can use the %p formatter. It's always best practice cast your pointer void* before printing.

The C standard says:

The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

Here's how you do it:

printf("%p", (void*)p);

Android: alternate layout xml for landscape mode

By default, the layouts in /res/layout are applied to both portrait and landscape.

If you have for example

/res/layout/main.xml

you can add a new folder /res/layout-land, copy main.xml into it and make the needed adjustments.

orientation

See also http://www.androidpeople.com/android-portrait-amp-landscape-differeent-layouts and http://www.devx.com/wireless/Article/40792/1954 for some more options.

What is a daemon thread in Java?

Daemon threads are low-priority threads whose only role is to provide services to user threads.

Daemon threads are generally created by JVM for background tasks while user threads are created by application for foreground tasks.

Since daemon threads are meant to serve user threads and are only needed while user threads are running, they won't prevent the JVM from exiting once all user threads have finished their execution.

We can set non-daemon thread to daemon using :

setDaemon(true)

PowerShell equivalent to grep -f

I'm not familiar with grep but with Select-String you can do:

Get-ChildItem filename.txt | Select-String -Pattern <regexPattern>

You can also do that with Get-Content:

(Get-Content filename.txt) -match 'pattern'

Trusting all certificates with okHttp

SSLSocketFactory does not expose its X509TrustManager, which is a field that OkHttp needs to build a clean certificate chain. This method instead must use reflection to extract the trust manager. Applications should prefer to call sslSocketFactory(SSLSocketFactory, X509TrustManager), which avoids such reflection.

Source: OkHttp documentation

OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.sslSocketFactory(sslContext.getSocketFactory(),
    new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }
    });

MS-access reports - The search key was not found in any record - on save

Following on from @Wilf's answer, I was trying to import a spreadsheet which had spaces in one of the headings, which I eliminated. I checked for leading and trailing spaces, but still had the same problem - until I used Ctrl-Right from the last real heading cell, and found another cell on the first row that looked blank but obviously contained some whitespace. After deleting this, my import works. Thanks for the pointers :)

How to change background color of cell in table using java script

<table border="1" cellspacing="0" cellpadding= "20">
    <tr>
    <td id="id1" ></td>
    </tr>
</table>
<script>
    document.getElementById('id1').style.backgroundColor='#003F87';
</script>

Put id for cell and then change background of the cell.

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

@watson

On windows forms it is available, at the top of the class put

  static void Main(string[] args)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
       //other stuff here
    }

since windows is single threaded, its all you need, in the event its a service you need to put it right above the call to the service (since there is no telling what thread you'll be on).

using System.Security.Principal 

is also needed.

Apache Cordova - uninstall globally

Super late here and I still couldn't uninstall using sudo as the other answers suggest. What did it for me was checking where cordova was installed by running

which cordova

it will output something like this

/usr/local/bin/

then removing by

rm -rf /usr/local/bin/cordova

How to get rows count of internal table in abap?

if I understand your question correctly, you want to know the row number during a conditional loop over an internal table. You can use the system variable sy-tabix if you work with internal tables. Please refer to the ABAP documentation if you need more information (especially the chapter on internal table processing).

Example:

LOOP AT itab INTO workarea
        WHERE tablefield = value.

     WRITE: 'This is row number ', sy-tabix.

ENDLOOP.

How to get selected value from Dropdown list in JavaScript

Hope it's working for you

 function GetSelectedItem()
 {
     var index = document.getElementById(select1).selectedIndex;

     alert("value =" + document.getElementById(select1).value); // show selected value
     alert("text =" + document.getElementById(select1).options[index].text); // show selected text 
 }

How to put a delay on AngularJS instant search?

I think the easiest way here is to preload the json or load it once on$dirty and then the filter search will take care of the rest. This'll save you the extra http calls and its much faster with preloaded data. Memory will hurt, but its worth it.

Warning message: In `...` : invalid factor level, NA generated

The easiest way to fix this is to add a new factor to your column. Use the levels function to determine how many factors you have and then add a new factor.

    > levels(data$Fireplace.Qu)
    [1] "Ex" "Fa" "Gd" "Po" "TA"
    > levels(data$Fireplace.Qu) = c("Ex", "Fa", "Gd", "Po", "TA", "None")
    [1] "Ex"   "Fa"   "Gd"   "Po"   " TA"  "None"