Programs & Examples On #Bcs

Microsoft Business Connectivity Services is a set of services and features that connect SharePoint-based solutions to sources of external data. It is included in Microsoft SharePoint Foundation 2010, Microsoft SharePoint Server 2010, and Microsoft Office 2010 applications.

How to VueJS router-link active style

The :active pseudo-class is not the same as adding a class to style the element.

The :active CSS pseudo-class represents an element (such as a button) that is being activated by the user. When using a mouse, "activation" typically starts when the mouse button is pressed down and ends when it is released.

What we are looking for is a class, such as .active, which we can use to style the navigation item.

For a clearer example of the difference between :active and .active see the following snippet:

_x000D_
_x000D_
li:active {_x000D_
  background-color: #35495E;_x000D_
}_x000D_
_x000D_
li.active {_x000D_
  background-color: #41B883;_x000D_
}
_x000D_
<ul>_x000D_
  <li>:active (pseudo-class) - Click me!</li>_x000D_
  <li class="active">.active (class)</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_


Vue-Router

vue-router automatically applies two active classes, .router-link-active and .router-link-exact-active, to the <router-link> component.


router-link-active

This class is applied automatically to the <router-link> component when its target route is matched.

The way this works is by using an inclusive match behavior. For example, <router-link to="/foo"> will get this class applied as long as the current path starts with /foo/ or is /foo.

So, if we had <router-link to="/foo"> and <router-link to="/foo/bar">, both components would get the router-link-active class when the path is /foo/bar.


router-link-exact-active

This class is applied automatically to the <router-link> component when its target route is an exact match. Take into consideration that both classes, router-link-active and router-link-exact-active, will be applied to the component in this case.

Using the same example, if we had <router-link to="/foo"> and <router-link to="/foo/bar">, the router-link-exact-activeclass would only be applied to <router-link to="/foo/bar"> when the path is /foo/bar.


The exact prop

Lets say we have <router-link to="/">, what will happen is that this component will be active for every route. This may not be something that we want, so we can use the exact prop like so: <router-link to="/" exact>. Now the component will only get the active class applied when it is an exact match at /.


CSS

We can use these classes to style our element, like so:

 nav li:hover,
 nav li.router-link-active,
 nav li.router-link-exact-active {
   background-color: indianred;
   cursor: pointer;
 }

The <router-link> tag was changed using the tag prop, <router-link tag="li" />.


Change default classes globally

If we wish to change the default classes provided by vue-router globally, we can do so by passing some options to the vue-router instance like so:

const router = new VueRouter({
  routes,
  linkActiveClass: "active",
  linkExactActiveClass: "exact-active",
})

Change default classes per component instance (<router-link>)

If instead we want to change the default classes per <router-link> and not globally, we can do so by using the active-class and exact-active-class attributes like so:

<router-link to="/foo" active-class="active">foo</router-link>

<router-link to="/bar" exact-active-class="exact-active">bar</router-link>

v-slot API

Vue Router 3.1.0+ offers low level customization through a scoped slot. This comes handy when we wish to style the wrapper element, like a list element <li>, but still keep the navigation logic in the anchor element <a>.

<router-link
  to="/foo"
  v-slot="{ href, route, navigate, isActive, isExactActive }"
>
  <li
    :class="[isActive && 'router-link-active', isExactActive && 'router-link-exact-active']"
  >
    <a :href="href" @click="navigate">{{ route.fullPath }}</a>
  </li>
</router-link>

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I had this error with MySQL as my database and the only solution was reinstall all components of MySQL, because before I installed just the server.

So try to download other versions of PostgreSQL and get all the components

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

Adding spring.jpa.database-platform=org.hibernate.dialect.MariaDB53Dialect to my properties file worked for me.

PS: i'm using MariaDB

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

rails generate model

For me what happened was that I generated the app with rails new rails new chapter_2 but the RVM --default had rails 4.0.2 gem, but my chapter_2 project use a new gemset with rails 3.2.16.

So when I ran

rails generate scaffold User name:string email:string

the console showed

Usage:
   rails new APP_PATH [options]

So I fixed the RVM and the gemset with the rails 3.2.16 gem , and then generated the app again then I executed

 rails generate scaffold User name:string email:string

and it worked

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

How to convert image into byte array and byte array to base64 String in android?

Try this:

// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg), 
                       Base64.NO_WRAP);

Eclipse cannot load SWT libraries

For Windows Subsystem for Linux (WSL) you'll need

apt install libswt-gtk-4-jni

If you don't have an OpenJDK 8 you'll also need

apt install openjdk-8-jdk

JPA - Returning an auto generated id after persist()

The ID is only guaranteed to be generated at flush time. Persisting an entity only makes it "attached" to the persistence context. So, either flush the entity manager explicitely:

em.persist(abc);
em.flush();
return abc.getId();

or return the entity itself rather than its ID. When the transaction ends, the flush will happen, and users of the entity outside of the transaction will thus see the generated ID in the entity.

@Override
public ABC addNewABC(ABC abc) {
    abcDao.insertABC(abc);
    return abc;
}

H2 database error: Database may be already in use: "Locked by another process"

For InteliJ: right lick on your database in the database view and choose "Disconnect".

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

  1. First Replace the MySQL dependency as given below

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.44</version>
    </dependency>
    
  2. An error showing "Authentication plugin 'caching_sha2_password'" will appear. Run this command:

    mysql -u root -p
    ALTER USER 'username'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
    

How to start rails server?

For rails 3.2.3 and latest version of rails you can start server by:
First install all gem with command: bundle install or bundle.
Then Configure your database to the database.yml.
Create new database: rake db:create
Then start rails server.
rails server orrails s

Remove all special characters except space from a string using JavaScript

You can do it specifying the characters you want to remove:

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g, '');

How to increase Heap size of JVM

-XmxSIZE

For example: -Xmx1024M

H2 in-memory database. Table not found

DB_CLOSE_DELAY=-1

hbm2ddl closes the connection after creating the table, so h2 discards it.

If you have your connection-url configured like this

jdbc:h2:mem:test

the content of the database is lost at the moment the last connection is closed.

If you want to keep your content you have to configure the url like this

jdbc:h2:mem:test;DB_CLOSE_DELAY=-1

If doing so, h2 will keep its content as long as the vm lives.

Notice the semicolon (;) rather than colon (:).

See the In-Memory Databases section of the Features page. To quote:

By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1.

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

Android, Java: HTTP POST Request

I'd rather recommend you to use Volley to make GET, PUT, POST... requests.

First, add dependency in your gradle file.

compile 'com.he5ed.lib:volley:android-cts-5.1_r4'

Now, use this code snippet to make requests.

RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

        StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.d("Response", response);
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.d("Error.Response", error.toString());
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String>();
                //add your parameters here as key-value pairs
                params.put("username", username);
                params.put("password", password);

                return params;
            }
        };
        queue.add(postRequest);

Multiple glibc libraries on a single host

It is very possible to have multiple versions of glibc on the same system (we do that every day).

However, you need to know that glibc consists of many pieces (200+ shared libraries) which all must match. One of the pieces is ld-linux.so.2, and it must match libc.so.6, or you'll see the errors you are seeing.

The absolute path to ld-linux.so.2 is hard-coded into the executable at link time, and can not be easily changed after the link is done (Update: can be done with patchelf; see this answer below).

To build an executable that will work with the new glibc, do this:

g++ main.o -o myapp ... \
   -Wl,--rpath=/path/to/newglibc \
   -Wl,--dynamic-linker=/path/to/newglibc/ld-linux.so.2

