Programs & Examples On #Spanned

Html.fromHtml deprecated in Android N

From official doc :

fromHtml(String) method was deprecated in API level 24. use fromHtml(String, int) instead.

  1. TO_HTML_PARAGRAPH_LINES_CONSECUTIVE Option for toHtml(Spanned, int): Wrap consecutive lines of text delimited by '\n' inside <p> elements.

  2. TO_HTML_PARAGRAPH_LINES_INDIVIDUAL Option for toHtml(Spanned, int): Wrap each line of text delimited by '\n' inside a <p> or a <li> element.

https://developer.android.com/reference/android/text/Html.html

how do you filter pandas dataframes by multiple columns

For more general boolean functions that you would like to use as a filter and that depend on more than one column, you can use:

df = df[df[['col_1','col_2']].apply(lambda x: f(*x), axis=1)]

where f is a function that is applied to every pair of elements (x1, x2) from col_1 and col_2 and returns True or False depending on any condition you want on (x1, x2).

GridLayout and Row/Column Span Woe

Android Support V7 GridLayout library makes excess space distribution easy by accommodating the principle of weight. To make a column stretch, make sure the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity. Remember to add dependency for this library. Add com.android.support:gridlayout-v7:25.0.1 in build.gradle.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:columnCount="2"
app:rowCount="2">

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="First"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Second"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Third"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"        
    app:layout_columnWeight="1"
    app:layout_rowWeight="1"
    android:text="fourth"/>

</android.support.v7.widget.GridLayout>

How to pass a view's onClick event to its parent on Android?

If you want to both OnTouch and OnClick listener to parent and child view both, please use below trick:

  1. User ScrollView as a Parent view and inside that placed your child view inside Relative/LinearLayout.

  2. Make Parent ScrollView android:fillViewport="true" so View not be scrolled.

  3. Then set OnTouch listener to parent and OnClick listener to Child views. And enjoy both listener callbacks.

Why do we have to specify FromBody and FromUri?

The default behavior is:

  1. If the parameter is a primitive type (int, bool, double, ...), Web API tries to get the value from the URI of the HTTP request.

  2. For complex types (your own object, for example: Person), Web API tries to read the value from the body of the HTTP request.

So, if you have:

  • a primitive type in the URI, or
  • a complex type in the body

...then you don't have to add any attributes (neither [FromBody] nor [FromUri]).

But, if you have a primitive type in the body, then you have to add [FromBody] in front of your primitive type parameter in your WebAPI controller method. (Because, by default, WebAPI is looking for primitive types in the URI of the HTTP request.)

Or, if you have a complex type in your URI, then you must add [FromUri]. (Because, by default, WebAPI is looking for complex types in the body of the HTTP request by default.)

Primitive types:

public class UsersController : ApiController
{
    // api/users
    public HttpResponseMessage Post([FromBody]int id)
    {

    }
    // api/users/id
    public HttpResponseMessage Post(int id)
    {

    }       
}

Complex types:

public class UsersController : ApiController
{       
    // api/users
    public HttpResponseMessage Post(User user)
    {

    }

    // api/users/user
    public HttpResponseMessage Post([FromUri]User user)
    {

    }       
}

This works as long as you send only one parameter in your HTTP request. When sending multiple, you need to create a custom model which has all your parameters like this:

public class MyModel
{
    public string MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
    // model.MyProperty;
    // model.MyProperty2;
}

From Microsoft's documentation for parameter binding in ASP.NET Web API:

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.

This should work:

public HttpResponseMessage Post([FromBody] string name) { ... }

This will not work:

// Caution: This won't work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

Redirecting to a new page after successful login

You need to set the location header as follows:

header('Location: http://www.example.com/');

Replacing http://www.example.com of course with the url of your landing page.

Add this where you have finished logging the user in.

Note: When redirecting the user will be immediately redirected so you're message probably won't display.

Additionally, you need to move your PHP code to the top of the file for this solution to work.

On another side note, please see my comment above regarding the use of the deprecated mysql statements and consider using the newer, safer and improved mysqli or PDO statements.

Find object by id in an array of JavaScript objects

As others have pointed out, .find() is the way to go when looking for one object within your array. However, if your object cannot be found using this method, your program will crash:

_x000D_
_x000D_
const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];_x000D_
const res = myArray.find(x => x.id === '100').foo; // Uh oh!_x000D_
/*_x000D_
Error:_x000D_
"Uncaught TypeError: Cannot read property 'foo' of undefined"_x000D_
*/
_x000D_
_x000D_
_x000D_

This can be fixed by checking whether the result of .find() is defined before using using .foo on it. Modern JS allows us to do this easily with optional chaining, returning undefined if the object cannot be found, rather than crashing your code:

_x000D_
_x000D_
const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];_x000D_
const res = myArray.find(x => x.id === '100')?.foo; // No error!_x000D_
console.log(res); // undefined when the object cannot be found
_x000D_
_x000D_
_x000D_

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained by @Nitzan Tomer. But also you can just define property as any, if you want to write code almost as in JavaScript:

arr.filter((item:any) => {
    return item.isSelected == true;
}

Generate random numbers with a given (numerical) distribution

None of these answers is particularly clear or simple.

Here is a clear, simple method that is guaranteed to work.

accumulate_normalize_probabilities takes a dictionary p that maps symbols to probabilities OR frequencies. It outputs usable list of tuples from which to do selection.

def accumulate_normalize_values(p):
        pi = p.items() if isinstance(p,dict) else p
        accum_pi = []
        accum = 0
        for i in pi:
                accum_pi.append((i[0],i[1]+accum))
                accum += i[1]
        if accum == 0:
                raise Exception( "You are about to explode the universe. Continue ? Y/N " )
        normed_a = []
        for a in accum_pi:
                normed_a.append((a[0],a[1]*1.0/accum))
        return normed_a

Yields:

>>> accumulate_normalize_values( { 'a': 100, 'b' : 300, 'c' : 400, 'd' : 200  } )
[('a', 0.1), ('c', 0.5), ('b', 0.8), ('d', 1.0)]

Why it works

The accumulation step turns each symbol into an interval between itself and the previous symbols probability or frequency (or 0 in the case of the first symbol). These intervals can be used to select from (and thus sample the provided distribution) by simply stepping through the list until the random number in interval 0.0 -> 1.0 (prepared earlier) is less or equal to the current symbol's interval end-point.

The normalization releases us from the need to make sure everything sums to some value. After normalization the "vector" of probabilities sums to 1.0.

The rest of the code for selection and generating a arbitrarily long sample from the distribution is below :

def select(symbol_intervals,random):
        print symbol_intervals,random
        i = 0
        while random > symbol_intervals[i][1]:
                i += 1
                if i >= len(symbol_intervals):
                        raise Exception( "What did you DO to that poor list?" )
        return symbol_intervals[i][0]


def gen_random(alphabet,length,probabilities=None):
        from random import random
        from itertools import repeat
        if probabilities is None:
                probabilities = dict(zip(alphabet,repeat(1.0)))
        elif len(probabilities) > 0 and isinstance(probabilities[0],(int,long,float)):
                probabilities = dict(zip(alphabet,probabilities)) #ordered
        usable_probabilities = accumulate_normalize_values(probabilities)
        gen = []
        while len(gen) < length:
                gen.append(select(usable_probabilities,random()))
        return gen

Usage :

>>> gen_random (['a','b','c','d'],10,[100,300,400,200])
['d', 'b', 'b', 'a', 'c', 'c', 'b', 'c', 'c', 'c']   #<--- some of the time

Creating a list of pairs in java

Sounds like you need to create your own pair class (see discussion here). Then make a List of that pair class you created

How to use glyphicons in bootstrap 3.0

Bootstrap 3 requires span tag not i

<span class="glyphicon glyphicon-search"></span>`

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I'm answering because I don't see this particular solution listed by anyone else.

Apparently my antivirus (Ad-Aware) was flagging a DLL one of my projects depends on, and deleting it. Even after excluding the directory where the DLL lives, the same behaviour continued until I restarted my computer.

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

simply "CUT" project folder and move it out of workspace directory and do the following

file=>import=>(select new directory)=> mark (copy to my workspace) checkbox 

and you done !

Binding a generic list to a repeater - ASP.NET

Code Behind:

public class Friends
{
    public string   ID      { get; set; }
    public string   Name    { get; set; }
    public string   Image   { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
        List <Friends> friendsList = new List<Friends>();

        foreach (var friend  in friendz)
        {
            friendsList.Add(
                new Friends { ID = friend.id, Name = friend.name }    
            );

        }

        this.rptFriends.DataSource = friendsList;
        this.rptFriends.DataBind();
}

.aspx Page

<asp:Repeater ID="rptFriends" runat="server">
            <HeaderTemplate>
                <table border="0" cellpadding="0" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
            </HeaderTemplate>
            <ItemTemplate>
                    <tr>
                        <td><%# Eval("ID") %></td>
                        <td><%# Eval("Name") %></td>
                    </tr>
            </ItemTemplate>
            <FooterTemplate>
                    </tbody>
                </table>
            </FooterTemplate>
        </asp:Repeater>

Could not find server 'server name' in sys.servers. SQL Server 2014

At first check out that your linked server is in the list by this query

select name from sys.servers

If it not exists then try to add to the linked server

EXEC sp_addlinkedserver @server = 'SERVER_NAME' --or may be server ip address

After that login to that linked server by

EXEC sp_addlinkedsrvlogin 'SERVER_NAME'
                         ,'false'
                         ,NULL
                         ,'USER_NAME'
                         ,'PASSWORD'

Then you can do whatever you want ,treat it like your local server

exec [SERVER_NAME].[DATABASE_NAME].dbo.SP_NAME @sample_parameter

Finally you can drop that server from linked server list by

sp_dropserver 'SERVER_NAME', 'droplogins'

If it will help you then please upvote.

Check the current number of connections to MongoDb

Connect to MongoDB using mongo-shell and run following command.

db.serverStatus().connections

e.g:

mongo> db.serverStatus().connections
{ "current" : 3, "available" : 816, "totalCreated" : NumberLong(1270) }

Avoid printStackTrace(); use a logger call instead

A production quality program should use one of the many logging alternatives (e.g. log4j, logback, java.util.logging) to report errors and other diagnostics. This has a number of advantages:

  • Log messages go to a configurable location.
  • The end user doesn't see the messages unless you configure the logging so that he/she does.
  • You can use different loggers and logging levels, etc to control how much little or much logging is recorded.
  • You can use different appender formats to control what the logging looks like.
  • You can easily plug the logging output into a larger monitoring / logging framework.
  • All of the above can be done without changing your code; i.e. by editing the deployed application's logging config file.

By contrast, if you just use printStackTrace, the deployer / end user has little if any control, and logging messages are liable to either be lost or shown to the end user in inappropriate circumstances. (And nothing terrifies a timid user more than a random stack trace.)

Row count with PDO

when you make a COUNT(*) in your mysql statement like in

$q = $db->query("SELECT COUNT(*) FROM ...");

your mysql query is already counting the number of result why counting again in php? to get the result of your mysql

$q = $db->query("SELECT COUNT(*) as counted FROM ...");
$nb = $q->fetch(PDO::FETCH_OBJ);
$nb = $nb->counted;

and $nb will contain the integer you have counted with your mysql statement a bit long to write but fast to execute

Edit: sorry for the wrong post but as some example show query with count in, I was suggesting using the mysql result, but if you don't use the count in sql fetchAll() is efficient, if you save the result in a variable you won't loose a line.

$data = $dbh->query("SELECT * FROM ...");
$table = $data->fetchAll(PDO::FETCH_OBJ);

count($table) will return the number of row and you can still use the result after like $row = $table[0] or using a foreach

foreach($table as $row){
  print $row->id;
}

VBA paste range

To literally fix your example you would use this:

Sub Normalize()


    Dim Ticker As Range
    Sheets("Sheet1").Activate
    Set Ticker = Range(Cells(2, 1), Cells(65, 1))
    Ticker.Copy

    Sheets("Sheet2").Select
    Cells(1, 1).PasteSpecial xlPasteAll



End Sub

To Make slight improvments on it would be to get rid of the Select and Activates:

Sub Normalize()
    With Sheets("Sheet1")
        .Range(.Cells(2, 1), .Cells(65, 1)).Copy Sheets("Sheet2").Cells(1, 1)
    End With
End Sub

but using the clipboard takes time and resources so the best way would be to avoid a copy and paste and just set the values equal to what you want.

Sub Normalize()
Dim CopyFrom As Range

Set CopyFrom = Sheets("Sheet1").Range("A2", [A65])
Sheets("Sheet2").Range("A1").Resize(CopyFrom.Rows.Count).Value = CopyFrom.Value

End Sub

To define the CopyFrom you can use anything you want to define the range, You could use Range("A2:A65"), Range("A2",[A65]), Range("A2", "A65") all would be valid entries. also if the A2:A65 Will never change the code could be further simplified to:

Sub Normalize()

Sheets("Sheet2").Range("A1:A65").Value = Sheets("Sheet1").Range("A2:A66").Value

End Sub

I added the Copy from range, and the Resize property to make it slightly more dynamic in case you had other ranges you wanted to use in the future.

What's the scope of a variable initialized in an if statement?

And note that since Python types are only checked at runtime you can have code like:

if True:
    x = 2
    y = 4
else:
    x = "One"
    y = "Two"
print(x + y)

But I'm having trouble thinking of other ways in which the code would operate without an error because of type issues.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

When you use recv in connection with select if the socket is ready to be read from but there is no data to read that means the client has closed the connection.

Here is some code that handles this, also note the exception that is thrown when recv is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :

def listenToSockets(self):

    while True:

        changed_sockets = self.currentSockets

        ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)

        for s in ready_to_read:

            if s == self.serverSocket:
                self.acceptNewConnection(s)
            else:
                self.readDataFromSocket(s)

And the function that receives the data :

def readDataFromSocket(self, socket):

    data = ''
    buffer = ''
    try:

        while True:
            data = socket.recv(4096)

            if not data: 
                break

            buffer += data

    except error, (errorCode,message): 
        # error 10035 is no data available, it is non-fatal
        if errorCode != 10035:
            print 'socket.error - ('+str(errorCode)+') ' + message


    if data:
        print 'received '+ buffer
    else:
        print 'disconnected'

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

In short, to ensure proper unicode handling in Python 2:

  • use io.open for reading/writing files
  • use from __future__ import unicode_literals
  • configure other data inputs/outputs (e.g., databases, network) to use unicode
  • if you cannot configure outputs to utf-8, convert your output for them print(text.encode('ascii', 'replace').decode())

For explanations, see @Alastair McCormack's detailed answer.

How do you set your pythonpath in an already-created virtualenv?

I modified my activate script to source the file .virtualenvrc, if it exists in the current directory, and to save/restore PYTHONPATH on activate/deactivate.

You can find the patched activate script here.. It's a drop-in replacement for the activate script created by virtualenv 1.11.6.

Then I added something like this to my .virtualenvrc:

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/some/library/path"

Postgresql GROUP_CONCAT equivalent?

This is probably a good starting point (version 8.4+ only):

SELECT id_field, array_agg(value_field1), array_agg(value_field2)
FROM data_table
GROUP BY id_field

array_agg returns an array, but you can CAST that to text and edit as needed (see clarifications, below).

Prior to version 8.4, you have to define it yourself prior to use:

CREATE AGGREGATE array_agg (anyelement)
(
    sfunc = array_append,
    stype = anyarray,
    initcond = '{}'
);

(paraphrased from the PostgreSQL documentation)

Clarifications:

  • The result of casting an array to text is that the resulting string starts and ends with curly braces. Those braces need to be removed by some method, if they are not desired.
  • Casting ANYARRAY to TEXT best simulates CSV output as elements that contain embedded commas are double-quoted in the output in standard CSV style. Neither array_to_string() or string_agg() (the "group_concat" function added in 9.1) quote strings with embedded commas, resulting in an incorrect number of elements in the resulting list.
  • The new 9.1 string_agg() function does NOT cast the inner results to TEXT first. So "string_agg(value_field)" would generate an error if value_field is an integer. "string_agg(value_field::text)" would be required. The array_agg() method requires only one cast after the aggregation (rather than a cast per value).

What is the difference between a generative and a discriminative algorithm?

In practice, the models are used as follows.

In discriminative models, to predict the label y from the training example x, you must evaluate:

enter image description here

which merely chooses what is the most likely class y considering x. It's like we were trying to model the decision boundary between the classes. This behavior is very clear in neural networks, where the computed weights can be seen as a complexly shaped curve isolating the elements of a class in the space.

Now, using Bayes' rule, let's replace the enter image description here in the equation by enter image description here. Since you are just interested in the arg max, you can wipe out the denominator, that will be the same for every y. So, you are left with

enter image description here

which is the equation you use in generative models.

While in the first case you had the conditional probability distribution p(y|x), which modeled the boundary between classes, in the second you had the joint probability distribution p(x, y), since p(x | y) p(y) = p(x, y), which explicitly models the actual distribution of each class.

With the joint probability distribution function, given a y, you can calculate ("generate") its respective x. For this reason, they are called "generative" models.

Hibernate Criteria for Dates

By using this way you can get the list of selected records.

GregorianCalendar gregorianCalendar = new GregorianCalendar();
Criteria cri = session.createCriteria(ProjectActivities.class);
cri.add(Restrictions.ge("EffectiveFrom", gregorianCalendar.getTime()));
List list = cri.list();

All the Records will be generated into list which are greater than or equal to '08-Oct-2012' or else pass the date of user acceptance date at 2nd parameter of Restrictions (gregorianCalendar.getTime()) of criteria to get the records.

Creating a list of dictionaries results in a list of copies of the same dictionary

You have misunderstood the Python list object. It is similar to a C pointer-array. It does not actually "copy" the object which you append to it. Instead, it just store a "pointer" to that object.

Try the following code:

>>> d={}
>>> dlist=[]
>>> for i in xrange(0,3):
    d['data']=i
    dlist.append(d)
    print(d)

{'data': 0}
{'data': 1}
{'data': 2}
>>> print(dlist)
[{'data': 2}, {'data': 2}, {'data': 2}]

So why is print(dlist) not the same as print(d)?

The following code shows you the reason:

>>> for i in dlist:
    print "the list item point to object:", id(i)

the list item point to object: 47472232
the list item point to object: 47472232
the list item point to object: 47472232

So you can see all the items in the dlist is actually pointing to the same dict object.

The real answer to this question will be to append the "copy" of the target item, by using d.copy().

>>> dlist=[]
>>> for i in xrange(0,3):
    d['data']=i
    dlist.append(d.copy())
    print(d)

{'data': 0}
{'data': 1}
{'data': 2}
>>> print dlist
[{'data': 0}, {'data': 1}, {'data': 2}]

Try the id() trick, you can see the list items actually point to completely different objects.

>>> for i in dlist:
    print "the list item points to object:", id(i)

the list item points to object: 33861576
the list item points to object: 47472520
the list item points to object: 47458120

How can I clear the content of a file?

Try using something like

File.Create

Creates or overwrites a file in the specified path.

PHP convert string to hex and hex to string

For people that end up here and are just looking for the hex representation of a (binary) string.

bin2hex("that's all you need");
# 74686174277320616c6c20796f75206e656564

hex2bin('74686174277320616c6c20796f75206e656564');
# that's all you need

Doc: bin2hex, hex2bin.

Finding duplicate values in a SQL table

This selects/deletes all duplicate records except one record from each group of duplicates. So, the delete leaves all unique records + one record from each group of the duplicates.

Select duplicates:

SELECT *
FROM table
WHERE
    id NOT IN (
        SELECT MIN(id)
        FROM table
        GROUP BY column1, column2
);

Delete duplicates:

DELETE FROM table
WHERE
    id NOT IN (
        SELECT MIN(id)
        FROM table
        GROUP BY column1, column2
);

Be aware of larger amounts of records, it can cause performance problems.

Utilizing multi core for tar+gzip/bzip compression/decompression

If you want to have more flexibility with filenames and compression options, you can use:

find /my/path/ -type f -name "*.sql" -o -name "*.log" -exec \
tar -P --transform='s@/my/path/@@g' -cf - {} + | \
pigz -9 -p 4 > myarchive.tar.gz

Step 1: find

find /my/path/ -type f -name "*.sql" -o -name "*.log" -exec

This command will look for the files you want to archive, in this case /my/path/*.sql and /my/path/*.log. Add as many -o -name "pattern" as you want.

-exec will execute the next command using the results of find: tar

Step 2: tar

tar -P --transform='s@/my/path/@@g' -cf - {} +

--transform is a simple string replacement parameter. It will strip the path of the files from the archive so the tarball's root becomes the current directory when extracting. Note that you can't use -C option to change directory as you'll lose benefits of find: all files of the directory would be included.

-P tells tar to use absolute paths, so it doesn't trigger the warning "Removing leading `/' from member names". Leading '/' with be removed by --transform anyway.

-cf - tells tar to use the tarball name we'll specify later

{} + uses everyfiles that find found previously

Step 3: pigz

pigz -9 -p 4

Use as many parameters as you want. In this case -9 is the compression level and -p 4 is the number of cores dedicated to compression. If you run this on a heavy loaded webserver, you probably don't want to use all available cores.

Step 4: archive name

> myarchive.tar.gz

Finally.

JAX-RS — How to return JSON and HTTP status code together?

If your WS-RS needs raise an error why not just use the WebApplicationException?

@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Path("{id}")
public MyEntity getFoo(@PathParam("id") long id,  @QueryParam("lang")long idLanguage) {

if (idLanguage== 0){
    // No URL parameter idLanguage was sent
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.entity("Missing idLanguage parameter on request");
    Response response = builder.build();
    throw new WebApplicationException(response);
    }
... //other stuff to return my entity
return myEntity;
}

fatal error: Python.h: No such file or directory

For the OpenSuse comrades out there:

sudo zypper install python3-devel

center aligning a fixed position div

if you don't want to use the wrapper method. then you can do this:

.fixed_center_div {
  position: fixed;
  width: 200px;
  height: 200px;
  left: 50%;
  top: 50%;
  margin-left: -100px; /* 50% of width */
  margin-top: -100px; /* 50% of height */
}

Running a cron every 30 seconds

Have a look at frequent-cron - it's old but very stable and you can step down to micro-seconds. At this point in time, the only thing that I would say against it is that I'm still trying to work out how to install it outside of init.d but as a native systemd service, but certainly up to Ubuntu 18 it's running just fine still using init.d (distance may vary on latter versions). It has the added advantage (?) of ensuring that it won't spawn another instance of the PHP script unless a prior one has completed, which reduces potential memory leakage issues.

Select from multiple tables without a join?

Union will fetch data by row not column,So If your are like me who is looking for fetching column data from two different table with no relation and without join.
In my case I am fetching state name and country name by id. Instead of writing two query you can do this way.

select 
   (
   select s.state_name from state s where s.state_id=3
   ) statename,
   (
   select c.description from country c where c.id=5
   ) countryname
   from dual;   

where dual is a dummy table with single column--anything just require table to view

Windows 7: unable to register DLL - Error Code:0X80004005

Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.

C:\Windows\SysWOW64>regsvr32 "c:\dll.name" 

Make Frequency Histogram for Factor Variables

Data as factor can be used as input to the plot function.

An answer to a similar question has been given here: https://stat.ethz.ch/pipermail/r-help/2010-December/261873.html

 x=sample(c("Richard", "Minnie", "Albert", "Helen", "Joe", "Kingston"),  
 50, replace=T)
 x=as.factor(x)
 plot(x)

How do I get textual contents from BLOB in Oracle SQL

You can try this:

SELECT TO_CHAR(dbms_lob.substr(BLOB_FIELD, 3900)) FROM TABLE_WITH_BLOB;

However, It would be limited to 4000 byte

Most Useful Attributes

// on configuration sections
[ConfigurationProperty] 

// in asp.net
[NotifyParentProperty(true)]

How can I send and receive WebSocket messages on the server side?

PHP Implementation:

function encode($message)
{
    $length = strlen($message);

    $bytesHeader = [];
    $bytesHeader[0] = 129; // 0x1 text frame (FIN + opcode)

    if ($length <= 125) {
            $bytesHeader[1] = $length;
    } else if ($length >= 126 && $length <= 65535) {
            $bytesHeader[1] = 126;
            $bytesHeader[2] = ( $length >> 8 ) & 255;
            $bytesHeader[3] = ( $length      ) & 255;
    } else {
            $bytesHeader[1] = 127;
            $bytesHeader[2] = ( $length >> 56 ) & 255;
            $bytesHeader[3] = ( $length >> 48 ) & 255;
            $bytesHeader[4] = ( $length >> 40 ) & 255;
            $bytesHeader[5] = ( $length >> 32 ) & 255;
            $bytesHeader[6] = ( $length >> 24 ) & 255;
            $bytesHeader[7] = ( $length >> 16 ) & 255;
            $bytesHeader[8] = ( $length >>  8 ) & 255;
            $bytesHeader[9] = ( $length       ) & 255;
    }

    $str = implode(array_map("chr", $bytesHeader)) . $message;

    return $str;
}

Delete keychain items when an app is uninstalled

For those looking for a Swift version of @amro's answer:

    let userDefaults = NSUserDefaults.standardUserDefaults()

    if userDefaults.boolForKey("hasRunBefore") == false {

        // remove keychain items here


        // update the flag indicator
        userDefaults.setBool(true, forKey: "hasRunBefore")
        userDefaults.synchronize() // forces the app to update the NSUserDefaults

        return
    }

How to transfer some data to another Fragment?

getArguments() is returning null because "Its doesn't get anything"

Try this code to handle this situation

if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}

