Programs & Examples On #Sniffing

Sniffing is an eavesdropping attempt which consists of capturing packets transmitted through a third party network and reading the data in search of confidential information.

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

If you don't get any direct answer to this you could always run Fiddler on a windows machine and configure your browser on the Mac to use the windows machine as a proxy server. Not very satisfactory and requires a second machine (although it could be virtual).

iPhone and WireShark

This worked for me:

  1. Connect your iOS device by USB

  2. $ rvictl -s UDID where UDID is the UDID of your device (located in XCode under Devices, shortcut to with ??2)

  3. $ sudo launchctl list com.apple.rpmuxd

  4. $ sudo tcpdump -n -t -i rvi0 -q tcp or $ sudo tcpdump -i rvi0 -n

If victl is not working install Xcode and the developer tools.

For more info see Remote Virtual Interface and for the original tutorial here's the Use Your Loaf blog post

Django -- Template tag in {% if %} block

You shouldn't use the double-bracket {{ }} syntax within if or ifequal statements, you can simply access the variable there like you would in normal python:

{% if title == source %}
   ...
{% endif %}

filters on ng-model in an input

I would suggest to watch model value and update it upon chage: http://plnkr.co/edit/Mb0uRyIIv1eK8nTg3Qng?p=preview

The only interesting issue is with spaces: In AngularJS 1.0.3 ng-model on input automatically trims string, so it does not detect that model was changed if you add spaces at the end or at start (so spaces are not automatically removed by my code). But in 1.1.1 there is 'ng-trim' directive that allows to disable this functionality (commit). So I've decided to use 1.1.1 to achieve exact functionality you described in your question.

Change Image of ImageView programmatically in Android

If the above solutions are not working just delete this entire line from XML

android:src="@drawable/image"

& only try

imageView.setBackgroundResource(R.drawable.image);

how to iterate through dictionary in a dictionary in django template?

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

How to deal with floating point number precision in JavaScript?

You just have to make up your mind on how many decimal digits you actually want - can't have the cake and eat it too :-)

Numerical errors accumulate with every further operation and if you don't cut it off early it's just going to grow. Numerical libraries which present results that look clean simply cut off the last 2 digits at every step, numerical co-processors also have a "normal" and "full" lenght for the same reason. Cuf-offs are cheap for a processor but very expensive for you in a script (multiplying and dividing and using pov(...)). Good math lib would provide floor(x,n) to do the cut-off for you.

So at the very least you should make global var/constant with pov(10,n) - meaning that you decided on the precision you need :-) Then do:

Math.floor(x*PREC_LIM)/PREC_LIM  // floor - you are cutting off, not rounding

You could also keep doing math and only cut-off at the end - assuming that you are only displaying and not doing if-s with results. If you can do that, then .toFixed(...) might be more efficient.

If you are doing if-s/comparisons and don't want to cut of then you also need a small constant, usually called eps, which is one decimal place higher than max expected error. Say that your cut-off is last two decimals - then your eps has 1 at the 3rd place from the last (3rd least significant) and you can use it to compare whether the result is within eps range of expected (0.02 -eps < 0.1*0.2 < 0.02 +eps).

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

Similar to other answers I had miss typed the query.

I had -

SELECT t.id FROM t.table LEFT JOIN table2 AS t2 ON t.id = t2.table_id

Should have been

SELECT t.id FROM table AS t LEFT JOIN table2 AS t2 ON t.id = t2.table_id

Mysql was trying to find a database called t which the user didn't have permission for.

How to serve .html files with Spring

It sounds like you are trying to do something like this:

  • Static HTML views
  • Spring controllers serving AJAX

If that is the case, as previously mentioned, the most efficient way is to let the web server(not Spring) handle HTML requests as static resources. So you'll want the following:

  1. Forward all .html, .css, .js, .png, etc requests to the webserver's resource handler
  2. Map all other requests to spring controllers

Here is one way to accomplish that...

web.xml - Map servlet to root (/)

<servlet>
            <servlet-name>sprung</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            ...
<servlet>

<servlet-mapping>
            <servlet-name>sprung</servlet-name>
            <url-pattern>/</url-pattern>
</servlet-mapping>

Spring JavaConfig

public class SpringSprungConfig extends DelegatingWebMvcConfiguration {

    // Delegate resource requests to default servlet
    @Bean
    protected DefaultServletHttpRequestHandler defaultServletHttpRequestHandler() {
        DefaultServletHttpRequestHandler dsrh = new DefaultServletHttpRequestHandler();
        return dsrh;
    }

    //map static resources by extension
    @Bean
    public SimpleUrlHandlerMapping resourceServletMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();

        //make sure static resources are mapped first since we are using
        //a slightly different approach
        mapping.setOrder(0);
        Properties urlProperties = new Properties();
        urlProperties.put("/**/*.css", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.js", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.png", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.html", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.woff", "defaultServletHttpRequestHandler");
        urlProperties.put("/**/*.ico", "defaultServletHttpRequestHandler");
        mapping.setMappings(urlProperties);
        return mapping;
    }

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();

        //controller mappings must be evaluated after the static resource requests
        handlerMapping.setOrder(1);
        handlerMapping.setInterceptors(this.getInterceptors());
        handlerMapping.setPathMatcher(this.getPathMatchConfigurer().getPathMatcher());
        handlerMapping.setRemoveSemicolonContent(false);
        handlerMapping.setUseSuffixPatternMatch(false);
        //set other options here
        return handlerMapping;
    }
}

Additional Considerations

  • Hide .html extension - This is outside the scope of Spring if you are delegating the static resource requests. Look into a URL rewriting filter.
  • Templating - You don't want to duplicate markup in every single HTML page for common elements. This likely can't be done on the server if serving HTML as a static resource. Look into a client-side *VC framework. I'm fan of YUI which has numerous templating mechanisms including Handlebars.

How do I convert csv file to rdd

I'd recommend reading the header directly from the driver, not through Spark. Two reasons for this: 1) It's a single line. There's no advantage to a distributed approach. 2) We need this line in the driver, not the worker nodes.

It goes something like this:

// Ridiculous amount of code to read one line.
val uri = new java.net.URI(filename)
val conf = sc.hadoopConfiguration
val fs = hadoop.fs.FileSystem.get(uri, conf)
val path = new hadoop.fs.Path(filename)
val stream = fs.open(path)
val source = scala.io.Source.fromInputStream(stream)
val header = source.getLines.head

Now when you make the RDD you can discard the header.

val csvRDD = sc.textFile(filename).filter(_ != header)

Then we can make an RDD from one column, for example:

val idx = header.split(",").indexOf(columnName)
val columnRDD = csvRDD.map(_.split(",")(idx))

"Couldn't read dependencies" error with npm

I ran into this problem after I cloned a git repository to a directory, renamed the directory, then tried to run npm install. I'm not sure what the problem was, but something was bungled. Deleting everything, re-cloning (this time with the correct directory name), and then running npm install resolved my issue.

PHP check if date between two dates

You cannot compare date-strings. It is good habit to use PHP's DateTime object instead:

$paymentDate = new DateTime(); // Today
echo $paymentDate->format('d/m/Y'); // echos today! 
$contractDateBegin = new DateTime('2001-01-01');
$contractDateEnd  = new DateTime('2015-01-01');

if (
  $paymentDate->getTimestamp() > $contractDateBegin->getTimestamp() && 
  $paymentDate->getTimestamp() < $contractDateEnd->getTimestamp()){
  echo "is between";
}else{
   echo "NO GO!";  
}

Can I have multiple primary keys in a single table?

A table can have multiple candidate keys. Each candidate key is a column or set of columns that are UNIQUE, taken together, and also NOT NULL. Thus, specifying values for all the columns of any candidate key is enough to determine that there is one row that meets the criteria, or no rows at all.

Candidate keys are a fundamental concept in the relational data model.

It's common practice, if multiple keys are present in one table, to designate one of the candidate keys as the primary key. It's also common practice to cause any foreign keys to the table to reference the primary key, rather than any other candidate key.

I recommend these practices, but there is nothing in the relational model that requires selecting a primary key among the candidate keys.

How to filter by object property in angularJS

You could also do this to make it more dynamic.

<input name="filterByPolarity" data-ng-model="text.polarity"/>

Then you ng-repeat will look like this

<div class="tweet" data-ng-repeat="tweet in tweets | filter:text"></div>

This filter will of course only be used to filter by polarity

Map with Key as String and Value as List in Groovy

One additional small piece that is helpful when dealing with maps/list as the value in a map is the withDefault(Closure) method on maps in groovy. Instead of doing the following code:

Map m = [:]
for(object in listOfObjects)
{
  if(m.containsKey(object.myKey))
  {
    m.get(object.myKey).add(object.myValue)
  }
  else
  {
    m.put(object.myKey, [object.myValue]
  }
}

You can do the following:

Map m = [:].withDefault{key -> return []}
for(object in listOfObjects)
{
  List valueList = m.get(object.myKey)
  m.put(object.myKey, valueList)
}

With default can be used for other things as well, but I find this the most common use case for me.

API: http://www.groovy-lang.org/gdk.html

Map -> withDefault(Closure)

Serializing and submitting a form with jQuery and PHP

The problem can be PHP configuration:

Please check the setting max_input_vars in the php.ini file.

Try to increase the value of this setting to 5000 as example.

max_input_vars = 5000

Then restart your web-server and try.

Find distance between two points on map using Google Map API V2

THIS IS THE EASY AND PERFECT CODE FOR DURATION AND DISTANCE FINDING

  • Step 1;(add this and sync in your gradle)

    compile 'com.android.volley:volley:1.0.0'  
    
  • Step 2:(write this in your trigger method)

    public void clicked(View view) throws JSONException {  
    
         JSONObject locationJsonObject = new JSONObject();
                locationJsonObject.put("origin", "54.406505,18.67708");
                locationJsonObject.put("destination", "54.446251,18.570993");
                LatlngCalc(locationJsonObject);
    }
    
  • Step 3:(Copy & Paste in your class)

    private void LatlngCalc(JSONObject locationJsonObject) throws JSONException {
    
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        String url = "http://maps.googleapis.com/maps/api/distancematrix/" +
                    "json?origins=" + locationJsonObject.getString("origin") + "&destinations=" + locationJsonObject.getString("destination") + "&mode=driving&" +
                    "language=en-EN&sensor=false";
    
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
    
                        mTextView.setText("Response is: " + response.substring(0, 500));
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mTextView.setText("That didn't work!");
            }
        });
        queue.add(stringRequest);  
    }
    

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

in my case, I got the same exception because the user that I configured in the app did not existed in the DB, creating the user and granting needed permissions solved the problem.

Sorting a tab delimited file

Using bash, this will do the trick:

$ sort -t$'\t' -k3 -nr file.txt

Notice the dollar sign in front of the single-quoted string. You can read about it in the ANSI-C Quoting sections of the bash man page.

reading from app.config file

The reason is simple, your call to ConfigurationSettings.AppSettings is not returning the required config file. Please try any of the following ways:

  • Make sure your app config has the same name as your application's exe file - with the extension .config appended eg MyApp.exe.config
  • OR you can use ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings["StartingMonthColumn"]

Hope this helps

Excel to CSV with UTF8 encoding

I have written a small Python script that can export worksheets in UTF-8.

You just have to provide the Excel file as first parameter followed by the sheets that you would like to export. If you do not provide the sheets, the script will export all worksheets that are present in the Excel file.

#!/usr/bin/env python

# export data sheets from xlsx to csv

from openpyxl import load_workbook
import csv
from os import sys

reload(sys)
sys.setdefaultencoding('utf-8')

def get_all_sheets(excel_file):
    sheets = []
    workbook = load_workbook(excel_file,use_iterators=True,data_only=True)
    all_worksheets = workbook.get_sheet_names()
    for worksheet_name in all_worksheets:
        sheets.append(worksheet_name)
    return sheets

def csv_from_excel(excel_file, sheets):
    workbook = load_workbook(excel_file,use_iterators=True,data_only=True)
    for worksheet_name in sheets:
        print("Export " + worksheet_name + " ...")

        try:
            worksheet = workbook.get_sheet_by_name(worksheet_name)
        except KeyError:
            print("Could not find " + worksheet_name)
            sys.exit(1)

        your_csv_file = open(''.join([worksheet_name,'.csv']), 'wb')
        wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
        for row in worksheet.iter_rows():
            lrow = []
            for cell in row:
                lrow.append(cell.value)
            wr.writerow(lrow)
        print(" ... done")
    your_csv_file.close()

if not 2 <= len(sys.argv) <= 3:
    print("Call with " + sys.argv[0] + " <xlxs file> [comma separated list of sheets to export]")
    sys.exit(1)
else:
    sheets = []
    if len(sys.argv) == 3:
        sheets = list(sys.argv[2].split(','))
    else:
        sheets = get_all_sheets(sys.argv[1])
    assert(sheets != None and len(sheets) > 0)
    csv_from_excel(sys.argv[1], sheets)