The -rpath linker option will make the runtime loader search for libraries in /path/to/newglibc (so you wouldn't have to set LD_LIBRARY_PATH before running it), and the -dynamic-linker option will "bake" path to correct ld-linux.so.2 into the application.

If you can't relink the myapp application (e.g. because it is a third-party binary), not all is lost, but it gets trickier. One solution is to set a proper chroot environment for it. Another possibility is to use rtldi and a binary editor. Update: or you can use patchelf.

Causes of getting a java.lang.VerifyError

Another reason for this error can be the combination of AspectJ <= 1.6.11 with JRE > 6.

See Eclipse Bug 353467 and Kieker ticket 307 for details.

This is especially true when everything works fine on JRE 6 and moving to JRE7 breaks things.

What is the difference between single and double quotes in SQL?

The difference lies in their usage. The single quotes are mostly used to refer a string in WHERE, HAVING and also in some built-in SQL functions like CONCAT, STRPOS, POSITION etc.

When you want to use an alias that has space in between then you can use double quotes to refer to that alias.

For example

(select account_id,count(*) "count of" from orders group by 1)sub 

Here is a subquery from an orders table having account_id as Foreign key that I am aggregating to know how many orders each account placed. Here I have given one column any random name as "count of" for sake of purpose.

Now let's write an outer query to display the rows where "count of" is greater than 20.

select "count of" from 
(select account_id,count(*) "count of" from orders group by 1)sub where "count of" >20;

You can apply the same case to Common Table expressions also.

How can I de-install a Perl module installed via `cpan`?

You can't. There isn't a feature in my CPAN client to do such a thing. We were talking about how we might do something like that at this weekend's Perl QA Workshop, but it's generally hard for all the reasons that Ether mentioned.

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

Using parse_requirements is problematic because the pip API isn't publicly documented and supported. In pip 1.6, that function is actually moving, so existing uses of it are likely to break.

A more reliable way to eliminate duplication between setup.py and requirements.txt is to specific your dependencies in setup.py and then put -e . into your requirements.txt file. Some information from one of the pip developers about why that's a better way to go is available here: https://caremad.io/blog/setup-vs-requirement/

.htaccess redirect http to https

Insert this code in your .htaccess file. And it should work

RewriteCond %{HTTP_HOST} yourDomainName\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourDomainName.com/$1 [R,L]

Installation error: INSTALL_FAILED_OLDER_SDK

If you are totally new like me, you must install the minimum SDK at first. Check the link.

This worked out perfectly for me:

Same problem other post with a good solution

Regards,

Khaled.

What is the HTML5 equivalent to the align attribute in table cells?

you can use this code as replacement for table align

table 
{
    margin:auto;
}

Creating a very simple linked list

A linked list is a node-based data structure. Each node designed with two portions (Data & Node Reference).Actually, data is always stored in Data portion (Maybe primitive data types eg Int, Float .etc or we can store user-defined data type also eg. Object reference) and similarly Node Reference should also contain the reference to next node, if there is no next node then the chain will end.

This chain will continue up to any node doesn't have a reference point to the next node.

Please find the source code from my tech blog - http://www.algonuts.info/linked-list-program-in-java.html

package info.algonuts;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

class LLNode {
    int nodeValue;
    LLNode childNode;

    public LLNode(int nodeValue) {
        this.nodeValue = nodeValue;
        this.childNode = null;
    }
}

class LLCompute {
    private static LLNode temp;
    private static LLNode previousNode;
    private static LLNode newNode;
    private static LLNode headNode;

    public static void add(int nodeValue) {
        newNode = new LLNode(nodeValue);
        temp = headNode;
        previousNode = temp;
        if(temp != null)
        {   compute();  }
        else
        {   headNode = newNode; }   //Set headNode
    }

    private static void compute() {
        if(newNode.nodeValue < temp.nodeValue) {    //Sorting - Ascending Order
            newNode.childNode = temp;
            if(temp == headNode) 
            {   headNode = newNode; }
            else if(previousNode != null) 
            {   previousNode.childNode = newNode;   }
        }
        else
        {
            if(temp.childNode == null)
            {   temp.childNode = newNode;   }
            else
            {
                previousNode = temp;
                temp = temp.childNode;
                compute();
            }
        }
    }

    public static void display() {
        temp = headNode;
        while(temp != null) {
            System.out.print(temp.nodeValue+" ");
            temp = temp.childNode;
        }
    }
}

public class LinkedList {
    //Entry Point
    public static void main(String[] args) {
        //First Set Input Values
        List <Integer> firstIntList = new ArrayList <Integer>(Arrays.asList(50,20,59,78,90,3,20,40,98));   
        Iterator<Integer> ptr  = firstIntList.iterator();
        while(ptr.hasNext()) 
        {   LLCompute.add(ptr.next());  }
        System.out.println("Sort with first Set Values");
        LLCompute.display();
        System.out.println("\n");

        //Second Set Input Values
        List <Integer> secondIntList = new ArrayList <Integer>(Arrays.asList(1,5,8,100,91));   
        ptr  = secondIntList.iterator();
        while(ptr.hasNext()) 
        {   LLCompute.add(ptr.next());  }
        System.out.println("Sort with first & Second Set Values");
        LLCompute.display();
        System.out.println();
    }
}

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

This worked for me on win replace REL_PATH_TO_FILE with the relative path to the file to remove Removing sensitive data from a repository The docs say full path - but that errored for me -so I tried rel path and it worked.

<from the repo dir>git filter-branch --force --index-filter "git rm --cached --ignore-unmatch REL_PATH_TO_FILE" --prune-empty --tag-name-filter cat -- --all

Insert data into table with result from another select query

INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`) 
SELECT sum(p1), sum(p2), sum(p3) 
FROM `test`.`product`;

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws Exception {
        ProcessBuilder pb = new ProcessBuilder("script.bat");
        pb.redirectErrorStream(true);
        Process p = pb.start();
        BufferedReader logReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String logLine = null;
        while ( (logLine = logReader.readLine()) != null) {
           System.out.println("Script output: " + logLine);
        }
    }
}

By using this line: pb.redirectErrorStream(true); we can combine InputStream and ErrorStream

How to find the array index with a value?

Here is my take on it, seems like most peoples solutions don't check if the item exists and it removes random values if it does not exist.

First check if the element exists by looking for it's index. If it does exist, remove it by its index using the splice method

elementPosition = array.indexOf(value);

if(elementPosition != -1) {
  array.splice(elementPosition, 1);
}

Converting a value to 2 decimal places within jQuery

You need to use the .toFixed() method

It takes as a parameter the number of digits to show after the decimal point.

$(document).ready(function() {
  $('.add').click(function() {
     var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
     $('#total').text( value.toFixed(2) );
  });
})

Splitting comma separated string in a PL/SQL stored proc

CREATE OR REPLACE PROCEDURE insert_into (
   p_errcode        OUT   NUMBER,
   p_errmesg        OUT   VARCHAR2,
   p_rowsaffected   OUT   INTEGER
)
AS
   v_param0   VARCHAR2 (30) := '0.25,2.25,33.689, abc, 99';
   v_param1   VARCHAR2 (30) := '2.65,66.32, abc-def, 21.5';
BEGIN
   FOR i IN (SELECT COLUMN_VALUE
               FROM TABLE (SPLIT (v_param0, ',')))
   LOOP
      INSERT INTO tempo
                  (col1
                  )
           VALUES (i.COLUMN_VALUE
                  );
   END LOOP;

   FOR i IN (SELECT COLUMN_VALUE
               FROM TABLE (SPLIT (v_param1, ',')))
   LOOP
      INSERT INTO tempo
                  (col2
                  )
           VALUES (i.COLUMN_VALUE
                  );
   END LOOP;
END;

HTML table with fixed headers?

Use the latest version of jQuery, and include the following JavaScript code.

$(window).scroll(function(){
  $("id of the div element").offset({top:$(window).scrollTop()});
});

What does "exited with code 9009" mean during this build?

You need to make sure you have installed grunt globally

WordPress path url in js script file

For users working with the Genesis framework.

Add the following to your child theme functions.php

add_action( 'genesis_before', 'script_urls' );

function script_urls() {
?>
    <script type="text/javascript">
     var stylesheetDir = '<?= get_bloginfo("stylesheet_directory"); ?>';
    </script>
<?php
}

And use that variable to set the relative url in your script. For example:

Reset.style.background = " url('"+stylesheetDir+"/images/searchfield_clear.png') ";

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

I have been having similar issues, and have been looking into the possibility that browsers have limits on how often getCurrentPosition can be called. It seems I can often get a location, but if i refresh the page right away it will time out. If I wait for a bit, I can usually get a location again. This usually happens with FF. In Chrome and Safari, I have not yet noticed getCurrentPosition timing out. Just a thought...

Although I cannot find any documentation to support this, it was a conclusion I came to after much testing. Perhaps someone else has has some info about that?

How to query nested objects?

Since there is a lot of confusion about queries MongoDB collection with sub-documents, I thought its worth to explain the above answers with examples:

First I have inserted only two objects in the collection namely: message as:

> db.messages.find().pretty()
{
    "_id" : ObjectId("5cce8e417d2e7b3fe9c93c32"),
    "headers" : {
        "From" : "[email protected]"
    }
}
{
    "_id" : ObjectId("5cce8eb97d2e7b3fe9c93c33"),
    "headers" : {
        "From" : "[email protected]",
        "To" : "[email protected]"
    }
}
>

So what is the result of query: db.messages.find({headers: {From: "[email protected]"} }).count()

It should be one because these queries for documents where headers equal to the object {From: "[email protected]"}, only i.e. contains no other fields or we should specify the entire sub-document as the value of a field.

So as per the answer from @Edmondo1984

Equality matches within sub-documents select documents if the subdocument matches exactly the specified sub-document, including the field order.

From the above statements, what is the below query result should be?

> db.messages.find({headers: {To: "[email protected]", From: "[email protected]"}  }).count()
0

And what if we will change the order of From and To i.e same as sub-documents of second documents?

> db.messages.find({headers: {From: "[email protected]", To: "[email protected]"}  }).count()
1

so, it matches exactly the specified sub-document, including the field order.

For using dot operator, I think it is very clear for every one. Let's see the result of below query:

> db.messages.find( { 'headers.From': "[email protected]" }  ).count()
2

I hope these explanations with the above example will make someone more clarity on find query with sub-documents.

Get string between two strings in a string

I think this works:

   static void Main(string[] args)
    {
        String text = "One=1,Two=2,ThreeFour=34";

        Console.WriteLine(betweenStrings(text, "One=", ",")); // 1
        Console.WriteLine(betweenStrings(text, "Two=", ",")); // 2
        Console.WriteLine(betweenStrings(text, "ThreeFour=", "")); // 34

        Console.ReadKey();

    }

    public static String betweenStrings(String text, String start, String end)
    {
        int p1 = text.IndexOf(start) + start.Length;
        int p2 = text.IndexOf(end, p1);

        if (end == "") return (text.Substring(p1));
        else return text.Substring(p1, p2 - p1);                      
    }

pandas dataframe columns scaling with sklearn

I know it's a very old comment, but still:

Instead of using single bracket (dfTest['A']), use double brackets (dfTest[['A']]).

i.e: min_max_scaler.fit_transform(dfTest[['A']]).

I believe this will give the desired result.

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

5 Jan 2021: link update thanks to @Sadap's comment.

Kind of a corollary answer: the people on this site have taken the time to make tables of macros defined for every OS/compiler pair.

For example, you can see that _WIN32 is NOT defined on Windows with Cygwin (POSIX), while it IS defined for compilation on Windows, Cygwin (non-POSIX), and MinGW with every available compiler (Clang, GNU, Intel, etc.).

Anyway, I found the tables quite informative and thought I'd share here.

Best way to show a loading/progress indicator?

Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".

Currently the recommended method is to use a DialogFragment :

public class MySpinnerDialog extends DialogFragment {

    public MySpinnerDialog() {
        // use empty constructors. If something is needed use onCreate's
    }

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {

        _dialog = new ProgressDialog(getActivity());
        this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
        _dialog.setMessage("Spinning.."); // set your messages if not inflated from XML

        _dialog.setCancelable(false);  

        return _dialog;
    }
}

Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:

FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");

Once your server has responded complete you will dismiss it:

myInstance.dismiss()

Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide

Listing all permutations of a string/integer

Here is one more implementation of the algo mentioned.

public class Program
{
    public static void Main(string[] args)
    {
        string str = "abcefgh";
        var astr = new Permutation().GenerateFor(str);
        Console.WriteLine(astr.Length);
        foreach(var a in astr)
        {
            Console.WriteLine(a);
        }
        //a.ForEach(Console.WriteLine);
    }
}

class Permutation
{
    public string[] GenerateFor(string s)
    {  

        if(s.Length == 1)
        {

            return new []{s}; 
        }

        else if(s.Length == 2)
        {

            return new []{s[1].ToString()+s[0].ToString(),s[0].ToString()+s[1].ToString()};

        }

        var comb = new List<string>();

        foreach(var c in s)
        {

            string cStr = c.ToString();

            var sToProcess = s.Replace(cStr,"");
            if (!string.IsNullOrEmpty(sToProcess) && sToProcess.Length>0)
            {
                var conCatStr = GenerateFor(sToProcess);



                foreach(var a in conCatStr)
                {
                    comb.Add(c.ToString()+a);
                }


            }
        }
        return comb.ToArray();

    }
}

Transfer files to/from session I'm logged in with PuTTY

Since you asked about to/from, here's a trick that works for the 'from' part. Open the 'Change settings...' screen, Terminal, and under 'Printer to send ANSI printer output to:' select 'Generic / Text Only'

Now on the remote system, run this on one line:

tput mc5; cat whatever.txt; tput mc4

Putty will inform you that the file was saved. What this is doing is putting the terminal into printer mode (tput mc5), printing the file to the screen (cat), and then turning off printer mode (tput mc4). If you don't put all the commands on one line, the screen will appear frozen because Putty is saving all terminal output to a file in the background.

If you're on a more limited system that doesn't have the tput command (e.g. a qnap), you can try printf "\x1b[5i" instead of tput mc5, and printf "\x1b[4i" instead of tput mc4.

The command in the middle is just anything that prints to the screen. So use tail -n 10000 blah.log to download the last 10k lines of the log file, or use a base64 encoder to map a binary file to something you can print (and then decode on your local system):

printf "\x1b[5i"; openssl enc -base64 -in something.zip; printf "\x1b[4i"

How to use Morgan logger?

In my case:

-console.log()  // works
-console.error() // works
-app.use(logger('dev')) // Morgan is NOT logging requests that look like "GET /myURL 304 9.072 ms - -"

FIX: I was using Visual Studio code, and I had to add this to my Launch Config

"outputCapture": "std"

Suggestion, in case you are running from an IDE, run directly from the command line to make sure the IDE is not causing the problem.

What is the purpose of the var keyword and when should I use it (or omit it)?

Here's quite a good example of how you can get caught out from not declaring local variables with var:

<script>
one();

function one()
{
    for (i = 0;i < 10;i++)
    {
        two();
        alert(i);
    }
}

function two()
{
    i = 1;
}
</script>

(i is reset at every iteration of the loop, as it's not declared locally in the for loop but globally) eventually resulting in infinite loop

How do I view 'git diff' output with my preferred diff tool/ viewer?

If you happen to already have a diff tool associated with filetypes (say, because you installed TortoiseSVN which comes with a diff viewer) you could just pipe the regular git diff output to a "temp" file, then just open that file directly without needing to know anything about the viewer:

git diff > "~/temp.diff" && start "~/temp.diff"

Setting it as a global alias works even better: git what

[alias]
    what = "!f() { git diff > "~/temp.diff" && start "~/temp.diff"; }; f"

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

How to deserialize a list using GSON or another JSON library in Java?

With Gson, you'd just need to do something like:

List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());

You might also need to provide a no-arg constructor on the Video class you're deserializing to.

How do I base64 encode (decode) in C?

libb64 has both C and C++ APIs. It is lightweight and perhaps the fastest publicly available implementation. It's also a dedicated stand-alone base64 encoding library, which can be nice if you don't need all the other stuff that comes from using a larger library such as OpenSSL or glib.

How to clear the cache of nginx?

In my nginx install I found I had to go to:

/opt/nginx/cache

and

sudo rm -rf *

in that directory. If you know the path to your nginx install and can find the cache directory the same may work for you. Be very careful with the rm -rf command, if you are in the wrong directory you could delete your entire hard drive.

How to check programmatically if an application is installed or not in Android?

So nicer with Kotlin suger:

  private fun isSomePackageInstalled(context: Context, packageName: String): Boolean {

    val packageManager = context.packageManager

    return runCatching { packageManager.getPackageInfo(packageName, 0) }.isSuccess
  }

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

What is a web service endpoint?

A endpoint is a URL for web service.And Endpoints also is a distributed API.

The Simple Object Access Protocol (SOAP) endpoint is a URL. It identifies the location on the built-in HTTP service where the web services listener listens for incoming requests.

Reference: https://www.ibm.com/support/knowledgecenter/SSSHYH_7.1.0.4/com.ibm.netcoolimpact.doc/dsa/imdsa_web_netcool_impact_soap_endpoint_c.html

Convert a PHP object to an associative array

Here I've made an objectToArray() method, which also works with recursive objects, like when $objectA contains $objectB which points again to $objectA.

Additionally I've restricted the output to public properties using ReflectionClass. Get rid of it, if you don't need it.

    /**
     * Converts given object to array, recursively.
     * Just outputs public properties.
     *
     * @param object|array $object
     * @return array|string
     */
    protected function objectToArray($object) {
        if (in_array($object, $this->usedObjects, TRUE)) {
            return '**recursive**';
        }
        if (is_array($object) || is_object($object)) {
            if (is_object($object)) {
                $this->usedObjects[] = $object;
            }
            $result = array();
            $reflectorClass = new \ReflectionClass(get_class($this));
            foreach ($object as $key => $value) {
                if ($reflectorClass->hasProperty($key) && $reflectorClass->getProperty($key)->isPublic()) {
                    $result[$key] = $this->objectToArray($value);
                }
            }
            return $result;
        }
        return $object;
    }

To identify already used objects, I am using a protected property in this (abstract) class, named $this->usedObjects. If a recursive nested object is found, it will be replaced by the string **recursive**. Otherwise it would fail in because of infinite loop.

How to implement class constructor in Visual Basic?

Not sure what you mean with "class constructor" but I'd assume you mean one of the ones below.

Instance constructor:

Public Sub New()

End Sub

Shared constructor:

Shared Sub New()

End Sub

JavaScript array to CSV

The cited answer was wrong. You had to change

csvContent += index < infoArray.length ? dataString+ "\n" : dataString;

to

csvContent += dataString + "\n";

As to why the cited answer was wrong (funny it has been accepted!): index, the second parameter of the forEach callback function, is the index in the looped-upon array, and it makes no sense to compare this to the size of infoArray, which is an item of said array (which happens to be an array too).

EDIT

Six years have passed now since I wrote this answer. Many things have changed, including browsers. The following was part of the answer:

START of aged part

BTW, the cited code is suboptimal. You should avoid to repeatedly append to a string. You should append to an array instead, and do an array.join("\n") at the end. Like this:

var lineArray = [];
data.forEach(function (infoArray, index) {
    var line = infoArray.join(",");
    lineArray.push(index == 0 ? "data:text/csv;charset=utf-8," + line : line);
});
var csvContent = lineArray.join("\n");

END of aged part

(Keep in mind that the CSV case is a bit different from generic string concatenation, since for every string you also have to add the separator.)

Anyway, the above seems not to be true anymore, at least not for Chrome and Firefox (it seems to still be true for Safari, though).

To put an end to uncertainty, I wrote a jsPerf test that tests whether, in order to concatenate strings in a comma-separated way, it's faster to push them onto an array and join the array, or to concatenate them first with the comma, and then directly with the result string using the += operator.

Please follow the link and run the test, so that we have enough data to be able to talk about facts instead of opinions.

How to Deep clone in javascript

We can utilize recursion for making deepCopy. It can create copy of array, object, array of object, object with function. if you want, you can add function for other type of data structure like map etc.

function deepClone(obj) {
         var retObj;
        _assignProps = function(obj, keyIndex, retObj) {
               var subType = Object.prototype.toString.call(obj[keyIndex]);
               if(subType === "[object Object]" || subType === "[object Array]") {
                    retObj[keyIndex] = deepClone(obj[keyIndex]);
               }
               else {
                     retObj[keyIndex] = obj[keyIndex];
               }
        };

        if(Object.prototype.toString.call(obj) === "[object Object]") {
           retObj = {};
           for(key in obj) {
               this._assignProps(obj, key, retObj);
           }
        }
        else if(Object.prototype.toString.call(obj) == "[object Array]") {
           retObj = [];
           for(var i = 0; i< obj.length; i++) {
              this._assignProps(obj, i, retObj);
            }
        };

        return retObj;
    };

@Media min-width & max-width

I've found the best method is to write your default CSS for the older browsers, as older browsers including i.e. 5.5, 6, 7 and 8. Can't read @media. When I use @media I use it like this:

<style type="text/css">
    /* default styles here for older browsers. 
       I tend to go for a 600px - 960px width max but using percentages
    */
    @media only screen and (min-width: 960px) {
        /* styles for browsers larger than 960px; */
    }
    @media only screen and (min-width: 1440px) {
        /* styles for browsers larger than 1440px; */
    }
    @media only screen and (min-width: 2000px) {
        /* for sumo sized (mac) screens */
    }
    @media only screen and (max-device-width: 480px) {
       /* styles for mobile browsers smaller than 480px; (iPhone) */
    }
    @media only screen and (device-width: 768px) {
       /* default iPad screens */
    }
    /* different techniques for iPad screening */
    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
      /* For portrait layouts only */
    }

    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
      /* For landscape layouts only */
    }
</style>

But you can do whatever you like with your @media, This is just an example of what I've found best for me when building styles for all browsers.

iPad CSS specifications.

Also! If you're looking for printability you can use @media print{}

List<String> to ArrayList<String> conversion issue

Cast works where the actual instance of the list is an ArrayList. If it is, say, a Vector (which is another extension of List) it will throw a ClassCastException.

The error when changing the definition of your HashMap is due to the elements later being processed, and that process expects a method that is defined only in ArrayList. The exception tells you that it did not found the method it was looking for.

Create a new ArrayList with the contents of the old one.

new ArrayList<String>(myList);

How to set NODE_ENV to production/development in OS X

On OSX I'd recommend adding export NODE_ENV=development to your ~/.bash_profile and/or ~/.bashrc and/or ~/.profile.

Personally I add that entry to my ~/.bashrc and then have the ~/.bash_profile ~/.profile import the contents of that file, so it's consistent across environments.

After making these additions, be sure to restart your terminal to pick up settings.

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

How to make a stable two column layout in HTML/CSS

Piece of cake.

Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.

No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.

Voila. Grids FTW.

Adding two Java 8 streams, or an extra element to a stream

If you don't mind using 3rd Party Libraries cyclops-react has an extended Stream type that will allow you to do just that via the append / prepend operators.

Individual values, arrays, iterables, Streams or reactive-streams Publishers can be appended and prepended as instance methods.

Stream stream = ReactiveSeq.of(1,2)
                           .filter(x -> x!=0)
                           .append(ReactiveSeq.of(3,4))
                           .filter(x -> x!=1)
                           .append(5)
                           .filter(x -> x!=2);

[Disclosure I am the lead developer of cyclops-react]

iterating over and removing from a map

Java 8 support a more declarative approach to iteration, in that we specify the result we want rather than how to compute it. Benefits of the new approach are that it can be more readable, less error prone.

public static void mapRemove() {

    Map<Integer, String> map = new HashMap<Integer, String>() {
        {
            put(1, "one");
            put(2, "two");
            put(3, "three");
        }
    };

    map.forEach( (key, value) -> { 
        System.out.println( "Key: " + key + "\t" + " Value: " + value );  
    }); 

    map.keySet().removeIf(e->(e>2)); // <-- remove here

    System.out.println("After removing element");

    map.forEach( (key, value) -> { 
        System.out.println( "Key: " + key + "\t" + " Value: " + value ); 
    });
}

And result is as follows:

Key: 1   Value: one
Key: 2   Value: two
Key: 3   Value: three
After removing element
Key: 1   Value: one
Key: 2   Value: two

Incorrect integer value: '' for column 'id' at row 1

For the same error in wamp/phpmyadmin, I have edited my.ini, commented the original :

;sql-mode= "STRICT_ALL_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ZERO_DATE,NO_ZERO_IN_DATE,NO_AUTO_CREATE_USER"

and added sql_mode = "".

How to send email in ASP.NET C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Globalization;
    using System.Text.RegularExpressions;
    
    /// <summary>
    /// Summary description for RegexUtilities
    /// </summary>
    public class RegexUtilities
    {
        bool InValid = false;
    
        public bool IsValidEmail(string strIn)
        {
            InValid = false;
            if (String.IsNullOrEmpty(strIn))
                return false;
    
            // Use IdnMapping class to convert Unicode domain names.
            strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper);
            if (InValid)
                return false;
    
            // Return true if strIn is in valid e-mail format. 
            return Regex.IsMatch(strIn, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                   RegexOptions.IgnoreCase);
        }
    
        private string DomainMapper(Match match)
        {
            // IdnMapping class with default property values.
            IdnMapping idn = new IdnMapping();
    
            string domainName = match.Groups[2].Value;
            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                InValid = true;
            }
            return match.Groups[1].Value + domainName;
        }
    
    }



 private void GetSendEmInfo()
    {
        #region For Get All Type Email Informations..!!
        IPL.DoId = ddlName.SelectedValue;
        DataTable dt = IdBL.GetEmailS(IPL);
        if (dt.Rows.Count > 0)
        {
            hid_MailId.Value = dt.Rows[0]["MailId"].ToString();
            hid_UsedPName.Value = dt.Rows[0]["UName"].ToString();
            hid_EmailSubject.Value = dt.Rows[0]["EmailSubject"].ToString();
            hid_EmailBody.Value = dt.Rows[0]["EmailBody"].ToString();
            hid_EmailIdName.Value = dt.Rows[0]["EmailIdName"].ToString();
            hid_EmPass.Value = dt.Rows[0]["EPass"].ToString();
            hid_SeName.Value = dt.Rows[0]["SenName"].ToString();
            hid_TNo.Value = dt.Rows[0]["TeNo"].ToString();
            hid_EmaLimit.Value = dt.Rows[0]["EmailLimit"].ToString();
            hidlink.Value = dt.Rows[0][link"].ToString();
        }
        #endregion

        #region For Set Some Local Variables..!!
        int StartLmt, FinalLmt, SendCurrentMail;
        StartLmt = FinalLmt = SendCurrentMail = 0;
        bool Valid_LimitMail;
        Valid_LimitMail = true;
        /**For Get Finalize Limit For Send Mail**/
        FinalLmt = Convert.ToInt32(hid_EmailmaxLimit.Value);
        #region For Check Email Valid Limits..!!
        if (FinalLmt > 0)
        {
            Valid_LimitMail = true;
        }
        else
        {
            Valid_LimitMail = false;
        }
        #endregion
        /**For Get Finalize Limit For Send Mail**/
        #endregion

        if (Valid_LimitMail == true)
        {
            #region For Send Current Email Status..!!
            bool EmaiValid;
            string CreateFileName;
            string retmailflg = null;
            EmaiValid = false;
            #endregion

            #region For Set Start Limit And FinalLimit Send No Of Email..!!
            mPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
            DataTable dtsendEmail = m1BL.GetEmailSendLog(mPL);
            if (dtsendEmail.Rows.Count > 0)
            {
                StartLmt = Convert.ToInt32(dtsendEmail.Rows[0]["SendNo_Of_Email"].ToString());
            }
            else
            {
                StartLmt = 0;
            }
            #endregion

            #region For Find Grid View Controls..!!
            for (int i = 0; i < GrdEm.Rows.Count; i++)
            {
                #region For Find Grid view Controls..!!
                CheckBox Chk_SelectOne = (CheckBox)GrdEmp.Rows[i].FindControl("chkSingle");
                Label lbl_No = (Label)GrdEmAtt.Rows[i].FindControl("lblGrdCode");
                lblCode.Value = lbl_InNo.Text;

                Label lbl_EmailId = (Label)GrdEomAtt.Rows[i].FindControl("lblGrdEmpEmail");

                #endregion

                /**Region For If Check Box Checked Then**/
                if (Chk_SelectOne.Checked == true)
                {
                    if (!string.IsNullOrEmpty(lbl_EmailId.Text))
                    {
                        #region For When Check Box Checked..!!
                        /**If Start Limit Less Or Equal To Then Condition Performs**/
                        if (StartLmt < FinalLmt)
                        {
                            StartLmt = StartLmt + 1;
                        }
                        else
                        {
                            Valid_LimitMail = false;
                            EmaiValid = false;
                        }
                        /**End Region**/
                        string[] SplitClients_Email = lbl_EmailId.Text.Split(',');
                        string Send_Email, Hold_Email;
                        Send_Email = Hold_Email = "";

                        int CountEmail;/**Region For Count Total Email**/
                        CountEmail = 0;/**First Time Email Counts Zero**/

                        Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();
                        /**Region For If Clients Have One Email**/
                        #region For First Emails Send On Client..!!
                        if (SplitClients_Email[0].ToString() != "")
                        {
                            if (EmailRegex.IsValidEmail(Hold_Email))
                            {
                                Send_Email = Hold_Email;
                                CountEmail = 1;
                                EmaiValid = true;
                            }
                            else
                            {
                                EmaiValid = false;
                            }
                        }
                        #endregion
                        /**Region For If Clients Have One Email**/
                        /**Region For If Clients Have Two Email**/

                        /**Region For If Clients Have Two Email**/
                        if (EmaiValid == true)
                        {
                            #region For Create Email Body And Create File Name..!!
                            //fofile = Server.MapPath("PDFs");
                            fofile = Server.MapPath("~/vvv/vvvv/") + "/";
                            CreateFileName = lbl_INo.Text.ToString() + "_1" + ".Pdf";/**Create File Name**/
                            string[] orimail = Send_Email.Split(',');
                            string Billbody, TempInvoiceId;
                            // DateTime dtLstdate = new DateTime(Convert.ToInt32(txtYear.Text), Convert.ToInt32(ddlMonth.SelectedValue), 16);

                            //  DateTime IndtLmt = dtLstdate.AddMonths(1);
                            TempInvoiceId = "";

                            //byte[] Buffer = Encrypt.Encryptiondata(lbl_InvoiceNo.Text.ToString());
                            //TempInvoiceId = Convert.ToBase64String(Buffer);


                            #region Create Encrypted Path


                            byte[] EncCode = Encrypt.Encryptiondata(lbl_INo.Text);
                            hidEncrypteCode.Value = Convert.ToBase64String(EncECode);
                            #endregion

                        

                            //#region Create Email Body !!
                            //body = hid_EmailBody.Value.Replace("@greeting", lbl_CoName.Text).Replace("@free", hid_ToNo.Value).Replace("@llnk", "<a style='font-family: Tahoma; font-size: 10pt; color: #800000; font-weight: bold' href='http://1ccccc/ccc/ccc/ccc.aspx?EC=" + hidEncryptedCode.Value+ "' > C cccccccc </a>");
                          

                            body = hid_EmailBody.Value.Replace("@greeting", "Hii").Replace("@No", hid_No.Value);/*For Mail*/
                            //#endregion



                            #region For Email Sender Informations..!!
                            for (int j = 0; j < CountEmail; j++)
                            {
                                //if (File.Exists(fofile + "\\" + CreateFileName))
                                //{
                                #region
                                lbl_EmailId.Text = orimail[j];
                                retmailflg = "";

                                /**Region For Send Email For Clients**/
                                //retmailflg = SendPreMail("Wp From " + lbl_CName.Text + "", body, lbl_EmailId.Text, lbl_IeNo.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
                                retmailflg = SendPreMail(hid_EmailSubject.Value, Body, lbl_EmailId.Text, lbl_No.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
                                /**End Region**/

                                /**Region For Create Send Email Log  When Email Send Successfully**/
                                if (retmailflg == "True")
                                {
                                    SendCurrentMail = Convert.ToInt32(SendCurrentMail) + 1;
                                    StartLmt = Convert.ToInt32(StartLmt) + 1;

                                    if (SendCurrentMail > 0)
                                    {
                                        CreateEmailLog(lbl_InNo.Text, StartLmt, hid_EmailIdName.Value, lbl_EmailId.Text);
                                        
                                    }
                                }
                                

                                /**End Region**/
                                #endregion
                                //}
                            }
                            #endregion
                        }
                        #endregion
                    }
                }
                /**End Region**/
            }
            #endregion

        }
       
    }
    private void CreateEmailLog(string UniqueId, int StartLmt, string FromEmailId, string TotxtEmailId)
    {
        FPL.EmailId_From = FromEmailId;
        FPL.To_EmailId = TotxtEmailId;
        FPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
        FPL.EmailUniqueId = UniqueId;
        FPL.SendNo_Of_Email = StartLmt.ToString();
        FPL.LoginUserId = Session["LoginUserId"].ToString();
        int i = FBL.InsertEmaDoc(FPL);
    }

    public string SendPreMail(string emsub, string embody, string EmailId, string FileId, string EmailFromId, string Password)
    {
        string retval = "False";
        try
        {
            string emailBody, emailSubject, emailToList, emailFrom,
            accountPassword, smtpServer;
            bool enableSSL;
            int port;

            emailBody = embody;
            emailSubject = emsub;
            emailToList = EmailId;
            emailFrom = EmailFromId;
            accountPassword = Password;
            smtpServer = "smtp.gmail.com";
            enableSSL = true;
            port = 587;

            string crefilename;
            string fofile;
            fofile = Server.MapPath("PDF");
            crefilename = FileId + ".Pdf";

            string[] att = { crefilename };

            string retemail, insertqry;
            retemail = "";

            retemail = SendEmail(emailBody, emailSubject, emailFrom, emailToList, att, smtpServer, enableSSL, accountPassword, port);

            if (retemail == "True")
            {

                retval = retemail;
            }
        }
        catch
        {
            retval = "False";
        }
        finally
        {

        }
        return retval;
    }

    public string SendEmail(string emailBody, string emailSubject, string emailFrom, string emailToList, string[] attachedFiles, string smtpIPAddress, bool enableSSL, string accountPassword, int port)
    {
        MailMessage mail = new MailMessage();
        string retflg;
        retflg = "False";
        try
        {
            mail.From = new MailAddress(emailFrom);
            if (emailToList.Contains(";"))
            {
                emailToList = emailToList.Replace(";", ",");
            }
            mail.To.Add(emailToList);

            mail.Subject = emailSubject;
            mail.IsBodyHtml = true;
            mail.Body = emailBody;


            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential(emailFrom, accountPassword);
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mail);
            retflg = "True";

        }
        catch
        {
            retflg = "False";
        }
        finally
        {
            mail.Dispose();
        }
        return retflg;
    }

How to access your website through LAN in ASP.NET

You will need to configure you IIS (assuming this is the web server your are/will using) allowing access from WLAN/LAN to specific users (or anonymous). Allow IIS trought your firewall if you have one.

Your application won't need to be changed, that's just networking problems ans configuration you will have to face to allow acces only trought LAN and WLAN.

Emulate ggplot2 default color palette

It is just equally spaced hues around the color wheel, starting from 15:

gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

For example:

n = 4
cols = gg_color_hue(n)

dev.new(width = 4, height = 4)
plot(1:n, pch = 16, cex = 2, col = cols)

enter image description here

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

Question still relevant as of Android Studio 3.5.2 for Windows.

In my specific use case, I was trying to add Gander (https://github.com/Ashok-Varma/Gander) to my list of dependencies when I keep getting this particular headache.

It turns out that I have yet to get JCenter Certificate approved in my cacerts file. I'm going through a company firewall and i had to do this with dependencies that I attempt to import. Thus, to do so:

  1. Ensure that your Android Studio does not need to go through any proxy.

  2. Export the certificate where you get your dependency (usually just JCenter)

  3. Add the certificate to your cacerts file:

    keytool -import -alias [your-certificate-name] -keystore 'C:\Program Files\Java\jdk[version]\jre\lib\security\cacerts' -file [absolute\path\to\your\certificate].cer

  4. Restart Android Studio

  5. Try syncing again.

Answer is based on this one: https://stackoverflow.com/a/26183328/4972380

Add custom message to thrown exception while maintaining stack trace in Java

you can use super while extending Exception

if (pass.length() < minPassLength)
    throw new InvalidPassException("The password provided is too short");
 } catch (NullPointerException e) {
    throw new InvalidPassException("No password provided", e);
 }


// A custom business exception
class InvalidPassException extends Exception {

InvalidPassException() {

}

InvalidPassException(String message) {
    super(message);
}
InvalidPassException(String message, Throwable cause) {
   super(message, cause);
}

}

}

source

force css grid container to fill full screen of device

Two important CSS properties to set for full height pages are these:

  1. Allow the body to grow as high as the content in it requires.

    html { height: 100%; }
    
  2. Force the body not to get any smaller than then window height.

    body { min-height: 100%; }
    

What you do with your gird is irrelevant as long as you use fractions or percentages you should be safe in all cases.

Have a look at this common dashboard layout.

Reusing output from last command in Bash

Very Simple Solution

One that I've used for years.

Script (add to your .bashrc or .bash_profile)

# capture the output of a command so it can be retrieved with ret
cap () { tee /tmp/capture.out}

# return the output of the most recent command that was captured by cap
ret () { cat /tmp/capture.out }

Usage

$ find . -name 'filename' | cap
/path/to/filename

$ ret
/path/to/filename

I tend to add | cap to the end of all of my commands. This way when I find I want to do text processing on the output of a slow running command I can always retrieve it with res.

android:drawableLeft margin and/or padding

Make your drawable resources.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <inset android:drawable="@drawable/small_m" android:insetLeft="10dp" android:insetTop="10dp" />
    </item>
    <item>
        <inset android:drawable="@drawable/small_p" android:insetLeft="10dp" android:insetTop="10dp" />
    </item>
</selector>

Rails :include vs. :joins

'joins' just used to join tables and when you called associations on joins then it will again fire query (it mean many query will fire)

lets suppose you have tow model, User and Organisation
User has_many organisations
suppose you have 10 organisation for a user 
@records= User.joins(:organisations).where("organisations.user_id = 1")
QUERY will be 
 select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1

it will return all records of organisation related to user
and @records.map{|u|u.organisation.name}
it run QUERY like 
select * from organisations where organisations.id = x then time(hwo many organisation you have)

total number of SQL is 11 in this case

But with 'includes' will eager load the included associations and add them in memory(load all associations on first load) and not fire query again

when you get records with includes like @records= User.includes(:organisations).where("organisations.user_id = 1") then query will be

select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1
and 


 select * from organisations where organisations.id IN(IDS of organisation(1, to 10)) if 10 organisation
and when you run this 

@records.map{|u|u.organisation.name} no query will fire

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

Enter triggers button click

Using

<button type="button">Whatever</button>

should do the trick.

The reason is because a button inside a form has its type implicitly set to submit. As zzzzBoz says, the Spec says that the first button or input with type="submit" is what is triggered in this situation. If you specifically set type="button", then it's removed from consideration by the browser.

Google reCAPTCHA: How to get user response and validate in the server side?

Here is complete demo code to understand client side and server side process. you can copy paste it and just replace google site key and google secret key.

<?php 
if(!empty($_REQUEST))
{
      //  echo '<pre>'; print_r($_REQUEST); die('END');
        $post = [
            'secret' => 'Your Secret key',
            'response' => $_REQUEST['g-recaptcha-response'],
        ];
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec($ch);

        curl_close ($ch);
        echo '<pre>'; print_r($server_output); die('ss');
}
?>
<html>
  <head>
    <title>reCAPTCHA demo: Explicit render for multiple widgets</title>
    <script type="text/javascript">
      var site_key = 'Your Site key';
      var verifyCallback = function(response) {
        alert(response);
      };
      var widgetId1;
      var widgetId2;
      var onloadCallback = function() {
        // Renders the HTML element with id 'example1' as a reCAPTCHA widget.
        // The id of the reCAPTCHA widget is assigned to 'widgetId1'.
        widgetId1 = grecaptcha.render('example1', {
          'sitekey' : site_key,
          'theme' : 'light'
        });
        widgetId2 = grecaptcha.render(document.getElementById('example2'), {
          'sitekey' : site_key
        });
        grecaptcha.render('example3', {
          'sitekey' : site_key,
          'callback' : verifyCallback,
          'theme' : 'dark'
        });
      };
    </script>
  </head>
  <body>
    <!-- The g-recaptcha-response string displays in an alert message upon submit. -->
    <form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
      <div id="example1"></div>
      <br>
      <input type="submit" value="getResponse">
    </form>
    <br>
    <!-- Resets reCAPTCHA widgetId2 upon submit. -->
    <form action="javascript:grecaptcha.reset(widgetId2);">
      <div id="example2"></div>
      <br>
      <input type="submit" value="reset">
    </form>
    <br>
    <!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
    <form action="?" method="POST">
      <div id="example3"></div>
      <br>
      <input type="submit" value="Submit">
    </form>
    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
        async defer>
    </script>
  </body>
</html>

Make a DIV fill an entire table cell

This is my Solution for extend 100% height and 100% width in a html <td>

if you delete the first line in your code you can fix it ...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

because this doctype does not permit in some files to use the 100% percent inside of <td>, but if you delete this line, the body fails expanding the background to 100% height and 100% width, so I found this DOCTYPE that solves the problem

<!DOCTYPE html PUBLIC "-//IETF//DTD HTML 2.0//EN">

this DOCTYPE let you extends the background in your body as 100% height and 100% width, and let you take all the 100% height and 100% width into the <td>

Get IP address of visitors using Flask for Python

See the documentation on how to access the Request object and then get from this same Request object, the attribute remote_addr.

Code example

from flask import request
from flask import jsonify

@app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
    return jsonify({'ip': request.remote_addr}), 200

For more information see the Werkzeug documentation.

How to get JSON Key and Value?

$.each(result, function(key, value) {
  console.log(key+ ':' + value);
});

How to "perfectly" override a dict?

After trying out both of the top two suggestions, I've settled on a shady-looking middle route for Python 2.7. Maybe 3 is saner, but for me:

class MyDict(MutableMapping):
   # ... the few __methods__ that mutablemapping requires
   # and then this monstrosity
   @property
   def __class__(self):
       return dict

which I really hate, but seems to fit my needs, which are:

  • can override **my_dict
    • if you inherit from dict, this bypasses your code. try it out.
    • this makes #2 unacceptable for me at all times, as this is quite common in python code
  • masquerades as isinstance(my_dict, dict)
    • rules out MutableMapping alone, so #1 is not enough
    • I heartily recommend #1 if you don't need this, it's simple and predictable
  • fully controllable behavior
    • so I cannot inherit from dict

If you need to tell yourself apart from others, personally I use something like this (though I'd recommend better names):

def __am_i_me(self):
  return True

@classmethod
def __is_it_me(cls, other):
  try:
    return other.__am_i_me()
  except Exception:
    return False

As long as you only need to recognize yourself internally, this way it's harder to accidentally call __am_i_me due to python's name-munging (this is renamed to _MyDict__am_i_me from anything calling outside this class). Slightly more private than _methods, both in practice and culturally.

So far I have no complaints, aside from the seriously-shady-looking __class__ override. I'd be thrilled to hear of any problems that others encounter with this though, I don't fully understand the consequences. But so far I've had no problems whatsoever, and this allowed me to migrate a lot of middling-quality code in lots of locations without needing any changes.


As evidence: https://repl.it/repls/TraumaticToughCockatoo

Basically: copy the current #2 option, add print 'method_name' lines to every method, and then try this and watch the output:

d = LowerDict()  # prints "init", or whatever your print statement said
print '------'
splatted = dict(**d)  # note that there are no prints here

You'll see similar behavior for other scenarios. Say your fake-dict is a wrapper around some other datatype, so there's no reasonable way to store the data in the backing-dict; **your_dict will be empty, regardless of what every other method does.

This works correctly for MutableMapping, but as soon as you inherit from dict it becomes uncontrollable.


Edit: as an update, this has been running without a single issue for almost two years now, on several hundred thousand (eh, might be a couple million) lines of complicated, legacy-ridden python. So I'm pretty happy with it :)

Edit 2: apparently I mis-copied this or something long ago. @classmethod __class__ does not work for isinstance checks - @property __class__ does: https://repl.it/repls/UnitedScientificSequence

Error: Could not find or load main class

Check your BuildPath, it could be that you are referencing a library that does not exist anymore.

Printing Exception Message in java

The output looks correct to me:

Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1

I think Invalid Javascript code: .. is the start of the exception message.

Normally the stacktrace isn't returned with the message:

try {
    throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
    System.out.println(e.getMessage()); // prints "hu?"
}

So maybe the code you are calling catches an exception and rethrows a ScriptException. In this case maybe e.getCause().getMessage() can help you.

Do I need a content-type header for HTTP GET requests?

The accepted answer is wrong. The quote is correct, the assertion that PUT and POST must have it is incorrect. There is no requirement that PUT or POST actually have additional content. Nor is there a prohibition against GET actually having content.

The RFCs say exactly what they mean .. IFF your side (client OR origin server) will be sending additional content, beyond the HTTP headers, it SHOULD specify a Content-Type header. But note it is allowable to omit the Content-Type and still include content (say, by using a Content-Length header).

Adding a y-axis label to secondary y-axis in matplotlib

The best way is to interact with the axes object directly

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

plt.show()

example graph

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

In the future the format might need to be changed which could be a small head ache having date.dateFromISO8601 calls everywhere in an app. Use a class and protocol to wrap the implementation, changing the date time format call in one place will be simpler. Use RFC3339 if possible, its a more complete representation. DateFormatProtocol and DateFormat is great for dependency injection.

class AppDelegate: UIResponder, UIApplicationDelegate {

    internal static let rfc3339DateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
    internal static let localeEnUsPosix = "en_US_POSIX"
}

import Foundation

protocol DateFormatProtocol {

    func format(date: NSDate) -> String
    func parse(date: String) -> NSDate?

}


import Foundation

class DateFormat:  DateFormatProtocol {

    func format(date: NSDate) -> String {
        return date.rfc3339
    }

    func parse(date: String) -> NSDate? {
        return date.rfc3339
    }

}


extension NSDate {

    struct Formatter {
        static let rfc3339: NSDateFormatter = {
            let formatter = NSDateFormatter()
            formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
            formatter.locale = NSLocale(localeIdentifier: AppDelegate.localeEnUsPosix)
            formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
            formatter.dateFormat = rfc3339DateFormat
            return formatter
        }()
    }

    var rfc3339: String { return Formatter.rfc3339.stringFromDate(self) }
}

extension String {
    var rfc3339: NSDate? {
        return NSDate.Formatter.rfc3339.dateFromString(self)
    }
}



class DependencyService: DependencyServiceProtocol {

    private var dateFormat: DateFormatProtocol?

    func setDateFormat(dateFormat: DateFormatProtocol) {
        self.dateFormat = dateFormat
    }

    func getDateFormat() -> DateFormatProtocol {
        if let dateFormatObject = dateFormat {

            return dateFormatObject
        } else {
            let dateFormatObject = DateFormat()
            dateFormat = dateFormatObject

            return dateFormatObject
        }
    }

}

'Framework not found' in Xcode

Delete the framework that is causing the issue (by removing the reference).

Then add it again, following these steps for adding FBSDK frameworks and libraries:

  1. click project
  2. general settings
  3. linked framework and libraries
  4. click the plus button and add all that you want

Angular window resize event

<div (window:resize)="onResize($event)"
onResize(event) {
  event.target.innerWidth;
}

or using the HostListener decorator:

@HostListener('window:resize', ['$event'])
onResize(event) {
  event.target.innerWidth;
}

Supported global targets are window, document, and body.

Until https://github.com/angular/angular/issues/13248 is implemented in Angular it is better for performance to subscribe to DOM events imperatively and use RXJS to reduce the amount of events as shown in some of the other answers.

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

for anyone who comes across this problem now, with android studio 4.0+ you just have to enable java 8 as mentioned here

android {
    defaultConfig {
            ...
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Setting selection to Nothing when programming Excel

If you select a cell in an already selected range, it will not work. But, Selecting a range outside the original selection will clear the original selection.

'* The original selection *' ActiveSheet.range("A1:K10").Select

'* New Selections *' Activesheet.Range("L1").Select

'* Then *' Activesheet.Range("A1").Select

Showing all errors and warnings

Display errors could be turned off in the php.ini or your Apache configuration file.

You can turn it on in the script:

error_reporting(E_ALL);
ini_set('display_errors', '1');

You should see the same messages in the PHP error log.

Using JavaMail with TLS

We actually have some notification code in our product that uses TLS to send mail if it is available.

You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.

Properties props = new Properties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");  // If you need to authenticate
// Use the following if you need SSL
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

You can then either pass this to a JavaMail Session or any other session instantiator like Session.getDefaultInstance(props).

How to place div in top right hand corner of page

You can use css float

<div style='float: left;'><a href="login.php">Log in</a></div>

<div style='float: right;'><a href="home.php">Back to Home</a></div>

Have a look at this CSS Positioning

Python socket connection timeout

If you are using Python2.6 or newer, it's convenient to use socket.create_connection

sock = socket.create_connection(address, timeout=10)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

npm install doesn't create node_modules directory

As soon as you have run npm init and you start installing npm packages it'll create the node_moduals folder after that first install

e.g

npm init

(Asks you to set up your package.json file)

npm install <package name here> --save-dev

installs package & creates the node modules directory

C++ String Declaring

C++ supplies a string class that can be used like this:

#include <string>
#include <iostream>

int main() {
    std::string Something = "Some text";
    std::cout << Something << std::endl;
}

Date difference in minutes in Python

If you are trying to find the difference between timestamps that are in pandas columns, the the answer is fairly simple. If you need it in days or seconds then

# For difference in days:
df['diff_in_days']=(df['timestamp2'] - df['timestamp1']).dt.days
# For difference in seconds
df['diff_in_seconds']=(df['timestamp2'] - df['timestamp1']).dt.seconds

Now minute is tricky as dt.minute works only on datetime64[ns] dtype. whereas the column generated from subtracting two datetimes has format

AttributeError: 'TimedeltaProperties' object has no attribute 'm8'

So like mentioned by many above to get the actual value of the difference in minute you have to do:

df['diff_in_min']=df['diff_in_seconds']/60

But if just want the difference between the minute parts of the two timestamps then do the following

#convert the timedelta to datetime and then extract minute
df['diff_in_min']=(pd.to_datetime(df['timestamp2']-df['timestamp1'])).dt.minute

You can also read the article https://docs.python.org/3.4/library/datetime.html and see section 8.1.2 you'll see the read only attributes are only seconds,days and milliseconds. And this settles why the minute function doesn't work directly.

How do I filter date range in DataTables?

Here is DataTable with Single DatePicker as "from" Date Filter

LiveDemo

Here is DataTable with Two DatePickers for DateRange (To and From) Filter

LiveDemo

How to clear APC cache entries?

Another possibility for command-line usage, not yet mentioned, is to use curl.

This doesn't solve your problem for all cache entries if you're using the stock apc.php script, but it could call an adapted script or another one you've put in place.

This clears the opcode cache:

curl --user apc:$PASSWORD "http://www.example.com/apc.php?CC=1&OB=1&`date +%s`"

Change the OB parameter to 3 to clear the user cache:

curl --user apc:$PASSWORD "http://www.example.com/apc.php?CC=1&OB=3&`date +%s`"

Put both lines in a script and call it with $PASSWORD in your env.

When should I use semicolons in SQL Server?

When using either a DISABLE or ENABLE TRIGGER statement in a batch that has other statements in it, the statement just before it must end with a semicolon. Otherwise, you'll get a syntax error. I tore my hair out with this one... And afterwards, I stumbled on this MS Connect item about the same thing. It is closed as won't fix.

see here

Reinitialize Slick js after successful ajax call

You should use the unslick method:

function getSliderSettings(){
  return {
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1
  }
}

$.ajax({
  type: 'get',
  url: '/public/index',
  dataType: 'script',
  data: data_send,
  success: function() {
    $('.skills_section').slick('unslick'); /* ONLY remove the classes and handlers added on initialize */
    $('.my-slide').remove(); /* Remove current slides elements, in case that you want to show new slides. */
    $('.skills_section').slick(getSliderSettings()); /* Initialize the slick again */
  }
});

AngularJs $http.post() does not send data

I know has accepted answer. But, following might help to future readers, if the answer doesn't suit them for any reason.

Angular doesn't do ajax same as jQuery. While I tried to follow the guide to modify angular $httpprovider , I encountered other problems. E.g. I use codeigniter in which $this->input->is_ajax_request() function always failed (which was written by another programmer and used globally, so cant change) saying this was not real ajax request.

To solve it, I took help of deferred promise. I tested it in Firefox, and ie9 and it worked.

I have following function defined outside any of the angular code. This function makes regular jquery ajax call and returns deferred/promise (I'm still learning) object.

function getjQueryAjax(url, obj){
    return $.ajax({
        type: 'post',
        url: url,
        cache: true,
        data: obj
    });
}

Then I'm calling it angular code using the following code. Please note that we have to update the $scope manually using $scope.$apply() .

    var data = {
        media: "video",
        scope: "movies"
    };
    var rPromise = getjQueryAjax("myController/getMeTypes" , data);
    rPromise.success(function(response){
        console.log(response);
        $scope.$apply(function(){
            $scope.testData = JSON.parse(response);
            console.log($scope.testData);
        });
    }).error(function(){
        console.log("AJAX failed!");
    });

This may not be the perfect answer, but it allowed me to use jquery ajax calls with angular and allowed me to update the $scope.

When do I use path params vs. query params in a RESTful API?

Segmentation is more hierarchal and "pretty" but can be limiting.

For example, if you have a url with three segments, each one passing different parameters to search for a car via make, model and color:

www.example.com/search/honda/civic/blue

This is a very pretty url and more easily remembered by the end user, but now your kind of stuck with this structure. Say you want to make it so that in the search the user could search for ALL blue cars, or ALL Honda Civics? A query parameter solves this because it give a key value pair. So you could pass:

www.example.com/search?color=blue
www.example.com/search?make=civic

Now you have a way to reference the value via it's key - either "color" or "make" in your query code.

You could get around this by possibly using more segments to create a kind of key value structure like:

www.example.com/search/make/honda/model/civic/color/blue

Hope that makes sense..

Get the cell value of a GridView row

Have you tried Cell[0]? Remember indexes start at 0, not 1.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

How to run an EXE file in PowerShell with parameters with spaces and quotes

I had spaces in both command and parameters, and this is what worked for me:

$Command = "E:\X64\Xendesktop Setup\XenDesktopServerSetup.exe"
$Parms = "/COMPONENTS CONTROLLER,DESKTOPSTUDIO,DESKTOPDIRECTOR,LICENSESERVER,STOREFRONT /PASSIVE /NOREBOOT /CONFIGURE_FIREWALL /NOSQL"

$Prms = $Parms.Split(" ")
& "$Command" $Prms

It's basically the same as Akira's answer, but this works if you dynamically build your command parameters and put them in a variable.

Get value from hidden field using jQuery

html

<input type="hidden" value="hidden value" id='h_v' class='h_v'>

js

var hv = $('#h_v').attr("value");
alert(hv);

example

IF a cell contains a string

SEARCH does not return 0 if there is no match, it returns #VALUE!. So you have to wrap calls to SEARCH with IFERROR.

For example...

=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")

or

=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))

Here, IFERROR returns the value from SEARCH when it works; the given value of 0 otherwise.

WCF service maxReceivedMessageSize basicHttpBinding issue

Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:

<services>
  <service name="Service.IService">
    <clear />
    <endpoint binding="basicHttpBinding" contract="Service.IService" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
        maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
  </basicHttpBinding>
  <webHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
  </webHttpBinding>
</bindings>

Also note that I removed the bindingConfiguration attribute from the endpoint node. Otherwise you would get an exception.

This same solution was found here : Problem with large requests in WCF

Watch multiple $scope attributes

$watch first parameter can also be a function.

$scope.$watch(function watchBothItems() {
  return itemsCombinedValue();
}, function whenItemsChange() {
  //stuff
});

If your two combined values are simple, the first parameter is just an angular expression normally. For example, firstName and lastName:

$scope.$watch('firstName + lastName', function() {
  //stuff
});

Execute PHP scripts within Node.js web server

A simple, fast approach in my opinion would be to use dnode-php for that.

You can see a brief introduction here. Simple, quick and easy!

How to convert string to boolean in typescript Angular 4

Method 1 :

var stringValue = "true";
var boolValue = (/true/i).test(stringValue) //returns true

Method 2 :

var stringValue = "true";
var boolValue = (stringValue =="true");   //returns true

Method 3 :

var stringValue = "true";
var boolValue = JSON.parse(stringValue);   //returns true

Method 4 :

var stringValue = "true";
var boolValue = stringValue.toLowerCase() == 'true'; //returns true

Method 5 :

var stringValue = "true";
var boolValue = getBoolean(stringValue); //returns true
function getBoolean(value){
   switch(value){
        case true:
        case "true":
        case 1:
        case "1":
        case "on":
        case "yes":
            return true;
        default: 
            return false;
    }
}

source: http://codippa.com/how-to-convert-string-to-boolean-javascript/

How to copy files across computers using SSH and MAC OS X Terminal

First zip or gzip the folders:
Use the following command:

zip -r NameYouWantForZipFile.zip foldertozip/

or

tar -pvczf BackUpDirectory.tar.gz /path/to/directory

for gzip compression use SCP:

scp [email protected]:~/serverpath/public_html ~/Desktop

SQL Format as of Round off removing decimals

use ROUND () (See examples ) function in sql server

select round(11.6,0)

result:

12.0

ex2:

select round(11.4,0)

result:

11.0

if you don't want the decimal part, you could do

select cast(round(11.6,0) as int)

Which browser has the best support for HTML 5 currently?

To test your browser, go to http://html5test.com/. The code is being maintained at: github dot com slash NielsLeenheer slash html5test.

Assign JavaScript variable to Java Variable in JSP

you cant do it.. because jsp is compiled and converted into html server side whereas javascript is executed on client side. you may set the value to a hidden html element and send to servlet in request just in case you want to use for further

How to get the difference between two arrays in JavaScript?

This question is old but is still the top hit for javascript array subtraction so I wanted to add the solution I am using. This fits for the following case:

var a1 = [1,2,2,3]
var a2 = [1,2]
//result = [2,3]

The following method will produced the desired result:

function arrayDifference(minuend, subtrahend) {
  for (var i = 0; i < minuend.length; i++) {
    var j = subtrahend.indexOf(minuend[i])
    if (j != -1) {
      minuend.splice(i, 1);
      subtrahend.splice(j, 1);
    }
  }
  return minuend;
}

It should be noted that the function does not include values from the subtrahend that are not present in the minuend:

var a1 = [1,2,3]
var a2 = [2,3,4]
//result = [1]

Find an object in SQL Server (cross-database)

select db_name(), * From sysobjects where xtype in ('U', 'P') And name = 'OBJECT_name'

First column will display name of database where object is located at.

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

This isn’t a solution in the sense that it doesn’t resolve the conditions which cause the message to appear in the logs, but the message can be suppressed by appending the following to conf/logging.properties:

org.apache.catalina.webresources.Cache.level = SEVERE

This filters out the “Unable to add the resource” logs, which are at level WARNING.

In my view a WARNING is not necessarily an error that needs to be addressed, but rather can be ignored if desired.

Access the css ":after" selector with jQuery

If you use jQuery built-in after() with empty value it will create a dynamic object that will match your :after CSS selector.

$('.active').after().click(function () {
    alert('clickable!');
});

See the jQuery documentation.

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

PHP filesize MB/KB conversion

This would be a cleaner implementation:

function size2Byte($size) {
    $units = array('KB', 'MB', 'GB', 'TB');
    $currUnit = '';
    while (count($units) > 0  &&  $size > 1024) {
        $currUnit = array_shift($units);
        $size /= 1024;
    }
    return ($size | 0) . $currUnit;
}

Set width of dropdown element in HTML select dropdown options

Small And Better One

var i = 0;
$("#container > option").each(function(){ 
    if($(this).val().length > i) {
        i = $(this).val().length;

        console.log(i);
        console.log($(this).val());
    }
});

How do I divide in the Linux console?

I also had the same problem. It's easy to divide integer numbers but decimal numbers are not that easy. if you have 2 numbers like 3.14 and 2.35 and divide the numbers then, the code will be Division=echo 3.14 / 2.35 | bc echo "$Division" the quotes are different. Don't be confused, it's situated just under the esc button on your keyboard. THE ONLY DIFFERENCE IS THE | bc and also here echo works as an operator for the arithmetic calculations in stead of printing. So, I had added echo "$Division" for printing the value. Let me know if it works for you. Thank you.

How to bring a window to the front?

Windows has the facility to prevent windows from stealing focus; instead it flashes the taskbar icon. In XP it's on by default (the only place I've seen to change it is using TweakUI, but there is a registry setting somewhere). In Vista they may have changed the default and/or exposed it as a user accessible setting with the out-of-the-box UI.

Preventing windows from forcing themselves to the front and taking focus is a feature since Windows 2K (and I, for one, am thankful for it).

That said, I have a little Java app I use to remind me to record my activities while working, and it makes itself the active window every 30 minutes (configurable, of course). It always works consistently under Windows XP and never flashes the title bar window. It uses the following code, called in the UI thread as a result of a timer event firing:

if(getState()!=Frame.NORMAL) { setState(Frame.NORMAL); }
toFront();
repaint();

(the first line restores if minimized... actually it would restore it if maximized too, but I never have it so).

While I usually have this app minimized, quite often it's simply behind my text editor. And, like I said, it always works.

I do have an idea on what your problem could be - perhaps you have a race condition with the setVisible() call. toFront() may not be valid unless the window is actually displayed when it is called; I have had this problem with requestFocus() before. You may need to put the toFront() call in a UI listener on a window activated event.

2014-09-07: At some point in time the above code stopped working, perhaps at Java 6 or 7. After some investigation and experimentation I had to update the code to override the window's toFront method do this (in conjunction with modified code from what is above):

setVisible(true);
toFront();
requestFocus();
repaint();

...

public @Override void toFront() {
    int sta = super.getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL;

    super.setExtendedState(sta);
    super.setAlwaysOnTop(true);
    super.toFront();
    super.requestFocus();
    super.setAlwaysOnTop(false);
}

As of Java 8_20, this code seems to be working fine.

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);
    }
}
fclose(pFile);
fclose(pFile2);

C# DataRow Empty-check

AFAIK, there is no method that does this in the framework. Even if there was support for something like this in the framework, it would essentially be doing the same thing. And that would be looking at each cell in the DataRow to see if it is empty.

How do I import a sql data file into SQL Server?

A .sql file is a set of commands that can be executed against the SQL server.

Sometimes the .sql file will specify the database, other times you may need to specify this.

You should talk to your DBA or whoever is responsible for maintaining your databases. They will probably want to give the file a quick look. .sql files can do a lot of harm, even inadvertantly.

See the other answers if you want to plunge ahead.

NOW() function in PHP

There is no built-in PHP now() function, but you can do it using date().

Example

function now() {
    return date('Y-m-d H:i:s');
}

You can use date_default_timezone_set() if you need to change timezone.

Otherwise you can make use of Carbon - A simple PHP API extension for DateTime.

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I can think of the following possible causes:

  1. there are files or subdirectories which need higher permissions
  2. there are files in use, not only by WSearch, but maybe by your virus scanner or anything else

For 1.) you can try runas /user:Administrator in order to get higher privileges or start the batch file as administrator via context menu. If that doesn't help, maybe even the administrator doesn't have the rights. Then you need to take over the ownership of the directory.

For 2.) download Process Explorer, click Find/Find handle or DLL... or press Ctrl+F, type the name of the directory and find out who uses it. Close the application which uses the directory, if possible.

What is PHPSESSID?

Check php.ini for auto session id.

If you enable it, you will have PHPSESSID in your cookies.

What happens if you mount to a non-empty mount point with fuse?

Apparently nothing happens, it fails in a non-destructive way and gives you a warning.

I've had this happen as well very recently. One way you can solve this is by moving all the files in the non-empty mount point to somewhere else, e.g.:

mv /nonEmptyMountPoint/* ~/Desktop/mountPointDump/

This way your mount point is now empty, and your mount command will work.

case in sql stored procedure on SQL Server

(SELECT CASE WHEN (SELECT  Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 )=0 THEN 'Pending'
WHEN (SELECT  Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 AND )<>0 THEN (SELECT CASE  WHEN ISNULL(ChequeNo,0) IS NOT NULL   THEN 'Deposit' ELSE 'Pending' END AS Deposite FROM tbl_EEsi WHERE  AND (Month= 1) AND (Year = 2020) AND )END AS Stat)

How do I change the default library path for R packages

Windows 7/10: If your C:\Program Files (or wherever R is installed) is blocked for writing, as mine is, then you'll get frustrated editing RProfile.site (as I did). As specified above, I updated R_LIBS_USER and it worked. However, even after reading the fine manual several times and extensive searching, it took me several hours to do this. In the spirit of saving someone else time...

Let's assume you want your packages to reside in C:\R\Library:

  1. Create the folder C:\R\Library
  2. Click Start --> Control Panel --> User Accounts --> Change my environmental variables
  3. The Environmental Variables window pops up. If you see R_LIBS_USER, highlight it and click Edit. Otherwise click New. Both actions open a window with fields for Variable and Value.
  4. In my case, R_LIBS_USER was already there, and the value was a path to my desktop. I added to the path the folder that I created, separated by semicolon as mentioned above. C:\R\Library;C:\Users\Eric.Krantz\Desktop\R stuff\Packages. NOTE: I could have removed the path to the Desktop location and simply left C:\R\Library.

Get Character value from KeyCode in JavaScript... then trim

Readable key names indexed by key code

There are relatively few key codes so I simply listed all the corresponding values in a static array so I could simply convert the number 65 into A using keyboardMap[65]

Not all key codes map to a printable character so some other identifiable string is returned.

You may need to modify the array to suit your needs and can simply return empty strings for all the characters you don't care to translate. The following array allows me to quickly and reliably determine which key was pressed in any environment. Enjoy!

// names of known key codes (0-255)

var keyboardMap = [
  "", // [0]
  "", // [1]
  "", // [2]
  "CANCEL", // [3]
  "", // [4]
  "", // [5]
  "HELP", // [6]
  "", // [7]
  "BACK_SPACE", // [8]
  "TAB", // [9]
  "", // [10]
  "", // [11]
  "CLEAR", // [12]
  "ENTER", // [13]
  "ENTER_SPECIAL", // [14]
  "", // [15]
  "SHIFT", // [16]
  "CONTROL", // [17]
  "ALT", // [18]
  "PAUSE", // [19]
  "CAPS_LOCK", // [20]
  "KANA", // [21]
  "EISU", // [22]
  "JUNJA", // [23]
  "FINAL", // [24]
  "HANJA", // [25]
  "", // [26]
  "ESCAPE", // [27]
  "CONVERT", // [28]
  "NONCONVERT", // [29]
  "ACCEPT", // [30]
  "MODECHANGE", // [31]
  "SPACE", // [32]
  "PAGE_UP", // [33]
  "PAGE_DOWN", // [34]
  "END", // [35]
  "HOME", // [36]
  "LEFT", // [37]
  "UP", // [38]
  "RIGHT", // [39]
  "DOWN", // [40]
  "SELECT", // [41]
  "PRINT", // [42]
  "EXECUTE", // [43]
  "PRINTSCREEN", // [44]
  "INSERT", // [45]
  "DELETE", // [46]
  "", // [47]
  "0", // [48]
  "1", // [49]
  "2", // [50]
  "3", // [51]
  "4", // [52]
  "5", // [53]
  "6", // [54]
  "7", // [55]
  "8", // [56]
  "9", // [57]
  "COLON", // [58]
  "SEMICOLON", // [59]
  "LESS_THAN", // [60]
  "EQUALS", // [61]
  "GREATER_THAN", // [62]
  "QUESTION_MARK", // [63]
  "AT", // [64]
  "A", // [65]
  "B", // [66]
  "C", // [67]
  "D", // [68]
  "E", // [69]
  "F", // [70]
  "G", // [71]
  "H", // [72]
  "I", // [73]
  "J", // [74]
  "K", // [75]
  "L", // [76]
  "M", // [77]
  "N", // [78]
  "O", // [79]
  "P", // [80]
  "Q", // [81]
  "R", // [82]
  "S", // [83]
  "T", // [84]
  "U", // [85]
  "V", // [86]
  "W", // [87]
  "X", // [88]
  "Y", // [89]
  "Z", // [90]
  "OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac)
  "", // [92]
  "CONTEXT_MENU", // [93]
  "", // [94]
  "SLEEP", // [95]
  "NUMPAD0", // [96]
  "NUMPAD1", // [97]
  "NUMPAD2", // [98]
  "NUMPAD3", // [99]
  "NUMPAD4", // [100]
  "NUMPAD5", // [101]
  "NUMPAD6", // [102]
  "NUMPAD7", // [103]
  "NUMPAD8", // [104]
  "NUMPAD9", // [105]
  "MULTIPLY", // [106]
  "ADD", // [107]
  "SEPARATOR", // [108]
  "SUBTRACT", // [109]
  "DECIMAL", // [110]
  "DIVIDE", // [111]
  "F1", // [112]
  "F2", // [113]
  "F3", // [114]
  "F4", // [115]
  "F5", // [116]
  "F6", // [117]
  "F7", // [118]
  "F8", // [119]
  "F9", // [120]
  "F10", // [121]
  "F11", // [122]
  "F12", // [123]
  "F13", // [124]
  "F14", // [125]
  "F15", // [126]
  "F16", // [127]
  "F17", // [128]
  "F18", // [129]
  "F19", // [130]
  "F20", // [131]
  "F21", // [132]
  "F22", // [133]
  "F23", // [134]
  "F24", // [135]
  "", // [136]
  "", // [137]
  "", // [138]
  "", // [139]
  "", // [140]
  "", // [141]
  "", // [142]
  "", // [143]
  "NUM_LOCK", // [144]
  "SCROLL_LOCK", // [145]
  "WIN_OEM_FJ_JISHO", // [146]
  "WIN_OEM_FJ_MASSHOU", // [147]
  "WIN_OEM_FJ_TOUROKU", // [148]
  "WIN_OEM_FJ_LOYA", // [149]
  "WIN_OEM_FJ_ROYA", // [150]
  "", // [151]
  "", // [152]
  "", // [153]
  "", // [154]
  "", // [155]
  "", // [156]
  "", // [157]
  "", // [158]
  "", // [159]
  "CIRCUMFLEX", // [160]
  "EXCLAMATION", // [161]
  "DOUBLE_QUOTE", // [162]
  "HASH", // [163]
  "DOLLAR", // [164]
  "PERCENT", // [165]
  "AMPERSAND", // [166]
  "UNDERSCORE", // [167]
  "OPEN_PAREN", // [168]
  "CLOSE_PAREN", // [169]
  "ASTERISK", // [170]
  "PLUS", // [171]
  "PIPE", // [172]
  "HYPHEN_MINUS", // [173]
  "OPEN_CURLY_BRACKET", // [174]
  "CLOSE_CURLY_BRACKET", // [175]
  "TILDE", // [176]
  "", // [177]
  "", // [178]
  "", // [179]
  "", // [180]
  "VOLUME_MUTE", // [181]
  "VOLUME_DOWN", // [182]
  "VOLUME_UP", // [183]
  "", // [184]
  "", // [185]
  "SEMICOLON", // [186]
  "EQUALS", // [187]
  "COMMA", // [188]
  "MINUS", // [189]
  "PERIOD", // [190]
  "SLASH", // [191]
  "BACK_QUOTE", // [192]
  "", // [193]
  "", // [194]
  "", // [195]
  "", // [196]
  "", // [197]
  "", // [198]
  "", // [199]
  "", // [200]
  "", // [201]
  "", // [202]
  "", // [203]
  "", // [204]
  "", // [205]
  "", // [206]
  "", // [207]
  "", // [208]
  "", // [209]
  "", // [210]
  "", // [211]
  "", // [212]
  "", // [213]
  "", // [214]
  "", // [215]
  "", // [216]
  "", // [217]
  "", // [218]
  "OPEN_BRACKET", // [219]
  "BACK_SLASH", // [220]
  "CLOSE_BRACKET", // [221]
  "QUOTE", // [222]
  "", // [223]
  "META", // [224]
  "ALTGR", // [225]
  "", // [226]
  "WIN_ICO_HELP", // [227]
  "WIN_ICO_00", // [228]
  "", // [229]
  "WIN_ICO_CLEAR", // [230]
  "", // [231]
  "", // [232]
  "WIN_OEM_RESET", // [233]
  "WIN_OEM_JUMP", // [234]
  "WIN_OEM_PA1", // [235]
  "WIN_OEM_PA2", // [236]
  "WIN_OEM_PA3", // [237]
  "WIN_OEM_WSCTRL", // [238]
  "WIN_OEM_CUSEL", // [239]
  "WIN_OEM_ATTN", // [240]
  "WIN_OEM_FINISH", // [241]
  "WIN_OEM_COPY", // [242]
  "WIN_OEM_AUTO", // [243]
  "WIN_OEM_ENLW", // [244]
  "WIN_OEM_BACKTAB", // [245]
  "ATTN", // [246]
  "CRSEL", // [247]
  "EXSEL", // [248]
  "EREOF", // [249]
  "PLAY", // [250]
  "ZOOM", // [251]
  "", // [252]
  "PA1", // [253]
  "WIN_OEM_CLEAR", // [254]
  "" // [255]
];

Note: The position of each value in the array above is important. The "" are placeholders for codes with unknown values.

Try the following code snippet using this static array lookup approach...

_x000D_
_x000D_
var keyCodes = [];_x000D_
_x000D_
$("#reset").click(function() {_x000D_
  keyCodes = [];_x000D_
  $("#in").val("");_x000D_
  $("#key-codes").html("var keyCodes = [ ];");_x000D_
  $("#key-names").html("var keyNames = [ ];");_x000D_
});_x000D_
_x000D_
$(document).keydown(function(e) {_x000D_
  keyCodes.push(e.which);_x000D_
  updateOutput();_x000D_
});_x000D_
_x000D_
function updateOutput() {_x000D_
  var kC = "var keyCodes = [ ";_x000D_
  var kN = "var keyNames = [ ";_x000D_
_x000D_
  var len = keyCodes.length;_x000D_
_x000D_
  for (var i = 0; i < len; i++) {_x000D_
    kC += keyCodes[i];_x000D_
    kN += "'"+keyboardMap[keyCodes[i]]+"'";_x000D_
    if (i !== (len - 1)) {_x000D_
      kC += ", ";_x000D_
      kN += ", ";_x000D_
    }_x000D_
  }_x000D_
_x000D_
  kC += " ];";_x000D_
  kN += " ];";_x000D_
_x000D_
  $("#key-codes").html(kC);_x000D_
  $("#key-names").html(kN);_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
var keyboardMap = [_x000D_
  "", // [0]_x000D_
  "", // [1]_x000D_
  "", // [2]_x000D_
  "CANCEL", // [3]_x000D_
  "", // [4]_x000D_
  "", // [5]_x000D_
  "HELP", // [6]_x000D_
  "", // [7]_x000D_
  "BACK_SPACE", // [8]_x000D_
  "TAB", // [9]_x000D_
  "", // [10]_x000D_
  "", // [11]_x000D_
  "CLEAR", // [12]_x000D_
  "ENTER", // [13]_x000D_
  "ENTER_SPECIAL", // [14]_x000D_
  "", // [15]_x000D_
  "SHIFT", // [16]_x000D_
  "CONTROL", // [17]_x000D_
  "ALT", // [18]_x000D_
  "PAUSE", // [19]_x000D_
  "CAPS_LOCK", // [20]_x000D_
  "KANA", // [21]_x000D_
  "EISU", // [22]_x000D_
  "JUNJA", // [23]_x000D_
  "FINAL", // [24]_x000D_
  "HANJA", // [25]_x000D_
  "", // [26]_x000D_
  "ESCAPE", // [27]_x000D_
  "CONVERT", // [28]_x000D_
  "NONCONVERT", // [29]_x000D_
  "ACCEPT", // [30]_x000D_
  "MODECHANGE", // [31]_x000D_
  "SPACE", // [32]_x000D_
  "PAGE_UP", // [33]_x000D_
  "PAGE_DOWN", // [34]_x000D_
  "END", // [35]_x000D_
  "HOME", // [36]_x000D_
  "LEFT", // [37]_x000D_
  "UP", // [38]_x000D_
  "RIGHT", // [39]_x000D_
  "DOWN", // [40]_x000D_
  "SELECT", // [41]_x000D_
  "PRINT", // [42]_x000D_
  "EXECUTE", // [43]_x000D_
  "PRINTSCREEN", // [44]_x000D_
  "INSERT", // [45]_x000D_
  "DELETE", // [46]_x000D_
  "", // [47]_x000D_
  "0", // [48]_x000D_
  "1", // [49]_x000D_
  "2", // [50]_x000D_
  "3", // [51]_x000D_
  "4", // [52]_x000D_
  "5", // [53]_x000D_
  "6", // [54]_x000D_
  "7", // [55]_x000D_
  "8", // [56]_x000D_
  "9", // [57]_x000D_
  "COLON", // [58]_x000D_
  "SEMICOLON", // [59]_x000D_
  "LESS_THAN", // [60]_x000D_
  "EQUALS", // [61]_x000D_
  "GREATER_THAN", // [62]_x000D_
  "QUESTION_MARK", // [63]_x000D_
  "AT", // [64]_x000D_
  "A", // [65]_x000D_
  "B", // [66]_x000D_
  "C", // [67]_x000D_
  "D", // [68]_x000D_
  "E", // [69]_x000D_
  "F", // [70]_x000D_
  "G", // [71]_x000D_
  "H", // [72]_x000D_
  "I", // [73]_x000D_
  "J", // [74]_x000D_
  "K", // [75]_x000D_
  "L", // [76]_x000D_
  "M", // [77]_x000D_
  "N", // [78]_x000D_
  "O", // [79]_x000D_
  "P", // [80]_x000D_
  "Q", // [81]_x000D_
  "R", // [82]_x000D_
  "S", // [83]_x000D_
  "T", // [84]_x000D_
  "U", // [85]_x000D_
  "V", // [86]_x000D_
  "W", // [87]_x000D_
  "X", // [88]_x000D_
  "Y", // [89]_x000D_
  "Z", // [90]_x000D_
  "OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac)_x000D_
  "", // [92]_x000D_
  "CONTEXT_MENU", // [93]_x000D_
  "", // [94]_x000D_
  "SLEEP", // [95]_x000D_
  "NUMPAD0", // [96]_x000D_
  "NUMPAD1", // [97]_x000D_
  "NUMPAD2", // [98]_x000D_
  "NUMPAD3", // [99]_x000D_
  "NUMPAD4", // [100]_x000D_
  "NUMPAD5", // [101]_x000D_
  "NUMPAD6", // [102]_x000D_
  "NUMPAD7", // [103]_x000D_
  "NUMPAD8", // [104]_x000D_
  "NUMPAD9", // [105]_x000D_
  "MULTIPLY", // [106]_x000D_
  "ADD", // [107]_x000D_
  "SEPARATOR", // [108]_x000D_
  "SUBTRACT", // [109]_x000D_
  "DECIMAL", // [110]_x000D_
  "DIVIDE", // [111]_x000D_
  "F1", // [112]_x000D_
  "F2", // [113]_x000D_
  "F3", // [114]_x000D_
  "F4", // [115]_x000D_
  "F5", // [116]_x000D_
  "F6", // [117]_x000D_
  "F7", // [118]_x000D_
  "F8", // [119]_x000D_
  "F9", // [120]_x000D_
  "F10", // [121]_x000D_
  "F11", // [122]_x000D_
  "F12", // [123]_x000D_
  "F13", // [124]_x000D_
  "F14", // [125]_x000D_
  "F15", // [126]_x000D_
  "F16", // [127]_x000D_
  "F17", // [128]_x000D_
  "F18", // [129]_x000D_
  "F19", // [130]_x000D_
  "F20", // [131]_x000D_
  "F21", // [132]_x000D_
  "F22", // [133]_x000D_
  "F23", // [134]_x000D_
  "F24", // [135]_x000D_
  "", // [136]_x000D_
  "", // [137]_x000D_
  "", // [138]_x000D_
  "", // [139]_x000D_
  "", // [140]_x000D_
  "", // [141]_x000D_
  "", // [142]_x000D_
  "", // [143]_x000D_
  "NUM_LOCK", // [144]_x000D_
  "SCROLL_LOCK", // [145]_x000D_
  "WIN_OEM_FJ_JISHO", // [146]_x000D_
  "WIN_OEM_FJ_MASSHOU", // [147]_x000D_
  "WIN_OEM_FJ_TOUROKU", // [148]_x000D_
  "WIN_OEM_FJ_LOYA", // [149]_x000D_
  "WIN_OEM_FJ_ROYA", // [150]_x000D_
  "", // [151]_x000D_
  "", // [152]_x000D_
  "", // [153]_x000D_
  "", // [154]_x000D_
  "", // [155]_x000D_
  "", // [156]_x000D_
  "", // [157]_x000D_
  "", // [158]_x000D_
  "", // [159]_x000D_
  "CIRCUMFLEX", // [160]_x000D_
  "EXCLAMATION", // [161]_x000D_
  "DOUBLE_QUOTE", // [162]_x000D_
  "HASH", // [163]_x000D_
  "DOLLAR", // [164]_x000D_
  "PERCENT", // [165]_x000D_
  "AMPERSAND", // [166]_x000D_
  "UNDERSCORE", // [167]_x000D_
  "OPEN_PAREN", // [168]_x000D_
  "CLOSE_PAREN", // [169]_x000D_
  "ASTERISK", // [170]_x000D_
  "PLUS", // [171]_x000D_
  "PIPE", // [172]_x000D_
  "HYPHEN_MINUS", // [173]_x000D_
  "OPEN_CURLY_BRACKET", // [174]_x000D_
  "CLOSE_CURLY_BRACKET", // [175]_x000D_
  "TILDE", // [176]_x000D_
  "", // [177]_x000D_
  "", // [178]_x000D_
  "", // [179]_x000D_
  "", // [180]_x000D_
  "VOLUME_MUTE", // [181]_x000D_
  "VOLUME_DOWN", // [182]_x000D_
  "VOLUME_UP", // [183]_x000D_
  "", // [184]_x000D_
  "", // [185]_x000D_
  "SEMICOLON", // [186]_x000D_
  "EQUALS", // [187]_x000D_
  "COMMA", // [188]_x000D_
  "MINUS", // [189]_x000D_
  "PERIOD", // [190]_x000D_
  "SLASH", // [191]_x000D_
  "BACK_QUOTE", // [192]_x000D_
  "", // [193]_x000D_
  "", // [194]_x000D_
  "", // [195]_x000D_
  "", // [196]_x000D_
  "", // [197]_x000D_
  "", // [198]_x000D_
  "", // [199]_x000D_
  "", // [200]_x000D_
  "", // [201]_x000D_
  "", // [202]_x000D_
  "", // [203]_x000D_
  "", // [204]_x000D_
  "", // [205]_x000D_
  "", // [206]_x000D_
  "", // [207]_x000D_
  "", // [208]_x000D_
  "", // [209]_x000D_
  "", // [210]_x000D_
  "", // [211]_x000D_
  "", // [212]_x000D_
  "", // [213]_x000D_
  "", // [214]_x000D_
  "", // [215]_x000D_
  "", // [216]_x000D_
  "", // [217]_x000D_
  "", // [218]_x000D_
  "OPEN_BRACKET", // [219]_x000D_
  "BACK_SLASH", // [220]_x000D_
  "CLOSE_BRACKET", // [221]_x000D_
  "QUOTE", // [222]_x000D_
  "", // [223]_x000D_
  "META", // [224]_x000D_
  "ALTGR", // [225]_x000D_
  "", // [226]_x000D_
  "WIN_ICO_HELP", // [227]_x000D_
  "WIN_ICO_00", // [228]_x000D_
  "", // [229]_x000D_
  "WIN_ICO_CLEAR", // [230]_x000D_
  "", // [231]_x000D_
  "", // [232]_x000D_
  "WIN_OEM_RESET", // [233]_x000D_
  "WIN_OEM_JUMP", // [234]_x000D_
  "WIN_OEM_PA1", // [235]_x000D_
  "WIN_OEM_PA2", // [236]_x000D_
  "WIN_OEM_PA3", // [237]_x000D_
  "WIN_OEM_WSCTRL", // [238]_x000D_
  "WIN_OEM_CUSEL", // [239]_x000D_
  "WIN_OEM_ATTN", // [240]_x000D_
  "WIN_OEM_FINISH", // [241]_x000D_
  "WIN_OEM_COPY", // [242]_x000D_
  "WIN_OEM_AUTO", // [243]_x000D_
  "WIN_OEM_ENLW", // [244]_x000D_
  "WIN_OEM_BACKTAB", // [245]_x000D_
  "ATTN", // [246]_x000D_
  "CRSEL", // [247]_x000D_
  "EXSEL", // [248]_x000D_
  "EREOF", // [249]_x000D_
  "PLAY", // [250]_x000D_
  "ZOOM", // [251]_x000D_
  "", // [252]_x000D_
  "PA1", // [253]_x000D_
  "WIN_OEM_CLEAR", // [254]_x000D_
  "" // [255]_x000D_
];
_x000D_
#key-codes,_x000D_
#key-names {_x000D_
  font-family: courier, serif;_x000D_
  font-size: 1.2em;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input id="in" placeholder="Type here..." />_x000D_
<button id="reset">Reset</button>_x000D_
<br/>_x000D_
<br/>_x000D_
<div id="key-codes">var keyCodes = [ ];</div>_x000D_
<div id="key-names">var keyNames = [ ];</div>
_x000D_
_x000D_
_x000D_


Key codes worth noting

Letters A-Z: (65-90)

keyboardMap[65];  // A
...
keyboardMap[90];  // Z

Digits 0-9: (48-57)

keyboardMap[48];  // 0
...
keyboardMap[57];  // 9

Number Pad 0-9: (96-105)

keyboardMap[96];   // NUMPAD0
...
keyboardMap[105];  // NUMPAD9

Arrow Keys: (37-40)

keyboardMap[37];  // LEFT
keyboardMap[38];  // UP
keyboardMap[39];  // RIGHT
keyboardMap[40];  // DOWN

Tab Key: (9)

keyboardMap[9];  // TAB

Enter Key: (13)

keyboardMap[13];  // ENTER

Spacebar Key: (32)

keyboardMap[32];  // SPACE

OS Specific Key (91) Windows Key (Windows) or Command Key (Mac)

keyboardMap[91];  // OS_KEY

Alt Key: (18)

keyboardMap[18];  // ALT

Control Key: (17)

keyboardMap[17];  // CONTROL

Shift Key: (16)

keyboardMap[16];  // SHIFT

Caps Lock Key: (20)

keyboardMap[20];  // CAPS_LOCK

Add and remove attribute with jquery

Once you remove the ID "page_navigation" that element no longer has an ID and so cannot be found when you attempt to access it a second time.

The solution is to cache a reference to the element:

$(document).ready(function(){
    // This reference remains available to the following functions
    // even when the ID is removed.
    var page_navigation = $("#page_navigation1");

    $("#add").click(function(){
        page_navigation.attr("id","page_navigation1");
    });     

    $("#remove").click(function(){
        page_navigation.removeAttr("id");
    });     
});

How to update the value of a key in a dictionary in Python?

n = eval(input('Num books: '))
books = {}
for i in range(n):
    titlez = input("Enter Title: ")
    copy = eval(input("Num of copies: "))
    books[titlez] = copy

prob = input('Sell a book; enter YES or NO: ')
if prob == 'YES' or 'yes':
    choice = input('Enter book title: ')
    if choice in books:
        init_num = books[choice]
        init_num -= 1
        books[choice] = init_num
        print(books)

There is no argument given that corresponds to the required formal parameter - .NET Error

I received this same error in the following Linq statement regarding DailyReport. The problem was that DailyReport had no default constructor. Apparently, it instantiates the object before populating the properties.

var sums = reports
    .GroupBy(r => r.CountryRegion)
    .Select(cr => new DailyReport
    {
        CountryRegion = cr.Key,
        ProvinceState = "All",
        RecordDate = cr.First().RecordDate,
        Confirmed = cr.Sum(c => c.Confirmed),
        Recovered = cr.Sum(c => c.Recovered),
        Deaths = cr.Sum(c => c.Deaths)
    });

Raise an event whenever a property's value changed?

I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY

public class TheClass : INotifyPropertyChanged {
    private int _property1;
    private string _property2;
    private double _property3;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if(handler != null) {
            handler(this, e);
        }
    }

    protected void SetPropertyField<T>(string propertyName, ref T field, T newValue) {
        if(!EqualityComparer<T>.Default.Equals(field, newValue)) {
            field = newValue;
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    }

    public int Property1 {
        get { return _property1; }
        set { SetPropertyField("Property1", ref _property1, value); }
    }
    public string Property2 {
        get { return _property2; }
        set { SetPropertyField("Property2", ref _property2, value); }
    }
    public double Property3 {
        get { return _property3; }
        set { SetPropertyField("Property3", ref _property3, value); }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.

Match linebreaks - \n or \r\n?

You have different line endings in the example texts in Debuggex. What is especially interesting is that Debuggex seems to have identified which line ending style you used first, and it converts all additional line endings entered to that style.

I used Notepad++ to paste sample text in Unix and Windows format into Debuggex, and whichever I pasted first is what that session of Debuggex stuck with.

So, you should wash your text through your text editor before pasting it into Debuggex. Ensure that you're pasting the style you want. Debuggex defaults to Unix style (\n).

Also, NEL (\u0085) is something different entirely: https://en.wikipedia.org/wiki/Newline#Unicode

(\r?\n) will cover Unix and Windows. You'll need something more complex, like (\r\n|\r|\n), if you want to match old Mac too.

Grep and Python

You might be interested in pyp. Citing my other answer:

"The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

Intel HAXM is required to run this AVD. VT-x is disabled in BIOS.

Enable VT-x in your BIOS security settings (refer to documentation for your computer).this error on android studio I dont no how to do Bios Security

How to write unit testing for Angular / TypeScript for private methods with Jasmine

Sorry for the necro on this post, but I feel compelled to weigh in on a couple of things that do not seem to have been touched on.

First a foremost - when we find ourselves needing access to private members on a class during unit testing, it is generally a big, fat red flag that we've goofed in our strategic or tactical approach and have inadvertently violated the single responsibility principal by pushing behavior where it does not belong. Feeling the need to access methods that are really nothing more than an isolated subroutine of a construction procedure is one of the most common occurrences of this; however, it's kind of like your boss expecting you to show up for work ready-to-go and also having some perverse need to know what morning routine you went through to get you into that state...

The other most common instance of this happening is when you find yourself trying to test the proverbial "god class." It is a special kind of problem in and of itself, but suffers from the same basic issue with needing to know intimate details of a procedure - but that's getting off topic.

In this specific example, we've effectively assigned the responsibility of fully initializing the Bar object to the FooBar class's constructor. In object oriented programming, one of the core tenents is that the constructor is "sacred" and should be guarded against invalid data that would invalidate its' own internal state and leave it primed to fail somewhere else downstream (in what could be a very deep pipeline.)

We've failed to do that here by allowing the FooBar object to accept a Bar that is not ready at the time that the FooBar is constructed, and have compensated by sort-of "hacking" the FooBar object to take matters into its' own hands.

This is the result of a failure to adhere to another tenent of object oriented programming (in the case of Bar,) which is that an object's state should be fully initialized and ready to handle any incoming calls to its' public members immediately after creation. Now, this does not mean immediately after the constructor is called in all instances. When you have an object that has many complex construction scenarios, then it is better to expose setters to its optional members to an object that is implemented in accordance with a creation design-pattern (Factory, Builder, etc...) In any of the latter cases, you would be pushing the initialization of the target object off into another object graph whose sole purpose is directing traffic to get you to a point where you have a valid instance of that which you are requesting - and the product should not be considered "ready" until after this creation object has served it up.

In your example, the Bar's "status" property does not seem to be in a valid state in which a FooBar can accept it - so the FooBar does something to it to correct that issue.

The second issue I am seeing is that it appears that you are trying to test your code rather than practice test-driven development. This is definitely my own opinion at this point in time; but, this type of testing is really an anti-pattern. What you end up doing is falling into the trap of realizing that you have core design problems that prevent your code from being testable after the fact, rather than writing the tests you need and subsequently programming to the tests. Either way you come at the problem, you should still end up with the same number of tests and lines of code had you truly achieved a SOLID implementation. So - why try and reverse engineer your way into testable code when you can just address the matter at the onset of your development efforts?

Had you done that, then you would have realized much earlier on that you were going to have to write some rather icky code in order to test against your design and would have had the opportunity early on to realign your approach by shifting behavior to implementations that are easily testable.

Postgresql 9.2 pg_dump version mismatch

I had same error and this is how I solved it in my case. This means your postgresql version is 9.2.1 but you have started postgresql service of 9.1.6.

If you run psql postgres you will see:

psql (9.2.1, server 9.1.6)

What I did to solve this problem is:

  1. brew services stop [email protected]
  2. brew services restart [email protected]

Now run psql postgres and you should have: psql (9.2.1)

You can also run brew services list to see the status of your postgres.

SVN 405 Method Not Allowed

I just fixed this in my own repository. I'm using TortoiseSVN on Windows, so I'm not sure exactly what commands this translates to on the command line, but here's what I did:

The problematic folder is called lib, and it was due to be added.

  • First I undid the add, so that SVN was no longer paying attention to it.
  • Then I renamed it (to libs, not that that matters) using the Windows context menu, added it, and committed successfully.
  • Finally I renamed it back to lib using TortoiseSVN's context menu (this is probably important), and committed again.

deleting rows in numpy array

numpy provides a simple function to do the exact same thing: supposing you have a masked array 'a', calling numpy.ma.compress_rows(a) will delete the rows containing a masked value. I guess this is much faster this way...

How to close a thread from within?

If you want force stop your thread: thread._Thread_stop() For me works very good.

How to get id from URL in codeigniter?

In codeigniter you can't pass parameters in the url as you are doing in core php.So remove the "?" and "product_id" and simply pass the id.If you want more security you can encrypt the id and pass it.

How do I directly modify a Google Chrome Extension File? (.CRX)

It's possible to modify the code of .CRX extension, because it's a simple .zip archive. You can download extension, extract it's source code, modify it (test and debug it as it's on your side), and package back into .CRX file.

I googled out this tool to simply download .CRX extension and extract the source code and it worked for me: http://crxextractor.com

Everything it does is parses .CRX file format and extracts actual .zip containing the source code.

Checking if a string array contains a value, and if so, getting its position

var index = Array.FindIndex(stringArray, x => x == value)

How to create a new figure in MATLAB?

As simple as this-

figure, plot(yourfigure);

Correct way to pause a Python program

For cross Python 2/3 compatibility, you can use input via the six library:

import six
six.moves.input( 'Press the <ENTER> key to continue...' )

Allow multiple roles to access controller action

You can use Authorization Policy in Startup.cs

    services.AddAuthorization(options =>
    {
        options.AddPolicy("admin", policy => policy.RequireRole("SuperAdmin","Admin"));
        options.AddPolicy("teacher", policy => policy.RequireRole("SuperAdmin", "Admin", "Teacher"));
    });

And in Controller Files:

 [Authorize(Policy = "teacher")]
 [HttpGet("stats/{id}")]
 public async Task<IActionResult> getStudentStats(int id)
 { ... }

"teacher" policy accept 3 roles.

Make div scrollable

Place this into your DIV style

overflow:scroll;

Nesting optgroups in a dropdownlist/select

Ok, if anyone ever reads this: the best option is to add four &nbsp;s at each extra level of indentation, it would seem!

so:

_x000D_
_x000D_
<select>_x000D_
 <optgroup label="Level One">_x000D_
  <option> A.1 </option>_x000D_
  <optgroup label="&nbsp;&nbsp;&nbsp;&nbsp;Level Two">_x000D_
   <option>&nbsp;&nbsp;&nbsp;&nbsp; A.B.1 </option>_x000D_
  </optgroup>_x000D_
  <option> A.2 </option>_x000D_
 </optgroup>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How do I set the icon for my application in visual studio 2008?

First go to Resource View (from menu: View --> Other Window --> Resource View). Then in Resource View navigate through resources, if any. If there is already a resource of Icon type, added by Visual Studio, then open and edit it. Otherwise right-click and select Add Resource, and then add a new icon.

Use the embedded image editor in order to edit the existing or new icon. Note that an icon can include several types (sizes), selected from Image menu.

Then compile your project and see the effect.

See: http://social.microsoft.com/Forums/en-US/vcgeneral/thread/87614e26-075c-4d5d-a45a-f462c79ab0a0

Angular2 - Input Field To Accept Only Numbers

Well Thanks to JeanPaul A. and rdanielmurphy. I had made my own Custom directive for limiting input field to number only. Also added the max and min input attributes. Will work in angular 7 also.

Angular

    import { Directive, ElementRef, Input, HostListener } from '@angular/core';

@Directive({
  selector: '[appNumberOnly]'
})
export class NumberOnlyDirective {
  // Allow decimal numbers. The \. is only allowed once to occur
  private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);

  // Allow key codes for special events. Reflect :
  // Backspace, tab, end, home
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];
  constructor(private el: ElementRef) { }

  @Input() maxlength: number;
  @Input() min: number;
  @Input() max: number;

  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }

    // Do not use event.keycode this is deprecated.
    // See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
    const current: string = this.el.nativeElement.value;

    // We need this because the current value on the DOM element
    // is not yet updated with the value from this event
    const next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex) || (this.maxlength && next.length > this.maxlength) ||
      (this.min && +next < this.min) ||
      (this.max && +next >= this.max)) {
      event.preventDefault();
    }
  }

  @HostListener('paste', ['$event']) onPaste(event) {
    // Don't allow pasted text that contains non-numerics
    const pastedText = (event.originalEvent || event).clipboardData.getData('text/plain');

    if (pastedText) {
      const regEx = new RegExp('^[0-9]*$');
      if (!regEx.test(pastedText) || (this.maxlength && pastedText.length > this.maxlength) ||
        (this.min && +pastedText < this.min) ||
        (this.max && +pastedText >= this.max)) {
        event.preventDefault();
      }
    }
  }

}

HTML

<input type="text" class="text-area" [(ngModel)]="itemName" maxlength="3" appNumberOnly />

Generating a PDF file from React Components

Rendering react as pdf is generally a pain, but there is a way around it using canvas.

The idea is to convert : HTML -> Canvas -> PNG (or JPEG) -> PDF

To achieve the above, you'll need :

  1. html2canvas &
  2. jsPDF

_x000D_
_x000D_
import React, {Component, PropTypes} from 'react';_x000D_
_x000D_
// download html2canvas and jsPDF and save the files in app/ext, or somewhere else_x000D_
// the built versions are directly consumable_x000D_
// import {html2canvas, jsPDF} from 'app/ext';_x000D_
_x000D_
_x000D_
export default class Export extends Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
  }_x000D_
_x000D_
  printDocument() {_x000D_
    const input = document.getElementById('divToPrint');_x000D_
    html2canvas(input)_x000D_
      .then((canvas) => {_x000D_
        const imgData = canvas.toDataURL('image/png');_x000D_
        const pdf = new jsPDF();_x000D_
        pdf.addImage(imgData, 'JPEG', 0, 0);_x000D_
        // pdf.output('dataurlnewwindow');_x000D_
        pdf.save("download.pdf");_x000D_
      })_x000D_
    ;_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (<div>_x000D_
      <div className="mb5">_x000D_
        <button onClick={this.printDocument}>Print</button>_x000D_
      </div>_x000D_
      <div id="divToPrint" className="mt4" {...css({_x000D_
        backgroundColor: '#f5f5f5',_x000D_
        width: '210mm',_x000D_
        minHeight: '297mm',_x000D_
        marginLeft: 'auto',_x000D_
        marginRight: 'auto'_x000D_
      })}>_x000D_
        <div>Note: Here the dimensions of div are same as A4</div> _x000D_
        <div>You Can add any component here</div>_x000D_
      </div>_x000D_
    </div>);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

The snippet will not work here because the required files are not imported.

An alternate approach is being used in this answer, where the middle steps are dropped and you can simply convert from HTML to PDF. There is an option to do this in the jsPDF documentation as well, but from personal observation, I feel that better accuracy is achieved when dom is converted into png first.

Update 0: September 14, 2018

The text on the pdfs created by this approach will not be selectable. If that's a requirement, you might find this article helpful.

Create a custom View by inflating a layout?

Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.

What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.

http://developer.android.com/guide/topics/ui/custom-components.html

How to compare two dates along with time in java

An Alternative is....

Convert both dates into milliseconds as below

Date d = new Date();
long l = d.getTime();

Now compare both long values

How do I debug a stand-alone VBScript script?

Run cscript.exe for full command args, I think

cscript //X scriptfile.vbs MyArg1 MyArg2

will run the script in a debugger.

Java; String replace (using regular expressions)?

You'll want to look into capturing in regex to handle wrapping the 3 in ^3.

What is RSS and VSZ in Linux memory management

They are not managed, but measured and possibly limited (see getrlimit system call, also on getrlimit(2)).

RSS means resident set size (the part of your virtual address space sitting in RAM).

You can query the virtual address space of process 1234 using proc(5) with cat /proc/1234/maps and its status (including memory consumption) thru cat /proc/1234/status

How do relative file paths work in Eclipse?

You need "src/Hankees.txt"

Your file is in the source folder which is not counted as the working directory.\

Or you can move the file up to the root directory of your project and just use "Hankees.txt"

JavaScript: How do I print a message to the error console?

The WebKit Web Inspector also supports Firebug's console API (just a minor addition to Dan's answer).

CSS: Force float to do a whole new line

Use display:inline-block

You may also find vertical-align: top or vertical-align:middle useful.

How do I make a MySQL database run completely in memory?

Assuming you understand the consequences of using the MEMORY engine as mentioned in comments, and here, as well as some others you'll find by searching about (no transaction safety, locking issues, etc) - you can proceed as follows:

MEMORY tables are stored differently than InnoDB, so you'll need to use an export/import strategy. First dump each table separately to a file using SELECT * FROM tablename INTO OUTFILE 'table_filename'. Create the MEMORY database and recreate the tables you'll be using with this syntax: CREATE TABLE tablename (...) ENGINE = MEMORY;. You can then import your data using LOAD DATA INFILE 'table_filename' INTO TABLE tablename for each table.

"The operation is not valid for the state of the transaction" error and transaction scope

After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:

public void MyAddUpdateMethod()
{
    using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //do my first add update statement            
        }

        //removed the method call from the first sql server using statement
        bool DoesRecordExist = this.SelectStatementCall(id)
    }
}

public bool SelectStatementCall(System.Guid id)
{
    using(SQLServer Sql = new SQLServer(this.m_connstring))
    {
        //create parameters
    }
}

Windows batch: sleep

I just wrote my own sleep which called the Win32 Sleep API function.

Why is textarea filled with mysterious white spaces?

Open (and close!) your PHP tags right after, and before, your textarea tags:

<textarea style="width:350px; height:80px;" cols="42" rows="5" name="sitelink"><?php
  if($siteLink_val) echo $siteLink_val;
?></textarea>

Android: install .apk programmatically

This question is very helpfully BUT Don't forget to mount SD Card in your emulator, if you don't do this its doesn't work.

I lose my time before discover this.

How do I check if an array includes a value in JavaScript?

Just another option

// usage: if ( ['a','b','c','d'].contains('b') ) { ... }
Array.prototype.contains = function(value){
    for (var key in this)
        if (this[key] === value) return true;
    return false;
}

Be careful because overloading javascript array objects with custom methods can disrupt the behavior of other javascripts, causing unexpected behavior.

How do I schedule a task to run at periodic intervals?

Advantage of ScheduledExecutorService over Timer

I wish to offer you an alternative to Timer using - ScheduledThreadPoolExecutor, an implementation of the ScheduledExecutorService interface. It has some advantages over the Timer class, according to "Java in Concurrency":

A Timer creates only a single thread for executing timer tasks. If a timer task takes too long to run, the timing accuracy of other TimerTask can suffer. If a recurring TimerTask is scheduled to run every 10 ms and another Timer-Task takes 40 ms to run, the recurring task either (depending on whether it was scheduled at fixed rate or fixed delay) gets called four times in rapid succession after the long-running task completes, or "misses" four invocations completely. Scheduled thread pools address this limitation by letting you provide multiple threads for executing deferred and periodic tasks.

Another problem with Timer is that it behaves poorly if a TimerTask throws an unchecked exception. Also, called "thread leakage"

The Timer thread doesn't catch the exception, so an unchecked exception thrown from a TimerTask terminates the timer thread. Timer also doesn't resurrect the thread in this situation; instead, it erroneously assumes the entire Timer was cancelled. In this case, TimerTasks that are already scheduled but not yet executed are never run, and new tasks cannot be scheduled.

And another recommendation if you need to build your own scheduling service, you may still be able to take advantage of the library by using a DelayQueue, a BlockingQueue implementation that provides the scheduling functionality of ScheduledThreadPoolExecutor. A DelayQueue manages a collection of Delayed objects. A Delayed has a delay time associated with it: DelayQueue lets you take an element only if its delay has expired. Objects are returned from a DelayQueue ordered by the time associated with their delay.

Function inside a function.?

X returns (value +3), while Y returns (value*2)

Given a value of 4, this means (4+3) * (4*2) = 7 * 8 = 56.

Although functions are not limited in scope (which means that you can safely 'nest' function definitions), this particular example is prone to errors:

1) You can't call y() before calling x(), because function y() won't actually be defined until x() has executed once.

2) Calling x() twice will cause PHP to redeclare function y(), leading to a fatal error:

Fatal error: Cannot redeclare y()

The solution to both would be to split the code, so that both functions are declared independent of each other:

function x ($y) 
{
  return($y+3);
}

function y ($z)
{
  return ($z*2);
}

This is also a lot more readable.

How to add Certificate Authority file in CentOS 7

Maybe late to the party but in my case it was RHEL 6.8:

Copy certificate.crt issued by hosting to:

/etc/pki/ca-trust/source/anchors/

Then:

update-ca-trust force-enable (ignore not found warnings)
update-ca-trust extract

Hope it helps

How to remove title bar from the android activity?

you just add this style in your style.xml file which is in your values folder

<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
</style>

After that set this style to your activity class in your AndroidManifest.xml file

android:theme="@style/AppTheme.NoActionBar"

Edit:- If you are going with programmatic way to hide ActionBar then use below code in your activity onCreate() method.

if(getSupportedActionbar()!=null)    
     this.getSupportedActionBar().hide();

and if you want to hide ActionBar from Fragment then

getActivity().getSupportedActionBar().hide();

AppCompat v7:- Use following theme in your Activities where you don't want actiobBar Theme.AppComat.NoActionBar or Theme.AppCompat.Light.NoActionBar or if you want to hide in whole app then set this theme in your <application... /> in your AndroidManifest.

In Kotlin:

add this line of code in your onCreate() method or you can use above theme.

if (supportActionBar != null)
        supportActionBar?.hide()

i hope this will help you more.

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

How do I copy a 2 Dimensional array in Java?

Using java 8 this can be done with

`int[][] destination=Arrays.stream(source)
                    .map(a ->  Arrays.copyOf(a, a.length))
                    .toArray(int[][]::new);

css rotate a pseudo :after or :before content:""

Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block or display: inline-block to transform them:

_x000D_
_x000D_
#whatever:after {
  content: "\24B6";
  display: inline-block;
  transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
_x000D_
_x000D_

Creating a JSON dynamically with each input value using jquery

May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.

var obj = [];
var elems = $("input[class=email]");

for (i = 0; i < elems.length; i += 1) {
    var id = this.getAttribute('title');
    var email = this.value;
    tmp = {
        'title': id,
        'email': email
    };

    obj.push(tmp);
}

Truncate to three decimals in Python

You can use an additional float() around it if you want to preserve it as a float.

%.3f'%(1324343032.324325235)

Programmatically change UITextField Keyboard type

It's worth noting that if you want a currently-focused field to update the keyboard type immediately, there's one extra step:

// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress

[textField setKeyboardType:UIKeyboardTypeEmailAddress];
[textField reloadInputViews];

Without the call to reloadInputViews, the keyboard will not change until the selected field (the first responder) loses and regains focus.

A full list of the UIKeyboardType values can be found here, or:

typedef enum : NSInteger {
    UIKeyboardTypeDefault,
    UIKeyboardTypeASCIICapable,
    UIKeyboardTypeNumbersAndPunctuation,
    UIKeyboardTypeURL,
    UIKeyboardTypeNumberPad,
    UIKeyboardTypePhonePad,
    UIKeyboardTypeNamePhonePad,
    UIKeyboardTypeEmailAddress,
    UIKeyboardTypeDecimalPad,
    UIKeyboardTypeTwitter,
    UIKeyboardTypeWebSearch,
    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;

How to set default value for form field in Symfony2?

If you're using a FormBuilder in symfony 2.7 to generate the form, you can also pass the initial data to the createFormBuilder method of the Controler

$values = array(
    'name' => "Bob"
);

$formBuilder = $this->createFormBuilder($values);
$formBuilder->add('name', 'text');

how to check if the input is a number or not in C?

Another way of doing it is by using isdigit function. Below is the code for it:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
    char input[MAXINPUT] = "";
    int length,i; 

    scanf ("%s", input);
    length = strlen (input);
    for (i=0;i<length; i++)
        if (!isdigit(input[i]))
        {
            printf ("Entered input is not a number\n");
            exit(1);
        }
    printf ("Given input is a number\n");
}

PHPUnit assert that an exception was thrown?

<?php
require_once 'PHPUnit/Framework.php';

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        $this->expectException(InvalidArgumentException::class);
        // or for PHPUnit < 5.2
        // $this->setExpectedException(InvalidArgumentException::class);

        //...and then add your test code that generates the exception 
        exampleMethod($anInvalidArgument);
    }
}