What is the &#xA; character?

This is the ASCII format.

Please consider that:

Some data (like URLs) can be sent over the Internet using the ASCII character-set. Since data often contain characters outside the ASCII set, so it has to be converted into a valid ASCII format.

To find it yourself, you can visit https://en.wikipedia.org/wiki/ASCII, there you can find big tables of characters. The one you are looking is in Control Characters table.

Digging to table you can find

Oct Dec Hex Name 012 10 0A Line Feed

In the html file you can use Dec and Hex representation of charters

The Dec is represented with &#10;

The Hex is represented with &#x0A (or you can omit the leading zero &#xA)

There is a good converter at https://r12a.github.io/apps/conversion/ .

How to add a boolean datatype column to an existing table in sql?

The answer given by P????? creates a nullable bool, not a bool, which may be fine for you. For example in C# it would create: bool? AdminApprovednot bool AdminApproved.

If you need to create a bool (defaulting to false):

    ALTER TABLE person
    ADD AdminApproved BIT
    DEFAULT 0 NOT NULL;

Altering a column to be nullable

For HSQLDB:

ALTER TABLE tableName ALTER COLUMN columnName SET NULL;

Changing background color of selected item in recyclerview

I made this implementation in kotlin I thing is not very efficient but works ivIsSelected is a ImageView that represent in my case a check mark

var selectedItems = mutableListOf<Int>(-1)

override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
    // holder.setData(ContactViewModel, position)  // I'm passing this to the ViewHolder
    holder.itemView.setBackgroundColor(Color.WHITE)   
    holder.itemView.ivIsSelected.visibility = INVISIBLE
    selectedItems.forEach {
        if (it == position) {
            holder.itemView.setBackgroundColor(Color.argb(45, 0, 255, 43))
            holder.itemView.ivIsSelected.visibility = VISIBLE
        }
    }

    holder.itemView.setOnClickListener { it ->
        it.setBackgroundColor(Color.BLUE)  
        selectedItems.add(position)
        selectedItems.forEach { selectedItem ->  // this forEach is required to refresh all the list
            notifyItemChanged(selectedItem)
        }

    }
}

javascript set cookie with expire time

I've set the time to 1000*36000.

function display() { 
  var now = new Date();
  var time = now.getTime();
  var expireTime = time + 1000*36000;
  now.setTime(expireTime);
  document.cookie = 'cookie=ok;expires='+now.toUTCString()+';path=/';
  //console.log(document.cookie);  // 'Wed, 31 Oct 2012 08:50:17 UTC'
}

expiration

Unable to create Genymotion Virtual Device

I solved this problem on windows setting up sdk path in configuration option.

how to use python2.7 pip instead of default pip

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

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

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

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

Passing Javascript variable to <a href >

JAVASCRIPT CODE:

<script>

    function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

var user = getUrlVars()["user"];
var pass = getUrlVars()["pass"];
var sub  = getUrlVars()["sub"];
</script>

<script>
    var myApp = angular.module('myApp',[]);

myApp.controller('dropdownCtrl', ['$scope','$window','$http', function($scope, $window, $http) {

 $http.get('http://dummy.com/app/chapter.php?user='+user+'&pass='+pass)

     .then(function (response) {$scope.names = response.data.admin;});
    $scope.names = [];

        $http.get('http://dummy.com/app/chapter.php?user='+user+'&pass='+pass+'&sub='+sub)

            .then(function (response) {$scope.chapter = response.data.chp;});
           $scope.chapter = [];

};


}]);
    </script>

HTML:

<div ng-controller="dropdownCtrl">
<div ng-repeat="a in chapter">
<a href="topic.html?ch={{a.chapter}}" onClick="location.href=this.href+'&user='+user+'&pass='+pass+'&sub='+sub;return false;">{{a.chapter}}</a>
</div>

Android - Dynamically Add Views into View

Use the LayoutInflater to create a view based on your layout template, and then inject it into the view where you need it.

LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);

// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");

// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

You may have to adjust the index where you want to insert the view.

Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT, or MATCH_PARENT, etc.

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

If you want to have projects choice list when you open Git Bash:

  • Edit ppath in the code header to your Git projects path, put this code into .bashrc file, and copy it into your $HOME directory (in Windows Vista / Windows 7 it is often C:\Users\$YOU)

.

#!/bin/bash
ppath="/d/-projects/-github"
cd $ppath
unset PROJECTS
PROJECTS+=(".")
i=0

echo
echo -e "projects:\n-------------"

for f in *
do
    if [ -d "$f" ]
    then
        PROJECTS+=("$f")
        echo -e $((++i)) "- \e[1m$f\e[0m"
    fi
done


if [ ${#PROJECTS[@]} -gt 1 ]
then
    echo -ne "\nchoose project: "
    read proj
    case "$proj" in
        [0-`expr ${#PROJECTS[@]} - 1`]) cd "${PROJECTS[proj]}" ;;
        *) echo " wrong choice" ;;
    esac
else
    echo "there is no projects"
fi
unset PROJECTS
  • You may want set this file as executable inside Git Bash, chmod +x .bashrc (but it's probably redundant, since this file is stored on an NTFS filesystem)

Populate one dropdown based on selection in another

Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.

Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.

var data = [ // The data
    ['ten', [
        'eleven','twelve'
    ]],
    ['twenty', [
        'twentyone', 'twentytwo'
    ]]
];

$a = $('#a'); // The dropdowns
$b = $('#b');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       attr("value",first).
       data("sel", i).
       text(first));
}

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][1]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           attr("value",second[j]).
           data("sel", j).
           text(second[j]));
    }
}).change(); // Trigger once to add options at load of first choice

SQL select * from column where year = 2010

its just simple

  select * from myTable where year(columnX) = 2010

Open soft keyboard programmatically

InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

How do I get only directories using Get-ChildItem?

The accepted answer mentions

Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | Select-Object FullName

to get a "raw string". But in fact objects of type Selected.System.IO.DirectoryInfo will be returned. For raw strings the following can be used:

Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | % { $_.FullName }

The difference matters if the value is concatenated to a string:

  • with Select-Object suprisingly foo\@{FullName=bar}
  • with the ForEach-operator the expected: foo\bar

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

This will maybe give you a hint on what went wrong.

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        BigDecimal bdTest = new BigDecimal(0.745);
        BigDecimal bdTest1 = new BigDecimal("0.745");
        bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
        bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("bdTest:" + bdTest); // prints "bdTest:0.74"
        System.out.println("bdTest1:" + bdTest1); // prints "bdTest:0.75"
    }
}

The problem is, that your input (a double x=0.745;) can not represent 0.745 exactly. It actually saves a value slightly lower. For BigDecimals, this is already below 0.745, so it rounds down...

Try not to use the BigDecimal(double/float) constructors.

CSS Equivalent of the "if" statement

The only conditions available in CSS are selectors and @media. Some browsers support some of the CSS 3 selectors and media queries.

You can modify an element with JavaScript to change if it matches a selector or not (e.g. by adding a new class).

Convert string to binary then back again using PHP

Why you are using PHP for the conversion. Now, there are so many front end languages available, Why you are still including a server? You can convert the password into the binary number in the front-end and send the converted string in the Database. According to my point of view, this would be convenient.

