Programs & Examples On #Location aware

CodeIgniter Active Record - Get number of returned rows

function getCount(){
    return $this->db->get('table_name')->num_rows();
}

Add a new item to recyclerview programmatically?

simply add to your data structure ( mItems ) , and then notify your adapter about dataset change

private void addItem(String item) {
  mItems.add(item);
  mAdapter.notifyDataSetChanged();
}

addItem("New Item");

php variable in html no other way than: <?php echo $var; ?>

In a php section before the HTML section, use sprinf() to create a constant string from the variables:

$mystuff = sprinf("My name is %s and my mother's name is %s","Suzy","Caroline");

Then in the HTML section you can do whatever you like, such as:

<p>$mystuff</p> 

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

How to create a GUID in Excel?

=CONCATENATE(
    DEC2HEX(RANDBETWEEN(0;4294967295);8);"-";
    DEC2HEX(RANDBETWEEN(0;42949);4);"-";
    DEC2HEX(RANDBETWEEN(0;42949);4);"-";
    DEC2HEX(RANDBETWEEN(0;42949);4);"-";
    DEC2HEX(RANDBETWEEN(0;4294967295);8);
    DEC2HEX(RANDBETWEEN(0;42949);4)
)

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

You can use auto in data placement like data-placement="auto left". It will automatic adjust according to your screen size and default placement will be left.

dynamic_cast and static_cast in C++

No, not easily. The compiler assigns a unique identity to every class, that information is referenced by every object instance, and that is what gets inspected at runtime to determine if a dynamic cast is legal. You could create a standard base class with this information and operators to do the runtime inspection on that base class, then any derived class would inform the base class of its place in the class hierarchy and any instances of those classes would be runtime-castable via your operations.

edit

Here's an implementation that demonstrates one technique. I'm not claiming the compiler uses anything like this, but I think it demonstrates the concepts:

class SafeCastableBase
{
public:
    typedef long TypeID;
    static TypeID s_nextTypeID;
    static TypeID GetNextTypeID()
    {
        return s_nextTypeID++;
    }
    static TypeID GetTypeID()
    {
        return 0;
    }
    virtual bool CanCastTo(TypeID id)
    {
        if (GetTypeID() != id) { return false; }
        return true;
    }
    template <class Target>
    static Target *SafeCast(SafeCastableBase *pSource)
    {
        if (pSource->CanCastTo(Target::GetTypeID()))
        {
            return (Target*)pSource;
        }
        return NULL;
    }
};
SafeCastableBase::TypeID SafeCastableBase::s_nextTypeID = 1;

class TypeIDInitializer
{
public:
    TypeIDInitializer(SafeCastableBase::TypeID *pTypeID)
    {
        *pTypeID = SafeCastableBase::GetNextTypeID();
    }
};

class ChildCastable : public SafeCastableBase
{
public:
    static TypeID s_typeID;
    static TypeID GetTypeID()
    {
        return s_typeID;
    }
    virtual bool CanCastTo(TypeID id)
    {
        if (GetTypeID() != id) { return SafeCastableBase::CanCastTo(id); }
        return true;
    }
};
SafeCastableBase::TypeID ChildCastable::s_typeID;

TypeIDInitializer ChildCastableInitializer(&ChildCastable::s_typeID);

class PeerChildCastable : public SafeCastableBase
{
public:
    static TypeID s_typeID;
    static TypeID GetTypeID()
    {
        return s_typeID;
    }
    virtual bool CanCastTo(TypeID id)
    {
        if (GetTypeID() != id) { return SafeCastableBase::CanCastTo(id); }
        return true;
    }
};
SafeCastableBase::TypeID PeerChildCastable::s_typeID;

TypeIDInitializer PeerChildCastableInitializer(&PeerChildCastable::s_typeID);

int _tmain(int argc, _TCHAR* argv[])
{
    ChildCastable *pChild = new ChildCastable();
    SafeCastableBase *pBase = new SafeCastableBase();
    PeerChildCastable *pPeerChild = new PeerChildCastable();
    ChildCastable *pSameChild = SafeCastableBase::SafeCast<ChildCastable>(pChild);
    SafeCastableBase *pBaseToChild = SafeCastableBase::SafeCast<SafeCastableBase>(pChild);
    ChildCastable *pNullDownCast = SafeCastableBase::SafeCast<ChildCastable>(pBase);
    SafeCastableBase *pBaseToPeerChild = SafeCastableBase::SafeCast<SafeCastableBase>(pPeerChild);
    ChildCastable *pNullCrossCast = SafeCastableBase::SafeCast<ChildCastable>(pPeerChild);
    return 0;
}

Entity framework self referencing loop detected

The message error means that you have a self referencing loop.

The json you produce is like this example (with a list of one employee) :

[
employee1 : {
    name: "name",
    department : {
        name: "departmentName",
        employees : [
            employee1 : {
                name: "name",
                department : {
                    name: "departmentName",
                    employees : [
                        employee1 : {
                            name: "name",
                            department : {
                                and again and again....
                            }
                    ]
                }
            }
        ]
    }
}

]

You have to tell the db context that you don't want to get all linked entities when you request something. The option for DbContext is Configuration.LazyLoadingEnabled

The best way I found is to create a context for serialization :

public class SerializerContext : LabEntities 
{
    public SerializerContext()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }
}

How do I set the time zone of MySQL?

To set the standard time zone at MariaDB you have to go to the 50-server.cnf file.

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Then you can enter the following entry in the mysqld section.

default-time-zone='+01:00'

Example:

#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
# See the examples of server my.cnf files in /usr/share/mysql/
#

# this is read by the standalone daemon and embedded servers
[server]

# this is only for the mysqld standalone daemon
[mysqld]

#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking

### Default timezone ###
default-time-zone='+01:00'

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.

The change must be made via the configuration file, otherwise the MariaDB server will reset the mysql tables after a restart!

Why does this code using random strings print "hello world"?

I'll just leave it here. Whoever has a lot of (CPU) time to spare, feel free to experiment :) Also, if you have mastered some fork-join-fu to make this thing burn all CPU cores (just threads are boring, right?), please share your code. I would greatly appreciate it.

public static void main(String[] args) {
    long time = System.currentTimeMillis();
    generate("stack");
    generate("over");
    generate("flow");
    generate("rulez");

    System.out.println("Took " + (System.currentTimeMillis() - time) + " ms");
}

private static void generate(String goal) {
    long[] seed = generateSeed(goal, Long.MIN_VALUE, Long.MAX_VALUE);
    System.out.println(seed[0]);
    System.out.println(randomString(seed[0], (char) seed[1]));
}

public static long[] generateSeed(String goal, long start, long finish) {
    char[] input = goal.toCharArray();
    char[] pool = new char[input.length];
    label:
    for (long seed = start; seed < finish; seed++) {
        Random random = new Random(seed);

        for (int i = 0; i < input.length; i++)
            pool[i] = (char) random.nextInt(27);

        if (random.nextInt(27) == 0) {
            int base = input[0] - pool[0];
            for (int i = 1; i < input.length; i++) {
                if (input[i] - pool[i] != base)
                    continue label;
            }
            return new long[]{seed, base};
        }

    }

    throw new NoSuchElementException("Sorry :/");
}

public static String randomString(long i, char base) {
    System.out.println("Using base: '" + base + "'");
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    for (int n = 0; ; n++) {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char) (base + k));
    }

    return sb.toString();
}

Output:

-9223372036808280701
Using base: 'Z'
stack
-9223372036853943469
Using base: 'b'
over
-9223372036852834412
Using base: 'e'
flow
-9223372036838149518
Using base: 'd'
rulez
Took 7087 ms

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

  1. Add ssh public key to Google cloud
  • cat ~/.ssh/id_rsa.pub
  • go and click your VM instances
  • edit VM instances
  • add ssh public key(from id_rsa.pub) in SSH keys area toptruyenfull.com enter image description here enter image description here enter image description here enter image description hereenter image description here
  1. ssh login from Git bash on your computer

    ssh -i ~/.ssh/id_rsa [email protected]

Invalid Host Header when ngrok tries to connect to React dev server

If you use webpack devServer the simplest way is to set disableHostCheck, check webpack doc like this

devServer: {
    contentBase: path.join(__dirname, './dist'),
    compress: true,
    host: 'localhost',
    // host: '0.0.0.0',
    port: 8080,
    disableHostCheck: true //for ngrok
},

Count number of lines in a git repository

I've encountered batching problems with git ls-files | xargs wc -l when dealing with large numbers of files, where the line counts will get chunked out into multiple total lines.

Taking a tip from question Why does the wc utility generate multiple lines with "total"?, I've found the following command to bypass the issue:

wc -l $(git ls-files)

Or if you want to only examine some files, e.g. code:

wc -l $(git ls-files | grep '.*\.cs')

Custom Adapter for List View

Here is the complete walk through to create a custom adapter for list view step by step -

https://www.caveofprogramming.com/guest-posts/custom-listview-with-imageview-and-textview-in-android.html

public class CustomAdapter extends BaseAdapter{   
    String [] result;
    Context context;
 int [] imageId;
      private static LayoutInflater inflater=null;
    public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
        // TODO Auto-generated constructor stub
        result=prgmNameList;
        context=mainActivity;
        imageId=prgmImages;
         inflater = ( LayoutInflater )context.
                 getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return result.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class Holder
    {
        TextView tv;
        ImageView img;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        Holder holder=new Holder();
        View rowView;       
             rowView = inflater.inflate(R.layout.program_list, null);
             holder.tv=(TextView) rowView.findViewById(R.id.textView1);
             holder.img=(ImageView) rowView.findViewById(R.id.imageView1);       
         holder.tv.setText(result[position]);
         holder.img.setImageResource(imageId[position]);         
         rowView.setOnClickListener(new OnClickListener() {            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
            }
        });   
        return rowView;
    }

} 

What is the proper way to display the full InnerException?

You can simply print exception.ToString() -- that will also include the full text for all the nested InnerExceptions.

Is it ok to run docker from inside docker?

Running Docker inside Docker (a.k.a. dind), while possible, should be avoided, if at all possible. (Source provided below.) Instead, you want to set up a way for your main container to produce and communicate with sibling containers.

Jérôme Petazzoni — the author of the feature that made it possible for Docker to run inside a Docker container — actually wrote a blog post saying not to do it. The use case he describes matches the OP's exact use case of a CI Docker container that needs to run jobs inside other Docker containers.

Petazzoni lists two reasons why dind is troublesome:

  1. It does not cooperate well with Linux Security Modules (LSM).
  2. It creates a mismatch in file systems that creates problems for the containers created inside parent containers.

From that blog post, he describes the following alternative,

[The] simplest way is to just expose the Docker socket to your CI container, by bind-mounting it with the -v flag.

Simply put, when you start your CI container (Jenkins or other), instead of hacking something together with Docker-in-Docker, start it with:

docker run -v /var/run/docker.sock:/var/run/docker.sock ...

Now this container will have access to the Docker socket, and will therefore be able to start containers. Except that instead of starting "child" containers, it will start "sibling" containers.

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

How to split a comma separated string and process in a loop using JavaScript

Please run below code may it helps you :)

_x000D_
_x000D_
var str = "this,is,an,example";_x000D_
var strArr = str.split(',');_x000D_
var data = "";_x000D_
for(var i=0; i<strArr.length; i++){_x000D_
  data += "Index : "+i+" value : "+strArr[i]+"<br/>";_x000D_
}_x000D_
document.getElementById('print').innerHTML = data;
_x000D_
<div id="print">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Set initial focus in an Android application

@Someone Somewhere, I tried all of the above to no avail. The fix I found is from http://www.helloandroid.com/tutorials/remove-autofocus-edittext-android . Basically, you need to create an invisible layout just above the problematic Button:

<LinearLayout android:focusable="true"
              android:focusableInTouchMode="true" 
              android:layout_width="0px"
              android:layout_height="0px" >
    <requestFocus />
</LinearLayout>

Modify XML existing content in C#

Using LINQ to xml if you are using framework 3.5

using System.Xml.Linq;

XDocument xmlFile = XDocument.Load("books.xml"); 
var query = from c in xmlFile.Elements("catalog").Elements("book")    
            select c; 
foreach (XElement book in query) 
{
    book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

First the mysqldump command is executed and the output generated is redirected using the pipe. The pipe is sending the standard output into the gzip command as standard input. Following the filename.gz, is the output redirection operator (>) which is going to continue redirecting the data until the last filename, which is where the data will be saved.

For example, this command will dump the database and run it through gzip and the data will finally land in three.gz

mysqldump -u user -pupasswd my-database | gzip > one.gz > two.gz > three.gz

$> ls -l
-rw-r--r--  1 uname  grp     0 Mar  9 00:37 one.gz
-rw-r--r--  1 uname  grp  1246 Mar  9 00:37 three.gz
-rw-r--r--  1 uname  grp     0 Mar  9 00:37 two.gz

My original answer is an example of redirecting the database dump to many compressed files (without double compressing). (Since I scanned the question and seriously missed - sorry about that)

This is an example of recompressing files:

mysqldump -u user -pupasswd my-database | gzip -c > one.gz; gzip -c one.gz > two.gz; gzip -c two.gz > three.gz

$> ls -l
-rw-r--r--  1 uname  grp  1246 Mar  9 00:44 one.gz
-rw-r--r--  1 uname  grp  1306 Mar  9 00:44 three.gz
-rw-r--r--  1 uname  grp  1276 Mar  9 00:44 two.gz

This is a good resource explaining I/O redirection: http://www.codecoffee.com/tipsforlinux/articles2/042.html

How can I solve equations in Python?

Use a different tool. Something like Wolfram Alpha, Maple, R, Octave, Matlab or any other algebra software package.

As a beginner you should probably not attempt to solve such a non-trivial problem.

When to use static methods

Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.

How to submit http form using C#

I needed to have a button handler that created a form post to another application within the client's browser. I landed on this question but didn't see an answer that suited my scenario. This is what I came up with:

      protected void Button1_Click(object sender, EventArgs e)
        {

            var formPostText = @"<html><body><div>
<form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
  <input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" /> 
  <input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" /> 
</form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
";
            Response.Write(formPostText);
        }

How do we check if a pointer is NULL pointer?

Apparently the thread you refer is about C++.

In C your snippet will always work. I like the simpler if (p) { /* ... */ }.

How do I force "git pull" to overwrite local files?

I know of a much easier and less painful method:

$ git branch -m [branch_to_force_pull] tmp
$ git fetch
$ git checkout [branch_to_force_pull]
$ git branch -D tmp

That's it!

How do I select an element with its name attribute in jQuery?

You could always do $('input[name="somename"]')

What does the 'b' character do in front of a string literal?

You can use JSON to convert it to dictionary

import json
data = b'{"key":"value"}'
print(json.loads(data))

{"key":"value"}


FLASK:

This is an example from flask. Run this on terminal line:

import requests
requests.post(url='http://localhost(example)/',json={'key':'value'})

In flask/routes.py

@app.route('/', methods=['POST'])
def api_script_add():
    print(request.data) # --> b'{"hi":"Hello"}'
    print(json.loads(request.data))
return json.loads(request.data)

{'key':'value'}

What are the differences between LDAP and Active Directory?

active directory is the directory service database to store the organizational based data,policy,authentication etc whereas ldap is the protocol used to talk to the directory service database that is ad or adam.

Are HTTP cookies port specific?

In IE 8, cookies (verified only against localhost) are shared between ports. In FF 10, they are not.

I've posted this answer so that readers will have at least one concrete option for testing each scenario.

Is there something like Codecademy for Java

Check out CodingBat! It really helped me learn java way back when (although it used to be JavaBat back then). It's a lot like Codecademy.

Semi-transparent color layer over background-image?

You can also use a linear gradient and an image: http://codepen.io/anon/pen/RPweox

.background{
  background: linear-gradient(rgba(0,0,0,.5), rgba(0,0,0,.5)),
    url('http://www.imageurl.com');
}

This is because the linear gradient function creates an Image which is added to the background stack. https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient

Android Studio: Unable to start the daemon process

Try this... I have tried and work fine for me

This issue is related to low memory...

Close your browsers, visual Studio and other services..

after that run following command

ionic build android 

it will run successfully..

//Solutions is
create "gradle.properties" file in android folder and add following line into file
org.gradle.jvmargs=-Xmx512m -XX:MaxPermSize=512m

<your project>\platforms\android\gradle.properties

You can open browser and others..

ionic build android

Now it will work fine.

C# Break out of foreach loop after X number of items

Or just use a regular for loop instead of foreach. A for loop is slightly faster (though you won't notice the difference except in very time critical code).

Rename computer and join to domain in one step with PowerShell

Also add local account + rename computer at prompt + join to domain at promt

#Set A local admin account
$computername = $env:computername   # place computername here for remote access
$username = 'localadmin'
$password = 'P@ssw0rd1'
$desc = 'Local admin account'
$computer = [ADSI]"WinNT://$computername,computer"
$user = $computer.Create("user", $username)
$user.SetPassword($password)
$user.Setinfo()
$user.description = $desc
$user.setinfo()
$user.UserFlags = 65536
$user.SetInfo()
$group = [ADSI]("WinNT://$computername/administrators,group")
$group.add("WinNT://$username,user")

# Set computer name 
$computerName = Get-WmiObject Win32_ComputerSystem 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$name = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Desired Computer Name ")
$computername.rename("$name")

#Now Join to Domain
Add-Computer -DomainName [domainname] -Credential [user\domain]  -Verbose
Restart-Computer

Why is Android Studio reporting "URI is not registered"?

I had this problem and for me it was due to creating and manipulating resource files outside Android Studio. I followed the instructions on creating new resource files and folders through Android Studio and solved the problem. You need to create a new Resource File Not directory. It will let you specify or create a directory for you if you need it. If you are creating directories for layouts for different versions, enter the info at the top including the name of the resource file you want to copy to the new folder and select Version and enter the Android version. It will create the appropriate directory with a copy of your resource in it.

React.createElement: type is invalid -- expected a string

In simply words, somehow the following is happening:

render() {
    return (
        <MyComponent /> // MyComponent is undefined.
    );
}

It may not necessarily be related with some incorrect import or export:

render() {
    // MyComponent may be undefined here, for example.
    const MyComponent = this.wizards[this.currentStep];

    return (
        <MyComponent />
    );
}

How to speed up insertion performance in PostgreSQL

Use COPY table TO ... WITH BINARY which is according to the documentation is "somewhat faster than the text and CSV formats." Only do this if you have millions of rows to insert, and if you are comfortable with binary data.

Here is an example recipe in Python, using psycopg2 with binary input.

How to use the ConfigurationManager.AppSettings

Your web.config file should have this structure:

<configuration>
    <connectionStrings>
        <add name="MyConnectionString" connectionString="..." />
    </connectionStrings>
</configuration>

Then, to create a SQL connection using the connection string named MyConnectionString:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

If you'd prefer to keep your connection strings in the AppSettings section of your configuration file, it would look like this:

<configuration>
    <appSettings>
        <add key="MyConnectionString" value="..." />
    </appSettings>
</configuration>

And then your SqlConnection constructor would look like this:

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);

how to fire event on file select

<input id="fusk" type="file" name="upload" style="display: none;"
    onChange=" document.getElementById('myForm').submit();"
>

JPA & Criteria API - Select only specific columns

First of all, I don't really see why you would want an object having only ID and Version, and all other props to be nulls. However, here is some code which will do that for you (which doesn't use JPA Em, but normal Hibernate. I assume you can find the equivalence in JPA or simply obtain the Hibernate Session obj from the em delegate Accessing Hibernate Session from EJB using EntityManager ):

List<T> results = session.createCriteria(entityClazz)
    .setProjection( Projections.projectionList()
        .add( Property.forName("ID") )
        .add( Property.forName("VERSION") )
    )
    .setResultTransformer(Transformers.aliasToBean(entityClazz); 
    .list();

This will return a list of Objects having their ID and Version set and all other props to null, as the aliasToBean transformer won't be able to find them. Again, I am uncertain I can think of a situation where I would want to do that.

Detecting Browser Autofill

In Chrome and Edge (2020) checking for :-webkit-autofill will tell you that the inputs have been filled. However, until the user interacts with the page in some way, your JavaScript cannot get the values in the inputs.

Using $('x').focus() and $('x').blur() or triggering a mouse event in code don't help.

See https://stackoverflow.com/a/35783761/32429

How to establish a connection pool in JDBC?

In late 2017 Proxool, BoneCP, C3P0, DBCP are mostly defunct at this time. HikariCP (created in 2012) seems promising, blows the doors off anything else I know of. http://www.baeldung.com/hikaricp

Proxool has a number of issues:
- Under heavy load can exceed max number of connections and not return below max
- Can manage to not return to min connections even after connections expire
- Can lock up the entire pool (and all server/client threads) if it has trouble connecting to the database during HouseKeeper thread (does not use .setQueryTimeout)
- HouseKeeper thread, while having connection pool lock for its process, requests the Prototyper thread to recreate connections (sweep) which can result in race condition/lockup. In these method calls the last parameter should always be sweep:false during the loop, only sweep:true below it.
- HouseKeeper only needs the single PrototypeController sweep at the end and has more [mentioned above]
- HouseKeeper thread checks for testing of connections before seeing what connections may be expired [some risk of testing expired connection that may be broken/terminated through other timeouts to DB in firewall, etc.]
- The project has unfinished code (properties that are defined but not acted upon)
- The Default max connection life if not defined is 4 hours (excessive)
- HouseKeeper thread runs every five seconds per pool (excessive)

You can modify the code and make these improvements. But as it was created in 2003, and updated in 2008, its lacking nearly 10 years of java improvements that solutions like hikaricp utilize.

What is the equivalent of "none" in django templates?

Look at the yesno helper

Eg:

{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}

Share cookie between subdomain and domain

Please everyone note that you can set a cookie from a subdomain on a domain.

(sent in the response for requesting subdomain.mydomain.com)

Set-Cookie: name=value; Domain=mydomain.com // GOOD

But you CAN'T set a cookie from a domain on a subdomain.

(sent in the response for requesting mydomain.com)

Set-Cookie: name=value; Domain=subdomain.mydomain.com // Browser rejects cookie

WHY ?

According to the specifications RFC 6265 section 5.3.6 Storage Model

If the canonicalized request-host does not domain-match the domain-attribute: Ignore the cookie entirely and abort these steps.

and RFC 6265 section 5.1.3 Domain Matching

Domain Matching

A string domain-matches a given domain string if at least one of the following conditions hold:

  1. The domain string and the string are identical. (Note that both the domain string and the string will have been canonicalized to lower case at this point.)

  2. All of the following conditions hold:

    • The domain string is a suffix of the string.

    • The last character of the string that is not included in the domain string is a %x2E (".") character.

    • The string is a host name (i.e., not an IP address).

So "subdomain.mydomain.com" domain-matches "mydomain.com", but "mydomain.com" does NOT domain-match "subdomain.mydomain.com"

Check this answer also.

How do you do block comments in YAML?

In .gitlab-ci.yml file following works::

To comment out a block (multiline): Select the whole block section > Ctrl K C

To uncomment already commented out block (multiline): Select the whole block section > Ctrl K U

How to change CSS using jQuery?

To clear things up a little, since some of the answers are providing incorrect information:


The jQuery .css() method allows the use of either DOM or CSS notation in many cases. So, both backgroundColor and background-color will get the job done.

Additionally, when you call .css() with arguments you have two choices as to what the arguments can be. They can either be 2 comma separated strings representing a css property and its value, or it can be a Javascript object containing one or more key value pairs of CSS properties and values.

In conclusion the only thing wrong with your code is a missing }. The line should read:

$("#myParagraph").css({"backgroundColor":"black","color":"white"});

You cannot leave the curly brackets out, but you may leave the quotes out from around backgroundColor and color. If you use background-color you must put quotes around it because of the hyphen.

In general, it's a good habit to quote your Javascript objects, since problems can arise if you do not quote an existing keyword.


A final note is that about the jQuery .ready() method

$(handler);

is synonymous with:

$(document).ready(handler);

as well as with a third not recommended form.

This means that $(init) is completely correct, since init is the handler in that instance. So, init will be fired when the DOM is constructed.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

My Mac OS didn't like that it didn't find the env variable set in the settings file:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('MY_SERVER_ENV_VAR_NAME')

but after adding the env var to my local Mac OS dev environment, the error disappeared:

export MY_SERVER_ENV_VAR_NAME ='fake dev security key that is longer than 50 characters.'

In my case, I also needed to add the --settings param:

python3 manage.py check --deploy --settings myappname.settings.production

where production.py is a file containing production specific settings inside a settings folder.

How to run test methods in specific order in JUnit4?

If you get rid of your existing instance of Junit, and download JUnit 4.11 or greater in the build path, the following code will execute the test methods in the order of their names, sorted in ascending order:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SampleTest {

    @Test
    public void testAcreate() {
        System.out.println("first");
    }
    @Test
    public void testBupdate() {
        System.out.println("second");
    }
    @Test
    public void testCdelete() {
        System.out.println("third");
    }
}

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

You might have not copied the MySQL connector/J jar file into the lib folder and then this file has to be there in the classpath.

If you have not done so, please let me know I shall elaborate the answer

How to iterate over the file in python

with open('test.txt', 'r') as inf, open('test1.txt', 'w') as outf:
    for line in inf:
        line = line.strip()
        if line:
            try:
                outf.write(str(int(line, 16)))
                outf.write('\n')
            except ValueError:
                print("Could not parse '{0}'".format(line))

How to get some values from a JSON string in C#?

Following code is working for me.

Usings:

using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;

Code:

 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            string json = responseReader.ReadToEnd();
                            string data = JObject.Parse(json)["id"].ToString();
                        }
                    }
                }

//json = {"kind": "ALL", "id": "1221455", "longUrl": "NewURL"}

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

Your module and your class AthleteList have the same name. The line

import AthleteList

imports the module and creates a name AthleteList in your current scope that points to the module object. If you want to access the actual class, use

AthleteList.AthleteList

In particular, in the line

return(AthleteList(templ.pop(0), templ.pop(0), templ))

you are actually accessing the module object and not the class. Try

return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))

Javascript checkbox onChange

try

totalCost.value = checkbox.checked ? 10 : calculate();

_x000D_
_x000D_
function change(checkbox) {_x000D_
  totalCost.value = checkbox.checked ? 10 : calculate();_x000D_
}_x000D_
_x000D_
function calculate() {_x000D_
  return other.value*2;_x000D_
}
_x000D_
input { display: block}
_x000D_
Checkbox: <input type="checkbox" onclick="change(this)"/>_x000D_
Total cost: <input id="totalCost" type="number" value=5 />_x000D_
Other: <input id="other" type="number" value=7 />
_x000D_
_x000D_
_x000D_

How to get video duration, dimension and size in PHP?

https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...

<?php
        require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);

        $width=$fileinfo['video']['resolution_x'];
        $height=$fileinfo['video']['resolution_y'];

        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '<pre>';print_r($fileinfo);echo '</pre>';
?>

How can I export data to an Excel file

I was also struggling with a similar issue dealing with exporting data into an Excel spreadsheet using C#. I tried many different methods working with external DLLs and had no luck.

For the export functionality you do not need to use anything dealing with the external DLLs. Instead, just maintain the header and content type of the response.

Here is an article that I found rather helpful. The article talks about how to export data to Excel spreadsheets using ASP.NET.

http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c-sharp.html

JavaScript URL Decode function

//How decodeURIComponent Works

function proURIDecoder(val)
{
  val=val.replace(/\+/g, '%20');
  var str=val.split("%");
  var cval=str[0];
  for (var i=1;i<str.length;i++)
  {
    cval+=String.fromCharCode(parseInt(str[i].substring(0,2),16))+str[i].substring(2);
  }

  return cval;
}

document.write(proURIDecoder(window.location.href));

SQL Case Sensitive String Compare

You can also convert that attribute as case sensitive using this syntax :

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CS_AS

Now your search will be case sensitive.

If you want to make that column case insensitive again, then use

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CI_AS

How do I use HTML as the view engine in Express?

HTML files can be rendered using ejs engine:

app.set('view engine', 'ejs');

And make sure your files under "/views" are named with ".ejs".

For example "index.ejs".

Do you (really) write exception safe code?

I try my darned best to write exception-safe code, yes.

That means I take care to keep an eye on which lines can throw. Not everyone can, and it is critically important to keep that in mind. The key is really to think about, and design your code to satisfy, the exception guarantees defined in the standard.

Can this operation be written to provide the strong exception guarantee? Do I have to settle for the basic one? Which lines may throw exceptions, and how can I ensure that if they do, they don't corrupt the object?

CSS : center form in page horizontally and vertically

you can use display:flex to do this : http://codepen.io/anon/pen/yCKuz

html,body {
  height:100%;
  width:100%;
  margin:0;
}
body {
  display:flex;
}
form {
  margin:auto;/* nice thing of auto margin if display:flex; it center both horizontal and vertical :) */
}

or display:table http://codepen.io/anon/pen/LACnF/

body, html {   
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    display:table;
}
body {
    display:table-cell;
    vertical-align:middle;
}
form {
    display:table;/* shrinks to fit content */
    margin:auto;
}

Android Stop Emulator from Command Line

To automate this, you can use any script or app that can send a string to a socket. I personally like nc (netcat) under cygwin. As I said before, I use it like this:

$ echo kill | nc -w 2 localhost 5554

(that means to send "kill" string to the port 5554 on localhost, and terminate netcat after 2 seconds.)

jQuery: get data attribute

1. Try this: .attr()

  $('.field').hover(function () {
    var value=$(this).attr('data-fullText');
  $(this).html(value);
});

DEMO 1: http://jsfiddle.net/hsakapandit/Jn4V3/

2. Try this: .data()

$('.field').hover(function () {
    var value=$(this).data('fulltext');
  $(this).html(value);
});

DEMO 2: http://jsfiddle.net/hsakapandit/Jn4V3/1/