expectException() PHPUnit documentation

PHPUnit author article provides detailed explanation on testing exceptions best practices.

Using Linq to group a list of objects into a new grouped list of list of objects

Your group statement will group by group ID. For example, if you then write:

foreach (var group in groupedCustomerList)
{
    Console.WriteLine("Group {0}", group.Key);
    foreach (var user in group)
    {
        Console.WriteLine("  {0}", user.UserName);
    }
}

that should work fine. Each group has a key, but also contains an IGrouping<TKey, TElement> which is a collection that allows you to iterate over the members of the group. As Lee mentions, you can convert each group to a list if you really want to, but if you're just going to iterate over them as per the code above, there's no real benefit in doing so.

Unable to show a Git tree in terminal

git log --oneline --decorate --all --graph

A visual tree with branch names included.

Use this to add it as an alias

git config --global alias.tree "log --oneline --decorate --all --graph"

You call it with

git tree

Git Tree

Size of character ('a') in C/C++

As Paul stated, it's because 'a' is an int in C but a char in C++.

I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

How to get the public IP address of a user in C#

I have an extension method:

public static string GetIp(this HttpContextBase context)
{
    if (context == null || context.Request == null)
        return string.Empty;

    return context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] 
           ?? context.Request.UserHostAddress;
}

Note: "HTTP_X_FORWARDED_FOR" is for ip behind proxy. context.Request.UserHostAddress is identical to "REMOTE_ADDR".

