Programs & Examples On #Windows server

A family of server operating systems by Microsoft. This tag can also be used to denote a server with Windows, as opposed to Unix, installed.

Which version of Python do I have installed?

In [1]: import sys

In [2]: sys.version
2.7.11 |Anaconda 2.5.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]

In [3]: sys.version_info
sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)

In [4]: sys.version_info >= (2,7)
Out[4]: True

In [5]: sys.version_info >= (3,)
Out[5]: False

Default settings Raspberry Pi /etc/network/interfaces

For my Raspberry Pi 3B model it was

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

How do I hide the status bar in a Swift iOS app?

Swift 5: In the main view controller, or main navigation controller if you have,

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    override var prefersStatusBarHidden: Bool {
        return false
    }

And "View controller-based status bar appearance" in plist must be YES, otherwise the above code will not be called.

If you want to hide status bar when launching app, "Status bar is initially hidden" in plist must be YES. This can prevent launch image from being distorted when extra blue bar showing on screen top.

Dynamic classname inside ngClass in angular 2

You can use <i [className]="'fa fa-' + data?.icon"> </i>

How to generate sample XML documents from their DTD or XSD?

XMLSpy does that for you, although that's not free...

I believe that Liquid Xml Studio does it for you and is free, but I have not personally used it to create test data.

How can I split a JavaScript string by white space or comma?

input.split(/\s*[\s,]\s*/)

\s* matches zero or more white space characters (not just spaces, but also tabs and newlines).

... [\s,] matches one white space character or one comma

If you want to avoid blank elements from input like "foo,bar,,foobar", this will do the trick:

input.split(/(\s*,?\s*)+/)

The + matches one or more of the preceding character or group.

Edit:

Added ?after comma which matches zero or one comma.

Edit 2:

Turns out edit 1 was a mistake. Fixed it. Now there has to be at least one comma or one space for the expression to find a match.

REST API error code 500 handling

It is a server error, not a client error. If server errors weren't to be returned to the client, there wouldn't have been created an entire status code class for them (i.e. 5xx).

You can't hide the fact that you either made a programming error or some service you rely on is unavailable, and that certainly isn't the client's fault. Returning any other range of code in those cases than the 5xx series would make no sense.

RFC 7231 mentions in section 6.6. Server Error 5xx:

The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method.

This is exactly the case. There's nothing "internal" about the code "500 Internal Server Error" in the sense that it shouldn't be exposed to the client.

'str' object has no attribute 'decode'. Python 3 error?

Begining with Python 3, all strings are unicode objects.

  a = 'Happy New Year' # Python 3
  b = unicode('Happy New Year') # Python 2

The instructions above are the same. So I think you should remove the .decode('utf-8') part because you already have a unicode object.

What does <a href="#" class="view"> mean?

I felt like replying as well, explaining the same thing as the others a bit differently. I am sure you know most of this, but it might help someone else.

<a href="#" class="view">

The

href="#"

part is a commonly used way to make sure the link doesn't lead anywhere on it's own. the #-attribute is used to create a link to some other section in the same document. For example clicking a link of this kind:

<a href="#news">Go to news</a>

will take you to wherever you have the

<a name="news"></a>

code. So if you specify # without any name like in your case, the link leads nowhere.

The

class="view"

part gives it an identifier that CSS or javascript can use. Inside the CSS-files (if you have any) you will find specific styling procedures on all the elements tagged with the "view"-class.

To find out where the URL is specified I would look in the javascript code. It is either written directly in the same document or included from another file.

Search your source code for something like:

<script type="text/javascript"> bla bla bla </script>

or

<script> bla bla bla </script>

and then search for any reference to your "view"-class. An included javascript file can look something like this:

<script type="text/javascript" src="include/javascript.js"></script>

In that case, open javascript.js under the "include" folder and search in that file. Most commonly the includes are placed between <head> and </head> or close to the </body>-tag.

A faster way to find the link is to search for the actual link it goes to. For example, if you are directed to http://www.google.com/search?q=html when you click it, search for "google.com" or something in all the files you have in your web project, just remember the included files.

In many text editors you can open all the files at once, and then search in them all for something.

100% width table overflowing div container

Add display: block; and overflow: auto; to .my-table. This will simply cut off anything past the 280px limit you enforced. There's no way to make it "look pretty" with that requirement due to words like pélagosthrough which are wider than 280px.

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

File > New > folder > assets Folder

Assets Folder

How should strace be used?

strace lists all system calls done by the process it's applied to. If you don't know what system calls mean, you won't be able to get much mileage from it.

Nevertheless, if your problem involves files or paths or environment values, running strace on the problematic program and redirecting the output to a file and then grepping that file for your path/file/env string may help you see what your program is actually attempting to do, as distinct from what you expected it to.

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

How do I declare a 2d array in C++ using new?

There are two general techniques that I would recommend for this in C++11 and above, one for compile time dimensions and one for run time. Both answers assume you want uniform, two-dimensional arrays (not jagged ones).

Compile time dimensions

Use a std::array of std::array and then use new to put it on the heap:

// the alias helps cut down on the noise:
using grid = std::array<std::array<int, sizeX>, sizeY>;
grid * ary = new grid;

Again, this only works if the sizes of the dimensions are known at compile time.

Run time dimensions

The best way to accomplish a 2 dimensional array with sizes only known at runtime is to wrap it into a class. The class will allocate a 1d array and then overload operator [] to provide indexing for the first dimension. This works because in C++ a 2D array is row-major:

 matrix shown in logical form and one-dimensional form

(Taken from http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/)

A contiguous sequence of memory is good for performance reasons and is also easy to clean up. Here's an example class that omits a lot of useful methods but shows the basic idea:

#include <memory>

class Grid {
  size_t _rows;
  size_t _columns;
  std::unique_ptr<int[]> data;

public:
  Grid(size_t rows, size_t columns)
      : _rows{rows},
        _columns{columns},
        data{std::make_unique<int[]>(rows * columns)} {}

  size_t rows() const { return _rows; }

  size_t columns() const { return _columns; }

  int *operator[](size_t row) { return row * _columns + data.get(); }

  int &operator()(size_t row, size_t column) {
    return data[row * _columns + column];
  }
}

So we create an array with std::make_unique<int[]>(rows * columns) entries. We overload operator [] which will index the row for us. It returns an int * which points to the beginning of the row, which can then be dereferenced as normal for the column. Note that make_unique first ships in C++14 but you can polyfill it in C++11 if necessary.

It's also common for these types of structures to overload operator() as well:

  int &operator()(size_t row, size_t column) {
    return data[row * _columns + column];
  }

Technically I haven't used new here, but it's trivial to move from std::unique_ptr<int[]> to int * and use new/delete.

Printf width specifier to maintain precision of floating-point value

No, there is no such printf width specifier to print floating-point with maximum precision. Let me explain why.

The maximum precision of float and double is variable, and dependent on the actual value of the float or double.

Recall float and double are stored in sign.exponent.mantissa format. This means that there are many more bits used for the fractional component for small numbers than for big numbers.

enter image description here

For example, float can easily distinguish between 0.0 and 0.1.

float r = 0;
printf( "%.6f\n", r ) ; // 0.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // 0.100000

But float has no idea of the difference between 1e27 and 1e27 + 0.1.

r = 1e27;
printf( "%.6f\n", r ) ; // 999999988484154753734934528.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // still 999999988484154753734934528.000000

This is because all the precision (which is limited by the number of mantissa bits) is used up for the large part of the number, left of the decimal.

The %.f modifier just says how many decimal values you want to print from the float number as far as formatting goes. The fact that the accuracy available depends on the size of the number is up to you as the programmer to handle. printf can't/doesn't handle that for you.

Updating .class file in jar

Do you want to do it automatically or manually? If manually, a JAR file is really just a ZIP file, so you should be able to open it with any ZIP reader. (You may need to change the extension first.) If you want to update the JAR file automatically via Eclipse, you may want to look into Ant support in Eclipse and look at the zip task.

How to compare times in Python?

You can use the time() method of datetime objects to get the time of day, which you can use for comparison without taking the date into account:

>>> this_morning = datetime.datetime(2009, 12, 2, 9, 30)
>>> last_night = datetime.datetime(2009, 12, 1, 20, 0)
>>> this_morning.time() < last_night.time()
True

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

A simple solution for me was to go to Properties -> Java Build Path -> Order and Export, then check the Apache Tomcat library. This is assumes you've already set Tomcat as your deployment target and are still getting the error.

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

View the Inner Exception of the exception to get a more specific error message.

One way to view the Inner Exception would be to catch the exception, and put a breakpoint on it. Then in the Locals window: select the Exception variable > InnerException > Message

And/Or just write to console:

    catch (Exception e)
    {
        Console.WriteLine(e.InnerException.Message);
    }

Convert a Pandas DataFrame to a dictionary

Should a dictionary like:

