Programs & Examples On #Wcf client

For questions about Windows Communication Foundation (WCF) clients.

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

What is the best workaround for the WCF client `using` block issue?

Override the client's Dispose() without the need to generate a proxy class based on ClientBase, also without the need to manage channel creation and caching! (Note that WcfClient is not an ABSTRACT class and is based on ClientBase)

// No need for a generated proxy class
//using (WcfClient<IOrderService> orderService = new WcfClient<IOrderService>())
//{
//    results = orderService.GetProxy().PlaceOrder(input);
//}

public class WcfClient<TService> : ClientBase<TService>, IDisposable
    where TService : class
{
    public WcfClient()
    {
    }

    public WcfClient(string endpointConfigurationName) :
        base(endpointConfigurationName)
    {
    }

    public WcfClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress)
    {
    }

    public WcfClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress)
    {
    }

    public WcfClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
        base(binding, remoteAddress)
    {
    }

    protected virtual void OnDispose()
    {
        bool success = false;

        if ((base.Channel as IClientChannel) != null)
        {
            try
            {
                if ((base.Channel as IClientChannel).State != CommunicationState.Faulted)
                {
                    (base.Channel as IClientChannel).Close();
                    success = true;
                }
            }
            finally
            {
                if (!success)
                {
                    (base.Channel as IClientChannel).Abort();
                }
            }
        }
    }

    public TService GetProxy()
    {
        return this.Channel as TService;
    }

    public void Dispose()
    {
        OnDispose();
    }
}

WCF change endpoint address at runtime

We store our URLs in a database and load them at runtime.

public class ServiceClientFactory<TChannel> : ClientBase<TChannel> where TChannel : class
{
    public TChannel Create(string url)
    {
        this.Endpoint.Address = new EndpointAddress(new Uri(url));
        return this.Channel;
    }
}

Implementation

var client = new ServiceClientFactory<yourServiceChannelInterface>().Create(newUrl);

How to create an email form that can send email using html

you can use Simple Contact Form in HTML with PHP mailer. It's easy to implement in you website. You can try the demo from following link: Simple Contact/Feedback Form in HTML-PHP mailer

Otherwise you can watch the demo video in following link: Youtube: Simple Contact/Feedback Form in HTML-PHP mailer

When you are running in localhost, you may get following error:

Warning: mail(): Failed to connect to mailserver at "smtp.gmail.com" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in S:\wamp\www\sample\mailTo.php on line 10

You can check in this link for more detailed information: Simple Contact/Feedback Form in HTML with php (HTML-PHP mailer) And this is the screenshot of HTML form: Simple Form

And this is the main PHP coding:

<?php
if($_POST["submit"]) {
    $recipient="[email protected]"; //Enter your mail address
    $subject="Contact from Website"; //Subject 
    $sender=$_POST["name"];
    $senderEmail=$_POST["email"];
    $message=$_POST["comments"];
    $mailBody="Name: $sender\nEmail Address: $senderEmail\n\nMessage: $message";
    mail($recipient, $subject, $mailBody);
    sleep(1);
    header("Location:http://blog.antonyraphel.in/sample/"); // Set here redirect page or destination page
}
?>

Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

How to run specific test cases in GoogleTest

Finally I got some answer, ::test::GTEST_FLAG(list_tests) = true; //From your program, not w.r.t console.

If you would like to use --gtest_filter =*; /* =*, =xyz*... etc*/ // You need to use them in Console.

So, my requirement is to use them from the program not from the console.

Updated:-

Finally I got the answer for updating the same in from the program.

 ::testing::GTEST_FLAG(filter) = "*Counter*:*IsPrime*:*ListenersTest.DoesNotLeak*";//":-:*Counter*";
      InitGoogleTest(&argc, argv);
RUN_ALL_TEST();

So, Thanks for all the answers.

You people are great.

Percentage Height HTML 5/CSS

You need to set the height on the <html> and <body> elements as well; otherwise, they will only be large enough to fit the content. For example:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<title>Example of 100% width and height</title>_x000D_
<style>_x000D_
html, body { height: 100%; margin: 0; }_x000D_
div { height: 100%; width: 100%; background: red; }_x000D_
</style>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

incompatible character encodings: ASCII-8BIT and UTF-8

For Haml put an encoding hint:

-# coding: UTF-8

on the top left of the Haml page.

JavaScript: Alert.Show(message) From ASP.NET Code-behind

private void MessageBox(string msg)
{
    Label lbl = new Label();
    lbl.Text  = string.Format(@"<script type='text/javascript'>alert('{0}');</script>",msg);
    Page.Controls.Add(lbl);
}

Windows recursive grep command-line

I recommend a really great tool:

native unix utils:

Just unpack them and put that folder into your PATH environment variable and voila! :)

Works like a charm, and there are much more then just grep ;)

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

How can I check whether a numpy array is empty or not?

Why would we want to check if an array is empty? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append is a frequent novice error.

Using a list in if alist: hinges on its boolean value:

In [102]: bool([])                                                                       
Out[102]: False
In [103]: bool([1])                                                                      
Out[103]: True

But trying to do the same with an array produces (in version 1.18):

In [104]: bool(np.array([]))                                                             
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value 
   of an empty array is ambiguous. Returning False, but in 
   future this will result in an error. Use `array.size > 0` to 
   check that an array is not empty.
  #!/usr/bin/python3
Out[104]: False

In [105]: bool(np.array([1]))                                                            
Out[105]: True

and bool(np.array([1,2]) produces the infamous ambiguity error.

edit

The accepted answer suggests size:

In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0

But I (and most others) check the shape more than the size:

In [13]: x.shape
Out[13]: (0,)

Another thing in its favor is that it 'maps' on to an empty list:

In [14]: x.tolist()
Out[14]: []

But there are other other arrays with 0 size, that aren't 'empty' in that last sense:

In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True

np.array([[],[]]) is also size 0, but shape (2,0) and len 2.

While the concept of an empty list is well defined, an empty array is not well defined. One empty list is equal to another. The same can't be said for a size 0 array.

The answer really depends on

  • what do you mean by 'empty'?
  • what are you really test for?

How do I fix the npm UNMET PEER DEPENDENCY warning?

Today available Angular 2 rc.7, and I had a similar problem with [email protected] UNMET PEER DEPENDENCY.

If you, like me, simply replaced @angular/...rc.6 to @angular/...rc.7 - it's not enough. Because, for example, @angular/router has no rc.6 version.

In this case, better review package.json in Quick start

sql server convert date to string MM/DD/YYYY

select convert(varchar(10), cast(fmdate as date), 101) from sery

Without cast I was not getting fmdate converted, so fmdate was a string.

How to modify a text file?

If you know some unix you could try the following:

Notes: $ means the command prompt

Say you have a file my_data.txt with content as such:

$ cat my_data.txt
This is a data file
with all of my data in it.

Then using the os module you can use the usual sed commands

import os

# Identifiers used are:
my_data_file = "my_data.txt"
command = "sed -i 's/all/none/' my_data.txt"

# Execute the command
os.system(command)

If you aren't aware of sed, check it out, it is extremely useful.

Performing Breadth First Search recursively

Here's a python implementation:

graph = {'A': ['B', 'C'],
         'B': ['C', 'D'],
         'C': ['D'],
         'D': ['C'],
         'E': ['F'],
         'F': ['C']}

def bfs(paths, goal):
    if not paths:
        raise StopIteration

    new_paths = []
    for path in paths:
        if path[-1] == goal:
            yield path

        last = path[-1]
        for neighbor in graph[last]:
            if neighbor not in path:
                new_paths.append(path + [neighbor])
    yield from bfs(new_paths, goal)


for path in bfs([['A']], 'D'):
    print(path)

How do I do word Stemming or Lemmatization?

.Net lucene has an inbuilt porter stemmer. You can try that. But note that porter stemming does not consider word context when deriving the lemma. (Go through the algorithm and its implementation and you will see how it works)

In where shall I use isset() and !empty()

When and how to use:

  1. isset()

True for 0, 1, empty string, a string containing a value, true, false

False for null

e.g

$status = 0
if (isset($status)) // True
$status = null 
if (isset($status)) // False
  1. Empty

False for 1, a string containing a value, true

True for null, empty string, 0, false e.g

$status = 0
if(empty($status)) // true
$status = 1
if(empty($status)) // False

Make Bootstrap 3 Tabs Responsive

I prefer a css only scheme based on horizontal scroll, like tabs on android. This's my solution, just wrap with a class nav-tabs-responsive:

<div class="nav-tabs-responsive">
  <ul class="nav nav-tabs" role="tablist">
    <li>...</li>
  </ul>
</div>

And two css lines:

.nav-tabs { min-width: 600px; }
.nav-tabs-responsive { overflow: auto; }

600px is the point over you will be responsive (you can set it using bootstrap variables)

Dynamic height for DIV

This worked for me as-
HTML-

    <div style="background-color: #535; width: 100%; height: 80px;">
        <div class="center">
            Test <br>
            kumar adnioas<br>
            sanjay<br>
            1990
        </div>
    </div> 

CSS-

.center {
    position: relative;
    left: 50%;
    top: 50%;
    height: 82%;
    transform: translate(-50%, -50%);
    transform: -webkit-translate(-50%, -50%);
    transform: -ms-translate(-50%, -50%);
   }  

Hope will help you too.

How to completely remove node.js from Windows

Whatever Node.js version you have installed, run its installer again. It asks you to remove Node.js like this:

Node.js Setup window with buttons for Change, Repair, Remove

ToList().ForEach in Linq

You shouldn't use ForEach in that way. Read Lippert's “foreach” vs “ForEach”

If you want to be cruel with yourself (and the world), at least don't create useless List

employees.All(p => {
    collection.AddRange(p.Departments);
    p.Departments.All(u => { u.SomeProperty = null; return true; } );
    return true;
});

Note that the result of the All expression is a bool value that we are discarding (we are using it only because it "cycles" all the elements)

I'll repeat. You shouldn't use ForEach to change objects. LINQ should be used in a "functional" way (you can create new objects but you can't change old objects nor you can create side-effects). And what you are writing is creating so many useless List only to gain two lines of code...

HTML5 - mp4 video does not play in IE9

Whithout JavaScript, the only way I could play without errors:

<!--[if lte IE 9]>
<!-- PUT HERE A FLASH PLAYER WITH video.flv -->
<![endif]-->

<!--[if gt IE 9]><!-->
<video controls class="video">
    <source src="video.mp4" type="video/mp4">
    <!-- REPEAT FLASH PLAYER CODE HERE -->
</video>
<!--<![endif]-->

How can I use a JavaScript variable as a PHP variable?

I had the same problem a few weeks ago like yours; but I invented a brilliant solution for exchanging variables between PHP and JavaScript. It worked for me well:

  1. Create a hidden form on a HTML page

  2. Create a Textbox or Textarea in that hidden form

  3. After all of your code written in the script, store the final value of your variable in that textbox

  4. Use $_REQUEST['textbox name'] line in your PHP to gain access to value of your JavaScript variable.

I hope this trick works for you.

convert iso date to milliseconds in javascript

A shorthand of the previous solutions is

var myDate = +new Date("2012-02-10T13:19:11+0000");

It does an on the fly type conversion and directly outputs date in millisecond format.

Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.

var myDate = Date.parse("2012-02-10T13:19:11+0000");

WCF ServiceHost access rights

I am working on Windows Vista. Even i faced the same problem but when i tried to run VS 2008 with administrative privileges, the issue resolved and my service was up and running. :)

How do I convert an array object to a string in PowerShell?

I found that piping the array to the Out-String cmdlet works well too.

For example:

PS C:\> $a  | out-string

This
Is
a
cat

It depends on your end goal as to which method is the best to use.

How to view query error in PDO PHP

You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.
And since you expect the exception to be thrown by the prepare() method you should disable the PDO::ATTR_EMULATE_PREPARES* feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


    $pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');
}
catch(Exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

prints (in my case)

Exception -> string(91) "SQLSTATE[42S02]: Base table or view not found: 
1146 Table 'test.doesnotexist' doesn't exist"

see http://wezfurlong.org/blog/2006/apr/using-pdo-mysql/
EMULATE_PREPARES=true seems to be the default setting for the pdo_mysql driver right now. The query cache thing has been fixed/change since then and with the mysqlnd driver I hadn't problems with EMULATE_PREPARES=false (though I'm only a php hobbyist, don't take my word on it...)

*) and then there's PDO::MYSQL_ATTR_DIRECT_QUERY - I must admit that I don't understand the interaction of those two attributes (yet?), so I set them both, like

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));

Command line .cmd/.bat script, how to get directory of running script

for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d

pushd %curdir%

Source

Find and replace in file and overwrite file doesn't work, it empties the file

use sed's -i option, e.g.

sed -i bak -e s/STRING_TO_REPLACE/REPLACE_WITH/g index.html

How to get text from EditText?

Put this in your MainActivity:

{
    public EditText bizname, storeno, rcpt, item, price, tax, total;
    public Button click, click2;
    int contentView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main_activity );
        bizname = (EditText) findViewById( R.id.editBizName );
        item = (EditText) findViewById( R.id.editItem );
        price = (EditText) findViewById( R.id.editPrice );
        tax = (EditText) findViewById( R.id.editTax );
        total = (EditText) findViewById( R.id.editTotal );
        click = (Button) findViewById( R.id.button );
    }
}

Put this under a button or something

public void clickBusiness(View view) {
    checkPermsOfStorage( this );

    bizname = (EditText) findViewById( R.id.editBizName );
    item = (EditText) findViewById( R.id.editItem );
    price = (EditText) findViewById( R.id.editPrice );
    tax = (EditText) findViewById( R.id.editTax );
    total = (EditText) findViewById( R.id.editTotal );
    String x = ("\nItem/Price: " + item.getText() + price.getText() + "\nTax/Total" + tax.getText() + total.getText());
    Toast.makeText( this, x, Toast.LENGTH_SHORT ).show();
    try {
        this.WriteBusiness(bizname,storeno,rcpt,item,price,tax,total);
        String vv = tax.getText().toString();
        System.console().printf( "%s", vv );
        //new XMLDivisionWriter(getString(R.string.SDDoc) + "/tax_div_business.xml");
    } catch (ReflectiveOperationException e) {
        e.printStackTrace();
    }
}

