Programs & Examples On #Dynamic list

Regular expression that doesn't contain certain string

I'm not sure it's a standard construct, but I think you should have a look on "negative lookahead" (which writes : "?!", without the quotes). It's far easier than all answers in this thread, including the accepted one.

Example : Regex : "^(?!123)[0-9]*\w" Captures any string beginning by digits followed by letters, UNLESS if "these digits" are 123.

http://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx#grouping_constructs (microsoft page, but quite comprehensive) for lookahead / lookbehind

PS : it works well for me (.Net). But if I'm wrong on something, please let us know. I find this construct very simple and effective, so I'm surprised of the accepted answer.

Does a "Find in project..." feature exist in Eclipse IDE?

First customize your search dialog. Ctrl+H. Click on the Customize button and select inly File Search while deselecting all the others. Close the dialog.

Now you can search by selecting the word and hitting the Ctrl+H and then Enter.

Enabling WiFi on Android Emulator

When using an AVD with API level 25 or higher, the emulator provides a simulated Wi-Fi access point ("AndroidWifi"), and Android automatically connects to it.

Source : https://developer.android.com/studio/run/emulator.html#wi-fi

onclick on a image to navigate to another page using Javascript

Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:

<script>
    $(document).ready(function() {
        $('img.thumbnail').click(function() {
            window.location.href = this.id + '.html';
        });
    });
</script>

Basically, it attaches an onClick event to all images with class thumbnail to redirect to the corresponding HTML page (id + .html). Then you only need the images in your HTML (without the a elements), like this:

<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />

How do I remove the file suffix and path portion from a path string in Bash?

look at the basename command:

NAME="$(basename /foo/fizzbuzz.bar .bar)"

instructs it to remove the suffix .bar, results in NAME=fizzbuzz

Find stored procedure by name

This will work for tables and views (among other things) as well, not just sprocs:

SELECT
    '[' + s.name + '].[' + o.Name + ']',
    o.type_desc
FROM
    sys.objects o
    JOIN sys.schemas s ON s.schema_id = o.schema_id
WHERE
    o.name = 'CreateAllTheThings' -- if you are certain of the exact name
    OR o.name LIKE '%CreateAllThe%' -- if you are not so certain

It also gives you the schema name which will be useful in any non-trivial database (e.g. one where you need a query to find a stored procedure by name).

How to fix Terminal not loading ~/.bashrc on OS X Lion

Terminal opens a login shell. This means, ~/.bash_profile will get executed, ~/.bashrc not.

The solution on most systems is to "require" the ~/.bashrc in the ~/.bash_profile: just put this snippet in your ~/.bash_profile:

[[ -s ~/.bashrc ]] && source ~/.bashrc

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

In the SQL Server, try these steps:

  1. Open one database.
  2. Click in the option Server Object.
  3. Click in Linked Servers.
  4. Click in Providers.
  5. Right click on Microsoft.ACE.OLEDB.12.0 and click Properties.
  6. Uncheck all the options and close.

How do I solve the INSTALL_FAILED_DEXOPT error?

I found there's one reason for this problem: not enough space on mobile. So I delete several APP from mobile and it's fixed.

How to undo a git pull?

Or to make it more explicit than the other answer:

git pull 

whoops?

git reset --keep HEAD@{1}

Versions of git older than 1.7.1 do not have --keep. If you use such version, you could use --hard - but that is a dangerous operation because it loses any local changes.


To the commenter

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation)

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

How can I send an inner <div> to the bottom of its parent <div>?

You may not want absolute positioning because it breaks the reflow: in some circumstances, a better solution is to make the grandparent element display:table; and the parent element display:table-cell;vertical-align:bottom;. After doing this, you should be able to give the the child elements display:inline-block; and they will automagically flow towards the bottom of the parent.

flutter remove back button on appbar

Just want to add some description over @Jackpap answer:

automaticallyImplyLeading:

This checks whether we want to apply the back widget(leading widget) over the app bar or not. If the automaticallyImplyLeading is false then automatically space is given to the title and if If the leading widget is true, then this parameter has no effect.

void main() {
  runApp(
    new MaterialApp(
      home: new Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false, // Used for removing back buttoon. 
          title: new Center(
            child: new Text("Demo App"),
          ),
        ),
        body: new Container(
          child: new Center(
            child: Text("Hello world!"),
          ),
        ),
      ),
    ),
  );
}  

When to use SELECT ... FOR UPDATE?

Short answers:

Q1: Yes.

Q2: Doesn't matter which you use.

Long answer:

A select ... for update will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.

Another way of looking at it, it is as if the following two statements are executed atomically:

select * from my_table where my_condition;

update my_table set my_column = my_column where my_condition;

Since the rows affected by my_condition are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.

Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.

What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

Adding skipLibCheck: true in compilerOptions inside tsconfig.json file fixed my issue.

"compilerOptions": {
   "skipLibCheck": true,
},

Running a script inside a docker container using shell script

I was searching an answer for this same question and found ENTRYPOINT in Dockerfile solution for me.

Dockerfile

...
ENTRYPOINT /my-script.sh ; /my-script2.sh ; /bin/bash

Now the scripts are executed when I start the container and I get the bash prompt after the scripts has been executed.

get keys of json-object in JavaScript

var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];

for(var i in jsonData){
    var key = i;
    var val = jsonData[i];
    for(var j in val){
        var sub_key = j;
        var sub_val = val[j];
        console.log(sub_key);
    }
}

EDIT

var jsonObj = {"person":"me","age":"30"};
Object.keys(jsonObj);  // returns ["person", "age"]

Object has a property keys, returns an Array of keys from that Object

Chrome, FF & Safari supports Object.keys

Postgresql -bash: psql: command not found

export PATH=/usr/pgsql-9.2/bin:$PATH

The program executable psql is in the directory /usr/pgsql-9.2/bin, and that directory is not included in the path by default, so we have to tell our shell (terminal) program where to find psql. When most packages are installed, they are added to an existing path, such as /usr/local/bin, but not this program.

So we have to add the program's path to the shell PATH variable if we do not want to have to type the complete path to the program every time we execute it.

This line should typically be added to theshell startup script, which for the bash shell will be in the file ~/.bashrc.

export html table to csv

Using just jQuery, vanilla Javascript, and the table2CSV library:

export-to-html-table-as-csv-file-using-jquery

Put this code into a script to be loaded in the head section:

 $(document).ready(function () {
    $('table').each(function () {
        var $table = $(this);

        var $button = $("<button type='button'>");
        $button.text("Export to spreadsheet");
        $button.insertAfter($table);

        $button.click(function () {
            var csv = $table.table2CSV({
                delivery: 'value'
            });
            window.location.href = 'data:text/csv;charset=UTF-8,' 
            + encodeURIComponent(csv);
        });
    });
})

Notes:

Requires jQuery and table2CSV: Add script references to both libraries before the script above.

The table selector is used as an example, and can be adjusted to suit your needs.

It only works in browsers with full Data URI support: Firefox, Chrome and Opera, not in IE, which only supports Data URIs for embedding binary image data into a page.

For full browser compatibility you would have to use a slightly different approach that requires a server side script to echo the CSV.

Understanding PIVOT function in T-SQL

Ive something to add here which no one mentioned.

The pivot function works great when the source has 3 columns: One for the aggregate, one to spread as columns with for, and one as a pivot for row distribution. In the product example it's QTY, CUST, PRODUCT.

However, if you have more columns in the source it will break the results into multiple rows instead of one row per pivot based on unique values per additional column (as Group By would do in a simple query).

See this example, ive added a timestamp column to the source table:

enter image description here

Now see its impact:

SELECT CUST, MILK

FROM Product
-- FROM (SELECT CUST, Product, QTY FROM PRODUCT) p
PIVOT (
    SUM(QTY) FOR PRODUCT IN (MILK)
) AS pvt

ORDER BY CUST

enter image description here


In order to fix this, you can either pull a subquery as a source as everyone has done above - with only 3 columns (this is not always going to work for your scenario, imagine if you need to put a where condition for the timestamp).

Second solution is to use a group by and do a sum of the pivoted column values again.

SELECT 
CUST, 
sum(MILK) t_MILK

FROM Product
PIVOT (
    SUM(QTY) FOR PRODUCT IN (MILK)
) AS pvt

GROUP BY CUST
ORDER BY CUST

GO

enter image description here

How to use LocalBroadcastManager?

localbroadcastmanager is deprecated, use implementations of the observable pattern instead.

androidx.localbroadcastmanager is being deprecated in version 1.1.0

Reason

LocalBroadcastManager is an application-wide event bus and embraces layer violations in your app; any component may listen to events from any other component. It inherits unnecessary use-case limitations of system BroadcastManager; developers have to use Intent even though objects live in only one process and never leave it. For this same reason, it doesn’t follow feature-wise BroadcastManager .

These add up to a confusing developer experience.

Replacement

You can replace usage of LocalBroadcastManager with other implementations of the observable pattern. Depending on your use case, suitable options may be LiveData or reactive streams.

Advantage of LiveData

You can extend a LiveData object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveData object connects to the system service once, and then any observer that needs the resource can just watch the LiveData object.

 public class MyFragment extends Fragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LiveData<BigDecimal> myPriceListener = ...;
        myPriceListener.observe(this, price -> {
            // Update the UI.
        });
    }
}

The observe() method passes the fragment, which is an instance of LifecycleOwner, as the first argument. Doing so denotes that this observer is bound to the Lifecycle object associated with the owner, meaning:

  • If the Lifecycle object is not in an active state, then the observer isn't called even if the value changes.

  • After the Lifecycle object is destroyed, the observer is automatically removed

The fact that LiveData objects are lifecycle-aware means that you can share them between multiple activities, fragments, and services.

Flattening a shallow list in Python

In Python 2.6, using chain.from_iterable():

>>> from itertools import chain
>>> list(chain.from_iterable(mi.image_set.all() for mi in h.get_image_menu()))

It avoids creating of intermediate list.

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

I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!! use close(fd) system call after you finished working on a file.

How to select the rows with maximum values in each group with dplyr?

df %>% group_by(A,B) %>% slice(which.max(value))

Android WebView not loading an HTTPS URL

Copy and paste your code line bro , it will work trust me :) i am thinking ,you get a ssl error. If you use override onReceivedSslError method and remove super it's super method. Just write handler.proceed() ,error will solve.

    webView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {

            activity.setTitle("Loading...");
            activity.setProgress(progress * 100);

            if (progress == 100)
                activity.setTitle(getResources().getString(R.string.app_name));
        }
    });

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d("Failure Url :" , failingUrl);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            Log.d("Ssl Error:",handler.toString() + "error:" +  error);
            handler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.loadUrl(Constant.VIRTUALPOS_URL + "token=" + Preference.getInstance(getContext()).getToken() + "&dealer=" + Preference.getInstance(getContext()).getDealerCode());

How do I move a redis database from one server to another?

If you have the connectivity between servers it is better to set up replication (which is trivial, unlike with SQL) with the new instance as a slave node - then you can switch the new node to master with a single command and do the move with zero downtime.

fatal: could not create work tree dir 'kivy'

If you are working on a mac, then this is probably because you don't have permission to write to the directory. When I had this issue, I followed the following steps:

  • Opened the folder in finder -> right-click -> get info -> click on the lock on the bottom right of the pop up window, enter admin password -> then change the Sharing and Permissions to Read and Write for wheel, and everyone -> click lock again to save

LDAP root query syntax to search more than one specific OU

After speaking with an LDAP expert, it's not possible this way. One query can't search more than one DC or OU.

Your options are:

  1. Run more then 1 query and parse the result.
  2. Use a filter to find the desired users/objects based off a different attribute like an AD group or by name.

Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

you can keep booth EAGER lists in JPA and add to at least one of them the JPA annotation @OrderColumn (with obviously the name of a field to be ordered). No need of specific hibernate annotations. But keep in mind it could create empty elements in the list if the chosen field does not have values starting from 0

 [...]
 @OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
 @OrderColumn(name="orderIndex")
 private List<Child> children;
 [...]

in Children then you should add the orderIndex field

How to save and extract session data in codeigniter

You can set data to session simply like this in Codeigniter:

$this->load->library('session');
$this->session->set_userdata(array(
    'user_id'  => $user->uid,
    'username' => $user->username,
    'groupid'  => $user->groupid,
    'date'     => $user->date_cr,
    'serial'   => $user->serial,
    'rec_id'   => $user->rec_id,
    'status'   => TRUE
));

and you can get it like this:

$u_rec_id = $this->session->userdata('rec_id');
$serial = $this->session->userdata('serial');

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

In Java you would do something similar to:

Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();    

Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.

How to get a variable name as a string in PHP?

why we have to use globals to get variable name... we can use simply like below.

    $variableName = "ajaxmint";

    echo getVarName('$variableName');

    function getVarName($name) {
        return str_replace('$','',$name);
    }

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

maybe you have code like this before the jquery:

var $jq=jQuery.noConflict();
$jq('ul.menu').lavaLamp({
    fx: "backout", 
    speed: 700
});

and them was Conflict

you can change $ to (jQuery)

How do I pass variables and data from PHP to JavaScript?

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

In no particular order:

  1. Use AJAX to get the data you need from the server.
  2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
  3. Echo the data directly to JavaScript.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

1. Use AJAX to get the data you need from the server

This method is considered the best, because your server side and client side scripts are completely separate.

Pros

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for asynchronous data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.

Cons

  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g., if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

Implementation Example

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

get-data.php

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 *
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well.
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); // In the end, you need to echo the result.
                      // All data should be json_encode()d.

                      // You can json_encode() any value in PHP, arrays, strings,
                      //even objects.

index.php (or whatever the actual page is named like)

<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); // New request object
    oReq.onload = function() {
        // This is where you handle what to do with the response.
        // The actual data is found on this.responseText
        alert(this.responseText); // Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

Some more reading material

2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

Pros

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.

Cons

  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JavaScript that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

index.php

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php
        $output = "42"; // Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

3. Echo the data directly to JavaScript

This is probably the easiest to understand.

Pros

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.

Cons

  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

Implementation is relatively straightforward:

<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->

Good luck!

What is the difference between a function expression vs declaration in JavaScript?

Regarding 3rd definition:

var foo = function foo() { return 5; }

Heres an example which shows how to use possibility of recursive call:

a = function b(i) { 
  if (i>10) {
    return i;
  }
  else {
    return b(++i);
  }
}

console.log(a(5));  // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15

Edit: more interesting example with closures:

a = function(c) {
 return function b(i){
  if (i>c) {
   return i;
  }
  return b(++i);
 }
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8

What is the MySQL JDBC driver connection string?

For Mysql, the jdbc Driver connection string is com.mysql.jdbc.Driver. Use the following code to get connected:-

class DBConnection {
   private static Connection con = null;
   private static String USERNAME = "your_mysql_username";
   private static String PASSWORD = "your_mysql_password";
   private static String DRIVER = "com.mysql.jdbc.Driver";
   private static String URL = "jdbc:mysql://localhost:3306/database_name";

   public static Connection getDatabaseConnection(){
       Class.forName(DRIVER);
       return con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
   }
}

Show which git tag you are on?

Show all tags on current HEAD (or commit)

git tag --points-at HEAD

Why is json_encode adding backslashes?

I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.

Here is what was happening. If you do:

$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);

The result is:

["{\"test\":\"2\"}","{\"test\":\"four\"}"]

So, what you actually need to do is:

$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);

And this will return

[{"test":"2"},{"test":"four"}]

how to rename an index in a cluster?

If you can't REINDEX a workaround is to use aliases. From the official documentation:

APIs in elasticsearch accept an index name when working against a specific index, and several indices when applicable. The index aliases API allow to alias an index with a name, with all APIs automatically converting the alias name to the actual index name. An alias can also be mapped to more than one index, and when specifying it, the alias will automatically expand to the aliases indices. An alias can also be associated with a filter that will automatically be applied when searching, and routing values. An alias cannot have the same name as an index.

Be aware that this solution does not work if you're using More Like This feature. https://github.com/elastic/elasticsearch/issues/16560

SQL: Alias Column Name for Use in CASE Statement

  • If you write only equal condition just: Select Case columns1 When 0 then 'Value1' when 1 then 'Value2' else 'Unknown' End

  • If you want to write greater , Less then or equal you must do like this: Select Case When [ColumnsName] >0 then 'value1' When [ColumnsName]=0 Or [ColumnsName]<0 then 'value2' Else 'Unkownvalue' End

From tablename

Thanks Mr.Buntha Khin

typesafe select onChange event using reactjs and typescript

In my case onChange event was typed as React.ChangeEvent:

onChange={ (e: React.ChangeEvent<HTMLSelectElement>) => {
           console.warn('onChange TextInput value: ' + e.target.value);
           } 
         }

Include another HTML file in a HTML file

Checkout HTML5 imports via Html5rocks tutorial and at polymer-project

For example:

<head>
  <link rel="import" href="/path/to/imports/stuff.html">
</head>

Using mysql concat() in WHERE clause?

SELECT *,concat_ws(' ',first_name,last_name) AS whole_name FROM users HAVING whole_name LIKE '%$search_term%'

...is probably what you want.

Angular pass callback function to child component as @Input similar to AngularJS way

Another alternative.

The OP asked a way to use a callback. In this case he was referring specifically to a function that process an event (in his example: a click event), which shall be treated as the accepted answer from @serginho suggests: with @Output and EventEmitter.

However, there is a difference between a callback and an event: With a callback your child component can retrieve some feedback or information from the parent, but an event only can inform that something happened without expect any feedback.

There are use cases where a feedback is necessary, ex. get a color, or a list of elements that the component needs to handle. You can use bound functions as some answers have suggested, or you can use interfaces (that's always my preference).

Example

Let's suppose you have a generic component that operates over a list of elements {id, name} that you want to use with all your database tables that have these fields. This component should:

  • retrieve a range of elements (page) and show them in a list
  • allow remove an element
  • inform that an element was clicked, so the parent can take some action(s).
  • allow retrieve the next page of elements.

Child Component

Using normal binding we would need 1 @Input() and 3 @Output() parameters (but without any feedback from the parent). Ex. <list-ctrl [items]="list" (itemClicked)="click($event)" (itemRemoved)="removeItem($event)" (loadNextPage)="load($event)" ...>, but creating an interface we will need only one @Input():

import {Component, Input, OnInit} from '@angular/core';

export interface IdName{
  id: number;
  name: string;
}

export interface IListComponentCallback<T extends IdName> {
    getList(page: number, limit: number): Promise< T[] >;
    removeItem(item: T): Promise<boolean>;
    click(item: T): void;
}

@Component({
    selector: 'list-ctrl',
    template: `
      <button class="item" (click)="loadMore()">Load page {{page+1}}</button>
      <div class="item" *ngFor="let item of list">
          <button (click)="onDel(item)">DEL</button>
          <div (click)="onClick(item)">
            Id: {{item.id}}, Name: "{{item.name}}"
          </div>
      </div>
    `,
    styles: [`
      .item{ margin: -1px .25rem 0; border: 1px solid #888; padding: .5rem; width: 100%; cursor:pointer; }
      .item > button{ float: right; }
      button.item{margin:.25rem;}
    `]
})
export class ListComponent implements OnInit {
    @Input() callback: IListComponentCallback<IdName>; // <-- CALLBACK
    list: IdName[];
    page = -1; 
    limit = 10;

    async ngOnInit() {
      this.loadMore();
    }
    onClick(item: IdName) {
      this.callback.click(item);   
    }
    async onDel(item: IdName){ 
        if(await this.callback.removeItem(item)) {
          const i = this.list.findIndex(i=>i.id == item.id);
          this.list.splice(i, 1);
        }
    }
    async loadMore(){
      this.page++;
      this.list = await this.callback.getList(this.page, this.limit); 
    }
}

Parent Component

Now we can use the list component in the parent.

import { Component } from "@angular/core";
import { SuggestionService } from "./suggestion.service";
import { IdName, IListComponentCallback } from "./list.component";

type Suggestion = IdName;

@Component({
  selector: "my-app",
  template: `
    <list-ctrl class="left" [callback]="this"></list-ctrl>
    <div class="right" *ngIf="msg">{{ msg }}<br/><pre>{{item|json}}</pre></div>
  `,
  styles:[`
    .left{ width: 50%; }
    .left,.right{ color: blue; display: inline-block; vertical-align: top}
    .right{max-width:50%;overflow-x:scroll;padding-left:1rem}
  `]
})
export class ParentComponent implements IListComponentCallback<Suggestion> {
  msg: string;
  item: Suggestion;

  constructor(private suggApi: SuggestionService) {}

  getList(page: number, limit: number): Promise<Suggestion[]> {
    return this.suggApi.getSuggestions(page, limit);
  }
  removeItem(item: Suggestion): Promise<boolean> {
    return this.suggApi.removeSuggestion(item.id)
      .then(() => {
        this.showMessage('removed', item);
        return true;
      })
      .catch(() => false);
  }
  click(item: Suggestion): void {
    this.showMessage('clicked', item);
  }
  private showMessage(msg: string, item: Suggestion) {
    this.item = item;
    this.msg = 'last ' + msg;
  }
}

Note that the <list-ctrl> receives this (parent component) as the callback object. One additional advantage is that it's not required to send the parent instance, it can be a service or any object that implements the interface if your use case allows it.

The complete example is on this stackblitz.

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

    .first-character{
        font-weight:bold;
        color:#F00;
        text-transform:capitalize;
   }
.capital-text{
    text-transform:uppercase;
    }

How to find the php.ini file used by the command line?

The easiest way nowadays is to use PHP configure:

# php-config --ini-dir
/usr/local/etc/php/7.4/conf.d

There's more you can find there. Example output of the --help sub command (macOS local install):

# php-config --help
Usage: /usr/local/bin/php-config [OPTION]
Options:
  --prefixUsage: /usr/local/bin/php-config [OPTION]
Options:
  --prefix            [/usr/local/Cellar/php/7.4.11]
  --includes          [-I/usr/local/Cellar/php/7.4.11/include/php - …ETC…]
  --ldflags           [ -L/usr/local/Cellar/krb5/1.18.2/lib -…ETC…]
  --libs              [ -ltidy -largon2 …ETC… ]
  --extension-dir     [/usr/local/Cellar/php/7.4.11/pecl/20190902]
  --include-dir       [/usr/local/Cellar/php/7.4.11/include/php]
  --man-dir           [/usr/local/Cellar/php/7.4.11/share/man]
  --php-binary        [/usr/local/Cellar/php/7.4.11/bin/php]
  --php-sapis         [ apache2handler cli fpm phpdbg cgi]
  --ini-path          [/usr/local/etc/php/7.4]
  --ini-dir           [/usr/local/etc/php/7.4/conf.d]
  --configure-options [--prefix=/usr/local/Cellar/php/7.4.11 --…ETC…]
  --version           [7.4.11]
  --vernum            [70411]

How to access elements of a JArray (or iterate over them)

Update - I verified the below works. Maybe the creation of your JArray isn't quite right.

[TestMethod]
    public void TestJson()
    {
        var jsonString = @"{""trends"": [
              {
                ""name"": ""Croke Park II"",
                ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                ""promoted_content"": null,
                ""query"": ""%22Croke+Park+II%22"",
                ""events"": null
              },
              {
                ""name"": ""Siptu"",
                ""url"": ""http://twitter.com/search?q=Siptu"",
                ""promoted_content"": null,
                ""query"": ""Siptu"",
                ""events"": null
              },
              {
                ""name"": ""#HNCJ"",
                ""url"": ""http://twitter.com/search?q=%23HNCJ"",
                ""promoted_content"": null,
                ""query"": ""%23HNCJ"",
                ""events"": null
              },
              {
                ""name"": ""Boston"",
                ""url"": ""http://twitter.com/search?q=Boston"",
                ""promoted_content"": null,
                ""query"": ""Boston"",
                ""events"": null
              },
              {
                ""name"": ""#prayforboston"",
                ""url"": ""http://twitter.com/search?q=%23prayforboston"",
                ""promoted_content"": null,
                ""query"": ""%23prayforboston"",
                ""events"": null
              },
              {
                ""name"": ""#TheMrsCarterShow"",
                ""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
                ""promoted_content"": null,
                ""query"": ""%23TheMrsCarterShow"",
                ""events"": null
              },
              {
                ""name"": ""#Raw"",
                ""url"": ""http://twitter.com/search?q=%23Raw"",
                ""promoted_content"": null,
                ""query"": ""%23Raw"",
                ""events"": null
              },
              {
                ""name"": ""Iran"",
                ""url"": ""http://twitter.com/search?q=Iran"",
                ""promoted_content"": null,
                ""query"": ""Iran"",
                ""events"": null
              },
              {
                ""name"": ""#gaa"",
                ""url"": ""http://twitter.com/search?q=%23gaa"",
                ""promoted_content"": null,
                ""query"": ""gaa"",
                ""events"": null
              },
              {
                ""name"": ""Facebook"",
                ""url"": ""http://twitter.com/search?q=Facebook"",
                ""promoted_content"": null,
                ""query"": ""Facebook"",
                ""events"": null
              }]}";

        var twitterObject = JToken.Parse(jsonString);
        var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;


        foreach (var item in trendsArray.Children())
        {
            var itemProperties = item.Children<JProperty>();
            //you could do a foreach or a linq here depending on what you need to do exactly with the value
            var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
            var myElementValue = myElement.Value; ////This is a JValue type
        }
    }

So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.

foreach(var item in yourJArray.Children())
{
    var itemProperties = item.Children<JProperty>();
    //you could do a foreach or a linq here depending on what you need to do exactly with the value
    var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
    var myElementValue = myElement.Value; ////This is a JValue type
}

How to check if a string starts with one of several prefixes?

Of course, be mindful that your program will only be useful in english speaking countries if you detect dates this way. You might want to consider:

Set<String> dayNames = Calendar.getInstance()
 .getDisplayNames(Calendar.DAY_OF_WEEK,
      Calendar.SHORT,
      Locale.getDefault())
 .keySet();