How can I fill a column with random numbers in SQL? I get the same value in every row

require_once('db/connect.php');

//rand(1000000 , 9999999);

$products_query = "SELECT id FROM products";
$products_result = mysqli_query($conn, $products_query);
$products_row = mysqli_fetch_array($products_result);
$ids_array = [];

do
{
    array_push($ids_array, $products_row['id']);
}
while($products_row = mysqli_fetch_array($products_result));

/*
echo '<pre>';
print_r($ids_array);
echo '</pre>';
*/
$row_counter = count($ids_array);

for ($i=0; $i < $row_counter; $i++)
{ 
    $current_row = $ids_array[$i];
    $rand = rand(1000000 , 9999999);
    mysqli_query($conn , "UPDATE products SET code='$rand' WHERE id='$current_row'");
}

gson throws MalformedJsonException

In the debugger you don't need to add back slashes, the input field understands the special chars.

In java code you need to escape the special chars

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

High Quality Image Scaling Library

You can try dotImage, one of my company's products, which includes an object for resampling images that has 18 filter types for various levels of quality.

Typical usage is:

// BiCubic is one technique available in PhotoShop
ResampleCommand resampler = new ResampleCommand(newSize, ResampleMethod.BiCubic);
AtalaImage newImage = resampler.Apply(oldImage).Image;

in addition, dotImage includes 140 some odd image processing commands including many filters similar to those in PhotoShop, if that's what you're looking for.

How to detect when cancel is clicked on file input?

Just add 'change' listener on your input whose type is file. i.e

<input type="file" id="file_to_upload" name="file_to_upload" />

I have done using jQuery and obviously anyone can use valina JS (as per the requirement).

$("#file_to_upload").change(function() {

            if (this.files.length) {

            alert('file choosen');

            } else {

            alert('file NOT choosen');

            }

    });

How can strip whitespaces in PHP's variable?

The \s regex argument is not compatible with UTF-8 multybyte strings.

This PHP RegEx is one I wrote to solve this using PCRE (Perl Compatible Regular Expressions) based arguments as a replacement for UTF-8 strings:

function remove_utf8_whitespace($string) { 
   return preg_replace('/\h+/u','',preg_replace('/\R+/u','',$string)); 
}

- Example Usage -

Before:

$string = " this is a test \n and another test\n\r\t ok! \n";

echo $string;

 this is a test
 and another test
         ok!

echo strlen($string); // result: 43

After:

$string = remove_utf8_whitespace($string);

echo $string;

thisisatestandanothertestok!

echo strlen($string); // result: 28

PCRE Argument Listing

Source: https://www.rexegg.com/regex-quickstart.html

Character   Legend  Example Sample Match
\t  Tab T\t\w{2}    T     ab
\r  Carriage return character   see below   
\n  Line feed character see below   
\r\n    Line separator on Windows   AB\r\nCD    AB
    CD
\N  Perl, PCRE (C, PHP, R…): one character that is not a line break \N+ ABC
\h  Perl, PCRE (C, PHP, R…), Java: one horizontal whitespace character: tab or Unicode space separator      
\H  One character that is not a horizontal whitespace       
\v  .NET, JavaScript, Python, Ruby: vertical tab        
\v  Perl, PCRE (C, PHP, R…), Java: one vertical whitespace character: line feed, carriage return, vertical tab, form feed, paragraph or line separator      
\V  Perl, PCRE (C, PHP, R…), Java: any character that is not a vertical whitespace      
\R  Perl, PCRE (C, PHP, R…), Java: one line break (carriage return + line feed pair, and all the characters matched by \v)      

Do a "git export" (like "svn export")?

My preference would actually be to have a dist target in your Makefile (or other build system) that exports a distributable archive of your code (.tar.bz2, .zip, .jar, or whatever is appropriate). If you happen to be using GNU autotools or Perl's MakeMaker systems, I think this exists for you automatically. If not, I highly recommend adding it.

ETA (2012-09-06): Wow, harsh downvotes. I still believe it is better to build your distributions with your build tools rather than your source code control tool. I believe in building artifacts with build tools. In my current job, our main product is built with an ant target. We are in the midst of switching source code control systems, and the presence of this ant target means one less hassle in migration.

T-SQL XOR Operator

There is a bitwise XOR operator - the caret (^), i.e. for:

SELECT 170 ^ 75

The result is 225.

For logical XOR, use the ANY keyword and NOT ALL, i.e.

WHERE 5 > ANY (SELECT foo) AND NOT (5 > ALL (SELECT foo))

Ignore .pyc files in git repository

You have probably added them to the repository before putting *.pyc in .gitignore.
First remove them from the repository.

The project type is not supported by this installation

Open up the .csproj file for your solution in wordpad or some text editor. Look for the ProjectTypeGuids. They indicate the required supported types for your solutions. Search the internet these GUIDs to find out what they require. For example E53F8FEA-EAE0-44A6-8774-FFD645390401 means it requires "MVC 3.0"

java create date object using a value string

What you're basically trying to do is this:-

Calendar cal = Calendar.getInstance();
Date date = cal.getTime();

The reason being, the String which you're printing is just a String representation of the Date in your required format. If you try to convert it to date, you'll eventually end up doing what I've mentioned above.

Formatting Date(cal.getTime()) to a String and trying to get back a Date from it - makes no sense. Date has no format as such. You can only get a String representation of that using the SDF.

Any way to select without causing locking in MySQL?

Use

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED.

Version 5.0 Docs are here.

Version 5.1 Docs are here.

how to install tensorflow on anaconda python 3.6

For Windows 10 with Anaconda 4.4 Python 3.6:

1st step) conda create -n tensorflow python=3.6

2nd step) activate tensorflow

3rd step) pip3 install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.2.1-cp36-cp36m-win_amd64.whl

What are the pros and cons of parquet format compared to other formats?

I think the main difference I can describe relates to record oriented vs. column oriented formats. Record oriented formats are what we're all used to -- text files, delimited formats like CSV, TSV. AVRO is slightly cooler than those because it can change schema over time, e.g. adding or removing columns from a record. Other tricks of various formats (especially including compression) involve whether a format can be split -- that is, can you read a block of records from anywhere in the dataset and still know it's schema? But here's more detail on columnar formats like Parquet.

Parquet, and other columnar formats handle a common Hadoop situation very efficiently. It is common to have tables (datasets) having many more columns than you would expect in a well-designed relational database -- a hundred or two hundred columns is not unusual. This is so because we often use Hadoop as a place to denormalize data from relational formats -- yes, you get lots of repeated values and many tables all flattened into a single one. But it becomes much easier to query since all the joins are worked out. There are other advantages such as retaining state-in-time data. So anyway it's common to have a boatload of columns in a table.

Let's say there are 132 columns, and some of them are really long text fields, each different column one following the other and use up maybe 10K per record.

While querying these tables is easy with SQL standpoint, it's common that you'll want to get some range of records based on only a few of those hundred-plus columns. For example, you might want all of the records in February and March for customers with sales > $500.

To do this in a row format the query would need to scan every record of the dataset. Read the first row, parse the record into fields (columns) and get the date and sales columns, include it in your result if it satisfies the condition. Repeat. If you have 10 years (120 months) of history, you're reading every single record just to find 2 of those months. Of course this is a great opportunity to use a partition on year and month, but even so, you're reading and parsing 10K of each record/row for those two months just to find whether the customer's sales are > $500.

In a columnar format, each column (field) of a record is stored with others of its kind, spread all over many different blocks on the disk -- columns for year together, columns for month together, columns for customer employee handbook (or other long text), and all the others that make those records so huge all in their own separate place on the disk, and of course columns for sales together. Well heck, date and months are numbers, and so are sales -- they are just a few bytes. Wouldn't it be great if we only had to read a few bytes for each record to determine which records matched our query? Columnar storage to the rescue!

Even without partitions, scanning the small fields needed to satisfy our query is super-fast -- they are all in order by record, and all the same size, so the disk seeks over much less data checking for included records. No need to read through that employee handbook and other long text fields -- just ignore them. So, by grouping columns with each other, instead of rows, you can almost always scan less data. Win!