How to send image to PHP file using Ajax?

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('#abc').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            url: 'post.php',
            method:'POST',
            data: new FormData(this),
            contentType: false,
            cache:false,
            processData:false,
            success: function (data) {
              alert(data);
              location.reload();
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form enctype= "multipart/form-data" id="abc">
      <input name="fname" ><br>
      <input name="lname"><br>
      <input type="file" name="file" required=""><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

JavaFX and OpenJDK

As a quick solution you can copy the JavaFX runtime JAR file and those referenced from Oracle JRE(JDK) or any self-contained application that uses JavaFX(e.g. JavaFX Scene Builder 2.0):

cp <JRE_WITH_JAVAFX_HOME>/lib/ext/jfxrt.jar     <JRE_HOME>/lib/ext/
cp <JRE_WITH_JAVAFX_HOME>/lib/javafx.properties <JRE_HOME>/lib/
cp <JRE_WITH_JAVAFX_HOME>/lib/amd64/libprism_*  <JRE_HOME>/lib/amd64/
cp <JRE_WITH_JAVAFX_HOME>/lib/amd64/libglass.so <JRE_HOME>/lib/amd64/
cp <JRE_WITH_JAVAFX_HOME>/lib/amd64/libjavafx_* <JRE_HOME>/lib/amd64/

just make sure you have the gtk 2.18 or higher

How to write a unit test for a Spring Boot Controller endpoint

Here is another answer using Spring MVC's standaloneSetup. Using this way you can either autowire the controller class or Mock it.

    import static org.mockito.Mockito.mock;
    import static org.springframework.test.web.server.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.server.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.server.result.MockMvcResultMatchers.status;

    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.http.MediaType;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.web.server.MockMvc;
    import org.springframework.test.web.server.setup.MockMvcBuilders;


    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class DemoApplicationTests {

        final String BASE_URL = "http://localhost:8080/";

        @Autowired
        private HelloWorld controllerToTest;

        private MockMvc mockMvc;

        @Before
        public void setup() {
            this.mockMvc = MockMvcBuilders.standaloneSetup(controllerToTest).build();
        }

        @Test
        public void testSayHelloWorld() throws Exception{
            //Mocking Controller
            controllerToTest = mock(HelloWorld.class);

             this.mockMvc.perform(get("/")
                     .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                     .andExpect(status().isOk())
                     .andExpect(content().mimeType(MediaType.APPLICATION_JSON));
        }

        @Test
        public void contextLoads() {
        }

    }

Convert Mat to Array/Vector in OpenCV

You can use iterators:

Mat matrix = ...;

std::vector<float> vec(matrix.begin<float>(), matrix.end<float>());

In Java, how to find if first character in a string is upper case without regex

Make sure you first check for null and empty and ten converts existing string to upper. Use S.O.P if want to see outputs otherwise boolean like Rabiz did.

 public static void main(String[] args)
 {
     System.out.println("Enter name");
     Scanner kb = new Scanner (System.in);
     String text =  kb.next();

     if ( null == text || text.isEmpty())
     {
         System.out.println("Text empty");
     }
     else if (text.charAt(0) == (text.toUpperCase().charAt(0)))
     {
         System.out.println("First letter in word "+ text + " is upper case");
     }
  }

How to use JQuery with ReactJS

Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-

  1. npm install jquery --save

  2. Then, import $ from "jquery";

    See here

ImportError: No module named sklearn.cross_validation

If you have code that needs to run various versions you could do something like this:

import sklearn
if sklearn.__version__ > '0.18':
    from sklearn.model_selection import train_test_split
else:
    from sklearn.cross_validation import train_test_split

This isn't ideal though because you're comparing package versions as strings, which usually works but doesn't always. If you're willing to install packaging, this is a much better approach:

from packaging.version import parse
import sklearn
if parse(sklearn.__version__) > parse('0.18'):
    from sklearn.model_selection import train_test_split
else:
    from sklearn.cross_validation import train_test_split

How to create a date and time picker in Android?

Another option is the android-wheel project that comes pretty close the the UIDatePicker dialog of iOS.

It provides a vertical slider to pick anything(including date and time). If you prefer horizontal slider, the DateSlider referenced by Rabi is better.

jQuery .val change doesn't change input value

Use attr instead.
$('#link').attr('value', 'new value');

demo

How to open a web server port on EC2 instance

You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-

  1. On the Start menu, click Run, type WF.msc, and then click OK.
  2. In the Windows Firewall with Advanced Security, in the left pane, right-click Inbound Rules, and then click New Rule in the action pane.
  3. In the Rule Type dialog box, select Port, and then click Next.
  4. In the Protocol and Ports dialog box, select TCP. Select Specific local ports, and then type the port number , such as 8787 for the default instance. Click Next.
  5. In the Action dialog box, select Allow the connection, and then click Next.
  6. In the Profile dialog box, select any profiles that describe the computer connection environment when you want to connect , and then click Next.
  7. In the Name dialog box, type a name and description for this rule, and then click Finish.

Ref:- Microsoft Docs for port Opening

Setting Django up to use MySQL

To the very first please run the below commands to install python dependencies otherwise python runserver command will throw error.

sudo apt-get install libmysqlclient-dev
sudo pip install MySQL-python

Then configure the settings.py file as defined by #Andy and at the last execute :

python manage.py runserver

Have fun..!!

Convert Enumeration to a Set/List

If you need Set rather than List, you can use EnumSet.allOf().

Set<EnumerationClass> set = EnumSet.allOf(EnumerationClass.class);

Update: JakeRobb is right. My answer is about java.lang.Enum instead of java.util.Enumeration. Sorry for unrelated answer.

AngularJS - difference between pristine/dirty and touched/untouched

This is a late answer but hope this might help.

Scenario 1: You visited the site for first time and did not touch any field. The state of form is

ng-untouched and ng-pristine

Scenario 2: You are currently entering the values in a particular field in the form. Then the state is

ng-untouched and ng-dirty

Scenario 3: You are done with entering the values in the field and moved to next field

ng-touched and ng-dirty

Scenario 4: Say a form has a phone number field . You have entered the number but you have actually entered 9 digits but there are 10 digits required for a phone number.Then the state is ng-invalid

In short:

ng-untouched:When the form field has not been visited yet

ng-touched: When the form field is visited AND the field has lost focus

ng-pristine: The form field value is not changed

ng-dirty: The form field value is changed

ng-valid : When all validations of form fields are successful

ng-invalid: When all validations of form fields are not successful

How to get sp_executesql result into a variable?

DECLARE @ValueTable TABLE
    (
    Value VARCHAR (100)
    )

SELECT @sql = N'SELECT SRS_SizeSetDetails.'+@COLUMN_NAME+' FROM SRS_SizeSetDetails WHERE FSizeID = '''+@FSizeID+''' AND SRS_SizeSetID = '''+@SRS_SizeSetID+'''';

INSERT INTO @ValueTable
EXEC sp_executesql @sql;

SET @Value='';

SET @Value = (SELECT TOP 1  Value FROM @ValueTable)

DELETE FROM @ValueTable

how to get the last character of a string?

You can get the last char like this :

var lastChar=yourString.charAt(yourString.length-1);

Convert a string to datetime in PowerShell

ParseExact is told the format of the date it is expected to parse, not the format you wish to get out.

$invoice = '01-Jul-16'
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null)

If you then wish to output a date string:

[datetime]::parseexact($invoice, 'dd-MMM-yy', $null).ToString('yyyy-MM-dd')

Chris

jQuery if checkbox is checked

this $('#checkboxId').is(':checked') for verify if is checked

& this $("#checkboxId").prop('checked', true) to check

& this $("#checkboxId").prop('checked', false) to uncheck

Is there a way to collapse all code blocks in Eclipse?

Right click on the +/- sign and click collapse all or expand all.

"And" and "Or" troubles within an IF statement

This is not an answer, but too long for a comment.

In reply to JP's answers / comments, I have run the following test to compare the performance of the 2 methods. The Profiler object is a custom class - but in summary, it uses a kernel32 function which is fairly accurate (Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)).

Sub test()

  Dim origNum As String
  Dim creditOrDebit As String
  Dim b As Boolean
  Dim p As Profiler
  Dim i As Long

  Set p = New_Profiler

  origNum = "30062600006"
  creditOrDebit = "D"

  p.startTimer ("nested_ifs")

  For i = 1 To 1000000

    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        b = True
      ElseIf origNum = "30062600006" Then
        b = True
      End If
    End If

  Next i

  p.stopTimer ("nested_ifs")
  p.startTimer ("or_and")

  For i = 1 To 1000000

    If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
      b = True
    End If

  Next i

  p.stopTimer ("or_and")

  p.printReport

End Sub

The results of 5 runs (in ms for 1m loops):

20-Jun-2012 19:28:25
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:26
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:27
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:28
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 141 - Last Run: 141 - Average Run: 141

20-Jun-2012 19:28:29
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

Note

If creditOrDebit is not "D", JP's code runs faster (around 60ms vs. 125ms for the or/and code).

What is the 'realtime' process priority setting for?

It basically is higher/greater in everything else. A keyboard is less of a priority than the real time process. This means the process will be taken into account faster then keyboard and if it can't handle that, then your keyboard is slowed.

How to position three divs in html horizontally?

I know this is a very old question. Just posting this here as I solved this problem using FlexBox. Here is the solution

_x000D_
_x000D_
#container {
  height: 100%;
  width: 100%;
  display: flex;
}
#leftThing {
  width: 25%;
  background-color: blue;
}
#content {
  width: 50%;
  background-color: green;
}
#rightThing {
  width: 25%;
  background-color: yellow;
}
_x000D_
<div id="container">

  <div id="leftThing">
    Left Side Menu
  </div>

  <div id="content">
    Random Content
  </div>

  <div id="rightThing">
    Right Side Menu
  </div>

</div>
_x000D_
_x000D_
_x000D_

Just had to add display:flex to the container! No floats required.

.keyCode vs. .which

If you are staying in vanilla Javascript, please note keyCode is now deprecated and will be dropped:

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any tim

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

Instead use either: .key or .code depending on what behavior you want: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

Both are implemented on modern browsers.

How to split a string in Haskell?

In addition to the efficient and pre-built functions given in answers I'll add my own which are simply part of my repertory of Haskell functions I was writing to learn the language on my own time:

-- Correct but inefficient implementation
wordsBy :: String -> Char -> [String]
wordsBy s c = reverse (go s []) where
    go s' ws = case (dropWhile (\c' -> c' == c) s') of
        "" -> ws
        rem -> go ((dropWhile (\c' -> c' /= c) rem)) ((takeWhile (\c' -> c' /= c) rem) : ws)

-- Breaks up by predicate function to allow for more complex conditions (\c -> c == ',' || c == ';')
wordsByF :: String -> (Char -> Bool) -> [String]
wordsByF s f = reverse (go s []) where
    go s' ws = case ((dropWhile (\c' -> f c')) s') of
        "" -> ws
        rem -> go ((dropWhile (\c' -> (f c') == False)) rem) (((takeWhile (\c' -> (f c') == False)) rem) : ws)

The solutions are at least tail-recursive so they won't incur a stack overflow.

JavaScript string newline character?

printAccountSummary: function()
        {return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // method

Prints:

Welcome!
Your balance is currently $1000 and your interest rate is 1%.

How do I copy a version of a single file from one git branch to another?

1) Ensure you're in branch where you need a copy of the file. for eg: i want sub branch file in master so you need to checkout or should be in master git checkout master

2) Now checkout specific file alone you want from sub branch into master,

git checkout sub_branch file_path/my_file.ext

here sub_branch means where you have that file followed by filename you need to copy.

slashes in url variables

Check out this w3schools page about "HTML URL Encoding Reference": https://www.w3schools.com/tags/ref_urlencode.asp

for / you would escape with %2F

Provisioning Profiles menu item missing from Xcode 5

Try this:

Xcode >> Preferences >> Accounts

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

$.ajax - dataType

as per docs:

  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "text": A plain text string.

how to bind img src in angular 2 in ngFor?

I hope i am understanding your question correctly, as the above comment says you need to provide more information.

In order to bind it to your view you would use property binding which is using [property]="value". Hope this helps.

<div *ngFor="let student of students">  
 {{student.id}}
 {{student.name}}

 <img [src]="student.image">

</div>  

How to initialize a List<T> to a given size (as opposed to capacity)?

Create an array with the number of items you want first and then convert the array in to a List.

int[] fakeArray = new int[10];

List<int> list = fakeArray.ToList();

Oracle SQL - select within a select (on the same table!)

I'm a bit confused by the quotes, however, below should work for you:

SELECT "Gc_Staff_Number",
       "Start_Date", x.end_date
FROM   "Employment_History" eh,
(SELECT "End_Date"
        FROM   "Employment_History"
        WHERE  "Current_Flag" != 'Y'
               AND ROWNUM = 1
               AND "Employee_Number" = eh.Employee_Number
        ORDER  BY "End_Date" ASC) x
WHERE  "Current_Flag" = 'Y'

Get safe area inset top and bottom heights

Try this :

In Objective C

if (@available(iOS 11.0, *)) {
    UIWindow *window = UIApplication.sharedApplication.windows.firstObject;
    CGFloat topPadding = window.safeAreaInsets.top;
    CGFloat bottomPadding = window.safeAreaInsets.bottom;
}

In Swift

if #available(iOS 11.0, *) {
    let window = UIApplication.shared.keyWindow
    let topPadding = window?.safeAreaInsets.top
    let bottomPadding = window?.safeAreaInsets.bottom
}

In Swift - iOS 13.0 and above

// Use the first element from windows array as KeyWindow deprecated

if #available(iOS 13.0, *) {
    let window = UIApplication.shared.windows[0]
    let topPadding = window.safeAreaInsets.top
    let bottomPadding = window.safeAreaInsets.bottom
}

JSON.parse vs. eval()

All JSON.parse implementations most likely use eval()

JSON.parse is based on Douglas Crockford's solution, which uses eval() right there on line 497.

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

j = eval('(' + text + ')');

The advantage of JSON.parse is that it verifies the argument is correct JSON syntax.

How to check the input is an integer or not in Java?

If the user input is a String then you can try to parse it as an integer using parseInt method, which throws NumberFormatException when the input is not a valid number string:

try {

    int intValue = Integer.parseInt(stringUserInput));
}(NumberFormatException e) {
    System.out.println("Input is not a valid integer");
}

Resetting a setTimeout

To reset the timer, you would need to set and clear out the timer variable

$time_out_handle = 0;
window.clearTimeout($time_out_handle);
$time_out_handle = window.setTimeout( function(){---}, 60000 );

How to show disable HTML select option in by default?

 selected disabled="true"

Use this. It will work in new browsers

How can I insert data into Database Laravel?

make sure you use the POST to insert the data. Actually you were using GET.

How to convert an array to a string in PHP?

PHP has a built-in function implode to assign array values to string. Use it like this:

$str = implode(",", $array);

How to count occurrences of a column value efficiently in SQL?

select s.id, s.age, c.count
from students s
inner join (
    select age, count(*) as count
    from students
    group by age
) c on s.age = c.age
order by id

How can I refresh c# dataGridView after update ?

I know thats an old topic but i suddenly found the best way of doing it and it does not require nullifying the datasource and reassigning it. Just use a BindingList instead of a List.

for example:

//declare your list
private BindingList<myclass> mMyList = new BindingList<myclass>();

//then bind it to your datagrid, i usually do it on the Load event
private void Form1_Load(object sender, EventArgs e)
{
    _dgMyDatagrig.DataSource = mMyList;
}

//start populating your list 
private void addItem(mycclass item)
{
    mMylist.add(item);

//the datagrid will show automatically the new added/updated items, no need to do anything else

}

Getting the last element of a split string array

array.split(' ').slice(-1)[0]

The best one ever and my favorite.

Synchronously waiting for an async operation, and why does Wait() freeze the program here

With small custom synchronization context, sync function can wait for completion of async function, without creating deadlock. Here is small example for WinForms app.

Imports System.Threading
Imports System.Runtime.CompilerServices

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        SyncMethod()
    End Sub

    ' waiting inside Sync method for finishing async method
    Public Sub SyncMethod()
        Dim sc As New SC
        sc.WaitForTask(AsyncMethod())
        sc.Release()
    End Sub

    Public Async Function AsyncMethod() As Task(Of Boolean)
        Await Task.Delay(1000)
        Return True
    End Function

End Class

Public Class SC
    Inherits SynchronizationContext

    Dim OldContext As SynchronizationContext
    Dim ContextThread As Thread

    Sub New()
        OldContext = SynchronizationContext.Current
        ContextThread = Thread.CurrentThread
        SynchronizationContext.SetSynchronizationContext(Me)
    End Sub

    Dim DataAcquired As New Object
    Dim WorkWaitingCount As Long = 0
    Dim ExtProc As SendOrPostCallback
    Dim ExtProcArg As Object

    <MethodImpl(MethodImplOptions.Synchronized)>
    Public Overrides Sub Post(d As SendOrPostCallback, state As Object)
        Interlocked.Increment(WorkWaitingCount)
        Monitor.Enter(DataAcquired)
        ExtProc = d
        ExtProcArg = state
        AwakeThread()
        Monitor.Wait(DataAcquired)
        Monitor.Exit(DataAcquired)
    End Sub

    Dim ThreadSleep As Long = 0

    Private Sub AwakeThread()
        If Interlocked.Read(ThreadSleep) > 0 Then ContextThread.Resume()
    End Sub

    Public Sub WaitForTask(Tsk As Task)
        Dim aw = Tsk.GetAwaiter

        If aw.IsCompleted Then Exit Sub

        While Interlocked.Read(WorkWaitingCount) > 0 Or aw.IsCompleted = False
            If Interlocked.Read(WorkWaitingCount) = 0 Then
                Interlocked.Increment(ThreadSleep)
                ContextThread.Suspend()
                Interlocked.Decrement(ThreadSleep)
            Else
                Interlocked.Decrement(WorkWaitingCount)
                Monitor.Enter(DataAcquired)
                Dim Proc = ExtProc
                Dim ProcArg = ExtProcArg
                Monitor.Pulse(DataAcquired)
                Monitor.Exit(DataAcquired)
                Proc(ProcArg)
            End If
        End While

    End Sub

     Public Sub Release()
         SynchronizationContext.SetSynchronizationContext(OldContext)
     End Sub

End Class

Where can I find a list of keyboard keycodes?

I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).

Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

Need a query that returns every field that contains a specified letter

All the answers given using LIKEare totally valid, but as all of them noted will be slow. So if you have a lot of queries and not too many changes in the list of keywords, it pays to build a structure that allows for faster querying.

Here are some ideas:

If all you are looking for is the letters a-z and you don't care about uppercase/lowercase, you can add columns containsA .. containsZ and prefill those columns:

UPDATE table
SET containsA = 'X' 
WHERE UPPER(your_field) Like '%A%';

(and so on for all the columns).

Then index the contains.. columns and your query would be

SELECT 
FROM your_table
WHERE containsA = 'X'
AND containsB = 'X'

This may be normalized in an "index table" iTable with the columns your_table_key, letter, index the letter-column and your query becomes something like

SELECT
FROM your_table 
WHERE <key> in (select a.key
    From iTable a join iTable b and a.key = b.key
    Where a.letter = 'a'
    AND b.letter = 'b');

All of these require some preprocessing (maybe in a trigger or so), but the queries should be a lot faster.

How to check the exit status using an if statement

If you are writing a function, which is always preferred, you should propagate the error like this:

function() {
    if some_command; then
        echo worked
    else
        return $?
fi
}

This will propagate the error to the caller, so that he can do things like function && next as expected.

invalid use of non-static member function

You shall pass a this pointer to tell the function which object to work on because it relies on that as opposed to a static member function.

Key Listeners in python?

It's unfortunately not so easy to do that. If you're trying to make some sort of text user interface, you may want to look into curses. If you want to display things like you normally would in a terminal, but want input like that, then you'll have to work with termios, which unfortunately appears to be poorly documented in Python. Neither of these options are that simple, though, unfortunately. Additionally, they do not work under Windows; if you need them to work under Windows, you'll have to use PDCurses as a replacement for curses or pywin32 rather than termios.


I was able to get this working decently. It prints out the hexadecimal representation of keys you type. As I said in the comments of your question, arrows are tricky; I think you'll agree.

#!/usr/bin/env python
import sys
import termios
import contextlib


@contextlib.contextmanager
def raw_mode(file):
    old_attrs = termios.tcgetattr(file.fileno())
    new_attrs = old_attrs[:]
    new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
    try:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
        yield
    finally:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)


def main():
    print 'exit with ^C or ^D'
    with raw_mode(sys.stdin):
        try:
            while True:
                ch = sys.stdin.read(1)
                if not ch or ch == chr(4):
                    break
                print '%02x' % ord(ch),
        except (KeyboardInterrupt, EOFError):
            pass


if __name__ == '__main__':
    main()

Difference between rake db:migrate db:reset and db:schema:load

As far as I understand, it is going to drop your database and re-create it based on your db/schema.rb file. That is why you need to make sure that your schema.rb file is always up to date and under version control.

How do I run .sh or .bat files from Terminal?

I had this problem for *.sh files in Yosemite and couldn't figure out what the correct path is for a folder on my Desktop...after some gnashing of teeth, dragged the file itself into the Terminal window; hey presto!!

What does it mean if a Python object is "subscriptable" or not?

Off the top of my head, the following are the only built-ins that are subscriptable:

string:  "foobar"[3] == "b"
tuple:   (1,2,3,4)[3] == 4
list:    [1,2,3,4][3] == 4
dict:    {"a":1, "b":2, "c":3}["c"] == 3

But mipadi's answer is correct - any class that implements __getitem__ is subscriptable

How to extract the first two characters of a string in shell scripting?

Probably the most efficient method, if you're using the bash shell (and you appear to be, based on your comments), is to use the sub-string variant of parameter expansion:

pax> long="USCAGol.blah.blah.blah"
pax> short="${long:0:2}" ; echo "${short}"
US

This will set short to be the first two characters of long. If long is shorter than two characters, short will be identical to it.

This in-shell method is usually better if you're going to be doing it a lot (like 50,000 times per report as you mention) since there's no process creation overhead. All solutions which use external programs will suffer from that overhead.

If you also wanted to ensure a minimum length, you could pad it out before hand with something like:

pax> long="A"
pax> tmpstr="${long}.."
pax> short="${tmpstr:0:2}" ; echo "${short}"
A.

This would ensure that anything less than two characters in length was padded on the right with periods (or something else, just by changing the character used when creating tmpstr). It's not clear that you need this but I thought I'd put it in for completeness.


Having said that, there are any number of ways to do this with external programs (such as if you don't have bash available to you), some of which are:

short=$(echo "${long}" | cut -c1-2)
short=$(echo "${long}" | head -c2)
short=$(echo "${long}" | awk '{print substr ($0, 0, 2)}'
short=$(echo "${long}" | sed 's/^\(..\).*/\1/')

The first two (cut and head) are identical for a single-line string - they basically both just give you back the first two characters. They differ in that cut will give you the first two characters of each line and head will give you the first two characters of the entire input

The third one uses the awk sub-string function to extract the first two characters and the fourth uses sed capture groups (using () and \1) to capture the first two characters and replace the entire line with them. They're both similar to cut - they deliver the first two characters of each line in the input.

None of that matters if you are sure your input is a single line, they all have an identical effect.

How do you get the cursor position in a textarea?

Here's a cross browser function I have in my standard library:

function getCursorPos(input) {
    if ("selectionStart" in input && document.activeElement == input) {
        return {
            start: input.selectionStart,
            end: input.selectionEnd
        };
    }
    else if (input.createTextRange) {
        var sel = document.selection.createRange();
        if (sel.parentElement() === input) {
            var rng = input.createTextRange();
            rng.moveToBookmark(sel.getBookmark());
            for (var len = 0;
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                len++;
            }
            rng.setEndPoint("StartToStart", input.createTextRange());
            for (var pos = { start: 0, end: len };
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                pos.start++;
                pos.end++;
            }
            return pos;
        }
    }
    return -1;
}

Use it in your code like this:

var cursorPosition = getCursorPos($('#myTextarea')[0])

Here's its complementary function:

function setCursorPos(input, start, end) {
    if (arguments.length < 3) end = start;
    if ("selectionStart" in input) {
        setTimeout(function() {
            input.selectionStart = start;
            input.selectionEnd = end;
        }, 1);
    }
    else if (input.createTextRange) {
        var rng = input.createTextRange();
        rng.moveStart("character", start);
        rng.collapse();
        rng.moveEnd("character", end - start);
        rng.select();
    }
}

http://jsfiddle.net/gilly3/6SUN8/

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

How to add hyperlink in JLabel?

You can do this using a JLabel, but an alternative would be to style a JButton. That way, you don't have to worry about accessibility and can just fire events using an ActionListener.

  public static void main(String[] args) throws URISyntaxException {
    final URI uri = new URI("http://java.sun.com");
    class OpenUrlAction implements ActionListener {
      @Override public void actionPerformed(ActionEvent e) {
        open(uri);
      }
    }
    JFrame frame = new JFrame("Links");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(100, 400);
    Container container = frame.getContentPane();
    container.setLayout(new GridBagLayout());
    JButton button = new JButton();
    button.setText("<HTML>Click the <FONT color=\"#000099\"><U>link</U></FONT>"
        + " to go to the Java website.</HTML>");
    button.setHorizontalAlignment(SwingConstants.LEFT);
    button.setBorderPainted(false);
    button.setOpaque(false);
    button.setBackground(Color.WHITE);
    button.setToolTipText(uri.toString());
    button.addActionListener(new OpenUrlAction());
    container.add(button);
    frame.setVisible(true);
  }

  private static void open(URI uri) {
    if (Desktop.isDesktopSupported()) {
      try {
        Desktop.getDesktop().browse(uri);
      } catch (IOException e) { /* TODO: error handling */ }
    } else { /* TODO: error handling */ }
  }

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

Cache busting via params

It is safer to put the version number in the actual filename. This allows multiple versions to exist at once so you can roll out a new version and if any cached HTML pages still exist that are requesting the older version, they will get the version that works with their HTML.

Note, in one of the largest versioned deployments anywhere on the internet, jQuery uses version numbers in the actual filename and it safely allows multiple versions to co-exist without any special server-side logic (each version is just a different file).

This busts the cache once when you deploy new pages and new linked files (which is what you want) and from then on those versions can be effectively cached (which you also want).

What languages are Windows, Mac OS X and Linux written in?

As an addition about the core of Mac OS X, Finder had not been written in Objective-C prior to Snow Leopard. In Snow Leopard it was written in Cocoa, Objective-C

Right way to split an std::string into a vector<string>

A convenient way would be boost's string algorithms library.

#include <boost/algorithm/string/classification.hpp> // Include boost::for is_any_of
#include <boost/algorithm/string/split.hpp> // Include for boost::split
// ...

std::vector<std::string> words;
std::string s;
boost::split(words, s, boost::is_any_of(", "), boost::token_compress_on);

Function ereg_replace() is deprecated - How to clear this bug?

Here is more information regarding replacing ereg_replace with preg_replace

How to configure socket connect timeout

I solved the problem by using Socket.ConnectAsync Method instead of Socket.Connect Method. After invoking the Socket.ConnectAsync(SocketAsyncEventArgs), start a timer (timer_connection), if time is up, check whether socket connection is connected (if(m_clientSocket.Connected)), if not, pop up timeout error.

private void connect(string ipAdd,string port)
    {
        try
        {
            SocketAsyncEventArgs e=new SocketAsyncEventArgs();


            m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPAddress ip = IPAddress.Parse(serverIp);
            int iPortNo = System.Convert.ToInt16(serverPort);
            IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);

            //m_clientSocket.
            e.RemoteEndPoint = ipEnd;
            e.UserToken = m_clientSocket;
            e.Completed+=new EventHandler<SocketAsyncEventArgs>(e_Completed);                
            m_clientSocket.ConnectAsync(e);

            if (timer_connection != null)
            {
                timer_connection.Dispose();
            }
            else
            {
                timer_connection = new Timer();
            }
            timer_connection.Interval = 2000;
            timer_connection.Tick+=new EventHandler(timer_connection_Tick);
            timer_connection.Start();
        }
        catch (SocketException se)
        {
            lb_connectStatus.Text = "Connection Failed";
            MessageBox.Show(se.Message);
        }
    }
private void e_Completed(object sender,SocketAsyncEventArgs e)
    {
        lb_connectStatus.Text = "Connection Established";
        WaitForServerData();
    }
    private void timer_connection_Tick(object sender, EventArgs e)
    {
        if (!m_clientSocket.Connected)
        {
            MessageBox.Show("Connection Timeout");
            //m_clientSocket = null;

            timer_connection.Stop();
        }
    }

Set variable with multiple values and use IN

You need a table variable:

declare @values table
(
    Value varchar(1000)
)

insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')

select blah
from foo
where myField in (select value from @values)

How to clone a Date object?

Simplified version:

Date.prototype.clone = function () {
    return new Date(this.getTime());
}

Free Rest API to retrieve current datetime as string (timezone irrelevant)

If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.

correct PHP headers for pdf file download

Example 2 on w3schools shows what you are trying to achieve.

<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("original.pdf");
?>

Also remember that,

It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)

IsNothing versus Is Nothing

I'm leaning towards the "Is Nothing" alternative, primarily because it seems more OO.

Surely Visual Basic ain't got the Ain't keyword.

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

Here's a simple working solution:

@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }

.elem:hover {
    -webkit-animation:spin 1.5s linear infinite;
    -moz-animation:spin 1.5s linear infinite;
    animation:spin 1.5s linear infinite;
}

Align image to left of text on same line - Twitter Bootstrap3

Using Twitter Bootstrap classes may be the best choice :

  • pull-left makes an element floating left
  • clearfix allows the element to contain floating elements (if not already set via another class)
<div class="paragraphs">
  <div class="row">
    <div class="span4">
      <div class="clearfix content-heading">
          <img class="pull-left" src="../site/img/success32.png"/>
          <h3>Experience &nbsp </h3>
      </div>
      <p>Donec id elit non mi porta gravida at eget metus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
    </div>
  </div>
</div>

JavaScript Adding an ID attribute to another created Element

Since id is an attribute don't create an id element, just do this:

myPara.setAttribute("id", "id_you_like");

How to print full stack trace in exception?

Recommend to use LINQPad related nuget package, then you can use exceptionInstance.Dump().

enter image description here

For .NET core:

  • Install LINQPad.Runtime

For .NET framework 4 etc.

  • Install LINQPad

Sample code:

using System;
using LINQPad;

namespace csharp_Dump_test
{
    public class Program
    {
        public static void Main()
        {
            try
            {
                dosome();
            }
            catch (Exception ex)
            {
                ex.Dump();
            }
        }

        private static void dosome()
        {
            throw new Exception("Unable.");
        }
    }
}

Running result: enter image description here

LinqPad nuget package is the most awesome tool for printing exception stack information. May it be helpful for you.

The definitive guide to form-based website authentication

I'd like to add one suggestion I've used, based on defense in depth. You don't need to have the same auth&auth system for admins as regular users. You can have a separate login form on a separate url executing separate code for requests that will grant high privileges. This one can make choices that would be a total pain to regular users. One such that I've used is to actually scramble the login URL for admin access and email the admin the new URL. Stops any brute force attack right away as your new URL can be arbitrarily difficult (very long random string) but your admin user's only inconvenience is following a link in their email. The attacker no longer knows where to even POST to.

How to print to console in pytest?

I needed to print important warning about skipped tests exactly when PyTest muted literally everything.

I didn't want to fail a test to send a signal, so I did a hack as follow:

def test_2_YellAboutBrokenAndMutedTests():
    import atexit
    def report():
        print C_patch.tidy_text("""
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.""")
    if sys.stdout != sys.__stdout__:
        atexit.register(report)

The atexit module allows me to print stuff after PyTest released the output streams. The output looks as follow:

============================= test session starts ==============================
platform linux2 -- Python 2.7.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /media/Storage/henaro/smyth/Alchemist2-git/sources/C_patch, inifile: 
collected 15 items 

test_C_patch.py .....ssss....s.

===================== 10 passed, 5 skipped in 0.15 seconds =====================
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.
~/.../sources/C_patch$

Message is printed even when PyTest is in silent mode, and is not printed if you run stuff with py.test -s, so everything is tested nicely already.

How can I tell jackson to ignore a property for which I don't have control over the source code?

Annotation based approach is better. But sometimes manual operation is needed. For this purpose you can use without method of ObjectWriter.

ObjectMapper mapper   = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
ObjectWriter writer   = mapper.writer().withoutAttribute("property1").withoutAttribute("property2");
String       jsonText = writer.writeValueAsString(sourceObject);

LINQ to SQL - How to select specific columns and return strongly typed list

The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.

Thank you all for your help!

Change directory in PowerShell

Multiple posted answer here, but probably this can help who is newly using PowerShell

enter image description here

SO if any space is there in your directory path do not forgot to add double inverted commas "".

Keystore type: which one to use?

Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java----Overview

Below are the descriptions of different keystores from the post:

JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.

JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.

PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.

PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.

php Replacing multiple spaces with a single space

$output = preg_replace('/\s+/', ' ',$input);

\s is shorthand for [ \t\n\r]. Multiple spaces will be replaced with single space.

jQuery AJAX Call to PHP Script with JSON Return

I recommend you use:

var returnedData = JSON.parse(data);

to convert the JSON string (if it is just text) to a JavaScript object.

Send POST request using NSURLSession

    use like this.....

    Create file

    #import <Foundation/Foundation.h>`    
    #import "SharedManager.h"
    #import "Constant.h"
    #import "UserDetails.h"

    @interface APISession : NSURLSession<NSURLSessionDelegate>
    @property (nonatomic, retain) NSMutableData *responseData;
    +(void)postRequetsWithParam:(NSMutableDictionary* )objDic withAPIName:(NSString* 
    )strAPIURL completionHandler:(void (^)(id result, BOOL status))completionHandler;
    @end

****************.m*************************
    #import "APISession.h"
    #import <UIKit/UIKit.h>
    @implementation APISession

    +(void)postRequetsWithParam:(NSMutableDictionary *)objDic withAPIName:(NSString 
    *)strAPIURL completionHandler:(void (^)(id, BOOL))completionHandler
    {
    NSURL *url=[NSURL URLWithString:strAPIURL];
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSError *err = nil;

    NSData *data=[NSJSONSerialization dataWithJSONObject:objDic options:NSJSONWritingPrettyPrinted error:&err];
    [request setHTTPBody:data];

    NSString *strJsonFormat = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"API URL: %@ \t  Api Request Parameter ::::::::::::::%@",url,strJsonFormat);
    //    NSLog(@"Request data===%@",objDic);
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

    //  NSURLSession *session=[NSURLSession sharedSession];

    NSURLSessionTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                            {
                                if (error==nil) {
                                    NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];\
                                    NSLog(@"Response Data=============%@",dicData);
                                    if([[dicData valueForKey:@"tokenExpired"]integerValue] == 1)
                                    {

                                        NSLog(@"hello");
                                        NSDictionary *dict = [NSDictionary dictionaryWithObject:@"Access Token Expire." forKey:@"message"];
                                        [[NSNotificationCenter defaultCenter] postNotificationName:@"UserLogOut" object:self userInfo:dict];
                                    }
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        completionHandler(dicData,(error == nil));
                                    });
                                    NSLog(@"%@",dicData);
                                }
                                else{
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        completionHandler(error.localizedDescription,NO);
                                    });
                                }
                            }];
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [task resume];
    //    });
    }
    @end

    *****************************in .your view controller***********
    #import "file"
    txtEmail.text = [txtEmail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    {
            [SVProgressHUD showWithStatus:@"Loading..."];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];

            NSMutableDictionary *objLoginDic=[[NSMutableDictionary alloc] init];
            [objLoginDic setValue:txtEmail.text forKey:@"email"];
            [objLoginDic setValue:@0            forKey:kDeviceType];
            [objLoginDic setValue:txtPassword.text forKey:kPassword];
            [objLoginDic setValue:@"376545432"  forKey:kDeviceTokan];
            [objLoginDic setValue:@""           forKey:kcountryId];
            [objLoginDic setValue:@""           forKey:kfbAccessToken];
            [objLoginDic setValue:@0            forKey:kloginType];

            [APISession postRequetsWithParam:objLoginDic withAPIName:KLOGIN_URL completionHandler:^(id result, BOOL status) {

                [SVProgressHUD dismiss];

                NSInteger statusResponse=[[result valueForKey:kStatus] integerValue];
                NSString *strMessage=[result valueForKey:KMessage];
                if (status) {
                    if (statusResponse == 1)
                {
                        UserDetails *objLoginUserDetail=[[UserDetails alloc] 
                        initWithObject:[result valueForKey:@"userDetails"]];
                          [[NSUserDefaults standardUserDefaults] 
                        setObject:@(objLoginUserDetail.userId) forKey:@"user_id"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        [self clearTextfeilds];
                        HomeScreen *obj=[Kiran_Storyboard instantiateViewControllerWithIdentifier:@"HomeScreen"];
                        [self.navigationController pushViewController:obj animated:YES];
                    }
                    else{
                        [strMessage showAsAlert:self];
                    }
                }
            }];
        }
**********use model class for represnt data*************

    #import <Foundation/Foundation.h>
    #import "Constant.h"
    #import <objc/runtime.h>


    @interface UserDetails : NSObject
    @property(strong,nonatomic) NSString *emailId,
    *deviceToken,
    *countryId,
    *fbAccessToken,
    *accessToken,
    *countryName,
    *isProfileSetup,
    *profilePic,
    *firstName,
    *lastName,
    *password;

    @property (assign) NSInteger userId,deviceType,loginType;

    -(id)initWithObject :(NSDictionary *)dicUserData;
    -(void)saveLoginUserDetail;
    +(UserDetails *)getLoginUserDetail;
    -(UserDetails *)getEmptyModel;
    - (NSArray *)allPropertyNames;
    -(void)printDescription;
       -(NSMutableDictionary *)getDictionary;

    @end

    ******************model.m*************

    #import "UserDetails.h"
    #import "SharedManager.h"

    @implementation UserDetails



      -(id)initWithObject :(NSDictionary *)dicUserData
       {
       self = [[UserDetails alloc] init];
       if (self)
       {
           @try {
               [self setFirstName:([dicUserData valueForKey:@"firstName"] != [NSNull null])? 
               [dicUserData valueForKey:@"firstName"]:@""];


               [self setUserId:([dicUserData valueForKey:kUserId] != [NSNull null])? 
               [[dicUserData valueForKey:kUserId] integerValue]:0];


               }
        @catch (NSException *exception) {
            NSLog(@"Exception: %@",exception.description);
        }
        @finally {
        }
    }
    return self;
}

    -(UserDetails *)getEmptyModel{
    [self setFirstName:@""];
    [self setLastName:@""];



    [self setDeviceType:0];


    return self;
       }

     -  (void)encodeWithCoder:(NSCoder *)encoder {
    //    Encode properties, other class variables, etc
    [encoder encodeObject:_firstName forKey:kFirstName];


    [encoder encodeObject:[NSNumber numberWithInteger:_deviceType] forKey:kDeviceType];

    }

    - (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        _firstName = [decoder decodeObjectForKey:kEmailId];

        _deviceType= [[decoder decodeObjectForKey:kDeviceType] integerValue];

    }
    return self;
    }
    - (NSArray *)allPropertyNames
    {
    unsigned count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);

    NSMutableArray *rv = [NSMutableArray array];

    unsigned i;
    for (i = 0; i < count; i++)
    {
        objc_property_t property = properties[i];
        NSString *name = [NSString stringWithUTF8String:property_getName(property)];
        [rv addObject:name];
    }

    free(properties);

    return rv; 
    } 

    -(void)printDescription{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];

    for(NSString *key in [self allPropertyNames])
    {
        [dic setValue:[self valueForKey:key] forKey:key];
    }
    NSLog(@"\n========================= User Detail ==============================\n");
    NSLog(@"%@",[dic description]);
    NSLog(@"\n=============================================================\n");
    }
    -(NSMutableDictionary *)getDictionary{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    for(NSString *key in [self allPropertyNames])
    {
        [dic setValue:[self valueForKey:key] forKey:key];
    }
    return dic;
    }
    #pragma mark
    #pragma mark - Save and get User details
    -(void)saveLoginUserDetail{
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self];
    [Shared_UserDefault setObject:encodedObject forKey:kUserDefault_SavedUserDetail];
    [Shared_UserDefault synchronize];
    }
      +(UserDetails *)getLoginUserDetail{
      NSData *encodedObject = [Shared_UserDefault objectForKey:kUserDefault_SavedUserDetail];
    UserDetails *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
   }
    @end


     ************************usefull code while add data into model and get data********

                   NSLog(@"Response %@",result);
                  NSString *strMessg = [result objectForKey:kMessage];
                 NSString *status = [NSString stringWithFormat:@"%@",[result 
                objectForKey:kStatus]];

            if([status isEqualToString:@"1"])
            {
                arryBankList =[[NSMutableArray alloc]init];

                NSMutableArray *arrEvents=[result valueForKey:kbankList];
                ShareOBJ.isDefaultBank = [result valueForKey:kisDefaultBank];
                if ([arrEvents count]>0)
                {

                for (NSMutableArray *dic in arrEvents)
                    {
                        BankList *objBankListDetail =[[BankList alloc]initWithObject:[dic 
                         mutableCopy]];
                        [arryBankList addObject:objBankListDetail];
                    }
           //display data using model...
           BankList *objBankListing  =[arryBankList objectAtIndex:indexPath.row];

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

How can I create an object and add attributes to it?

as docs say:

Note: object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.

You could just use dummy-class instance.

Access to file download dialog in Firefox

I didnt unserstood your objective, Do you wanted your test to automatically download file when test is getting executed, if yes, then You need to use custom Firefox profile in your test execution.

In the custom profile, for first time execute test manually and if download dialog comes, the set it Save it to Disk, also check Always perform this action checkbox which will ensure that file automatically get downloaded next time you run your test.

Tainted canvases may not be exported

I also solved this error by adding useCORS : true, in my code like -

html2canvas($("#chart-section")[0], {
        useCORS : true,
        allowTaint : true,
        scale : 0.98,
        dpi : 500,
        width: 1400, height: 900
    }).then();

Detecting attribute change of value of an attribute I made

You can use MutationObserver to track attribute changes including data-* changes. For example:

_x000D_
_x000D_
var foo = document.getElementById('foo');_x000D_
_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  console.log('data-select-content-val changed');_x000D_
});_x000D_
observer.observe(foo, { _x000D_
  attributes: true, _x000D_
  attributeFilter: ['data-select-content-val'] });_x000D_
_x000D_
foo.dataset.selectContentVal = 1;
_x000D_
 <div id='foo'></div>_x000D_
 
_x000D_
_x000D_
_x000D_

How can I do GUI programming in C?

This is guaranteed to have nothing to do with the compiler. All compilers do is compile the code that they are given. What you're looking for is a GUI library, which you can write code against using any compiler that you want.

Of course, that being said, your first order of business should be to ditch Turbo C. That compiler is about 20 years old and continuing to use it isn't doing you any favors. You can't write modern GUI applications, as it will only produce 16-bit code. All modern operating systems are 32-bit, and many are now 64-bit. It's also worth noting that 64-bit editions of Windows will not run 16-bit applications natively. You'll need an emulator for that; it's not really going to engender much feeling of accomplishment if you can only write apps that work in a DOS emulator. :-)

Microsoft's Visual Studio Express C++ is available as a free download. It includes the same compiler available in the full version of the suite. The C++ package also compiles pure C code.

And since you're working in Windows, the Windows API is a natural choice. It allows you to write native Windows applications that have access to the full set of GUI controls. You'll find a nice tutorial here on writing WinAPI applications in C. If you choose to go with Visual Studio, it also includes boilerplate code for a blank WinAPI application that will get you up and running quickly.

If you really care about learning to do this, Charles Petzold's Programming Windows is the canonical resource of the subject, and definitely worth a read. The entire Windows API was written in C, and it's entirely possible to write full-featured Windows applications in C. You don't need no stinkin' C++.

That's the way I'd do it, at least. As the other answers suggest, GTK is also an option. But the applications it generates are just downright horrible-looking on Windows.


EDIT: Oh dear... It looks like you're not alone in wanting to write "GUI" applications using an antiquated compiler. A Google search turns up the following library: TurboGUI: A GUI Framework for Turbo C/C++:

 TurboGUI interface sample

If you're another one of those poor people stuck in the hopelessly out-of-date Indian school system and forced to use Turbo C to complete your education, this might be an option. I'm loathe to recommend it, as learning to work around its limitations will be completely useless to you once you graduate, but apparently it's out there for you if you're interested.

Call two functions from same onclick

onclick="pay(); cls();"

however, if you're using a return statement in "pay" function the execution will stop and "cls" won't execute,

a workaround to this:

onclick="var temp = function1();function2(); return temp;"

How to set iPhone UIView z index?

If you want to do this through XCode's Interface Builder, you can use the menu options under Editor->Arrangement. There you'll find "Send to Front", "Send to Back", etc.

iFrame onload JavaScript event

Use the iFrame's .onload function of JavaScript:

<iframe id="my_iframe" src="http://www.test.tld/">
    <script type="text/javascript">
        document.getElementById('my_iframe').onload = function() {
            __doPostBack('ctl00$ctl00$bLogout','');
        }
    </script>
    <!--OTHER STUFF-->
</iframe>

Counter increment in Bash loop not working

This is a simple example

COUNTER=1
for i in {1..5}
do   
   echo $COUNTER;
   //echo "Welcome $i times"
   ((COUNTER++));    
done

Call fragment from fragment

Just do that: getTabAt(index of your tab)

        ActionBar actionBar = getSupportActionBar();
        actionBar.selectTab(actionBar.getTabAt(0));

NoClassDefFoundError - Eclipse and Android

I have encountered the same issue. The reason was that the library that I was trying to use had been compiled with a standard JDK 7.

I recompiled it with the -source 1.6 -target 1.6 options and it worked fine.

Difference between char* and const char*?

In neither case can you modify a string literal, regardless of whether the pointer to that string literal is declared as char * or const char *.

However, the difference is that if the pointer is const char * then the compiler must give a diagnostic if you attempt to modify the pointed-to value, but if the pointer is char * then it does not.

how to set mongod --dbpath

You could also configure mongod to run on start up so that it is automatically running on start up and the dbpath is set upon configuration. To do this try:

mongod --smallfiles --config /etc/mongod.conf

The --smallfiles tag is there in case you get an error with size. It is, of course, optional. Doing this should solve your problem while also automating your mongodb setup.

How to filter rows containing a string pattern from a Pandas dataframe

>>> mask = df['ids'].str.contains('ball')    
>>> mask
0     True
1     True
2    False
3     True
Name: ids, dtype: bool

>>> df[mask]
     ids  vals
0  aball     1
1  bball     2
3  fball     4

When should I use nil and NULL in Objective-C?

nil means absence of value while NULL represent No Object,

NSArray *array = @[@"Hello World !", @101,[NSNULL null] ];

Here [NSNULL null] is an object which means no object, at the same time you cannot add nil to indicate absence of object.

you can use both nil and [NSNUll null] for checking too.

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

Short answer :

 :: Start - Run , type:
 cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"

 :: click into target media, Ctrl + V to paste the result 

Long answer

    @echo off
    :: START USAGE  ==================================================================
    ::SET THE NICETIME 
    :: SET NICETIME=BOO
    :: CALL GetNiceTime.cmd 

    :: ECHO NICETIME IS %NICETIME%

    :: echo nice time is %NICETIME%
    :: END USAGE  ==================================================================

    echo set hhmmsss
    :: this is Regional settings dependant so tweak this according your current settings
    for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c 
    ::DEBUG ECHO hhmmsss IS %hhmmsss%
    ::DEBUG PAUSE
    echo %yyyymmdd%
        :: this is Regional settings dependant so tweak this according your current settings
    for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set  yyyymmdd=%%F%%E%%D
    ::DEBUG ECHO yyyymmdd IS %yyyymmdd%
    ::DEBUG PAUSE


    set NICETIME=%yyyymmdd%_%hhmmsss%
    ::DEBUG echo THE NICETIME IS %NICETIME%

    ::DEBUG PAUSE

Safely override C++ virtual functions

I would suggest a slight change in your logic. It may or may not work, depending on what you need to accomplish.

handle_event() can still do the "boring default code" but instead of being virtual, at the point where you want it to do the "new exciting code" have the base class call an abstract method (i.e. must-be-overridden) method that will be supplied by your descendant class.

EDIT: And if you later decide that some of your descendant classes do not need to provide "new exciting code" then you can change the abstract to virtual and supply an empty base class implementation of that "inserted" functionality.

How to correctly close a feature branch in Mercurial?

imho there are two cases for branches that were forgot to close

Case 1: branch was not merged into default

in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.

hg up myBranch
hg commit --close-branch

Case 2: branch was merged into default

This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.

in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!

hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch

Hope this helps future readers.

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

For limit 1 use methods FirstOrDefault() or First().

Example

var y = (from x in q select x).FirstOrDefault();

How to format LocalDate to string?

A pretty nice way to do this is to use SimpleDateFormat I'll show you how:

SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);

I see that you have the date in a variable:

sdf.format(variable_name);

Cheers.

Python regular expressions return true/false

Match objects are always true, and None is returned if there is no match. Just test for trueness.

if re.match(...):

CSS transition with visibility not working

Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337

You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0 only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden, you can eliminate this problem:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:20px;_x000D_
}_x000D_
.menu {_x000D_
    visibility:hidden;_x000D_
    opacity:0;_x000D_
    transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
    _x000D_
    background:#eee;_x000D_
    width:100px;_x000D_
    margin:0;_x000D_
    padding:5px;_x000D_
    list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
    visibility:visible;_x000D_
    opacity:1;_x000D_
}
_x000D_
<div>_x000D_
  <a href="#">Open Menu</a>_x000D_
  <ul class="menu">_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

numbers not allowed (0-9) - Regex Expression in javascript

Simply:

/^([^0-9]*)$/

That pattern matches any number of characters that is not 0 through 9.

I recommend checking out http://regexpal.com/. It will let you easily test out a regex.

startsWith() and endsWith() functions in PHP

Based on James Black's answer, here is its endsWith version:

function startsWith($haystack, $needle, $case=true) {
    if ($case)
        return strncmp($haystack, $needle, strlen($needle)) == 0;
    else
        return strncasecmp($haystack, $needle, strlen($needle)) == 0;
}

function endsWith($haystack, $needle, $case=true) {
     return startsWith(strrev($haystack),strrev($needle),$case);

}

Note: I have swapped the if-else part for James Black's startsWith function, because strncasecmp is actually the case-insensitive version of strncmp.

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

Get local IP address in Node.js

If you're into the whole brevity thing, here it is using Lodash:

_x000D_
_x000D_
var os = require('os');
var _ = require('lodash');
var firstLocalIp = _(os.networkInterfaces()).values().flatten().where({ family: 'IPv4', internal: false }).pluck('address').first();

console.log('First local IPv4 address is ' + firstLocalIp);
_x000D_
_x000D_
_x000D_

What is the difference between static_cast<> and C style casting?

static_cast checks at compile time that conversion is not between obviously incompatible types. Contrary to dynamic_cast, no check for types compatibility is done at run time. Also, static_cast conversion is not necessarily safe.

static_cast is used to convert from pointer to base class to pointer to derived class, or between native types, such as enum to int or float to int.

The user of static_cast must make sure that the conversion is safe.

The C-style cast does not perform any check, either at compile or at run time.

In Python, how do I split a string and keep the separators?

# This keeps all separators  in result 
##########################################################################
import re
st="%%(c+dd+e+f-1523)%%7"
sh=re.compile('[\+\-//\*\<\>\%\(\)]')

def splitStringFull(sh, st):
   ls=sh.split(st)
   lo=[]
   start=0
   for l in ls:
     if not l : continue
     k=st.find(l)
     llen=len(l)
     if k> start:
       tmp= st[start:k]
       lo.append(tmp)
       lo.append(l)
       start = k + llen
     else:
       lo.append(l)
       start =llen
   return lo
  #############################

li= splitStringFull(sh , st)
['%%(', 'c', '+', 'dd', '+', 'e', '+', 'f', '-', '1523', ')%%', '7']

How can I convert a string to a float in mysql?

This will convert to a numeric value without the need to cast or specify length or digits:

STRING_COL+0.0

If your column is an INT, can leave off the .0 to avoid decimals:

STRING_COL+0

Cannot authenticate into mongo, "auth fails"

You can also try this :-

mongo localhost:27017/admin -u admin -p SECRETPASSWORD

Found it in this post

Here obviously the localhost can be some other host and the /admin can be some other database on which authentication has been applied

A variable modified inside a while loop is not remembered

Hmmm... I would almost swear that this worked for the original Bourne shell, but don't have access to a running copy just now to check.

There is, however, a very trivial workaround to the problem.

Change the first line of the script from:

#!/bin/bash

to

#!/bin/ksh

Et voila! A read at the end of a pipeline works just fine, assuming you have the Korn shell installed.

How may I sort a list alphabetically using jQuery?

HTML

<ul id="list">
    <li>alpha</li>
    <li>gamma</li>
    <li>beta</li>
</ul>

JavaScript

function sort(ul) {
    var ul = document.getElementById(ul)
    var liArr = ul.children
    var arr = new Array()
    for (var i = 0; i < liArr.length; i++) {
        arr.push(liArr[i].textContent)
    }
    arr.sort()
    arr.forEach(function(content, index) {
        liArr[index].textContent = content
    })
}

sort("list")

JSFiddle Demo https://jsfiddle.net/97oo61nw/

Here we are push all values of li elements inside ul with specific id (which we provided as function argument) to array arr and sort it using sort() method which is sorted alphabetical by default. After array arr is sorted we are loop this array using forEach() method and just replace text content of all li elements with sorted content

Convert object string to JSON

You need to use "eval" then JSON.stringify then JSON.parse to the result.

 var errorString= "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
 var jsonValidString = JSON.stringify(eval("(" + errorString+ ")"));
 var JSONObj=JSON.parse(jsonValidString);

enter image description here

Intercept and override HTTP requests from WebView

It looks like API level 11 has support for what you need. See WebViewClient.shouldInterceptRequest().

Returning value from Thread

What you are looking for is probably the Callable<V> interface in place of Runnable, and retrieving the value with a Future<V> object, which also lets you wait until the value has been computed. You can achieve this with an ExecutorService, which you can get from Executors.newSingleThreadExecutor() .

public void test() {
    int x;
    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<Integer> result = es.submit(new Callable<Integer>() {
        public Integer call() throws Exception {
            // the other thread
            return 2;
        }
    });
    try {
        x = result.get();
    } catch (Exception e) {
        // failed
    }
    es.shutdown();
}

How to clear a notification in Android

 Notification mNotification = new Notification.Builder(this)

                .setContentTitle("A message from: " + fromUser)
                .setContentText(msg)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.app_icon)
                .setContentIntent(pIntent)
                .build();

.setAutoCancel(true)

when you click on notification, open corresponding activity and remove notification from notification bar

Nginx location "not equal to" regex

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

jQuery ajax error function

you're using a function

error(error) 

but jquery is actually looking for a function with three parameters:

error(jqXHR, textStatus, errorThrown)

you'll need to add two more parameters.

ALSO: please have a look at all the comments above that mention 'deprecated' :)

$.ajax("www.stackoverflow.com/api/whatever", {
    dataType:"JSON"
    data: { id=1, name='example' }
}).succes(function (result) {
    // use result
}).error(function (jqXHR, textStatus, errorThrown) {
    // handle error
});

Error in Process.Start() -- The system cannot find the file specified

You can't use a filename like iexplore by itself because the path to internet explorer isn't listed in the PATH environment variable for the system or user.

However any path entered into the PATH environment variable allows you to use just the file name to execute it.

System32 isn't special in this regard as any directory can be added to the PATH variable. Each path is simply delimited by a semi-colon.

For example I have c:\ffmpeg\bin\ and c:\nmap\bin\ in my path environment variable, so I can do things like new ProcessStartInfo("nmap", "-foo") or new ProcessStartInfo("ffplay", "-bar")

The actual PATH variable looks like this on my machine.

%SystemRoot%\system32;C:\FFPlay\bin;C:\nmap\bin;

As you can see you can use other system variables, such as %SystemRoot% to build and construct paths in the environment variable.

So - if you add a path like "%PROGRAMFILES%\Internet Explorer;" to your PATH variable you will be able to use ProcessStartInfo("iexplore");

If you don't want to alter your PATH then simply use a system variable such as %PROGRAMFILES% or %SystemRoot% and then expand it when needed in code. i.e.

string path = Environment.ExpandEnvironmentVariables(
       @"%PROGRAMFILES%\Internet Explorer\iexplore.exe");
var info = new ProcessStartInfo(path);

INNER JOIN in UPDATE sql for DB2

Joins in update statements are non-standard and not supported by all vendors. What you're trying to do can be accomplished with a sub-select:

update
  file1
set
  firstfield = (select 'stuff' concat something from file2 where substr(file1.field1, 10, 20) = substr(file2.xxx,1,10) )
where
  file1.foo like 'BLAH%'

Prevent flex items from overflowing a container

One easy solution is to use overflow values other than visible to make the text flex basis width reset as expected.

  1. Here with value auto the text wraps as expected and the article content does not overflow main container.

  2. Also, the article flex value must either have a auto basis AND be able to shrink, OR, only grow AND explicit 0 basis

_x000D_
_x000D_
main, aside, article {_x000D_
  margin: 10px;_x000D_
  border: solid 1px #000;_x000D_
  border-bottom: 0;_x000D_
  height: 50px;_x000D_
  overflow: auto; /* 1. overflow not `visible` */_x000D_
}_x000D_
main {_x000D_
  display: flex;_x000D_
}_x000D_
aside {_x000D_
  flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
  flex: 1 1 auto; /* 2. Allow auto width content to shrink */_x000D_
  /* flex: 1 0 0; /* Or, explicit 0 width basis that grows */_x000D_
}
_x000D_
<main>_x000D_
  <aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
  <article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Appending HTML string to the DOM

Use insertAdjacentHTML if it's available, otherwise use some sort of fallback. insertAdjacentHTML is supported in all current browsers.

div.insertAdjacentHTML( 'beforeend', str );

Live demo: http://jsfiddle.net/euQ5n/

Matplotlib figure facecolor (background color)

It's because savefig overrides the facecolor for the background of the figure.

(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolor kwarg to savefig. It's a confusing and inconsistent default, though!)

The easiest workaround is just to do fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none') (I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)

Hope that helps!

jQuery if statement to check visibility

Yes you can use .is(':visible') in jquery. But while the code is running under the safari browser .is(':visible') is won't work.

So please use the below code

if( $(".example").offset().top > 0 )

The above line will work both IE as well as safari also.

Insert picture into Excel cell

There is some faster way (https://www.youtube.com/watch?v=TSjEMLBAYVc):

  1. Insert image (Ctrl+V) to the excel.
  2. Validate "Picture Tools -> Align -> Snap To Grid" is checked
  3. Resize the image to fit the cell (or number of cells)
  4. Right-click on the image and check "Size and Properties... -> Properties -> Move and size with cells"

Changing Underline color

Another way that the one described by danield is to have a child container width display inline, and the tipography color you want. The parent element width the text-decoration, and the color of underline you want. Like this:

_x000D_
_x000D_
div{text-decoration:underline;color:#ff0000;display:inline-block;width:50px}_x000D_
div span{color:#000;display:inline}
_x000D_
<div>_x000D_
  <span>Hover me, i can have many lines</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

putting datepicker() on dynamically created elements - JQuery/JQueryUI

The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to use ( _.each ) function.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;    

var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {

    _.each(repeaterWrapper, function (repeaterItem, index) {

        var jq_nodes = $(repeaterItem.addedNodes);

        jq_nodes.each(function () {

            // Date Picker
            $(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
                dateFormat: "dd MM, yy",
                showAnim: "slideDown",
                changeMonth: true,
                numberOfMonths: 1
            });

        });

    });

});

observerjQueryPlugins.observe(document, {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false
});

MySQL Fire Trigger for both Insert and Update

unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle

Convert a PHP script into a stand-alone windows executable

I had problems with most of the tools in other answers as they are all very outdated.

If you need a solution that will "just work", pack a bare-bones version of php with your project in a WinRar SFX archive, set it to extract everything to a temporary directory and execute php your_script.php.

To run a basic script, the only files required are php.exe and php5.dll (or php5ts.dll depending on version).

To add extensions, pack them along with a php.ini file:

[PHP]
extension_dir = "."
extension=php_curl.dll
extension=php_xxxx.dll
...

how to align text vertically center in android

Your TextView Attributes need to be something like,

<TextView ... 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical|right" ../>

Now, Description why these need to be done,

 android:layout_width="match_parent"
 android:layout_height="match_parent"

Makes your TextView to match_parent or fill_parent if You don't want to be it like, match_parent you have to give some specified values to layout_height so it get space for vertical center gravity. android:layout_width="match_parent" necessary because it align your TextView in Right side so you can recognize respect to Parent Layout of TextView.

Now, its about android:gravity which makes the content of Your TextView alignment. android:layout_gravity makes alignment of TextView respected to its Parent Layout.

Update:

As below comment says use fill_parent instead of match_parent. (Problem in some device.)

What are the differences between virtual memory and physical memory?

I am shamelessly copying the excerpts from man page of top

VIRT -- Virtual Image (kb) The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used.

SWAP -- Swapped size (kb) Memory that is not resident but is present in a task. This is memory that has been swapped out but could include additional non- resident memory. This column is calculated by subtracting physical memory from virtual memory

Update Git submodule to latest commit on origin

the simplest way to handle git projects containing submodules is to always add

--recurse-submodules 

at the end of each git command example:

git fetch --recurse-submodules

another

git pull --update --recurse-submodules

etc...