There! The debate is settled!

how to avoid a new line with p tag?

I came across this for css

span, p{overflow:hidden; white-space: nowrap;}

via similar stackoverflow question

error: package javax.servlet does not exist

maybe doesnt exists javaee-api-7.0.jar. download this jar and on your project right clik

  1. on your project right click
  2. build path
  3. Configure build path
  4. Add external Jars
  5. javaee-api-7.0.jar choose
  6. Apply and finish

How to select records from last 24 hours using SQL?

In MySQL:

SELECT  *
FROM    mytable
WHERE   record_date >= NOW() - INTERVAL 1 DAY

In SQL Server:

SELECT  *
FROM    mytable
WHERE   record_date >= DATEADD(day, -1, GETDATE())

In Oracle:

SELECT  *
FROM    mytable
WHERE   record_date >= SYSDATE - 1

In PostgreSQL:

SELECT  *
FROM    mytable
WHERE   record_date >= NOW() - '1 day'::INTERVAL

In Redshift:

SELECT  *
FROM    mytable
WHERE   record_date >= GETDATE() - '1 day'::INTERVAL

In SQLite:

SELECT  *
FROM    mytable
WHERE   record_date >= datetime('now','-1 day')

In MS Access:

SELECT  *
FROM    mytable
WHERE   record_date >= (Now - 1)

The APR based Apache Tomcat Native library was not found on the java.library.path

not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

The native lib is expected in one of the following locations

/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib

and not in

tomcat/lib

The files in tomcat/lib are all jar file and are added by tomcat to the classpath so that they are available to your application.

The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar, for linux it could be a .so file, for windows it could be a .dll file.

Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.

Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.

org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms

EDIT

The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.

If you are troubling with running your servlet then after the run on sever command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.

It should be something like that

http://localhost:8080/<your-context-name>/<your-servlet-name>

EDIT 2

Try to call your servlet using the following url

http://localhost:8080/com.filecounter/FileCounter

Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF.

It is better to configure your servlets there using servlet-name servlet-class and url-mapping. It could look like that:

  <servlet>
    <description></description>
    <display-name>File counter - My first servlet</display-name>
    <servlet-name>file_counter</servlet-name>
    <servlet-class>com.filecounter.FileCounter</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>file_counter</servlet-name>
    <url-pattern>/FileFounter</url-pattern>
  </servlet-mapping>

In eclipse dynamic web project the default context name is the same as your project name.

http://localhost:8080/<your-context-name>/FileCounter

will work too.

Do you use source control for your database items?

While this question has many good answers, most of them don’t include the innovations changes in the market, specifically with commercial tools.

Here is a short list of tools that do database version control, I listed the pros and cons of each (full discloser: I work for DBmaestro)

Red-Gate – has been on the market for many years. It provides version control of database objects using scripts integrated with file-based version control.

DBVS – provides version control of the database objects using scripts integrated with file-based version control.

DBmaestro – Provides an enforcement of the version control processes (check-out / check-in) on the real database objects. So there is no question if the version control repository is in-sync with the database being used by the application.

I would encourage you to read a comprehensive, unbiased review on Database Enforced Change Management solutions by veteran database expert Ben Taylor which he posted on LinkedIn https://www.linkedin.com/pulse/article/20140907002729-287832-solve-database-change-mangement-with-dbmaestro

setup android on eclipse but don't know SDK directory

a simple windows search for android-sdk should help you find it, assuming you named it that. You also might just wanna try sdk

Getting the parent of a directory in Bash

dir=/home/smith/Desktop/Test
parentdir="$(dirname "$dir")"

Works if there is a trailing slash, too.

How do I do an OR filter in a Django query?

It is worth to note that it's possible to add Q expressions.

For example:

from django.db.models import Q

query = Q(first_name='mark')
query.add(Q(email='[email protected]'), Q.OR)
query.add(Q(last_name='doe'), Q.AND)

queryset = User.objects.filter(query)

This ends up with a query like :

(first_name = 'mark' or email = '[email protected]') and last_name = 'doe'

This way there is no need to deal with or operators, reduce's etc.

display Java.util.Date in a specific format

How about:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));

> 31/05/2011

Check if image exists on server using JavaScript?

You could use something like:

function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status != 404;

}

Obviously you could use jQuery/similar to perform your HTTP request.

$.get(image_url)
    .done(function() { 
        // Do something now you know the image exists.

    }).fail(function() { 
        // Image doesn't exist - do something else.

    })

AJAX POST and Plus Sign ( + ) -- How to Encode?

Use encodeURIComponent() in JS and in PHP you should receive the correct values.

Note: When you access $_GET, $_POST or $_REQUEST in PHP, you are retrieving values that have already been decoded.

Example:

In your JS:

// url encode your string
var string = encodeURIComponent('+'); // "%2B"
// send it to your server
window.location = 'http://example.com/?string='+string; // http://example.com/?string=%2B

On your server:

echo $_GET['string']; // "+"

It is only the raw HTTP request that contains the url encoded data.

For a GET request you can retrieve this from the URI. $_SERVER['REQUEST_URI'] or $_SERVER['QUERY_STRING']. For a urlencoded POST, file_get_contents('php://stdin')

NB:

decode() only works for single byte encoded characters. It will not work for the full UTF-8 range.

eg:

text = "\u0100"; // A
// incorrect
escape(text); // %u0100 
// correct
encodeURIComponent(text); // "%C4%80"

Note: "%C4%80" is equivalent to: escape('\xc4\x80')

Which is the byte sequence (\xc4\x80) that represents A in UTF-8. So if you use encodeURIComponent() your server side must know that it is receiving UTF-8. Otherwise PHP will mangle the encoding.

Fast way to discover the row count of a table in PostgreSQL

I did this once in a postgres app by running:

EXPLAIN SELECT * FROM foo;

Then examining the output with a regex, or similar logic. For a simple SELECT *, the first line of output should look something like this:

Seq Scan on uids  (cost=0.00..1.21 rows=8 width=75)

You can use the rows=(\d+) value as a rough estimate of the number of rows that would be returned, then only do the actual SELECT COUNT(*) if the estimate is, say, less than 1.5x your threshold (or whatever number you deem makes sense for your application).

Depending on the complexity of your query, this number may become less and less accurate. In fact, in my application, as we added joins and complex conditions, it became so inaccurate it was completely worthless, even to know how within a power of 100 how many rows we'd have returned, so we had to abandon that strategy.

But if your query is simple enough that Pg can predict within some reasonable margin of error how many rows it will return, it may work for you.

How can I update a row in a DataTable in VB.NET?

The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.

To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse

dtResult.Rows(i)("Foo") = strVerse

Get average color of image via Javascript

I recently came across a jQuery plugin which does what I originally wanted https://github.com/briangonzalez/jquery.adaptive-backgrounds.js in regards to getting a dominiate color from an image.

Difference between Method and Function?

In C#, they are interchangeable (although method is the proper term) because you cannot write a method without incorporating it into a class. If it were independent of a class, then it would be a function. Methods are functions that operate through a designated class.

mysqli::query(): Couldn't fetch mysqli

Check if db name do not have "_" or "-" that helps in my case

How do I clone a generic List in Java?

I find using addAll works fine.

ArrayList<String> copy = new ArrayList<String>();
copy.addAll(original);

parentheses are used rather than the generics syntax

"Failed to install the following Android SDK packages as some licences have not been accepted" error

in Windows OS go to your sdkmanager path then execute

./sdkmanager.bat --licenses

You can find your sdkmanager in C:\Users\USER\AppData\Local\Android\Sdk\tools\bin

To find your actual android SDK path follow the red marked area of the below picture

enter image description here

Opening a CHM file produces: "navigation to the webpage was canceled"

"unblocking" the file fixes the problem. Screenshot:

enter image description here

Use different Python version with virtualenv

Mac OSX 10.6.8 (Snow Leopard):

1) When you do pip install virtualenv, the pip command is associated with one of your python versions, and virtualenv gets installed into that version of python. You can do

 $ which pip   

to see what version of python that is. If you see something like:

 $ which pip
 /usr/local/bin/pip

then do:

$ ls -al /usr/local/bin/pip
lrwxrwxr-x  1 root  admin  65 Apr 10  2015 /usr/local/bin/pip ->
../../../Library/Frameworks/Python.framework/Versions/2.7/bin/pip

You can see the python version in the output.

By default, that will be the version of python that is used for any new environment you create. However, you can specify any version of python installed on your computer to use inside a new environment with the -p flag:

$ virtualenv -p python3.2 my_env  
Running virtualenv with interpreter /usr/local/bin/python3.2  
New python executable in my_env/bin/python  
Installing setuptools, pip...done.  

virtualenv my_env will create a folder in the current directory which will contain the Python executable files, and a copy of the pip [command] which you can use to install other packages.

http://docs.python-guide.org/en/latest/dev/virtualenvs/

virtualenv just copies python from a location on your computer into the newly created my_env/bin/ directory.

2) The system python is in /usr/bin, while the various python versions I installed were, by default, installed into:

 /usr/local/bin

3) The various pythons I installed have names like python2.7 or python3.2, and I can use those names rather than full paths.

========VIRTUALENVWRAPPER=========

1) I had some problems getting virtualenvwrapper to work. This is what I ended up putting in ~/.bash_profile:

export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/django_projects  #Not very important -- mkproject command uses this
#Added the following based on: 
#http://stackoverflow.com/questions/19665327/virtualenvwrapper-installation-snow-leopard-python
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python2.7 
#source /usr/local/bin/virtualenvwrapper.sh
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh

2) The -p option works differently with virtualenvwrapper: I have to specify the full path to the python interpreter to be used in the new environment(when I do not want to use the default python version):

$ mkvirtualenv -p /usr/local/bin/python3.2 my_env
Running virtualenv with interpreter /usr/local/bin/python3
New python executable in my_env/bin/python
Installing setuptools, pip...done.
Usage: source deactivate

removes the 'bin' directory of the environment activated with 'source
activate' from PATH. 

Unlike virtualenv, virtualenvwrapper will create the environment at the location specified by the $WORKON_HOME environment variable. That keeps all your environments in one place.

An object reference is required to access a non-static member

You should make your audioSounds and minTime members static:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

But I would consider using singleton objects instead of static members instead:

public class SoundManager : MonoBehaviour
{

    public List<AudioSource> audioSounds = new List<AudioSource>();
    public double minTime = 0.5;

    public static SoundManager Instance { get; private set; }

    void Awake()
    {
        Instance = this;
    }

    public void playSound(AudioClip sourceSound, Vector3 objectPosition, int volume, float audioPitch, int dopplerLevel)
    {    
        bool playsound = false;
        foreach (AudioSource sound in audioSounds) // Loop through List with foreach
        {  
            if (sourceSound.name != sound.name && sound.time <= minTime)
            {
                playsound = true;
            }
        }

        if(playsound) {
            AudioSource.PlayClipAtPoint(sourceSound, objectPosition);
        }

    }
}

Update from September 2020:

Six years later, it is still one of my most upvoted answers on StackOverflow, so I feel obligated to add: singleton is a pattern that creates a lot of problems down the road, and personally, I consider it to be an anti-pattern. It can be accessed from anywhere, and using singletons for different game systems creates a spaghetti of invisible dependencies between different parts of your project.

If you're just learning to program, using singletons is OK for now. But please, consider reading about Dependency Injection, Inversion of Control and other architectural patterns. At least file it under "stuff I will learn later". This may sound as an overkill when you first learn about them, but a proper architecture can become a life-saver on middle and big projects.

Could not resolve '...' from state ''

Had the same issue with Ionic routing.

Simple solution is to use the name of the state - basically state.go(state name)

.state('tab.search', {
    url: '/search',
    views: {
      'tab-search': {
        templateUrl: 'templates/search.html',
        controller: 'SearchCtrl'
      }
    }
  })

And in controller you can use $state.go('tab.search');

How to convert a String to a Date using SimpleDateFormat?

String newstr = "08/16/2011";
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format = new SimpleDateFormat("EE MMM dd hh:mm:ss z yyyy");
Calendar c = Calendar.getInstance();
c.setTime(format1.parse(newstr));
System.out.println(format.format(c.getTime()));

How to assign multiple classes to an HTML container?

From the standard

7.5.2 Element identifiers: the id and class attributes

Attribute definitions

id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.

class = cdata-list [CS]
This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.

Yes, just put a space between them.

<article class="column wrapper">

Of course, there are many things you can do with CSS inheritance. Here is an article for further reading.

Understanding implicit in Scala

WARNING: contains sarcasm judiciously! YMMV...

Luigi's answer is complete and correct. This one is only to extend it a bit with an example of how you can gloriously overuse implicits, as it happens quite often in Scala projects. Actually so often, you can probably even find it in one of the "Best Practice" guides.

object HelloWorld {
  case class Text(content: String)
  case class Prefix(text: String)

  implicit def String2Text(content: String)(implicit prefix: Prefix) = {
    Text(prefix.text + " " + content)
  }

  def printText(text: Text): Unit = {
    println(text.content)
  }

  def main(args: Array[String]): Unit = {
    printText("World!")
  }

  // Best to hide this line somewhere below a pile of completely unrelated code.
  // Better yet, import its package from another distant place.
  implicit val prefixLOL = Prefix("Hello")
}

Any reason to prefer getClass() over instanceof when generating .equals()?

instanceof works for instences of the same class or its subclasses

You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

ArryaList and RoleList are both instanceof List

While