But wait, it gets better. If your query only needed to know those values and a few more (let's say 10 of the 132 columns) and didn't care about that employee handbook column, once it had picked the right records to return, it would now only have to go back to the 10 columns it needed to render the results, ignoring the other 122 of the 132 in our dataset. Again, we skip a lot of reading.

(Note: for this reason, columnar formats are a lousy choice when doing straight transformations, for example, if you're joining all of two tables into one big(ger) result set that you're saving as a new table, the sources are going to get scanned completely anyway, so there's not a lot of benefit in read performance, and because columnar formats need to remember more about the where stuff is, they use more memory than a similar row format).

One more benefit of columnar: data is spread around. To get a single record, you can have 132 workers each read (and write) data from/to 132 different places on 132 blocks of data. Yay for parallelization!

And now for the clincher: compression algorithms work much better when it can find repeating patterns. You could compress AABBBBBBCCCCCCCCCCCCCCCC as 2A6B16C but ABCABCBCBCBCCCCCCCCCCCCCC wouldn't get as small (well, actually, in this case it would, but trust me :-) ). So once again, less reading. And writing too.

So we read a lot less data to answer common queries, it's potentially faster to read and write in parallel, and compression tends to work much better.

Columnar is great when your input side is large, and your output is a filtered subset: from big to little is great. Not as beneficial when the input and outputs are about the same.

But in our case, Impala took our old Hive queries that ran in 5, 10, 20 or 30 minutes, and finished most in a few seconds or a minute.

Hope this helps answer at least part of your question!

Array length in angularjs returns undefined

Make it like this:

$scope.users.data.length;

Binding value to input in Angular JS

If you don't wan't to use ng-model there is ng-value you can try.

Here's the fiddle for this: http://jsfiddle.net/Rg9sG/1/

How to submit a form when the return key is pressed?

If you are using asp.net you can use the defaultButton attribute on the form.

JAXB :Need Namespace Prefix to all the elements

MSK,

Have you tried setting a namespace declaration to your member variables like this? :

@XmlElement(required = true, namespace = "http://example.com/a")
protected String username;

@XmlElement(required = true, namespace = "http://example.com/a")
protected String password;

For our project, it solved namespace issues. We also had to create NameSpacePrefixMappers.

Put icon inside input element in a form

Using with font-icon

<input name="foo" type="text" placeholder="&#61447;">

OR

<input id="foo" type="text" />

#foo::before
{
  font-family: 'FontAwesome';
  color:red;
  position: relative;
  left: -5px;
  content: "\f007";    
}

How do I ZIP a file in C#, using no 3rd-party APIs?

Add these 4 functions to your project:

        public const long BUFFER_SIZE = 4096;
    public static void AddFileToZip(string zipFilename, string fileToAdd)
    {
        using (Package zip = global::System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
        {
            string destFilename = ".\\" + Path.GetFileName(fileToAdd);
            Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
            if (zip.PartExists(uri))
            {
                zip.DeletePart(uri);
            }
            PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
            using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
            {
                using (Stream dest = part.GetStream())
                {
                    CopyStream(fileStream, dest);
                }
            }
        }
    }
    public static void CopyStream(global::System.IO.FileStream inputStream, global::System.IO.Stream outputStream)
    {
        long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
        byte[] buffer = new byte[bufferSize];
        int bytesRead = 0;
        long bytesWritten = 0;
        while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            outputStream.Write(buffer, 0, bytesRead);
            bytesWritten += bytesRead;
        }
    }
    public static void RemoveFileFromZip(string zipFilename, string fileToRemove)
    {
        using (Package zip = global::System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
        {
            string destFilename = ".\\" + fileToRemove;
            Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
            if (zip.PartExists(uri))
            {
                zip.DeletePart(uri);
            }
        }
    }
    public static void Remove_Content_Types_FromZip(string zipFileName)
    {
        string contents;
        using (ZipFile zipFile = new ZipFile(File.Open(zipFileName, FileMode.Open)))
        {
            /*
            ZipEntry startPartEntry = zipFile.GetEntry("[Content_Types].xml");
            using (StreamReader reader = new StreamReader(zipFile.GetInputStream(startPartEntry)))
            {
                contents = reader.ReadToEnd();
            }
            XElement contentTypes = XElement.Parse(contents);
            XNamespace xs = contentTypes.GetDefaultNamespace();
            XElement newDefExt = new XElement(xs + "Default", new XAttribute("Extension", "sab"), new XAttribute("ContentType", @"application/binary; modeler=Acis; version=18.0.2application/binary; modeler=Acis; version=18.0.2"));
            contentTypes.Add(newDefExt);
            contentTypes.Save("[Content_Types].xml");
            zipFile.BeginUpdate();
            zipFile.Add("[Content_Types].xml");
            zipFile.CommitUpdate();
            File.Delete("[Content_Types].xml");
            */
            zipFile.BeginUpdate();
            try
            {
                zipFile.Delete("[Content_Types].xml");
                zipFile.CommitUpdate();
            }
            catch{}
        }
    }

And use them like this:

foreach (string f in UnitZipList)
{
    AddFileToZip(zipFile, f);
    System.IO.File.Delete(f);
}
Remove_Content_Types_FromZip(zipFile);

Using variable in SQL LIKE statement

Joel is it that @SearchLetter hasn't been declared yet? Also the length of @SearchLetter2 isn't long enough for 't%'. Try a varchar of a longer length.

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

IEnumerable<string> e = (from char c in source
                        select new { Data = c.ToString() }).Select(t = > t.Data);
// or
IEnumerable<string> e = from char c in source
                        select c.ToString();
// or
IEnumerable<string> e = source.Select(c = > c.ToString());

Then you can call ToList():

List<string> l = (from char c in source
                  select new { Data = c.ToString() }).Select(t = > t.Data).ToList();
// or
List<string> l = (from char c in source
                  select c.ToString()).ToList();
// or
List<string> l = source.Select(c = > c.ToString()).ToList();

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

I write one with js and python, used in two projects, very nice and simple: a simple library (less then 2kb) used to format date with *** time ago statement.

simple, small, easy used, and well tested.

  1. npm install timeago.js

  2. import timeago from 'timeago.js'; // or use script tag

  3. use api format.

Sample:

var timeagoIns  = timeago();
timeagoIns .format('2016-06-12');

Also you can render in real-time.

var timeagoIns = timeago();
timeagoIns.render(document.querySelectorAll('time'));

What is the difference between getText() and getAttribute() in Selenium WebDriver?

getAttribute() -> It fetches the text that contains one of any attribute in the HTML tag. Suppose there is an HTML tag like

<input name="Name Locator" value="selenium">Hello</input>

Now getAttribute() fetches the data of the attribute of 'value', which is "Selenium".

Returns:

The attribute's current value or null if the value is not set.

driver.findElement(By.name("Name Locator")).getAttribute("value")  //

The field value is retrieved by the getAttribute("value") Selenium WebDriver predefined method and assigned to the String object.

getText() -> delivers the innerText of a WebElement. Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.

Returns:

The innerText of this element.

driver.findElement(By.name("Name Locator")).getText();

'Hello' will appear

Call another rest api from my server in Spring-Boot

Does Retrofit have any method to achieve this? If not, how I can do that?

YES

Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.

For more information refer the following link

https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial

How can I convince IE to simply display application/json rather than offer to download it?

Changing IE's JSON mime-type settings will effect the way IE treats all JSON responses.

Changing the mime-type header to text/html will effectively tell any browser that the JSON response you are returning is not JSON but plain text.

Neither options are preferable.

Instead you would want to use a plugin or tool like the above mentioned Fiddler or any other network traffic inspector proxy where you can choose each time how to process the JSON response.

MySQL order by before group by

Just use the max function and group function

    select max(taskhistory.id) as id from taskhistory
            group by taskhistory.taskid
            order by taskhistory.datum desc

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyInformationalVersion and AssemblyFileVersion are displayed when you view the "Version" information on a file through Windows Explorer by viewing the file properties. These attributes actually get compiled in to a VERSION_INFO resource that is created by the compiler.

AssemblyInformationalVersion is the "Product version" value. AssemblyFileVersion is the "File version" value.

The AssemblyVersion is specific to .NET assemblies and is used by the .NET assembly loader to know which version of an assembly to load/bind at runtime.

Out of these, the only one that is absolutely required by .NET is the AssemblyVersion attribute. Unfortunately it can also cause the most problems when it changes indiscriminately, especially if you are strong naming your assemblies.

AWS S3 CLI - Could not connect to the endpoint URL

Assuming that your profile in ~/aws/config is using the region (instead of AZ as per your original question); the other cause is your client's inability to connect to s3.us-east-1.amazonaws.com. In my case, I was unable to resolve that DNS name due to an error in my network configuration. Fixing the DNS issue solved my problem.

Python Image Library fails with message "decoder JPEG not available" - PIL

Same problem here, JPEG support available but still got IOError: decoder/encoder jpeg not available, except I use Pillow and not PIL.

I tried all of the above and more, but after many hours I realized that using sudo pip install does not work as I expected, in combination with virtualenv. Silly me.

Using sudo effectively launches the command in a new shell (my understanding of this may not be entirely correct) where the virtualenv is not activated, meaning that the packages will be installed in the global environment instead. (This messed things up, I think I had 2 different installations of Pillow.)

I cleaned things up, changed user to root and reinstalled in the virtualenv and now it works.
Hopefully this will help someone!

memory error in python

If you get an unexpected MemoryError and you think you should have plenty of RAM available, it might be because you are using a 32-bit python installation.

The easy solution, if you have a 64-bit operating system, is to switch to a 64-bit installation of python.

The issue is that 32-bit python only has access to ~4GB of RAM. This can shrink even further if your operating system is 32-bit, because of the operating system overhead.

You can learn more about why 32-bit operating systems are limited to ~4GB of RAM here: https://superuser.com/questions/372881/is-there-a-technical-reason-why-32-bit-windows-is-limited-to-4gb-of-ram

How do I rotate text in css?

You need to use the CSS3 transform property rotate - see here for which browsers support it and the prefix you need to use.

One example for webkit browsers is -webkit-transform: rotate(-90deg);

Edit: The question was changed substantially so I have added a demo that works in Chrome/Safari (as I only included the -webkit- CSS prefixed rules). The problem you have is that you do not want to rotate the title div, but simply the text inside it. If you remove your rotation, the <div>s are in the correct position and all you need to do is wrap the text in an element and rotate that instead.

There already exists a more customisable widget as part of the jQuery UI - see the accordion demo page. I am sure with some CSS cleverness you should be able to make the accordion vertical and also rotate the title text :-)

Edit 2: I had anticipated the text center problem and have already updated my demo. There is a height/width constraint though, so longer text could still break the layout.

Edit 3: It looks like the horizontal version was part of the original plan but I cannot see any way of configuring it on the demo page. I was incorrect… the new accordion is part of the upcoming jQuery UI 1.9! So you could try the development builds if you want the new functionality.

Hope this helps!

How to enable assembly bind failure logging (Fusion) in .NET

For those who are a bit lazy, I recommend running this as a bat file for when ever you want to enable it:

reg add "HKLM\Software\Microsoft\Fusion" /v EnableLog /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v ForceLog /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogFailures /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogResourceBinds /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogPath /t REG_SZ /d C:\FusionLog\

if not exist "C:\FusionLog\" mkdir C:\FusionLog

How to use ConcurrentLinkedQueue?

This is probably what you're looking for in terms of thread safety & "prettyness" when trying to consume everything in the queue:

for (YourObject obj = queue.poll(); obj != null; obj = queue.poll()) {
}

This will guarantee that you quit when the queue is empty, and that you continue to pop objects off of it as long as it's not empty.

C++ Best way to get integer division and remainder

On x86 the remainder is a by-product of the division itself so any half-decent compiler should be able to just use it (and not perform a div again). This is probably done on other architectures too.

Instruction: DIV src

Note: Unsigned division. Divides accumulator (AX) by "src". If divisor is a byte value, result is put to AL and remainder to AH. If divisor is a word value, then DX:AX is divided by "src" and result is stored in AX and remainder is stored in DX.

int c = (int)a / b;
int d = a % b; /* Likely uses the result of the division. */

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

Formatting MM/DD/YYYY dates in textbox in VBA

You could use an input mask on the text box, too. If you set the mask to ##/##/#### it will always be formatted as you type and you don't need to do any coding other than checking to see if what was entered was a true date.

Which just a few easy lines

txtUserName.SetFocus
If IsDate(txtUserName.text) Then
    Debug.Print Format(CDate(txtUserName.text), "MM/DD/YYYY")
Else
    Debug.Print "Not a real date"
End If

Why do I need an IoC container as opposed to straightforward DI code?

As you continue to decouple your classes and invert your dependencies, the classes continue to stay small and the "dependency graph" continues to grow in size. (This isn't bad.) Using basic features of an IoC container makes wiring up all these objects trivial, but doing it manually can get very burdensome. For example, what if I want to create a new instance of "Foo" but it needs a "Bar". And a "Bar" needs an "A", "B", and "C". And each of those need 3 other things, etc etc. (yes, I can't come up with good fake names :) ).

Using an IoC container to build your object graph for you reduces complexity a ton and pushes it out into one-time configuration. I simply say "create me a 'Foo'" and it figures out what's needed to build one.

Some people use the IoC containers for much more infrastructure, which is fine for advanced scenarios but in those cases I agree it can obfuscate and make code hard to read and debug for new devs.

How do you make an array of structs in C?

Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.

Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:

typedef struct
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
}Body;

Then declare your array of structs. Initialization of each element goes along with the declaration:

Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};

To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.

Increment a Integer's int value?

Integer objects are immutable. You can't change the value of the integer held by the object itself, but you can just create a new Integer object to hold the result:

Integer start = new Integer(5);
Integer end = start + 5; // end == 10;

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

you can force UTF8 with force_encoding(Encoding::UTF_8):

Example:

<%= yield.force_encoding(Encoding::UTF_8) %>

In a Git repository, how to properly rename a directory?

You can rename the directory using the file system. Then you can do git rm <old directory> and git add <new directory> (Help page). Then you can commit and push.

Git will detect that the contents are the same and that it's just a rename operation, and it'll appear as a rename entry in the history. You can check that this is the case before the commit using git status

Returning IEnumerable<T> vs. IQueryable<T>

In general you want to preserve the original static type of the query until it matters.

For this reason, you can define your variable as 'var' instead of either IQueryable<> or IEnumerable<> and you will know that you are not changing the type.

If you start out with an IQueryable<>, you typically want to keep it as an IQueryable<> until there is some compelling reason to change it. The reason for this is that you want to give the query processor as much information as possible. For example, if you're only going to use 10 results (you've called Take(10)) then you want SQL Server to know about that so that it can optimize its query plans and send you only the data you'll use.

A compelling reason to change the type from IQueryable<> to IEnumerable<> might be that you are calling some extension function that the implementation of IQueryable<> in your particular object either cannot handle or handles inefficiently. In that case, you might wish to convert the type to IEnumerable<> (by assigning to a variable of type IEnumerable<> or by using the AsEnumerable extension method for example) so that the extension functions you call end up being the ones in the Enumerable class instead of the Queryable class.

Angularjs checkbox checked by default on load and disables Select list when checked

If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.

http://jsfiddle.net/UTULc/

<div ng-app="">
  Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
  <select id="transferTo" ng-disabled="checked">
    <option>Tech1</option>
    <option>Tech2</option>
  </select>
</div>

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

For googlers and completeness sake:

Here's a reference I always use when I need to go through the pain of implementing html email-templates or signatures: http://www.campaignmonitor.com/css/

I'ts a list of CSS support for most, if not all, CSS options, nicely compared between some of the most used email clients.

For centering, feel free to just use CSS (as the align attribute is deprecated in HTML 4.01).

<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td style="text-align: center;">
            Your Content
        </td>
    </tr>
</table>

How to configure Fiddler to listen to localhost?

You cannot. Instead if you machine is named "myMachine", point your browser to http://mymachine instead of http://localhost

jQuery Ajax requests are getting cancelled without being sent

I had a similar issue. Using chrome://net-internals/#events I was able to see that my issue was due to some silent redirect. My get request was being fired in an onload script. The url was of the form, "http://example.com/inner-path" and the 301 was permanently redirecting to "/inner-path". To fix the issue I just changed the url to "/inner-path" and that fixed the issue. I still don't know why a script that worked a week ago was suddenly giving me issue... Hope this helps someone

M_PI works with math.h but not with cmath in Visual Studio

With CMake it would just be

add_compile_definitions(_USE_MATH_DEFINES)

in CMakeLists.txt.

Javascript - Track mouse position

ES6 based code:

let handleMousemove = (event) => {
  console.log(`mouse position: ${event.x}:${event.y}`);
};

document.addEventListener('mousemove', handleMousemove);

If you need throttling for mousemoving, use this:

let handleMousemove = (event) => {
  console.warn(`${event.x}:${event.y}\n`);
};

let throttle = (func, delay) => {
  let prev = Date.now() - delay;
  return (...args) => {
    let current = Date.now();
    if (current - prev >= delay) {
      prev = current;
      func.apply(null, args);
    }
  }
};

// let's handle mousemoving every 500ms only
document.addEventListener('mousemove', throttle(handleMousemove, 500));

here is example

How to call a function within class?

That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).

Use sed to replace all backslashes with forward slashes

This might work for you:

sed 'y/\\/\//'

Best XML Parser for PHP

Have a look at PHP's available XML extensions.

The main difference between XML Parser and SimpleXML is that the latter is not a pull parser. SimpleXML is built on top of the DOM extensions and will load the entire XML file into memory. XML Parser like XMLReader will only load the current node into memory. You define handlers for specific nodes which will get triggered when the Parser encounters it. That is faster and saves on memory. You pay for that with not being able to use XPath.