var bintext, textresult="", binlength;
    this.aaa = this.text_value;
    bintext = this.aaa.replace(/[^01]/g, "");
        binlength = bintext.length-(bintext.length%8);
        for(var z=0; z<binlength; z=z+8) {
            textresult += String.fromCharCode(parseInt(bintext.substr(z,8),2));
                            this.ans = textresult;

This is a Javascript code which I have found here: http://binarytotext.net/, they have used this code with Vue.js. In the code, this.aaa is the v-model dynamic value. To convert the binary into the text values, they have used big numbers. You need to install an additional package and convert it back into the text field. In my point of view, it would be easy.

Trying Gradle build - "Task 'build' not found in root project"

Check your file: settings.gradle for presence lines with included subprojects (for example: include chapter1-bookstore )

How to use group by with union in t-sql

GROUP BY 1

I've never known GROUP BY to support using ordinals, only ORDER BY. Either way, only MySQL supports GROUP BY's not including all columns without aggregate functions performed on them. Ordinals aren't recommended practice either because if they're based on the order of the SELECT - if that changes, so does your ORDER BY (or GROUP BY if supported).

There's no need to run GROUP BY on the contents when you're using UNION - UNION ensures that duplicates are removed; UNION ALL is faster because it doesn't - and in that case you would need the GROUP BY...

Your query only needs to be:

SELECT a.id,
       a.time
  FROM dbo.TABLE_A a
UNION
SELECT b.id,
       b.time
  FROM dbo.TABLE_B b

Why is enum class preferred over plain enum?

Because, as said in other answers, class enum are not implicitly convertible to int/bool, it also helps to avoid buggy code like:

enum MyEnum {
  Value1,
  Value2,
};
...
if (var == Value1 || Value2) // Should be "var == Value2" no error/warning

How do I hide anchor text without hiding the anchor?

a { text-indent:-9999px; }

Tends to work well from my exprience.

What’s the best way to get an HTTP response code from a URL?

Here's an httplib solution that behaves like urllib2. You can just give it a URL and it just works. No need to mess about splitting up your URLs into hostname and path. This function already does that.

import httplib
import socket
def get_link_status(url):
  """
    Gets the HTTP status of the url or returns an error associated with it.  Always returns a string.
  """
  https=False
  url=re.sub(r'(.*)#.*$',r'\1',url)
  url=url.split('/',3)
  if len(url) > 3:
    path='/'+url[3]
  else:
    path='/'
  if url[0] == 'http:':
    port=80
  elif url[0] == 'https:':
    port=443
    https=True
  if ':' in url[2]:
    host=url[2].split(':')[0]
    port=url[2].split(':')[1]
  else:
    host=url[2]
  try:
    headers={'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0',
             'Host':host
             }
    if https:
      conn=httplib.HTTPSConnection(host=host,port=port,timeout=10)
    else:
      conn=httplib.HTTPConnection(host=host,port=port,timeout=10)
    conn.request(method="HEAD",url=path,headers=headers)
    response=str(conn.getresponse().status)
    conn.close()
  except socket.gaierror,e:
    response="Socket Error (%d): %s" % (e[0],e[1])
  except StandardError,e:
    if hasattr(e,'getcode') and len(e.getcode()) > 0:
      response=str(e.getcode())
    if hasattr(e, 'message') and len(e.message) > 0:
      response=str(e.message)
    elif hasattr(e, 'msg') and len(e.msg) > 0:
      response=str(e.msg)
    elif type('') == type(e):
      response=e
    else:
      response="Exception occurred without a good error message.  Manually check the URL to see the status.  If it is believed this URL is 100% good then file a issue for a potential bug."
  return response

How to center a navigation bar with CSS or HTML?

You could also use float and inline-block to center your nav like the following:

nav li {
   float: left;
}
nav {
   display: inline-block;
}

How can I detect whether an iframe is loaded?

You can try onload event as well;

var createIframe = function (src) {
        var self = this;
        $('<iframe>', {
            src: src,
            id: 'iframeId',
            frameborder: 1,
            scrolling: 'no',
            onload: function () {
                self.isIframeLoaded = true;
                console.log('loaded!');
            }
        }).appendTo('#iframeContainer');

    };

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

Can I scroll a ScrollView programmatically in Android?

There are a lot of good answers here, but I only want to add one thing. It sometimes happens that you want to scroll your ScrollView to a specific view of the layout, instead of a full scroll to the top or the bottom.

A simple example: in a registration form, if the user tap the "Signup" button when a edit text of the form is not filled, you want to scroll to that specific edit text to tell the user that he must fill that field.

In that case, you can do something like that:

scrollView.post(new Runnable() { 
        public void run() { 
             scrollView.scrollTo(0, editText.getBottom());
        } 
});

or, if you want a smooth scroll instead of an instant scroll:

scrollView.post(new Runnable() { 
            public void run() { 
                 scrollView.smoothScrollTo(0, editText.getBottom());
            } 
    });

Obviously you can use any type of view instead of Edit Text. Note that getBottom() returns the coordinates of the view based on its parent layout, so all the views used inside the ScrollView should have only a parent (for example a Linear Layout).

If you have multiple parents inside the child of the ScrollView, the only solution i've found is to call requestChildFocus on the parent view:

editText.getParent().requestChildFocus(editText, editText);

but in this case you cannot have a smooth scroll.

I hope this answer can help someone with the same problem.

Add timer to a Windows Forms application

Something like this in your form main. Double click the form in the visual editor to create the form load event.

 Timer Clock=new Timer();
 Clock.Interval=2700000; // not sure if this length of time will work 
 Clock.Start();
 Clock.Tick+=new EventHandler(Timer_Tick);

Then add an event handler to do something when the timer fires.

  public void Timer_Tick(object sender,EventArgs eArgs)
  {
    if(sender==Clock)
    {
      // do something here      
    }
  }

jQuery's .on() method combined with the submit event

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;
 })

How to get child element by index in Jquery?

There are the following way to select first child

1) $('.second div:first-child')
2) $('.second *:first-child')
3) $('div:first-child', '.second')
4) $('*:first-child', '.second')
5) $('.second div:nth-child(1)')
6) $('.second').children().first()
7) $('.second').children().eq(0)

Angular/RxJs When should I unsubscribe from `Subscription`

I like the last two answers, but I experienced an issue if the the subclass referenced "this" in ngOnDestroy.

I modified it to be this, and it looks like it resolved that issue.

export abstract class BaseComponent implements OnDestroy {
    protected componentDestroyed$: Subject<boolean>;
    constructor() {
        this.componentDestroyed$ = new Subject<boolean>();
        let f = this.ngOnDestroy;
        this.ngOnDestroy = function()  {
            // without this I was getting an error if the subclass had
            // this.blah() in ngOnDestroy
            f.bind(this)();
            this.componentDestroyed$.next(true);
            this.componentDestroyed$.complete();
        };
    }
    /// placeholder of ngOnDestroy. no need to do super() call of extended class.
    ngOnDestroy() {}
}

Fastest way to Remove Duplicate Value from a list<> by lambda

If you want to stick with the original List instead of creating a new one, you can something similar to what the Distinct() extension method does internally, i.e. use a HashSet to check for uniqueness:

HashSet<long> set = new HashSet<long>(longs.Count);
longs.RemoveAll(x => !set.Add(x));

The List class provides this convenient RemoveAll(predicate) method that drops all elements not satisfying the condition specified by the predicate. The predicate is a delegate taking a parameter of the list's element type and returning a bool value. The HashSet's Add() method returns true only if the set doesn't contain the item yet. Thus by removing any items from the list that can't be added to the set you effectively remove all duplicates.

Euclidean distance of two vectors

If you want to use less code, you can also use the norm in the stats package (the 'F' stands for Forbenius, which is the Euclidean norm):

norm(matrix(x1-x2), 'F')

While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:

set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)

Then testing for time yields the following:

> system.time(a<-sqrt(sum((x1-x2)^2)))
user  system elapsed 
1.02    0.12    1.18 
> system.time(b<-norm(matrix(x1-x2), 'F'))
user  system elapsed 
0.97    0.33    1.31 

What is the difference between JVM, JDK, JRE & OpenJDK?

JRE executes the application but JVM reads the instructions line by line so it's interpreter.

JDK=JRE+Development Tools

JRE=JVM+Library Classes

How do I install an R package from source?

You can install directly from the repository (note the type="source"):

install.packages("RJSONIO", repos = "http://www.omegahat.org/R", type="source")

batch script - run command on each file in directory

I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.

set codedirectory=C:\Users\code
for /r  %codedirectory% %%i in (*.c) do 
( some GCC commands )

Iframe positioning

It's because you're missing position:relative; on #contentframe

<div id="contentframe" style="position:relative; top: 160px; left: 0px;">

position:absolute; positions itself against the closest ancestor that has a position that is not static. Since the default is static that is what was causing your issue.

Why does sed not replace all occurrences?

You have to put a g at the end, it stands for "global":

echo dog dog dos | sed -r 's:dog:log:g'
                                     ^

How to compare two files in Notepad++ v6.6.8

There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.

Alternatively you can install a specialized file compare software like WinMerge.

Updating the list view when the adapter data changes

Change this line:

mMyListView.setAdapter(new ArrayAdapter<String>(this, 
                           android.R.layout.simple_list_item_1, 
                           listItems));

to:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                   android.R.layout.simple_list_item_1, 
                                   listItems)
mMyListView.setAdapter(adapter);

and after updating the value of a list item, call:

adapter.notifyDataSetChanged();

How do I create a folder in a GitHub repository?

I don't know whenever I use "/" in repository name it is replaced by "-" maybe github changed method of creating folders.

So I'm going to tell you what I did to create a empty folder and to add files.

  1. Click on New
  2. enter your folder name and nothing else
  3. Click on "Add a README file"
  4. Click "Create Repository"
  5. Now clone the folder you created.
  6. Add files or folders in the local repo
  7. Commit changes.
  8. And there you go.

Difference between .on('click') vs .click()

I think, the difference is in usage patterns.

I would prefer .on over .click because the former can use less memory and work for dynamically added elements.

Consider the following html:

<html>
    <button id="add">Add new</button>
    <div id="container">
        <button class="alert">alert!</button>
    </div>
</html>

where we add new buttons via

$("button#add").click(function() {
    var html = "<button class='alert'>Alert!</button>";
    $("button.alert:last").parent().append(html);
});

and want "Alert!" to show an alert. We can use either "click" or "on" for that.


When we use click

$("button.alert").click(function() {
    alert(1);
});

with the above, a separate handler gets created for every single element that matches the selector. That means

  1. many matching elements would create many identical handlers and thus increase memory footprint
  2. dynamically added items won't have the handler - ie, in the above html the newly added "Alert!" buttons won't work unless you rebind the handler.

When we use .on

$("div#container").on('click', 'button.alert', function() {
    alert(1);
});

with the above, a single handler for all elements that match your selector, including the ones created dynamically.


...another reason to use .on

As Adrien commented below, another reason to use .on is namespaced events.

If you add a handler with .on("click", handler) you normally remove it with .off("click", handler) which will remove that very handler. Obviously this works only if you have a reference to the function, so what if you don't ? You use namespaces:

$("#element").on("click.someNamespace", function() { console.log("anonymous!"); });

with unbinding via

$("#element").off("click.someNamespace");

PHP: merge two arrays while keeping keys instead of reindexing?

You can simply 'add' the arrays:

>> $a = array(1, 2, 3);
array (
  0 => 1,
  1 => 2,
  2 => 3,
)
>> $b = array("a" => 1, "b" => 2, "c" => 3)
array (
  'a' => 1,
  'b' => 2,
  'c' => 3,
)
>> $a + $b
array (
  0 => 1,
  1 => 2,
  2 => 3,
  'a' => 1,
  'b' => 2,
  'c' => 3,
)

How to identify numpy types in python?

To get the type, use the builtin type function. With the in operator, you can test if the type is a numpy type by checking if it contains the string numpy;

In [1]: import numpy as np

In [2]: a = np.array([1, 2, 3])

In [3]: type(a)
Out[3]: <type 'numpy.ndarray'>