getClass() == o.getClass() will be true only if both objects ( this and o ) belongs to exactly the same class.

So depending on what you need to compare you could use one or the other.

If your logic is: "One objects is equals to other only if they are both the same class" you should go for the "equals", which I think is most of the cases.

Decreasing for loops in Python impossible?

This is very late, but I just wanted to add that there is a more elegant way: using reversed

for i in reversed(range(10)):
    print i

gives:

4
3
2
1
0

"Too many values to unpack" Exception

This problem looked familiar so I thought I'd see if I could replicate from the limited amount of information.

A quick search turned up an entry in James Bennett's blog here which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error.

To quote the blog entry:

The value of the setting is not "appname.models.modelname", it's just "appname.modelname". The reason is that Django is not using this to do a direct import; instead, it's using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like "appname.models.modelname" or "projectname.appname.models.modelname" in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded "too many values to unpack" error, so make sure you've put "appname.modelname", and nothing else, in the value of AUTH_PROFILE_MODULE.

If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding "models" to my AUTH_PROFILE_MODULE setting.

TemplateSyntaxError at /

Caught an exception while rendering: too many values to unpack

Original Traceback (most recent call last):
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 71, in render_node
    result = node.render(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/debug.py", line 87, in render
    output = force_unicode(self.filter_expression.resolve(context))
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 535, in resolve
    obj = self.var.resolve(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 676, in resolve
    value = self._resolve_lookup(context)
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/template/__init__.py", line 711, in _resolve_lookup
    current = current()
  File "/home/brandon/Development/DJANGO_VERSIONS/Django-1.0/django/contrib/auth/models.py", line 291, in get_profile
    app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
ValueError: too many values to unpack

This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn't throw the expected exception.

You can see at the end of the traceback that I posted how using anything other than the form "appname.modelname" for the AUTH_PROFILE_MODULE would cause the line "app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')" to throw the "too many values to unpack" error.

I'm 99% sure that this was the original problem encountered here.

Compiling C++11 with g++

You can refer to following link for which features are supported in particular version of compiler. It has an exhaustive list of feature support in compiler. Looks GCC follows standard closely and implements before any other compiler.

Regarding your question you can compile using

  1. g++ -std=c++11 for C++11
  2. g++ -std=c++14 for C++14
  3. g++ -std=c++17 for C++17
  4. g++ -std=c++2a for C++20, although all features of C++20 are not yet supported refer this link for feature support list in GCC.

The list changes pretty fast, keep an eye on the list, if you are waiting for particular feature to be supported.

How do I detect a click outside an element?

I know there are a million answers to this question, but I've always been a fan of using HTML and CSS to do most of the work. In this case, z-index and positioning. The simplest way that I have found to do this is as follows:

_x000D_
_x000D_
$("#show-trigger").click(function(){_x000D_
  $("#element").animate({width: 'toggle'});_x000D_
  $("#outside-element").show();_x000D_
});_x000D_
$("#outside-element").click(function(){_x000D_
  $("#element").hide();_x000D_
  $("#outside-element").hide();_x000D_
});
_x000D_
#outside-element {_x000D_
  position:fixed;_x000D_
  width:100%;_x000D_
  height:100%;_x000D_
  z-index:1;_x000D_
  display:none;_x000D_
}_x000D_
#element {_x000D_
  display:none;_x000D_
  padding:20px;_x000D_
  background-color:#ccc;_x000D_
  width:300px;_x000D_
  z-index:2;_x000D_
  position:relative;_x000D_
}_x000D_
#show-trigger {_x000D_
  padding:20px;_x000D_
  background-color:#ccc;_x000D_
  margin:20px auto;_x000D_
  z-index:2;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="outside-element"></div>_x000D_
<div id="element">_x000D_
  <div class="menu-item"><a href="#1">Menu Item 1</a></div>_x000D_
  <div class="menu-item"><a href="#2">Menu Item 1</a></div>_x000D_
  <div class="menu-item"><a href="#3">Menu Item 1</a></div>_x000D_
  <div class="menu-item"><a href="#4">Menu Item 1</a></div>_x000D_
</div>_x000D_
<div id="show-trigger">Show Menu</div>
_x000D_
_x000D_
_x000D_

This creates a safe environment, since nothing is going to get triggered unless the menu is actually open and the z-index protects any of the content within the element from creating any misfires upon being clicked.

Additionally, you're not requiring jQuery to cover all of your bases with propagation calls and having to purge all of the inner elements from misfires.

Calendar date to yyyy-MM-dd format in java

public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month, date);
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
    String formatted = format1.format(cal.getTime());
    System.out.println(formatted);
}

Setting background color for a JFrame

Probably the SIMPLEST method is this:

super.setBackground(Color.CYAN);

You must extend JFrame in the class before doing this!

What are some uses of template template parameters?

In the solution with variadic templates provided by pfalcon, I found it difficult to actually specialize the ostream operator for std::map due to the greedy nature of the variadic specialization. Here's a slight revision which worked for me:

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <map>

namespace containerdisplay
{
  template<typename T, template<class,class...> class C, class... Args>
  std::ostream& operator <<(std::ostream& os, const C<T,Args...>& objs)
  {
    std::cout << __PRETTY_FUNCTION__ << '\n';
    for (auto const& obj : objs)
      os << obj << ' ';
    return os;
  }  
}

template< typename K, typename V>
std::ostream& operator << ( std::ostream& os, 
                const std::map< K, V > & objs )
{  

  std::cout << __PRETTY_FUNCTION__ << '\n';
  for( auto& obj : objs )
  {    
    os << obj.first << ": " << obj.second << std::endl;
  }

  return os;
}


int main()
{

  {
    using namespace containerdisplay;
    std::vector<float> vf { 1.1, 2.2, 3.3, 4.4 };
    std::cout << vf << '\n';

    std::list<char> lc { 'a', 'b', 'c', 'd' };
    std::cout << lc << '\n';

    std::deque<int> di { 1, 2, 3, 4 };
    std::cout << di << '\n';
  }

  std::map< std::string, std::string > m1 
  {
      { "foo", "bar" },
      { "baz", "boo" }
  };

  std::cout << m1 << std::endl;

    return 0;
}

Vue component event after render

updated() should be what you're looking for:

Called after a data change causes the virtual DOM to be re-rendered and patched.

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.

gpg decryption fails with no secret key error

I have solved this problem, try to use root privileges, such as sudo gpg ... I think that gpg elevated without permissions does not refer to file permissions, but system

Conversion failed when converting the nvarchar value ... to data type int

You are trying to concatenate a string and an integer.
You need to cast @ID as a string.
try:

SET @sql=@sql+' AND Emp_Id_Pk=' + CAST(@ID AS NVARCHAR(10))

Check if String / Record exists in DataTable

Use the Find method if item_manuf_id is a primary key:

var result = dtPs.Rows.Find("some value");

If you only want to know if the value is in there then use the Contains method.

if (dtPs.Rows.Contains("some value"))
{
  ...
}

Primary key restriction applies to Contains aswell.

Clip/Crop background-image with CSS

Another option is to use linear-gradient() to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...

_x000D_
_x000D_
.flair {_x000D_
  min-width: 50px; /* width larger than sprite */_x000D_
  text-indent: 60px;_x000D_
  height: 25px;_x000D_
  display: inline-block;_x000D_
  background:_x000D_
    linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
    url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;_x000D_
}_x000D_
_x000D_
.flair-classic {_x000D_
  background-position: 50px 0, 0 -25px;_x000D_
}_x000D_
_x000D_
.flair-r2 {_x000D_
  background-position: 50px 0, -50px -175px;_x000D_
}_x000D_
_x000D_
.flair-smite {_x000D_
  text-indent: 35px;_x000D_
  background-position: 25px 0, -50px -25px;_x000D_
}
_x000D_
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />
_x000D_
_x000D_
_x000D_

I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before or ::after elements because I'm already using them for another hack.

How do I remove the top margin in a web page?

I had similar problem, got this resolved by the following CSS:

body {    
    margin: 0 !important;
    padding: 0 !important;
}

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

Selecting only first-level elements in jquery

You can also use $("ul li:first-child") to only get the direct children of the UL.

I agree though, you need an ID or something else to identify the main UL otherwise it will just select them all. If you had a div with an ID around the UL the easiest thing to do would be$("#someDiv > ul > li")

Add custom headers to WebView resource requests - android

Maybe my response quite late, but it covers API below and above 21 level.

To add headers we should intercept every request and create new one with required headers.

So we need to override shouldInterceptRequest method called in both cases: 1. for API until level 21; 2. for API level 21+

    webView.setWebViewClient(new WebViewClient() {

        // Handle API until level 21
        @SuppressWarnings("deprecation")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

            return getNewResponse(url);
        }

        // Handle API 21+
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

            String url = request.getUrl().toString();

            return getNewResponse(url);
        }

        private WebResourceResponse getNewResponse(String url) {

            try {
                OkHttpClient httpClient = new OkHttpClient();

                Request request = new Request.Builder()
                        .url(url.trim())
                        .addHeader("Authorization", "YOU_AUTH_KEY") // Example header
                        .addHeader("api-key", "YOUR_API_KEY") // Example header
                        .build();

                Response response = httpClient.newCall(request).execute();

                return new WebResourceResponse(
                        null,
                        response.header("content-encoding", "utf-8"),
                        response.body().byteStream()
                );

            } catch (Exception e) {
                return null;
            }

        }
   });

If response type should be processed you could change

        return new WebResourceResponse(
                null, // <- Change here
                response.header("content-encoding", "utf-8"),
                response.body().byteStream()
        );

to

        return new WebResourceResponse(
                getMimeType(url), // <- Change here
                response.header("content-encoding", "utf-8"),
                response.body().byteStream()
        );

and add method

        private String getMimeType(String url) {
            String type = null;
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);

            if (extension != null) {

                switch (extension) {
                    case "js":
                        return "text/javascript";
                    case "woff":
                        return "application/font-woff";
                    case "woff2":
                        return "application/font-woff2";
                    case "ttf":
                        return "application/x-font-ttf";
                    case "eot":
                        return "application/vnd.ms-fontobject";
                    case "svg":
                        return "image/svg+xml";
                }

                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            }

            return type;
        }

How to Call VBA Function from Excel Cells?

The issue you have encountered is that UDFs cannot modify the Excel environment, they can only return a value to the calling cell.

There are several alternatives

  1. For the sample given you don't actually need VBA. This formula will work
    ='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2

  2. Use a rather messy work around: See this answer

  3. You can use ExecuteExcel4Macro or OLEDB

How can I align button in Center or right using IONIC framework?

You should put the button inside a div, and in the div you should be able to use the classes:
text-left, text-center and text-right.

for example:

<div class="row">
   <div class="col text-center">
      <button class="button button-small button-light">Search</button>
   </div>
</div>

And about the "textarea" position:

<div class="list">
<label class="item item-input">
    <span class="input-label">Date</span>
    <input type="text" placeholder="Text Area">
</label>

Demo using your code:
http://codepen.io/douglask/pen/zxXvYY

What is the difference between procedural programming and functional programming?

A functional programming is identical to procedural programming in which global variables are not being used.

Populate nested array in mongoose

If you would like to populate another level deeper, here's what you need to do:

Airlines.findById(id)
      .populate({
        path: 'flights',
        populate:[
          {
            path: 'planeType',
            model: 'Plane'
          },
          {
          path: 'destination',
          model: 'Location',
          populate: { // deeper
            path: 'state',
            model: 'State',
            populate: { // even deeper
              path: 'region',
              model: 'Region'
            }
          }
        }]
      })

How to test if JSON object is empty in Java

If you're okay with a hack -

obj.toString().equals("{}");

Serializing the object is expensive and moreso for large objects, but it's good to understand that JSON is transparent as a string, and therefore looking at the string representation is something you can always do to solve a problem.

Redirect stderr and stdout in Bash

# Close STDOUT file descriptor
exec 1<&-
# Close STDERR FD
exec 2<&-

# Open STDOUT as $LOG_FILE file for read and write.
exec 1<>$LOG_FILE

# Redirect STDERR to STDOUT
exec 2>&1

echo "This line will appear in $LOG_FILE, not 'on screen'"

Now, simple echo will write to $LOG_FILE. Useful for daemonizing.

To the author of the original post,

It depends what you need to achieve. If you just need to redirect in/out of a command you call from your script, the answers are already given. Mine is about redirecting within current script which affects all commands/built-ins(includes forks) after the mentioned code snippet.


Another cool solution is about redirecting to both std-err/out AND to logger or log file at once which involves splitting "a stream" into two. This functionality is provided by 'tee' command which can write/append to several file descriptors(files, sockets, pipes, etc) at once: tee FILE1 FILE2 ... >(cmd1) >(cmd2) ...

exec 3>&1 4>&2 1> >(tee >(logger -i -t 'my_script_tag') >&3) 2> >(tee >(logger -i -t 'my_script_tag') >&4)
trap 'cleanup' INT QUIT TERM EXIT


get_pids_of_ppid() {
    local ppid="$1"

    RETVAL=''
    local pids=`ps x -o pid,ppid | awk "\\$2 == \\"$ppid\\" { print \\$1 }"`
    RETVAL="$pids"
}


# Needed to kill processes running in background
cleanup() {
    local current_pid element
    local pids=( "$$" )

    running_pids=("${pids[@]}")

    while :; do
        current_pid="${running_pids[0]}"
        [ -z "$current_pid" ] && break

        running_pids=("${running_pids[@]:1}")
        get_pids_of_ppid $current_pid
        local new_pids="$RETVAL"
        [ -z "$new_pids" ] && continue

        for element in $new_pids; do
            running_pids+=("$element")
            pids=("$element" "${pids[@]}")
        done
    done

    kill ${pids[@]} 2>/dev/null
}