Personally, I find SimpleXml quite limiting (hence simple) in what it offers over DOM. You can switch between DOM and SimpleXml easily though, but I usually dont bother and go the DOM route directly. DOM is an implementation of the W3C DOM API, so you might be familiar with it from other languages, for instance JavaScript.

Regular expression to match a line that doesn't contain a word

The given answers are perfectly fine, just an academic point:

Regular Expressions in the meaning of theoretical computer sciences ARE NOT ABLE do it like this. For them it had to look something like this:

^([^h].*$)|(h([^e].*$|$))|(he([^h].*$|$))|(heh([^e].*$|$))|(hehe.+$) 

This only does a FULL match. Doing it for sub-matches would even be more awkward.

Query-string encoding of a Javascript Object

Do you need to send arbitrary objects? If so, GET is a bad idea since there are limits to the lengths of URLs that user agents and web servers will accepts. My suggestion would be to build up an array of name-value pairs to send and then build up a query string:

function QueryStringBuilder() {
    var nameValues = [];

    this.add = function(name, value) {
        nameValues.push( {name: name, value: value} );
    };

    this.toQueryString = function() {
        var segments = [], nameValue;
        for (var i = 0, len = nameValues.length; i < len; i++) {
            nameValue = nameValues[i];
            segments[i] = encodeURIComponent(nameValue.name) + "=" + encodeURIComponent(nameValue.value);
        }
        return segments.join("&");
    };
}

var qsb = new QueryStringBuilder();
qsb.add("veg", "cabbage");
qsb.add("vegCount", "5");

alert( qsb.toQueryString() );

Does Java have something like C#'s ref and out keywords?

Direct answer: No

But you can simulate reference with wrappers.

And do the following:

void changeString( _<String> str ) {
    str.s("def");
}

void testRef() {
     _<String> abc = new _<String>("abc");
     changeString( abc );
     out.println( abc ); // prints def
}

Out

void setString( _<String> ref ) {
    str.s( "def" );
}
void testOut(){
    _<String> abc = _<String>();
    setString( abc );
    out.println(abc); // prints def
}

And basically any other type such as:

_<Integer> one = new <Integer>(1);
addOneTo( one );

out.println( one ); // May print 2

Field 'browser' doesn't contain a valid alias configuration

I'm using "@google-cloud/translate": "^5.1.4" and was truggling with this issue, until I tried this:

I opened google-gax\build\src\operationsClient.js file and changed

const configData = require('./operations_client_config');

to

const configData = require('./operations_client_config.json');

which solved the error

ERROR in ./node_modules/google-gax/build/src/operationsClient.js Module not found: Error: Can't resolve './operations_client_config' in 'C:\..\Projects\qaymni\node_modules\google-gax\build\src' resolve './operations_client_config' ......

I hope it helps someone

Add image in title bar

That method will not work. The <title> only supports plain text. You will need to create an .ico image with the filename of favicon.ico and save it into the root folder of your site (where your default page is).

Alternatively, you can save the icon where ever you wish and call it whatever you want, but simply insert the following code into the <head> section of your HTML and reference your icon:

<link rel="shortcut icon" href="your_image_path_and_name.ico" />

You can use Photoshop (with a plug in) or GIMP (free) to create an .ico file, or you can just use IcoFX, which is my personal favourite as it is really easy to use and does a great job (you can get an older version of the software for free from download.com).

Update 1: You can also use a number of online tools to create favicons such as ConvertIcon, which I've used successfully. There are other free online tools available now too, which do the same (accessible by a simple Google search), but also generate other icons such as the Windows 8/10 Start Menu icons and iOS App Icons.

Update 2: You can also use .png images as icons providing IE11 is the only version of IE you need to support. You just need to reference them using the HTML code above. Note that IE10 and older still require .ico files.

Update 3: You can now use Emoji characters in the title field. On Windows 10, it should generally fall back and use the Segoe UI Emoji font and display nicely, however you'll need to test and see how other systems support and display your chosen emoji, as not all devices may have the same Emoji available.

Which method performs better: .Any() vs .Count() > 0?

If you are using the Entity Framework and have a huge table with many records Any() will be much faster. I remember one time I wanted to check to see if a table was empty and it had millions of rows. It took 20-30 seconds for Count() > 0 to complete. It was instant with Any().

Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * ....

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

  1. Make sure that you have Office runtime installed on the server.
  2. If you are using Windows Server 2008 then using office interops is a lenghty configuration and here are the steps.

Better is to move to Open XML or you can configure as below

  • Install MS Office Pro Latest (I used 2010 Pro)
  • Create User ExcelUser. Assign WordUser with Admin Group
  • Go to Computer -> Manage
  • Add User with below options
  • User Options Password Never Expires
  • Password Cannot Be Change

Com+ Configuration

  • Go to Control Panel - > Administrator -> Component Services -> DCOM Config
  • Open Microsoft Word 97 - 2003 Properties
  • General -> Authentication Level : None
  • Security -> Customize all 3 permissions to allow everyone
  • Identity -> This User -> Use ExcelUser /password
  • Launch the Excel App to make sure everything is fine

3.Change the security settings of Microsoft Excel Application in DCOM Config.

Controlpanel --> Administrative tools-->Component Services -->computers --> myComputer -->DCOM Config --> Microsoft Excel Application.

Right click to get properties dialog. Go to Security tab and customize permissions

See the posts here: Error while creating Excel object , Excel manipulations in WCF using COM

How to insert current datetime in postgresql insert query

You can of course format the result of current_timestamp(). Please have a look at the various formatting functions in the official documentation.

Check if a string is a date value

This callable function works perfectly, returns true for valid date. Be sure to call using a date on ISO format (yyyy-mm-dd or yyyy/mm/dd):

function validateDate(isoDate) {

    if (isNaN(Date.parse(isoDate))) {
        return false;
    } else {
        if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) {
            return false;
        }
    }
    return true;
}

MySQL: How to set the Primary Key on phpMyAdmin?

You can set a primary key on a text column. In phpMyAdmin, display the Structure of your table, click on Indexes, then ask to create the index on one column. Then choose PRIMARY, pick your TEXT column, but you have to put a length big enough so that its unique.

Save matplotlib file to a directory

Here's the piece of code that saves plot to the selected directory. If the directory does not exist, it is created.

import os
import matplotlib.pyplot as plt

script_dir = os.path.dirname(__file__)
results_dir = os.path.join(script_dir, 'Results/')
sample_file_name = "sample"

if not os.path.isdir(results_dir):
    os.makedirs(results_dir)

plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.savefig(results_dir + sample_file_name)

Java Date vs Calendar

I always advocate Joda-time. Here's why.

  1. the API is consistent and intuitive. Unlike the java.util.Date/Calendar APIs
  2. it doesn't suffer from threading issues, unlike java.text.SimpleDateFormat etc. (I've seen numerous client issues relating to not realising that the standard date/time formatting is not thread-safe)
  3. it's the basis of the new Java date/time APIs (JSR310, scheduled for Java 8. So you'll be using APIs that will become core Java APIs.

EDIT: The Java date/time classes introduced with Java 8 are now the preferred solution, if you can migrate to Java 8

C++, copy set to vector

std::copy cannot be used to insert into an empty container. To do that, you need to use an insert_iterator like so:

std::set<double> input;
input.insert(5);
input.insert(6);

std::vector<double> output;
std::copy(input.begin(), input.end(), inserter(output, output.begin())); 

Copy/duplicate database without using mysqldump

Actually i wanted to achieve exactly that in PHP but none of the answers here were very helpful so here's my – pretty straightforward – solution using MySQLi:

// Database variables

$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '1234';

$DB_SRC = 'existing_db';
$DB_DST = 'newly_created_db';



// MYSQL Connect

$mysqli = new mysqli( $DB_HOST, $DB_USER, $DB_PASS ) or die( $mysqli->error );



// Create destination database

$mysqli->query( "CREATE DATABASE $DB_DST" ) or die( $mysqli->error );



// Iterate through tables of source database

$tables = $mysqli->query( "SHOW TABLES FROM $DB_SRC" ) or die( $mysqli->error );

while( $table = $tables->fetch_array() ): $TABLE = $table[0];


    // Copy table and contents in destination database

    $mysqli->query( "CREATE TABLE $DB_DST.$TABLE LIKE $DB_SRC.$TABLE" ) or die( $mysqli->error );
    $mysqli->query( "INSERT INTO $DB_DST.$TABLE SELECT * FROM $DB_SRC.$TABLE" ) or die( $mysqli->error );


endwhile;

Latest jQuery version on Google's CDN

To use the latest jquery version hosted by Google

Humans:

  1. https://developers.google.com/speed/libraries/#jquery

  2. Get the snippet:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  1. Put it in your code.
  2. Make sure it works.

Bots:

  1. Wait for a human to do it.

getting the screen density programmatically in android?

public static String getDensity(Context context) {
    String r;
    DisplayMetrics metrics = new DisplayMetrics();

    if (!(context instanceof Activity)) {
        r = "hdpi";
    } else {
        Activity activity = (Activity) context;
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

        if (metrics.densityDpi <= DisplayMetrics.DENSITY_LOW) {
            r = "ldpi";
        } else if (metrics.densityDpi <= DisplayMetrics.DENSITY_MEDIUM) {
            r = "mdpi";
        } else {
            r = "hdpi";
        }
    }

    return r;
}

Java JDBC connection status

If you are using MySQL

public static boolean isDbConnected() {
    final String CHECK_SQL_QUERY = "SELECT 1";
    boolean isConnected = false;
    try {
        final PreparedStatement statement = db.prepareStatement(CHECK_SQL_QUERY);
        isConnected = true;
    } catch (SQLException | NullPointerException e) {
        // handle SQL error here!
    }
    return isConnected;
}

I have not tested with other databases. Hope this is helpful.

Phone: numeric keyboard for text input

I couldn't find a type that worked best for me in all situations: I needed to default to numeric entry (entry of "7.5" for example) but also at certain times allow text ("pass" for example). Users wanted a numeric keypad (entry of 7.5 for example) but occasional text entry was required ("pass" for example).

Rather what I did was to add a checkbox to the form and allow the user to toggle my input (id="inputSresult") between type="number" and type="text".

<input type="number" id="result"... >
<label><input id="cbAllowTextResults" type="checkbox" ...>Allow entry of text results.</label>

Then I wired a click handler to the checkbox that toggles the type between text and number based on whether the checkbox above is checked:

$(document).ready(function () {
    var cb = document.getElementById('cbAllowTextResults');
    cb.onclick = function (event) {
        if ($("#cbAllowTextResults").is(":checked"))
            $("#result").attr("type", "text");
        else
            $("#result").attr("type", "number");

    }
});

This worked out well for us.

error::make_unique is not a member of ‘std’

If you have latest compiler, you can change the following in your build settings:

 C++ Language Dialect    C++14[-std=c++14]

This works for me.

How to get the path of the batch script in Windows?

That would be the %CD% variable.

@echo off
echo %CD%

%CD% returns the current directory the batch script is in.

If input value is blank, assign a value of "empty" with Javascript

You can do this:

var getValue  = function (input, defaultValue) {
    return input.value || defaultValue;
};

How to load Spring Application Context

I am using in the way and it is working for me.

public static void main(String[] args) {
    new CarpoolDBAppTest();

}

public CarpoolDBAppTest(){
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    Student stud = (Student) context.getBean("yourBeanId");
}

Here Student is my classm you will get the class matching yourBeanId.

Now work on that object with whatever operation you want to do.

Installing mysql-python on Centos

For centos7 I required: sudo yum install mysql-devel gcc python-pip python-devel sudo pip install mysql-python

So, gcc and mysql-devel (rather than mysql) were important

Create Map in Java

With the newer Java versions (i.e., Java 9 and forwards) you can use :

Map.of(1, new Point2D.Double(50, 50), 2, new Point2D.Double(100, 50), ...)

generically:

Map.of(Key1, Value1, Key2, Value2, KeyN, ValueN)

Bear in mind however that Map.of only works for at most 10 entries, if you have more than 10 entries that you can use :

Map.ofEntries(entry(1, new Point2D.Double(50, 50)), entry(2,  new Point2D.Double(100, 50)), ...);

Is there a way to make numbers in an ordered list bold?

If you are using Bootstrap 4:

<ol class="font-weight-bold">
    <li><span class="font-weight-light">Curabitur aliquet quam id dui posuere blandit.</span></li>
    <li><span class="font-weight-light">Curabitur aliquet quam id dui posuere blandit.</span></li>
</ol>

REACT - toggle class onclick

Here is a code I came Up with:

import React, {Component} from "react";
import './header.css'

export default class Header extends Component{
    state = {
        active : false
    };