From there you can use .startsWith or .matches or whatever other method that others have mentioned above. This way you get the default locale for the jvm. You could always pass in the locale (and maybe default it to the system locale if it's null) as well to be more robust.

Entity Framework 6 Code first Default value

Set the default value for the column in table in MSSQL Server, and in class code add attribute, like this:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

for the same property.

How can I change NULL to 0 when getting a single value from a SQL function?

You could use

SELECT ISNULL(SUM(ISNULL(Price, 0)), 0).

I'm 99% sure that will work.

How do I find the mime-type of a file with php?

According to the php manual, the finfo-file function is best way to do this. However, you will need to install the FileInfo PECL extension.

If the extension is not an option, you can use the outdated mime_content_type function.

How to access command line arguments of the caller inside a function?

#!/usr/bin/env bash

echo name of script is $0
echo first argument is $1
echo second argument is $2
echo seventeenth argument is $17
echo number of arguments is $#

Edit: please see my comment on question

How to get cell value from DataGridView in VB.Net?

The line would be as shown below:

Dim x As Integer    
x = dgvName.Rows(yourRowIndex).Cells(yourColumnIndex).Value

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

This is because your servlet is trying to access a request object which is no more exist.. A servlet's forward or include statement does not stop execution of method block. It continues to the end of method block or first return statement just like any other java method.

The best way to resolve this problem just set the page (where you suppose to forward the request) dynamically according your logic. That is:

protected void doPost(request , response){
String returnPage="default.jsp";
if(condition1){
 returnPage="page1.jsp";
}
if(condition2){
   returnPage="page2.jsp";
}
request.getRequestDispatcher(returnPage).forward(request,response); //at last line
}

and do the forward only once at last line...

you can also fix this problem using return statement after each forward() or put each forward() in if...else block

Android splash screen image sizes to fit all devices

Disclaimer

This answer is from 2013 and is seriously outdated. As of Android 3.2 there are now 6 groups of screen density. This answer will be updated as soon as I am able, but with no ETA. Refer to the official documentation for all the densities at the moment (although information on specific pixel sizes is as always hard to find).

Here's the tl/dr version

  • Create 4 images, one for each screen density:

    • xlarge (xhdpi): 640x960
    • large (hdpi): 480x800
    • medium (mdpi): 320x480
    • small (ldpi): 240x320
  • Read 9-patch image introduction in Android Developer Guide

  • Design images that have areas that can be safely stretched without compromising the end result

With this, Android will select the appropriate file for the device's image density, then it will stretch the image according to the 9-patch standard.

end of tl;dr. Full post ahead

I am answering in respect to the design-related aspect of the question. I am not a developer, so I won't be able to provide code for implementing many of the solutions provided. Alas, my intent is to help designers who are as lost as I was when I helped develop my first Android App.

Fitting all sizes

With Android, companies can develop their mobile phones and tables of almost any size, with almost any resolution they want. Because of that, there is no "right image size" for a splash screen, as there are no fixed screen resolutions. That poses a problem for people that want to implement a splash screen.

Do your users really want to see a splash screen?

(On a side note, splash screens are somewhat discouraged among the usability guys. It is argued that the user already knows what app he tapped on, and branding your image with a splash screen is not necessary, as it only interrupts the user experience with an "ad". It should be used, however, in applications that require some considerable loading when initialized (5s+), including games and such, so that the user is not stuck wondering if the app crashed or not)

Screen density; 4 classes

So, given so many different screen resolutions in the phones on the market, Google implemented some alternatives and nifty solutions that can help. The first thing you have to know is that Android separates ALL screens into 4 distinct screen densities:

  1. Low Density (ldpi ~ 120dpi)
  2. Medium Density (mdpi ~ 160dpi)
  3. High Density (hdpi ~ 240dpi)
  4. Extra-High Density (xhdpi ~ 320dpi) (These dpi values are approximations, since custom built devices will have varying dpi values)

What you (if you're a designer) need to know from this is that Android basically chooses from 4 images to display, depending on the device. So you basically have to design 4 different images (although more can be developed for different formats such as widescreen, portrait/landscape mode, etc).

With that in mind know this: unless you design a screen for every single resolution that is used in Android, your image will stretch to fit screen size. And unless your image is basically a gradient or blur, you'll get some undesired distortion with the stretching. So you have basically two options: create an image for each screen size/density combination, or create four 9-patch images.

The hardest solution is to design a different splash screen for every single resolution. You can start by following the resolutions in the table at the end of this page (there are more. Example: 960 x 720 is not listed there). And assuming you have some small detail in the image, such as small text, you have to design more than one screen for each resolution. For example, a 480x800 image being displayed in a medium screen might look ok, but on a smaller screen (with higher density/dpi) the logo might become too small, or some text might become unreadable.

9-patch image

The other solution is to create a 9-patch image. It is basically a 1-pixel-transparent-border around your image, and by drawing black pixels in the top and left area of this border you can define which portions of your image will be allowed to stretch. I won't go into the details of how 9-patch images work but, in short, the pixels that align to the markings in the top and left area are the pixels that will be repeated to stretch the image.

A few ground rules

  1. You can make these images in photoshop (or any image editing software that can accurately create transparent pngs).
  2. The 1-pixel border has to be FULL TRANSPARENT.
  3. The 1-pixel transparent border has to be all around your image, not just top and left.
  4. you can only draw black (#000000) pixels in this area.
  5. The top and left borders (which define the image stretching) can only have one dot (1px x 1px), two dots (both 1px x 1px) or ONE continuous line (width x 1px or 1px x height).
  6. If you choose to use 2 dots, the image will be expanded proportionally (so each dot will take turns expanding until the final width/height is achieved)
  7. The 1px border has to be in addition to the intended base file dimensions. So a 100x100 9-patch image has to actually have 102x102 (100x100 +1px on top, bottom, left and right)
  8. 9-patch images have to end with *.9.png

So you can place 1 dot on either side of your logo (in the top border), and 1 dot above and below it (on the left border), and these marked rows and columns will be the only pixels to stretch.

Example

Here's a 9-patch image, 102x102px (100x100 final size, for app purposes):

9-patch image, 102x102px

Here's a 200% zoom of the same image:

the same image, magnified 2x for clarity

Notice the 1px marks on top and left saying which rows/columns will expand.

Here's what this image would look like in 100x100 inside the app:

rendered into 100x100

And here's what it would like if expanded to 460x140:

rendered into 460x140

One last thing to consider. These images might look fine on your monitor screen and on most mobiles, but if the device has a very high image density (dpi), the image would look too small. Probably still legible, but on a tablet with 1920x1200 resolution, the image would appear as a very small square in the middle. So what's the solution? Design 4 different 9-patch launcher images, each for a different density set. To ensure that no shrinking will occur, you should design in the lowest common resolution for each density category. Shrinking is undesirable here because 9-patch only accounts for stretching, so in a shrinking process small text and other elements might lose legibility.

Here's a list of the smallest, most common resolutions for each density category:

  • xlarge (xhdpi): 640x960
  • large (hdpi): 480x800
  • medium (mdpi): 320x480
  • small (ldpi): 240x320

So design four splash screens in the above resolutions, expand the images, putting a 1px transparent border around the canvas, and mark which rows/columns will be stretchable. Keep in mind these images will be used for ANY device in the density category, so your ldpi image (240 x 320) might be stretched to 1024x600 on an extra large tablet with small image density (~120 dpi). So 9-patch is the best solution for the stretching, as long as you don't want a photo or complicated graphics for a splash screen (keep in mind these limitations as you create the design).

Again, the only way for this stretching not to happen is to design one screen each resolution (or one for each resolution-density combination, if you want to avoid images becoming too small/big on high/low density devices), or to tell the image not to stretch and have a background color appear wherever stretching would occur (also remember that a specific color rendered by the Android engine will probably look different from the same specific color rendered by photoshop, because of color profiles).

I hope this made any sense. Good luck!

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

We are using an old version hibernate (3.2.6) and the problem for us was, that Hibernate expected the first column in the result set to be the generated primary key. Took me ages to figure that out.

Solution: Ensure in that in the DDL the generated primary key is always the first column. Solution 2: Update hibernate

Rounding up to next power of 2

next = pow(2, ceil(log(x)/log(2)));

This works by finding the number you'd have raise 2 by to get x (take the log of the number, and divide by the log of the desired base, see wikipedia for more). Then round that up with ceil to get the nearest whole number power.

This is a more general purpose (i.e. slower!) method than the bitwise methods linked elsewhere, but good to know the maths, eh?

how to call javascript function in html.actionlink in asp.net mvc?

<a onclick="MyFunc()">blabla..</a>

There is nothing more in @Html.ActionLink that you could utilize in this case. And razor is evel by itself, drop it from where you can.

Cannot edit in read-only editor VS Code

  1. Go to File > Preference > Settings then
  2. type: run code and scroll down until you see code-runner: Run in terminal, There will be multiple options called "code-runner". In that you can find the option mentioned below.
  3. just check "Whether to run code in integrated terminal" and
  4. restart vscode.

For Mac users, it is Code > Preference > Settings.

How to find list of possible words from a letter matrix [Boggle Solver]

Not interested in VB? :) I couldn't resist. I've solved this differently than many of the solutions presented here.

My times are:

  • Loading the dictionary and word prefixes into a hashtable: .5 to 1 seconds.
  • Finding the words: averaging under 10 milliseconds.

EDIT: Dictionary load times on the web host server are running about 1 to 1.5 seconds longer than my home computer.

I don't know how badly the times will deteriorate with a load on the server.

I wrote my solution as a web page in .Net. myvrad.com/boggle

I'm using the dictionary referenced in the original question.

Letters are not reused in a word. Only words 3 characters or longer are found.

I'm using a hashtable of all unique word prefixes and words instead of a trie. I didn't know about trie's so I learned something there. The idea of creating a list of prefixes of words in addition to the complete words is what finally got my times down to a respectable number.

Read the code comments for additional details.

Here's the code:

Imports System.Collections.Generic
Imports System.IO

Partial Class boggle_Default

    'Bob Archer, 4/15/2009

    'To avoid using a 2 dimensional array in VB I'm not using typical X,Y
    'coordinate iteration to find paths.
    '
    'I have locked the code into a 4 by 4 grid laid out like so:
    ' abcd
    ' efgh
    ' ijkl
    ' mnop
    ' 
    'To find paths the code starts with a letter from a to p then
    'explores the paths available around it. If a neighboring letter
    'already exists in the path then we don't go there.
    '
    'Neighboring letters (grid points) are hard coded into
    'a Generic.Dictionary below.



    'Paths is a list of only valid Paths found. 
    'If a word prefix or word is not found the path is not
    'added and extending that path is terminated.
    Dim Paths As New Generic.List(Of String)

    'NeighborsOf. The keys are the letters a to p.
    'The value is a string of letters representing neighboring letters.
    'The string of neighboring letters is split and iterated later.
    Dim NeigborsOf As New Generic.Dictionary(Of String, String)

    'BoggleLetters. The keys are mapped to the lettered grid of a to p.
    'The values are what the user inputs on the page.
    Dim BoggleLetters As New Generic.Dictionary(Of String, String)

    'Used to store last postition of path. This will be a letter
    'from a to p.
    Dim LastPositionOfPath As String = ""

    'I found a HashTable was by far faster than a Generic.Dictionary 
    ' - about 10 times faster. This stores prefixes of words and words.
    'I determined 792773 was the number of words and unique prefixes that
    'will be generated from the dictionary file. This is a max number and
    'the final hashtable will not have that many.
    Dim HashTableOfPrefixesAndWords As New Hashtable(792773)

    'Stores words that are found.
    Dim FoundWords As New Generic.List(Of String)

    'Just to validate what the user enters in the grid.
    Dim ErrorFoundWithSubmittedLetters As Boolean = False

    Public Sub BuildAndTestPathsAndFindWords(ByVal ThisPath As String)
        'Word is the word correlating to the ThisPath parameter.
        'This path would be a series of letters from a to p.
        Dim Word As String = ""

        'The path is iterated through and a word based on the actual
        'letters in the Boggle grid is assembled.
        For i As Integer = 0 To ThisPath.Length - 1
            Word += Me.BoggleLetters(ThisPath.Substring(i, 1))
        Next

        'If my hashtable of word prefixes and words doesn't contain this Word
        'Then this isn't a word and any further extension of ThisPath will not
        'yield any words either. So exit sub to terminate exploring this path.
        If Not HashTableOfPrefixesAndWords.ContainsKey(Word) Then Exit Sub

        'The value of my hashtable is a boolean representing if the key if a word (true) or
        'just a prefix (false). If true and at least 3 letters long then yay! word found.
        If HashTableOfPrefixesAndWords(Word) AndAlso Word.Length > 2 Then Me.FoundWords.Add(Word)

        'If my List of Paths doesn't contain ThisPath then add it.
        'Remember only valid paths will make it this far. Paths not found
        'in the HashTableOfPrefixesAndWords cause this sub to exit above.
        If Not Paths.Contains(ThisPath) Then Paths.Add(ThisPath)

        'Examine the last letter of ThisPath. We are looking to extend the path
        'to our neighboring letters if any are still available.
        LastPositionOfPath = ThisPath.Substring(ThisPath.Length - 1, 1)

        'Loop through my list of neighboring letters (representing grid points).
        For Each Neighbor As String In Me.NeigborsOf(LastPositionOfPath).ToCharArray()
            'If I find a neighboring grid point that I haven't already used
            'in ThisPath then extend ThisPath and feed the new path into
            'this recursive function. (see recursive.)
            If Not ThisPath.Contains(Neighbor) Then Me.BuildAndTestPathsAndFindWords(ThisPath & Neighbor)
        Next
    End Sub

    Protected Sub ButtonBoggle_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonBoggle.Click

        'User has entered the 16 letters and clicked the go button.

        'Set up my Generic.Dictionary of grid points, I'm using letters a to p -
        'not an x,y grid system.  The values are neighboring points.
        NeigborsOf.Add("a", "bfe")
        NeigborsOf.Add("b", "cgfea")
        NeigborsOf.Add("c", "dhgfb")
        NeigborsOf.Add("d", "hgc")
        NeigborsOf.Add("e", "abfji")
        NeigborsOf.Add("f", "abcgkjie")
        NeigborsOf.Add("g", "bcdhlkjf")
        NeigborsOf.Add("h", "cdlkg")
        NeigborsOf.Add("i", "efjnm")
        NeigborsOf.Add("j", "efgkonmi")
        NeigborsOf.Add("k", "fghlponj")
        NeigborsOf.Add("l", "ghpok")
        NeigborsOf.Add("m", "ijn")
        NeigborsOf.Add("n", "ijkom")
        NeigborsOf.Add("o", "jklpn")
        NeigborsOf.Add("p", "klo")

        'Retrieve letters the user entered.
        BoggleLetters.Add("a", Me.TextBox1.Text.ToLower.Trim())
        BoggleLetters.Add("b", Me.TextBox2.Text.ToLower.Trim())
        BoggleLetters.Add("c", Me.TextBox3.Text.ToLower.Trim())
        BoggleLetters.Add("d", Me.TextBox4.Text.ToLower.Trim())
        BoggleLetters.Add("e", Me.TextBox5.Text.ToLower.Trim())
        BoggleLetters.Add("f", Me.TextBox6.Text.ToLower.Trim())
        BoggleLetters.Add("g", Me.TextBox7.Text.ToLower.Trim())
        BoggleLetters.Add("h", Me.TextBox8.Text.ToLower.Trim())
        BoggleLetters.Add("i", Me.TextBox9.Text.ToLower.Trim())
        BoggleLetters.Add("j", Me.TextBox10.Text.ToLower.Trim())
        BoggleLetters.Add("k", Me.TextBox11.Text.ToLower.Trim())
        BoggleLetters.Add("l", Me.TextBox12.Text.ToLower.Trim())
        BoggleLetters.Add("m", Me.TextBox13.Text.ToLower.Trim())
        BoggleLetters.Add("n", Me.TextBox14.Text.ToLower.Trim())
        BoggleLetters.Add("o", Me.TextBox15.Text.ToLower.Trim())
        BoggleLetters.Add("p", Me.TextBox16.Text.ToLower.Trim())

        'Validate user entered something with a length of 1 for all 16 textboxes.
        For Each S As String In BoggleLetters.Keys
            If BoggleLetters(S).Length <> 1 Then
                ErrorFoundWithSubmittedLetters = True
                Exit For
            End If
        Next

        'If input is not valid then...
        If ErrorFoundWithSubmittedLetters Then
            'Present error message.
        Else
            'Else assume we have 16 letters to work with and start finding words.
            Dim SB As New StringBuilder

            Dim Time As String = String.Format("{0}:{1}:{2}:{3}", Date.Now.Hour.ToString(), Date.Now.Minute.ToString(), Date.Now.Second.ToString(), Date.Now.Millisecond.ToString())

            Dim NumOfLetters As Integer = 0
            Dim Word As String = ""
            Dim TempWord As String = ""
            Dim Letter As String = ""
            Dim fr As StreamReader = Nothing
            fr = New System.IO.StreamReader(HttpContext.Current.Request.MapPath("~/boggle/dic.txt"))

            'First fill my hashtable with word prefixes and words.
            'HashTable(PrefixOrWordString, BooleanTrueIfWordFalseIfPrefix)
            While fr.Peek <> -1
                Word = fr.ReadLine.Trim()
                TempWord = ""
                For i As Integer = 0 To Word.Length - 1
                    Letter = Word.Substring(i, 1)
                    'This optimization helped quite a bit. Words in the dictionary that begin
                    'with letters that the user did not enter in the grid shouldn't go in my hashtable.
                    '
                    'I realize most of the solutions went with a Trie. I'd never heard of that before,
                    'which is one of the neat things about SO, seeing how others approach challenges
                    'and learning some best practices.
                    '
                    'However, I didn't code a Trie in my solution. I just have a hashtable with 
                    'all words in the dicitonary file and all possible prefixes for those words.
                    'A Trie might be faster but I'm not coding it now. I'm getting good times with this.
                    If i = 0 AndAlso Not BoggleLetters.ContainsValue(Letter) Then Continue While
                    TempWord += Letter
                    If Not HashTableOfPrefixesAndWords.ContainsKey(TempWord) Then
                        HashTableOfPrefixesAndWords.Add(TempWord, TempWord = Word)
                    End If
                Next
            End While

            SB.Append("Number of Word Prefixes and Words in Hashtable: " & HashTableOfPrefixesAndWords.Count.ToString())
            SB.Append("<br />")

            SB.Append("Loading Dictionary: " & Time & " - " & String.Format("{0}:{1}:{2}:{3}", Date.Now.Hour.ToString(), Date.Now.Minute.ToString(), Date.Now.Second.ToString(), Date.Now.Millisecond.ToString()))
            SB.Append("<br />")

            Time = String.Format("{0}:{1}:{2}:{3}", Date.Now.Hour.ToString(), Date.Now.Minute.ToString(), Date.Now.Second.ToString(), Date.Now.Millisecond.ToString())

            'This starts a path at each point on the grid an builds a path until 
            'the string of letters correlating to the path is not found in the hashtable
            'of word prefixes and words.
            Me.BuildAndTestPathsAndFindWords("a")
            Me.BuildAndTestPathsAndFindWords("b")
            Me.BuildAndTestPathsAndFindWords("c")
            Me.BuildAndTestPathsAndFindWords("d")
            Me.BuildAndTestPathsAndFindWords("e")
            Me.BuildAndTestPathsAndFindWords("f")
            Me.BuildAndTestPathsAndFindWords("g")
            Me.BuildAndTestPathsAndFindWords("h")
            Me.BuildAndTestPathsAndFindWords("i")
            Me.BuildAndTestPathsAndFindWords("j")
            Me.BuildAndTestPathsAndFindWords("k")
            Me.BuildAndTestPathsAndFindWords("l")
            Me.BuildAndTestPathsAndFindWords("m")
            Me.BuildAndTestPathsAndFindWords("n")
            Me.BuildAndTestPathsAndFindWords("o")
            Me.BuildAndTestPathsAndFindWords("p")

            SB.Append("Finding Words: " & Time & " - " & String.Format("{0}:{1}:{2}:{3}", Date.Now.Hour.ToString(), Date.Now.Minute.ToString(), Date.Now.Second.ToString(), Date.Now.Millisecond.ToString()))
            SB.Append("<br />")

            SB.Append("Num of words found: " & FoundWords.Count.ToString())
            SB.Append("<br />")
            SB.Append("<br />")

            FoundWords.Sort()
            SB.Append(String.Join("<br />", FoundWords.ToArray()))

            'Output results.
            Me.LiteralBoggleResults.Text = SB.ToString()
            Me.PanelBoggleResults.Visible = True

        End If

    End Sub

End Class

How to uninstall downloaded Xcode simulator?

NOTE: This will only remove a device configuration from the Xcode devices list. To remove the simulator files from your hard drive see the previous answer.

For Xcode 7 just use Window \ Devices menu in Xcode:

Devices menu

Then select emulator to delete in the list on the left side and right click on it. Here is Delete option: enter image description here

That's all.

Having services in React application

The first answer doesn't reflect the current Container vs Presenter paradigm.

If you need to do something, like validate a password, you'd likely have a function that does it. You'd be passing that function to your reusable view as a prop.

Containers

So, the correct way to do it is to write a ValidatorContainer, which will have that function as a property, and wrap the form in it, passing the right props in to the child. When it comes to your view, your validator container wraps your view and the view consumes the containers logic.

Validation could be all done in the container's properties, but it you're using a 3rd party validator, or any simple validation service, you can use the service as a property of the container component and use it in the container's methods. I've done this for restful components and it works very well.

Providers

If there's a bit more configuration necessary, you can use a Provider/Consumer model. A provider is a high level component that wraps somewhere close to and underneath the top application object (the one you mount) and supplies a part of itself, or a property configured in the top layer, to the context API. I then set my container elements to consume the context.

The parent/child context relations don't have to be near each other, just the child has to be descended in some way. Redux stores and the React Router function in this way. I've used it to provide a root restful context for my rest containers (if I don't provide my own).

(note: the context API is marked experimental in the docs, but I don't think it is any more, considering what's using it).

_x000D_
_x000D_
//An example of a Provider component, takes a preconfigured restful.js_x000D_
//object and makes it available anywhere in the application_x000D_
export default class RestfulProvider extends React.Component {_x000D_
 constructor(props){_x000D_
  super(props);_x000D_
_x000D_
  if(!("restful" in props)){_x000D_
   throw Error("Restful service must be provided");_x000D_
  }_x000D_
 }_x000D_
_x000D_
 getChildContext(){_x000D_
  return {_x000D_
   api: this.props.restful_x000D_
  };_x000D_
 }_x000D_
_x000D_
 render() {_x000D_
  return this.props.children;_x000D_
 }_x000D_
}_x000D_
_x000D_
RestfulProvider.childContextTypes = {_x000D_
 api: React.PropTypes.object_x000D_
};
_x000D_
_x000D_
_x000D_

Middleware

A further way I haven't tried, but seen used, is to use middleware in conjunction with Redux. You define your service object outside the application, or at least, higher than the redux store. During store creation, you inject the service into the middleware and the middleware handles any actions that affect the service.

In this way, I could inject my restful.js object into the middleware and replace my container methods with independent actions. I'd still need a container component to provide the actions to the form view layer, but connect() and mapDispatchToProps have me covered there.

The new v4 react-router-redux uses this method to impact the state of the history, for example.

_x000D_
_x000D_
//Example middleware from react-router-redux_x000D_
//History is our service here and actions change it._x000D_
_x000D_
import { CALL_HISTORY_METHOD } from './actions'_x000D_
_x000D_
/**_x000D_
 * This middleware captures CALL_HISTORY_METHOD actions to redirect to the_x000D_
 * provided history object. This will prevent these actions from reaching your_x000D_
 * reducer or any middleware that comes after this one._x000D_
 */_x000D_
export default function routerMiddleware(history) {_x000D_
  return () => next => action => {_x000D_
    if (action.type !== CALL_HISTORY_METHOD) {_x000D_
      return next(action)_x000D_
    }_x000D_
_x000D_
    const { payload: { method, args } } = action_x000D_
    history[method](...args)_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Rollback one specific migration in Laravel

If you want to rollback last migration.

php artisan migrate:rollback

If you want to rollback specific migration then go to migration table and set highest value of that record in batch. Then.

php artisan migrate:rollback

Currently i'm working on laravel 5.8 if not working any other version of laravel please inform to me.

What are the differences between git branch, fork, fetch, merge, rebase and clone?

A clone is simply a copy of a repository. On the surface, its result is equivalent to svn checkout, where you download source code from some other repository. The difference between centralized VCS like Subversion and DVCSs like Git is that in Git, when you clone, you are actually copying the entire source repository, including all the history and branches. You now have a new repository on your machine and any commits you make go into that repository. Nobody will see any changes until you push those commits to another repository (or the original one) or until someone pulls commits from your repository, if it is publicly accessible.

A branch is something that is within a repository. Conceptually, it represents a thread of development. You usually have a master branch, but you may also have a branch where you are working on some feature xyz, and another one to fix bug abc. When you have checked out a branch, any commits you make will stay on that branch and not be shared with other branches until you merge them with or rebase them onto the branch in question. Of course, Git seems a little weird when it comes to branches until you look at the underlying model of how branches are implemented. Rather than explain it myself (I've already said too much, methinks), I'll link to the "computer science" explanation of how Git models branches and commits, taken from the Git website:

http://eagain.net/articles/git-for-computer-scientists/

A fork isn't a Git concept really, it's more a political/social idea. That is, if some people aren't happy with the way a project is going, they can take the source code and work on it themselves separate from the original developers. That would be considered a fork. Git makes forking easy because everyone already has their own "master" copy of the source code, so it's as simple as cutting ties with the original project developers and doesn't require exporting history from a shared repository like you might have to do with SVN.

EDIT: since I was not aware of the modern definition of "fork" as used by sites such as GitHub, please take a look at the comments and also Michael Durrant's answer below mine for more information.

How do you run your own code alongside Tkinter's event loop?

This is the first working version of what will be a GPS reader and data presenter. tkinter is a very fragile thing with way too few error messages. It does not put stuff up and does not tell why much of the time. Very difficult coming from a good WYSIWYG form developer. Anyway, this runs a small routine 10 times a second and presents the information on a form. Took a while to make it happen. When I tried a timer value of 0, the form never came up. My head now hurts! 10 or more times per second is good enough for me. I hope it helps someone else. Mike Morrow

import tkinter as tk
import time

def GetDateTime():
  # Get current date and time in ISO8601
  # https://en.wikipedia.org/wiki/ISO_8601 
  # https://xkcd.com/1179/
  return (time.strftime("%Y%m%d", time.gmtime()),
          time.strftime("%H%M%S", time.gmtime()),
          time.strftime("%Y%m%d", time.localtime()),
          time.strftime("%H%M%S", time.localtime()))

class Application(tk.Frame):

  def __init__(self, master):

    fontsize = 12
    textwidth = 9

    tk.Frame.__init__(self, master)
    self.pack()

    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             text='Local Time').grid(row=0, column=0)
    self.LocalDate = tk.StringVar()
    self.LocalDate.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             textvariable=self.LocalDate).grid(row=0, column=1)

    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             text='Local Date').grid(row=1, column=0)
    self.LocalTime = tk.StringVar()
    self.LocalTime.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             textvariable=self.LocalTime).grid(row=1, column=1)

    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             text='GMT Time').grid(row=2, column=0)
    self.nowGdate = tk.StringVar()
    self.nowGdate.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             textvariable=self.nowGdate).grid(row=2, column=1)

    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             text='GMT Date').grid(row=3, column=0)
    self.nowGtime = tk.StringVar()
    self.nowGtime.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             textvariable=self.nowGtime).grid(row=3, column=1)

    tk.Button(self, text='Exit', width = 10, bg = '#FF8080', command=root.destroy).grid(row=4, columnspan=2)

    self.gettime()
  pass

  def gettime(self):
    gdt, gtm, ldt, ltm = GetDateTime()
    gdt = gdt[0:4] + '/' + gdt[4:6] + '/' + gdt[6:8]
    gtm = gtm[0:2] + ':' + gtm[2:4] + ':' + gtm[4:6] + ' Z'  
    ldt = ldt[0:4] + '/' + ldt[4:6] + '/' + ldt[6:8]
    ltm = ltm[0:2] + ':' + ltm[2:4] + ':' + ltm[4:6]  
    self.nowGtime.set(gdt)
    self.nowGdate.set(gtm)
    self.LocalTime.set(ldt)
    self.LocalDate.set(ltm)

    self.after(100, self.gettime)
   #print (ltm)  # Prove it is running this and the external code, too.
  pass