In [4]: 'numpy' in str(type(a))
Out[4]: True

(This example was run in IPython, by the way. Very handy for interactive use and quick tests.)

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Is it "safe" to use $_SERVER['HTTP_HOST'] for all links on a site without having to worry about XSS attacks, even when used in forms?

Yes, it's safe to use $_SERVER['HTTP_HOST'], (and even $_GET and $_POST) as long as you verify them before accepting them. This is what I do for secure production servers:

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
$reject_request = true;
if(array_key_exists('HTTP_HOST', $_SERVER)){
    $host_name = $_SERVER['HTTP_HOST'];
    // [ need to cater for `host:port` since some "buggy" SAPI(s) have been known to return the port too, see http://goo.gl/bFrbCO
    $strpos = strpos($host_name, ':');
    if($strpos !== false){
        $host_name = substr($host_name, $strpos);
    }
    // ]
    // [ for dynamic verification, replace this chunk with db/file/curl queries
    $reject_request = !array_key_exists($host_name, array(
        'a.com' => null,
        'a.a.com' => null,
        'b.com' => null,
        'b.b.com' => null
    ));
    // ]
}
if($reject_request){
    // log errors
    // display errors (optional)
    exit;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
echo 'Hello World!';
// ...

The advantage of $_SERVER['HTTP_HOST'] is that its behavior is more well-defined than $_SERVER['SERVER_NAME']. Contrast ??:

Contents of the Host: header from the current request, if there is one.

with:

The name of the server host under which the current script is executing.

Using a better defined interface like $_SERVER['HTTP_HOST'] means that more SAPIs will implement it using reliable well-defined behavior. (Unlike the other.) However, it is still totally SAPI dependent ??:

There is no guarantee that every web server will provide any of these [$_SERVER entries]; servers may omit some, or provide others not listed here.

To understand how to properly retrieve the host name, first and foremost you need to understand that a server which contains only code has no means of knowing (pre-requisite for verifying) its own name on the network. It needs to interface with a component that supplies it its own name. This can be done via:

  • local config file

  • local database

  • hardcoded source code

  • external request (curl)

  • client/attacker's Host: request

  • etc

Usually its done via the local (SAPI) config file. Note that you have configured it correctly, e.g. in Apache ??:

A couple of things need to be 'faked' to make the dynamic virtual host look like a normal one.

The most important is the server name which is used by Apache to generate self-referential URLs, etc. It is configured with the ServerName directive, and it is available to CGIs via the SERVER_NAME environment variable.

The actual value used at run time is controlled by the UseCanonicalName setting.

With UseCanonicalName Off the server name comes from the contents of the Host: header in the request. With UseCanonicalName DNS it comes from a reverse DNS lookup of the virtual host's IP address. The former setting is used for name-based dynamic virtual hosting, and the latter is used for** IP-based hosting.

If Apache cannot work out the server name because there is no Host: header or the DNS lookup fails then the value configured with ServerName is used instead.

no such file to load -- rubygems (LoadError)

I would just like to add that in my case rubygems wasn't installed.

Running sudo apt-get install rubygems solved the issue!

Check element CSS display with JavaScript

To find out if it's visible with plain JavaScript, check whether the display property is 'none' (don't check for 'block', it could also be blank or 'inline' and still be visible):

var isVisible = (elt.style.display != "none");

If you are using jQuery, you can use this instead:

var isVisible = $elt.is(":visible");

What does PHP keyword 'var' do?

In PHP7.3 still working...

https://www.php.net/manual/en/language.oop5.visibility.php

If declared using var, the property will be defined as public.

MongoDB Show all contents from all collections

Step 1: See all your databases:

show dbs

Step 2: Select the database

use your_database_name

Step 3: Show the collections

show collections

This will list all the collections in your selected database.

Step 4: See all the data

db.collection_name.find() 

or

db.collection_name.find().pretty()

How to do fade-in and fade-out with JavaScript and CSS

Ok, I've worked it out

element.style.opacity = parseFloat(element.style.opacity) + 0.1;

Should be used instead of

element.style.opacity += 0.1;

Same with

element.style.opacity = parseFloat(element.style.opacity) - 0.1;

Instead of

element.style.opacity -= 0.1;

Because opacity value is stored as string, not as float. I'm still not sure though why the addition has worked.

How do I drop a MongoDB database from the command line?

Here are some use full delete operations for mongodb using mongo shell

To delete particular document in collections: db.mycollection.remove( {name:"stack"} )

To delete all documents in collections: db.mycollection.remove()

To delete collection : db.mycollection.drop()

to delete database : first go to that database by use mydb command and then

db.dropDatabase()

directly from command prompt or blash : mongo mydb --eval "db.dropDatabase()

How should I have explained the difference between an Interface and an Abstract class?

The main difference what i have observed was that abstract class provides us with some common behaviour implemented already and subclasses only needs to implement specific functionality corresponding to them. where as for an interface will only specify what tasks needs to be done and no implementations will be given by interface. I can say it specifies the contract between itself and implemented classes.

Append a tuple to a list - what's the difference between two ways?

It has nothing to do with append. tuple(3, 4) all by itself raises that error.

The reason is that, as the error message says, tuple expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.

Just do (3, 4) to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.

Android: Storing username and password?

I think the best way to secure your credential is to first think of storing the Password with encryption in the account.db file which couldn't be easily available in non rooted devices and in case of rooted device the hacker must need the key to decrypt it.

Other option is do all your authentication like the way Gmail is doing. after the first authentication with the Gmail server . you got the Auth Token that would be use in case of your password . that token would be store in plain text.this token could be false in case you change the password from Server.

the last option I'd recommend you to enable 2-Factor Authentication & create Device Specific Password for your device. After losing device, all you need is to disable that device.

Ajax using https on an http page

Here's what I do:

Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

Less aggressive compilation with CSS3 calc

A very common usecase of calc is take 100% width and adding some margin around the element.

One can do so with:

@someMarginVariable = 15px;

margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);

Best way to check if an PowerShell Object exist?

I had the same Problem. This solution works for me.

$Word = $null
$Word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('word.application')
if ($Word -eq $null)
{
    $Word = new-object -ComObject word.application
}

https://msdn.microsoft.com/de-de/library/system.runtime.interopservices.marshal.getactiveobject(v=vs.110).aspx

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

You must analyse the actual HTML output, for the hint.

By giving the path like this means "from current location", on the other hand if you start with a / that would mean "from the context".

How can I get screen resolution in java?

This is the resolution of the screen that the given component is currently assigned (something like most part of the root window is visible on that screen).

public Rectangle getCurrentScreenBounds(Component component) {
    return component.getGraphicsConfiguration().getBounds();
}

Usage:

Rectangle currentScreen = getCurrentScreenBounds(frameOrWhateverComponent);
int currentScreenWidth = currentScreen.width // current screen width
int currentScreenHeight = currentScreen.height // current screen height
// absolute coordinate of current screen > 0 if left of this screen are further screens
int xOfCurrentScreen = currentScreen.x

If you want to respect toolbars, etc. you'll need to calculate with this, too:

GraphicsConfiguration gc = component.getGraphicsConfiguration();
Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(gc);

Global variables in R

As Christian's answer with assign() shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<- operator, ie

    a <<- "new" 

inside the function.

Horizontal list items

You could also use inline blocks to avoid floating elements

<ul>
    <li>
        <a href="#">some item</a>
    </li>
    <li>
        <a href="#">another item</a>
   </li>
</ul>

and then style as:

li{
    /* with fix for IE */
    display:inline;
    display:inline-block;
    zoom:1;
    /*
    additional styles to make it look nice
    */
 }

that way you wont need to float anything, eliminating the need for clearfixes

JavaScript hard refresh of current page

window.location.href = window.location.href

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

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

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

Cron job every three days

How about:

00 00  *  *   * every 3 days && echo test

Where every is a script:

#!/bin/sh

case $2 in
    days)
        expr `date +%j` % $1 = 0 > /dev/null
        ;;

    weeks)
        expr `date +%V` % $1 = 0 > /dev/null
        ;;

    months)
        expr `date +%m` % $1 = 0 > /dev/null
        ;;
esac

So it runs every day.

Using */3 runs on the 3rd, 6th, ... 27th, 30th of the month, but is then wrong after a month has a 31st day. The every script is only wrong after the end of the year.

How to destroy a JavaScript object?

I was facing a problem like this, and had the idea of simply changing the innerHTML of the problematic object's children.

adiv.innerHTML = "<div...> the original html that js uses </div>";

Seems dirty, but it saved my life, as it works!

How can I create Min stl priority_queue?

In C++11 you could also create an alias for convenience:

template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;

And use it like this:

min_heap<int> my_heap;

How to populate HTML dropdown list with values from database

<?php
 $query = "select username from users";
 $res = mysqli_query($connection, $query);   
?>


<form>
  <select>
     <?php
       while ($row = $res->fetch_assoc()) 
       {
         echo '<option value=" '.$row['id'].' "> '.$row['name'].' </option>';
       }
    ?>
  </select>
</form>

Javascript Src Path

Use an relative path to the root of your site, for example:

If clock.js is on http://domain.com/javascript/clock.js

Include :

<script language="JavaScript" src="/javascript/clock.js"></script>

If it's on your domain root directory:

<script language="JavaScript" src="/clock.js"></script>

Detect Safari using jQuery

My best solution

function getBrowserInfo() {
  const ua = navigator.userAgent; let tem;
  let M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  if (/trident/i.test(M[1])) {
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    return { name: 'IE ', version: (tem[1] || '') };
  }
  if (M[1] === 'Chrome') {
    tem = ua.match(/\bOPR\/(\d+)/);
    if (tem != null) {
      return { name: 'Opera', version: tem[1] };
    }
  }
  M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
  tem = ua.match(/version\/(\d+)/i);
  if (tem != null) {
    M.splice(1, 1, tem[1]);
  }
  return {
    name: M[0],
    version: M[1],
  };
}

getBrowserInfo();

Error: The 'brew link' step did not complete successfully

by the Finder, Delete this file:

/usr/local/lib/dtrace/node.d

in terminal:

$ brew link --overwrite --dry-run node

then:

$ brew link node

Singleton with Arguments in Java

If we take the problem as "how to make singleton with state", then it is not necessary to pass the state as constructor parameter. I agree with the posts that initialize the states or using set method after getting the singleton instance.

Another question is: is it good to have singleton with state?

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

PUT /testIndex
{
    "mappings": {
        "properties": {     <--ADD THIS
            "field1": {
                "type": "integer"
            },
            "field2": {  
                "type": "integer"
            },
            "field3": {
                "type": "string",
                "index": "not_analyzed"
            },
            "field4": {
                "type": "string",
                "analyzer": "autocomplete",
                "search_analyzer": "standard"
            }
        }
    },
    "settings": {
        bla
        bla
        bla
    }
}

Here's a similar command I know works:

curl -v -H "Content-Type: application/json" -H "Authorization: Basic cGC3COJ1c2Vy925hZGFJbXBvcnABCnRl" -X PUT -d '{"mappings":{"properties":{"city":{"type": "text"}}}}' https://35.80.2.21/manzanaIndex

The breakdown for the above curl command is:

PUT /manzanaIndex
{
    "mappings":{
        "properties":{
                "city":{
                    "type": "text"
                }
        }
    }
}

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