    toggleMenuSwitch = () => {
        this.setState((state)=>{
            return{
                active: !state.active
            }
        })
    };
    render() {
        //destructuring
        const {active} = this.state;

        let className = 'toggle__sidebar';

        if(active){
            className += ' active';
        }

        return(
            <header className="header">
                <div className="header__wrapper">
                    <div className="header__cell header__cell--logo opened">
                        <a href="#" className="logo">
                            <img src="https://www.nrgcrm.olezzek.id.lv/images/logo.svg" alt=""/>
                        </a>
                        <a href="#" className={className}
                           onClick={ this.toggleMenuSwitch }
                           data-toggle="sidebar">
                            <i></i>
                        </a>
                    </div>
                    <div className="header__cell">

                    </div>
                </div>
            </header>
        );
    };
};

Show hide divs on click in HTML and CSS without jQuery

I like Roko's answer, and added a few lines to it so that you get a triangle that points right when the element is hidden, and down when it is displayed:

.collapse { font-weight: bold; display: inline-block; }
.collapse + input:after { content: " \25b6"; display: inline-block; }
.collapse + input:checked:after { content: " \25bc"; display: inline-block; }
.collapse + input { display: inline-block; -webkit-appearance: none; -o-appearance:none; -moz-appearance:none;  }
.collapse + input + * { display: none; }
.collapse + input:checked + * { display: block; }

How to define a relative path in java

 public static void main(String[] args) {
        Properties prop = new Properties();
        InputStream input = null;
        try {
            File f=new File("config.properties");
            input = new FileInputStream(f.getPath());
            prop.load(input);
            System.out.println(prop.getProperty("name"));
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

You can also use
Path path1 =FileSystems.getDefault().getPath(System.getProperty("user.home"), "downloads", "somefile.txt");

Is there a Pattern Matching Utility like GREP in Windows?

I'll add my $0.02 to this thread. dnGREP is a great open source grep tool for windows that supports undo, windows explorer integration, search inside PDFs, zips, DOCs and bunch of other stuff...

JavaScript string with new line - but not using \n

The reason it is not working is because javascript strings must be terminated before the next newline character (not a \n obviously). The reason \n exists is to allow developers an easy way to put the newline character (ASCII: 10) into their strings.

When you have a string which looks like this:

//Note lack of terminating double quote
var foo = "Bob 

Your code will have a syntax error at that point and cease to run.

If you wish to have a string which spans multiple lines, you may insert a backslash character '\' just before you terminate the line, like so:

//Perfectly valid code
var foo = "Bob \
is \
cool.";

However that string will not contain \n characters in the positions where the string was broken into separate lines. The only way to insert a newline into a string is to insert a character with a value of 10, the easiest way of which is the \n escape character.

var foo = "Bob\nis\ncool.";

ORA-28000: the account is locked error getting frequently

Check the PASSWORD_LOCK_TIME parameter. If it is set to 1 then you won't be able to unlock the password for 1 day even after you issue the alter user unlock command.

Find specific string in a text file with VBS script

I'd recommend using a regular expressions instead of string operations for this:

Set fso = CreateObject("Scripting.FileSystemObject")

filename = "C:\VBS\filediprova.txt"

newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"

Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global  = False
re.IgnoreCase = True

text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")

The regular expression will match a line feed (\n) followed by a line containing the string Test Case followed by a number (\d), and the replacement will prepend that with the text you want to insert (variable newtext). Setting re.Global = False makes the replacement stop after the first match.

If the line breaks in your text file are encoded as CR-LF (carriage return + line feed) you'll have to change \n into \r\n and vbLf into vbCrLf.

If you have to modify several text files, you could do it in a loop like this:

For Each f In fso.GetFolder("C:\VBS").Files
  If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
    text = f.OpenAsTextStream.ReadAll
    f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
  End If
Next

npm global path prefix

Extending your PATH with:

export PATH=/usr/local/share/npm/bin:$PATH

isn't a terrible idea. Having said that, you shouldn't have to do it.

Run this:

npm config get prefix

The default on OS X is /usr/local, which means that npm will symlink binaries into /usr/local/bin, which should already be on your PATH (especially if you're using Homebrew).

So:

  1. npm config set prefix /usr/local if it's something else, and
  2. Don't use sudo with npm! According to the jslint docs, you should just be able to npm install it.

If you installed npm as sudo (sudo brew install), try reinstalling it with plain ol' brew install. Homebrew is supposed to help keep you sudo-free.

How to delete all the rows in a table using Eloquent?

I wanted to add another option for those getting to this thread via Google. I needed to accomplish this, but wanted to retain my auto-increment value which truncate() resets. I also didn't want to use DB:: anything because I wanted to operate directly off of the model object. So, I went with this:

Model::whereNotNull('id')->delete();

Obviously the column will have to actually exists, but in a standard, out-of-the-box Eloquent model, the id column exists and is never null. I don't know if this is the best choice, but it works for my purposes.

How can I determine the direction of a jQuery scroll event?

Scroll Event

The scroll event behaves oddly in FF (it is fired a lot of times because of the smoothness scrolling) but it works.

Note: The scroll event actually is fired when dragging the scroll bar, using cursor keys or mousewheel.

//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
    padding: "5px 7px",
    background: "#e9e9e9",
    position: "fixed",
    bottom: "15px",
    left: "35px"
});

//binds the "scroll" event
$(window).scroll(function (e) {
    var target = e.currentTarget,
        self = $(target),
        scrollTop = window.pageYOffset || target.scrollTop,
        lastScrollTop = self.data("lastScrollTop") || 0,
        scrollHeight = target.scrollHeight || document.body.scrollHeight,
        scrollText = "";

    if (scrollTop > lastScrollTop) {
        scrollText = "<b>scroll down</b>";
    } else {
        scrollText = "<b>scroll up</b>";
    }

    $("#test").html(scrollText +
      "<br>innerHeight: " + self.innerHeight() +
      "<br>scrollHeight: " + scrollHeight +
      "<br>scrollTop: " + scrollTop +
      "<br>lastScrollTop: " + lastScrollTop);

    if (scrollHeight - scrollTop === self.innerHeight()) {
      console.log("? End of scroll");
    }

    //saves the current scrollTop
    self.data("lastScrollTop", scrollTop);
});

Wheel Event

You also may take a look at MDN, it exposes a great information about the Wheel Event.

Note: The wheel event is fired only when using the mousewheel; cursor keys and dragging the scroll bar does not fire the event.

I read the document and the example: Listening to this event across browser
and after some tests with FF, IE, chrome, safari, I ended up with this snippet:

//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
    padding: "5px 7px",
    background: "#e9e9e9",
    position: "fixed",
    bottom: "15px",
    left: "15px"
});

//attach the "wheel" event if it is supported, otherwise "mousewheel" event is used
$("html").on(("onwheel" in document.createElement("div") ? "wheel" : "mousewheel"), function (e) {
    var evt = e.originalEvent || e;

    //this is what really matters
    var deltaY = evt.deltaY || (-1 / 40 * evt.wheelDelta), //wheel || mousewheel
        scrollTop = $(this).scrollTop() || $("body").scrollTop(), //fix safari
        scrollText = "";

    if (deltaY > 0) {
        scrollText = "<b>scroll down</b>";
    } else {
        scrollText = "<b>scroll up</b>";
    }

    //console.log("Event: ", evt);
    $("#test").html(scrollText +
      "<br>clientHeight: " + this.clientHeight +
      "<br>scrollHeight: " + this.scrollHeight +
      "<br>scrollTop: " + scrollTop +
      "<br>deltaY: " + deltaY);
});

Two Divs on the same row and center align both of them

I would vote against display: inline-block since its not supported across browsers, IE < 8 specifically.

.wrapper {
    width:500px; /* Adjust to a total width of both .left and .right */
    margin: 0 auto;
}
.left {
    float: left;
    width: 49%; /* Not 50% because of 1px border. */
    border: 1px solid #000;
}
.right {
    float: right;
    width: 49%; /* Not 50% because of 1px border. */
    border: 1px solid #F00;
}

<div class="wrapper">
    <div class="left">Div 1</div>
    <div class="right">Div 2</div>
</div>

EDIT: If no spacing between the cells is desired just change both .left and .right to use float: left;

What's the quickest way to multiply multiple cells by another number?

To multiply a column of numbers with a constant(same number), I have done like this.

Let C2 to C12 be different numbers which need to be multiplied by a single number (constant). Then type the numbers from C2 to C12.

In D2 type 1 (unity) and in E2 type formula =PRODUCT(C2:C12,CONSTANT). SELECT RIGHT ICON TO APPLY. NOW DRAG E2 THROUGH E12. YOU HAVE DONE IT.

C       D       E=PRODUCT(C2:C12,20)

25  1   500
30      600
35      700
40      800
45      900
50      1000
55      1100
60      1200
65      1300
70      1400
75      1500

How to raise a ValueError?

>>> def contains(string, char):
...     for i in xrange(len(string) - 1, -1, -1):
...         if string[i] == char:
...             return i
...     raise ValueError("could not find %r in %r" % (char, string))
...
>>> contains('bababa', 'k')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in contains
ValueError: could not find 'k' in 'bababa'
>>> contains('bababa', 'a')
5
>>> contains('bababa', 'b')
4
>>> contains('xbababa', 'x')
0
>>>

Wildcards in a Windows hosts file

I could not find a prohibition in writing, but by convention, the Windows hosts file closely follows the UNIX hosts file, and you cannot put wildcard hostname references into that file.

If you read the man page, it says:

DESCRIPTION
     The hosts file contains information regarding the known hosts on the net-
     work.  For each host a single line should be present with the following
     information:

           Internet address
           Official host name
           Aliases

Although it does say,

     Host names may contain any printable character other than a field delim-
     iter, newline, or comment character.

that is not true from a practical level.

Basically, the code that looks at the /etc/hosts file does not support a wildcard entry.

The workaround is to create all the entries in advance, maybe use a script to put a couple hundred entries at once.

Install a Python package into a different directory using pip?

To pip install a library exactly where I wanted it, I navigated to the location I wanted the directory with the terminal then used

pip install mylibraryName -t . 

the logic of which I took from this page: https://cloud.google.com/appengine/docs/python/googlecloudstorageclient/download

Passing data from controller to view in Laravel

The best and easy way to pass single or multiple variables to view from controller is to use compact() method.

For passing single variable to view,

return view("user/regprofile",compact('students'));

For passing multiple variable to view,

return view("user/regprofile",compact('students','teachers','others'));

And in view, you can easily loop through the variable,

@foreach($students as $student)
   {{$student}}
@endforeach

C# Checking if button was clicked

Click is an event that fires immediately after you release the mouse button. So if you want to check in the handler for button2.Click if button1 was clicked before, all you could do is have a handler for button1.Click which sets a bool flag of your own making to true.

private bool button1WasClicked = false;

private void button1_Click(object sender, EventArgs e)
{
    button1WasClicked = true;
}

private void button2_Click(object sender, EventArgs e)
{
    if (textBox2.Text == textBox3.Text && button1WasClicked)
    { 
        StreamWriter myWriter = File.CreateText(@"c:\Program Files\text.txt");
        myWriter.WriteLine(textBox1.Text);
        myWriter.WriteLine(textBox2.Text);
        button1WasClicked = false;
    }
}

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

I know this question is already been answered but for new comers those two solutions may help:

  1. Make sure your gmail is allowing low secure apps to sign in, you can turn it on here: https://www.google.com/settings/security/lesssecureapps.
  2. Change your password.

Best practices for circular shift (rotate) operations in C++

--- Substituting RLC in 8051 C for speed --- Rotate left carry
Here is an example using RLC to update a serial 8 bit DAC msb first:
                               (r=DACVAL, P1.4= SDO, P1.5= SCLK)
MOV     A, r
?1:
MOV     B, #8
RLC     A
MOV     P1.4, C
CLR     P1.5
SETB    P1.5
DJNZ    B, ?1

Here is the code in 8051 C at its fastest:
sbit ACC_7  = ACC ^ 7 ; //define this at the top to access bit 7 of ACC
ACC     =   r;
B       =   8;  
do  {
P1_4    =   ACC_7;  // this assembles into mov c, acc.7  mov P1.4, c 
ACC     <<= 1;
P1_5    =   0;
P1_5    =   1;
B       --  ; 
    } while ( B!=0 );
The keil compiler will use DJNZ when a loop is written this way.
I am cheating here by using registers ACC and B in c code.
If you cannot cheat then substitute with:
P1_4    =   ( r & 128 ) ? 1 : 0 ;
r     <<=   1;
This only takes a few extra instructions.
Also, changing B for a local var char n is the same.
Keil does rotate ACC left by ADD A, ACC which is the same as multiply 2.
It only takes one extra opcode i think.
Keeping code entirely in C keeps things simpler sometimes.

CSS transition when class removed

CSS transitions work by defining two states for the object using CSS. In your case, you define how the object looks when it has the class "saved" and you define how it looks when it doesn't have the class "saved" (it's normal look). When you remove the class "saved", it will transition to the other state according to the transition settings in place for the object without the "saved" class.

If the CSS transition settings apply to the object (without the "saved" class), then they will apply to both transitions.