root = tk.Tk()
root.wm_title('Temp Converter')
app = Application(master=root)

w = 200 # width for the Tk root
h = 125 # height for the Tk root

# get display screen width and height
ws = root.winfo_screenwidth()  # width of the screen
hs = root.winfo_screenheight() # height of the screen

# calculate x and y coordinates for positioning the Tk root window

#centered
#x = (ws/2) - (w/2)
#y = (hs/2) - (h/2)

#right bottom corner (misfires in Win10 putting it too low. OK in Ubuntu)
x = ws - w
y = hs - h - 35  # -35 fixes it, more or less, for Win10

#set the dimensions of the screen and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

root.mainloop()

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Select distinct rows from datatable in Linq

Check this link

get distinct rows from datatable using Linq (distinct with mulitiple columns)

Or try this

var distinctRows = (from DataRow dRow in dTable.Rows
                    select new  {  col1=dRow["dataColumn1"],col2=dRow["dataColumn2"]}).Distinct();

EDIT: Placed the missing first curly brace.

Convert Pandas DataFrame to JSON format

The output that you get after DF.to_json is a string. So, you can simply slice it according to your requirement and remove the commas from it too.

out = df.to_json(orient='records')[1:-1].replace('},{', '} {')

To write the output to a text file, you could do:

with open('file_name.txt', 'w') as f:
    f.write(out)

make div's height expand with its content

No need to use a lot of CSS, just use bootstrap, then use:

class="container"

for the div that needs to be filled.

You can get bootstrap from here

Does 'position: absolute' conflict with Flexbox?

In my case, the issue was that I had another element in the center of the div with a conflicting z-index.

_x000D_
_x000D_
.wrapper {_x000D_
  color: white;_x000D_
  width: 320px;_x000D_
  position: relative;_x000D_
  border: 1px dashed gray;_x000D_
  height: 40px_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  position: absolute;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  top: 20px;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  /* This z-index override is needed to display on top of the other_x000D_
     div. Or, just swap the order of the HTML tags. */_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  background: green;_x000D_
}_x000D_
_x000D_
.conflicting {_x000D_
  position: absolute;_x000D_
  left: 120px;_x000D_
  height: 40px;_x000D_
  background: red;_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="parent">_x000D_
    <div class="child">_x000D_
       Centered_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="conflicting">_x000D_
    Conflicting_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Javascript to display the current date and time

You can try the below:

function formatAMPM() {
    var date = new Date();
    var currDate = date.getDate();
    var hours = date.getHours();
    var dayName = getDayName(date.getDay());
    var minutes = date.getMinutes();
    var monthName = getMonthName(date.getMonth());
    var year = date.getFullYear();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = dayName + ' ' + monthName + ' ' + currDate + ' ' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
    alert(strTime);
}

function getMonthName(month) {
    var ar = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return ar[month];
}

function getDayName(day) {
    var ar1 = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    return ar1[day];
}

EDIT: Refer here for a working demo.

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

<configuration>
 <location path="Path/To/Public/Folder">
  <system.web>
     <authorization>
        <allow users="?"/>
     </authorization>
  </system.web>
 </location>
</configuration>

Seeking useful Eclipse Java code templates

And an equalsbuilder, hashcodebuilder adaptation:

${:import(org.apache.commons.lang.builder.EqualsBuilder,org.apache.commons.lang.builder.HashCodeBuilder)}
@Override
public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
}

@Override
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}

How do I change db schema to dbo

ALTER SCHEMA dbo TRANSFER jonathan.MovieData;

See ALTER SCHEMA.

Generalized Syntax:

ALTER SCHEMA TargetSchema TRANSFER SourceSchema.TableName; 

How do I get Bin Path?

var assemblyPath = Assembly.GetExecutingAssembly().CodeBase;

How to pattern match using regular expression in Scala?

Since version 2.10, one can use Scala's string interpolation feature:

implicit class RegexOps(sc: StringContext) {
  def r = new util.matching.Regex(sc.parts.mkString, sc.parts.tail.map(_ => "x"): _*)
}

scala> "123" match { case r"\d+" => true case _ => false }
res34: Boolean = true

Even better one can bind regular expression groups:

scala> "123" match { case r"(\d+)$d" => d.toInt case _ => 0 }
res36: Int = 123

scala> "10+15" match { case r"(\d\d)${first}\+(\d\d)${second}" => first.toInt+second.toInt case _ => 0 }
res38: Int = 25

It is also possible to set more detailed binding mechanisms:

scala> object Doubler { def unapply(s: String) = Some(s.toInt*2) }
defined module Doubler

scala> "10" match { case r"(\d\d)${Doubler(d)}" => d case _ => 0 }
res40: Int = 20

scala> object isPositive { def unapply(s: String) = s.toInt >= 0 }
defined module isPositive

scala> "10" match { case r"(\d\d)${d @ isPositive()}" => d.toInt case _ => 0 }
res56: Int = 10

An impressive example on what's possible with Dynamic is shown in the blog post Introduction to Type Dynamic:

object T {

  class RegexpExtractor(params: List[String]) {
    def unapplySeq(str: String) =
      params.headOption flatMap (_.r unapplySeq str)
  }

  class StartsWithExtractor(params: List[String]) {
    def unapply(str: String) =
      params.headOption filter (str startsWith _) map (_ => str)
  }

  class MapExtractor(keys: List[String]) {
    def unapplySeq[T](map: Map[String, T]) =
      Some(keys.map(map get _))
  }

  import scala.language.dynamics

  class ExtractorParams(params: List[String]) extends Dynamic {
    val Map = new MapExtractor(params)
    val StartsWith = new StartsWithExtractor(params)
    val Regexp = new RegexpExtractor(params)

    def selectDynamic(name: String) =
      new ExtractorParams(params :+ name)
  }

  object p extends ExtractorParams(Nil)

  Map("firstName" -> "John", "lastName" -> "Doe") match {
    case p.firstName.lastName.Map(
          Some(p.Jo.StartsWith(fn)),
          Some(p.`.*(\\w)$`.Regexp(lastChar))) =>
      println(s"Match! $fn ...$lastChar")
    case _ => println("nope")
  }
}

AngularJS: Service vs provider vs factory

From the AngularJS mailing list I got an amazing thread that explains service vs factory vs provider and their injection usage. Compiling the answers:

Services

Syntax: module.service( 'serviceName', function );
Result: When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService().

Factories

Syntax: module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Providers

Syntax: module.provider( 'providerName', function );
Result: When declaring providerName as an injectable argument you will be provided with (new ProviderFunction()).$get(). The constructor function is instantiated before the $get method is called - ProviderFunction is the function reference passed to module.provider.

Providers have the advantage that they can be configured during the module configuration phase.

See here for the provided code.

Here's a great further explanation by Misko:

provide.value('a', 123);

function Controller(a) {
  expect(a).toEqual(123);
}

In this case the injector simply returns the value as is. But what if you want to compute the value? Then use a factory

provide.factory('b', function(a) {
  return a*2;
});

function Controller(b) {
  expect(b).toEqual(246);
}

So factory is a function which is responsible for creating the value. Notice that the factory function can ask for other dependencies.

But what if you want to be more OO and have a class called Greeter?

function Greeter(a) {
  this.greet = function() {
    return 'Hello ' + a;
  }
}

Then to instantiate you would have to write

provide.factory('greeter', function(a) {
  return new Greeter(a);
});

Then we could ask for 'greeter' in controller like this

function Controller(greeter) {
  expect(greeter instanceof Greeter).toBe(true);
  expect(greeter.greet()).toEqual('Hello 123');
}