So, from the beginning. Let's assume we have terminal connected to /dev/stdout(FD #1) and /dev/stderr(FD #2). In practice, it could be a pipe, socket or whatever.

  • Create FDs #3 and #4 and point to the same "location" as #1 and #2 respectively. Changing FD #1 doesn't affect FD #3 from now on. Now, FDs #3 and #4 point to STDOUT and STDERR respectively. These will be used as real terminal STDOUT and STDERR.
  • 1> >(...) redirects STDOUT to command in parens
  • parens(sub-shell) executes 'tee' reading from exec's STDOUT(pipe) and redirects to 'logger' command via another pipe to sub-shell in parens. At the same time it copies the same input to FD #3(terminal)
  • the second part, very similar, is about doing the same trick for STDERR and FDs #2 and #4.

The result of running a script having the above line and additionally this one:

echo "Will end up in STDOUT(terminal) and /var/log/messages"

...is as follows:

$ ./my_script
Will end up in STDOUT(terminal) and /var/log/messages

$ tail -n1 /var/log/messages
Sep 23 15:54:03 wks056 my_script_tag[11644]: Will end up in STDOUT(terminal) and /var/log/messages

If you want to see clearer picture, add these 2 lines to the script:

ls -l /proc/self/fd/
ps xf

MINGW64 "make build" error: "bash: make: command not found"

You have to install mingw-get and after that you can run mingw-get install msys-make to have the command make available.

Here is a link for what you want http://www.mingw.org/wiki/getting_started

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

[Fixed] Server version: 10.1.38-MariaDB - mariadb.org binary distribution

Go to: C:\xampp\mysql\bin open my.ini in notepad and find [mysqld] (line number 27) then after this line(line no 28) just type: skip-grant-tables

save the file and then reload the phpmyadmin page.It worked for me.

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Eclipse interface icons very small on high resolution screen in Windows 8.1

The compatibility mode for Windows Xp, it's only available for the Eclipse 32 bit version and after running in this compatibility mode the icons and text will be the right size, but blurry because they are scaled from their native resolution to the screen resolution and doing so the quality is lost.

What's the best way to use R scripts on the command line (terminal)?

If you are interested in parsing command line arguments to an R script try RScript which is bundled with R as of version 2.5.x

http://stat.ethz.ch/R-manual/R-patched/library/utils/html/Rscript.html

ORA-00907: missing right parenthesis

Albeit from the useless _T and incorrectly spelled histories. If you are using SQL*Plus, it does not accept create table statements with empty new lines between create table <name> ( and column definitions.

Single quotes vs. double quotes in Python

"If you're going to use apostrophes, 
       ^

you'll definitely want to use double quotes".
   ^

For that simple reason, I always use double quotes on the outside. Always

Speaking of fluff, what good is streamlining your string literals with ' if you're going to have to use escape characters to represent apostrophes? Does it offend coders to read novels? I can't imagine how painful high school English class was for you!

How to combine 2 plots (ggplot) into one plot?

Dummy data (you should supply this for us)

visual1 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
visual2 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))

combine:

visuals = rbind(visual1,visual2)
visuals$vis=c(rep("visual1",100),rep("visual2",100)) # 100 points of each flavour

Now do:

 ggplot(visuals, aes(ISSUE_DATE,COUNTED,group=vis,col=vis)) + 
   geom_point() + geom_smooth()

and adjust colours etc to taste.

enter image description here

How to detect pressing Enter on keyboard using jQuery?

this my how I solved you shoud give return false;