We could help more specifically if you included all relevant CSS you're using to with the HTML you've provided.

My guess from looking at your HTML is that your transition CSS settings only apply to .saved and thus when you remove it, there are no controls to specify a CSS setting. You may want to add another class ".fade" that you leave on the object all the time and you can specify your CSS transition settings on that class so they are always in effect.

Func delegate with no return type

Try System.Func<T> and System.Action

You need to use a Theme.AppCompat theme (or descendant) with this activity

Do not forget to clean the project after VCS Local History restore

Tensorflow installation error: not a supported wheel on this platform

This may mean that you are installing the wrong pre-build binary

since my CPU on Ubuntu 18.04 my download url was: https://github.com/lakshayg/tensorflow-build/releases/download/tf1.12.0-ubuntu18.04-py2-py3/tensorflow-1.12.0-cp36-cp36m-linux_x86_64.whl

as it can be found on this github page: https://github.com/lakshayg/tensorflow-build

pip install --ignore-installed --upgrade <LOCAL PATH / BINARY-URL>

resolved the issue for me.

ASP.net vs PHP (What to choose)

This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You have a couple of options:

  1. Scope the domain down (see document.domain) in both the containing page and the iframe to the same thing. Then they will not be bound by 'same origin' constraints.

  2. Use postMessage which is supported by all HTML5 browsers for cross-domain communication.

How to link to a <div> on another page?

Create an anchor:

<a name="anchor" id="anchor"></a> 

then link to it:

<a href="http://server/page.html#anchor">Link text</a>

How to add google-services.json in Android?

For using Google SignIn in Android app, you need

google-services.json

which you can generate using the instruction mentioned here

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

How to create dictionary and add key–value pairs dynamically?

Since you've stated that you want a dictionary object (and not an array like I assume some understood) I think this is what you are after:

var input = [{key:"key1", value:"value1"},{key:"key2", value:"value2"}];

var result = {};

for(var i = 0; i < input.length; i++)
{
    result[input[i].key] = input[i].value;
}

console.log(result); // Just for testing

Invalid hook call. Hooks can only be called inside of the body of a function component

complementing the following comment

For those who use redux:

class AllowanceClass extends Component{
    ...
    render() {
        const classes = this.props.classes;
        ...
    }
}
    
const COMAllowanceClass = (props) =>
{
    const classes = useStyles();
    return (<AllowanceClass classes={classes} {...props} />);
};

const mapStateToProps = ({ InfoReducer }) => ({
    token: InfoReducer.token,
    user: InfoReducer.user,
    error: InfoReducer.error
});
export default connect(mapStateToProps, { actions })(COMAllowanceClass);

Find size of Git repository

If you use git LFS, git count-objects does not count your binaries, but only the pointers to them.

If your LFS files are managed by Artifactorys, you should use the REST API:

  • Get the www.jfrog.com API from any search engine
  • Look at Get Storage Summary Info

Error: package or namespace load failed for ggplot2 and for data.table

These steps work for me:

  1. Download the Rcpp manually from WebSite (https://cran.r-project.org/web/packages/Rcpp/index.html)
  2. unzip the folder/files to "Rcpp" folder
  3. Locate the "library" folder under R install directory Ex: C:\R\R-3.3.1\library
  4. Copy the "Rcpp" folder to Library folder.

Good to go!!!

library(Rcpp)
library(ggplot2) 

Returning a stream from File.OpenRead()

You forgot to reset the position of the memory stream:

private void Test()
{            
    System.IO.MemoryStream data = new System.IO.MemoryStream();
    System.IO.Stream str = TestStream();

    str.CopyTo(data);
    // Reset memory stream
    data.Seek(0, SeekOrigin.Begin);
    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);                       
}

Update:

There is one more thing to note: It usually pays not to ignore the return values of methods. A more robust implementation should check how many bytes have been read after the call returns:

private void Test()
{            
    using(MemoryStream data = new MemoryStream())
    {
        using(Stream str = TestStream())
        {
           str.CopyTo(data);
        }
        // Reset memory stream
        data.Seek(0, SeekOrigin.Begin);
        byte[] buf = new byte[data.Length];
        int bytesRead = data.Read(buf, 0, buf.Length);

        Debug.Assert(bytesRead == data.Length, 
                    String.Format("Expected to read {0} bytes, but read {1}.",
                        data.Length, bytesRead));
    }                     
}

Pandas sum by groupby, but exclude certain columns

The agg function will do this for you. Pass the columns and function as a dict with column, output:

df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]})  # Added example for two output columns from a single input column

This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.

To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:

df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})

How to remove folders with a certain name

This also works - it will remove all the folders called "a" and their contents:

rm -rf `find -type d -name a`

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

delete the module which is identified in .Net error message , 1 down vote

In Windows server 2012. Go to ISS -> Modules -> Remove the ServiceModel3-0. (without number worked for me)

Show/hide image with JavaScript

You can do this with jquery just visit http://jquery.com/ to get the link then do something like this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').show('slow');
      });
   });
</script>

or if you would like the link to turn the image on and off do this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none;" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').toggle();
      });
   });
</script>

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

current/duration time of html5 video?

https://www.w3schools.com/tags/av_event_timeupdate.asp

// Get the <video> element with id="myVideo"
var vid = document.getElementById("myVideo");

// Assign an ontimeupdate event to the <video> element, and execute a function if the current playback position has changed
vid.ontimeupdate = function() {myFunction()};

function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
    document.getElementById("demo").innerHTML = vid.currentTime;
}

Change priorityQueue to max priorityqueue

Using lamda, just multiple the result with -1 to get max priority queue.

PriorityQueue<> q = new PriorityQueue<Integer>(
                       (a,b) ->  -1 * Integer.compare(a, b)
                    );

Programmatically get height of navigation bar

Here is the beginning of my response to your update:

Why does the content height of my UIWebView not change with rotation?.

Could it be that because your auto resize doesn't have the autoresizingMask for all directions?

Another suggestion before I come back for this, could you use a toolbar for your needs. It's a little simpler, will always be on the bottom, auto-rotates/positions. You can hide/show it at will etc. Kind of like this: http://cdn.artoftheiphone.com/wp-content/uploads/2009/01/yellow-pages-iphone-app-2.jpg

You may have looked at that option, but just throwing it out there.

Another idea, could you possibly detect what orientation you are rotating from, and just place the button programmatically to adjust for the tab bar. (This is possible with code)

How to parse XML using shellscript?

A rather new project is the xml-coreutils package featuring xml-cat, xml-cp, xml-cut, xml-grep, ...

http://xml-coreutils.sourceforge.net/contents.html

How do you create a remote Git branch?

Create a new branch locally based on the current branch:

git checkout -b newbranch

Commit any changes as you normally would. Then, push it upstream:

git push -u origin HEAD

This is a shortcut to push the current branch to a branch of the same name on origin and track it so that you don't need to specify origin HEAD in the future.

Correctly determine if date string is a valid date in that format

Tested Regex solution:

    function isValidDate($date)
    {
            if (preg_match("/^(((((1[26]|2[048])00)|[12]\d([2468][048]|[13579][26]|0[48]))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|[12]\d))))|((([12]\d([02468][1235679]|[13579][01345789]))|((1[1345789]|2[1235679])00))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|1\d|2[0-8])))))$/", $date)) {
                    return $date;
            }
            return null;
    }

This will return null if the date is invalid or is not yyyy-mm-dd format, otherwise it will return the date.

Change window location Jquery

you can use the new push/pop state functions in the history manipulation API.

How to get row number from selected rows in Oracle

you can just do

select rownum, l.* from student  l where name like %ram%

this assigns the row number as the rows are fetched (so no guaranteed ordering of course).

if you wanted to order first do:

select rownum, l.*
  from (select * from student l where name like %ram% order by...) l;

Trigger insert old values- values that was updated

In your trigger, you have two pseudo-tables available, Inserted and Deleted, which contain those values.

In the case of an UPDATE, the Deleted table will contain the old values, while the Inserted table contains the new values.

So if you want to log the ID, OldValue, NewValue in your trigger, you'd need to write something like:

CREATE TRIGGER trgEmployeeUpdate
ON dbo.Employees AFTER UPDATE
AS 
   INSERT INTO dbo.LogTable(ID, OldValue, NewValue)
      SELECT i.ID, d.Name, i.Name
      FROM Inserted i
      INNER JOIN Deleted d ON i.ID = d.ID

Basically, you join the Inserted and Deleted pseudo-tables, grab the ID (which is the same, I presume, in both cases), the old value from the Deleted table, the new value from the Inserted table, and you store everything in the LogTable

How to select rows for a specific date, ignoring time in SQL Server

Try this:

true
select cast(salesDate as date) [date] from sales where salesDate = '2010/11/11'
false
select cast(salesDate as date) [date] from sales where salesDate = '11/11/2010'

How to get the selected index of a RadioGroup in Android

Kotlin:

val selectedIndex = radioButtonGroup?.indexOfChild(
  radioButtonGroup?.findViewById(
    radioButtonGroup.getCheckedRadioButtonId())
)

Set default host and port for ng serve in config file

enter image description here

Only one thing you have to do. Type this in in your Command Prompt: ng serve --port 4021 [or any other port you want to assign eg: 5050, 5051 etc ]. No need to do changes in files.

Can you Run Xcode in Linux?

It was weird that no one suggested KVM.

It is gonna provide you almost native performance and it is built-in Linux. Go and check it out.

you will feel like u are using mac only and then install Xcode there u may even choose to directly boot into the OSX GUI instead of Linux one on startup

font-weight is not working properly?

font-weight can also fail to work if the font you are using does not have those weights in existence – you will often hit this when embedding custom fonts. In those cases the browser will likely round the number to the closest weight that it does have available.

For example, if I embed the following font...

@font-face {
    font-family: 'Nexa';
    src: url(...);
    font-weight: 300;
    font-style: normal;
}

Then I will not be able to use anything other than a weight of 300. All other weights will revert to 300, unless I specify additional @font-face declarations with those additional weights.

How to convert an array into an object using stdClass()

To convert array to object using stdClass just add (object) to array u declare.

EX:

echo $array['value'];
echo $object->value;

to convert object to array

$obj = (object)$array;

to convert array to object

$arr = (array)$object

with these methods you can swap between array and object very easily.


Another method is to use json

$object = json_decode(json_encode($array), FALSE);

But this is a much more memory intensive way to do and is not supported by versions of PHP <= 5.1

Values of disabled inputs will not be submitted

select controls are still clickable even on readonly attrib

if you want to still disable the control but you want its value posted. You might consider creating a hidden field. with the same value as your control.

then create a jquery, on select change

$('#your_select_id').change(function () {
    $('#your_hidden_selectid').val($('#your_select_id').val());
});

How to show live preview in a small popup of linked page on mouse over on link?

I have done a little plugin to show a iframe window to preview a link. Still in beta version. Maybe it fits your case: https://github.com/Fischer-L/previewbox.

open() in Python does not create a file if it doesn't exist

So You want to write data to a file, but only if it doesn’t already exist?.

This problem is easily solved by using the little-known x mode to open() instead of the usual w mode. For example:

 >>> with open('somefile', 'wt') as f:
 ...     f.write('Hello\n')
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello\n')
...
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

If the file is binary mode, use mode xb instead of xt.

Is there any boolean type in Oracle databases?

Nope.

Can use:

IS_COOL NUMBER(1,0)

1 - true
0 - false

--- enjoy Oracle

Or use char Y/N as described here

Return array in a function

This is a fairly old question, but I'm going to put in my 2 cents as there are a lot of answers, but none showing all possible methods in a clear and concise manner (not sure about the concise bit, as this got a bit out of hand. TL;DR ).

I'm assuming that the OP wanted to return the array that was passed in without copying as some means of directly passing this to the caller to be passed to another function to make the code look prettier.

However, to use an array like this is to let it decay into a pointer and have the compiler treat it like an array. This can result in subtle bugs if you pass in an array like, with the function expecting that it will have 5 elements, but your caller actually passes in some other number.

There a few ways you can handle this better. Pass in a std::vector or std::array (not sure if std::array was around in 2010 when the question was asked). You can then pass the object as a reference without any copying/moving of the object.

std::array<int, 5>& fillarr(std::array<int, 5>& arr)
{
    // (before c++11)
    for(auto it = arr.begin(); it != arr.end(); ++it)
    { /* do stuff */ }

    // Note the following are for c++11 and higher.  They will work for all
    // the other examples below except for the stuff after the Edit.

    // (c++11 and up)
    for(auto it = std::begin(arr); it != std::end(arr); ++it)
    { /* do stuff */ }

    // range for loop (c++11 and up)
    for(auto& element : arr)
    { /* do stuff */ }

    return arr;
}

std::vector<int>& fillarr(std::vector<int>& arr)
{
    for(auto it = arr.begin(); it != arr.end(); ++it)
    { /* do stuff */ }
    return arr;
}

However, if you insist on playing with C arrays, then use a template which will keep the information of how many items in the array.