But bear in mind it is not necessary the actual IP though.

Sources:

IIS Server Variables

Link

How do I change screen orientation in the Android emulator?

In the updated emulator you don't have to remember the keyboard shortcuts -- they have added a side panel to the right side of the window. You can change the screen orientation by clicking either of the "rotate" buttons in that side panel.

enter image description here

Just click on Rotate button to change the landscape to portrait and vice versa.

How to change the style of the title attribute inside an anchor tag?

A jsfiddle for custom tooltip pattern is Here

It is based on CSS Positioning and pseduo class selectors

Check MDN docs for cross-browser support of pseudo classes

    <!-- HTML -->
<p>
    <a href="http://www.google.com/" class="tooltip">
    I am a 
        <span> (This website rocks) </span></a>&nbsp; a developer.
</p>

    /*CSS*/
a.tooltip {
    position: relative;
}

a.tooltip span {
    display: none;    
}

a.tooltip:hover span, a.tooltip:focus span {
    display:block;
    position:absolute;
    top:1em;
    left:1.5em;
    padding: 0.2em 0.6em;
    border:1px solid #996633;
    background-color:#FFFF66;
    color:#000;
}

Adding external library into Qt Creator project

And to add multiple library files you can write as below:

INCLUDEPATH *= E:/DebugLibrary/VTK E:/DebugLibrary/VTK/Common E:/DebugLibrary/VTK/Filtering E:/DebugLibrary/VTK/GenericFiltering E:/DebugLibrary/VTK/Graphics E:/DebugLibrary/VTK/GUISupport/Qt E:/DebugLibrary/VTK/Hybrid E:/DebugLibrary/VTK/Imaging E:/DebugLibrary/VTK/IO E:/DebugLibrary/VTK/Parallel E:/DebugLibrary/VTK/Rendering E:/DebugLibrary/VTK/Utilities E:/DebugLibrary/VTK/VolumeRendering E:/DebugLibrary/VTK/Widgets E:/DebugLibrary/VTK/Wrapping