json_encode($text, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);

Xcode 10: A valid provisioning profile for this executable was not found

Be aware that accepted answer prevents build to be uploaded to App Store Connect.

How to build and fill pandas dataframe from for loop?

Try this using list comprehension:

import pandas as pd

df = pd.DataFrame(
    [p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing()
)

jQuery animated number counter from zero to value

Your thisdoesn't refer to the element in the step callback, instead you want to keep a reference to it at the beginning of your function (wrapped in $thisin my example):

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

Update: If you want to display decimal numbers, then instead of rounding the value with Math.ceil you can round up to 2 decimals for instance with value.toFixed(2):

step: function () {
  $this.text(this.Counter.toFixed(2));
}

How to make a query with group_concat in sql server

Please run the below query, it doesn't requires STUFF and GROUP BY in your case:

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , CAST((
          SELECT  T.maskdetail+','
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH(''))as varchar(max)) as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid

Checking length of dictionary object

This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).

Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.

I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?

Edit #1: Why can't you just do this?

list = [ {name:'john'}, {name:'bob'} ];

Then iterate over list? The length is already set.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Convert the batch file to an exe. Try Bat To Exe Converter or Online Bat To Exe Converter, and choose the option to run it as a ghost application, i.e. no window.

How do I write a custom init for a UIView subclass in Swift?

Here is how I do it on iOS 9 in Swift -

import UIKit

class CustomView : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        //for debug validation
        self.backgroundColor = UIColor.blueColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Here is a full project with example:

How do I add more members to my ENUM-type column in MySQL?

The discussion I had with Asaph may be unclear to follow as we went back and forth quite a bit.

I thought that I might clarify the upshot of our discourse for others who might face similar situations in the future to benefit from:

ENUM-type columns are very difficult beasts to manipulate. I wanted to add two countries (Malaysia & Sweden) to the existing set of countries in my ENUM.

It seems that MySQL 5.1 (which is what I am running) can only update the ENUM by redefining the existing set in addition to what I want:

This did not work:

ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia') DEFAULT NULL;

The reason was that the MySQL statement was replacing the existing ENUM with another containing the entries 'Malaysia' and 'Sweden' only. MySQL threw up an error because the carmake table already had values like 'England' and 'USA' which were not part of the new ENUM's definition.

Surprisingly, the following did not work either:

ALTER TABLE carmake CHANGE country country ENUM('Australia','England','USA'...'Sweden','Malaysia') DEFAULT NULL;

It turns out that even the order of elements of the existing ENUM needs to be preserved while adding new members to it. So if my existing ENUM looks something like ENUM('England','USA'), then my new ENUM has to be defined as ENUM('England','USA','Sweden','Malaysia') and not ENUM('USA','England','Sweden','Malaysia'). This problem only becomes manifest when there are records in the existing table that use 'USA' or 'England' values.

BOTTOM LINE:

Only use ENUMs when you do not expect your set of members to change once defined. Otherwise, lookup tables are much easier to update and modify.

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

Minimal error reproduction

export const users = require('../data'); // presumes @types/node are installed
const foundUser = users.find(user => user.id === 42); 
// error: Parameter 'user' implicitly has an 'any' type.ts(7006)

Recommended solution: --resolveJsonModule

The simplest way for your case is to use --resolveJsonModule compiler option:
import users from "./data.json" // `import` instead of `require`
const foundUser = users.find(user => user.id === 42); // user is strongly typed, no `any`!

There are some alternatives for other cases than static JSON import.

Option 1: Explicit user type (simple, no checks)

type User = { id: number; name: string /* and others */ }
const foundUser = users.find((user: User) => user.id === 42)

Option 2: Type guards (middleground)

Type guards are a good middleground between simplicity and strong types:
function isUserArray(maybeUserArr: any): maybeUserArr is Array<User> {
  return Array.isArray(maybeUserArr) && maybeUserArr.every(isUser)
}

function isUser(user: any): user is User {
  return "id" in user && "name" in user
}

if (isUserArray(users)) {
  const foundUser = users.find((user) => user.id === 42)
}
You can even switch to assertion functions (TS 3.7+) to get rid of if and throw an error instead.
function assertIsUserArray(maybeUserArr: any): asserts maybeUserArr is Array<User> {
  if(!isUserArray(maybeUserArr)) throw Error("wrong json type")
}

assertIsUserArray(users)
const foundUser = users.find((user) => user.id === 42) // works

Option 3: Runtime type system library (sophisticated)

A runtime type check library like io-ts or ts-runtime can be integrated for more complex cases.


Not recommended solutions

noImplicitAny: false undermines many useful checks of the type system:
function add(s1, s2) { // s1,s2 implicitely get `any` type
  return s1 * s2 // `any` type allows string multiplication and all sorts of types :(
}
add("foo", 42)

Also better provide an explicit User type for user. This will avoid propagating any to inner layer types. Instead typing and validating is kept in the JSON processing code of the outer API layer.

How to start jenkins on different port rather than 8080 using command prompt in Windows?

Use the following command at command prompt:

java -jar jenkins.war --httpPort=9090

If you want to use https use the following command:

java -jar jenkins.war --httpsPort=9090

Details are here

The infamous java.sql.SQLException: No suitable driver found

I encountered this issue by putting a XML file into the src/main/resources wrongly, I deleted it and then all back to normal.

Removing all unused references from a project in Visual Studio projects

If you have Resharper (plugin) installed, you can access a feature that allows you to analyze used references via Solution Explorer > (right click) References > Optimize References...

http://www.jetbrains.com/resharper/webhelp/Refactorings__Remove_Unused_References.html

This feature does not correctly handle:

  • Dependency injected assemblies
  • Dynamically loaded assemblies (Assembly.LoadFile)
  • Native code assemblies loaded through interop
  • ActiveX controls (COM interop)
  • Other creative ways of loading assemblies

enter image description here

Linux : Search for a Particular word in a List of files under a directory

also you can try the following.

find . -name '*.java' -exec grep "<yourword" /dev/null {} \;

It gets all the files with .java extension and searches 'yourword' in each file, if it presents, it lists the file.

Hope it helps :)

Using OR & AND in COUNTIFS

i found i had to do something akin to

=(countifs (A1:A196,"yes", j1:j196, "agree") + (countifs (A1:A196,"no", j1:j196, "agree"))

How are booleans formatted in Strings in Python?

To update this for Python-3 you can do this

"{} {}".format(True, False)

However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.

>>> "{:<8} {}".format(True, False)
'1        False'

To get around this you can cast True as a string, e.g.

>>> "{:<8} {}".format(str(True), False)
'True     False'

Java 8 - Difference between Optional.flatMap and Optional.map

They both take a function from the type of the optional to something.

map() applies the function "as is" on the optional you have:

if (optional.isEmpty()) return Optional.empty();
else return Optional.of(f(optional.get()));

What happens if your function is a function from T -> Optional<U>?
Your result is now an Optional<Optional<U>>!

That's what flatMap() is about: if your function already returns an Optional, flatMap() is a bit smarter and doesn't double wrap it, returning Optional<U>.

It's the composition of two functional idioms: map and flatten.

How to run functions in parallel?

If you are a windows user and using python 3, then this post will help you to do parallel programming in python.when you run a usual multiprocessing library's pool programming, you will get an error regarding the main function in your program. This is because the fact that windows has no fork() functionality. The below post is giving a solution to the mentioned problem .

http://python.6.x6.nabble.com/Multiprocessing-Pool-woes-td5047050.html

Since I was using the python 3, I changed the program a little like this:

from types import FunctionType
import marshal

def _applicable(*args, **kwargs):
  name = kwargs['__pw_name']
  code = marshal.loads(kwargs['__pw_code'])
  gbls = globals() #gbls = marshal.loads(kwargs['__pw_gbls'])
  defs = marshal.loads(kwargs['__pw_defs'])
  clsr = marshal.loads(kwargs['__pw_clsr'])
  fdct = marshal.loads(kwargs['__pw_fdct'])
  func = FunctionType(code, gbls, name, defs, clsr)
  func.fdct = fdct
  del kwargs['__pw_name']
  del kwargs['__pw_code']
  del kwargs['__pw_defs']
  del kwargs['__pw_clsr']
  del kwargs['__pw_fdct']
  return func(*args, **kwargs)

def make_applicable(f, *args, **kwargs):
  if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
  kwargs['__pw_name'] = f.__name__  # edited
  kwargs['__pw_code'] = marshal.dumps(f.__code__)   # edited
  kwargs['__pw_defs'] = marshal.dumps(f.__defaults__)  # edited
  kwargs['__pw_clsr'] = marshal.dumps(f.__closure__)  # edited
  kwargs['__pw_fdct'] = marshal.dumps(f.__dict__)   # edited
  return _applicable, args, kwargs

def _mappable(x):
  x,name,code,defs,clsr,fdct = x
  code = marshal.loads(code)
  gbls = globals() #gbls = marshal.loads(gbls)
  defs = marshal.loads(defs)
  clsr = marshal.loads(clsr)
  fdct = marshal.loads(fdct)
  func = FunctionType(code, gbls, name, defs, clsr)
  func.fdct = fdct
  return func(x)

def make_mappable(f, iterable):
  if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
  name = f.__name__    # edited
  code = marshal.dumps(f.__code__)   # edited
  defs = marshal.dumps(f.__defaults__)  # edited
  clsr = marshal.dumps(f.__closure__)  # edited
  fdct = marshal.dumps(f.__dict__)  # edited
  return _mappable, ((i,name,code,defs,clsr,fdct) for i in iterable)

After this function , the above problem code is also changed a little like this:

from multiprocessing import Pool
from poolable import make_applicable, make_mappable

def cube(x):
  return x**3

if __name__ == "__main__":
  pool    = Pool(processes=2)
  results = [pool.apply_async(*make_applicable(cube,x)) for x in range(1,7)]
  print([result.get(timeout=10) for result in results])

And I got the output as :

[1, 8, 27, 64, 125, 216]

I am thinking that this post may be useful for some of the windows users.

Group by & count function in sqlalchemy

If you are using Table.query property:

from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()

If you are using session.query() method (as stated in miniwark's answer):

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Proper usage of Optional.ifPresent()

You can use method reference like this:

user.ifPresent(ClassNameWhereMethodIs::doSomethingWithUser);

Method ifPresent() get Consumer object as a paremeter and (from JavaDoc): "If a value is present, invoke the specified consumer with the value." Value it is your variable user.

Or if this method doSomethingWithUser is in the User class and it is not static, you can use method reference like this:

user.ifPresent(this::doSomethingWithUser);

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

if "allow zero datetime=true" is not working then use the following sollutions:-

Add this to your connection string: "allow zero datetime=no" - that made the type cast work perfectly.

How to present UIActionSheet iOS Swift?

Generetic Action Sheet working for Swift 4, 4.2, 5

If you like a generic version that you can call from every ViewController and in every project try this one:

class Alerts {
 static func showActionsheet(viewController: UIViewController, title: String, message: String, actions: [(String, UIAlertActionStyle)], completion: @escaping (_ index: Int) -> Void) {
    let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
    for (index, (title, style)) in actions.enumerated() {
        let alertAction = UIAlertAction(title: title, style: style) { (_) in
            completion(index)
        }
        alertViewController.addAction(alertAction)
     }
     viewController.present(alertViewController, animated: true, completion: nil)
    }
}

Call like this in your ViewController.

    var actions: [(String, UIAlertActionStyle)] = []
    actions.append(("Action 1", UIAlertActionStyle.default))
    actions.append(("Action 2", UIAlertActionStyle.destructive))
    actions.append(("Action 3", UIAlertActionStyle.cancel))

    //self = ViewController
    Alerts.showActionsheet(viewController: self, title: "D_My ActionTitle", message: "General Message in Action Sheet", actions: actions) { (index) in
        print("call action \(index)")
        /*
         results
         call action 0
         call action 1
         call action 2
         */
    }

enter image description here

Attention: Maybe you're wondering why I add Action 1/2/3 but got results like 0,1,2. In the line for (index, (title, style)) in actions.enumerated() I get the index of actions. Arrays always begin with the index 0. So the completion is 0,1,2.

If you like to set a enum, an id or another identifier I would recommend to hand over an object in parameter actions.

Convert RGB values to Integer

int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);

If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff

Additionaly

int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb)    &0x0ff;