template <size_t N>
int(&fillarr(int(&arr)[N]))[N]
{
    // N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
    for(int* it = arr; it != arr + N; ++it)
    { /* do stuff */ }
    return arr;
}

Except, that looks butt ugly, and super hard to read. I now use something to help with that which wasn't around in 2010, which I also use for function pointers:

template <typename T>
using type_t = T;

template <size_t N>
type_t<int(&)[N]> fillarr(type_t<int(&)[N]> arr)
{
    // N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
    for(int* it = arr; it != arr + N; ++it)
    { /* do stuff */ }
    return arr;
}

This moves the type where one would expect it to be, making this far more readable. Of course, using a template is superfluous if you are not going to use anything but 5 elements, so you can of course hard code it:

type_t<int(&)[5]> fillarr(type_t<int(&)[5]> arr)
{
    // Prefer using the compiler to figure out how many elements there are
    // as it reduces the number of locations where you have to change if needed.
    for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
    { /* do stuff */ }
    return arr;
}

As I said, my type_t<> trick wouldn't have worked at the time this question was asked. The best you could have hoped for back then was to use a type in a struct:

template<typename T>
struct type
{
  typedef T type;
};

typename type<int(&)[5]>::type fillarr(typename type<int(&)[5]>::type arr)
{
    // Prefer using the compiler to figure out how many elements there are
    // as it reduces the number of locations where you have to change if needed.
    for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
    { /* do stuff */ }
    return arr;
}

Which starts to look pretty ugly again, but at least is still more readable, though the typename may have been optional back then depending on the compiler, resulting in:

type<int(&)[5]>::type fillarr(type<int(&)[5]>::type arr)
{
    // Prefer using the compiler to figure out how many elements there are
    // as it reduces the number of locations where you have to change if needed.
    for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
    { /* do stuff */ }
    return arr;
}

And then of course you could have specified a specific type, rather than using my helper.

typedef int(&array5)[5];

array5 fillarr(array5 arr)
{
    // Prefer using the compiler to figure out how many elements there are
    // as it reduces the number of locations where you have to change if needed.
    for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
    { /* do stuff */ }
    return arr;
}

Back then, the free functions std::begin() and std::end() didn't exist, though could have been easily implemented. This would have allowed iterating over the array in a safer manner as they make sense on a C array, but not a pointer.

As for accessing the array, you could either pass it to another function that takes the same parameter type, or make an alias to it (which wouldn't make much sense as you already have the original in that scope). Accessing a array reference is just like accessing the original array.

void other_function(type_t<int(&)[5]> x) { /* do something else */ }

void fn()
{
    int array[5];
    other_function(fillarr(array));
}

or

void fn()
{
    int array[5];
    auto& array2 = fillarr(array); // alias. But why bother.
    int forth_entry = array[4];
    int forth_entry2 = array2[4]; // same value as forth_entry
}

To summarize, it is best to not allow an array decay into a pointer if you intend to iterate over it. It is just a bad idea as it keeps the compiler from protecting you from shooting yourself in the foot and makes your code harder to read. Always try and help the compiler help you by keeping the types as long as possible unless you have a very good reason not to do so.

Edit

Oh, and for completeness, you can allow it to degrade to a pointer, but this decouples the array from the number of elements it holds. This is done a lot in C/C++ and is usually mitigated by passing the number of elements in the array. However, the compiler can't help you if you make a mistake and pass in the wrong value to the number of elements.

// separate size value
int* fillarr(int* arr, size_t size)
{
    for(int* it = arr; it != arr + size; ++it)
    { /* do stuff */ }
    return arr;
}

Instead of passing the size, you can pass the end pointer, which will point to one past the end of your array. This is useful as it makes for something that is closer to the std algorithms, which take a begin and and end pointer, but what you return is now only something that you must remember.

// separate end pointer
int* fillarr(int* arr, int* end)
{
    for(int* it = arr; it != end; ++it)
    { /* do stuff */ }
    return arr;
}

Alternatively, you can document that this function will only take 5 elements and hope that the user of your function doesn't do anything stupid.

// I document that this function will ONLY take 5 elements and 
// return the same array of 5 elements.  If you pass in anything
// else, may nazal demons exit thine nose!
int* fillarr(int* arr)
{
    for(int* it = arr; it != arr + 5; ++it)
    { /* do stuff */ }
    return arr;
}

Note that the return value has lost it's original type and is degraded to a pointer. Because of this, you are now on your own to ensure that you are not going to overrun the array.

You could pass a std::pair<int*, int*>, which you can use for begin and end and pass that around, but then it really stops looking like an array.

std::pair<int*, int*> fillarr(std::pair<int*, int*> arr)
{
    for(int* it = arr.first; it != arr.second; ++it)
    { /* do stuff */ }
    return arr; // if you change arr, then return the original arr value.
}

void fn()
{
    int array[5];
    auto array2 = fillarr(std::make_pair(&array[0], &array[5]));

    // Can be done, but you have the original array in scope, so why bother.
    int fourth_element = array2.first[4];
}

or

void other_function(std::pair<int*, int*> array)
{
    // Can be done, but you have the original array in scope, so why bother.
    int fourth_element = array2.first[4];
}

void fn()
{
    int array[5];
    other_function(fillarr(std::make_pair(&array[0], &array[5])));
}

Funny enough, this is very similar to how std::initializer_list work (c++11), but they don't work in this context.

Matplotlib color according to class labels

Assuming that you have your data in a 2d array, this should work:

import numpy
import pylab
xy = numpy.zeros((2, 1000))
xy[0] = range(1000)
xy[1] = range(1000)
colors = [int(i % 23) for i in xy[0]]
pylab.scatter(xy[0], xy[1], c=colors)
pylab.show()

You can also set a cmap attribute to control which colors will appear through use of a colormap; i.e. replace the pylab.scatter line with:

pylab.scatter(xy[0], xy[1], c=colors, cmap=pylab.cm.cool)

A list of color maps can be found here

Export Postgresql table data using pgAdmin

In the pgAdmin4, Right click on table select backup like this

enter image description here

After that into the backup dialog there is Dump options tab into that there is section queries you can select Use Insert Commands which include all insert queries as well in the backup.

enter image description here

What is the command to exit a Console application in C#?

Several options, by order of most appropriate way:

  1. Return an int from the Program.Main method
  2. Throw an exception and don't handle it anywhere (use for unexpected error situations)
  3. To force termination elsewhere, System.Environment.Exit (not portable! see below)

Edited 9/2013 to improve readability

Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an int return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.

Another point against using Evironment.Exit - even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes Environment.Exit irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what Environment.Exit does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.

Android Open External Storage directory(sdcard) for storing file

Try using

new File(Environment.getExternalStorageDirectory(),"somefilename");

And don't forget to add WRITE_EXTERNAL STORAGE and READ_EXTERNAL STORAGE permissions

What's the Use of '\r' escape sequence?

\r move the cursor to the begin of the line.

Line breaks are managed differently on different systems. Some only use \n (line feed, e.g. Unix), some use (\r e.g. MacOS before OS X afaik) and some use \r\n (e.g. Windows afaik).

Set cookie and get cookie with JavaScript

These are much much better references than w3schools (the most awful web reference ever made):

Examples derived from these references:

// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

The Mozilla reference even has a nice cookie library you can use.

How to set focus on a view when a layout is created and displayed?

This works:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

The onunload event is not called in all browsers. Worse, you cannot check the return value of onbeforeunload event. That prevents us from actually preforming a logout function.

However, you can hack around this.

Call logout first thing in the onbeforeunload event. then prompt the user. If the user cancels their logout, automatically login them back in, by using the onfocus event. Kinda backwards, but I think it should work.

'use strict';

var reconnect = false;

window.onfocus = function () {
  if (reconnect) {
    reconnect = false;
    alert("Perform an auto-login here!");
  }
};

window.onbeforeunload = function () {
  //logout();
  var msg = "Are you sure you want to leave?";
  reconnect = true;
  return msg;
};

Neither BindingResult nor plain target object for bean name available as request attr

I worked on this same issue and I am sure I have found out the exact reason for it.

Neither BindingResult nor plain target object for bean name 'command' available as request attribute

If your successView property value (name of jsp page) is the same as your input page name, then second value of ModelAndView constructor must be match with the commandName of the input page.

E.g.

index.jsp

<html>
<body>
    <table>
        <tr><td><a href="Login.html">Login</a></td></tr>
    </table>
</body>
</html>

dispatcher-servlet.xml

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>
<bean id="urlMapping"
    class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="urlMap">
        <map>              
            <entry key="/Login.html">
                <ref bean="userController"/>
            </entry>
        </map>          
    </property>             
</bean>     
 <bean id="userController" class="controller.AddCountryFormController">     
       <property name="commandName"><value>country</value></property>
       <property name="commandClass"><value>controller.Country</value></property>        
       <property name="formView"><value>countryForm</value></property>
       <property name="successView"><value>countryForm</value></property>
   </bean>      

AddCountryFormController.java

package controller;

import javax.servlet.http.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;


public class AddCountryFormController extends SimpleFormController
{

    public AddCountryFormController(){
        setCommandName("Country.class");
    }

    protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors){

            Country country=(Country)command;

            System.out.println("calling onsubmit method !!!!!");

        return new ModelAndView(getSuccessView(),"country",country);

    }

}

Country.java

package controller;

public class Country
{
    private String countryName;

    public void setCountryName(String value){
        countryName=value;
    }

    public String getCountryName(){
        return countryName;
    }

}

countryForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
    <form:form commandName="country" method="POST" >
            <table>
                    <tr><td><form:input path="countryName"/></td></tr>
                    <tr><td><input type="submit" value="Save"/></td></tr>
            </table>
    </form:form>
</body>
<html>

Input page commandName="country" ModelAndView Constructor as return new ModelAndView(getSuccessView(),"country",country); Means inputpage commandName==ModeAndView(,"commandName",)

How to reset / remove chrome's input highlighting / focus border?

To remove the default focus, use the following in your default .css file :

:focus {outline:none;}

You can then control the focus border color either individually by element, or in the default .css:

:focus {outline:none;border:1px solid red}

Obviously replace red with your chosen hex code.

You could also leave the border untouched and control the background color (or image) to highlight the field:

:focus {outline:none;background-color:red}

:-)

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

if else in a list comprehension

[x+1 if x >= 45 else x+5 for x in l]

And for a reward, here is the comment, I wrote to remember this the first time I did this error:

Python's conditional expression is a if C else b and can't be used as:

[a for i in items if C else b]

The right form is:

[a if C else b for i in items]

Even though there is a valid form:

[a for i in items if C]

But that isn't the same as that is how you filter by C, but they can be combined:

[a if tC else b for i in items if fC]

Windows Batch Files: if else

you have to do like this...

if not "A%1" == "A"

if the input argument %1 is null, your code will have problem.

How to embed images in email

the third way is to base64 encode the image and place it in a data: url

example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACR0lEQVRYha1XvU4bQRD+bF/JjzEnpUDwCPROywPgB4h0PUWkFEkLposUIYyEU4N5AEpewnkDCiQcjBQpWLiLjk3DrnZnZ3buTv4ae25mZ+Z2Zr7daxljDGpg++Mv978Y5Nhc6+Di5tk9u7/bR3cjY9eOJnMUh3mg5y0roBjk+PF1F+1WCwCCJKTgpz9/ozjMg+ftVQQ/PtrB508f1OAcau8ADW5xfLRTOzgAZMPxTNy+YpDj6vaPGtxPgvpL7QwAtKXts8GqBveT8P1p5YF5x8nlo+n1p6bXn5ov3x9M+fZmjDGRXBXWH5X/Lv4FdqCLaLAmwX1/VKYJtIwJeYDO+dm3PSePJnO8vJbJhqN62hOUJ8QpoD1Au5kmIentr9TobAK04RyJEOazzjV9KokogVRwjvm6652kniYRJUBrTkft5bUEAGyuddzz7noHALBYls5O09skaE+4HdAYruobUz1FVI6qcy7xRFW95A915pzjiTp6zj7za6fB1lay1/Ssfa8/jRiLw/n1k9tizl7TS/aZ3xDakdqUByR/gDcF0qJV8QAXHACy+7v9wGA4ngWLVskDo8kcg4Ot8FpGa8PV0I7MyeWjq53f7Zrer3nyOLYJpJJowgN+g9IExNNQ4vLFskwyJtVrd8JoB7g3b4rz66dIpv7UHqg611xw/0om8QT7XXBx84zheCbKGui2U9n3p/YAlSVyqRqc+kt+mCyWJTSeoMGjOQciOQDXA6kjVTsL6JhpYHtA+wihPaGOWgLqnVACPQua4j8NK7bPLP4+qQAAAABJRU5ErkJggg==" width="32" height="32">

This Row already belongs to another table error when trying to add rows?

you can give some id to the columns and name it uniquely.

load Js file in HTML

If this is your detail.html I don't see where do you load detail.js? Maybe this

<script src="js/index.js"></script>