But that is way too wordy. A shorter way to write this would be provider.service('greeter', Greeter);

But what if we wanted to configure the Greeter class before the injection? Then we could write

provide.provider('greeter2', function() {
  var salutation = 'Hello';
  this.setSalutation = function(s) {
    salutation = s;
  }

  function Greeter(a) {
    this.greet = function() {
      return salutation + ' ' + a;
    }
  }

  this.$get = function(a) {
    return new Greeter(a);
  };
});

Then we can do this:

angular.module('abc', []).config(function(greeter2Provider) {
  greeter2Provider.setSalutation('Halo');
});

function Controller(greeter2) {
  expect(greeter2.greet()).toEqual('Halo 123');
}

As a side note, service, factory, and value are all derived from provider.

provider.service = function(name, Class) {
  provider.provide(name, function() {
    this.$get = function($injector) {
      return $injector.instantiate(Class);
    };
  });
}

provider.factory = function(name, factory) {
  provider.provide(name, function() {
    this.$get = function($injector) {
      return $injector.invoke(factory);
    };
  });
}

provider.value = function(name, value) {
  provider.factory(name, function() {
    return value;
  });
};

How to create a JSON object

Although the other answers posted here work, I find the following approach more natural:

$obj = (object) [
    'aString' => 'some string',
    'anArray' => [ 1, 2, 3 ]
];

echo json_encode($obj);

CSV new-line character seen in unquoted field error

I know this has been answered for quite some time but not solve my problem. I am using DictReader and StringIO for my csv reading due to some other complications. I was able to solve problem more simply by replacing delimiters explicitly:

with urllib.request.urlopen(q) as response:
    raw_data = response.read()
    encoding = response.info().get_content_charset('utf8') 
    data = raw_data.decode(encoding)
    if '\r\n' not in data:
        # proably a windows delimited thing...try to update it
        data = data.replace('\r', '\r\n')

Might not be reasonable for enormous CSV files, but worked well for my use case.

How to run html file using node js

Either you use a framework or you write your own server with nodejs.

A simple fileserver may look like this:

import * as http from 'http';
import * as url from 'url';
import * as fs from 'fs';
import * as path from 'path';

var mimeTypes = {
     "html": "text/html",
     "jpeg": "image/jpeg",
     "jpg": "image/jpeg",
     "png": "image/png",
     "js": "text/javascript",
     "css": "text/css"};

http.createServer((request, response)=>{
    var pathname = url.parse(request.url).pathname;
    var filename : string;
    if(pathname === "/"){
        filename = "index.html";
    }
    else
        filename = path.join(process.cwd(), pathname);

    try{
        fs.accessSync(filename, fs.F_OK);
        var fileStream = fs.createReadStream(filename);
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        response.writeHead(200, {'Content-Type':mimeType});
        fileStream.pipe(response);
    }
    catch(e) {
            console.log('File not exists: ' + filename);
            response.writeHead(404, {'Content-Type': 'text/plain'});
            response.write('404 Not Found\n');
            response.end();
            return;
    }
    return;
    }
}).listen(5000);

Android button font size

I tried to put the font size in the styles.xml but when i went to use it it was only allowing resources from the dimen folder so put it in there instead, dont know it this is right

        <Button
                android:layout_weight="1"
                android:id="@+id/three_btn"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:onClick="onButtonClick"
                android:textColor="#EEEEEE"
                android:textStyle="bold"
                android:textSize="@dimen/buttonFontSize"
                android:text="3"/>

jQuery vs. javascript?

  • Does jQuery heavily rely on browser sniffing? Could be that potential problem in future? Why?

No - there is the $.browser method, but it's deprecated and isn't used in the core.

  • I found plenty JS-selector engines, are there any AJAX and FX libraries?

Loads. jQuery is often chosen because it does AJAX and animations well, and is easily extensible. jQuery doesn't use it's own selector engine, it uses Sizzle, an incredibly fast selector engine.

  • Is there any reason (besides browser sniffing and personal "hate" against John Resig) why jQuery is wrong?

No - it's quick, relatively small and easy to extend.

For me personally it's nice to know that as browsers include more stuff (classlist API for example) that jQuery will update to include it, meaning that my code runs as fast as possible all the time.

Read through the source if you are interested, http://code.jquery.com/jquery-1.4.3.js - you'll see that features are added based on the best case first, and gradually backported to legacy browsers - for example, a section of the parseJSON method from 1.4.3:

return window.JSON && window.JSON.parse ?
    window.JSON.parse( data ) :
    (new Function("return " + data))();

As you can see, if window.JSON exists, the browser uses the native JSON parser, if not, then it avoids using eval (because otherwise minfiers won't minify this bit) and sets up a function that returns the data. This idea of assuming modern techniques first, then degrading to older methods is used throughout meaning that new browsers get to use all the whizz bang features without sacrificing legacy compatibility.

How to execute a bash command stored as a string with quotes and asterisk

To eliminate the need for the cmd variable, you can do this:

eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'

Passing data through intent using Serializable

Try to pass the serializable list using Bundle.Serializable:

Bundle bundle = new Bundle();
bundle.putSerializable("value", all_thumbs);
intent.putExtras(bundle);

And in SomeClass Activity get it as:

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();

List<Thumbnail> thumbs=
               (List<Thumbnail>)bundle.getSerializable("value");

What is sr-only in Bootstrap 3?

.sr-only is a class name specifically used for screen readers. You can use any class name, but .sr-only is pretty commonly used. If you don't care about developing with compliance in mind, then it can be removed. It will not affect UI in any way if removed because the CSS for this class is not visible to desktop and mobile device browsers.

There seems to be some information missing here about the use of .sr-only to explain its purpose and being for screen readers. First and foremost, it is very important to always keep impaired users in mind. Impairment is the purpose of 508 compliance: https://www.section508.gov/, and it is great that bootstrap takes this into consideration. However, the use of .sr-only is not all that needs to be taken into consideration for 508 compliance. You have the use of color, size of fonts, accessibility via navigation, descriptors, use of aria and so much more.

But as for .sr-only - what does the CSS actually do? There are several slightly different variants of the CSS used for .sr-only. One of the few I use is below:

.sr-only {
    position: absolute;
    margin: -1px 0 0 -1px;
    padding: 0;
    display: block;
    width: 1px;
    height: 1px;
    font-size: 1px;
    line-height: 1px;
    overflow: hidden;
    clip: rect(0,0,0,0);
    border: 0;
    outline: 0;
    }

The above CSS hides content in desktop and mobile browsers wrapped with this class, but is seen by a screen reader like JAWS: http://www.freedomscientific.com/Products/Blindness/JAWS. Example markup is as follows:

<a href="#" target="_blank">
    Click to Open Site
    <span class="sr-only">This is an external link</span>
</a>

Additionally, if a DOM element has a width and height of 0, the element is not seen by the DOM. This is why the above CSS uses width: 1px; height: 1px;. By using display: none and setting your CSS to height: 0 and width: 0, the element is not seen by the DOM and is thus problematic. The above CSS using width: 1px; height: 1px; is not all you do to make the content invisible to desktop and mobile browsers (without overflow: hidden, your content would still show on the screen), and visible to screen readers. Hiding the content from desktop and mobile browsers is done by adding an offset from width: 1px and height: 1px previously mentioned by using:

position: absolute;
margin: -1px 0 0 -1px; 
overflow: hidden;

Lastly, to have a very good idea of what a screen reader sees and relays to its impaired user, turn off page styling for your browser. For Firefox, you can do this by going to:

View > Page Style > No Style

I hope the information I provided here is of further use to someone in addition to the other responses.

Fast way to get the min/max values among properties of object

var newObj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
var maxValue = Math.max(...Object.values(newObj))
var minValue = Math.min(...Object.values(newObj))

python, sort descending dataframe with pandas

Edit: This is out of date, see @Merlin's answer.

[False], being a nonempty list, is not the same as False. You should write:

test = df.sort('one', ascending=False)

How to adjust the size of y axis labels only in R?

As the title suggests that we want to adjust the size of the labels and not the tick marks I figured that I actually might add something to the question, you need to use the mtext() if you want to specify one of the label sizes, or you can just use par(cex.lab=2) as a simple alternative. Here's a more advanced mtext() example:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data=foo,
     yaxt="n", ylab="", 
     xlab="Regular boring x", 
     pch=16,
     col="darkblue")
axis(2,cex.axis=1.2)
mtext("Awesome Y variable", side=2, line=2.2, cex=2)

enter image description here

You may need to adjust the line= option to get the optimal positioning of the text but apart from that it's really easy to use.

Adding a guideline to the editor in Visual Studio

If you are a user of the free Visual Studio Express edition the right key is in

HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\Text Editor

{note the VCExpress instead of VisualStudio) but it works! :)

Limit String Length

To truncate a string provided by the maximum limit without breaking a word use this:

/**
 * truncate a string provided by the maximum limit without breaking a word
 * @param string $str
 * @param integer $maxlen
 * @return string
 */
public static function truncateStringWords($str, $maxlen): string
{
    if (strlen($str) <= $maxlen) return $str;

    $newstr = substr($str, 0, $maxlen);
    if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));

    return $newstr;
}

Key existence check in HashMap

The Jon Skeet answer addresses well the two scenarios (map with null value and not null value) in an efficient way.

About the number entries and the efficiency concern, I would like add something.

I have a HashMap with say a 1.000 entries and I am looking at improving the efficiency. If the HashMap is being accessed very frequently, then checking for the key existence at every access will lead to a large overhead.

A map with 1.000 entries is not a huge map.
As well as a map with 5.000 or 10.000 entries.
Map are designed to make fast retrieval with such dimensions.

Now, it assumes that hashCode() of the map keys provides a good distribution.

If you may use an Integer as key type, do it.
Its hashCode() method is very efficient since the collisions are not possible for unique int values :

public final class Integer extends Number implements Comparable<Integer> {
    ...
    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }

    public static int hashCode(int value) {
        return value;
    }
    ...
}

If for the key, you have to use another built-in type as String for example that is often used in Map, you may have some collisions but from 1 thousand to some thousands of objects in the Map, you should have very few of it as the String.hashCode() method provides a good distribution.

If you use a custom type, override hashCode() and equals() correctly and ensure overall that hashCode() provides a fair distribution.
You may refer to the item 9 of Java Effective refers it.
Here's a post that details the way.

Multiplication on command line terminal

Yes, you can use bash's built-in Arithmetic Expansion $(( )) to do some simple maths

$ echo "$((5 * 5))"
25

Check the Shell Arithmetic section in the Bash Reference Manual for a complete list of operators.

For sake of completeness, as other pointed out, if you need arbitrary precision, bc or dc would be better.

Intersect Two Lists in C#

You need to first transform data1, in your case by calling ToString() on each element.

Use this if you want to return strings.

List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};

var newData = data1.Select(i => i.ToString()).Intersect(data2);

Use this if you want to return integers.

List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};

var newData = data1.Intersect(data2.Select(s => int.Parse(s));

Note that this will throw an exception if not all strings are numbers. So you could do the following first to check:

int temp;
if(data2.All(s => int.TryParse(s, out temp)))
{
    // All data2 strings are int's
}

Undo a merge by pull request?

Starting June 24th, 2014, you can try cancel a PR easily (See "Reverting a pull request") with:

Introducing the Revert Button

you can easily revert a pull request on GitHub by clicking Revert:

https://camo.githubusercontent.com/0d3350caf2bb1cba53123ffeafc00ca702b1b164/68747470733a2f2f6769746875622d696d616765732e73332e616d617a6f6e6177732e636f6d2f68656c702f70756c6c5f72657175657374732f7265766572742d70756c6c2d726571756573742d6c696e6b2e706e67

You'll be prompted to create a new pull request with the reverted changes:

https://camo.githubusercontent.com/973efae3cc2764fc1353885a6a45b9a518d9b78b/68747470733a2f2f6769746875622d696d616765732e73332e616d617a6f6e6177732e636f6d2f68656c702f70756c6c5f72657175657374732f7265766572742d70756c6c2d726571756573742d6e65772d70722e706e67

It remains to be tested though if that revert uses -m or not (for reverting merges as well)

But Adil H Raza adds in the comments (Dec. 2019):

That is the expected behavior, it created a new branch and you can create a PR from this new branch to your master.
This way in the future you can un-revert the revert if need be, it is safest option and not directly changing your master.


Warning: Korayem points out in the comments that:

After a revert, let's say you did some further changes on Git branch and created a new PR from same source/destination branch.
You will find the PR showing only new changes, but nothing of what was there before reverting.

Korayem refers us to "Github: Changes ignored after revert (git cherry-pick, git rebase)" for more.

Distribution certificate / private key not installed

  1. go to this link https://developer.apple.com/account/resources/certificates/list

  2. find certificate name in your alert upload then

  3. Revoke certificate that

  4. if you have certificate you download again
  5. upload testflight again

Java JSON serialization - best practice

Well, when writing it out to file, you do know what class T is, so you can store that in dump. Then, when reading it back in, you can dynamically call it using reflection.

public JSONObject dump() throws JSONException {
    JSONObject result = new JSONObject();
    JSONArray a = new JSONArray();
    for(T i : items){
        a.put(i.dump());
        // inside this i.dump(), store "class-name"
    }
    result.put("items", a);
    return result;
}

public void load(JSONObject obj) throws JSONException {
    JSONArray arrayItems = obj.getJSONArray("items");
    for (int i = 0; i < arrayItems.length(); i++) {
        JSONObject item = arrayItems.getJSONObject(i);
        String className = item.getString("class-name");
        try {
            Class<?> clazzy = Class.forName(className);
            T newItem = (T) clazzy.newInstance();
            newItem.load(obj);
            items.add(newItem);
        } catch (InstantiationException e) {
            // whatever
        } catch (IllegalAccessException e) {
            // whatever
        } catch (ClassNotFoundException e) {
            // whatever
        }
    }

What is the difference between HTTP status code 200 (cache) vs status code 304?

For your last question, why ? I'll try to explain with what I know

A brief explanation of those three status codes in layman's terms.

  • 200 - success (browser requests and get file from server)

If caching is enabled in the server

  • 200 (from memory cache) - file found in browser, so browser is not going request from server
  • 304 - browser request a file but it is rejected by server

For some files browser is deciding to request from server and for some it's deciding to read from stored (cached) files. Why is this ? Every files has an expiry date, so

If a file is not expired then the browser will use from cache (200 cache).

If file is expired, browser requests server for a file. Server check file in both places (browser and server). If same file found, server refuses the request. As per protocol browser uses existing file.

look at this nginx configuration

location / {
    add_header Cache-Control must-revalidate;
    expires     60;
    etag on;

    ...
}

Here the expiry is set to 60 seconds, so all static files are cached for 60 seconds. So if u request a file again within 60 seconds browser will read from memory (200 memory). If u request after 60 seconds browser will request server (304).

I assumed that the file is not changed after 60 seconds, in that case you would get 200 (ie, updated file will be fetched from server).

So, if the servers are configured with different expiring and caching headers (policies), the status may differ.

In your case you are using cdn, the main purpose of cdn is high availability and fast delivery. Therefore they use multiple servers. Even though it seems like files are in same directory, cdn might use multiple servers to provide u content, if those servers have different configurations. Then these status can change. Hope it helps.

Process to convert simple Python script into Windows executable

1) Get py2exe from here, according to your Python version.

2) Make a file called "setup.py" in the same folder as the script you want to convert, having the following code:

from distutils.core import setup
import py2exe
setup(console=['myscript.py']) #change 'myscript' to your script

3) Go to command prompt, navigate to that folder, and type:

python setup.py py2exe

4) It will generate a "dist" folder in the same folder as the script. This folder contains the .exe file.

Error running android: Gradle project sync failed. Please fix your project and try again

I had the same issue yesterday. After opening the "Android SDK Manager", updating all packages and restarting Android Studio, the project compiled again.

CMD command to check connected USB devices

You could use wmic command:

wmic logicaldisk where drivetype=2 get <DeviceID, VolumeName, Description, ...>

Drivetype 2 indicates that its a removable disk.

Latex Multiple Linebreaks

You can use the setspace package which gives you spacing environments, e.g.:

\documentclass{article}
\usepackage{setspace}
\begin{document}
\doublespace
my line of text blah blah blah

new line of text with blank line between
\end{document}

Or use a verbatim environment to control the layout of your code precisely.

How to uninstall a package installed with pip install --user

As @thomas-lotze has mentioned, currently pip tooling does not do that as there is no corresponding --user option. But what I find is that I can check in ~/.local/bin and look for the specific pip#.# which looks to me like it corresponds to the --user option.

In my case:

antho@noctil: ~/.l/bin$ pwd
/home/antho/.local/bin
antho@noctil: ~/.l/bin$ ls pip*
pip  pip2  pip2.7  pip3  pip3.5

And then just uninstall with the specific pip version.

JTable How to refresh table model after insert delete or update the data.

try this

public void setUpTableData() {
    DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();

    /**
    * additional code.
    **/
    tableModel.setRowCount(0);
    /**/
    ArrayList<Contact> list = new ArrayList<Contact>();
    if (!con.equals(""))
        list = sql.getContactListsByGroup(con);
    else
        list = sql.getContactLists();
    for (int i = 0; i < list.size(); i++) {
        String[] data = new String[7];

        data[0] = list.get(i).getName();
        data[1] = list.get(i).getEmail();
        data[2] = list.get(i).getPhone1();
        data[3] = list.get(i).getPhone2();
        data[4] = list.get(i).getGroup();
        data[5] = list.get(i).getId();

        tableModel.addRow(data);
    }
    jTable.setModel(tableModel);
    /**
    * additional code.
    **/
    tableModel.fireTableDataChanged();
    /**/
}

Html.RenderPartial() syntax with Razor

@Html.Partial("NameOfPartialView")

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

I had the same problem what caused it was that I already had created a pod from the docker image via the .yml file, however I mistyped the name, i.e test-app:1.0.1 when I needed test-app:1.0.2 in my .yml file. So I did kubectl delete pods --all to remove the faulty pod then redid the kubectl create -f name_of_file.yml which solved my problem.

Restoring MySQL database from physical files

I have the same problem but was not able to successfully recover the database, based on the instructions above.

I was only able to recover mysql database folders from my Ubuntu OS. My problem is how to recover my database with those unreadable mysql data folders. So I switched back to win7 OS for development environment.

*NOTE I have an existing database server running in win7 and I only need few database files to retrieve from the recovered files. To successfully recover the database files from Ubuntu OS I need to freshly install mysql database server (same version from Ubuntu OS in my win7 OS) to recover everything in that old database server.

  1. Make another new mysql database server same version from the recovered files.

  2. Stop the mysql server

  3. copy the recovered folder and paste in the (C:\ProgramData\MySQL\MySQL Server 5.5\data) mysql database is stored.

  4. copy the ibdata1 file located in linux mysql installed folder and paste it in (C:\ProgramData\MySQL\MySQL Server 5.5\data). Just overwrite the existing or make backup before replacing.

  5. start the mysql server and check if you have successfully recovered the database files.

  6. To use the recovered database in my currently used mysql server simply export the recovered database and import it my existing mysql server.

Hope these will help, because nothing else worked for me.

Avoid printStackTrace(); use a logger call instead

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

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

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

Why does Node.js' fs.readFile() return a buffer instead of string?

Try:

    fs.readFile("test.txt", "utf8", function(err, data) {...});

Basically, you need to specify the encoding.

open read and close a file in 1 line of code

Python Standard Library Pathlib module does what you looking for:

Path('pagehead.section.htm').read_text()

Don't forget to import Path:

jsk@dev1:~$ python3
Python 3.5.2 (default, Sep 10 2016, 08:21:44)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pathlib import Path
>>> (Path("/etc") / "hostname").read_text()
'dev1.example\n'

On Python 27 install backported pathlib or pathlib2

How to convert object to Dictionary<TKey, TValue> in C#?

object parsedData = se.Deserialize(reader);
System.Collections.IEnumerable stksEnum = parsedData as System.Collections.IEnumerable;

then will be able to enumerate it!

Aggregate multiple columns at once

You could try:

agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)

How can I convert a string to boolean in JavaScript?

function convertBoolean(value): boolean {
    if (typeof value == 'string') {
        value = value.toLowerCase();
    }
    switch (value) {
        case true:
        case "true":
        case "evet": // Locale
        case "t":
        case "e": // Locale
        case "1":
        case "on":
        case "yes":
        case 1:
            return true;
        case false:
        case "false":
        case "hayir": // Locale
        case "f":
        case "h": // Locale
        case "0":
        case "off":
        case "no":
        case 0:
            return false;
        default:
            return null;
    }
}

Windows 8.1 gets Error 720 on connect VPN

Based on the Microsoft support KBs, this can occur if TCP/IP is damaged or is not bound to your dial-up adapter.You can try reinstalling or resetting TCP/IP as follows:

  • Reset TCP/IP to Original Configuration- Using the NetShell utility, type this command (in CommandLine): netsh int ip reset [file_name.txt], [file_name.txt] is the name of the file where the actions taken by NetShell are record, for example netsh hint ip reset fixtcpip.txt.

  • Remove and re-install NIC – Open Controller and select System. Click Hardware tab and select devices. Double-click on Network Adapter and right-click on the NIC, select Uninstall. Restart the computer and the Windows should auto detect the NIC and re-install it.

  • Upgrade the NIC driver – You may download the latest NIC driver and upgrade the driver.

Hope it could help.

How to make a section of an image a clickable link

You can auto generate Image map from this website for selected area of image. https://www.image-map.net/

Easiest way to execute!

Access Form - Syntax error (missing operator) in query expression

I was able to quickly fix it by going into Design View of the Form and putting [] around any field names that had spaces. I am now able to use the built in filters without the annoying popup about syntax problems.

Vector of Vectors to create matrix

As it is, both dimensions of your vector are 0.

Instead, initialize the vector as this:

vector<vector<int> > matrix(RR);
for ( int i = 0 ; i < RR ; i++ )
   matrix[i].resize(CC);

This will give you a matrix of dimensions RR * CC with all elements set to 0.

ngFor with index as value in attribute

In Angular 5/6/7/8:

<ul>
  <li *ngFor="let item of items; index as i">
    {{i+1}} {{item}}
  </li>
</ul>

In older versions

<ul *ngFor="let item of items; index as i">
  <li>{{i+1}} {{item}}</li>
</ul>

Angular.io ? API ? NgForOf

Unit test examples

Another interesting example

android pinch zoom

Updated Answer

Code can be found here : official-doc

Answer Outdated

Check out the following links which may help you

Best examples are provided in the below links, which you can refactor to meet your requirements.

  1. implementing-the-pinch-zoom-gestur

  2. Android-pinch

  3. GestureDetector.SimpleOnGestureListener

Android sample bluetooth code to send a simple string via bluetooth

I made the following code so that even beginners can understand. Just copy the code and read comments. Note that message to be send is declared as a global variable which you can change just before sending the message. General changes can be done in Handler function.

multiplayerConnect.java

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

public class multiplayerConnect extends AppCompatActivity {

public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Set<BluetoothDevice> set_pairedDevices;
ArrayAdapter adapter_paired_devices;
BluetoothAdapter bluetoothAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static final int MESSAGE_READ=0;
public static final int MESSAGE_WRITE=1;
public static final int CONNECTING=2;
public static final int CONNECTED=3;
public static final int NO_SOCKET_FOUND=4;


String bluetooth_message="00";




@SuppressLint("HandlerLeak")
Handler mHandler=new Handler()
{
    @Override
    public void handleMessage(Message msg_type) {
        super.handleMessage(msg_type);

        switch (msg_type.what){
            case MESSAGE_READ:

                byte[] readbuf=(byte[])msg_type.obj;
                String string_recieved=new String(readbuf);

                //do some task based on recieved string

                break;
            case MESSAGE_WRITE:

                if(msg_type.obj!=null){
                    ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
                    connectedThread.write(bluetooth_message.getBytes());

                }
                break;

            case CONNECTED:
                Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
                break;

            case CONNECTING:
                Toast.makeText(getApplicationContext(),"Connecting...",Toast.LENGTH_SHORT).show();
                break;

            case NO_SOCKET_FOUND:
                Toast.makeText(getApplicationContext(),"No socket found",Toast.LENGTH_SHORT).show();
                break;
        }
    }
};



@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.multiplayer_bluetooth);
    initialize_layout();
    initialize_bluetooth();
    start_accepting_connection();
    initialize_clicks();

}

public void start_accepting_connection()
{
    //call this on button click as suited by you

    AcceptThread acceptThread = new AcceptThread();
    acceptThread.start();
    Toast.makeText(getApplicationContext(),"accepting",Toast.LENGTH_SHORT).show();
}
public void initialize_clicks()
{
    lv_paired_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Object[] objects = set_pairedDevices.toArray();
            BluetoothDevice device = (BluetoothDevice) objects[position];

            ConnectThread connectThread = new ConnectThread(device);
            connectThread.start();

            Toast.makeText(getApplicationContext(),"device choosen "+device.getName(),Toast.LENGTH_SHORT).show();
        }
    });
}

public void initialize_layout()
{
    lv_paired_devices = (ListView)findViewById(R.id.lv_paired_devices);
    adapter_paired_devices = new ArrayAdapter(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item);
    lv_paired_devices.setAdapter(adapter_paired_devices);
}

public void initialize_bluetooth()
{
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        // Device doesn't support Bluetooth
        Toast.makeText(getApplicationContext(),"Your Device doesn't support bluetooth. you can play as Single player",Toast.LENGTH_SHORT).show();
        finish();
    }

    //Add these permisions before
//        <uses-permission android:name="android.permission.BLUETOOTH" />
//        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
//        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
//        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    if (!bluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    else {
        set_pairedDevices = bluetoothAdapter.getBondedDevices();

        if (set_pairedDevices.size() > 0) {

            for (BluetoothDevice device : set_pairedDevices) {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address

                adapter_paired_devices.add(device.getName() + "\n" + device.getAddress());
            }
        }
    }
}


public class AcceptThread extends Thread
{
    private final BluetoothServerSocket serverSocket;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("NAME",MY_UUID);
        } catch (IOException e) { }
        serverSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                break;
            }

            // If a connection was accepted
            if (socket != null)
            {
                // Do work to manage the connection (in a separate thread)
                mHandler.obtainMessage(CONNECTED).sendToTarget();
            }
        }
    }
}


private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        bluetoothAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mHandler.obtainMessage(CONNECTING).sendToTarget();

            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
//            bluetooth_message = "Initial message"
//            mHandler.obtainMessage(MESSAGE_WRITE,mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
private class ConnectedThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[2];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();

            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
}

multiplayer_bluetooth.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Challenge player"/>

    <ListView
        android:id="@+id/lv_paired_devices"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
    </ListView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Make sure Device is paired"/>

</LinearLayout>

How to check the version of scipy

Using command line:

python -c "import scipy; print(scipy.__version__)"

How can I tell how many objects I've stored in an S3 bucket?

3Hub is discontinued. There's a better solution, you can use Transmit (Mac only), then you just connect to your bucket and choose Show Item Count from the View menu.

Pandas KeyError: value not in index

please try this to clean and format your column names:

df.columns = (df.columns.str.strip().str.upper()
              .str.replace(' ', '_')
              .str.replace('(', '')
              .str.replace(')', ''))

How to obtain the chat_id of a private Telegram channel?

For now you can write an invite link to bot @username_to_id_bot and you will get the id:

example: enter image description here

also works with public chats, channels and even users

Winforms issue - Error creating window handle

Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns... Then run your app and take a look at those columns for that app and see if one of those is growing really large.

It might be that you've got UI components that you think are cleaned up but haven't been Disposed.

Here's a link about this that might be helpful.

Good Luck!

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

Overflow:hidden dots at the end

Hopefully it's helpful for you:

_x000D_
_x000D_
.text-with-dots {_x000D_
    display: block;_x000D_
    max-width: 98%;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden !important;_x000D_
    text-overflow: ellipsis;_x000D_
}
_x000D_
<div class='text-with-dots'>Some texts here Some texts here Some texts here Some texts here Some texts here Some texts here </div>
_x000D_
_x000D_
_x000D_

What does 'var that = this;' mean in JavaScript?

This is a hack to make inner functions (functions defined inside other functions) work more like they should. In javascript when you define one function inside another this automatically gets set to the global scope. This can be confusing because you expect this to have the same value as in the outer function.

var car = {};
car.starter = {};

car.start = function(){
    var that = this;

    // you can access car.starter inside this method with 'this'
    this.starter.active = false;

    var activateStarter = function(){
        // 'this' now points to the global scope
        // 'this.starter' is undefined, so we use 'that' instead.
        that.starter.active = true;

        // you could also use car.starter, but using 'that' gives
        // us more consistency and flexibility
    };

    activateStarter();

};

This is specifically a problem when you create a function as a method of an object (like car.start in the example) then create a function inside that method (like activateStarter). In the top level method this points to the object it is a method of (in this case, car) but in the inner function this now points to the global scope. This is a pain.

Creating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). This is why the very general sounding name that is used. It's an easily recognizable convention for overcoming a shortcoming in the language.

Like El Ronnoco hints at Douglas Crockford thinks this is a good idea.

Calling class staticmethod within the class body?

What about this solution? It does not rely on knowledge of @staticmethod decorator implementation. Inner class StaticMethod plays as a container of static initialization functions.

class Klass(object):

    class StaticMethod:
        @staticmethod  # use as decorator
        def _stat_func():
            return 42

    _ANS = StaticMethod._stat_func()  # call the staticmethod

    def method(self):
        ret = self.StaticMethod._stat_func() + Klass._ANS
        return ret

Simplest way to form a union of two lists

I think this is all you really need to do:

var listB = new List<int>{3, 4, 5};
var listA = new List<int>{1, 2, 3, 4, 5};

var listMerged = listA.Union(listB);

Print a list in reverse order with range()?

Readibility aside, reversed(range(n)) seems to be faster than range(n)[::-1].

$ python -m timeit "reversed(range(1000000000))"
1000000 loops, best of 3: 0.598 usec per loop
$ python -m timeit "range(1000000000)[::-1]"
1000000 loops, best of 3: 0.945 usec per loop

Just if anyone was wondering :)

How do I import a Swift file from another Swift file?

As @high6 and @erik-p-hansen pointed out in the answer given by @high6, this can be overcome by importing the target for the module where the PrimeNumberModel class is, which is probably the same name as your project in a simple project.

While looking at this, I came across the article Write your first Unit Test in Swift on swiftcast.tv by Clayton McIlrath. It discusses access modifiers, shows an example of the same problem you are having (but for a ViewController rather than a model file) and shows how to both import the target and solve the access modifier problem by including the destination file in the target, meaning you don't have to make the class you are trying to test public unless you actually want to do so.

CSS media query to target only iOS devices

Yes, you can.

@supports (-webkit-touch-callout: none) {
  /* CSS specific to iOS devices */ 
}

@supports not (-webkit-touch-callout: none) {
  /* CSS for other than iOS devices */ 
}