{'red': '0.500', 'yellow': '0.250, 'blue': '0.125'}

be required out of a dataframe like:

        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125

simplest way would be to do:

dict(df.values)

working snippet below:

import pandas as pd
df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
dict(df.values)

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

If this is your own collection class rather than a built in one, you need to override its toString method. Eclipse calls that function for any objects for which it does not have a hard-wired formatting.

How to programmatically close a JFrame

If by Alt-F4 or X you mean "Exit the Application Immediately Without Regard for What Other Windows or Threads are Running", then System.exit(...) will do exactly what you want in a very abrupt, brute-force, and possibly problematic fashion.

If by Alt-F4 or X you mean hide the window, then frame.setVisible(false) is how you "close" the window. The window will continue to consume resources/memory but can be made visible again very quickly.

If by Alt-F4 or X you mean hide the window and dispose of any resources it is consuming, then frame.dispose() is how you "close" the window. If the frame was the last visible window and there are no other non-daemon threads running, the program will exit. If you show the window again, it will have to reinitialize all of the native resources again (graphics buffer, window handles, etc).

dispose() might be closest to the behavior that you really want. If your app has multiple windows open, do you want Alt-F4 or X to quit the app or just close the active window?

The Java Swing Tutorial on Window Listeners may help clarify things for you.

oracle varchar to number

select to_number(exception_value) from exception where to_number(exception_value) = 105

Angular/RxJs When should I unsubscribe from `Subscription`

Some of the best practices regarding observables unsubscriptions inside Angular components:

A quote from Routing & Navigation

When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed.

There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions.

The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

Feel free to unsubscribe anyway. It is harmless and never a bad practice.

And in responding to the following links:

I collected some of the best practices regarding observables unsubscriptions inside Angular components to share with you:

  • http observable unsubscription is conditional and we should consider the effects of the 'subscribe callback' being run after the component is destroyed on a case by case basis. We know that angular unsubscribes and cleans the http observable itself (1), (2). While this is true from the perspective of resources it only tells half the story. Let's say we're talking about directly calling http from within a component, and the http response took longer than needed so the user closed the component. The subscribe() handler will still be called even if the component is closed and destroyed. This can have unwanted side effects and in the worse scenarios leave the application state broken. It can also cause exceptions if the code in the callback tries to call something that has just been disposed of. However at the same time occasionally they are desired. Like, let's say you're creating an email client and you trigger a sound when the email is done sending - well you'd still want that to occur even if the component is closed (8).
  • No need to unsubscribe from observables that complete or error. However, there is no harm in doing so(7).
  • Use AsyncPipe as much as possible because it automatically unsubscribes from the observable on component destruction.
  • Unsubscribe from the ActivatedRoute observables like route.params if they are subscribed inside a nested (Added inside tpl with the component selector) or dynamic component as they may be subscribed many times as long as the parent/host component exists. No need to unsubscribe from them in other scenarios as mentioned in the quote above from Routing & Navigation docs.
  • Unsubscribe from global observables shared between components that are exposed through an Angular service for example as they may be subscribed multiple times as long as the component is initialized.
  • No need to unsubscribe from internal observables of an application scoped service since this service never get's destroyed, unless your entire application get's destroyed, there is no real reason to unsubscribe from it and there is no chance of memory leaks. (6).

    Note: Regarding scoped services, i.e component providers, they are destroyed when the component is destroyed. In this case, if we subscribe to any observable inside this provider, we should consider unsubscribing from it using the OnDestroy lifecycle hook which will be called when the service is destroyed, according to the docs.
  • Use an abstract technique to avoid any code mess that may be resulted from unsubscriptions. You can manage your subscriptions with takeUntil (3) or you can use this npm package mentioned at (4) The easiest way to unsubscribe from Observables in Angular.
  • Always unsubscribe from FormGroup observables like form.valueChanges and form.statusChanges
  • Always unsubscribe from observables of Renderer2 service like renderer2.listen
  • Unsubscribe from every observable else as a memory-leak guard step until Angular Docs explicitly tells us which observables are unnecessary to be unsubscribed (Check issue: (5) Documentation for RxJS Unsubscribing (Open)).
  • Bonus: Always use the Angular ways to bind events like HostListener as angular cares well about removing the event listeners if needed and prevents any potential memory leak due to event bindings.

A nice final tip: If you don't know if an observable is being automatically unsubscribed/completed or not, add a complete callback to subscribe(...) and check if it gets called when the component is destroyed.

Regular expressions inside SQL Server

SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp

you need to use a query like this:

select * from mytable where msisdn like '%7%'

or

select * from mytable where msisdn like '56655%'

Calculate RSA key fingerprint

The fastest way if your keys are in an SSH agent:

$ ssh-add -L | ssh-keygen -E md5 -lf /dev/stdin

Each key in the agent will be printed as:

4096 MD5:8f:c9:dc:40:ec:9e:dc:65:74:f7:20:c1:29:d1:e8:5a /Users/cmcginty/.ssh/id_rsa (RSA)

Socket.io + Node.js Cross-Origin Request Blocked

I just wanted to say that after trying a bunch of things, what fixed my CORS problem was simply using an older version of socket.io (version 2.2.0). My package.json file now looks like this:

{
  "name": "current-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "devStart": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "socket.io": "^2.2.0"
  },
  "devDependencies": {
    "nodemon": "^1.19.0"
  }
}


If you execute npm install with this, you may find that the CORS problem goes away when trying to use socket.io. At least it worked for me.

Fade In Fade Out Android Animation in Java

I know that this already has been answered but.....

<?xml version="1.0" encoding="utf-8"?> 
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="1.0" 
    android:toAlpha="0.0" 
    android:duration="1000"    
    android:repeatCount="infinite" 
    android:repeatMode="reverse"
    />

Quick and easy way to quickly do a fade in and out with a self repeat. Enjoy

EDIT : In your activity add this:

yourView.startAnimation(AnimationUtils.loadAnimation(co??ntext, R.anim.yourAnimation));

logout and redirecting session in php

Only this is necessary

session_start();
unset($_SESSION["nome"]);  // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");

Scroll to bottom of div?

If this is being done for scrolling to the bottom of chat window, do the following

The idea of scrolling to a particular div in the chat was the following

1) Each chat div consisting of Person, time and message is run in a for loop with class chatContentbox

2) querySelectorAll finds all such arrays. It could be 400 nodes (400 chats)

3) go to the last one

4) scrollIntoView()

let lastChatBox = document.querySelectorAll('.chatContentBox'); 
lastChatBox = lastChatBox[lastChatBox.length-1]; 
lastChatBox.scrollIntoView(); 

How to identify unused CSS definitions from multiple CSS files in a project

Google Chrome Developer Tools has (a currently experimental) feature called CSS Overview which will allow you to find unused CSS rules.

To enable it follow these steps:

  1. Open up DevTools (Command+Option+I on Mac; Control+Shift+I on Windows)
  2. Head over to DevTool Settings (Function+F1 on Mac; F1 on Windows)
  3. Click open the Experiments section
  4. Enable the CSS Overview option

enter image description here

A non-blocking read on a subprocess.PIPE in Python

Working from J.F. Sebastian's answer, and several other sources, I've put together a simple subprocess manager. It provides the request non-blocking reading, as well as running several processes in parallel. It doesn't use any OS-specific call (that I'm aware) and thus should work anywhere.

It's available from pypi, so just pip install shelljob. Refer to the project page for examples and full docs.

How to write a simple Html.DropDownListFor()?

With "Please select one Item"

@Html.DropDownListFor(model => model.ContentManagement_Send_Section,
  new List<SelectListItem> { new SelectListItem { Value = "0", Text = "Plese Select one Item" } }
    .Concat(db.NameOfPaperSections.Select(x => new SelectListItem { Text = x.NameOfPaperSection, Value = x.PaperSectionID.ToString() })),
  new { @class = "myselect" })  

Derived from the codes: Master Programmer && Joel Wahlund ;
King Reference : https://stackoverflow.com/a/1528193/1395101 JaredPar ;

Thanks Master Programmer && Joel Wahlund && JaredPar ;

Good luck friends.

Return JSON response from Flask view

Create a python dictionary to return as the response:

response = {'key': 'value'}

Then you can use json.dumps() or flask.jsonify() to turn a python dictionary into JSON:

from json import dumps

return dumps(response)
from flask import jsonify

return jsonify(response)

Note that flask.jsonify() is made for flask and also it has some more advatages. You can use it like in the following code:

from flask import jsonify

params = {
    'key': 'value'
}

return jsonify(**params)

This is like using the following line:

return jsonify(key='value')

Remeber in this code you don't need the response dictionary!

What should I do if the current ASP.NET session is null?

Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:

If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.

Edit

In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.

AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.

If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.

Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.

How to hide axes and gridlines in Matplotlib (python)

Turn the axes off with:

plt.axis('off')

And gridlines with:

plt.grid(b=None)

How to update the value stored in Dictionary in C#?

You can follow this approach:

void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
    int val;
    if (dic.TryGetValue(key, out val))
    {
        // yay, value exists!
        dic[key] = val + newValue;
    }
    else
    {
        // darn, lets add the value
        dic.Add(key, newValue);
    }
}

The edge you get here is that you check and get the value of corresponding key in just 1 access to the dictionary. If you use ContainsKey to check the existance and update the value using dic[key] = val + newValue; then you are accessing the dictionary twice.

MySQL - UPDATE query based on SELECT Query

Easy in MySQL:

UPDATE users AS U1, users AS U2 
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id

Android Imagebutton change Image OnClick

You can do it right in your XML file:

android:onClick="@drawable/ic_action_search"

How to select lines between two marker patterns which may occur multiple times with awk/sed

Use awk with a flag to trigger the print when necessary:

$ awk '/abc/{flag=1;next}/mno/{flag=0}flag' file
def1
ghi1
jkl1
def2
ghi2
jkl2

How does this work?

  • /abc/ matches lines having this text, as well as /mno/ does.
  • /abc/{flag=1;next} sets the flag when the text abc is found. Then, it skips the line.
  • /mno/{flag=0} unsets the flag when the text mno is found.
  • The final flag is a pattern with the default action, which is to print $0: if flag is equal 1 the line is printed.

For a more detailed description and examples, together with cases when the patterns are either shown or not, see How to select lines between two patterns?.

How to convert Excel values into buckets?

If conditions is the best way to do it. If u want the count use pivot table of buckets. It's the easiest way and the if conditions can go for more than 5-6 buckets too

Pressing Ctrl + A in Selenium WebDriver

To click Ctrl+A, you can do it with Actions

  Actions action = new Actions(); 
  action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0061')).perform();

\u0061 represents the character 'a'

\u0041 represents the character 'A'

To press other characters refer the unicode character table - http://unicode.org/charts/PDF/U0000.pdf

Android custom Row Item for ListView

Use a custom Listview.

You can also customize how row looks by having a custom background. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" 
 android:background="#0095FF"> //background color

<ListView android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="0dip"
 android:focusableInTouchMode="false"
 android:listSelector="@android:color/transparent"
 android:layout_weight="2"
 android:headerDividersEnabled="false"
 android:footerDividersEnabled="false"
 android:dividerHeight="8dp" 
 android:divider="#000000" 
 android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>  

MainActivity

Define populateString() in MainActivity

 public class MainActivity extends Activity {

   String data_array[];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
            data_array = populateString(); 
    ListView ll = (ListView) findViewById(R.id.list);
    CustomAdapter cus = new CustomAdapter();
    ll.setAdapter(cus);
}

class CustomAdapter extends BaseAdapter
{
    LayoutInflater mInflater;


    public CustomAdapter()
    {
        mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data_array.length;//listview item count. 
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHolder vh;
        vh= new ViewHolder();

        if(convertView==null )
         {
            convertView=mInflater.inflate(R.layout.row, parent,false);
                    //inflate custom layour
            vh.tv2= (TextView)convertView.findViewById(R.id.textView2);

         }
        else
        {
         convertView.setTag(vh);
        }
               //vh.tv2.setText("Position = "+position);
            vh.tv2.setText(data_array[position]);   
                           //set text of second textview based on position

        return convertView;
    }

 class ViewHolder
 {
    TextView tv1,tv2;
 }

   }  
}

row.xml. Custom layout for each row.

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

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Header" />

 <TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="TextView" />

 </LinearLayout>

Inflate a custom layout. Use a view holder for smooth scrolling and performance.

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

http://www.youtube.com/watch?v=wDBM6wVEO70. The talk is about listview performance by android developers.

enter image description here

How to automatically add user account AND password with a Bash script?

You could also use chpasswd:

echo username:new_password | chpasswd

so, you change password for user username to new_password.

Best way to save a trained model in PyTorch?

I've found this page on their github repo, I'll just paste the content here.


Recommended approach for saving a model

There are two main approaches for serializing and restoring a model.

The first (recommended) saves and loads only the model parameters:

torch.save(the_model.state_dict(), PATH)

Then later:

the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))

The second saves and loads the entire model:

torch.save(the_model, PATH)

Then later:

the_model = torch.load(PATH)

However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.

indexOf and lastIndexOf in PHP?

This is the best way to do it, very simple.

$msg = "Hello this is a string";
$first_index_of_i = stripos($msg,'i');
$last_index_of_i = strripos($msg, 'i');

echo "First i : " . $first_index_of_i . PHP_EOL ."Last i : " . $last_index_of_i;

Oracle's default date format is YYYY-MM-DD, WHY?

Most of the IDE you can configure the default mask for some kind of data as date, currency, decimal separator, etc.

If your are using Oracle SQL Developer:

Tool > Preferences > Database > NLS

Date Format: YYYY-MM-DD HH24:MI:SS

Difference between Return and Break statements

If you want to exit from a simple if else statement but still stays within a particular context (not by returning to the calling context), you can just set the block condition to false:

if(condition){
//do stuff
   if(something happens)
        condition = false;
}

This will guarantee that there is no further execution, the way I think you want it..You can only use break in a loop or switch case

How do I obtain crash-data from my Android application?

Google changed how much crash reports you actually get. Previously you only got manual reported bug reports.

Since the last developer conference and the introducation of Android Vitals you also get crash reports from users which have enabled to share diagnostics data.

You'll see all crashes collected from Android devices whose users have opted in to automatically share usage and diagnostics data. Data is available for the previous two months.

View crashes & application not responding (ANR) errors

Can you detect "dragging" in jQuery?

// here is how you can detect dragging in all four directions
var isDragging = false;
$("some DOM element").mousedown(function(e) {
    var previous_x_position = e.pageX;
    var previous_y_position = e.pageY;

    $(window).mousemove(function(event) {
        isDragging = true;
        var x_position = event.pageX;
        var y_position = event.pageY;

        if (previous_x_position < x_position) {
            alert('moving right');
        } else {
            alert('moving left');
        }
        if (previous_y_position < y_position) {
            alert('moving down');
        } else {
            alert('moving up');
        }
        $(window).unbind("mousemove");
    });
}).mouseup(function() {
    var wasDragging = isDragging;
    isDragging = false;
    $(window).unbind("mousemove");
});

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

In my case, I need both JDK 8 (trying to use the AVD and SDK manager in Qt under ubuntu) and 11 for different tools. Removing version 11 is not an option.

The 'JAVA_OPTS' solutions did not do anything. I don't really like the export JAVA_HOME, as it might force you do launch whatever tool calls these utils from the same shell (like Qt), or force you to make this permanent, which is not convenient.

So for me the solution is quite simple. Add something like this in the second line of ~/Android/tools/bin/sdkmanager and ~/Android/tools/bin/avdmanager:

JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"

(or whatever the path is to your rev 8 jdk).

With this, these command line tools work in a stand alone mode, they work also when called by other tools such as Qt, and jdk 11 is still the system default for others. No need to mix libs etc...

The only downside is that any update to these command line tools will erase these modifications, which you will have to put back in.

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

Simple. On your code first, set the type of DateTime to DateTime?. So you can work with nullable DateTime type in database. Entity example:

public class Alarme
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public DateTime? DataDisparado { get; set; }//.This allow you to work with nullable datetime in database.
        public DateTime? DataResolvido { get; set; }//.This allow you to work with nullable datetime in database.
        public long Latencia { get; set; }

        public bool Resolvido { get; set; }

        public int SensorId { get; set; }
        [ForeignKey("SensorId")]
        public virtual Sensor Sensor { get; set; }
    }

Server.Transfer Vs. Response.Redirect

Transfer is entirely server-side. Client address bar stays constant. Some complexity about the transfer of context between requests. Flushing and restarting page handlers can be expensive so do your transfer early in the pipeline e.g. in an HttpModule during BeginRequest. Read the MSDN docs carefully, and test and understand the new values of HttpContext.Request - especially in Postback scenarios. We usually use Server.Transfer for error scenarios.

Redirect terminates the request with a 302 status and client-side roundtrip response with and internally eats an exception (minor server perf hit - depends how many you do a day) Client then navigates to new address. Browser address bar & history updates etc. Client pays the cost of an extra roundtrip - cost varies depending on latency. In our business we redirect a lot we wrote our own module to avoid the exception cost.

How to detect DataGridView CheckBox event change?

Here is some code:

private void dgvStandingOrder_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (dgvStandingOrder.Columns[e.ColumnIndex].Name == "IsSelected" && dgvStandingOrder.CurrentCell is DataGridViewCheckBoxCell)
    {
        bool isChecked = (bool)dgvStandingOrder[e.ColumnIndex, e.RowIndex].EditedFormattedValue;
        if (isChecked == false)
        {
            dgvStandingOrder.Rows[e.RowIndex].Cells["Status"].Value = "";
        }
        dgvStandingOrder.EndEdit();
    }
}

private void dgvStandingOrder_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{

    dgvStandingOrder.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

private void dgvStandingOrder_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dgvStandingOrder.CurrentCell is DataGridViewCheckBoxCell)
    {
        dgvStandingOrder.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

Convert ArrayList to String array in Android

Use the method "toArray()"

ArrayList<String>  mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
Object[] mStringArray = mStringList.toArray();

for(int i = 0; i < mStringArray.length ; i++){
    Log.d("string is",(String)mStringArray[i]);
}

or you can do it like this: (mentioned in other answers)

ArrayList<String>  mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
String[] mStringArray = new String[mStringList.size()];
mStringArray = mStringList.toArray(mStringArray);

for(int i = 0; i < mStringArray.length ; i++){
    Log.d("string is",(String)mStringArray[i]);
}

http://developer.android.com/reference/java/util/ArrayList.html#toArray()

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

Show Curl POST Request Headers? Is there a way to do this?

You can make you request headers by yourself using:

// open a socket connection on port 80
$fp = fsockopen($host, 80);

// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);

$result = ''; 
while(!feof($fp)) {
    // receive the results of the request
    $result .= fgets($fp, 128);
}

// close the socket connection:
fclose($fp);

Like writen on how make request

jQuery or JavaScript auto click

You haven't provided your javascript code, but the usual cause of this type of issue is not waiting till the page is loaded. Remember that most javascript is executed before the DOM is loaded, so code trying to manipulate it won't work.

To run code after the page has finished loading, use the $(document).ready callback:

$(document).ready(function(){
  $('#some-id').trigger('click');
});

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

My gut told me the same thing when I came across this design.

I am working on a code base where there are three dbContexts to one database. 2 out of the 3 dbcontexts are dependent on information from 1 dbcontext because it serves up the administrative data. This design has placed constraints on how you can query your data. I ran into this problem where you cannot join across dbcontexts. Instead what you are required to do is query the two separate dbcontexts then do a join in memory or iterate through both to get the combination of the two as a result set. The problem with that is instead of querying for a specific result set you are now loading all your records into memory and then doing a join against the two result sets in memory. It can really slow things down.

I would ask the question "just because you can, should you?"

See this article for the problem I came across related to this design. The specified LINQ expression contains references to queries that are associated with different contexts

How To Create Table with Identity Column

Unique key allows max 2 NULL values. Explaination:

create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)

insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')

select * from teppp
null string , address1
NULL,address2
NULL,address3

If you try inserting same values as below:

insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')

Every time you will get error like:

Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

How to Add Stacktrace or debug Option when Building Android Studio Project

To be able to run options like --stacktrace within a gradle command, you need to put it at the beginning, like:

./gradlew --stacktrace assembleMyBuild

E.g,

./gradlew --stacktrace assembleDebug

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Internet options-->General Tab-->browsing History section.... click settings and then click "View objects". A list of your active X add on's are displayed in the windows folder that they are stored in. You can manipulate these files as you would any others. Simply delete the ones you want to uninstall and restart IE.

SQL Server Management Studio – tips for improving the TSQL coding process

I am developer of SSMSBoost add-in that was recently released for SSMS2008/R2, the intention was to add add features that speed up daily routine tasks:

Shorcuts: F2 - (in SQL Editor): script object located unted cursor

CTRL + F2 - (in SQL Editor): find object located under cursor in object explorer and focus it +It includes Shortcut editor, that is missing in SSMS2008 (is coming in SSMS2012)

also SSMSBoost adds toolbar with buttons:

  • Syncronize SQL Editor connection to Object Explorer (focuses current database in Object Explorer)
  • Manage your own preferred connections and switch between them through combo-box (including jumps between servers)
  • Auto-replacements: typing "sel" will replace it by select * from and you can also add your own token-replacement pairs
  • and some more useful features

SSMSBoost toolbar

How to use wait and notify in Java without IllegalMonitorStateException?

This looks like a situation for producer-consumer pattern. If you’re using java 5 or up, you may consider using blocking queue(java.util.concurrent.BlockingQueue) and leave the thread coordination work to the underlying framework/api implementation. See the example from java 5: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html or java 7 (same example): http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

These alternative libraries worked for me:

sudo apt-get update
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6

What's the difference between ViewData and ViewBag?

In this way we can make it use the values to the pass the information between the controller to other page with TEMP DATA

How to replace substrings in windows batch file

I have made a function for that, you only call it in a batch program within needing to code more.

The working is basically the same as the others, as it's the best way to do it.
Here's the link where I have that function

Convert digits into words with JavaScript

Try this code with a Turkish currency compliant JavaScript

function dene() {
         var inpt = document.getElementById("tar1").value;
         var spt = inpt.split('');
         spt.reverse();

         var tek = ["", "Bir", "Iki", "Üç", "Dört", "Bes", "Alti", "Yedi", "Sekiz", "Dokuz"];
         var onlu = ["", "On", "Yirmi", "Otuz", "Kirk", "Elli", "Atmis", "Yetmis", "Seksen", "Doksan"];
         var Yuz = ["", "Yüz", "IkiYüz", "Üçyüz", "DörtYüz", "BesYüz", "AltiYüz", "YediYüz", "SekizYüz", "DokuzYüz"];
         var ska = ["", "", "", "", "Bin", "Milyon", "Milyar", "Trilyon", "Katrilyon", "Kentilyon"];
         var i, j;
         var bas3 = "";
         var bas6 = "";
         var bas9 = "";
         var bas12 = "";
         var total;

               for(i = 0; i < 1; i++) {

                      bas3 += Yuz[spt[i+2]] + onlu[spt[i+1]] + tek[spt[i]];
                      bas6 += Yuz[spt[i+5]] + onlu[spt[i+4]] + tek[spt[i+3]] + ska[4];
                      bas9 += Yuz[spt[i+8]] + onlu[spt[i+7]] + tek[spt[i+6]] + ska[5];
                      bas12 += Yuz[spt[i+11]] + onlu[spt[i+10]] + tek[spt[i+9]] + ska[6];


                   if(inpt.length < 4) {
                       bas6 = '';
                       bas9 = '';
                   }
                   if(inpt.length > 6 && inpt.slice(5, 6) == 0) {
                     bas6 = bas6.replace(/Bin/g, '');
                   }
                   if(inpt.length < 7) {
                       bas9 = '';
                   } 
                   if(inpt.length > 9 && inpt.slice(1,3) == 000){
                       bas9 = bas9.replace(/Milyon/g, '');
                   }

                   if(inpt.length < 10) {
                    bas12 = '';
                 }
             }

         total = bas12 + bas9 + bas6 + bas3;
         total = total.replace(NaN, '');
         total = total.replace(undefined, '');

        document.getElementById('demo').innerHTML = 
            total;


     }

Get all child elements

Here is a code to get the child elements (In java):

String childTag = childElement.getTagName();
if(childTag.equals("html")) 
{
    return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath("..")); 
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++) 
{
    WebElement childrenElement = childrenElements.get(i);
    String childrenElementTag = childrenElement.getTagName();
    if(childTag.equals(childrenElementTag)) 
    {
        count++;
    }
 }

Batchfile to create backup and rename with timestamp

try this:

ren "File 1-1" "File 1 - %date:/=-% %time::=-%"

ImportError: No module named model_selection

I had the same problem while using Jupyter Notebook, no matter what I updated in Python 3, conda, I could not get in Jupyter:

import sklearn
print (sklearn.__version__)
0.17.1

to SHOW scikit-learn-0.18.1

Finally, I removed Anaconda3 and Jupyter Notebook and reinstalled fresh. I got it to work.

http://ukitech.blogspot.com/2017/02/sklearnmodelselection.html

How to set the 'selected option' of a select dropdown list with jquery

You have to replace YourID and value="3" for your current ones.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#YourID option[value="3"]').attr("selected", "selected");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
  <option value="1">A</option>_x000D_
  <option value="2">B</option>_x000D_
  <option value="3">C</option>_x000D_
  <option value="4">D</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

and value="3" for your current ones.

$('#YourID option[value="3"]').attr("selected", "selected");

<select id="YourID" >
<option value="1">A </option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>

Convert generic list to dataset in C#

One option would be to use a System.ComponenetModel.BindingList rather than a list.

This allows you to use it directly within a DataGridView. And unlike a normal System.Collections.Generic.List updates the DataGridView on changes.

Rails: Adding an index after adding column

Add in the generated migration after creating the column the following (example)

add_index :photographers, :email, :unique => true

Freely convert between List<T> and IEnumerable<T>

A List<T> is an IEnumerable<T>, so actually, there's no need to 'convert' a List<T> to an IEnumerable<T>. Since a List<T> is an IEnumerable<T>, you can simply assign a List<T> to a variable of type IEnumerable<T>.

The other way around, not every IEnumerable<T> is a List<T> offcourse, so then you'll have to call the ToList() member method of the IEnumerable<T>.

Confirm deletion in modal / dialog using Twitter Bootstrap?

Thanks to @Jousby's solution, I managed to get mine working as well, but found I had to improve his solution's Bootstrap modal markup a bit to make it render correctly as demonstrated in the official examples.

So, here's my modified version of the generic confirm function that worked fine:

/* Generic Confirm func */
  function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {

    var confirmModal = 
      $('<div class="modal fade">' +        
          '<div class="modal-dialog">' +
          '<div class="modal-content">' +
          '<div class="modal-header">' +
            '<a class="close" data-dismiss="modal" >&times;</a>' +
            '<h3>' + heading +'</h3>' +
          '</div>' +

          '<div class="modal-body">' +
            '<p>' + question + '</p>' +
          '</div>' +

          '<div class="modal-footer">' +
            '<a href="#!" class="btn" data-dismiss="modal">' + 
              cancelButtonTxt + 
            '</a>' +
            '<a href="#!" id="okButton" class="btn btn-primary">' + 
              okButtonTxt + 
            '</a>' +
          '</div>' +
          '</div>' +
          '</div>' +
        '</div>');

    confirmModal.find('#okButton').click(function(event) {
      callback();
      confirmModal.modal('hide');
    }); 

    confirmModal.modal('show');    
  };  
/* END Generic Confirm func */

Python/Json:Expecting property name enclosed in double quotes

Quite simply, that string is not valid JSON. As the error says, JSON documents need to use double quotes.

You need to fix the source of the data.

Converting cv::Mat to IplImage*

According to OpenCV cheat-sheet this can be done as follows:

IplImage* oldC0 = cvCreateImage(cvSize(320,240),16,1);
Mat newC = cvarrToMat(oldC0);

The cv::cvarrToMat function takes care of the conversion issues.

Custom Listview Adapter with filter Android

Just an update.

If the ticked answer is working fine for you but it shows nothing when the search text is empty. Here is the solution:

private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        
        String filterString = constraint.toString().toLowerCase();
        
        FilterResults results = new FilterResults();

        if(constraint.length() == 0)
        {
            results.count = originalData.size();
            results.values = originalData;
        }else {

        
        final List<String> list = originalData;

        int count = list.size();
        final ArrayList<String> nlist = new ArrayList<String>(count);

        String filterableString ;
        
        for (int i = 0; i < count; i++) {
            filterableString = list.get(i);
            if (filterableString.toLowerCase().contains(filterString)) {
                nlist.add(filterableString);
            }
        }
        
        results.values = nlist;
        results.count = nlist.size();
     }
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<String>) results.values;
        notifyDataSetChanged();
      }

   }

For any query comment below

How to update (append to) an href in jquery?

var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');

To loop with each()

$("a.directions-link").each(function() {
   var $this = $(this);       
   var _href = $this.attr("href"); 
   $this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});

Best way to find the intersection of multiple sets?

From Python version 2.6 on you can use multiple arguments to set.intersection(), like

u = set.intersection(s1, s2, s3)

If the sets are in a list, this translates to:

u = set.intersection(*setlist)

where *a_list is list expansion

Note that set.intersection is not a static method, but this uses the functional notation to apply intersection of the first set with the rest of the list. So if the argument list is empty this will fail.

HTML5 Number Input - Always show 2 decimal places

Based on this answer from @Guilherme Ferreira you can trigger the parseFloat method every time the field changes. Therefore the value always shows two decimal places, even if a user changes the value by manual typing a number.

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script type="text/javascript">_x000D_
    $(document).ready(function () {_x000D_
        $(".floatNumberField").change(function() {_x000D_
            $(this).val(parseFloat($(this).val()).toFixed(2));_x000D_
        });_x000D_
    });_x000D_
</script>_x000D_
_x000D_
<input type="number" class="floatNumberField" value="0.00" placeholder="0.00" step="0.01" />
_x000D_
_x000D_
_x000D_

jQuery get the rendered height of an element?

Try one of:

var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;

clientHeight includes the height and vertical padding.

offsetHeight includes the height, vertical padding, and vertical borders.

scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.

How to get the type of T from a member of a generic class or method?

With the following extension method you can get away without reflection:

public static Type GetListType<T>(this List<T> _)
{
    return typeof(T);
}

Or more general:

public static Type GetEnumeratedType<T>(this IEnumerable<T> _)
{
    return typeof(T);
}

Usage:

List<string>        list    = new List<string> { "a", "b", "c" };
IEnumerable<string> strings = list;
IEnumerable<object> objects = list;

Type listType    = list.GetListType();           // string
Type stringsType = strings.GetEnumeratedType();  // string
Type objectsType = objects.GetEnumeratedType();  // BEWARE: object

Replace comma with newline in sed on MacOS?

Though I am late to this post, just updating my findings. This answer is only for Mac OS X.

$ sed 's/new/
> /g' m1.json > m2.json
sed: 1: "s/new/
/g": unescaped newline inside substitute pattern

In the above command I tried with Shift+Enter to add new line which didn't work. So this time I tried with "escaping" the "unescaped newline" as told by the error.

$ sed 's/new/\
> /g' m1.json > m2.json 

Worked! (in Mac OS X 10.9.3)

MongoDB "root" user

"userAdmin is effectively the superuser role for a specific database. Users with userAdmin can grant themselves all privileges. However, userAdmin does not explicitly authorize a user for any privileges beyond user administration." from the link you posted

How to hide a status bar in iOS?

Well the easiest way that I do it is by typing the following into the .m file.

- (BOOL) prefersStatusBarHidden
{
    return YES;
}

This should work!

Convert JsonNode into POJO

If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)


    ObjectMapper mapper = new ObjectMapper();
    JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
    JsonNode tree = jsonParser.readValueAsTree();
    // Do stuff to the tree
    mapper.readValue(tree, Foo.class);

How do I filter an array with TypeScript in Angular 2?

You need to put your code into ngOnInit and use the this keyword:

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

You need ngOnInit because the input store wouldn't be set into the constructor:

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)

In your code, the books filtering is directly defined into the class content...

How to remove from a map while iterating it?

Pretty sad, eh? The way I usually do it is build up a container of iterators instead of deleting during traversal. Then loop through the container and use map.erase()

std::map<K,V> map;
std::list< std::map<K,V>::iterator > iteratorList;

for(auto i : map ){
    if ( needs_removing(i)){
        iteratorList.push_back(i);
    }
}
for(auto i : iteratorList){
    map.erase(*i)
}

PHP unable to load php_curl.dll extension

Add your php folder path to the System PATH and everything should work fine. It will also fix some other extensions that are broken.

"could not find stored procedure"

You may need to check who the actual owner of the stored procedure is. If it is a specific different user then that could be why you can't access it.

Submitting a form by pressing enter without a submit button

Have you tried this ?

<input type="submit" style="visibility: hidden;" />

Since most browsers understand visibility:hidden and it doesn't really work like display:none, I'm guessing that it should be fine, though. Haven't really tested it myself, so CMIIW.

How generate unique Integers based on GUIDs

If you are looking to break through the 2^32 barrier then try this method:

/// <summary>
/// Generate a BigInteger given a Guid. Returns a number from 0 to 2^128
/// 0 to 340,282,366,920,938,463,463,374,607,431,768,211,456
/// </summary>
    public BigInteger GuidToBigInteger(Guid guid)
    {
        BigInteger l_retval = 0;
        byte[] ba = guid.ToByteArray();
        int i = ba.Count();
        foreach (byte b in ba)
        {
            l_retval += b * BigInteger.Pow(256, --i);
        }
        return l_retval;
    }

The universe will decay to a cold and dark expanse before you experience a collision.

How to initialize an array in one step using Ruby?

Oneliner:

array = [] << 1 << 2 << 3   #this is for fixnums.

or

 a = %w| 1 2 3 4 5 |

or

 a = [*'1'..'3']

or

 a = Array.new(3, '1')

or

 a = Array[*'1'..'3']

Angular 2 'component' is not a known element

I had the same problem with Angular CLI: 10.1.5 The code works fine, but the error was shown in the VScode v1.50

Resolved by killing the terminal (ng serve) and restarting VScode.

Multi-line string with extra space (preserved indentation)

in a bash script the following works:

#!/bin/sh

text="this is line one\nthis is line two\nthis is line three"
echo -e $text > filename

alternatively:

text="this is line one
this is line two
this is line three"
echo "$text" > filename

cat filename gives:

this is line one
this is line two
this is line three

Selector on background color of TextView

Even this works.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/dim_orange_btn_pressed" />
    <item android:state_focused="true" android:drawable="@color/dim_orange_btn_pressed" />
    <item android:drawable="@android:color/white" />
</selector>

I added the android:drawable attribute to each item, and their values are colors.

By the way, why do they say that color is one of the attributes of selector? They don't write that android:drawable is required.

Color State List Resource

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:color="hex_color"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>

File Upload to HTTP server in iphone programming

Try this.. very easy to understand & implementation...

You can download sample code directly here https://github.com/Tech-Dev-Mobile/Json-Sample

- (void)simpleJsonParsingPostMetod
{

#warning set webservice url and parse POST method in JSON
    //-- Temp Initialized variables
    NSString *first_name;
    NSString *image_name;
    NSData *imageData;

    //-- Convert string into URL
    NSString *urlString = [NSString stringWithFormat:@"demo.com/your_server_db_name/service/link"];
    NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = @"14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    //-- Append data into posr url using following method
    NSMutableData *body = [NSMutableData data];


    //-- For Sending text

        //-- "firstname" is keyword form service
        //-- "first_name" is the text which we have to send
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"firstname"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@",first_name] dataUsingEncoding:NSUTF8StringEncoding]];


    //-- For sending image into service if needed (send image as imagedata)

        //-- "image_name" is file name of the image (we can set custom name)
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"file\"; filename=\"%@\"\r\n",image_name] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];


    //-- Sending data into server through URL
    [request setHTTPBody:body];

    //-- Getting response form server
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    //-- JSON Parsing with response data
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"Result = %@",result);
}