No need for multipling.

Retrieving subfolders names in S3 bucket from boto3

It took me a lot of time to figure out, but finally here is a simple way to list contents of a subfolder in S3 bucket using boto3. Hope it helps

prefix = "folderone/foldertwo/"
s3 = boto3.resource('s3')
bucket = s3.Bucket(name="bucket_name_here")
FilesNotFound = True
for obj in bucket.objects.filter(Prefix=prefix):
     print('{0}:{1}'.format(bucket.name, obj.key))
     FilesNotFound = False
if FilesNotFound:
     print("ALERT", "No file in {0}/{1}".format(bucket, prefix))

Converting pixels to dp

There is a default util in android SDK: http://developer.android.com/reference/android/util/TypedValue.html

float resultPix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,1,getResources().getDisplayMetrics())

Pandas DataFrame column to list

You can use pandas.Series.tolist

e.g.:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

Run:

>>> df['a'].tolist()

You will get

>>> [1, 2, 3]

How to change the author and committer name and e-mail of multiple commits in Git?

If you want to (easily) change the author for the current branch I would use something like this:

# update author for everything since origin/master
git rebase \
  -i origin/master \
  --exec 'git commit --amend --no-edit --author="Author Name <[email protected]>"'

Conditional Count on a field

I think you may be after

select 
    jobID, JobName,
    sum(case when Priority = 1 then 1 else 0 end) as priority1,
    sum(case when Priority = 2 then 1 else 0 end) as priority2,
    sum(case when Priority = 3 then 1 else 0 end) as priority3,
    sum(case when Priority = 4 then 1 else 0 end) as priority4,
    sum(case when Priority = 5 then 1 else 0 end) as priority5
from
    Jobs
group by 
    jobID, JobName

However I am uncertain if you need to the jobID and JobName in your results if so remove them and remove the group by,

Why is Visual Studio 2013 very slow?

I too have struggled a bit with bad performance in Visual Studio 2013 (Premium). Pretty much the same issues as TS had. Slow navigation, scrolling, building... just about everything. Luckily I have manage to solve my own problem by disabling Synchronized Settings in Visual Studio. Go to menu ToolsOptionsEnvironment-Synchronized Settings and remove this option by unchecking the checkbox.

Disable Synchronized Settings

java collections - keyset() vs entrySet() in map

Every call to the Iterator.next() moves the iterator to the next element. If you want to use the current element in more than one statement or expression, you have to store it in a local variable. Or even better, why don't you simply use a for-each loop?

for (String key : map.keySet()) {
    System.out.println(key + ":" + map.get(key));
}

Moreover, loop over the entrySet is faster, because you don't query the map twice for each key. Also Map.Entry implementations usually implement the toString() method, so you don't have to print the key-value pair manually.

for (Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry);
}

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout) Check it.

How to repeat last command in python interpreter shell?

If you use Debian Jessie run this to fix your system installation 2.7.9

sudo apt-get install libncurses5-dev libncursesw5-dev

To fix my other 3.5.2 installation which I installed with pyenv :

pip install readline

Sources:

[1] https://www.cyberciti.biz/faq/linux-install-ncurses-library-headers-on-debian-ubuntu-centos-fedora/

[2] https://github.com/yyuu/pyenv/issues/240

[3] https://stackoverflow.com/a/40229934/332788

git: Your branch is ahead by X commits

In my case it was because I switched to master using

 git checkout -B master

Just to pull the new version of it instead of

 git checkout master

The first command resets the head of master to my latest commits

I used

git reset --hard origin/master

To fix that

What's the difference between session.persist() and session.save() in Hibernate?

Here are the differences that can help you understand the advantages of persist and save methods:

  • First difference between save and persist is their return type. The return type of persist method is void while return type of save
    method is Serializable object.
  • The persist() method doesn’t guarantee that the identifier value will be assigned to the persistent state immediately, the assignment might happen at flush time.

  • The persist() method will not execute an insert query if it is called outside of transaction boundaries. While, the save() method returns an identifier so that an insert query is executed immediately to get the identifier, no matter if it are inside or outside of a transaction.

  • The persist method is called outside of transaction boundaries, it is useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.

  • Fifth difference between save and persist method in Hibernate: persist is supported by JPA, while save is only supported by Hibernate.

You can see the full working example from the post Difference between save and persist method in Hibernate

Navigation Drawer (Google+ vs. YouTube)

I know this is an old question but the most up to date answer is to use the Android Support Design library that will make your life easy.

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

Passing parameter using onclick or a click binding with KnockoutJS

Use a binding, like in this example:

<a href="#new-search" data-bind="click:SearchManager.bind($data,'1')">
  Search Manager
</a>
var ViewModelStructure = function () {
    var self = this;
    this.SearchManager = function (search) {
        console.log(search);
    };
}();

Can I specify maxlength in css?

As others have answered, there is no current way to add maxlength directly to a CSS class.

However, this creative solution can achieve what you are looking for.

I have the jQuery in a file named maxLengths.js which I reference in site (site.master for ASP)

run the snippet to see it in action, works well.

jquery, css, html:

_x000D_
_x000D_
$(function () {_x000D_
    $(".maxLenAddress1").keypress(function (event) {_x000D_
_x000D_
        if ($(this).val().length == 5) { /* obv 5 is too small for an address field, just want to use as an example though */_x000D_
            return false;_x000D_
        } else {_x000D_
            return true;_x000D_
        }_x000D_
_x000D_
    });_x000D_
});
_x000D_
.maxLenAddress1{} /* this is here mostly for intellisense usage, but can be altered if you like */
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" class="maxLenAddress1" />
_x000D_
_x000D_
_x000D_

The advantage of using this: if it is decided the max length for this type of field needs to be pushed out or in across your entire application you can change it in one spot. Comes in handy for field lengths for things like customer codes, full name fields, email fields, any field common across your application.

Convert integer to class Date

You can use ymd from lubridate

lubridate::ymd(v)
#[1] "2008-11-01"

Or anytime::anydate

anytime::anydate(v)
#[1] "2008-11-01"

Binding value to style

Turns out the binding of style to a string doesn't work. The solution would be to bind the background of the style.

 <div class="circle" [style.background]="color">

CSS background opacity with rgba not working in IE 8

this worked for me to solve the problem in IE8:

-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=1)";

Cheers

Highcharts - redraw() vs. new Highcharts.chart

var newData = [1,2,3,4,5,6,7];
var chart = $('#chartjs').highcharts();
chart.series[0].setData(newData, true);

Explanation:
Variable newData contains value that want to update in chart. Variable chart is an object of a chart. setData is a method provided by highchart to update data.

Method setData contains two parameters, in first parameter we need to pass new value as array and second param is Boolean value. If true then chart updates itself and if false then we have to use redraw() method to update chart (i.e chart.redraw();)

http://jsfiddle.net/NxEnH/8/

How to detect when cancel is clicked on file input?

    enter code here
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <h1>Hello</h1>
    <div id="cancel01">
      <button>Cancel</button>
    </div>

    <div id="cancel02">
      <button>Cancel</button>
    </div>

    <div id="cancel03">
      <button>Cancel</button>
    </div>

    <form>
      <input type="file" name="name" placeholder="Name" />
    </form>

    <script>
      const nameInput = document.querySelector('input[type="file"]');

      /******
       *The below code if for How to detect when cancel is clicked on file input
       ******/
      nameInput.addEventListener('keydown', e => {
        /******
         *If the cancel button is clicked,then you should change the input file value to empty
         ******/

        if (e.key == 'Backspace' || e.code == 'Backspace' || e.keyCode == 8) {
          console.log(e);

          /******
           *The below code will delete the file path
           ******/
          nameInput.value = '';
        }
      });
    </script>
  </body>
</html>

(grep) Regex to match non-ASCII characters?

This turned out to be very flexible and extensible. $field =~ s/[^\x00-\x7F]//g ; # thus all non ASCII or specific items in question could be cleaned. Very nice either in selection or pre-processing of items that will eventually become hash keys.

Getting the first index of an object

ES6

const [first] = Object.keys(obj)

How to check if a file exists in the Documents directory in Swift?

Swift 4.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    if let pathComponent = url.appendingPathComponent("nameOfFileHere") {
        let filePath = pathComponent.path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath) {
            print("FILE AVAILABLE")
        } else {
            print("FILE NOT AVAILABLE")
        }
    } else {
        print("FILE PATH NOT AVAILABLE")
    }

Swift 3.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = URL(fileURLWithPath: path)

    let filePath = url.appendingPathComponent("nameOfFileHere").path
    let fileManager = FileManager.default
    if fileManager.fileExists(atPath: filePath) {
        print("FILE AVAILABLE")
    } else {
        print("FILE NOT AVAILABLE")
    }

Swift 2.x version, need to use URLByAppendingPathComponent

    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    let filePath = url.URLByAppendingPathComponent("nameOfFileHere").path!
    let fileManager = NSFileManager.defaultManager()
    if fileManager.fileExistsAtPath(filePath) {
        print("FILE AVAILABLE")
    } else {
        print("FILE NOT AVAILABLE")
    }

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I was getting this error when using Laravel and eloquent, trying to make a foreign key link would cause a 1452. The problem was lack of data in the linked table.

Please see here for an example: http://mstd.eu/index.php/2016/12/02/laravel-eloquent-integrity-constraint-violation-1452-foreign-key-constraint/

Can we instantiate an abstract class directly?

According to others said, you cannot instantiate from abstract class. but it exist 2 way to use it. 1. make another non-abstact class that extends from abstract class. So you can instantiate from new class and use the attributes and methods in abstract class.

    public class MyCustomClass extends YourAbstractClass {

/// attributes, methods ,...
}
  1. work with interfaces.

Python not working in command prompt?

Rather than the command "python", consider launching Python via the py launcher, as described in sg7's answer, which by runs your latest version of Python (or lets you select a specific version). The py launcher is enabled via a check box during installation (default: "on").

Nevertheless, you can still put the "python" command in your PATH, either at "first installation" or by "modifying" an existing installation.


First Installation:

Checking the "[x] Add Python x.y to PATH" box on the very first dialog. Here's how it looks in version 3.8: enter image description here

This has the effect of adding the following to the PATH variable:

C:\Users\...\AppData\Local\Programs\Python\Python38-32\Scripts\
C:\Users\...\AppData\Local\Programs\Python\Python38-32\

Modifying an Existing Installation:

Re-run your installer (e.g. in Downloads, python-3.8.4.exe) and Select "Modify". Check all the optional features you want (likely no changes), then click [Next]. Check [x] "Add Python to environment variables", and [Install]. enter image description here

Android studio logcat nothing to show

You may put some text in the search and filter out the Logcat result.
That was the reason for my problem :)

How to implement the --verbose or -v option into a script?

It might be cleaner if you have a function, say called vprint, that checks the verbose flag for you. Then you just call your own vprint function any place you want optional verbosity.

matplotlib has no attribute 'pyplot'

pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

p = plt.plot(...)

Write to CSV file and export it?

Here is a CSV action result I wrote that takes a DataTable and converts it into CSV. You can return this from your view and it will prompt the user to download the file. You should be able to convert this easily into a List compatible form or even just put your list into a DataTable.

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;

namespace Detectent.Analyze.ActionResults
{
    public class CSVResult : ActionResult
    {
        /// <summary>
        /// Converts the columns and rows from a data table into an Microsoft Excel compatible CSV file.
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="fileName">The full file name including the extension.</param>
        public CSVResult(DataTable dataTable, string fileName)
        {
            Table = dataTable;
            FileName = fileName;
        }

        public string FileName { get; protected set; }
        public DataTable Table { get; protected set; }




        public override void ExecuteResult(ControllerContext context)
        {
            StringBuilder csv = new StringBuilder(10 * Table.Rows.Count * Table.Columns.Count);

            for (int c = 0; c < Table.Columns.Count; c++)
            {
                if (c > 0)
                    csv.Append(",");
                DataColumn dc = Table.Columns[c];
                string columnTitleCleaned = CleanCSVString(dc.ColumnName);
                csv.Append(columnTitleCleaned);
            }
            csv.Append(Environment.NewLine);
            foreach (DataRow dr in Table.Rows)
            {
                StringBuilder csvRow = new StringBuilder();
                for(int c = 0; c < Table.Columns.Count; c++)
                {
                    if(c != 0)
                        csvRow.Append(",");

                    object columnValue = dr[c];
                    if (columnValue == null)
                        csvRow.Append("");
                    else
                    {
                        string columnStringValue = columnValue.ToString();


                        string cleanedColumnValue = CleanCSVString(columnStringValue);

                        if (columnValue.GetType() == typeof(string) && !columnStringValue.Contains(","))
                        {
                            cleanedColumnValue = "=" + cleanedColumnValue; // Prevents a number stored in a string from being shown as 8888E+24 in Excel. Example use is the AccountNum field in CI that looks like a number but is really a string.
                        }
                        csvRow.Append(cleanedColumnValue);
                    }
                }
                csv.AppendLine(csvRow.ToString());
            }

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "text/csv";
            response.AppendHeader("Content-Disposition", "attachment;filename=" + this.FileName);
            response.Write(csv.ToString());
        }

        protected string CleanCSVString(string input)
        {
            string output = "\"" + input.Replace("\"", "\"\"").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", "") + "\"";
            return output;
        }
    }
}

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

Serializing with Jackson (JSON) - getting "No serializer found"?

For Jackson to serialize that class, the SomeString field needs to either be public (right now it's package level isolation) or you need to define getter and setter methods for it.

Can't bind to 'ngIf' since it isn't a known property of 'div'

Instead of [ngIf] you should use *ngIf like this:

<div *ngIf="isAuth" id="sidebar">

Changing Underline color

You can also use the box-shadow property to simulate an underline.

Here is a fiddle. The idea is to use two layered box shadows to position the line in the same place as an underline.

a.underline {
    text-decoration: none;
    box-shadow: inset 0 -4px 0 0 rgba(255, 255, 255, 1), inset 0 -5px 0 0 rgba(255, 0, 0, 1);
}

Convert JSON array to Python list

Tested on Ideone.


import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

Convert text to columns in Excel using VBA

If someone is facing issue using texttocolumns function in UFT. Please try using below function.

myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true

Here we are using coma(,) as delimiter.

Converting an int to a binary string representation in Java?

here is my methods, it is a little bit convince that number of bytes fixed

private void printByte(int value) {
String currentBinary = Integer.toBinaryString(256 + value);
System.out.println(currentBinary.substring(currentBinary.length() - 8));
}

public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
  if(numbers[i]=='1')
    result += Math.pow(2, (numbers.length-i - 1));
return result;
}

"Sources directory is already netbeans project" error when opening a project from existing sources

  1. copy an existing netbeans project folder in to your new project and manually edit the xml project name.

  2. reinstall netbeans

  3. copy/move all files/folders (except nbproject/ folder) to a new folder for your project, with a new name.

Setting Java heap space under Maven 2 on Windows

After trying to use the MAVEN_OPTS variable with no luck, I came across this site which worked for me. So all I had to do was add -Xms128m -Xmx1024m to the default VM options and it worked.

To change those in Eclipse, go to Window -> Preferences -> Java -> Installed JREs. Select the checked JRE/JDK and click edit.

css - position div to bottom of containing div

.outside {
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Needs to be

.outside {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Absolute positioning looks for the nearest relatively positioned parent within the DOM, if one isn't defined it will use the body.

Ant if else condition?

You can also do this with ant contrib's if task.

<if>
    <equals arg1="${condition}" arg2="true"/>
    <then>
        <copy file="${some.dir}/file" todir="${another.dir}"/>
    </then>
    <elseif>
        <equals arg1="${condition}" arg2="false"/>
        <then>
            <copy file="${some.dir}/differentFile" todir="${another.dir}"/>
        </then>
    </elseif>
    <else>
        <echo message="Condition was neither true nor false"/>
    </else>
</if>

MySQL - Rows to Columns

If you could use MariaDB there is a very very easy solution.

Since MariaDB-10.02 there has been added a new storage engine called CONNECT that can help us to convert the results of another query or table into a pivot table, just like what you want: You can have a look at the docs.

First of all install the connect storage engine.

Now the pivot column of our table is itemname and the data for each item is located in itemvalue column, so we can have the result pivot table using this query:

create table pivot_table
engine=connect table_type=pivot tabname=history
option_list='PivotCol=itemname,FncCol=itemvalue';

Now we can select what we want from the pivot_table:

select * from pivot_table

More details here

This app won't run unless you update Google Play Services (via Bazaar)

I've been trying to run an Android Google Maps v2 under an emulator, and I found many ways to do that, but none of them worked for me. I have always this warning in the Logcat Google Play services out of date. Requires 3025100 but found 2010110 and when I want to update Google Play services on the emulator nothing happened. The problem was that the com.google.android.gms APK was not compatible with the version of the library in my Android SDK.

I installed these files "com.google.android.gms.apk", "com.android.vending.apk" on my emulator and my app Google Maps v2 worked fine. None of the other steps regarding /system/app were required.

How do I change UIView Size?

Here you go. this should work.

questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7) 

answerFrame.frame =  CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)

how to resolve DTS_E_OLEDBERROR. in ssis

Knowing the version of Windows and SQL Server might be helpful in some cases. From the Native Client 10.0 I infer either SQL Server 2008 or SQL Server 2008 R2.

There are a few possible things to check, but I would check to see if 'priority boost' was configured on the SQL Server. This is a deprecated setting and will eventually be removed. The problem is that it can rob the operating system of needed resources. See the notes at:

http://msdn.microsoft.com/en-in/library/ms180943(v=SQL.105).aspx

If 'priority boost' has been configured to 1, then get it configured back to 0.

exec sp_configure 'priority boost', 0;
RECONFIGURE;

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I resolved this issue by adding jackson-json data binding to my pom.

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.3</version>
</dependency>

SQL - Select first 10 rows only?

Oracle

WHERE ROWNUM <= 10  and whatever_else ;

ROWNUM is a magic variable which contains each row's sequence number 1..n.

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

Kindly delele all folders under the in /.graddle/version/

This is how i solved mine. good luck

SQL query for today's date minus two months

SELECT COUNT(1) FROM FB 
WHERE Dte > DATE_SUB(now(), INTERVAL 2 MONTH)

Push an associative item into an array in JavaScript

JavaScript has associative arrays.

Here is a working snippet.

_x000D_
_x000D_
<script type="text/javascript">
  var myArray = [];
  myArray['thank'] = 'you';
  myArray['no'] = 'problem';
  console.log(myArray);
</script>
_x000D_
_x000D_
_x000D_

They are simply called objects.

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

class HealthConditions extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

jQuery: If this HREF contains

Try this:

$("a").each(function() {
    if ($('[href$="?"]', this).length()) {
        alert("Contains questionmark");
    }
});

How to clear Route Caching on server: Laravel 5.2.37

If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.

php artisan cache:clear

php artisan route:cache

It should work.

The first day of the current month in php using date_modify as DateTime object

You can do it like this:

$firstday = date_create()->modify('first day January 2010');

How do I add a ToolTip to a control?

I did it this way: Just add the event to any control, set the control's tag, and add a conditional to handle the tooltip for the appropriate control/tag.

private void Info_MouseHover(object sender, EventArgs e)
{
    Control senderObject = sender as Control;
    string hoveredControl = senderObject.Tag.ToString();

    // only instantiate a tooltip if the control's tag contains data
    if (hoveredControl != "")
    {
        ToolTip info = new ToolTip
        {
            AutomaticDelay = 500
        };

        string tooltipMessage = string.Empty;

        // add all conditionals here to modify message based on the tag 
        // of the hovered control
        if (hoveredControl == "save button")
        {
            tooltipMessage = "This button will save stuff.";
        }

        info.SetToolTip(senderObject, tooltipMessage);
    }
}

How do I deal with installing peer dependencies in Angular CLI?

Peer dependency warnings, more often than not, can be ignored. The only time you will want to take action is if the peer dependency is missing entirely, or if the version of a peer dependency is higher than the version you have installed.

Let's take this warning as an example:

npm WARN @angular/[email protected] requires a peer of @angular/[email protected] but none is installed. You must install peer dependencies yourself.

With Angular, you would like the versions you are using to be consistent across all packages. If there are any incompatible versions, change the versions in your package.json, and run npm install so they are all synced up. I tend to keep my versions for Angular at the latest version, but you will need to make sure your versions are consistent for whatever version of Angular you require (which may not be the most recent).

In a situation like this:

npm WARN [email protected] requires a peer of @angular/core@^2.4.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.

If you are working with a version of Angular that is higher than 4.0.0, then you will likely have no issues. Nothing to do about this one then. If you are using an Angular version under 2.4.0, then you need to bring your version up. Update the package.json, and run npm install, or run npm install for the specific version you need. Like this:

npm install @angular/[email protected] --save

You can leave out the --save if you are running npm 5.0.0 or higher, that version saves the package in the dependencies section of the package.json automatically.

In this situation:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

You are running Windows, and fsevent requires OSX. This warning can be ignored.

Hope this helps, and have fun learning Angular!

Accessing the index in 'for' loops?

If I were to iterate nums = [1, 2, 3, 4, 5] I would do

for i, num in enumerate(nums, start=1):
    print(i, num)

Or get the length as l = len(nums)

for i in range(l):
    print(i+1, nums[i])