YMMV.

It works because only Safari Mobile implements -webkit-touch-callout: https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-touch-callout

Please note that @supports does not work in IE. IE will skip both of the above @support blocks above. To find out more see https://hacks.mozilla.org/2016/08/using-feature-queries-in-css/. It is recommended to not use @supports not because of this.

What about Chrome or Firefox on iOS? The reality is these are just skins over the WebKit rendering engine. Hence the above works everywhere on iOS as long as iOS policy does not change. See 2.5.6 in App Store Review Guidelines.

Warning: iOS may remove support for this in any new iOS release in the coming years. You SHOULD try a bit harder to not need the above CSS. An earlier version of this answer used -webkit-overflow-scrolling but a new iOS version removed it. As a commenter pointed out, there are other options to choose from: Go to Supported CSS Properties and search for "Safari on iOS".

Completely cancel a rebase

You are lucky that you didn't complete the rebase, so you can still do git rebase --abort. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.

Create Django model or update if exists

It's unclear whether your question is asking for the get_or_create method (available from at least Django 1.3) or the update_or_create method (new in Django 1.7). It depends on how you want to update the user object.

Sample use is as follows:

# In both cases, the call will get a person object with matching
# identifier or create one if none exists; if a person is created,
# it will be created with name equal to the value in `name`.

# In this case, if the Person already exists, its existing name is preserved
person, created = Person.objects.get_or_create(
        identifier=identifier, defaults={"name": name}
)

# In this case, if the Person already exists, its name is updated
person, created = Person.objects.update_or_create(
        identifier=identifier, defaults={"name": name}
)

How abstraction and encapsulation differ?

I will try to demonstrate Encapsulation and Abstraction in a simple way.. Lets see..

  • The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Encapsulation containing and hiding information about an object, such as internal data structures and code.

Encapsulation is -

  • Hiding Complexity,
  • Binding Data and Function together,
  • Making Complicated Method's Private,
  • Making Instance Variable's Private,
  • Hiding Unnecessary Data and Functions from End User.

Encapsulation implements Abstraction.

And Abstraction is -

  • Showing Whats Necessary,
  • Data needs to abstract from End User,

Lets see an example-

The below Image shows a GUI of "Customer Details to be ADD-ed into a Database".

Customer Screen GUI

By looking at the Image we can say that we need a Customer Class.

Step - 1: What does my Customer Class needs?

i.e.

  • 2 variables to store Customer Code and Customer Name.

  • 1 Function to Add the Customer Code and Customer Name into Database.

  namespace CustomerContent
    {
       public class Customer
       {
           public string CustomerCode = "";
           public string CustomerName = "";
           public void ADD()
           {
              //my DB code will go here
           }

Now only ADD method wont work here alone.

Step -2: How will the validation work, ADD Function act?

We will need Database Connection code and Validation Code (Extra Methods).

     public bool Validate()
     {
    //Granular Customer Code and Name
    return true;
     }

     public bool CreateDBObject()
     {
    //DB Connection Code
    return true;
     }


class Program
{
   static void main(String[] args)
   {
     CustomerComponent.Customer obj = new CustomerComponent.Customer;

     obj.CustomerCode = "s001";
     obj.CustomerName = "Mac";

     obj.Validate();
     obj.CreateDBObject();

     obj.ADD();
    }
}

Now there is no need of showing the Extra Methods(Validate(); CreateDBObject() [Complicated and Extra method] ) to the End User.End user only needs to see and know about Customer Code, Customer Name and ADD button which will ADD the record.. End User doesn't care about HOW it will ADD the Data to Database?.

Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction.

So making those Complicated and Extra method as Private instead Public(i.e Hiding those methods) and deleting the obj.Validate(); obj.CreateDBObject(); from main in class Program we achieve Encapsulation.

In other words Simplifying Interface to End User is Encapsulation.

So now the complete code looks like as below -

 namespace CustomerContent
 {
     public class Customer
     {
        public string CustomerCode = "";
        public string CustomerName = "";

        public void ADD()
        {
           //my DB code will go here
        }

        private bool Validate()
        {
           //Granular Customer Code and Name
           return true;
        }

        private bool CreateDBObject()
        {
           //DB Connection Code
           return true;
        }


  class Program
  {
     static void main(String[] args)
     {
        CustomerComponent.Customer obj = new CustomerComponent.Customer;

        obj.CustomerCode = "s001";

        obj.CustomerName = "Mac";

        obj.ADD();
   }
}

Summary :

Step -1: What does my Customer Class needs? is Abstraction.

Step -3: Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction is Encapsulation.

P.S. - The code above is hard and fast.

UPDATE: There is an video on this link to explain the sample: What is the difference between Abstraction and Encapsulation

Moment.js - tomorrow, today and yesterday

You can use this:


const today     = moment();

const tomorrow  = moment().add(1, 'days');

const yesterday = moment().subtract(1, 'days');

How to position text over an image in css

This is another method for working with Responsive sizes. It will keep your text centered and maintain its position within its parent. If you don't want it centered then it's even easier, just work with the absolute parameters. Keep in mind the main container is using display: inline-block. There are many others ways to do this, depending on what you're working on.

Based off of Centering the Unknown

Working codepen example here

HTML

<div class="containerBox">
    <div class="text-box">
        <h4>Your Text is responsive and centered</h4>
    </div>
    <img class="img-responsive" src="http://placehold.it/900x100"/>
</div>

CSS

.containerBox {
    position: relative;
    display: inline-block;
}
.text-box {
    position: absolute;    
    height: 100%;
    text-align: center;    
    width: 100%;
}
.text-box:before {
   content: '';
   display: inline-block;
   height: 100%;
   vertical-align: middle;
}
h4 {
   display: inline-block;
   font-size: 20px; /*or whatever you want*/
   color: #FFF;   
}
img {
  display: block;
  max-width: 100%;
  height: auto;
}

Angular 2 router no base href set

I had faced similar issue with Angular4 and Jasmine unit tests; below given solution worked for me

Add below import statement

import { APP_BASE_HREF } from '@angular/common';

Add below statement for TestBed configuration:

TestBed.configureTestingModule({
    providers: [
        { provide: APP_BASE_HREF, useValue : '/' }
    ]
})

Looping through rows in a DataView

You can iterate DefaultView as the following code by Indexer:

DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
{
    DataRow oRow = dt.DefaultView[i].Row;
    // Do your stuff with oRow
    // ...
}

PHP CURL Enable Linux

If it's php 7 on ubuntu, try this

apt-get install php7.0-curl
/etc/init.d/apache2 restart

R - argument is of length zero in if statement

I spent an entire day bashing my head against this, the solution turned out to be simple..

R isn't zero-index.

Every programming language that I've used before has it's data start at 0, R starts at 1. The result is an off-by-one error but in the opposite direction of the usual. going out of bounds on a data structure returns null and comparing null in an if statement gives the argument is of length zero error. The confusion started because the dataset doesn't contain any null, and starting at position [0] like any other pgramming language turned out to be out of bounds.

Perhaps starting at 1 makes more sense to people with no programming experience (the target market for R?) but for a programmer is a real head scratcher if you're unaware of this.

jQuery: outer html()

If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:

var myID = "xxx";

var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";

How do I get total physical memory size using PowerShell without WMI?

Id like to say that instead of going with the systeminfo this would help over to get the total physical memory in GB's the machine

Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {"{0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}

you can pass this value to the variable and get the gross output for the total physical memory in the machine

   $totalmemory = Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {"{0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}
   $totalmemory

Read file-contents into a string in C++

Like this:

#include <fstream>
#include <string>

int main(int argc, char** argv)
{

  std::ifstream ifs("myfile.txt");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

  return 0;
}

The statement

  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

can be split into

std::string content;
content.assign( (std::istreambuf_iterator<char>(ifs) ),
                (std::istreambuf_iterator<char>()    ) );

which is useful if you want to just overwrite the value of an existing std::string variable.

Check if year is leap year in javascript

My Code Is Very Easy To Understand

var year = 2015;
var LeapYear = year % 4;

if (LeapYear==0) {
    alert("This is Leap Year");
} else {
    alert("This is not leap year");
}

Right HTTP status code to wrong input

According to the below scenario ,

Let's say that someone makes a request to your server with data that is in the correct format, but is simply not "good" data. So for example, imagine that someone posted a String value to an API endpoint that expected a String value; but, the value of the string contained data that was blacklisted (ex. preventing people from using "password" as their password). then the status code could be either 400 or 422 ?

Until now, I would have returned a "400 Bad Request", which, according to the w3.org, means:

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

This description doesn't quite fit the circumstance; but, if you go by the list of core HTTP status codes defined in the HTTP/1.1 protocol, it's probably your best bet.

Recently, however, Someone from my Dev team pointed out [to me] that popular APIs are starting to use HTTP extensions to get more granular with their error reporting. Specifically, many APIs, like Twitter and Recurly, are using the status code "422 Unprocessable Entity" as defined in the HTTP extension for WebDAV. HTTP status code 422 states:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Going back to our password example from above, this 422 status code feels much more appropriate. The server understands what you're trying to do; and it understands the data that you're submitting; it simply won't let that data be processed.

Pushing from local repository to GitHub hosted remote

Type

git push

from the command line inside the repository directory

Leave menu bar fixed on top when scrolled

You can try this with your nav div:

postion: fixed;
top: 0;
width: 100%;

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

Hibernate: hbm2ddl.auto=update in production?

We do it in a project running in production for months now and never had a problem so far. Keep in mind the 2 ingredients needed for this recipe:

  1. Design your object model with a backwards-compatibility approach, that is deprecate objects and attributes rather than removing/altering them. This means that if you need to change the name of an object or attribute, leave the old one as is, add the new one and write some kind of migration script. If you need to change an association between objects, if you already are in production, this means that your design was wrong in the first place, so try to think of a new way of expressing the new relationship, without affecting old data.

  2. Always backup the database prior to deployment.

My sense is - after reading this post - that 90% of the people taking part in this discussion are horrified just with the thought of using automations like this in a production environment. Some throw the ball at the DBA. Take a moment though to consider that not all production environments will provide a DBA and not many dev teams are able to afford one (at least for medium size projects). So, if we're talking about teams where everyone has to do everything, the ball is on them.

In this case, why not just try to have the best of both worlds? Tools like this are here to give a helping hand, which - with a careful design and plan - can help in many situations. And believe me, administrators may initially be hard to convince but if they know that the ball is not on their hands, they will love it.

Personally, I'd never go back to writing scripts by hand for extending any type of schema, but that's just my opinion. And after starting to adopt NoSQL schema-less databases recently, I can see that more than soon, all these schema-based operations will belong to the past, so you'd better start changing your perspective and look ahead.

Most efficient way to increment a Map value in Java

Another way would be creating a mutable integer:

class MutableInt {
  int value = 0;
  public void inc () { ++value; }
  public int get () { return value; }
}
...
Map<String,MutableInt> map = new HashMap<String,MutableInt> ();
MutableInt value = map.get (key);
if (value == null) {
  value = new MutableInt ();
  map.put (key, value);
} else {
  value.inc ();
}

of course this implies creating an additional object but the overhead in comparison to creating an Integer (even with Integer.valueOf) should not be so much.

In Mongoose, how do I sort by date? (node.js)

You can also sort by the _id field. For example, to get the most recent record, you can do,

const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });

It's much quicker too, because I'm more than willing to bet that your date field is not indexed.

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.

Suppose we have a datetime object and date is represented as: "2017-05-04"

>>> from datetime import datetime
>>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
>>> print(date)
2017-05-04 00:00:00
>>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
>>> print(date)
2018-06-01 23:59:59

What is the difference between atomic / volatile / synchronized?

I know that two threads can not enter in Synchronize block at the same time

Two thread cannot enter a synchronized block on the same object twice. This means that two threads can enter the same block on different objects. This confusion can lead to code like this.

private Integer i = 0;

synchronized(i) {
   i++;
}

This will not behave as expected as it could be locking on a different object each time.

if this is true than How this atomic.incrementAndGet() works without Synchronize ?? and is thread safe ??

yes. It doesn't use locking to achieve thread safety.

If you want to know how they work in more detail, you can read the code for them.

And what is difference between internal reading and writing to Volatile Variable / Atomic Variable ??

Atomic class uses volatile fields. There is no difference in the field. The difference is the operations performed. The Atomic classes use CompareAndSwap or CAS operations.

i read in some article that thread has local copy of variables what is that ??

I can only assume that it referring to the fact that each CPU has its own cached view of memory which can be different from every other CPU. To ensure that your CPU has a consistent view of data, you need to use thread safety techniques.

This is only an issue when memory is shared at least one thread updates it.

How to display special characters in PHP

This works for me:

Create/edit .htaccess file with these lines:

AddDefaultCharset UTF-8
AddCharset UTF-8 .php

If you prefer create/edit php.ini:

default_charset = "utf-8"

Sources:

Cross field validation with Hibernate Validator (JSR 303)

With Hibernate Validator 4.1.0.Final I recommend using @ScriptAssert. Exceprt from its JavaDoc:

Script expressions can be written in any scripting or expression language, for which a JSR 223 ("Scripting for the JavaTM Platform") compatible engine can be found on the classpath.

Note: the evaluation is being performed by a scripting "engine" running in the Java VM, therefore on Java "server side", not on "client side" as stated in some comments.

Example:

@ScriptAssert(lang = "javascript", script = "_this.passVerify.equals(_this.pass)")
public class MyBean {
  @Size(min=6, max=50)
  private String pass;

  private String passVerify;
}

or with shorter alias and null-safe:

@ScriptAssert(lang = "javascript", alias = "_",
    script = "_.passVerify != null && _.passVerify.equals(_.pass)")
public class MyBean {
  @Size(min=6, max=50)
  private String pass;

  private String passVerify;
}

or with Java 7+ null-safe Objects.equals():

@ScriptAssert(lang = "javascript", script = "Objects.equals(_this.passVerify, _this.pass)")
public class MyBean {
  @Size(min=6, max=50)
  private String pass;

  private String passVerify;
}

Nevertheless, there is nothing wrong with a custom class level validator @Matches solution.

Show loading image while $.ajax is performed

something like this:

$('#image').show();
$.ajax({
    url: uri,
    cache: false,
    success: function(html){
       $('.info').append(html);
       $('#image').hide();
    }
});

what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?

In the context of Drupal, the difference will depend whether clean URLs are on or not.

With them off, $_SERVER['REQUEST_URI'] will have the full path of the page as called w/ /index.php, while $_GET["q"] will just have what is assigned to q.

With them on, they will be nearly identical w/o other arguments, but $_GET["q"] will be missing the leading /. Take a look towards the end of the default .htaccess to see what is going on. They will also differ if additional arguments are passed into the page, eg when a pager is active.

Create table in SQLite only if it doesn't exist already

Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).

        # for completeness lets do the routine thing of connections and cursors
        conn = sqlite3.connect(db_file, timeout=1000) 

        cursor = conn.cursor() 

        # get the count of tables with the name  
        tablename = 'KABOOM' 
        cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))

        print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.

        # check if the db has existing table named KABOOM
        # if the count is 1, then table exists 
        if cursor.fetchone()[0] ==1 : 
            print('Table exists. I can do my custom stuff here now.... ')
            pass
        else: 
           # then table doesn't exist. 
           custRET = myCustFunc(foo,bar) # replace this with your custom logic

Android Service Stops When App Is Closed

try this, it will keep the service running in the background.

BackServices.class

public class BackServices extends Service{

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }
   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

in your MainActivity onCreate drop this line of code

startService(new Intent(getBaseContext(), BackServices.class));

Now the service will stay running in background.

Stopping an Android app from console

If you target a non-rooted device and/or have services in you APK that you don't want to stop as well, the other solutions won't work.

To solve this problem, I've resorted to a broadcast message receiver I've added to my activity in order to stop it.

public class TestActivity extends Activity {
    private static final String STOP_COMMAND = "com.example.TestActivity.STOP";

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TestActivity.this.finish();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //other stuff...

        registerReceiver(broadcastReceiver, new IntentFilter(STOP_COMMAND));
    }
}