React - Component Full Screen (with height 100%)

Adding this in the index.html head worked for me:

<style>
    html, body, #app, #app>div { position: absolute; width: 100% !important; height: 100% !important; }
</style>

Convert data file to blob

As pointed in the comments, file is a blob:

file instanceof Blob; // true

And you can get its content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader

Read more: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

_x000D_
_x000D_
var input = document.querySelector('input[type=file]');
var textarea = document.querySelector('textarea');

function readFile(event) {
  textarea.textContent = event.target.result;
  console.log(event.target.result);
}

function changeFile() {
  var file = input.files[0];
  var reader = new FileReader();
  reader.addEventListener('load', readFile);
  reader.readAsText(file);
}

input.addEventListener('change', changeFile);
_x000D_
<input type="file">
<textarea rows="10" cols="50"></textarea>
_x000D_
_x000D_
_x000D_

How can I list all foreign keys referencing a given table in SQL Server?

This gets any foreign key that involves the chosen table. *Assumes a _FIRSTABLENAME_SECONDTABLENAME format.

 declare @tablename as varchar(MAX)
 SET @tablename = 'yourtablename'
 SELECT name
 FROM YOURDATABASE.sys.objects
 WHERE type_desc = 'FOREIGN_KEY_CONSTRAINT' and (name LIKE '%_' + @tablename + 'empdb_%' or name LIKE '%_' + @tablename )

This is a more general form:

 SELECT name
 FROM YOURDATABASE_PROD.sys.objects
 WHERE type_desc = 'FOREIGN_KEY_CONSTRAINT' and name LIKE '%' + @tablename + '%' and
 name NOT LIKE '[a-zA-Z0-9]' + @tablename + '%' and name NOT LIKE '%' + @tablename + '[a-zA-Z0-9]' 

android: data binding error: cannot find symbol class

Don't forget to add in app level gradle, apply plugin: 'kotlin-kapt'

PHP mkdir: Permission denied problem

You need to have file system permission to create the directory.

Example: In Ubuntu 10.04 apache (php) runs as user: www-data in group: www-data

Meaning the user www-data needs access to create the directory.

You can try this yourself by using: 'su www-data' to become the www-data user.

As a quick fix, you can do: sudo chmod 777 my_parent_dir

What's the best CRLF (carriage return, line feed) handling strategy with Git?

Try setting the core.autocrlf configuration option to true. Also have a look at the core.safecrlf option.

Actually it sounds like core.safecrlf might already be set in your repository, because (emphasis mine):

If this is not the case for the current setting of core.autocrlf, git will reject the file.

If this is the case, then you might want to check that your text editor is configured to use line endings consistently. You will likely run into problems if a text file contains a mixture of LF and CRLF line endings.

Finally, I feel that the recommendation to simply "use what you're given" and use LF terminated lines on Windows will cause more problems than it solves. Git has the above options to try to handle line endings in a sensible way, so it makes sense to use them.

Using FileUtils in eclipse

Open the project's properties---> Java Build Path ---> Libraries tab ---> Add External Jars

will allow you to add jars.

You need to download commonsIO from here.

Check/Uncheck a checkbox on datagridview

The code bellow allows the user to un-/check the checkboxes in the DataGridView, if the Cells are created in code

private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];

    if (chk.Value == chk.TrueValue)
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
    }
    else
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
    }

}

What is the better API to Reading Excel sheets in java - JXL or Apache POI

For reading "plain" CSV files in Java, there is a library called OpenCSV, available here: http://opencsv.sourceforge.net/

Does JSON syntax allow duplicate keys in an object?

There are 2 documents specifying the JSON format:

  1. http://json.org/
  2. https://tools.ietf.org/html/rfc7159

The accepted answer quotes from the 1st document. I think the 1st document is more clear, but the 2nd contains more detail.

The 2nd document says:

  1. Objects

    An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

So it is not forbidden to have a duplicate name, but it is discouraged.

Playing a MP3 file in a WinForm application

1) The most simple way would be using WMPLib

WMPLib.WindowsMediaPlayer Player;

private void PlayFile(String url)
{
    Player = new WMPLib.WindowsMediaPlayer();
    Player.PlayStateChange += Player_PlayStateChange;
    Player.URL = url;
    Player.controls.play();
}

private void Player_PlayStateChange(int NewState)
{
    if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
    {
        //Actions on stop
    }
}

2) Alternatively you can use the open source library NAudio. It can play mp3 files using different methods and actually offers much more than just playing a file.

This is as simple as

using NAudio;
using NAudio.Wave;

IWavePlayer waveOutDevice = new WaveOut();
AudioFileReader audioFileReader = new AudioFileReader("Hadouken! - Ugly.mp3");

waveOutDevice.Init(audioFileReader);
waveOutDevice.Play();

Don't forget to dispose after the stop

waveOutDevice.Stop();
audioFileReader.Dispose();
waveOutDevice.Dispose();

Class method differences in Python: bound, unbound and static

that is an error.

first of all, first line should be like this (be careful of capitals)

class Test(object):

Whenever you call a method of a class, it gets itself as the first argument (hence the name self) and method_two gives this error

>>> a.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

blur vs focusout -- any real differences?

As stated in the JQuery documentation

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

Get the latest record from mongodb collection

Yet another way of getting the last item from a MongoDB Collection (don't mind about the examples):

> db.collection.find().sort({'_id':-1}).limit(1)

Normal Projection

> db.Sports.find()
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2017", "Body" : "Again, the Pats won the Super Bowl." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }

Sorted Projection ( _id: reverse order )

> db.Sports.find().sort({'_id':-1})
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2018", "Body" : "Again, the Pats won the Super Bowl" }

sort({'_id':-1}), defines a projection in descending order of all documents, based on their _ids.

Sorted Projection ( _id: reverse order ): getting the latest (last) document from a collection.

> db.Sports.find().sort({'_id':-1}).limit(1)
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }

SQL Server : fetching records between two dates?

The unambiguous way to write this is (i.e. increase the 2nd date by 1 and make it <)

select * 
from xxx 
where dates >= '20121026'
  and dates <  '20121028'

If you're using SQL Server 2008 or above, you can safety CAST as DATE while retaining SARGability, e.g.

select * 
from xxx 
where CAST(dates as DATE) between '20121026' and '20121027'

This explicitly tells SQL Server that you are only interested in the DATE portion of the dates column for comparison against the BETWEEN range.

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

You can use an RDLC file provided in visual studio to define your report layout. You can view the rdlc using the ReportViewer control.

Both are provided out of the box with visual studio.

What is the best way to uninstall gems from a rails3 project?

This will uninstall a gem installed by bundler:

bundle exec gem uninstall GEM_NAME

Note that this throws