should be this

<script src="js/detail.js"></script>

?

Drop Down Menu/Text Field in one

I'd like to add a jQuery autocomplete based solution that does the job.

Step 1: Make the list fixed height and scrollable

Get the code from https://jqueryui.com/autocomplete/ "Scrollable" example, setting max height to the list of results so it behaves as a select box.

Step 2: Open the list on focus:

Display jquery ui auto-complete list on focus event

Step 3: Set minimum chars to 0 so it opens no matter how many chars are in the input

Final result:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Scrollable results</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  .ui-autocomplete {
    max-height: 100px;
    overflow-y: auto;
    /* prevent horizontal scrollbar */
    overflow-x: hidden;
  }
  /* IE 6 doesn't support max-height
   * we use height instead, but this forces the menu to always be this tall
   */
  * html .ui-autocomplete {
    height: 100px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
//      source: availableTags, // uncomment this and comment the following to have normal autocomplete behavior
      source: function (request, response) {
          response( availableTags);
      },
      minLength: 0
    }).focus(function(){
//        $(this).data("uiAutocomplete").search($(this).val()); // uncomment this and comment the following to have autocomplete behavior when opening
        $(this).data("uiAutocomplete").search('');
    });
  } );
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>


</body>
</html>

Check jsfiddle here:

https://jsfiddle.net/bao7fhm3/1/

How to change Label Value using javascript

This will work in Chrome

// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'

But after looking, labels doesn't seem to be widely supported..


You can use querySelector

// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'

How to check the function's return value if true or false

you're comparing the result against a string ('false') not the built-in negative constant (false)

just use

if(ValidateForm() == false) {

or better yet

if(!ValidateForm()) {

also why are you calling validateForm twice?

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

  1. session_start() must be at the top of your source, no html or other output befor!
  2. your can only send session_start() one time
  3. by this way if(session_status()!=PHP_SESSION_ACTIVE) session_start()

gulp command not found - error after installing gulp

  1. Be sure that you have gulp and gulp.cmd (use windows search)
  2. Copy the path of gulp.cmd (C:\Users\XXXX\AppData\Roaming\npm)
  3. Add this path to the Path envirement variable or edit PATH environment variable and add %APPDATA%\npm
  4. Reopen cmd.

Add %APPDATA%\npm to front of Path, not end of the Path.

How to create jobs in SQL Server Express edition

SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.

What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:

backup.bat:

sqlcmd -i backup.sql

backup.sql:

backup database TeamCity to disk = 'c:\backups\MyBackup.bak'

Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.

The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE queries instead.


If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.

It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:

How do I get started with the SQL Server Maintenance Solution on SQL Server Express?

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

  1. Download MaintenanceSolution.sql.

  2. Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.

  3. Create cmd files to execute the stored procedures; for example:
    sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txt

  4. In Windows Scheduled Tasks, create tasks to call the cmd files.

  5. Schedule the tasks.

  6. Start the tasks and verify that they are completing successfully.

How to disable the back button in the browser using JavaScript

Our approach is simple, but it works! :)

When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are on...simulating opening in new browser window without any history to go back to.

<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
    function logOut() {
        window.close = function () { 
            window.open('Default.aspx', '_blank'); 
        };
    }
</script>

PHP/MySQL: How to create a comment section in your website

It's a hard question to answer without more information. There are a number of things you should consider when looking at implementing commenting on an existing website.

How will you address the issue of spam? It doesn't matter how remote your website is, spammers WILL find it and they'll filled it up in no time. You may want to look into something like reCAPTCHA (http://recaptcha.net/).

The structure of the website may also influence how you implement your comments. Are the comments for the overall site, a particular product or page, or even another comment? You'll need to know the relationship between the content and the comment so you can properly define the relationship in the database. To put it another way, you know you want an email address, the comment, and whether it is approved or not, but now we need a way to identify what, if anything, the comment is linked to.

If your site is already established and built on a PHP framework (CakePHP for instance) you'll need to address how to integrate your code properly with what is already in place.

Lastly, there are a number of resources and tutorials on the web for PHP. If you do a quick google search for something along the lines of "PHP blog tutorial" I'm sure you'll find hundreds and the majority will show you step by step how to implement comments.

How do I get next month date from today's date and insert it in my database?

I think this is similar to kouton's answer, but this one just takes in a timeStamp and returns a timestamp SOMEWHERE in the next month. You could use date("m", $nextMonthDateN) from there.

function nextMonthTimeStamp($curDateN){ 
   $nextMonthDateN = $curDateN;
   while( date("m", $nextMonthDateN) == date("m", $curDateN) ){
      $nextMonthDateN += 60*60*24*27;
   }
   return $nextMonthDateN; //or return date("m", $nextMonthDateN);
}

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

there is a .bat script to start it (python 2.7).

c:\Python27\Lib\idlelib\idle.bat

android.view.InflateException: Binary XML file: Error inflating class fragment

FWIW: I was getting "Android.Views.InflateException Message=Binary XML file line #1: Binary XML file line #1: Error inflating class android.view.TextureView"

I am new to android form design. In trying to put a border on some buttons I found an SO post that inspired me to create buttonborder.xml that looks like:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@android:color/transparent" />
<stroke android:width="1dp" android:color="@android:color/white"/>

Then for each button I added

android:background="@drawable/buttonborder"

However, in my enthusiasm I also added it to a TextureView - which was my problem. When I removed the line from the TextureView, things worked.

CSS body background image fixed to full screen even when zooming in/out

I've used these techniques before and they both work well. If you read the pros/cons of each you can decide which is right for your site.

Alternatively you could use the full size background image jQuery plugin if you want to get away from the bugs in the above.

Is it better to use std::memcpy() or std::copy() in terms to performance?

All compilers I know will replace a simple std::copy with a memcpy when it is appropriate, or even better, vectorize the copy so that it would be even faster than a memcpy.

In any case: profile and find out yourself. Different compilers will do different things, and it's quite possible it won't do exactly what you ask.

See this presentation on compiler optimisations (pdf).

Here's what GCC does for a simple std::copy of a POD type.

#include <algorithm>

struct foo
{
  int x, y;    
};

void bar(foo* a, foo* b, size_t n)
{
  std::copy(a, a + n, b);
}

Here's the disassembly (with only -O optimisation), showing the call to memmove:

bar(foo*, foo*, unsigned long):
    salq    $3, %rdx
    sarq    $3, %rdx
    testq   %rdx, %rdx
    je  .L5
    subq    $8, %rsp
    movq    %rsi, %rax
    salq    $3, %rdx
    movq    %rdi, %rsi
    movq    %rax, %rdi
    call    memmove
    addq    $8, %rsp
.L5:
    rep
    ret

If you change the function signature to

void bar(foo* __restrict a, foo* __restrict b, size_t n)

then the memmove becomes a memcpy for a slight performance improvement. Note that memcpy itself will be heavily vectorised.

How do I select an element in jQuery by using a variable for the ID?

The shortest way would be:

$("#" + row_id)

Limiting the search to the body doesn't have any benefit.

Also, you should consider renaming your ids to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

I had the same issue - it turned out that i was using a deprecated angular-cli instead of @angular/cli. The latter was used by my dev team and it took me some time to notice that we were using a different versions of angular-cli.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

Loop through JSON in EJS

JSON.stringify(data).length return string length not Object length, you can use Object.keys.

<% for(var i=0; i < Object.keys(data).length ; i++) {%>

https://stackoverflow.com/a/14379528/3224296

How do you plot bar charts in gnuplot?

Simple bar graph:

bar graph

set boxwidth 0.5
set style fill solid
plot "data.dat" using 1:3:xtic(2) with boxes

data.dat:

0 label       100
1 label2      450
2 "bar label" 75

If you want to style your bars differently, you can do something like:

multi color bar graph

set style line 1 lc rgb "red"
set style line 2 lc rgb "blue"

set style fill solid
set boxwidth 0.5

plot "data.dat" every ::0::0 using 1:3:xtic(2) with boxes ls 1, \
     "data.dat" every ::1::2 using 1:3:xtic(2) with boxes ls 2

If you want to do multiple bars for each entry:

data.dat:

0     5
0.5   6


1.5   3
2     7


3     8
3.5   1

gnuplot:

set xtics ("label" 0.25, "label2" 1.75, "bar label" 3.25,)

set boxwidth 0.5
set style fill solid

plot 'data.dat' every 2    using 1:2 with boxes ls 1,\
     'data.dat' every 2::1 using 1:2 with boxes ls 2

barchart_multi

If you want to be tricky and use some neat gnuplot tricks:

Gnuplot has psuedo-columns that can be used as the index to color:

plot 'data.dat' using 1:2:0 with boxes lc variable

barchart_multi2

Further you can use a function to pick the colors you want:

mycolor(x) = ((x*11244898) + 2851770)
plot 'data.dat' using 1:2:(mycolor($0)) with boxes lc rgb variable

barchart_multi3

Note: you will have to add a couple other basic commands to get the same effect as the sample images.

Laravel: Auth::user()->id trying to get a property of a non-object

Check your route for the function in which you are using Auth::user(), For getting Auth::user() data the function should be inside web middleware Route::group(['middleware' => 'web'], function () {}); .

Can't execute jar- file: "no main manifest attribute"

If you are using the command line to assemble .jar it is possible to point to the main without adding Manifest file. Example:

jar cfve app.jar TheNameOfClassWithMainMethod *.class

(param "e" does that: TheNameOfClassWithMainMethod is a name of the class with the method main() and app.jar - name of executable .jar and *.class - just all classes files to assemble)

How to create a delay in Swift?

I agree with Palle that using dispatch_after is a good choice here. But you probably don't like the GCD calls as they are quite annoying to write. Instead you can add this handy helper:

public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) {
    let dispatchTime = DispatchTime.now() + seconds
    dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}

public enum DispatchLevel {
    case main, userInteractive, userInitiated, utility, background
    var dispatchQueue: DispatchQueue {
        switch self {
        case .main:                 return DispatchQueue.main
        case .userInteractive:      return DispatchQueue.global(qos: .userInteractive)
        case .userInitiated:        return DispatchQueue.global(qos: .userInitiated)
        case .utility:              return DispatchQueue.global(qos: .utility)
        case .background:           return DispatchQueue.global(qos: .background)
        }
    }
}

Now you simply delay your code on a background thread like this:

delay(bySeconds: 1.5, dispatchLevel: .background) { 
    // delayed code that will run on background thread
}

Delaying code on the main thread is even simpler:

delay(bySeconds: 1.5) { 
    // delayed code, by default run in main thread
}

If you prefer a Framework that also has some more handy features then checkout HandySwift. You can add it to your project via SwiftPM then use it exactly like in the examples above:

import HandySwift    

delay(by: .seconds(1.5)) { 
    // delayed code
}

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

In my case, I'm producing ms office file like word or excel, I run Win+R and execute dcomcnfg, in the DCOM Config, besides select OFFICE related name item (such as name contains Excel or Word or Office) and Open the properties, select Identity tab and select the interactive user. as this answer,

My error message show CLSID {000209FF-0000-0000-C000-000000000046}, so I have to try to find this specific CLSID in DCOM Config, and it does exsits, and I select it and follow same step set the interactive user, then it works.

Forbidden :You don't have permission to access /phpmyadmin on this server

You need to follow the following steps:

Find line that read follows

Require ip 127.0.0.1

Replace with your workstation IP address:

Require ip 10.1.3.53

Again find the following line:

Allow from 127.0.0.1

Replace as follows:

Allow from 10.1.3.53

Also find deny from all and comment it in the entire file.

Save and close the file.Restart Apache httpd server:

# service httpd restart

Edit: Since this is the selected answer and gets best visibility ... please also make sure that PHP is installed, otherwise you get same Forbidden error.

TypeError: 'list' object is not callable in python

Seems like you've shadowed the builtin name list pointing at a class by the same name pointing at its instance. Here is an example:

>>> example = list('easyhoss')  # here `list` refers to the builtin class
>>> list = list('abc')  # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss')  # here `list` refers to the instance
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: 'list' object is not callable

I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know, Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced:

  1. Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest namespaces. As I've already mentioned, namespaces are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace. In fact it's just a local namespace with respect to that particular module.

  2. Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a NameError. Builtin functions and classes reside in a special high-order namespace __builtins__. If you declare a variable named list in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is __builtins__). Similarly, suppose you create a variable var inside a function in your module, and another variable var in the module. Then, if you reference var inside the function, you will never get the global var, because there is a var in the local namespace - the interpreter has no need to search it elsewhere.

Here is a simple illustration.

>>> example = list("abc")  # Works fine
>>> 
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>> 
>>> example = list("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>> 
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name. 
>>> example = list("abc")  # It works.

So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.

You might as well be wondering what is a "callable", in which case you can read this post. list, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation (quite conveniently, the same page covers namespaces and scoping).

If you want to know more about builtins, please read the answer by Christian Dean.

P.S. When you start an interactive Python session, you create a temporary module.