That way, you can issue this adb command to stop your activity:

adb shell am broadcast -a com.example.TestActivity.STOP

How can I write a heredoc to a file in Bash script?

Note:

The question (how to write a here document (aka heredoc) to a file in a bash script?) has (at least) 3 main independent dimensions or subquestions:

  1. Do you want to overwrite an existing file, append to an existing file, or write to a new file?
  2. Does your user or another user (e.g., root) own the file?
  3. Do you want to write the contents of your heredoc literally, or to have bash interpret variable references inside your heredoc?

(There are other dimensions/subquestions which I don't consider important. Consider editing this answer to add them!) Here are some of the more important combinations of the dimensions of the question listed above, with various different delimiting identifiers--there's nothing sacred about EOF, just make sure that the string you use as your delimiting identifier does not occur inside your heredoc:

  1. To overwrite an existing file (or write to a new file) that you own, substituting variable references inside the heredoc:

    cat << EOF > /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    EOF
    
  2. To append an existing file (or write to a new file) that you own, substituting variable references inside the heredoc:

    cat << FOE >> /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    FOE
    
  3. To overwrite an existing file (or write to a new file) that you own, with the literal contents of the heredoc:

    cat << 'END_OF_FILE' > /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    END_OF_FILE
    
  4. To append an existing file (or write to a new file) that you own, with the literal contents of the heredoc:

    cat << 'eof' >> /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    eof
    
  5. To overwrite an existing file (or write to a new file) owned by root, substituting variable references inside the heredoc:

    cat << until_it_ends | sudo tee /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    until_it_ends
    
  6. To append an existing file (or write to a new file) owned by user=foo, with the literal contents of the heredoc:

    cat << 'Screw_you_Foo' | sudo -u foo tee -a /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    Screw_you_Foo
    

Getting 404 Not Found error while trying to use ErrorDocument

The ErrorDocument directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot. In your case, this means that the actual path to the ErrorDocument is

ErrorDocument 404 /hellothere/error/404page.html

Get class list for element with jQuery

You can use document.getElementById('divId').className.split(/\s+/); to get you an array of class names.

Then you can iterate and find the one you want.

var classList = document.getElementById('divId').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
    if (classList[i] === 'someClass') {
        //do something
    }
}

jQuery does not really help you here...

var classList = $('#divId').attr('class').split(/\s+/);
$.each(classList, function(index, item) {
    if (item === 'someClass') {
        //do something
    }
});

Spring @Transactional - isolation, propagation

We can add for this:

@Transactional(readOnly = true)
public class Banking_CustomerService implements CustomerService {

    public Customer getDetail(String customername) {
        // do something
    }

    // these settings have precedence for this method
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void updateCustomer(Customer customer) {
        // do something
    }
}

What does (function($) {})(jQuery); mean?

Just small addition to explanation

This structure (function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:

(function($) {
  // do something
})(jQuery);

this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $.

MySQL JOIN the most recent row only?

If you are working with heavy queries, you better move the request for the latest row in the where clause. It is a lot faster and looks cleaner.

SELECT c.*,
FROM client AS c
LEFT JOIN client_calling_history AS cch ON cch.client_id = c.client_id
WHERE
   cch.cchid = (
      SELECT MAX(cchid)
      FROM client_calling_history
      WHERE client_id = c.client_id AND cal_event_id = c.cal_event_id
   )

How to refresh token with Google API client?

Google has made some changes since this question was originally posted.

Here is my currently working example.

    public function update_token($token){

    try {

        $client = new Google_Client();
        $client->setAccessType("offline"); 
        $client->setAuthConfig(APPPATH . 'vendor' . DIRECTORY_SEPARATOR . 'google' . DIRECTORY_SEPARATOR . 'client_secrets.json');  
        $client->setIncludeGrantedScopes(true); 
        $client->addScope(Google_Service_Calendar::CALENDAR); 
        $client->setAccessToken($token);

        if ($client->isAccessTokenExpired()) {
            $refresh_token = $client->getRefreshToken();
            if(!empty($refresh_token)){
                $client->fetchAccessTokenWithRefreshToken($refresh_token);      
                $token = $client->getAccessToken();
                $token['refresh_token'] = json_decode($refresh_token);
                $token = json_encode($token);
            }
        }

        return $token;

    } catch (Exception $e) { 
        $error = json_decode($e->getMessage());
        if(isset($error->error->message)){
            log_message('error', $error->error->message);
        }
    }


}

Export/import jobs in Jenkins

In a web browser visit:

http://[jenkinshost]/job/[jobname]/config.xml

Just save the file to your disk.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I have solved this problem by importing the following dependency. you must manually import httpclient

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>*</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Open web in new tab Selenium + Python

browser.execute_script('''window.open("http://bings.com","_blank");''')

Where browser is the webDriver

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

indexOf Case Sensitive?

What are you doing with the index value once returned?

If you are using it to manipulate your string, then could you not use a regular expression instead?

import static org.junit.Assert.assertEquals;    
import org.junit.Test;

public class StringIndexOfRegexpTest {

    @Test
    public void testNastyIndexOfBasedReplace() {
        final String source = "Hello World";
        final int index = source.toLowerCase().indexOf("hello".toLowerCase());
        final String target = "Hi".concat(source.substring(index
                + "hello".length(), source.length()));
        assertEquals("Hi World", target);
    }

    @Test
    public void testSimpleRegexpBasedReplace() {
        final String source = "Hello World";
        final String target = source.replaceFirst("(?i)hello", "Hi");
        assertEquals("Hi World", target);
    }
}

Remove border from IFrame

For browser specific issues also add frameborder="0" hspace="0" vspace="0" marginheight="0" marginwidth="0" according to Dreamweaver:

<iframe src="test.html" name="banner" width="300" marginwidth="0" height="300" marginheight="0" align="top" scrolling="No" frameborder="0" hspace="0" vspace="0">Browser not compatible. </iframe>

Can I pass column name as input parameter in SQL stored Procedure

Please Try with this. I hope it will work for you.

Create Procedure Test
(
    @Table VARCHAR(500),
    @Column VARCHAR(100),
    @Value  VARCHAR(300)
)
AS
BEGIN

DECLARE @sql nvarchar(1000)

SET @sql = 'SELECT * FROM ' + @Table + ' WHERE ' + @Column + ' = ' + @Value

--SELECT @sql
exec (@sql)

END

-----execution----

/** Exec Test Products,IsDeposit,1 **/

MySQL: Fastest way to count number of rows

I did some benchmarks to compare the execution time of COUNT(*) vs COUNT(id) (id is the primary key of the table - indexed).

Number of trials: 10 * 1000 queries

Results: COUNT(*) is faster 7%

VIEW GRAPH: benchmarkgraph

My advice is to use: SELECT COUNT(*) FROM table

Border in shape xml

It looks like you forgot the prefix on the color attribute. Try

 <stroke android:width="2dp" android:color="#ff00ffff"/>

How does the class_weight parameter in scikit-learn work?

The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.

SUMMARY

  • for moderately imbalanced data WITHOUT noise, there is not much of a difference in applying class weights
  • for moderately imbalanced data WITH noise and strongly imbalanced, it is better to apply class weights
  • param class_weight="balanced" works decent in the absence of you wanting to optimize manually
  • with class_weight="balanced" you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
    • as a result, the total % TRUE might be higher than actual because of all the false positives
    • AUC might misguide you here if the false alarms are an issue
  • no need to change decision threshold to the imbalance %, even for strong imbalance, ok to keep 0.5 (or somewhere around that depending on what you need)

NB

The result might differ when using RF or GBM. sklearn does not have class_weight="balanced" for GBM but lightgbm has LGBMClassifier(is_unbalance=False)

CODE

# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd

# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same

# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last

print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%

print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE

File to byte[] in Java

Since JDK 7 - one liner:

byte[] array = Files.readAllBytes(Paths.get("/path/to/file"));

No external dependencies needed.

Convert datetime to Unix timestamp and convert it back in python

Well, when converting TO unix timestamp, python is basically assuming UTC, but while converting back it will give you a date converted to your local timezone.

See this question/answer; Get timezone used by datetime.datetime.fromtimestamp()

List comprehension vs map

If you plan on writing any asynchronous, parallel, or distributed code, you will probably prefer map over a list comprehension -- as most asynchronous, parallel, or distributed packages provide a map function to overload python's map. Then by passing the appropriate map function to the rest of your code, you may not have to modify your original serial code to have it run in parallel (etc).

When do you use Java's @Override annotation and why?

Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements), but it's better than nothing.

Convert UTC to local time in Rails 3

Rails has its own names. See them with:

rake time:zones:us

You can also run rake time:zones:all for all time zones. To see more zone-related rake tasks: rake -D time

So, to convert to EST, catering for DST automatically:

Time.now.in_time_zone("Eastern Time (US & Canada)")

Math.random() versus Random.nextInt(int)

According to this example Random.nextInt(n) has less predictable output then Math.random() * n. According to [sorted array faster than an unsorted array][1] I think we can say Random.nextInt(n) is hard to predict.

usingRandomClass : time:328 milesecond.

usingMathsRandom : time:187 milesecond.

package javaFuction;
import java.util.Random;
public class RandomFuction 
{
    static int array[] = new int[9999];
    static long sum = 0;
    public static void usingMathsRandom() {
        for (int i = 0; i < 9999; i++) {
         array[i] = (int) (Math.random() * 256);
       }

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];
                }
            }
        }
    }

    public static void usingRandomClass() {
        Random random = new Random();
        for (int i = 0; i < 9999; i++) {
            array[i] = random.nextInt(256);
        }

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];
                }
            }

        }

    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        usingRandomClass();
        long end = System.currentTimeMillis();
        System.out.println("usingRandomClass " + (end - start));
        start = System.currentTimeMillis();
        usingMathsRandom();
        end = System.currentTimeMillis();
        System.out.println("usingMathsRandom " + (end - start));

    }

}

forEach loop Java 8 for Map entry set

String ss = "Pawan kavita kiyansh Patidar Patidar";
    StringBuilder ress = new StringBuilder();
    
    Map<Character, Integer> fre = ss.chars().boxed()
            .collect(Collectors.toMap(k->Character.valueOf((char) k.intValue()),k->1,Integer::sum));
    
      //fre.forEach((k, v) -> System.out.println((k + ":" + v)));
    
    fre.entrySet().forEach(e ->{
            //System.out.println(e.getKey() + ":" + e.getValue());
            //ress.append(String.valueOf(e.getKey())+e.getValue());
        }); 

    fre.forEach((k,v)->{
        //System.out.println("Item : " + k + " Count : " + v);
        ress.append(String.valueOf(k)+String.valueOf(v));
    });
    
    System.out.println(ress.toString());

How to decompile an APK or DEX file on Android platform?

You can decompile an apk on Android device using this : https://play.google.com/store/apps/details?id=com.njlabs.showjava

For more info look here: http://forum.xda-developers.com/showthread.php?t=2601315

EDIT: 28-02-2015

For decompiling an apk you can use this tool: https://apkstudio.codeplex.com/license

If that doesnt help check this link

Trying to load local JSON file to show data in a html page using JQuery

Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.

According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:

A file can read another file only if the parent directory of the originating file is an ancestor directory of the target file.

Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>        
<script type="text/javascript" language="javascript" src="priorities.json"></script> 

<script type="text/javascript">
   $(document).ready(function(e) {
         alert(jsonObject.start.count);
   });
</script>

Your priorities.json file:

var jsonObject = {
"start": {
    "count": "5",
    "title": "start",
    "priorities": [
        {
            "txt": "Work"
        },
        {
            "txt": "Time Sense"
        },
        {
            "txt": "Dicipline"
        },
        {
            "txt": "Confidence"
        },
        {
            "txt": "CrossFunctional"
        }
    ]
}
}

Or declare a callback function on your page and wrap it like jsonp technique:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js">    </script> 
     <script type="text/javascript">
           $(document).ready(function(e) {

           });

           function jsonCallback(jsonObject){
               alert(jsonObject.start.count);
           }
        </script>

 <script type="text/javascript" language="javascript" src="priorities.json"></script> 

Your priorities.json file:

jsonCallback({
    "start": {
        "count": "5",
        "title": "start",
        "priorities": [
            {
                "txt": "Work"
            },
            {
                "txt": "Time Sense"
            },
            {
                "txt": "Dicipline"
            },
            {
                "txt": "Confidence"
            },
            {
                "txt": "CrossFunctional"
            }
        ]
    }
    })

Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.

With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

Would not creating a UserJsonResponse class and populating with the wanted fields be a cleaner solution?

Returning directly a JSON seems a great solution when you want to give all the model back. Otherwise it just gets messy.

In the future, for example you might want to have a JSON field that does not match any Model field and then you're in a bigger trouble.

'innerText' works in IE, but not in Firefox

innerText has been added to Firefox and should be available in the FF45 release: https://bugzilla.mozilla.org/show_bug.cgi?id=264412

A draft spec has been written and is expected to be incorporated into the HTML living standard in the future: http://rocallahan.github.io/innerText-spec/, https://github.com/whatwg/html/issues/465

Note that currently the Firefox, Chrome and IE implementations are all incompatible. Going forward, we can probably expect Firefox, Chrome and Edge to converge while old IE remains incompatible.

See also: https://github.com/whatwg/compat/issues/5

How to trim a list in Python

To trim a list in place without creating copies of it, use del:

>>> t = [1, 2, 3, 4, 5]
>>> # delete elements starting from index 4 to the end
>>> del t[4:]
>>> t
[1, 2, 3, 4]
>>> # delete elements starting from index 5 to the end
>>> # but the list has only 4 elements -- no error
>>> del t[5:]
>>> t
[1, 2, 3, 4]
>>> 

Check if a file exists locally using JavaScript only

Try this:

window.onclick=(function(){
  try {
    var file = window.open("file://mnt/sdcard/download/Click.ogg");
    setTimeout('file.close()', 100);
    setTimeout("alert('Audio file found. Have a nice day!');", 101);
  } catch(err) {
    var wantstodl=confirm("Warning:\n the file, Click.ogg is not found.\n do you want to download it?\n "+err.message);
    if (wantstodl) {
      window.open("https://www.dropbox.com/s/qs9v6g2vru32xoe/Click.ogg?dl=1"); //downloads the audio file
    }
  }
});

make: *** [ ] Error 1 error

Sometimes you will get lots of compiler outputs with many warnings and no line of output that says "error: you did something wrong here" but there was still an error. An example of this is a missing header file - the compiler says something like "no such file" but not "error: no such file", then it exits with non-zero exit code some time later (perhaps after many more warnings). Make will bomb out with an error message in these cases!

How to perform element-wise multiplication of two lists?

For large lists, we can do it the iter-way:

product_iter_object = itertools.imap(operator.mul, [1,2,3,4], [2,3,4,5])

product_iter_object.next() gives each of the element in the output list.

The output would be the length of the shorter of the two input lists.

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

For me it was bad formatting of the tnsnames.ora connect identifier. The indentation of the identifier string is required as shown in the tnsnames.ora example in the comment.

Vue 'export default' vs 'new Vue'

export default is used to create local registration for Vue component.

Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e