_x000D_
_x000D_
 
 $(document).on('keypress',function(e) {
            if(e.which == 13) {
                $('#sub_btn').trigger('click');
                alert('You pressed a "enter" key in somewhere'); 
                return false;     
            }
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="sub_email_form">
                    <div class="modal-header">
                        <button type="button" class="close" id="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Subscribe to our Technical Analysis</h4>
                    </div>
                    <div class="modal-body">
                        <p>Signup for our regular Technical Analysis updates to review recommendations delivered directly in your inbox.</p>
                        <div class="input-group">
                            <input type="email" name="sub_email" id="sub_email" class="form-control" placeholder="Enter your email" required>
                        </div>
                        <span id="save-error"></span>
                    </div>
                    <div class="modal-footer">
                        <div class="input-group-append">
                            <input type="submit" class="btn btn-primary sub_btn" id="sub_btn" name="sub_btn" value="Subscribe">
                        </div>
                    </div>
                </form>
_x000D_
_x000D_
_x000D_

`

Find files in created between a date range

List files between 2 dates

find . -type f -newermt "2019-01-01" ! -newermt "2019-05-01"

or

find path -type f -newermt "2019-01-01" ! -newermt "2019-05-01"

Get exit code of a background process

I would change your approach slightly. Rather than checking every few seconds if the command is still alive and reporting a message, have another process that reports every few seconds that the command is still running and then kill that process when the command finishes. For example:

#!/bin/sh

cmd() { sleep 5; exit 24; }

cmd &   # Run the long running process
pid=$!  # Record the pid

# Spawn a process that coninually reports that the command is still running
while echo "$(date): $pid is still running"; do sleep 1; done &
echoer=$!

# Set a trap to kill the reporter when the process finishes
trap 'kill $echoer' 0

# Wait for the process to finish
if wait $pid; then
    echo "cmd succeeded"
else
    echo "cmd FAILED!! (returned $?)"
fi

Read all contacts' phone numbers in android

Accepted answer working but not given unique numbers.

See this code, it return unique numbers.

public static void readContacts(Context context) {
        if (context == null)
            return;
        ContentResolver contentResolver = context.getContentResolver();

        if (contentResolver == null)
            return;

        String[] fieldListProjection = {
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
                ContactsContract.Contacts.HAS_PHONE_NUMBER
        };

        Cursor phones = contentResolver
                .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                        , fieldListProjection, null, null, null);
        HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();

        if (phones != null && phones.getCount() > 0) {
            while (phones.moveToNext()) {
                String normalizedNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
                if (Integer.parseInt(phones.getString(phones.getColumnIndex(
                        ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
                        String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                        String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Log.d("test", " Print all values");
                    }
                }
            }
            phones.close();
        }
    }

How to fix Subversion lock error

We had the same repeating problem. It's a disaster. What can you do if cleanup and unlock does not help because there is no existing lock?

  1. Search the hidden .svn folder in your directory structure. It contains a wc.db file which is an sql lite file.
  2. Open it with an sql client, e.g. DBeaver. Add an sql lite connection to the dbeaver by selecting the wc.db file.
  3. Open the WC_LOCK table. You can see one or more rows that contains the URL which was mentioned in the phantom lock error window.
  4. Delete these rows from the table.
  5. Try to update your project from the repo.
  6. If you use more than 1 repo in 1 project (externals) another phantom lock may appear during the update. In this case repeat the process with that folder.

How to handle Pop-up in Selenium WebDriver using Java

I found the solution for the above program, which had the goal of signing in to http://rediff.com

public class Handle_popupNAlert
{
    public static void main(String[] args ) throws InterruptedException
    {
        WebDriver driver= new FirefoxDriver(); 
        driver.get("http://www.rediff.com/");
        WebElement sign = driver.findElement(By.xpath("//html/body/div[3]/div[3]/span[4]/span/a"));
        sign.click();

        Set<String> windowId = driver.getWindowHandles();    // get  window id of current window
        Iterator<String> itererator = windowId.iterator();   

        String mainWinID = itererator.next();
        String  newAdwinID = itererator.next();

        driver.switchTo().window(newAdwinID);
        System.out.println(driver.getTitle());
        Thread.sleep(3000);
        driver.close();

        driver.switchTo().window(mainWinID);
        System.out.println(driver.getTitle());
        Thread.sleep(2000);

        WebElement email_id= driver.findElement(By.xpath("//*[@id='c_uname']"));
        email_id.sendKeys("hi");
        Thread.sleep(5000);

        driver.close();
        driver.quit();
    }  
}

How to rename a class and its corresponding file in Eclipse?

Just right click on the class in the project explorer and select "Refactor" -> "Rename". That it is is under the "Refactor" submenu.

Vue js error: Component template should contain exactly one root element

instead of using this

Vue.component('tabs', {
    template: `
        <div class="tabs">
          <ul>
            <li class="is-active"><a>Pictures</a></li>
            <li><a>Music</a></li>
            <li><a>Videos</a></li>
            <li><a>Documents</a></li>
          </ul>
        </div>

        <div class="tabs-content">
          <slot></slot>
        </div>
    `,
});

you should use


Vue.component('tabs', {
    template: `
      <div>
        <div class="tabs">
          <ul>
            <li class="is-active"><a>Pictures</a></li>
            <li><a>Music</a></li>
            <li><a>Videos</a></li>
            <li><a>Documents</a></li>
          </ul>
        </div>

        <div class="tabs-content">
          <slot></slot>
        </div>
      </div>
    `,
});

Get JavaScript object from array of objects by value of property

If you are looking for a single result, rather than an array, may I suggest reduce?

Here is a solution in plain 'ole javascript that returns a matching object if one exists, or null if not.

var result = arr.reduce(function(prev, curr) { return (curr.b === 6) ? curr : prev; }, null);

How to initialize a nested struct?

If you don't want to go with separate struct definition for nested struct and you don't like second method suggested by @OneOfOne you can use this third method:

package main
import "fmt"
type Configuration struct {
    Val   string
    Proxy struct {
        Address string
        Port    string
    }
}

func main() {
    c := &Configuration{
        Val: "test",
    }

    c.Proxy.Address = `127.0.0.1`
    c.Proxy.Port = `8080`
}

You can check it here: https://play.golang.org/p/WoSYCxzCF2

Compare two columns using pandas

You can use .equals for columns or entire dataframes.

df['col1'].equals(df['col2'])

If they're equal, that statement will return True, else False.

Turn on torch/flash on iPhone

iWasRobbed's answer is great, except there is an AVCaptureSession running in the background all the time. On my iPhone 4s it takes about 12% CPU power according to Instrument so my app took about 1% battery in a minute. In other words if the device is prepared for AV capture it's not cheap.

Using the code below my app requires 0.187% a minute so the battery life is more than 5x longer.

This code works just fine on any device (tested on both 3GS (no flash) and 4s). Tested on 4.3 in simulator as well.

#import <AVFoundation/AVFoundation.h>

- (void) turnTorchOn:(BOOL)on {

    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]){

            [device lockForConfiguration:nil];
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
                torchIsOn = YES;
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
                torchIsOn = NO;            
            }
            [device unlockForConfiguration];
        }
    }
}

How to show current user name in a cell?

Without VBA macro, you can use this tips to get the username from the path :

=MID(INFO("DIRECTORY"),10,LEN(INFO("DIRECTORY"))-LEN(MID(INFO("DIRECTORY"),FIND("\",INFO("DIRECTORY"),10),1000))-LEN("C:\Users\"))

How to get first character of a string in SQL?

If you search the first char of string in Sql string

SELECT CHARINDEX('char', 'my char')

=> return 4

How can I check if a string contains ANY letters from the alphabet?

You can also do this in addition

import re
string='24234ww'
val = re.search('[a-zA-Z]+',string) 
val[0].isalpha() # returns True if the variable is an alphabet
print(val[0]) # this will print the first instance of the matching value

Also note that if variable val returns None. That means the search did not find a match

Convert string with commas to array

Split (",") can convert Strings with commas into a String array, here is my code snippet.

    var input ='Hybrid App, Phone-Gap, Apache Cordova, HTML5, JavaScript, BootStrap, JQuery, CSS3, Android Wear API'
    var output = input.split(",");
    console.log(output);

["Hybrid App", " Phone-Gap", " Apache Cordova", " HTML5", " JavaScript", " BootStrap", " JQuery", " CSS3", " Android Wear API"]

What is the difference between ELF files and bin files?

A bin file is just the bits and bytes that go into the rom or a particular address from which you will run the program. You can take this data and load it directly as is, you need to know what the base address is though as that is normally not in there.

An elf file contains the bin information but it is surrounded by lots of other information, possible debug info, symbols, can distinguish code from data within the binary. Allows for more than one chunk of binary data (when you dump one of these to a bin you get one big bin file with fill data to pad it to the next block). Tells you how much binary you have and how much bss data is there that wants to be initialised to zeros (gnu tools have problems creating bin files correctly).

The elf file format is a standard, arm publishes its enhancements/variations on the standard. I recommend everyone writes an elf parsing program to understand what is in there, dont bother with a library, it is quite simple to just use the information and structures in the spec. Helps to overcome gnu problems in general creating .bin files as well as debugging linker scripts and other things that can help to mess up your bin or elf output.

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

I had same problem in the render() method. The problem comes when you return from render() as :

render() {
    return 
    (
        <div>Here comes JSX !</div>
    );
}

i.e. if you start the parenthesis in a new line

Try using:

render() {
    return (
        <div>Here comes JSX !</div>
    );
}

This will solve the error

How to display JavaScript variables in a HTML page without document.write

You could use jquery to get hold of the html element that you want to load the value with.

Say for instance if your page looks something like this,

<div id="FirstDiv">
  <div id="SecondDiv">
     ...
  </div>
 </div>

And if your javascript (I hope) looks something as simple as this,

function somefunction(){
  var somevalue = "Data to be inserted";
  $("#SecondDiv").text(somevalue);
}

I hope this is what you were looking for.

how to apply click event listener to image in android

ImageView img = (ImageView) findViewById(R.id.myImageId);
img.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
       // your code here
    }
});

Firebase FCM force onTokenRefresh() to be called

Guys it has very simple solution

https://developers.google.com/instance-id/guides/android-implementation#generate_a_token

Note: If your app used tokens that were deleted by deleteInstanceID, your app will need to generate replacement tokens.

In stead of deleting instance Id, delete only token:

String authorizedEntity = PROJECT_ID;
String scope = "GCM";
InstanceID.getInstance(context).deleteToken(authorizedEntity,scope);

Difference between modes a, a+, w, w+, and r+ in built-in open function?

The options are the same as for the fopen function in the C standard library:

w truncates the file, overwriting whatever was already there

a appends to the file, adding onto whatever was already there

w+ opens for reading and writing, truncating the file but also allowing you to read back what's been written to the file

a+ opens for appending and reading, allowing you both to append to the file and also read its contents

Count number of occurrences by month

Sooooo, I had this same question. here's my answer: COUNTIFS(sheet1!$A:$A,">="&D1,sheet1!$A:$A,"<="&D2)

you don't need to specify A2:A50, unless there are dates beyond row 50 that you wish to exclude. this is cleaner in the sense that you don't have to go back and adjust the rows as more PO data comes in on sheet1.

also, the reference to D1 and D2 are start and end dates (respectively) for each month. On sheet2, you could have a hidden column that translates April to 4/1/2014, May into 5/1/2014, etc. THen, D1 would reference the cell that contains 4/1/2014, and D2 would reference the cell that contains 5/1/2014.

if you want to sum, it works the same way, except that the first argument is the sum array (column or row) and then the rest of the ranges/arrays and arguments are the same as the countifs formula.

btw-this works in excel AND google sheets. cheers

sqlalchemy: how to join several tables by one query?

Expanding on Abdul's answer, you can obtain a KeyedTuple instead of a discrete collection of rows by joining the columns:

q = Session.query(*User.__table__.columns + Document.__table__.columns).\
        select_from(User).\
        join(Document, User.email == Document.author).\
        filter(User.email == 'someemail').all()

Inheriting constructors

You have to explicitly define the constructor in B and explicitly call the constructor for the parent.

B(int x) : A(x) { }

or

B() : A(5) { }

ValueError when checking if variable is None or numpy.array

Using not a to test whether a is None assumes that the other possible values of a have a truth value of True. However, most NumPy arrays don't have a truth value at all, and not cannot be applied to them.

If you want to test whether an object is None, the most general, reliable way is to literally use an is check against None:

if a is None:
    ...
else:
    ...

This doesn't depend on objects having a truth value, so it works with NumPy arrays.

Note that the test has to be is, not ==. is is an object identity test. == is whatever the arguments say it is, and NumPy arrays say it's a broadcasted elementwise equality comparison, producing a boolean array:

>>> a = numpy.arange(5)
>>> a == None
array([False, False, False, False, False])
>>> if a == None:
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
 Use a.any() or a.all()

On the other side of things, if you want to test whether an object is a NumPy array, you can test its type:

# Careful - the type is np.ndarray, not np.array. np.array is a factory function.
if type(a) is np.ndarray:
    ...
else:
    ...

You can also use isinstance, which will also return True for subclasses of that type (if that is what you want). Considering how terrible and incompatible np.matrix is, you may not actually want this:

# Again, ndarray, not array, because array is a factory function.
if isinstance(a, np.ndarray):
    ...
else:
    ...    

Android selector & text color

In order to make it work on selection in a list view use the following code:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#fff"/>
    <item android:state_activated="true" android:color="#fff"/>
    <item android:color="#000" />
</selector>

Apparently the key is state_activated="true" state.

How to use java.String.format in Scala?

The official reference is the class Formatter.

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

How to use HTML Agility pack

I don't know if this will be of any help to you, but I have written a couple of articles which introduce the basics.

The next article is 95% complete, I just have to write up explanations of the last few parts of the code I have written. If you are interested then I will try to remember to post here when I publish it.

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

how to access parent window object using jquery?

Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:

window.parent.$("#serverMsg")

Difference between == and === in JavaScript

Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html

The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.

0 == false   // true
0 === false  // false, because they are of a different type
1 == "1"     // true, automatic type conversion for value only
1 === "1"    // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

Why is Dictionary preferred over Hashtable in C#?

Because Dictionary is a generic class ( Dictionary<TKey, TValue> ), so that accessing its content is type-safe (i.e. you do not need to cast from Object, as you do with a Hashtable).

Compare

var customers = new Dictionary<string, Customer>();
...
Customer customer = customers["Ali G"];

to

var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer;

However, Dictionary is implemented as hash table internally, so technically it works the same way.

MySql Inner Join with WHERE clause

You are using two WHERE clauses but only one is allowed. Use it like this:

SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
WHERE
  table1.f_com_id = '430'
  AND table1.f_status = 'Submitted'
  AND table2.f_type = 'InProcess'

Explain ggplot2 warning: "Removed k rows containing missing values"

Even if your data falls within your specified limits (e.g. c(0, 335)), adding a geom_jitter() statement could push some points outside those limits, producing the same error message.

library(ggplot2)

range(mtcars$hp)
#> [1]  52 335

# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) + 
    geom_point() +
    scale_y_continuous(limits=c(0,335))


# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) + 
    geom_point() +
    geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
    scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).

Created on 2020-08-24 by the reprex package (v0.3.0)

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

First, if you are unfamiliar with the command line, try using phpmyadmin from your webbrowser. This will make sure you actually have a mysql database created and a username.

This is how you connect from the command line (bash):

mysql -h hostname -u username -p database_name

For example:

fabio@crunchbang ~ $ mysql -h 127.0.0.1 -u fabio -p fabiodb

How do I get started with Node.js

You can follow these tutorials to get started

Tutorials

Developer Sites

Videos

Screencasts

Books

Courses

Blogs

Podcasts

JavaScript resources

Node.js Modules

Other

Remove columns from DataTable in C#

To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.

DataTable dt;
int desiredSize = 10;

while (dt.Columns.Count > desiredSize)
{
   dt.Columns.RemoveAt(desiredSize);
}

Mailto on submit button

What you need to do is use the onchange event listener in the form and change the href attribute of the send button according to the context of the mail:

<form id="form" onchange="mail(this)">
  <label>Name</label>
  <div class="row margin-bottom-20">
    <div class="col-md-6 col-md-offset-0">
      <input class="form-control" name="name" type="text">
    </div>
  </div>

  <label>Email <span class="color-red">*</span></label>
  <div class="row margin-bottom-20">
    <div class="col-md-6 col-md-offset-0">
      <input class="form-control" name="email" type="text">
    </div>
  </div>

  <label>Date of visit/departure </label>
  <div class="row margin-bottom-20">
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control w8em" name="adate" type="text">
      <script>
        datePickerController.createDatePicker({
          // Associate the text input to a DD/MM/YYYY date format
          formElements: {
            "adate": "%d/%m/%Y"
          }
        });
      </script>
    </div>
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" name="ddate" type="date">
    </div>
  </div>

  <label>No. of people travelling with</label>
  <div class="row margin-bottom-20">
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" placeholder="Adults" min=1 name="adult" type="number">
    </div>
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" placeholder="Children" min=0 name="childeren" type="number">
    </div>
  </div>

  <label>Cities you want to visit</label><br />
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Cassablanca">Cassablanca</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Fez">Fez</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Tangier">Tangier</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Marrakech">Marrakech</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Rabat">Rabat</label>
  </div>

  <div class="row margin-bottom-20">
    <div class="col-md-8 col-md-offset-0">
      <textarea rows="4" placeholder="Activities Intersted in" name="activities" class="form-control"></textarea>
    </div>
  </div>


  <div class="row margin-bottom-20">
    <div class="col-md-8 col-md-offset-0">
      <textarea rows="6" class="form-control" name="comment" placeholder="Comment"></textarea>
    </div>
  </div>

  <p><a id="send" class="btn btn-primary">Create Message</a></p>
</form>

JavaScript

function mail(form) {
    var name = form.name.value;
    var city = "";
    var adate = form.adate.value;
    var ddate = form.ddate.value;
    var activities = form.activities.value;
    var adult = form.adult.value;
    var child = form.childeren.value;
    var comment = form.comment.value;
    var warning = ""
    for (i = 0; i < form.city.length; i++) {
        if (form.city[i].checked)
            city += " " + form.city[i].value;
    }
    var str = "mailto:[email protected]?subject=travel to morocco&body=";
    if (name.length > 0) {
        str += "Hi my name is " + name + ", ";
    } else {
        warning += "Name is required"
    }
    if (city.length > 0) {
        str += "I am Intersted in visiting the following citis: " + city + ", ";
    }
    if (activities.length > 0) {
        str += "I am Intersted in following activities: " + activities + ". "
    }
    if (adate.length > 0) {
        str += "I will be ariving on " + adate;
    }
    if (ddate.length > 0) {
        str += " And departing on " + ddate;
    }
    if (adult.length > 0) {
        if (adult == 1 && child == null) {
            str += ". I will be travelling alone"
        } else if (adult > 1) {
            str += ".We will have a group of " + adult + " adults ";
        }
        if (child == null) {
            str += ".";
        } else if (child > 1) {
            str += "along with " + child + " children.";
        } else if (child == 1) {
            str += "along with a child.";
        }
    }

    if (comment.length > 0) {
        str += "%0D%0A" + comment + "."
    }

    if (warning.length > 0) {
        alert(warning)
    } else {
        str += "%0D%0ARegards,%0D%0A" + name;
        document.getElementById('send').href = str;
    }
}

How to render a DateTime in a specific format in ASP.NET MVC 3?

Had the same problem recently.

I discovered that simply defining DataType as Date in the model works as well (using Code First approach)

[DataType(DataType.Date)]
public DateTime Added { get; set; }

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

An alternate solution uses the following class/interface. It's not truly dynamic, but it works.

public interface IID
{
    int ID
    {
        get; set;
    }
}

public static class Utils
{
    public static int GetID<T>(ObjectQuery<T> items) where T:EntityObject, IID
    {
        if (items.Count() == 0) return 1;
        return items.OrderByDescending(u => u.ID).FirstOrDefault().ID + 1;
    }
}

What are the rules about using an underscore in a C++ identifier?

From MSDN:

Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers.

This means that you can use a single underscore as a member variable prefix, as long as it's followed by a lower-case letter.

This is apparently taken from section 17.4.3.1.2 of the C++ standard, but I can't find an original source for the full standard online.

See also this question.

How to update values using pymongo?

You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child values.

If p is the object retrieved:

existing = p['d']['a']

For pymongo versions < 3.0

db.ProductData.update({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False)

However if you just need to increment the value, this approach could introduce issues when multiple requests could be running concurrently. Instead you should use the $inc syntax:

For pymongo versions < 3.0:

db.ProductData.update({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0:

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False)

This ensures your increments will always happen.

Location Services not working in iOS 8

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc] init];
    
    self.locationManager.delegate = self;
    if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]){
        NSUInteger code = [CLLocationManager authorizationStatus];
        if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) {
            // choose one request according to your business.
            if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){
                [self.locationManager requestAlwaysAuthorization];
            } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
                [self.locationManager  requestWhenInUseAuthorization];
            } else {
                NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
            }
        }
    }
    [self.locationManager startUpdatingLocation];
}

>  #pragma mark - CLLocationManagerDelegate

    - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
    {
        NSLog(@"didFailWithError: %@", error);
        UIAlertView *errorAlert = [[UIAlertView alloc]
                                   initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [errorAlert show];
    }
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
    {
        NSLog(@"didUpdateToLocation: %@", newLocation);
        CLLocation *currentLocation = newLocation;
        
        if (currentLocation != nil) {
            longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
            latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
        }
    }

In iOS 8 you need to do two extra things to get location working: Add a key to your Info.plist and request authorization from the location manager asking it to start. There are two Info.plist keys for the new location authorization. One or both of these keys is required. If neither of the keys are there, you can call startUpdatingLocation but the location manager won’t actually start. It won’t send a failure message to the delegate either (since it never started, it can’t fail). It will also fail if you add one or both of the keys but forget to explicitly request authorization. So the first thing you need to do is to add one or both of the following keys to your Info.plist file:

  • NSLocationWhenInUseUsageDescription
  • NSLocationAlwaysUsageDescription

Both of these keys take a string

which is a description of why you need location services. You can enter a string like “Location is required to find out where you are” which, as in iOS 7, can be localized in the InfoPlist.strings file.

enter image description here

Create a Date with a set timezone without using a string representation

This may help someone, put UTC at the end of what you pass in to the new constructor

At least in chrome you can say var date = new Date("2014-01-01 11:00:00 UTC")

What is the difference between a "function" and a "procedure"?

In the context of db: Stored procedure is precompiled execution plan where as functions are not.

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

for visual studio 2019 need change MSBuild path

npm config set msvs_version 2017

npm config set msbuild_path "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MSBuild.exe"

npm rebuild node-sass

Number prime test in JavaScript

Simple version:

function isPrime(num) {
    if (num <= 1) { 
        return false;
    } else {
        for (var i = 2; i < num; i++) {
            if (num % i === 0) {
                return false; 
            }
        }
        return true;
    }  
}

console.log(isPrime(9));

How do I programmatically set device orientation in iOS 7?

For those like me who struggled to get @Sunny Shah accepted answer to work on iPads. You need to set the "Requires full screen" checkbox on in the project settings. Note that this will prevent your app from working on multitasking mode which may or not be acceptable.

enter image description here

Can I set state inside a useEffect hook

For future purposes, this may help too:

It's ok to use setState in useEffect you just need to have attention as described already to not create a loop.

But it's not the only problem that may occur. See below:

Imagine that you have a component Comp that receives props from parent and according to a props change you want to set Comp's state. For some reason, you need to change for each prop in a different useEffect:

DO NOT DO THIS

useEffect(() => {
  setState({ ...state, a: props.a });
}, [props.a]);

useEffect(() => {
  setState({ ...state, b: props.b });
}, [props.b]);

It may never change the state of a as you can see in this example: https://codesandbox.io/s/confident-lederberg-dtx7w

The reason why this happen in this example it's because both useEffects run in the same react cycle when you change both prop.a and prop.b so the value of {...state} when you do setState are exactly the same in both useEffect because they are in the same context. When you run the second setState it will replace the first setState.

DO THIS INSTEAD

The solution for this problem is basically call setState like this:

useEffect(() => {
  setState(state => ({ ...state, a: props.a }));
}, [props.a]);

useEffect(() => {
  setState(state => ({ ...state, b: props.b }));
}, [props.b]);

Check the solution here: https://codesandbox.io/s/mutable-surf-nynlx

Now, you always receive the most updated and correct value of the state when you proceed with the setState.

I hope this helps someone!

Is there a typescript List<> and/or Map<> class/library?

Did they add a runtime List<> and/or Map<> type class to typepad 1.0

No, providing a runtime is not the focus of the TypeScript team.

is there a solid library out there someone wrote that provides this functionality?

I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections

Update

JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts : https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want

Setting state on componentDidMount()

According to the React Documentation it's perfectly OK to call setState() from within the componentDidMount() function.

It will cause render() to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.

You can find the documentation here:

https://reactjs.org/docs/react-component.html#componentdidmount

Here is the excerpt from the documentation:

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Be aware to use constant HTTPS or HTTP for all requests. I had the same error msg: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

How to pass all arguments passed to my bash script to a function of mine?

The $@ variable expands to all command-line parameters separated by spaces. Here is an example.

abc "$@"

When using $@, you should (almost) always put it in double-quotes to avoid misparsing of arguments containing spaces or wildcards (see below). This works for multiple arguments. It is also portable to all POSIX-compliant shells.

It is also worth nothing that $0 (generally the script's name or path) is not in $@.

The Bash Reference Manual Special Parameters Section says that $@ expands to the positional parameters starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is "$@" is equivalent to "$1" "$2" "$3"....

Passing some arguments:

If you want to pass all but the first arguments, you can first use shift to "consume" the first argument and then pass "$@" to pass the remaining arguments to another command. In bash (and zsh and ksh, but not in plain POSIX shells like dash), you can do this without messing with the argument list using a variant of array slicing: "${@:3}" will get you the arguments starting with "$3". "${@:3:4}" will get you up to four arguments starting at "$3" (i.e. "$3" "$4" "$5" "$6"), if that many arguments were passed.

Things you probably don't want to do:

"$*" gives all of the arguments stuck together into a single string (separated by spaces, or whatever the first character of $IFS is). This looses the distinction between spaces within arguments and the spaces between arguments, so is generally a bad idea. Although it might be ok for printing the arguments, e.g. echo "$*", provided you don't care about preserving the space within/between distinction.

Assigning the arguments to a regular variable (as in args="$@") mashes all the arguments together just like "$*" does. If you want to store the arguments in a variable, use an array with args=("$@") (the parentheses make it an array), and then reference them as e.g. "${args[0]}" etc (note that bash array indexes start at 0, so $1 will be in args[0], etc).

Leaving off the double-quotes, with either $@ or $*, will try to split each argument up into separate words (based on whitespace or whatever's in $IFS), and also try to expand anything that looks like a filename wildcard into a list of matching filenames. This can have really weird effects, and should almost always be avoided.

How to drop a table if it exists?

Have seen so many that don't really work. when a temp table is created it must be deleted from the tempdb!

The only code that works is:

IF OBJECT_ID('tempdb..#tempdbname') IS NOT NULL     --Remove dbo here 
    DROP TABLE #tempdbname   -- Remoeve "tempdb.dbo"

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

When an Abstract Class Implements an Interface

In the section on Interfaces, it was noted that a class that implements an interface must implement all of the interface's methods. It is possible, however, to define a class that does not implement all of the interface's methods, provided that the class is declared to be abstract. For example,

abstract class X implements Y {   
    // implements all but one method of Y
}

class XX extends X {   
    // implements the remaining method in Y 
} 

In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact, implement Y.

Reference: http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

How do you specify the Java compiler version in a pom.xml file?

maven-compiler-plugin it's already present in plugins hierarchy dependency in pom.xml. Check in Effective POM.

For short you can use properties like this:

<properties>
   <maven.compiler.source>1.8</maven.compiler.source>
   <maven.compiler.target>1.8</maven.compiler.target>
</properties>

I'm using Maven 3.2.5.

Change icons of checked and unchecked for Checkbox for Android

it's android:button="@drawable/selector_checkbox" to make it work

Java 8 lambda Void argument

I don't think it is possible, because function definitions do not match in your example.

Your lambda expression is evaluated exactly as

void action() { }

whereas your declaration looks like

Void action(Void v) {
    //must return Void type.
}

as an example, if you have following interface

public interface VoidInterface {
    public Void action(Void v);
}

the only kind of function (while instantiating) that will be compatibile looks like

new VoidInterface() {
    public Void action(Void v) {
        //do something
        return v;
    }
}

and either lack of return statement or argument will give you a compiler error.

Therefore, if you declare a function which takes an argument and returns one, I think it is impossible to convert it to function which does neither of mentioned above.

Where to place the 'assets' folder in Android Studio?

If you tried all your bullets in this thread in vain try cleaning your project . In my case it only worked after Projet -> clean

Simplest Way to Test ODBC on WIndows

a simple way is:

create a fake "*.UDL" file on desktop

(UDL files are described here: https://msdn.microsoft.com/en-us/library/e38h511e(v=vs.71).aspx.

in case you can also customized it as explained there. )

Where does Vagrant download its .box files to?

The actual .box file is deleted by Vagrant once the download and box installation is complete. As mentioned in other answers, whilst downloading, the .box file is stored as:

~/.vagrant.d/tmp/boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

where the file name is 'box' followed by a 40 byte hexadecimal hash. A temporary file on my system for example, is:

~/.vagrant.d/tmp/boxc74a85fe4af3197a744851517c6af4d4959db77f

As far as I can tell, this file is never saved with a *.box extension, which explains why the searches above failed to locate it. There are two ways to retrieve the actual box file:

  1. Download the .box file from vagrantcloud.com

    1. Find the box you're interested in on the atlas. For example, https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1
    2. Replace the domain name with vagrantcloud.com. So https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1 becomes https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box.
    3. Add /providers/virtualbox.box to the end of that URL. So https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1 becomes https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box
    4. Save the .box file
    5. Use the .box as you wish, for example, hosting it yourself and pointing config.vm.box_url to the URL. OR
  2. Get the .box directly from Vagrant

    This requires you to modify the ruby source to prevent Vagrant from deleting the box after successful download.

    1. Locate the box_add.rb file in your Vagrant installation directory. On my system it's located at /Applications/Vagrant/embedded/gems/gems/vagrant-1.5.2/lib/vagrant/action/builtin/box_add.rb
    2. Find the box_add function. Within the box_add function, there is a block that reads:

      ensure # Make sure we delete the temporary file after we add it, # unless we were interrupted, in which case we keep it around # so we can resume the download later. if !@download_interrupted @logger.debug("Deleting temporary box: #{box_url}") begin box_url.delete if box_url rescue Errno::ENOENT # Not a big deal, the temp file may not actually exist end end

    3. Comment this block out.
    4. Add another box using vagrant add box <boxname>.
    5. Wait for it to download. You can watch it save in the ~/.vagrant.d/tmp/ directory as a boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX file.
    6. Rename the the file to something more useful. Eg, mv boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX trusty64.box.

Why would you want this?

For me, this has been useful to retrieve the .box file so it can be hosted on local, fast infrastructure as opposed to downloading from HashiCorp's Atlas box catalog or another box provider.

This really should be part of the default Vagrant functionality as it has a very definitive use case.

Is jQuery $.browser Deprecated?

Second Question

Will my existing implementations continue to work? If not, is there an easy to implement alternative.

The answer is yes, but not without a little work.

$.browser is an official plugin which was included in older versions of jQuery, so like any plugin you can simple copy it and incorporate it into your project or you can simply add it to the end of any jQuery release.

I have extracted the code for you incase you wish to use it.


// Limit scope pollution from any deprecated API
(function() {

    var matched, browser;

// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
    jQuery.uaMatch = function( ua ) {
        ua = ua.toLowerCase();

        var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
            /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
            /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
            /(msie) ([\w.]+)/.exec( ua ) ||
            ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
            [];

        return {
            browser: match[ 1 ] || "",
            version: match[ 2 ] || "0"
        };
    };

    matched = jQuery.uaMatch( navigator.userAgent );
    browser = {};

    if ( matched.browser ) {
        browser[ matched.browser ] = true;
        browser.version = matched.version;
    }

// Chrome is Webkit, but Webkit is also Safari.
    if ( browser.chrome ) {
        browser.webkit = true;
    } else if ( browser.webkit ) {
        browser.safari = true;
    }

    jQuery.browser = browser;

    jQuery.sub = function() {
        function jQuerySub( selector, context ) {
            return new jQuerySub.fn.init( selector, context );
        }
        jQuery.extend( true, jQuerySub, this );
        jQuerySub.superclass = this;
        jQuerySub.fn = jQuerySub.prototype = this();
        jQuerySub.fn.constructor = jQuerySub;
        jQuerySub.sub = this.sub;
        jQuerySub.fn.init = function init( selector, context ) {
            if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
                context = jQuerySub( context );
            }

            return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
        };
        jQuerySub.fn.init.prototype = jQuerySub.fn;
        var rootjQuerySub = jQuerySub(document);
        return jQuerySub;
    };

})();

If you're asking why anyone would need a depreciated plugin, I have prepared the following answer.

First and foremost the answer is compatibility. Since jQuery is plugin based, some developers opted to use $.browser and with the latest releases of jQuery which doesn't include $.browser all those plugins where rendered useless.

jQuery did release a migration plugin, which was created for developers to detect whether their plugin's used any depreciated dependencies such as $.browser.

Although this helped developers patch their plugin's. jQuery dropped $.browser completely so the above fix is probably the only solution until your developers patch or incorporate the above.

About: jQuery.browser

Matplotlib legends in subplot

This does what you want and overcomes some of the problems in other answers:

import matplotlib.pyplot as plt

labels = ["HHZ 1", "HHN", "HHE"]
colors = ["r","g","b"]

f,axs = plt.subplots(3, sharex=True, sharey=True)

# ---- loop over axes ----
for i,ax in enumerate(axs):
  axs[i].plot([0,1],[1,0],color=colors[i],label=labels[i])
  axs[i].legend(loc="upper right")

plt.show()

... produces ... subplots

Why must wait() always be in synchronized block

directly from this java oracle tutorial:

When a thread invokes d.wait, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock.

php & mysql query not echoing in html with tags?

I can spot a few different problems with this. However, in the interest of time, try this chunk of code instead:

<?php require 'db.php'; ?>  <?php if (isset($_POST['search'])) {     $limit = $_POST['limit'];     $country = $_POST['country'];     $state = $_POST['state'];     $city = $_POST['city'];     $data = mysqli_query(         $link,         "SELECT * FROM proxies WHERE country = '{$country}' AND state = '{$state}' AND city = '{$city}' LIMIT {$limit}"     );     while ($assoc = mysqli_fetch_assoc($data)) {         $proxy = $assoc['proxy'];         ?>             <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"                 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">             <html xmlns="http://www.w3.org/1999/xhtml">                 <head>                     <title>Sock5Proxies</title>                     <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />                     <link href="./style.css" rel="stylesheet" type="text/css" />                     <link href="./buttons.css" rel="stylesheet" type="text/css" />                 </head>                 <body>                     <center>                         <h1>Sock5Proxies</h1>                     </center>                     <div id="wrapper">                         <div id="header">                             <ul id="nav">                                 <li class="active"><a href="index.html"><span></span>Home</a></li>                                 <li><a href="leads.html"><span></span>Leads</a></li>                                 <li><a href="payout.php"><span></span>Pay out</a></li>                                 <li><a href="contact.html"><span></span>Contact</a></li>                                 <li><a href="logout.php"><span></span>Logout</a></li>                             </ul>                         </div>                         <div id="content">                             <div id="center">                                 <table cellpadding="0" cellspacing="0" style="width:690px">                                     <thead>                                     <tr>                                         <th width="75" class="first">Proxy</th>                                         <th width="50" class="last">Status</th>                                     </tr>                                     </thead>                                     <tbody>                                     <tr class="rowB">                                         <td class="first"> <?php echo $proxy ?> </td>                                         <td class="last">Check</td>                                     </tr>                                     </tbody>                                 </table>                             </div>                         </div>                         <div id="footer"></div>                         <span id="about">Version 1.0</span>                     </div>                 </body>             </html>         <?php     } } ?> <html> <form action="" method="POST">     <input type="text" name="limit" placeholder="10" /><br>     <input type="text" name="country" placeholder="Country" /><br>     <input type="text" name="state" placeholder="State" /><br>     <input type="text" name="city" placeholder="City" /><br>     <input type="submit" name="search" value="Search" /><br> </form> </html> 

Set The Window Position of an application via command line

This probably should be a comment under the cmdow.exe answer, but here is a simple batch file I wrote to allow for fairly sophisticated and simple control over all windows that you can see in the taskbar.

First step is to run cmdow /t to display a list of those windows. Look at what the image name is in the column Image, then command line:

mycmdowscript.cmd imagename

Here are the contents of the batch file:

:: mycmdowscript.cmd

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET IMAGE=%1
SET ACTION=/%2
SET REST=1
SET PARAMS=

:: GET ANY ADDITIONAL PARAMS AND STORE THEM IN A VARIABLE

FOR %%I in (%*) DO (
   IF !REST! geq 3 (
      SET PARAMS=!PARAMS! %%I
   )
   SET /A REST+=1
)

FOR /F "USEBACKQ tokens=1,8" %%I IN (`CMDOW /t`) DO (
     IF %IMAGE%==%%J (

     :: you now have access to the handle in %%I
     cmdow %%I %ACTION% !PARAMS!

     )
)

ENDLOCAL
@echo on

EXIT /b

example usage

:: will set notepad to 500 500

mycmdowscript.cmd notepad siz 500 500

You could probably rewrite this to allow for multiple actions on a single command, but I haven't tried yet.

For this to work, cmdow.exe must be located in your path. Beware that when you download this, your AV program might yell at you. This tool has (I guess) in the past been used by malware authors to manipulate windows. It is not harmful by itself.

How to change values in a tuple?

You can change the value of tuple using copy by reference

>>> tuple1=[20,30,40]

>>> tuple2=tuple1

>>> tuple2
    [20, 30, 40]

>>> tuple2[1]=10

>>> print(tuple2)
    [20, 10, 40]

>>> print(tuple1)
    [20, 10, 40]

Convert LocalDateTime to LocalDateTime in UTC

Question?

Looking at the answers and the question, it seems the question has been modified significantly. So to answer the current question:

Convert LocalDateTime to LocalDateTime in UTC.

Timezone?

LocalDateTime does not store any information about the time-zone, it just basically holds the values of year, month, day, hour, minute, second, and smaller units. So an important question is: What is the timezone of the original LocalDateTime? It might as well be UTC already, therefore no conversion has to be made.

System Default Timezone

Considering that you asked the question anyway, you probably meant that the original time is in your system-default timezone and you want to convert it to UTC. Because usually a LocalDateTime object is created by using LocalDateTime.now() which returns the current time in the system-default timezone. In this case, the conversion would be the following:

LocalDateTime convertToUtc(LocalDateTime time) {
    return time.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

An example of the conversion process:

2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+1 // [atZone] converted to ZonedDateTime (system timezone is Madrid)
2019-02-25 10:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 10:39 // [toLocalDateTime] losing the timezone information

Explicit Timezone

In any other case, when you explicitly specify the timezone of the time to convert, the conversion would be the following:

LocalDateTime convertToUtc(LocalDateTime time, ZoneId zone) {
    return time.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

An example of the conversion process:

2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+2 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2019-02-25 09:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 09:39 // [toLocalDateTime] losing the timezone information

The atZone() Method

The result of the atZone() method depends on the time passed as its argument, because it considers all the rules of the timezone, including Daylight Saving Time (DST). In the examples, the time was 25th February, in Europe this means winter time (no DST).

If we were to use a different date, let's say 25th August from last year, the result would be different, considering DST:

2018-08-25 11:39 // [time] original LocalDateTime without a timezone
2018-08-25 11:39 GMT+3 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2018-08-25 08:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2018-08-25 08:39 // [toLocalDateTime] losing the timezone information

The GMT time does not change. Therefore the offsets in the other timezones are adjusted. In this example, the summer time of Estonia is GMT+3, and winter time GMT+2.

Also, if you specify a time within the transition of changing clocks back one hour. E.g. October 28th, 2018 03:30 for Estonia, this can mean two different times:

2018-10-28 03:30 GMT+3 // summer time [UTC 2018-10-28 00:30]
2018-10-28 04:00 GMT+3 // clocks are turned back 1 hour [UTC 2018-10-28 01:00]
2018-10-28 03:00 GMT+2 // same as above [UTC 2018-10-28 01:00]
2018-10-28 03:30 GMT+2 // winter time [UTC 2018-10-28 01:30]

Without specifying the offset manually (GMT+2 or GMT+3), the time 03:30 for the timezone Europe/Tallinn can mean two different UTC times, and two different offsets.

Summary

As you can see, the end result depends on the timezone of the time passed as an argument. Because the timezone cannot be extracted from the LocalDateTime object, you have to know yourself which timezone it is coming from in order to convert it to UTC.

How to change to an older version of Node.js

nvmw is no longer maintained, but I found another source that seems to be up to date (as of 1/4/17).

nvm-windows

It works. Allowed me to downgrade to 6.3.1

How to handle screen orientation change when progress dialog and background thread active?

I've tried EVERYTHING. Spent days experimenting. I didn't want to block the activity from rotating. My scenario was:

  1. A progress dialog showing dynamic information to the user. E.g.: "Connecting to server...", "Downloading data...", etc.
  2. A thread doing the heavy stuff and updating the dialog
  3. Updating the UI with the results at the end.

The problem was, when rotating the screen, every solution on the book failed. Even with the AsyncTask class, which is the correct Android way of dealing with this situations. When rotating the screen, the current Context that the starting thread is working with, is gone, and that messes up with the dialog that is showing. The problem was always the Dialog, no matter how many tricks I added to the code (passing new contexts to running threads, retaining thread states through rotations, etc...). The code complexity at the end was always huge and there was always something that could go wrong.

The only solution that worked for me was the Activity/Dialog trick. It's simple and genius and it's all rotation proof:

  1. Instead of creating a Dialog and ask to show it, create an Activity that has been set in the manifest with android:theme="@android:style/Theme.Dialog". So, it just looks like a dialog.

  2. Replace showDialog(DIALOG_ID) with startActivityForResult(yourActivityDialog, yourCode);

  3. Use onActivityResult in the calling Activity to get the results from the executing thread (even the errors) and update the UI.

  4. On your 'ActivityDialog', use threads or AsyncTask to execute long tasks and onRetainNonConfigurationInstance to save "dialog" state when rotating the screen.

This is fast and works fine. I still use dialogs for other tasks and the AsyncTask for something that doesn't require a constant dialog on screen. But with this scenario, I always go for the Activity/Dialog pattern.

And, I didn't try it, but it's even possible to block that Activity/Dialog from rotating, when the thread is running, speeding things up, while allowing the calling Activity to rotate.

Using two values for one switch case statement

Just do

case text1: case text4: 
     do stuff;
     break;

REST vs JSON-RPC?

I've been a big fan of REST in the past and it has many advantages over RPC on paper. You can present the client with different Content-Types, Caching, reuse of HTTP status codes, you can guide the client through the API and you can embed documentation in the API if it isn't mostly self-explaining anyway.

But my experience has been that in practice this doesn't hold up and instead you do a lot of unnecessary work to get everything right. Also the HTTP status codes often don't map to your domain logic exactly and using them in your context often feels a bit forced. But the worst thing about REST in my opinion is that you spend a lot of time to design your resources and the interactions they allow. And whenever you do some major additions to your API you hope you find a good solution to add the new functionality and you didn't design yourself into a corner already.

This often feels like a waste of time to me because most of the time I already have a perfectly fine and obvious idea about how to model an API as a set of remote procedure calls. And if I have gone through all this effort to model my problem inside the constraints of REST the next problem is how to call it from the client? Our programs are based on calling procedures so building a good RPC client library is easy, building a good REST client library not so much and in most cases you will just map back from your REST API on the server to a set of procedures in your client library.

Because of this, RPC feels a lot simpler and more natural to me today. What I really miss though is a consistent framework that makes it easy to write RPC services that are self-describing and interoperable. Therefore I created my own project to experiment with new ways to make RPC easier for myself and maybe somebody else finds it useful, too: https://github.com/aheck/reflectrpc

How to set CATALINA_HOME variable in windows 7?

There is no requirement of setting CATALINA-HOME.

Follow below instruction .

Right click on computer --> properties --> Advanced system setting --> Environment variables.

User variables section --> click on "New" --> variable name : CLASSPATH , variable value : D:\java\lib*.;D:\tomcat8\lib\servlet-api.jar.; --> Click "Ok"

New --> variable name : PATH , variable value : D:\java\bin; --> Click "Ok"

System variables section:-

Click on "New" --> variable name : PATH , variable value : D:\java\jre --> Click "Ok"

I've installed java and tomcat in D drive henceforth the locations above are under my respective paths.

Give location paths where java and tomcat are installed in your PC. Thank You

Why use HttpClient for Synchronous Connection

In my case the accepted answer did not work. I was calling the API from an MVC application which had no async actions.

This is how I managed to make it work:

private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static T RunSync<T>(Func<Task<T>> func)
    {           
        CultureInfo cultureUi = CultureInfo.CurrentUICulture;
        CultureInfo culture = CultureInfo.CurrentCulture;
        return _myTaskFactory.StartNew<Task<T>>(delegate
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = cultureUi;
            return func();
        }).Unwrap<T>().GetAwaiter().GetResult();
    }

Then I called it like this:

Helper.RunSync(new Func<Task<ReturnTypeGoesHere>>(async () => await AsyncCallGoesHere(myparameter)));

How can I detect keydown or keypress event in angular.js?

You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress (also Enter key, backspace key, alter key ,control key)

<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>

Link entire table row?

I feel like the simplest solution is sans javascript and simply putting the link in each cell (provided you don't have massive gullies between your cells or really think border lines). Have your css:

.tableClass td a{
   display: block;
}

and then add a link per cell:

<table class="tableClass">
    <tr>
        <td><a href="#link">Link name</a></td>
        <td><a href="#link">Link description</a></td>
        <td><a href="#link">Link somthing else</a></td>
    </tr>
</table>

boring but clean.

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

I have resolved it by adding below line in my context:

modelBuilder.Entity<YourObject>().Property(e => e.YourColumn).HasMaxLength(4000);

Somehow, [MaxLength] didn't work for me.

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

I used JUG (Java UUID Generator) to generate unique ID. It is unique across JVMs. Pretty good to use. Here is the code for your reference:

private static final SecureRandom secureRandom = new SecureRandom();
private static final UUIDGenerator generator = UUIDGenerator.getInstance();

public synchronized static String generateUniqueId() {
  UUID uuid = generator.generateRandomBasedUUID(secureRandom);

  return uuid.toString().replaceAll("-", "").toUpperCase();
}

You could download the library from: https://github.com/cowtowncoder/java-uuid-generator

How can I use a custom font in Java?

If you include a font file (otf, ttf, etc.) in your package, you can use the font in your application via the method described here:

Oracle Java SE 6: java.awt.Font

There is a tutorial available from Oracle that shows this example:

try {
     GraphicsEnvironment ge = 
         GraphicsEnvironment.getLocalGraphicsEnvironment();
     ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
     //Handle exception
}

I would probably wrap this up in some sort of resource loader though as to not reload the file from the package every time you want to use it.

An answer more closely related to your original question would be to install the font as part of your application's installation process. That process will depend on the installation method you choose. If it's not a desktop app you'll have to look into the links provided.

jQuery Set Select Index

Even simpler:

$('#selectBox option')[3].selected = true;

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

I had a very similar problem. The goal was to mock a service that persists Objects and can return them by their name. The service looks like this:

public class RoomService {
    public Room findByName(String roomName) {...}
    public void persist(Room room) {...}
}

The service mock uses a map to store the Room instances.

RoomService roomService = mock(RoomService.class);
final Map<String, Room> roomMap = new HashMap<String, Room>();

// mock for method persist
doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            Room room = (Room) arguments[0];
            roomMap.put(room.getName(), room);
        }
        return null;
    }
}).when(roomService).persist(any(Room.class));

// mock for method findByName
when(roomService.findByName(anyString())).thenAnswer(new Answer<Room>() {
    @Override
    public Room answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            String key = (String) arguments[0];
            if (roomMap.containsKey(key)) {
                return roomMap.get(key);
            }
        }
        return null;
    }
});

We can now run our tests on this mock. For example:

String name = "room";
Room room = new Room(name);
roomService.persist(room);
assertThat(roomService.findByName(name), equalTo(room));
assertNull(roomService.findByName("none"));

How to get the hours difference between two date objects?

The simplest way would be to directly subtract the date objects from one another.

For example:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

Docker: Multiple Dockerfiles in project

In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax.

Send multipart/form-data files with angular using $http

Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.

Angular 5 Solution:

import {HttpClient} from '@angular/common/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = {} as any; // Set any options you like
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.httpClient.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

Angular 4 Solution:

// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';

uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
  // Note that setting a content-type header
  // for mutlipart forms breaks some built in
  // request parsers like multer in express.
  const options = new RequestOptions();
  const formData = new FormData();

  // Append files to the virtual form.
  for (const file of files) {
    formData.append(file.name, file)
  }

  // Optional, append other kev:val rest data to the form.
  Object.keys(restObj).forEach(key => {
    formData.append(key, restObj[key]);
  });

  // Send it.
  return this.http.post(uploadUrl, formData, options)
    .toPromise()
    .catch((e) => {
      // handle me
    });
}

AngularJS ng-if with multiple conditions

you can also try with && for mandatory constion if both condtion are true than work

//div ng-repeat="(k,v) in items"

<div ng-if="(k == 'a' &&  k == 'b')">
    <!-- SOME CONTENT -->
</div>

Is there a way to provide named parameters in a function call in JavaScript?

Coming from Python this bugged me. I wrote a simple wrapper/Proxy for node that will accept both positional and keyword objects.

https://github.com/vinces1979/node-def/blob/master/README.md

Open a facebook link by native Facebook app on iOS

If the Facebook application is logged in, the page will be opened when executing the following code. If the Facebook application is not logged in when executing the code, the user will then be redirected to the Facebook app to login and then after connecting the Facebook is not redirected to the page!

NSURL *fbNativeAppURL = [NSURL URLWithString:@"fb://page/yourPageIDHere"] [[UIApplication sharedApplication] openURL:fbNativeAppURL]

Generating a Random Number between 1 and 10 Java

The standard way to do this is as follows:

Provide:

  • min Minimum value
  • max Maximum value

and get in return a Integer between min and max, inclusive.

Random rand = new Random();

// nextInt as provided by Random is exclusive of the top value so you need to add 1 

int randomNum = rand.nextInt((max - min) + 1) + min;

See the relevant JavaDoc.

As explained by Aurund, Random objects created within a short time of each other will tend to produce similar output, so it would be a good idea to keep the created Random object as a field, rather than in a method.

Java, How to specify absolute value and square roots

Use the static methods in the Math class for both - there are no operators for this in the language:

double root = Math.sqrt(value);
double absolute = Math.abs(value);

(Likewise there's no operator for raising a value to a particular power - use Math.pow for that.)

If you use these a lot, you might want to use static imports to make your code more readable:

import static java.lang.Math.sqrt;
import static java.lang.Math.abs;

...

double x = sqrt(abs(x) + abs(y));

instead of

double x = Math.sqrt(Math.abs(x) + Math.abs(y));

How do I close an open port from the terminal on the Mac?

very simple find port 5900:

sudo lsof -i :5900

then considering 59553 as PID

sudo kill 59553

Removing html5 required attribute with jQuery

_x000D_
_x000D_
$('#id').removeAttr('required');?????
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

@synthesize vs @dynamic, what are the differences?

@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass or will be provided at runtime).

Uses for @dynamic are e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet.

@dynamic also can be used to delegate the responsibility of implementing the accessors. If you implement the accessors yourself within the class then you normally do not use @dynamic.

Super class:

@property (nonatomic, retain) NSButton *someButton;
...
@synthesize someButton;

Subclass:

@property (nonatomic, retain) IBOutlet NSButton *someButton;
...
@dynamic someButton;

What's the difference between select_related and prefetch_related in Django ORM?

As Django documentation says:

prefetch_related()

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

More information about this: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-related

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

To install the prerequisites for GPU support in TensorFlow 2.1:

  1. Install your latest GPU drivers.
  2. Install CUDA 10.1.
    • If the CUDA installer reports "you are installing an older driver version", you may wish to choose a custom installation and deselect some components. Indeed, note that software bundled with CUDA including GeForce Experience, PhysX, a Display Driver, and Visual Studio integration are not required by TensorFlow.
    • Also note that TensorFlow requires a specific version of the CUDA Toolkit unless you build from source; for TensorFlow 2.1 and 2.2, this is currently version 10.1.
  3. Install cuDNN.
    1. Download cuDNN v7.6.4 for CUDA 10.1. This will require you to sign up to the NVIDIA Developer Program.
    2. Unzip to a suitable location and add the bin directory to your PATH.
  4. Install tensorflow by pip install tensorflow.
  5. You may need to restart your PC.

Where can I download english dictionary database in a text format?

Check if these free resources fit your need -

When to use EntityManager.find() vs EntityManager.getReference() with JPA

I usually use getReference method when i do not need to access database state (I mean getter method). Just to change state (I mean setter method). As you should know, getReference returns a proxy object which uses a powerful feature called automatic dirty checking. Suppose the following

public class Person {

    private String name;
    private Integer age;

}


public class PersonServiceImpl implements PersonService {

    public void changeAge(Integer personId, Integer newAge) {
        Person person = em.getReference(Person.class, personId);

        // person is a proxy
        person.setAge(newAge);
    }

}

If i call find method, JPA provider, behind the scenes, will call

SELECT NAME, AGE FROM PERSON WHERE PERSON_ID = ?

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

If i call getReference method, JPA provider, behind the scenes, will call

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

And you know why ???

When you call getReference, you will get a proxy object. Something like this one (JPA provider takes care of implementing this proxy)

public class PersonProxy {

    // JPA provider sets up this field when you call getReference
    private Integer personId;

    private String query = "UPDATE PERSON SET ";

    private boolean stateChanged = false;

    public void setAge(Integer newAge) {
        stateChanged = true;

        query += query + "AGE = " + newAge;
    }

}

So before transaction commit, JPA provider will see stateChanged flag in order to update OR NOT person entity. If no rows is updated after update statement, JPA provider will throw EntityNotFoundException according to JPA specification.

regards,

Using Chrome, how to find to which events are bound to an element

For Chrome Version 52.0.2743.116:

  1. In Chrome's Developer Tools, bring up the 'Search' panel by hitting Ctrl+Shift+F.

  2. Type in the name of the element you're trying to find.

Results for binded elements should appear in the panel and state the file they're located in.

How to add conditional attribute in Angular 2?

If it's an input element you can write something like.... <input type="radio" [checked]="condition"> The value of condition must be true or false.

Also for style attributes... <h4 [style.color]="'red'">Some text</h4>

Are dictionaries ordered in Python 3.6+?

I wanted to add to the discussion above but don't have the reputation to comment.

Python 3.8 is not quite released yet, but it will even include the reversed() function on dictionaries (removing another difference from OrderedDict.

Dict and dictviews are now iterable in reversed insertion order using reversed(). (Contributed by Rémi Lapeyre in bpo-33462.) See what's new in python 3.8

I don't see any mention of the equality operator or other features of OrderedDict so they are still not entirely the same.

What is the difference between parseInt(string) and Number(string) in JavaScript?

parseInt("123qwe")

returns 123

Number("123qwe")

returns NaN

In other words parseInt() parses up to the first non-digit and returns whatever it had parsed. Number() wants to convert the entire string into a number, which can also be a float BTW.


EDIT #1: Lucero commented about the radix that can be used along with parseInt(). As far as that is concerned, please see THE DOCTOR's answer below (I'm not going to copy that here, the doc shall have a fair share of the fame...).


EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number() in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat() aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui") also returns NaN). And the biggest difference is the use of radix that Number() doesn't know of and parseInt() may indirectly guess from the given string (that can cause weird results sometimes).

How to sort a data frame by alphabetic order of a character variable in R?

The arrange function in the plyr package makes it easy to sort by multiple columns. For example, to sort DF by ID first and then decreasing by num, you can write

plyr::arrange(DF, ID, desc(num))

How to parse/read a YAML file into a Python object?

From http://pyyaml.org/wiki/PyYAMLDocumentation:

add_path_resolver(tag, path, kind) adds a path-based implicit tag resolver. A path is a list of keys that form a path to a node in the representation graph. Paths elements can be string values, integers, or None. The kind of a node can be str, list, dict, or None.

#!/usr/bin/env python
import yaml

class Person(yaml.YAMLObject):
  yaml_tag = '!person'

  def __init__(self, name):
    self.name = name

yaml.add_path_resolver('!person', ['Person'], dict)

data = yaml.load("""
Person:
  name: XYZ
""")

print data
# {'Person': <__main__.Person object at 0x7f2b251ceb10>}

print data['Person'].name
# XYZ

Whats the CSS to make something go to the next line in the page?

There are two options that I can think of, but without more details, I can't be sure which is the better:

#elementId {
    display: block;
}

This will force the element to a 'new line' if it's not on the same line as a floated element.

#elementId {
     clear: both;
}

This will force the element to clear the floats, and move to a 'new line.'

In the case of the element being on the same line as another that has position of fixed or absolute nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.

OWIN Security - How to Implement OAuth2 Refresh Tokens

Just implemented my OWIN Service with Bearer (called access_token in the following) and Refresh Tokens. My insight into this is that you can use different flows. So it depends on the flow you want to use how you set your access_token and refresh_token expiration times.

I will describe two flows A and B in the follwing (I suggest what you want to have is flow B):

A) expiration time of access_token and refresh_token are the same as it is per default 1200 seconds or 20 minutes. This flow needs your client first to send client_id and client_secret with login data to get an access_token, refresh_token and expiration_time. With the refresh_token it is now possible to get a new access_token for 20 minutes (or whatever you set the AccessTokenExpireTimeSpan in the OAuthAuthorizationServerOptions to). For the reason that the expiration time of access_token and refresh_token are the same, your client is responsible to get a new access_token before the expiration time! E.g. your client could send a refresh POST call to your token endpoint with the body (remark: you should use https in production)

grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxx

to get a new token after e.g. 19 minutes to prevent the tokens from expiration.

B) in this flow you want to have a short term expiration for your access_token and a long term expiration for your refresh_token. Lets assume for test purpose you set the access_token to expire in 10 seconds (AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(10)) and the refresh_token to 5 Minutes. Now it comes to the interesting part setting the expiration time of refresh_token: You do this in your createAsync function in SimpleRefreshTokenProvider class like this:

var guid = Guid.NewGuid().ToString();


        //copy properties and set the desired lifetime of refresh token
        var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
        {
            IssuedUtc = context.Ticket.Properties.IssuedUtc,
            ExpiresUtc = DateTime.UtcNow.AddMinutes(5) //SET DATETIME to 5 Minutes
            //ExpiresUtc = DateTime.UtcNow.AddMonths(3) 
        };
        /*CREATE A NEW TICKET WITH EXPIRATION TIME OF 5 MINUTES 
         *INCLUDING THE VALUES OF THE CONTEXT TICKET: SO ALL WE 
         *DO HERE IS TO ADD THE PROPERTIES IssuedUtc and 
         *ExpiredUtc to the TICKET*/
        var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

        //saving the new refreshTokenTicket to a local var of Type ConcurrentDictionary<string,AuthenticationTicket>
        // consider storing only the hash of the handle
        RefreshTokens.TryAdd(guid, refreshTokenTicket);            
        context.SetToken(guid);

Now your client is able to send a POST call with a refresh_token to your token endpoint when the access_token is expired. The body part of the call may look like this: grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xx

One important thing is that you may want to use this code not only in your CreateAsync function but also in your Create function. So you should consider to use your own function (e.g. called CreateTokenInternal) for the above code. Here you can find implementations of different flows including refresh_token flow(but without setting the expiration time of the refresh_token)

Here is one sample implementation of IAuthenticationTokenProvider on github (with setting the expiration time of the refresh_token)

I am sorry that I can't help out with further materials than the OAuth Specs and the Microsoft API Documentation. I would post the links here but my reputation doesn't let me post more than 2 links....

I hope this may help some others to spare time when trying to implement OAuth2.0 with refresh_token expiration time different to access_token expiration time. I couldn't find an example implementation on the web (except the one of thinktecture linked above) and it took me some hours of investigation until it worked for me.

New info: In my case I have two different possibilities to receive tokens. One is to receive a valid access_token. There I have to send a POST call with a String body in format application/x-www-form-urlencoded with the following data

client_id=YOURCLIENTID&grant_type=password&username=YOURUSERNAME&password=YOURPASSWORD

Second is if access_token is not valid anymore we can try the refresh_token by sending a POST call with a String body in format application/x-www-form-urlencoded with the following data grant_type=refresh_token&client_id=YOURCLIENTID&refresh_token=YOURREFRESHTOKENGUID

Count the Number of Tables in a SQL Server Database

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables

How can I show a combobox in Android?

Not tested, but the closer you can get seems to be is with AutoCompleteTextView. You can write an adapter wich ignores the filter functions. Something like:

class UnconditionalArrayAdapter<T> extends ArrayAdapter<T> {
    final List<T> items;
    public UnconditionalArrayAdapter(Context context, int textViewResourceId, List<T> items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    public Filter getFilter() {
        return new NullFilter();
    }

    class NullFilter extends Filter {
        protected Filter.FilterResults performFiltering(CharSequence constraint) {
            final FilterResults results = new FilterResults();
            results.values = items;
            return results;
        }

        protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
            items.clear(); // `items` must be final, thus we need to copy the elements by hand.
            for (Object item : (List) results.values) {
                items.add((String) item);
            }
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

... then in your onCreate:

String[] COUNTRIES = new String[] {"Belgium", "France", "Italy", "Germany"};
List<String> contriesList = Arrays.asList(COUNTRIES());
ArrayAdapter<String> adapter = new UnconditionalArrayAdapter<String>(this,
    android.R.layout.simple_dropdown_item_1line, contriesList);
AutoCompleteTextView textView = (AutoCompleteTextView)
    findViewById(R.id.countries_list);
textView.setAdapter(adapter);

The code is not tested, there can be some features with the filtering method I did not consider, but there you have it, the basic principles to emulate a ComboBox with an AutoCompleteTextView.

Edit Fixed NullFilter implementation. We need access on the items, thus the constructor of the UnconditionalArrayAdapter needs to take a reference to a List (kind of a buffer). You can also use e.g. adapter = new UnconditionalArrayAdapter<String>(..., new ArrayList<String>); and then use adapter.add("Luxemburg"), so you don't need to manage the buffer list.

How to see full query from SHOW PROCESSLIST

See full query from SHOW PROCESSLIST :

SHOW FULL PROCESSLIST;

Or

 SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;

How do I protect Python code?

Use the same way to protect binary file of c/c++, that is, obfuscate each function body in executable or library binary file, insert an instruction "jump" at the begin of each function entry, jump to special function to restore obfuscated code. Byte-code is binary code of Python script, so

  • First compile python script to code object
  • Then iterate each code object, obfuscate co_code of each code object as the following
    0   JUMP_ABSOLUTE            n = 3 + len(bytecode)

    3
    ...
    ... Here it's obfuscated bytecode
    ...

    n   LOAD_GLOBAL              ? (__pyarmor__)
    n+3 CALL_FUNCTION            0
    n+6 POP_TOP
    n+7 JUMP_ABSOLUTE            0
  • Save obfuscated code object as .pyc or .pyo file

Those obfuscated file (.pyc or .pyo) can be used by normal python interpreter, when those code object is called first time

  • First op is JUMP_ABSOLUTE, it will jump to offset n

  • At offset n, the instruction is to call a PyCFunction. This function will restore those obfuscated bytecode between offset 3 and n, and put the original byte-code at offset 0. The obfuscated code can be got by the following code

        char *obfucated_bytecode;
        Py_ssize_t len;
        PyFrameObject* frame = PyEval_GetFrame();
        PyCodeObject *f_code = frame->f_code;
        PyObject *co_code = f_code->co_code;      
        PyBytes_AsStringAndSize(co_code, &obfucated_bytecode, &len)
    
  • After this function returns, the last instruction is to jump to offset 0. The really byte-code now is executed.

There is a tool Pyarmor to obfuscate python scripts by this way.

Copy files on Windows Command Line with Progress

This technet link has some good info for copying large files. I used an exchange server utility mentioned in the article which shows progress and uses non buffered copy functions internally for faster transfer.

In another scenario, I used robocopy. Robocopy GUI makes it easier to get your command line options right.

Error inflating class android.support.v7.widget.Toolbar?

If you are using new androidx implementations, when typing Toolbar, the Studio will autocomplete it to android.support.v7.widget.Toolbar, but you should use androidx.appcompat.widget.Toolbar instead, otherwise you will get this error.