LIBS *= -LE:/DebugLibrary/VTKBin/bin/release -lvtkCommon -lvtksys -lQVTK -lvtkWidgets -lvtkRendering -lvtkGraphics -lvtkImaging -lvtkIO -lvtkFiltering -lvtkDICOMParser -lvtkpng -lvtktiff -lvtkzlib -lvtkjpeg -lvtkexpat -lvtkNetCDF -lvtkexoIIc -lvtkftgl -lvtkfreetype -lvtkHybrid -lvtkVolumeRendering -lQVTKWidgetPlugin -lvtkGenericFiltering

How to use Java property files?

Here is another way to iterate over the properties:

Enumeration eProps = properties.propertyNames();
while (eProps.hasMoreElements()) { 
    String key = (String) eProps.nextElement(); 
    String value = properties.getProperty(key); 
    System.out.println(key + " => " + value); 
}

Calculate mean across dimension in a 2D array

a.mean() takes an axis argument:

In [1]: import numpy as np

In [2]: a = np.array([[40, 10], [50, 11]])

In [3]: a.mean(axis=1)     # to take the mean of each row
Out[3]: array([ 25. ,  30.5])

In [4]: a.mean(axis=0)     # to take the mean of each col
Out[4]: array([ 45. ,  10.5])

Or, as a standalone function:

In [5]: np.mean(a, axis=1)
Out[5]: array([ 25. ,  30.5])

The reason your slicing wasn't working is because this is the syntax for slicing:

In [6]: a[:,0].mean() # first column
Out[6]: 45.0

In [7]: a[:,1].mean() # second column
Out[7]: 10.5

C-like structures in Python

You access C-Style struct in python in following way.

class cstruct:
    var_i = 0
    var_f = 0.0
    var_str = ""

if you just want use object of cstruct

obj = cstruct()
obj.var_i = 50
obj.var_f = 50.00
obj.var_str = "fifty"
print "cstruct: obj i=%d f=%f s=%s" %(obj.var_i, obj.var_f, obj.var_str)

if you want to create an array of objects of cstruct

obj_array = [cstruct() for i in range(10)]
obj_array[0].var_i = 10
obj_array[0].var_f = 10.00
obj_array[0].var_str = "ten"

#go ahead and fill rest of array instaces of struct

#print all the value
for i in range(10):
    print "cstruct: obj_array i=%d f=%f s=%s" %(obj_array[i].var_i, obj_array[i].var_f, obj_array[i].var_str)

Note: instead of 'cstruct' name, please use your struct name instead of var_i, var_f, var_str, please define your structure's member variable.

Best way to define error codes/strings in Java?