ERROR: While executing gem ... (NoMethodError) undefined method `delete' for #<Bundler::SpecSet:0x00000101142268>

but the gem is actually removed. Next time you run bundle install the gem will be reinstalled.

JavaScript: Get image dimensions

var img = new Image();

img.onload = function(){
  var height = img.height;
  var width = img.width;

  // code here to use the dimensions
}

img.src = url;

How to make grep only match if the entire line matches?

similarly with awk

 awk '/^ABB\.log$/' file

Compiling dynamic HTML strings from database

Try this below code for binding html through attr

.directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      scope: { dynamic: '=dynamic'},
      link: function postLink(scope, element, attrs) {
        scope.$watch( 'attrs.dynamic' , function(html){
          element.html(scope.dynamic);
          $compile(element.contents())(scope);
        });
      }
    };
  });

Try this element.html(scope.dynamic); than element.html(attr.dynamic);

async/await - when to return a Task vs void?

I have come across this very useful article about async and void written by Jérôme Laban: https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html

The bottom line is that an async+void can crash the system and usually should be used only on the UI side event handlers.

The reason behind this is the Synchronization Context used by the AsyncVoidMethodBuilder, being none in this example. When there is no ambient Synchronization Context, any exception that is unhandled by the body of an async void method is rethrown on the ThreadPool. While there is seemingly no other logical place where that kind of unhandled exception could be thrown, the unfortunate effect is that the process is being terminated, because unhandled exceptions on the ThreadPool effectively terminate the process since .NET 2.0. You may intercept all unhandled exception using the AppDomain.UnhandledException event, but there is no way to recover the process from this event.

When writing UI event handlers, async void methods are somehow painless because exceptions are treated the same way found in non-async methods; they are thrown on the Dispatcher. There is a possibility to recover from such exceptions, with is more than correct for most cases. Outside of UI event handlers however, async void methods are somehow dangerous to use and may not that easy to find.

Why can templates only be implemented in the header file?

Templates need to be instantiated by the compiler before actually compiling them into object code. This instantiation can only be achieved if the template arguments are known. Now imagine a scenario where a template function is declared in a.h, defined in a.cpp and used in b.cpp. When a.cpp is compiled, it is not necessarily known that the upcoming compilation b.cpp will require an instance of the template, let alone which specific instance would that be. For more header and source files, the situation can quickly get more complicated.

One can argue that compilers can be made smarter to "look ahead" for all uses of the template, but I'm sure that it wouldn't be difficult to create recursive or otherwise complicated scenarios. AFAIK, compilers don't do such look aheads. As Anton pointed out, some compilers support explicit export declarations of template instantiations, but not all compilers support it (yet?).

ASP.NET MVC View Engine Comparison

Check this SharpDOM . This is a c# 4.0 internal dsl for generating html and also asp.net mvc view engine.

In SQL Server, what does "SET ANSI_NULLS ON" mean?

If @Region is not a null value (lets say @Region = 'South') it will not return rows where the Region field is null, regardless of the value of ANSI_NULLS.

ANSI_NULLS will only make a difference when the value of @Region is null, i.e. when your first query essentially becomes the second one.

In that case, ANSI_NULLS ON will not return any rows (because null = null will yield an unknown boolean value (a.k.a. null)) and ANSI_NULLS OFF will return any rows where the Region field is null (because null = null will yield true)

python list by value not by reference

When you do b = a you simply create another pointer to the same memory of a, that's why when you append to b , a changes too.

You need to create copy of a and that's done like this:

b = a[:]

How do I iterate through table rows and cells in JavaScript?

If you want one with a functional style, like this:

    const table = document.getElementById("mytab1");
    const cells = table.rows.toArray()
                  .flatMap(row => row.cells.toArray())
                  .map(cell => cell.innerHTML); //["col1 Val1", "col2 Val2", "col1 Val3", "col2 Val4"]

You may modify the prototype object of HTMLCollection (allowing to use in a way that resembles extension methods in C#) and embed into it a function that converts collection into array, allowing to use higher order funcions with the above style (kind of linq style in C#):

    Object.defineProperty(HTMLCollection.prototype, "toArray", {
        value: function toArray() {
            return Array.prototype.slice.call(this, 0);
        },
        writable: true,
        configurable: true
    });

Current date without time

it should be as simple as

DateTime.Today

Array of char* should end at '\0' or "\0"?

The termination of an array of characters with a null character is just a convention that is specifically for strings in C. You are dealing with something completely different -- an array of character pointers -- so it really has no relation to the convention for C strings. Sure, you could choose to terminate it with a null pointer; that perhaps could be your convention for arrays of pointers. There are other ways to do it. You can't ask people how it "should" work, because you're assuming some convention that isn't there.

What's the difference between RANK() and DENSE_RANK() functions in oracle?

The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).

For example, consider the set {25, 25, 50, 75, 75, 100}. For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.

How to get autocomplete in jupyter notebook without using tab?

There is an extension called Hinterland for jupyter, which automatically displays the drop down menu when typing. There are also some other useful extensions.

In order to install extensions, you can follow the guide on this github repo. To easily activate extensions, you may want to use the extensions configurator.

What is the best way to search the Long datatype within an Oracle database?

Example:

create table longtable(id number,text long);

insert into longtable values(1,'hello world');
insert into longtable values(2,'say hello!');

commit;

create or replace function search_long(r rowid) return varchar2 is
temporary_varchar varchar2(4000);
begin
select text into temporary_varchar from longtable where rowid=r;
return temporary_varchar;
end;
/


SQL> select text from longtable where search_long(rowid) like '%hello%';                                                                              

TEXT
--------------------------------------------------------------------------------
hello world
say hello!

But be careful. A PL/SQL function will only search the first 32K of LONG.

Changing background color of text box input not working when empty

You didn't call the function and you have other errors, should be:

function checkFilled() {
    var inputVal = document.getElementById("subEmail");
    if (inputVal.value == "") {
        inputVal.style.backgroundColor = "yellow";
    }
}
checkFilled();

Fiddle

You were setting inputVal to the string value of the input, but then you tried to set style.backgroundColor on it, which won't work because it's a string, not the element. I changed your variable to store the element object instead of its value.

Select from one table matching criteria in another?

You should make tags their own table with a linking table.

items:
id    object
1     lamp  
2     table   
3     stool  
4     bench 

tags:
id     tag
1      furniture
2      chair

items_tags:
item_id tag_id
1       1
2       1
3       1
4       1
3       2
4       2

How to add multiple classes to a ReactJS Component?

for more classes adding

... className={`${classes.hello} ${classes.hello1}`...

python pandas dataframe to dictionary

If you want a simple way to preserve duplicates, you could use groupby:

>>> ptest = pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id', 'value']) 
>>> ptest
  id  value
0  a      1
1  a      2
2  b      3
>>> {k: g["value"].tolist() for k,g in ptest.groupby("id")}
{'a': [1, 2], 'b': [3]}

How to generate unique ID with node.js

Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random().

Math.random()

Mathematically, the chances of fractions being the same in a real space [0, 1] is theoretically 0. Probability-wise it is approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.

I call this the "Fractional-Unique-ID".

Wrote code to generate 1,000,000 Math.random() numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):

random_numbers = [] 
for (i = 0; i < 1000000; i++) { 
   random_numbers.push(Math.random()); 
   //random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16 
} 

if (i === 1000000) { 
   console.log("Before checking duplicate"); 
   console.log(random_numbers.length); 
   console.log("After checking duplicate"); 
   random_set = new Set(random_numbers); // Set removes duplicates
   console.log([...random_set].length); // length is still the same after removing
} 

The remote server returned an error: (403) Forbidden

In my case I remembered that a hole in the firewall was created for this address some time ago, so I had to set useDefaultWebProxy="false" on the binding in the config file, as if the default was to use the proxy if useDefaultWebProxy is not specified.

Deciding between HttpClient and WebClient

Perhaps you could think about the problem in a different way. WebClient and HttpClient are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient and HttpClient, and then use the IoC container to inject the implementation via config.

What this would allow you to do would be to switch between HttpClient and WebClient easily so that you are able to objectively test in the production environment.

So questions like:

Will HttpClient be a better design choice if we upgrade to .Net 4.5?

Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient or WebClient.

/// <summary>
/// Dependency Injection abstraction for rest clients. 
/// </summary>
public interface IClient
{
    /// <summary>
    /// Adapter for serialization/deserialization of http body data
    /// </summary>
    ISerializationAdapter SerializationAdapter { get; }

    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns></returns>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Default timeout for http requests
    /// </summary>
    TimeSpan Timeout { get; set; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    Uri BaseUri { get; set; }

    /// <summary>
    /// Name of the client
    /// </summary>
    string Name { get; }
}

public class Request<TRequestBody>
{
    #region Public Properties
    public IHeadersCollection Headers { get; }
    public Uri Resource { get; set; }
    public HttpRequestMethod HttpRequestMethod { get; set; }
    public TRequestBody Body { get; set; }
    public CancellationToken CancellationToken { get; set; }
    public string CustomHttpRequestMethod { get; set; }
    #endregion

    public Request(Uri resource,
        TRequestBody body,
        IHeadersCollection headers,
        HttpRequestMethod httpRequestMethod,
        IClient client,
        CancellationToken cancellationToken)
    {
        Body = body;
        Headers = headers;
        Resource = resource;
        HttpRequestMethod = httpRequestMethod;
        CancellationToken = cancellationToken;

        if (Headers == null) Headers = new RequestHeadersCollection();

        var defaultRequestHeaders = client?.DefaultRequestHeaders;
        if (defaultRequestHeaders == null) return;

        foreach (var kvp in defaultRequestHeaders)
        {
            Headers.Add(kvp);
        }
    }
}

public abstract class Response<TResponseBody> : Response
{
    #region Public Properties
    public virtual TResponseBody Body { get; }

    #endregion

    #region Constructors
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response() : base()
    {
    }

    protected Response(
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    TResponseBody body,
    Uri requestUri
    ) : base(
        headersCollection,
        statusCode,
        httpRequestMethod,
        responseData,
        requestUri)
    {
        Body = body;
    }

    public static implicit operator TResponseBody(Response<TResponseBody> readResult)
    {
        return readResult.Body;
    }
    #endregion
}

public abstract class Response
{
    #region Fields
    private readonly byte[] _responseData;
    #endregion

    #region Public Properties
    public virtual int StatusCode { get; }
    public virtual IHeadersCollection Headers { get; }
    public virtual HttpRequestMethod HttpRequestMethod { get; }
    public abstract bool IsSuccess { get; }
    public virtual Uri RequestUri { get; }
    #endregion

    #region Constructor
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response()
    {
    }

    protected Response
    (
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    Uri requestUri
    )
    {
        StatusCode = statusCode;
        Headers = headersCollection;
        HttpRequestMethod = httpRequestMethod;
        RequestUri = requestUri;
        _responseData = responseData;
    }
    #endregion

    #region Public Methods
    public virtual byte[] GetResponseData()
    {
        return _responseData;
    }
    #endregion
}

Full code

HttpClient Implementation

You can use Task.Run to make WebClient run asynchronously in its implementation.

Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient may work better for some customers, and HttpClient may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.

BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.

How to fill DataTable with SQL Table

The SqlDataReader is a valid data source for the DataTable. As such, all you need to do its this:

public DataTable GetData()
{
    SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
    conn.Open();
    string query = "SELECT * FROM [EventOne]";
    SqlCommand cmd = new SqlCommand(query, conn);

    DataTable dt = new DataTable();
    dt.Load(cmd.ExecuteReader());
    conn.Close();
    return dt;
}

How to embed images in html email

I'm using this function that find all images in my letter and attaches it to the message.

Parameters: Takes your HTML (which you want to send);
Return: The necessary HTML and headers, which you can use in mail();

Example usage:

define("DEFCALLBACKMAIL", "[email protected]"); // WIll be shown as "from".
$final_msg = preparehtmlmail($html); // give a function your html*

mail('[email protected]', 'your subject', $final_msg['multipart'], $final_msg['headers']); 
// send email with all images from html attached to letter


function preparehtmlmail($html) {

  preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
  $i = 0;
  $paths = array();

  foreach ($matches[1] as $img) {
    $img_old = $img;

    if(strpos($img, "http://") == false) {
      $uri = parse_url($img);
      $paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
      $content_id = md5($img);
      $html = str_replace($img_old,'cid:'.$content_id,$html);
      $paths[$i++]['cid'] = $content_id;
    }
  }

  $boundary = "--".md5(uniqid(time()));
  $headers .= "MIME-Version: 1.0\n";
  $headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
  $headers .= "From: ".DEFCALLBACKMAIL."\r\n";
  $multipart = '';
  $multipart .= "--$boundary\n";
  $kod = 'utf-8';
  $multipart .= "Content-Type: text/html; charset=$kod\n";
  $multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
  $multipart .= "$html\n\n";

  foreach ($paths as $path) {
    if(file_exists($path['path']))
      $fp = fopen($path['path'],"r");
      if (!$fp)  {
        return false;
      }

    $imagetype = substr(strrchr($path['path'], '.' ),1);
    $file = fread($fp, filesize($path['path']));
    fclose($fp);

    $message_part = "";

    switch ($imagetype) {
      case 'png':
      case 'PNG':
            $message_part .= "Content-Type: image/png";
            break;
      case 'jpg':
      case 'jpeg':
      case 'JPG':
      case 'JPEG':
            $message_part .= "Content-Type: image/jpeg";
            break;
      case 'gif':
      case 'GIF':
            $message_part .= "Content-Type: image/gif";
            break;
    }

    $message_part .= "; file_name = \"$path\"\n";
    $message_part .= 'Content-ID: <'.$path['cid'].">\n";
    $message_part .= "Content-Transfer-Encoding: base64\n";
    $message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
    $message_part .= chunk_split(base64_encode($file))."\n";
    $multipart .= "--$boundary\n".$message_part."\n";

  }

  $multipart .= "--$boundary--\n";
  return array('multipart' => $multipart, 'headers' => $headers);  
}

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

What worked for me was to rename the project by removing the special characters.

Example: "project_marketplace" to "projectmarketplace"

In this case, I redid the project with react-native init and copied the src and package.json folder.

HttpURLConnection timeout settings

If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period

public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
    AsyncTask<Params, Progress, Result> {

private static final int HTTP_REQUEST_TIMEOUT = 30000;

@Override
protected Result doInBackground(Params... params) {
    createTimeoutListener();
    return doInBackgroundImpl(params);
}

private void createTimeoutListener() {
    Thread timeout = new Thread() {
        public void run() {
            Looper.prepare();

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    if (AsyncTaskWithTimer.this != null
                            && AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
                        AsyncTaskWithTimer.this.cancel(true);
                    handler.removeCallbacks(this);
                    Looper.myLooper().quit();
                }
            }, HTTP_REQUEST_TIMEOUT);

            Looper.loop();
        }
    };
    timeout.start();
}

abstract protected Result doInBackgroundImpl(Params... params);
}

A Sample for this

public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {

    @Override
    protected void onCancelled(Void void) {
        Log.d(TAG, "Async Task onCancelled With Result");
        super.onCancelled(result);
    }

    @Override
    protected void onCancelled() {
        Log.d(TAG, "Async Task onCancelled");
        super.onCancelled();
    }

    @Override
    protected Void doInBackgroundImpl(Void... params) {
        // Do background work
        return null;
    };
 }

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;

ArrayList<String> recordings = new ArrayList<String>();

this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.

How to list containers in Docker

To show only running containers use the given command:

docker ps

To show all containers use the given command:

docker ps -a

To show the latest created container (includes all states) use the given command:

docker ps -l

To show n last created containers (includes all states) use the given command:

docker ps -n=-1

To display total file sizes use the given command:

docker ps -s

The content presented above is from docker.com.

In the new version of Docker, commands are updated, and some management commands are added:

docker container ls

It is used to list all the running containers.

docker container ls -a

And then, if you want to clean them all,

docker rm $(docker ps -aq)

It is used to list all the containers created irrespective of its state.

And to stop all the Docker containers (force)

docker rm -f $(docker ps -a -q)  

Here the container is the management command.

OpenCV !_src.empty() in function 'cvtColor' error

If the path is correct and the name of the image is OK, but you are still getting the error

use:

from skimage import io

img = io.imread(file_path)

instead of:

cv2.imread(file_path)

The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).

Get last 3 characters of string

The easiest way would be using Substring

string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);

Using the overload with one int as I put would get the substring of a string, starting from the index int. In your case being str.Length - 3, since you want to get the last three chars.

Adding 'serial' to existing column in Postgres

You can also use START WITH to start a sequence from a particular point, although setval accomplishes the same thing, as in Euler's answer, eg,

SELECT MAX(a) + 1 FROM foo;
CREATE SEQUENCE foo_a_seq START WITH 12345; -- replace 12345 with max above
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

spring.jackson.serialization-inclusion=non_null used to work for us

But when we upgraded spring boot version to 1.4.2.RELEASE or higher, it stopped working.

Now, another property spring.jackson.default-property-inclusion=non_null is doing the magic.

in fact, serialization-inclusion is deprecated. This is what my intellij throws at me.

Deprecated: ObjectMapper.setSerializationInclusion was deprecated in Jackson 2.7

So, start using spring.jackson.default-property-inclusion=non_null instead

How to convert a string into double and vice versa?

To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter configured for the locale from which you're reading the string.

Different locales will format numbers differently. For example, in some parts of the world, COMMA is used as a decimal separator while in others it is PERIOD — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.

It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter for the way your input is formatted and use -[NSFormatter numberFromString:] to get an NSNumber from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:] instead.

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

Hyphen, underscore, or camelCase as word delimiter in URIs?

It is recommended to use the spinal-case (which is highlighted by RFC3986), this case is used by Google, PayPal, and other big companies.

source:- https://blog.restcase.com/5-basic-rest-api-design-guidelines/

Richtextbox wpf binding

I know this is an old post, but check out the Extended WPF Toolkit. It has a RichTextBox that supports what you are tryign to do.

How to comment out a block of code in Python

In Eclipse + PyDev, Python block commenting is similar to Eclipse Java block commenting; select the lines you want to comment and use Ctrl + / to comment. To uncomment a commented block, do the same thing.

How to resolve Unneccessary Stubbing exception

If you use any() when mocking, you have to relpace @RunWith(MockitoJUnitRunner.class) with @RunWith(MockitoJUnitRunner.Silent.class).

MongoDB running but can't connect using shell

If your mongoDB server(remote server)'s version is greater then 4.0.3, then you will face this issue. Hence you should replace your current mongo-client shell with below mongo :

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org

Then you mongo client will be able to connect your remove mongodb

Auto logout with Angularjs based on idle user

View Demo which is using angularjs and see your's browser log

<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>

<body>
</body>

<script>

var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {    
    console.log('starting run');

    // Timeout timer value
    var TimeOutTimerValue = 5000;

    // Start a timeout
    var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    var bodyElement = angular.element($document);

    /// Keyboard Events
    bodyElement.bind('keydown', function (e) { TimeOut_Resetter(e) });  
    bodyElement.bind('keyup', function (e) { TimeOut_Resetter(e) });    

    /// Mouse Events    
    bodyElement.bind('click', function (e) { TimeOut_Resetter(e) });
    bodyElement.bind('mousemove', function (e) { TimeOut_Resetter(e) });    
    bodyElement.bind('DOMMouseScroll', function (e) { TimeOut_Resetter(e) });
    bodyElement.bind('mousewheel', function (e) { TimeOut_Resetter(e) });   
    bodyElement.bind('mousedown', function (e) { TimeOut_Resetter(e) });        

    /// Touch Events
    bodyElement.bind('touchstart', function (e) { TimeOut_Resetter(e) });       
    bodyElement.bind('touchmove', function (e) { TimeOut_Resetter(e) });        

    /// Common Events
    bodyElement.bind('scroll', function (e) { TimeOut_Resetter(e) });       
    bodyElement.bind('focus', function (e) { TimeOut_Resetter(e) });    

    function LogoutByTimer()
    {
        console.log('Logout');

        ///////////////////////////////////////////////////
        /// redirect to another page(eg. Login.html) here
        ///////////////////////////////////////////////////
    }

    function TimeOut_Resetter(e)
    {
        console.log('' + e);

        /// Stop the pending timeout
        $timeout.cancel(TimeOut_Thread);

        /// Reset the timeout
        TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    }

})
</script>

</html>

Below code is pure javascript version

<html>
    <head>
        <script type="text/javascript">         
            function logout(){
                console.log('Logout');
            }

            function onInactive(millisecond, callback){
                var wait = setTimeout(callback, millisecond);               
                document.onmousemove = 
                document.mousedown = 
                document.mouseup = 
                document.onkeydown = 
                document.onkeyup = 
                document.focus = function(){
                    clearTimeout(wait);
                    wait = setTimeout(callback, millisecond);                       
                };
            }           
        </script>
    </head> 
    <body onload="onInactive(5000, logout);"></body>
</html>

UPDATE

I updated my solution as @Tom suggestion.

<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>

<body>
</body>

<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {    
    console.log('starting run');

    // Timeout timer value
    var TimeOutTimerValue = 5000;

    // Start a timeout
    var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    var bodyElement = angular.element($document);

    angular.forEach(['keydown', 'keyup', 'click', 'mousemove', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'scroll', 'focus'], 
    function(EventName) {
         bodyElement.bind(EventName, function (e) { TimeOut_Resetter(e) });  
    });

    function LogoutByTimer(){
        console.log('Logout');
        ///////////////////////////////////////////////////
        /// redirect to another page(eg. Login.html) here
        ///////////////////////////////////////////////////
    }

    function TimeOut_Resetter(e){
        console.log(' ' + e);

        /// Stop the pending timeout
        $timeout.cancel(TimeOut_Thread);

        /// Reset the timeout
        TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    }

})
</script>
</html>

Click here to see at Plunker for updated version

In an array of objects, fastest way to find the index of an object whose attributes match a search

Maybe you would like to use higher-order functions such as "map". Assuming you want search by 'field' attribute:

var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];

Test if a property is available on a dynamic variable

I know this is really old post but here is a simple solution to work with dynamic type in c#.

  1. can use simple reflection to enumerate direct properties
  2. or can use the object extention method
  3. or use GetAsOrDefault<int> method to get a new strongly typed object with value if exists or default if not exists.
public static class DynamicHelper
{
    private static void Test( )
    {
        dynamic myobj = new
                        {
                            myInt = 1,
                            myArray = new[ ]
                                      {
                                          1, 2.3
                                      },
                            myDict = new
                                     {
                                         myInt = 1
                                     }
                        };

        var myIntOrZero = myobj.GetAsOrDefault< int >( ( Func< int > )( ( ) => myobj.noExist ) );
        int? myNullableInt = GetAs< int >( myobj, ( Func< int > )( ( ) => myobj.myInt ) );

        if( default( int ) != myIntOrZero )
            Console.WriteLine( $"myInt: '{myIntOrZero}'" );

        if( default( int? ) != myNullableInt )
            Console.WriteLine( $"myInt: '{myNullableInt}'" );

        if( DoesPropertyExist( myobj, "myInt" ) )
            Console.WriteLine( $"myInt exists and it is: '{( int )myobj.myInt}'" );
    }

    public static bool DoesPropertyExist( dynamic dyn, string property )
    {
        var t = ( Type )dyn.GetType( );
        var props = t.GetProperties( );
        return props.Any( p => p.Name.Equals( property ) );
    }

    public static object GetAs< T >( dynamic obj, Func< T > lookup )
    {
        try
        {
            var val = lookup( );
            return ( T )val;
        }
        catch( RuntimeBinderException ) { }

        return null;
    }

    public static T GetAsOrDefault< T >( this object obj, Func< T > test )
    {
        try
        {
            var val = test( );
            return ( T )val;
        }
        catch( RuntimeBinderException ) { }

        return default( T );
    }
}

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

JOptionPane Input to int

Simply use:

int ans = Integer.parseInt( JOptionPane.showInputDialog(frame,
        "Text",
        JOptionPane.INFORMATION_MESSAGE,
        null,
        null,
        "[sample text to help input]"));

You cannot cast a String to an int, but you can convert it using Integer.parseInt(string).

Why use double indirection? or Why use pointers to pointers?

I saw a very good example today, from this blog post, as I summarize below.

Imagine you have a structure for nodes in a linked list, which probably is

typedef struct node
{
    struct node * next;
    ....
} node;

Now you want to implement a remove_if function, which accepts a removal criterion rm as one of the arguments and traverses the linked list: if an entry satisfies the criterion (something like rm(entry)==true), its node will be removed from the list. In the end, remove_if returns the head (which may be different from the original head) of the linked list.

You may write

for (node * prev = NULL, * curr = head; curr != NULL; )
{
    node * const next = curr->next;
    if (rm(curr))
    {
        if (prev)  // the node to be removed is not the head
            prev->next = next;
        else       // remove the head
            head = next;
        free(curr);
    }
    else
        prev = curr;
    curr = next;
}

as your for loop. The message is, without double pointers, you have to maintain a prev variable to re-organize the pointers, and handle the two different cases.

But with double pointers, you can actually write

// now head is a double pointer
for (node** curr = head; *curr; )
{
    node * entry = *curr;
    if (rm(entry))
    {
        *curr = entry->next;
        free(entry);
    }
    else
        curr = &entry->next;
}

You don't need a prev now because you can directly modify what prev->next pointed to.

To make things clearer, let's follow the code a little bit. During the removal:

  1. if entry == *head: it will be *head (==*curr) = *head->next -- head now points to the pointer of the new heading node. You do this by directly changing head's content to a new pointer.
  2. if entry != *head: similarly, *curr is what prev->next pointed to, and now points to entry->next.

No matter in which case, you can re-organize the pointers in a unified way with double pointers.

Transaction isolation levels relation with locks on table

I want to understand the lock each transaction isolation takes on the table

For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT statement to read data. C reads and updates data. All these process work on the same table T.

  • READ UNCOMMITTED - no lock on the table. You can read data in the table while writing on it. This means A writes data (uncommitted) and B can read this uncommitted data and use it (for any purpose). If A executes a rollback, B still has read the data and used it. This is the fastest but most insecure way to work with data since can lead to data holes in not physically related tables (yes, two tables can be logically but not physically related in real-world apps =\).
  • READ COMMITTED - lock on committed data. You can read the data that was only committed. This means A writes data and B can't read the data saved by A until A executes a commit. The problem here is that C can update data that was read and used on B and B client won't have the updated data.
  • REPEATABLE READ - lock on a block of SQL(which is selected by using select query). This means B reads the data under some condition i.e. WHERE aField > 10 AND aField < 20, A inserts data where aField value is between 10 and 20, then B reads the data again and get a different result.
  • SERIALIZABLE - lock on a full table(on which Select query is fired). This means, B reads the data and no other transaction can modify the data on the table. This is the most secure but slowest way to work with data. Also, since a simple read operation locks the table, this can lead to heavy problems on production: imagine that T table is an Invoice table, user X wants to know the invoices of the day and user Y wants to create a new invoice, so while X executes the read of the invoices, Y can't add a new invoice (and when it's about money, people get really mad, especially the bosses).

I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also

Using JDBC, you define it using Connection#setTransactionIsolation.

Using Hibernate:

<property name="hibernate.connection.isolation">2</property>

Where

  • 1: READ UNCOMMITTED
  • 2: READ COMMITTED
  • 4: REPEATABLE READ
  • 8: SERIALIZABLE

Hibernate configuration is taken from here (sorry, it's in Spanish).

By the way, you can set the isolation level on RDBMS as well:

and on and on...

Converting String Array to an Integer Array

Stream.of().mapToInt().toArray() seems to be the best options.

int[] arr = Stream.of(new String[]{"1", "2", "3"})
                  .mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));

How can I get the name of an html page in Javascript?

var path = window.location.pathname;
var page = path.split("/").pop();
console.log( page );

How to change indentation in Visual Studio Code?

To change the indentation based on programming language:

  1. Open the Command Palette (CtrlShiftP | macOS: ??P)

  2. Preferences: Configure language specific settings... (command id: workbench.action.configureLanguageBasedSettings)

  3. Select programming language (for example TypeScript)

  4. Add this code:

    "[typescript]": {
        "editor.tabSize": 2
    }
    

See also: VS Code Docs

What is an alternative to execfile in Python 3?

If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?

If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.

>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'

test.py:

def run():
        return "Hello world!"

If you're using Python 3.1 or later, you should also take a look at importlib.

Lumen: get URL parameter in a Blade view

Laravel 5.8

{{ request()->a }}

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

Jquery select change not firing

For me perfectly fork this code.

$('#dom_object_id').on('change paste keyup', function(){
    console.log($("#dom_object_id").val().length)
});

Key event for .on() function is "paste" to get changes dynamically

Find the 2nd largest element in an array with minimum number of comparisons

PHP version of the Gumbo algorithm: http://sandbox.onlinephpfunctions.com/code/51e1b05dac2e648fd13e0b60f44a2abe1e4a8689

$numbers = [10, 9, 2, 3, 4, 5, 6, 7];

$largest = $numbers[0];
$secondLargest = null;
for ($i=1; $i < count($numbers); $i++) {
    $number = $numbers[$i];
    if ($number > $largest) {
        $secondLargest = $largest;
        $largest = $number;
    } else if ($number > $secondLargest) {
        $secondLargest = $number;
    }
}

echo "largest=$largest, secondLargest=$secondLargest";

Java string replace and the NUL (NULL, ASCII 0) character?

I think it should be the case. To erase the character, you should use replace(".", "") instead.

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

If you are trying to delete a column which is a FOREIGN KEY, you must find the correct name which is not the column name. Eg: If I am trying to delete the server field in the Alarms table which is a foreign key to the servers table.

  1. SHOW CREATE TABLE alarm; Look for the CONSTRAINT `server_id_refs_id_34554433` FORIEGN KEY (`server_id`) REFERENCES `server` (`id`) line.
  2. ALTER TABLE `alarm` DROP FOREIGN KEY `server_id_refs_id_34554433`;
  3. ALTER TABLE `alarm` DROP `server_id`

This will delete the foreign key server from the Alarms table.

CSS: how do I create a gap between rows in a table?

Simply you can use padding-top and padding-bottom on a td element.

Unit can anything from this list:

enter image description here

Demo Code:

_x000D_
_x000D_
td_x000D_
{_x000D_
  padding-top: 10px;_x000D_
  padding-bottom: 10px;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <th>Firstname</th>_x000D_
    <th>Lastname</th>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Peter</td>_x000D_
    <td>Griffin</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Lois</td>_x000D_
    <td>Griffin</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

Use

sudo pip install virtualenv

Apparently you will have powers of administrator when adding "sudo" before the line... just don't forget your password.

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

We had a similar issue. Uploaded builds were queueing up and it simply said "Processing" with the popup help, “After builds are uploaded they will go through a processing state before they can be used.” Days passed.

Selecting "Internal Testers," making a change, and saving seemed to immediately clear the queue: The latest build was now active and available for testing. I've done this twice with two different apps now.

Update: At this point, all bets are off. It seems "processing" happens when Apple quietly upgrades iTunes Connect and there's nothing you can do about it.

On September 23, 2015 iTunes Connect didn't accept any uploads for nearly 24 hours. The "Internal Testers" trick didn't work. Eventually bumping the version number (to avoid "duplicate binary" error) and re-submitting worked.

The next day, Surprise! iTunes Connect was completely changed. I guess we were all looking at a dead site while they brought up the new version in the background :(

In our case we can still see dozens of "failed" uploads still sitting in the "processing" state. Oh well.

Some people report using Application Loader works better than Xcode for submitting builds to iTunes Connect. You can find it inside Xcode now, under the Xcode menu "Open Developer Tool" item.

Sometimes this works. Sometimes it doesn't. Your milage may vary ¯\_(?)_/¯

How can I change the user on Git Bash?

Check what git remote -v returns: the account used to push to an http url is usually embedded into the remote url itself.

https://[email protected]/...

If that is the case, put an url which will force Git to ask for the account to use when pushing:

git remote set-url origin https://github.com/<user>/<repo>

Or one to use the Fre1234 account:

git remote set-url origin https://[email protected]/<user>/<repo>

Also check if you installed your Git For Windows with or without a credential helper as in this question.


The OP Fre1234 adds in the comments:

I finally found the solution.
Go to: Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials

Under Generic Credentials there are some credentials related to Github,
Click on them and click "Remove".

That is because the default installation for Git for Windows set a Git-Credential-Manager-for-Windows.
See git config --global credential.helper output (it should be manager)

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
      MessageBox.Show("Hello")
    else if(btn.Tag == "Goodbye")
       Application.Exit();
    // etc.
}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
    if(/* some condition*/)
    {
       // Cancel this event
       e.Cancel = true;
    }
}

Adding hours to JavaScript Date object?

Check if its not already defined, otherwise defines it on the Date prototype:

if (!Date.prototype.addHours) {
    Date.prototype.addHours = function(h) {
        this.setHours(this.getHours() + h);
        return this;
    };
}

'if' in prolog?

A standard prolog predicate will do this.

   isfive(5). 

will evaluate to true if you call it with 5 and fail(return false) if you run it with anything else. For not equal you use \=

isNotEqual(A,B):- A\=B.

Technically it is does not unify, but it is similar to not equal.

Learn Prolog Now is a good website for learning prolog.

Edit: To add another example.

isEqual(A,A). 

How can I get the baseurl of site?

I go with

HttpContext.Current.Request.ServerVariables["HTTP_HOST"]

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

In Perl, how do I create a hash whose keys come from a given array?

Note that if typing if ( exists $hash{ key } ) isn’t too much work for you (which I prefer to use since the matter of interest is really the presence of a key rather than the truthiness of its value), then you can use the short and sweet

@hash{@key} = ();

What is the main difference between PATCH and PUT request?

There are limitations in PUT over PATCH while making updates. Using PUT requires us to specify all attributes even if we want to change only one attribute. But if we use the PATCH method we can update only the fields we need and there is no need to mention all the fields. PATCH does not allow us to modify a value in an array, or remove an attribute or array entry.

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

How do I get milliseconds from epoch (1970-01-01) in Java?

java.time

Using the java.time framework built into Java 8 and later.

import java.time.Instant;

Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900

This works in UTC because Instant.now() is really call to Clock.systemUTC().instant()

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html

Is it possible to specify a different ssh port when using rsync?

Another option, in the host you run rsync from, set the port in the ssh config file, ie:

cat ~/.ssh/config
Host host
    Port 2222

Then rsync over ssh will talk to port 2222:

rsync -rvz --progress --remove-sent-files ./dir user@host:/path

symfony 2 No route found for "GET /"

The problem is that you don't have a route for /. Change your definition to this:

ShopMyShopBundle_homepage:
    pattern:  /
    defaults: { _controller: ShopMyShopBundle:Main:index }
    requirements:
        _method:  GET

How to create an array from a CSV file using PHP and the fgetcsv function

This function will return array with Header values as array keys.

function csv_to_array($file_name) {
        $data =  $header = array();
        $i = 0;
        $file = fopen($file_name, 'r');
        while (($line = fgetcsv($file)) !== FALSE) {
            if( $i==0 ) {
                $header = $line;
            } else {
                $data[] = $line;        
            }
            $i++;
        }
        fclose($file);
        foreach ($data as $key => $_value) {
            $new_item = array();
            foreach ($_value as $key => $value) {
                $new_item[ $header[$key] ] =$value;
            }
            $_data[] = $new_item;
        }
        return $_data;
    }

How do I set the selected item in a drop down box

A Simple Solution: It work's for me

<div class="form-group">
    <label for="mcategory">Select Category</label>
    <select class="form-control" id="mcategory" name="mcategory" required>
        <option value="">Please select category</option>
        <?php foreach ($result_cat as $result): ?>
        <option value="<?php echo $result['name'];?>"<?php 
           if($result['name']==$mcategory){
               echo 'selected';
           } ?>><?php echo $result['name']; ?></option>
                                        }
        <?php endforeach; ?>
    </select>
</div>

textarea character limit

... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...

It ought to work.

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For Android SDK, setEndpoint solves the problem, although it's been deprecated.

CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
                context, "identityPoolId", Regions.US_EAST_1);
AmazonS3 s3 = new AmazonS3Client(credentialsProvider);
s3.setEndpoint("s3.us-east-2.amazonaws.com");

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

Argument list too long error for rm, cp, mv commands

Or you can try:

find . -name '*.pdf' -exec rm -f {} \;

form confirm before submit

Simply...

  $('#myForm').submit(function() {
   return confirm("Click OK to continue?");
  });

or

  $('#myForm').submit(function() {
   var status = confirm("Click OK to continue?");
   if(status == false){
   return false;
   }
   else{
   return true; 
   }
  });

Android: remove notification from notification bar

You can try this quick code

public static void cancelNotification(Context ctx, int notifyId) {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
    nMgr.cancel(notifyId);
}

How to add browse file button to Windows Form using C#

var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string fileToOpen = FD.FileName;

    System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);

    //OR

    System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
    //etc
}

How do I set a checkbox in razor view?

you set AllowRating property to true from your controller or model

      @Html.CheckBoxFor(m => m.AllowRating, new { @checked =Model.AllowRating })

Renaming files in a folder to sequential numbers

Here is what worked for me.
I Have used rename command so that if any file contains spaces in name of it then , mv command dont get confused between spaces and actual file.

Here i replaced spaces , ' ' in a file name with '_' for all jpg files
#! /bin/bash
rename 'y/ /_/' *jpg         #replacing spaces with _
let x=0;
for i in *.jpg;do
    let x=(x+1)
    mv $i $x.jpg
done

Python Tkinter clearing a frame

https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html

w.winfo_children()
Returns a list of all w's children, in their stacking order from lowest (bottom) to highest (top).

for widget in frame.winfo_children():
    widget.destroy()

Will destroy all the widget in your frame. No need for a second frame.