Well there's certainly a better implementation of the enum solution (which is generally quite nice):

public enum Error {
  DATABASE(0, "A database error has occurred."),
  DUPLICATE_USER(1, "This user already exists.");

  private final int code;
  private final String description;

  private Error(int code, String description) {
    this.code = code;
    this.description = description;
  }

  public String getDescription() {
     return description;
  }

  public int getCode() {
     return code;
  }

  @Override
  public String toString() {
    return code + ": " + description;
  }
}

You may want to override toString() to just return the description instead - not sure. Anyway, the main point is that you don't need to override separately for each error code. Also note that I've explicitly specified the code instead of using the ordinal value - this makes it easier to change the order and add/remove errors later.

Don't forget that this isn't internationalised at all - but unless your web service client sends you a locale description, you can't easily internationalise it yourself anyway. At least they'll have the error code to use for i18n at the client side...

newline in <td title="">

If you're looking to put line breaks into the tooltip that appears on mouseover, there's no reliable crossbrowser way to do that. You'd have to fall back to one of the many Javascript tooltip code samples

In plain English, what does "git reset" do?

TL;DR

git reset resets Staging to the last commit. Use --hard to also reset files in your Working directory to the last commit.

LONGER VERSION

But that's obviously simplistic hence the many rather verbose answers. It made more sense for me to read up on git reset in the context of undoing changes. E.g. see this:

If git revert is a “safe” way to undo changes, you can think of git reset as the dangerous method. When you undo with git reset(and the commits are no longer referenced by any ref or the reflog), there is no way to retrieve the original copy—it is a permanent undo. Care must be taken when using this tool, as it’s one of the only Git commands that has the potential to lose your work.

From https://www.atlassian.com/git/tutorials/undoing-changes/git-reset

and this

On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.

From https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting/commit-level-operations

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I have python2.7 installed via brew and the following solved my problem

brew install numpy

It installs python3, but it still works and sets it up for 2.7 as well.

How to specify the download location with wget?

man wget: -O file --output-document=file

wget "url" -O /tmp/cron_test/<file>

Laravel form html with PUT method for PUT routes

If you are using HTML Form element instead Laravel Form Builder, you must place method_field between your form opening tag and closing end. By doing this you may explicitly define form method type.

<form>
{{ method_field('PUT') }}
</form>

count (non-blank) lines-of-code in bash

'wc' counts lines, words, chars, so to count all lines (including blank ones) use:

wc *.py

To filter out the blank lines, you can use grep:

grep -v '^\s*$' *.py | wc

'-v' tells grep to output all lines except those that match '^' is the start of a line '\s*' is zero or more whitespace characters '$' is the end of a line *.py is my example for all the files you wish to count (all python files in current dir) pipe output to wc. Off you go.

I'm answering my own (genuine) question. Couldn't find an stackoverflow entry that covered this.

Popup Message boxes

javax.swing.JOptionPane

Here is the code to a method I call whenever I want an information box to pop up, it hogs the screen until it is accepted:

import javax.swing.JOptionPane;

public class ClassNameHere
{

    public static void infoBox(String infoMessage, String titleBar)
    {
        JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
    }
}

The first JOptionPane parameter (null in this example) is used to align the dialog. null causes it to center itself on the screen, however any java.awt.Component can be specified and the dialog will appear in the center of that Component instead.

I tend to use the titleBar String to describe where in the code the box is being called from, that way if it gets annoying I can easily track down and delete the code responsible for spamming my screen with infoBoxes.

To use this method call:

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");

javafx.scene.control.Alert

For a an in depth description of how to use JavaFX dialogs see: JavaFX Dialogs (official) by code.makery. They are much more powerful and flexible than Swing dialogs and capable of far more than just popping up messages.

As above I'll post a small example of how you could use JavaFX dialogs to achieve the same result

import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;

public class ClassNameHere
{

    public static void infoBox(String infoMessage, String titleBar)
    {
        /* By specifying a null headerMessage String, we cause the dialog to
           not have a header */
        infoBox(infoMessage, titleBar, null);
    }

    public static void infoBox(String infoMessage, String titleBar, String headerMessage)
    {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle(titleBar);
        alert.setHeaderText(headerMessage);
        alert.setContentText(infoMessage);
        alert.showAndWait();
    }
}

One thing to keep in mind is that JavaFX is a single threaded GUI toolkit, which means this method should be called directly from the JavaFX application thread. If you have another thread doing work, which needs a dialog then see these SO Q&As: JavaFX2: Can I pause a background Task / Service? and Platform.Runlater and Task Javafx.

To use this method call:

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");

or

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE", "HEADER MESSAGE");

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

Remove Android App Title Bar

Just change the theme in the design view of your activity to NoActionBar like the one here

Fastest way to check a string contain another substring in JavaScript?

It's easy way to use .match() method to string.

var re = /(AND|OR|MAYBE)/;
var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING";
console.log('Do we found something?', Boolean(str.match(re)));

Wish you a nice day, sir!

How to add a button dynamically in Android?

I've used this (or very similar) code to add several TextViews to a LinearLayout:

// Quick & dirty pre-made list of text labels...
String names[] = {"alpha", "beta", "gamma", "delta", "epsilon"};
int namesLength = 5;

// Create a LayoutParams...
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT, 
    LinearLayout.LayoutParams.FILL_PARENT);

// Get existing UI containers...
LinearLayout nameButtons = (LinearLayout) view.findViewById(R.id.name_buttons);
TextView label = (TextView) view.findViewById(R.id.master_label);

TextView tv;

for (int i = 0; i < namesLength; i++) {
    // Grab the name for this "button"
    final String name = names[i];

    tv = new TextView(context);
    tv.setText(name);

    // TextViews CAN have OnClickListeners
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            label.setText("Clicked button for " + name); 
        }
    });

    nameButtons.addView(tv, params);
}

The main difference between this and dicklaw795's code is it doesn't set() and re-get() the ID for each TextView--I found it unnecessary, although I may need it to later identify each button in a common handler routine (e.g. one called by onClick() for each TextView).

SQLRecoverableException: I/O Exception: Connection reset

Solution
Change the setup for your application, so you this parameter[-Djava.security.egd=file:/dev/../dev/urandom] next to the java command:

java -Djava.security.egd=file:/dev/../dev/urandom [your command]

Ref :- https://community.oracle.com/thread/943911

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

This error happens when you have a __unicode__ method that is a returning a field that is not entered. Any blank field is None and Python cannot convert None, so you get the error.

In your case, the problem most likely is with the PCE model's __unicode__ method, specifically the field its returning.

You can prevent this by returning a default value:

def __unicode__(self):
   return self.some_field or u'None'

SQL 'like' vs '=' performance

You are asking the wrong question. In databases is not the operator performance that matters, is always the SARGability of the expression, and the coverability of the overall query. Performance of the operator itself is largely irrelevant.

So, how do LIKE and = compare in terms of SARGability? LIKE, when used with an expression that does not start with a constant (eg. when used LIKE '%something') is by definition non-SARGabale. But does that make = or LIKE 'something%' SARGable? No. As with any question about SQL performance the answer does not lie with the query of the text, but with the schema deployed. These expression may be SARGable if an index exists to satisfy them.

So, truth be told, there are small differences between = and LIKE. But asking whether one operator or other operator is 'faster' in SQL is like asking 'What goes faster, a red car or a blue car?'. You should eb asking questions about the engine size and vechicle weight, not about the color... To approach questions about optimizing relational tables, the place to look is your indexes and your expressions in the WHERE clause (and other clauses, but it usually starts with the WHERE).

Update select2 data without rebuilding the control

I solved this issue by using the ajax option and specifying a custom transport function.

see this fiddle Select2 dynamic options demo

Here is the relevant js to get this to work.

var $items = [];

let options = {
ajax: {
    transport: function(params, success, failure) {
    let items = $items;

    if (params.data && params.data.q) {
        items = items.filter(function(item) {
        return new RegExp(params.data.q).test(item.text);
        });
    }

    let promise = new Promise(function(resolve, reject) {
        resolve({
        results: items
        });
    });

    promise.then(success);
    promise.catch(failure);
    }
},
placeholder: 'Select item'
};

$('select').select2(options);

let count = $items.length + 1;

$('button').on('click', function() {
$items.push({
    id: count,
    text: 'Item' + count
});
count++;
});

Case insensitive 'Contains(string)'

The InStr method from the VisualBasic assembly is the best if you have a concern about internationalization (or you could reimplement it). Looking at in it dotNeetPeek shows that not only does it account for caps and lowercase, but also for kana type and full- vs. half-width characters (mostly relevant for Asian languages, although there are full-width versions of the Roman alphabet too). I'm skipping over some details, but check out the private method InternalInStrText:

private static int InternalInStrText(int lStartPos, string sSrc, string sFind)
{
  int num = sSrc == null ? 0 : sSrc.Length;
  if (lStartPos > num || num == 0)
    return -1;
  if (sFind == null || sFind.Length == 0)
    return lStartPos;
  else
    return Utils.GetCultureInfo().CompareInfo.IndexOf(sSrc, sFind, lStartPos, CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth);
}

SOAP client in .NET - references or examples?

I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.

That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):

  • Go ahead and do code-first to create your initial WSDL. Then, delete your code and re-generate the server class(es) from the WSDL. Almost every platform has a tool for this. This will show you what odd habits your particular platform has, and you can begin tweaking the WSDL to be simpler and more straightforward. Tweak, re-gen, repeat. You'll learn a lot this way, and it's portable knowledge.
  • Stick to plain old language classes (POCO, POJO, etc.) for complex types. Do NOT use platform-specific constructs like List<> or DataTable. Even PHP associative arrays will appear to work but fail in ways that are difficult to debug across platforms.
  • Stick to basic data types: bool, int, float, string, date(Time), and arrays. Odds are, the more particular you get about a data type, the less agile you'll be to new requirements over time. You do NOT want to change your WSDL if you can avoid it.
  • One exception to the data types above - give yourself a NameValuePair mechanism of some kind. You wouldn't believe how many times a list of these things will save your bacon in terms of flexibility.
  • Set a real namespace for your WSDL. It's not hard, but you might not believe how many web services I've seen in namespace "http://www.tempuri.org". Also, use a URN ("urn:com-myweb-servicename-v1", not a URL-based namespace ("http://servicename.myweb.com/v1". It's not a website, it's an abstract set of characters that defines a logical grouping. I've probably had a dozen people call me for support and say they went to the "website" and it didn't work.

</rant> :)

Get keys of a Typescript interface as array of strings

You will need to make a class that implements your interface, instantiate it and then use Object.keys(yourObject) to get the properties.

export class YourClass implements IMyTable {
    ...
}

then

let yourObject:YourClass = new YourClass();
Object.keys(yourObject).forEach((...) => { ... });

How can I unstage my files again after making a local commit?

Lets say you want to unstage changes upto n commits,

Where commit hashes are as follows:

  • h1
  • h2 ...
  • hn
  • hn+1

Then run the following command:
git reset hn

Now the HEAD will be at hn+1. Changes from h1 to hn will be unstaged.