Programs & Examples On #Adapter

A design pattern that makes several interfaces compatible through a common interface or class. One of the Gang of Four's structural design patterns.

Remove all items from RecyclerView

For my case adding an empty list did the job.

List<Object> data = new ArrayList<>();
adapter.setData(data);
adapter.notifyDataSetChanged();

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

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 start Activity in adapter?

public class MyAdapter extends Adapter {
     private Context context;      


     public MyAdapter(Context context) {
          this.context = context;         
     }


     public View getView(...){  
         View v;  
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                  Intent intent= new Intent(context, ToActivity.class); 
                   intent.putExtra("your_extra","your_class_value");
                 context.startActivity(intent);
             }
         });
     }
}

Bridged networking not working in Virtualbox under Windows 10

Go to your net card. Go to properties and then "Add service", which? This: VirtualBox NDIS6 Bridged Networking Driver

Reopen Virtual Box

How to set selected item of Spinner by value, not by position?

Based on Merrill's answer here is how to do with a CursorAdapter

CursorAdapter myAdapter = (CursorAdapter) spinner_listino.getAdapter(); //cast
    for(int i = 0; i < myAdapter.getCount(); i++)
    {
        if (myAdapter.getItemId(i) == ordine.getListino() )
        {
            this.spinner_listino.setSelection(i);
            break;
        }
    }

Call Activity method from adapter

You can do it this way:

Declare interface:

public interface MyInterface{
    public void foo();
}

Let your Activity imlement it:

    public class MyActivity extends Activity implements MyInterface{
        public void foo(){
            //do stuff
        }
        
        public onCreate(){
            //your code
            MyAdapter adapter = new MyAdapter(this); //this will work as your 
                                                     //MyInterface listener
        }
    }

Then pass your activity to ListAdater:

public MyAdapter extends BaseAdater{
    private MyInterface listener;

    public MyAdapter(MyInterface listener){
        this.listener = listener;
    }
}

And somewhere in adapter, when you need to call that Activity method:

listener.foo();

How to remove listview all items

You can do this:

listView.setAdapter(null);

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

Several days ago I met the same problem and causes several thousands of crash per day, about 0.1% of users meet this situation. I tried setVisibility(GONE/VISIBLE) and requestLayout(), but crash count only decreases a little.

And I finally solved it. Nothing with setVisibility(GONE/VISIBLE). Nothing with requestLayout().

Finally I found the reason is I used a Handler to call notifyDataSetChanged() after update data, which may lead to a sort of:

  1. Updates data to a model object(I call it a DataSource)
  2. User touches listview(which may call checkForTap()/onTouchEvent() and finally calls layoutChildren() )
  3. Adapter gets data from model object and call notifyDataSetChanged() and update views

And I made another mistake that in getCount(), getItem() and getView(), I directly use fields in DataSource, rather than copy them to the adapter. So finally it crashes when:

  1. Adapter updates data which last response gives
  2. When next response back, DataSource updates data, which causes item count change
  3. User touches listview, which may be a tap or a move or flip
  4. getCount() and getView() is called, and listview finds data is not consistent, and throws exceptions like java.lang.IllegalStateException: The content of the adapter has changed but.... Another common exception is an IndexOutOfBoundException if you use header/footer in ListView.

So solution is easy, I just copy data to adapter from my DataSource when my Handler triggers adapter to get data and calls notifyDataSetChanged(). The crash now never happens again.

Android: How to bind spinner to custom object list?

For simple solutions you can just Overwrite the "toString" in your object

public class User{
    public int ID;
    public String name;

    @Override
    public String toString() {
        return name;
    }
}

and then you can use:

ArrayAdapter<User> dataAdapter = new ArrayAdapter<User>(mContext, android.R.layout.simple_spinner_item, listOfUsers);

This way your spinner will show only the user names.

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

I found a solution to this. It's bloody witchcraft, but it works.

When you install the client, open Control Panel > Network Connections.

You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).

Right Click it, click Enable.

The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.

Clear listview content?

Simple its works me:)

YourArrayList_Object.clear();

How do I use MySQL through XAMPP?

XAMPP Apache + MariaDB + PHP + Perl (X -any OS)

  • After successful installation execute xampp-control.exe in XAMPP folder
  • Start Apache and MySQL enter image description here

  • Open browser and in url type localhost or 127.0.0.1

  • then you are welcomed with dashboard

By default your port is listing with 80.If you want you can change it to your desired port number in httpd.conf file.(If port 80 is already using with other app then you have to change it).

For example you changed port number 80 to 8090 then you can run as 'localhost:8090' or '127.0.0.1:8090'

Download multiple files with a single action

Here is the way I do that. I open multiple ZIP but also other kind of data (I export projet in PDF and at same time many ZIPs with document).

I just copy past part of my code. The call from a button in a list:

$url_pdf = "pdf.php?id=7";
$url_zip1 = "zip.php?id=8";
$url_zip2 = "zip.php?id=9";
$btn_pdf = "<a href=\"javascript:;\" onClick=\"return open_multiple('','".$url_pdf.",".$url_zip1.",".$url_zip2."');\">\n";
$btn_pdf .= "<img src=\"../../../images/icones/pdf.png\" alt=\"Ver\">\n";
$btn_pdf .= "</a>\n"

So a basic call to a JS routine (Vanilla rules!). here is the JS routine:

 function open_multiple(base,url_publication)
 {
     // URL of pages to open are coma separated
     tab_url = url_publication.split(",");
     var nb = tab_url.length;
     // Loop against URL    
     for (var x = 0; x < nb; x++)
     {
        window.open(tab_url[x]);
      }

     // Base is the dest of the caller page as
     // sometimes I need it to refresh
     if (base != "")
      {
        window.location.href  = base;
      }
   }

The trick is to NOT give the direct link of the ZIP file but to send it to the browser. Like this:

  $type_mime = "application/zip, application/x-compressed-zip";
 $the_mime = "Content-type: ".$type_mime;
 $tdoc_size = filesize ($the_zip_path);
 $the_length = "Content-Length: " . $tdoc_size;
 $tdoc_nom = "Pesquisa.zip";
 $the_content_disposition = "Content-Disposition: attachment; filename=\"".$tdoc_nom."\"";

  header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");   // Date in the past
  header($the_mime);
  header($the_length);
  header($the_content_disposition);

  // Clear the cache or some "sh..." will be added
  ob_clean();
  flush();
  readfile($the_zip_path);
  exit();

Python Pandas Replacing Header with Top Row

header = table_df.iloc[0]
table_df.drop([0], axis =0, inplace=True)
table_df.reset_index(drop=True)
table_df.columns = header
table_df

List of phone number country codes

I copy-pasted the whole pdf in a text editor and got something like:

...
31 Netherlands (Kingdom of the)  
32 Belgium  
33 France  
34 Spain  
350 Gibraltar  
351 Portugal  
352 Luxembourg  
353 Ireland  
354 Iceland
...

You could easily parse this to create a xml :)

SQL Server equivalent of MySQL's NOW()?

SYSDATETIME() and SYSUTCDATETIME()

are the DateTime2 equivalents of

GetDate() and GetUTCDate()

which return a DateTime.

DateTime2 is now the preferred method for storing the date and time in SQL Server 2008+. See the following StackOverflow Post.

Moving Panel in Visual Studio Code to right side

VSCode 1.42 (January 2020) introduces:

Panel on the left/right

The panel can now be moved to the left side of the editor with the setting:

"workbench.panel.defaultLocation": "left"

This removes the command View: Toggle Panel Position (workbench.action.togglePanelPosition) in favor of the following new commands:

  • View: Move Panel Left (workbench.action.positionPanelLeft)
  • View: Move Panel Right (workbench.action.positionPanelRight)
  • View: Move Panel To Bottom (workbench.action.positionPanelBottom)

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              
            System.out.print(cell.getStringCellValue());

        }
    }       

For specific type of cell you can try:

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
    cellValue = cell.getStringCellValue();
    break;

case Cell.CELL_TYPE_FORMULA:
    cellValue = cell.getCellFormula();
    break;

case Cell.CELL_TYPE_NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());
    }
    break;

case Cell.CELL_TYPE_BLANK:
    cellValue = "";
    break;

case Cell.CELL_TYPE_BOOLEAN:
    cellValue = Boolean.toString(cell.getBooleanCellValue());
    break;

}

python JSON only get keys in first level

A good way to check whether a python object is an instance of a type is to use isinstance() which is Python's 'built-in' function. For Python 3.6:

dct = {
       "1": "a", 
       "3": "b", 
       "8": {
            "12": "c", 
            "25": "d"
           }
      }

for key in dct.keys():
    if isinstance(dct[key], dict)== False:
       print(key, dct[key])
#shows:
# 1 a
# 3 b

Query comparing dates in SQL

please try with below query

select id,numbers_from,created_date,amount_numbers,SMS_text 
from Test_Table
where 
convert(datetime, convert(varchar(10), created_date, 102))  <= convert(datetime,'2013-04-12')

How to check the exit status using an if statement

You could try to find out if $? is empty by using the said script below:

# Code that may fail here
if [ -z "$?" ]
then
      echo "Code if not failed"
else
      echo "Code if failed"
fi

How do I get my Python program to sleep for 50 milliseconds?

Use time.sleep():

import time
time.sleep(50 / 1000)

See the Python documentation: https://docs.python.org/library/time.html#time.sleep

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

You need to either provide the absolute path to data.csv, or run your script in the same directory as data.csv.

Docker error: invalid reference format: repository name must be lowercase

In my case was the -e before the parameters for mysql docker

docker run --name mysql-standalone -e MYSQL_ROOT_PASSWORD=hello -e MYSQL_DATABASE=hello -e MYSQL_USER=hello -e MYSQL_PASSWORD=hello -d mysql:5.6

Check also if there are missing whitespaces

Received fatal alert: handshake_failure through SSLHandshakeException

I had a similar issue; upgrading to Apache HTTPClient 4.5.3 fixed it.

Get folder name of the file in Python

You could get the full path as a string then split it into a list using your operating system's separator character. Then you get the program name, folder name etc by accessing the elements from the end of the list using negative indices.

Like this:

import os
strPath = os.path.realpath(__file__)
print( f"Full Path    :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( "List of Folders:", nmFolders )
print( f"Program Name :{nmFolders[-1]}" )
print( f"Folder Name  :{nmFolders[-2]}" )
print( f"Folder Parent:{nmFolders[-3]}" )

The output of the above was this:

Full Path    :C:\Users\terry\Documents\apps\environments\dev\app_02\app_02.py
List of Folders: ['C:', 'Users', 'terry', 'Documents', 'apps', 'environments', 'dev', 'app_02', 'app_02.py']
Program Name :app_02.py
Folder Name  :app_02
Folder Parent:dev

What is the role of "Flatten" in Keras?

If you read the Keras documentation entry for Dense, you will see that this call:

Dense(16, input_shape=(5,3))

would result in a Dense network with 3 inputs and 16 outputs which would be applied independently for each of 5 steps. So, if D(x) transforms 3 dimensional vector to 16-d vector, what you'll get as output from your layer would be a sequence of vectors: [D(x[0,:]), D(x[1,:]),..., D(x[4,:])] with shape (5, 16). In order to have the behavior you specify you may first Flatten your input to a 15-d vector and then apply Dense:

model = Sequential()
model.add(Flatten(input_shape=(3, 2)))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(4))
model.compile(loss='mean_squared_error', optimizer='SGD')

EDIT: As some people struggled to understand - here you have an explaining image:

enter image description here

Remove all the children DOM elements in div

In Dojo 1.7 or newer, use domConstruct.empty(String|DomNode):

require(["dojo/dom-construct"], function(domConstruct){
  // Empty node's children byId:
  domConstruct.empty("someId");
});

In older Dojo, use dojo.empty(String|DomNode) (deprecated at Dojo 1.8):

dojo.empty( id or DOM node );

Each of these empty methods safely removes all children of the node.

removing html element styles via javascript

In jQuery, you can use

$(".className").attr("style","");

Sending and receiving data over a network using TcpClient

First of all, TCP does not guarantee that everything that you send will be received with the same read at the other end. It only guarantees that all bytes that you send will arrive and in the correct order.

Therefore, you will need to keep building up a buffer when reading from the stream. You will also have to know how large each message is.

The simplest ever is to use a non-typeable ASCII character to mark the end of the packet and look for it in the received data.

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

For me the following works good. Just add it. You can edit it as per your requirement. This is just a nice trick I use.

text-shadow : 0 0 0 #your-font-color;

How do I count cells that are between two numbers in Excel?

=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")

Is it possible to install iOS 6 SDK on Xcode 5?

The other answers here are correct too, but I find the following steps to be the easiest:

Just download Xcode 4.6.3 from the dev center link that says "Looking for an older version of Xcode?" (currently points here) and mount the dmg.

Then in terminal, copy the SDK files over:

cp -R /Volumes/Xcode/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/

Finally, relaunch Xcode and you're done.

Twitter bootstrap remote modal shows same content every time

The problem is two-fold.

First, once a Modal object is instantiated, it is persistently attached to the element specified by data-target and subsequent calls to show that modal will only call toggle() on it, but will not update the values in the options. So, even though the href attributes are different on your different links, when the modal is toggled, the value for remote is not getting updated. For most options, one can get around this by directly editing the object. For instance:

$('#myModal').data('bs.modal').options.remote = "http://website.com/item/7";

However, that won't work in this case, because...

Second, the Modal plugin is designed to load the remote resource in the constructor of the Modal object, which unfortunately means that even if a change is made to the options.remote, it will never be reloaded.

A simple remedy is to destroy the Modal object before subsequent toggles. One option is to just destroy it after it finishes hiding:

$('body').on('hidden.bs.modal', '.modal', function () {
  $(this).removeData('bs.modal');
});

Note: Adjust the selectors as needed. This is the most general.

Plunker

Or you could try coming up with a more complicated scheme to do something like check whether the link launching the modal is different from the previous one. If it is, destroy; if it isn't, then no need to reload.

SQL Server IN vs. EXISTS Performance

To optimize the EXISTS, be very literal; something just has to be there, but you don't actually need any data returned from the correlated sub-query. You're just evaluating a Boolean condition.

So:

WHERE EXISTS (SELECT TOP 1 1 FROM Base WHERE bx.BoxID = Base.BoxID AND [Rank] = 2)

Because the correlated sub-query is RBAR, the first result hit makes the condition true, and it is processed no further.

Mongoose query where value is not null

You should be able to do this like (as you're using the query api):

Entrant.where("pincode").ne(null)

... which will result in a mongo query resembling:

entrants.find({ pincode: { $ne: null } })

A few links that might help:

Delete cookie by name?

You can try this solution

var d = new Date();
d.setTime(d.getTime());
var expires = "expires="+d.toUTCString();
document.cookie = 'COOKIE_NAME' + "=" + "" + ";domain=domain.com;path=/;" + expires;

How do you set the startup page for debugging in an ASP.NET MVC application?

If you want to start at the "application root" as you describe right click on the top level Default.aspx page and choose set as start page. Hit F5 and you're done.

If you want to start at a different controller action see Mark's answer.

How to get multiple counts with one SQL query?

Building on other posted answers.

Both of these will produce the right values:

select distributor_id,
    count(*) total,
    sum(case when level = 'exec' then 1 else 0 end) ExecCount,
    sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id

SELECT a.distributor_id,
          (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
          (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
          (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
       FROM myTable a ; 

However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.

I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.

As an example, run the following script:

IF OBJECT_ID (N't1', N'U') IS NOT NULL 
drop table t1

create table t1 (f1 int)


    insert into t1 values (1) 
    insert into t1 values (1) 
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)


SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1

SELECT 
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)

Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.

Adding a clustered index is also interesting. E.g.

Create clustered index t1f1 on t1(f1);
Update Statistics t1;

The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.

Checking if an Android application is running in the background

Another solution for this old post (for those that it might help) :


<application android:name=".BaseApplication" ... >

public class BaseApplication extends Application {

    private class Status {
        public boolean isVisible = true;
        public boolean isFocused = true;
    }

    private Map<Activity, Status> activities;

    @Override
    public void onCreate() {
        activities = new HashMap<Activity, Status>();
        super.onCreate();
    }

    private boolean hasVisibleActivity() {
        for (Status status : activities.values())
            if (status.isVisible)
                return true;
        return false;
    }

    private boolean hasFocusedActivity() {
        for (Status status : activities.values())
            if (status.isFocused)
                return true;
        return false;
    }

    public void onActivityCreate(Activity activity, boolean isStarting) {
        if (isStarting && activities.isEmpty())
            onApplicationStart();
        activities.put(activity, new Status());
    }

    public void onActivityStart(Activity activity) {
        if (!hasVisibleActivity() && !hasFocusedActivity())
            onApplicationForeground();
        activities.get(activity).isVisible = true;
    }

    public void onActivityWindowFocusChanged(Activity activity, boolean hasFocus) {
        activities.get(activity).isFocused = hasFocus;
    }

    public void onActivityStop(Activity activity, boolean isFinishing) {
        activities.get(activity).isVisible = false;
        if (!isFinishing && !hasVisibleActivity() && !hasFocusedActivity())
            onApplicationBackground();
    }

    public void onActivityDestroy(Activity activity, boolean isFinishing) {
        activities.remove(activity);
        if(isFinishing && activities.isEmpty())
            onApplicationStop();
    }

    private void onApplicationStart() {Log.i(null, "Start");}
    private void onApplicationBackground() {Log.i(null, "Background");}
    private void onApplicationForeground() {Log.i(null, "Foreground");}
    private void onApplicationStop() {Log.i(null, "Stop");}

}

public class MyActivity extends BaseActivity {...}

public class BaseActivity extends Activity {

    private BaseApplication application;

    @Override
    protected void onCreate(Bundle state) {
        application = (BaseApplication) getApplication();
        application.onActivityCreate(this, state == null);
        super.onCreate(state);
    }

    @Override
    protected void onStart() {
        application.onActivityStart(this);
        super.onStart();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        application.onActivityWindowFocusChanged(this, hasFocus);
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    protected void onStop() {
        application.onActivityStop(this, isFinishing());
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        application.onActivityDestroy(this, isFinishing());
        super.onDestroy();
    }

}

filters on ng-model in an input

If you are using read only input field, you can use ng-value with filter.

for example:

ng-value="price | number:8"

How to parse a string in JavaScript?

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

SQLite Reset Primary Key Field

Try this:

delete from your_table;    
delete from sqlite_sequence where name='your_table';

SQLite Autoincrement

SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.

How to convert unix timestamp to calendar date moment.js

moment(timestamp).format('''any format''')

"Parser Error Message: Could not load type" in Global.asax

Two ways to get this:

  • The configuration manager shows the dll builds as a mix of '64' and 'any cpu' builds. Putting them all to the same build fixes it.

  • When switching between branches, the IIS express path is sometimes not updated. Right click 'IIS Express' in the task bar > Show all applications and verifty that the path is to the correct branch.

How do I set a column value to NULL in SQL Server Management Studio?

If you are using the table interface you can type in NULL (all caps)

otherwise you can run an update statement where you could:

Update table set ColumnName = NULL where [Filter for record here]

Uri not Absolute exception getting while calling Restful Webservice

For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: @Value annotation.

How is an HTTP POST request made in node.js?

To Post Rest/JSON Request
We can simply use request package and save the values we have to send in Json variable.

First install the require package in your console by npm install request --save

var request = require('request');

    var options={
                'key':'28',
                'key1':'value',
                'key2':'value'
                }

    request({
             url:"http://dev.api.ean.com/ean-services/rs/hotel/v3/ping?                      
                 minorRev="+options.key+
                 "&cid="+options.key1+
                 "&apiKey="+options.key2,
             method:"POST",
             json:true},function(error,response,body){
                     console.log(body)
               }
    );

What is __declspec and when do I need to use it?

I know it's been eight years but I wanted to share this piece of code found in MRuby that shows how __declspec() can bee used at the same level as the export keyword.

/** Declare a public MRuby API function. */
#if defined(MRB_BUILD_AS_DLL)
#if defined(MRB_CORE) || defined(MRB_LIB)
# define MRB_API __declspec(dllexport)
#else
# define MRB_API __declspec(dllimport)
#endif
#else
# define MRB_API extern
#endif

Comparing two dataframes and getting the differences

Since pandas >= 1.1.0 we have DataFrame.compare and Series.compare.

Note: the method can only compare identically-labeled DataFrame objects, this means DataFrames with identical row and column labels.

df1 = pd.DataFrame({'A': [1, 2, 3],
                    'B': [4, 5, 6],
                    'C': [7, np.NaN, 9]})

df2 = pd.DataFrame({'A': [1, 99, 3],
                    'B': [4, 5, 81],
                    'C': [7, 8, 9]})

   A  B    C
0  1  4  7.0
1  2  5  NaN
2  3  6  9.0 

    A   B  C
0   1   4  7
1  99   5  8
2   3  81  9
df1.compare(df2)

     A          B          C      
  self other self other self other
1  2.0  99.0  NaN   NaN  NaN   8.0
2  NaN   NaN  6.0  81.0  NaN   NaN

jQuery click / toggle between two functions

If all you're doing is keeping a boolean isEven then you can consider checking if a class isEven is on the element then toggling that class.

Using a shared variable like count is kind of bad practice. Ask yourself what is the scope of that variable, think of if you had 10 items that you'd want to toggle on your page, would you create 10 variables, or an array or variables to store their state? Probably not.

Edit:
jQuery has a switchClass method that, when combined with hasClass can be used to animate between the two width you have defined. This is favourable because you can change these sizes later in your stylesheet or add other parameters, like background-color or margin, to transition.

Parse JSON file using GSON

Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then use Gson.fromJson() method.
For example:

class Response {
    Map<String, App> descriptor;
    // standard getters & setters...
}

class App {
  String name;
  int age;
  String[] messages;
  // standard getters & setters...
}

Then just use:

Gson gson = new Gson();
Response response = gson.fromJson(yourJson, Response.class);

Where yourJson can be a String, any Reader, a JsonReader or a JsonElement.

Finally, if you want to access any particular field, you just have to do:

String name = response.getDescriptor().get("app3").getName();

You can always parse the JSON manually as suggested in other answers, but personally I think this approach is clearer, more maintainable in long term and it fits better with the whole idea of JSON.

How to pass a type as a method parameter in Java

You could pass a Class<T> in.

private void foo(Class<?> cls) {
    if (cls == String.class) { ... }
    else if (cls == int.class) { ... }
}

private void bar() {
    foo(String.class);
}

Update: the OOP way depends on the functional requirement. Best bet would be an interface defining foo() and two concrete implementations implementing foo() and then just call foo() on the implementation you've at hand. Another way may be a Map<Class<?>, Action> which you could call by actions.get(cls). This is easily to be combined with an interface and concrete implementations: actions.get(cls).foo().

Update and left outer join statements

In mysql the SET clause needs to come after the JOIN. Example:

UPDATE e
    LEFT JOIN a ON a.id = e.aid
    SET e.id = 2
    WHERE  
        e.type = 'user' AND
        a.country = 'US';

Concat a string to SELECT * MySql

You cannot do this on multiple fields. You can also look for this.

How to vertical align an inline-block in a line of text?

display: inline-block is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:

Working Example

(it looks like your picture anyway ;))

CSS:

p, div {
  display: inline-block; 
  vertical-align: middle;
}
p, div {
  display: inline !ie7; /* hack for IE7 and below */
}

table {
  background: #000; 
  color: #fff; 
  font-size: 16px; 
  font-weight: bold; margin: 0 10px;
}

td {
  padding: 5px; 
  text-align: center;
}

HTML:

<p>some text</p> 
<div>
  <table summary="">
  <tr><td>A</td></tr>
  <tr><td>B</td></tr>
  <tr><td>C</td></tr>
  <tr><td>D</td></tr>
  </table>
</div> 
<p>continues afterwards</p>

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Sergey is correct, but if you need to get a response from your home-spun dialog(s) for evaluation in the same block of code that invoked it, you should use .showAndWait(), not .show(). Here's my rendition of a couple of the dialog types that are provided in Swing's OptionPane:

public class FXOptionPane {

public enum Response { NO, YES, CANCEL };

private static Response buttonSelected = Response.CANCEL;

private static ImageView icon = new ImageView();

static class Dialog extends Stage {
    public Dialog( String title, Stage owner, Scene scene, String iconFile ) {
        setTitle( title );
        initStyle( StageStyle.UTILITY );
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        setResizable( false );
        setScene( scene );
        icon.setImage( new Image( getClass().getResourceAsStream( iconFile ) ) );
    }
    public void showDialog() {
        sizeToScene();
        centerOnScreen();
        showAndWait();
    }
}

static class Message extends Text {
    public Message( String msg ) {
        super( msg );
        setWrappingWidth( 250 );
    }
}

public static Response showConfirmDialog( Stage owner, String message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Confirm.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button yesButton = new Button( "Yes" );
    yesButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.YES;
        }
    } );
    Button noButton = new Button( "No" );
    noButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.NO;
        }
    } );
    BorderPane bp = new BorderPane();
    HBox buttons = new HBox();
    buttons.setAlignment( Pos.CENTER );
    buttons.setSpacing( 10 );
    buttons.getChildren().addAll( yesButton, noButton );
    bp.setCenter( buttons );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, new Message( message ) );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
    return buttonSelected;
}

public static void showMessageDialog( Stage owner, String message, String title ) {
    showMessageDialog( owner, new Message( message ), title );
}
public static void showMessageDialog( Stage owner, Node message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Info.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button okButton = new Button( "OK" );
    okButton.setAlignment( Pos.CENTER );
    okButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
        }
    } );
    BorderPane bp = new BorderPane();
    bp.setCenter( okButton );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, message );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
}

}

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Preserve Line Breaks From TextArea When Writing To MySQL

This works:

function getBreakText($t) {
    return strtr($t, array('\\r\\n' => '<br>', '\\r' => '<br>', '\\n' => '<br>'));
}

Getting The ASCII Value of a character in a C# string

Here's an alternative since you don't like the cast to int:

foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))
    Console.Write(b.ToString());

In PHP, how can I add an object element to an array?

Do you really need an object? What about:

$myArray[] = array("name" => "my name");

Just use a two-dimensional array.

Output (var_dump):

array(1) {
  [0]=>
  array(1) {
    ["name"]=>
    string(7) "my name"
  }
}

You could access your last entry like this:

echo $myArray[count($myArray) - 1]["name"];

Reference list item by index within Django template?

{{ data.0 }} should work.

Let's say you wrote data.obj django tries data.obj and data.obj(). If they don't work it tries data["obj"]. In your case data[0] can be written as {{ data.0 }}. But I recommend you to pull data[0] in the view and send it as separate variable.

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

The issue has been resolved while installation of the maven settings is provided as External in Eclipse. The navigation settings are Window --> Preferences --> Installations. Select the External as installation Type, provide the Installation home and name and click on Finish. Finally select this as default installations.

What does file:///android_asset/www/index.html mean?

It is actually called file:///android_asset/index.html

file:///android_assets/index.html will give you a build error.

Python3 project remove __pycache__ folders and .pyc files

This is my alias that works both with Python 2 and Python 3 removing all .pyc .pyo files as well __pycache__ directories recursively.

alias pyclean='find . -name "*.py[co]" -o -name __pycache__ -exec rm -rf {} +'

Ignoring new fields on JSON objects using Jackson

@JsonIgnoreProperties(ignoreUnknown = true) worked well for me. I have a java application which runs on tomcat with jdk 1.7.

Compiler error "archive for required library could not be read" - Spring Tool Suite

Delete corrupted files from your local .m2 repository and Ctrl+F5 (Update Maven Project) in Eclipse/STS. It'll download and install these files.

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

How to remove all callbacks from a Handler?

As josh527 said, handler.removeCallbacksAndMessages(null); can work.
But why?
If you have a look at the source code, you can understand it more clearly. There are 3 type of method to remove callbacks/messages from handler(the MessageQueue):

  1. remove by callback (and token)
  2. remove by message.what (and token)
  3. remove by token

Handler.java (leave some overload method)

/**
 * Remove any pending posts of Runnable <var>r</var> with Object
 * <var>token</var> that are in the message queue.  If <var>token</var> is null,
 * all callbacks will be removed.
 */
public final void removeCallbacks(Runnable r, Object token)
{
    mQueue.removeMessages(this, r, token);
}

/**
 * Remove any pending posts of messages with code 'what' and whose obj is
 * 'object' that are in the message queue.  If <var>object</var> is null,
 * all messages will be removed.
 */
public final void removeMessages(int what, Object object) {
    mQueue.removeMessages(this, what, object);
}

/**
 * Remove any pending posts of callbacks and sent messages whose
 * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
 * all callbacks and messages will be removed.
 */
public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}

MessageQueue.java do the real work:

void removeMessages(Handler h, int what, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.what == what
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.what == what
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeMessages(Handler h, Runnable r, Object object) {
    if (h == null || r == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.callback == r
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.callback == r
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeCallbacksAndMessages(Handler h, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h
                && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

What is the maximum number of characters that nvarchar(MAX) will hold?

From char and varchar (Transact-SQL)

varchar [ ( n | max ) ]

Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

Is it possible to set UIView border properties from interface builder?

while this might set the properties, it doesnt actually reflect in IB. So if you're essentially writing code in IB, you might as well then do it in your source code

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

put this in your "head" of your index.html

 <style>
  html body{
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: 0;
  }
  </style>

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

How to embed a video into GitHub README.md?

This is an old post but I was looking for an answer and I found this: https://gifs.com. Just upload the video, then it creates a gif we can add easily in a github markdown. I tried it, the quality of the gif is a good one.

Reading an Excel file in PHP

// Here is the simple code using COM object in PHP
class Excel_ReadWrite{

    private $XLSHandle;
    private $WrkBksHandle;
    private $xlBook;

    function __construct() {
        $this->XLSHandle = new COM("excel.application") or die("ERROR: Unable to instantaniate COM!\r\n"); 
    }

    function __destruct(){
        //if already existing file is opened
        if($this->WrkBksHandle != null)
        {   
            $this->WrkBksHandle->Close(True);
            unset($this->WrkBksHandle);
            $this->XLSHandle->Workbooks->Close();
        }
        //if created new xls file
        if($this->xlBook != null)
        {
            $this->xlBook->Close(True);
            unset($this->xlBook);
        }
        //Quit Excel Application
        $this->XLSHandle->Quit();
        unset($this->XLSHandle);
    }

    public function OpenFile($FilePath)
    {
        $this->WrkBksHandle = $this->XLSHandle->Workbooks->Open($FilePath);
    }

    public function ReadData($RowNo, $ClmNo)
    {
       $Value = $this->XLSHandle->ActiveSheet->Cells($RowNo, $ClmNo)->Value;
       return $Value;
    }  

    public function SaveOpenedFile()
    {
        $this->WrkBksHandle->Save(); 
    }  

    /***********************************************************************************
    * Function Name:- WriteToXlsFile() will write data based on row and column numbers
    * @Param:- $CellData- cell data
    * @Param:- $RowNumber- xlsx file row number
    * @Param:- $ColumnNumber- xlsx file column numbers
   ************************************************************************************/
   function WriteToXlsFile($CellData, $RowNumber, $ColumnNumber)
   {
       try{
               $this->XLSHandle->ActiveSheet->Cells($RowNumber,$ColumnNumber)->Value = $CellData;
           }
       catch(Exception $e){
               throw new Exception("Error:- Unable to write data to xlsx sheet");
           }
   }


   /****************************************************************************************
    * Function Name:- CreateXlsFileWithClmName() will initialize xls file with column Names
    * @Param:- $XlsColumnNames- Array of columns data
    * @Param:- $XlsColumnWidth- Array of columns width
   *******************************************************************************************/
   function CreateXlsFileWithClmNameAndWidth($WorkSheetName = "Raman", $XlsColumnNames = null, $XlsColumnWidth = null)
   {
       //Hide MS Excel application window
       $this->XLSHandle->Visible = 0;
       //Create new document
       $this->xlBook = $this->XLSHandle->Workbooks->Add();

       //Create Sheet 1
       $this->xlBook->Worksheets(1)->Name = $WorkSheetName;
       $this->xlBook->Worksheets(1)->Select;

       if($XlsColumnWidth != null)
       {
           //$XlsColumnWidth = array("A1"=>15,"B1"=>20);
           foreach($XlsColumnWidth as $Clm=>$Width)
           {
               //Set Columns Width
               $this->XLSHandle->ActiveSheet->Range($Clm.":".$Clm)->ColumnWidth = $Width;
           }    
       }
       if($XlsColumnNames != null)
       {
           //$XlsColumnNames = array("FirstColumnName"=>1, "SecondColumnName"=>2);
           foreach($XlsColumnNames as $ClmName=>$ClmNumber)
           {
               // Cells(Row,Column)
               $this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Value = $ClmName;
               $this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Font->Bold = True;
               $this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Interior->ColorIndex = "15";
           }
       }
   }
   //56 is for xls 8
    public function SaveCreatedFile($FileName, $FileFormat = 56)
    {
        $this->xlBook->SaveAs($FileName, $FileFormat);
    }

    public function MakeFileVisible()
    {
       //Hide MS Excel application window`enter code here`
       $this->XLSHandle->Visible = 1;
    }
}//end of EXCEL class

How to add a custom button to the toolbar that calls a JavaScript function?

You'll need to create a plug-in. The documentation for CKEditor is very poor for this, especially since I believe it has changed significantly since FCKEditor. I would suggest copying an existing plug-in and studying it. A quick google for "CKEditor plugin" also found this blog post.

Check whether a value is a number in JavaScript or jQuery

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

jQuery select change show/hide div event

Try this:

 $(function () {
     $('#row_dim').hide(); // this line you can avoid by adding #row_dim{display:none;} in your CSS
     $('#type').change(function () {
         $('#row_dim').hide();
         if (this.options[this.selectedIndex].value == 'parcel') {
             $('#row_dim').show();
         }
     });
 });

Demo here

The import javax.persistence cannot be resolved

If anyone is using Maven, you'll need to add the dependency in the POM.XML file. The latest version as of this post is below:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Target parameters:

float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);

Your original file:

var image = new Bitmap(file);

Target sizing (scale factor):

float scale = Math.Min(width / image.Width, height / image.Height);

The resize including brushing canvas first:

var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);

// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;

var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);

graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);

And don't forget to do a bmp.Save(filename) to save the resulting file.

Websocket connections with Postman

I ran into the exact same problem. Had to make a Web Socket call. I was able to accomplish this using Advanced Rest Client. I'm using ARC version : 12.1.3

enter image description here

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

fatal error LNK1104: cannot open file 'kernel32.lib'

Add lib path of WindowsSdks in project->properties->Configuration Properties->VC++ Directories -> Library directories.

I added following path and error goes::

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib;

My system is Win-7, 64bit, VS 2013, .net framework 4.5

Setting table column width

_x000D_
_x000D_
    table { table-layout: fixed; }_x000D_
    .subject { width: 70%; }
_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th>From</th>_x000D_
        <th class="subject">Subject</th>_x000D_
        <th>Date</th>_x000D_
      </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

Vue.js : How to set a unique ID for each component instance?

If your uid is not used by other compoment, I have an idea.

uid: Math.random()

Simple and enough.

html vertical align the text inside input type button

I found that using a fixed width with padding seems to work (in ff at least)

.Btn
 {
   width:75px;
   padding:10px;
 }

Try it at:-

http://jsfiddle.net/stevenally/z32kg/

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

I too used the chosen solution (downgrading pip) to work around this issue until I ran into another seemingly unrelated issue caused by the same underlying problem. Python's version of OpenSSL was out of date. Check your OpenSSL version:

python -c 'import ssl; print(ssl.OPENSSL_VERSION)'

If the version is 0.9.7, that should verify that OpenSSL needs to be updated. If you know how to do that directly, great (but please let me know in a comment). If not, you can follow the advice in this answer, and reinstall python from the 64 bit/32 bit installer instead of the 32 bit only installer from python.org (I'm using python 3.4.2). I now have OpenSSL version 0.9.8, and none of these issues.

How to open Atom editor from command line in OS X?

I am on mingw bash, so I have created ~.profile file with following: alias atom='~/AppData/Local/atom/bin/atom'

How to validate Google reCAPTCHA v3 on server side?

this is solution

index.html

<html>
  <head>
    <title>Google recapcha demo - Codeforgeek</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action="form.php" method="post">
      <input type="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
      <div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>
    </form>
  </body>
</html>

verify.php

<?php
    $email; $comment; $captcha;

    if(isset($_POST['email']))
        $email=$_POST['email'];
    if(isset($_POST['comment']))
        $comment=$_POST['comment'];
    if(isset($_POST['g-recaptcha-response']))
        $captcha=$_POST['g-recaptcha-response'];

    if(!$captcha){
        echo '<h2>Please check the the captcha form.</h2>';
        exit;
    }

    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
    if($response['success'] == false)
    {
        echo '<h2>You are spammer ! Get the @$%K out</h2>';
    }
    else
    {
        echo '<h2>Thanks for posting comment.</h2>';
    }
?>

http://codeforgeek.com/2014/12/google-recaptcha-tutorial/

What is an ORM, how does it work, and how should I use one?

Introduction

Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase "an ORM".

An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same language you're using.

For example, here is a completely imaginary case with a pseudo language:

You have a book class, you want to retrieve all the books of which the author is "Linus". Manually, you would do something like that:

book_list = new List();
sql = "SELECT book FROM library WHERE author = 'Linus'";
data = query(sql); // I over simplify ...
while (row = data.next())
{
     book = new Book();
     book.setAuthor(row.get('author');
     book_list.add(book);
}

With an ORM library, it would look like this:

book_list = BookTable.query(author="Linus");

The mechanical part is taken care of automatically via the ORM library.

Pros and Cons

Using ORM saves a lot of time because:

  • DRY: You write your data model in only one place, and it's easier to update, maintain, and reuse the code.
  • A lot of stuff is done automatically, from database handling to I18N.
  • It forces you to write MVC code, which, in the end, makes your code a little cleaner.
  • You don't have to write poorly-formed SQL (most Web programmers really suck at it, because SQL is treated like a "sub" language, when in reality it's a very powerful and complex one).
  • Sanitizing; using prepared statements or transactions are as easy as calling a method.

Using an ORM library is more flexible because:

  • It fits in your natural way of coding (it's your language!).
  • It abstracts the DB system, so you can change it whenever you want.
  • The model is weakly bound to the rest of the application, so you can change it or use it anywhere else.
  • It lets you use OOP goodness like data inheritance without a headache.

But ORM can be a pain:

  • You have to learn it, and ORM libraries are not lightweight tools;
  • You have to set it up. Same problem.
  • Performance is OK for usual queries, but a SQL master will always do better with his own SQL for big projects.
  • It abstracts the DB. While it's OK if you know what's happening behind the scene, it's a trap for new programmers that can write very greedy statements, like a heavy hit in a for loop.

How to learn about ORM?

Well, use one. Whichever ORM library you choose, they all use the same principles. There are a lot of ORM libraries around here:

If you want to try an ORM library in Web programming, you'd be better off using an entire framework stack like:

  • Symfony (PHP, using Propel or Doctrine).
  • Django (Python, using a internal ORM).

Do not try to write your own ORM, unless you are trying to learn something. This is a gigantic piece of work, and the old ones took a lot of time and work before they became reliable.

How to view the assembly behind the code using Visual C++?

Additional note: there is big difference between Debug assembler output and Release one. The first one is good to learn how compiler produces assembler code from C++. The second one is good to learn how compiler optimizes various C++ constructs. In this case some C++-to-asm transformations are not obvious.

Add Variables to Tuple

In Python 3, you can use * to create a new tuple of elements from the original tuple along with the new element.

>>> tuple1 = ("foo", "bar")
>>> tuple2 = (*tuple1, "baz")
>>> tuple2
('foo', 'bar', 'baz')

The byte code is almost the same as tuple1 + ("baz",)

Python 3.7.5 (default, Oct 22 2019, 10:35:10) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     tuple1 = ("foo", "bar")
...     tuple2 = (*tuple1, "baz")
...     return tuple2
... 
>>> def g():
...     tuple1 = ("foo", "bar")
...     tuple2 = tuple1 + ("baz",)
...     return tuple2
... 
>>> from dis import dis
>>> dis(f)
  2           0 LOAD_CONST               1 (('foo', 'bar'))
              2 STORE_FAST               0 (tuple1)

  3           4 LOAD_FAST                0 (tuple1)
              6 LOAD_CONST               3 (('baz',))
              8 BUILD_TUPLE_UNPACK       2
             10 STORE_FAST               1 (tuple2)

  4          12 LOAD_FAST                1 (tuple2)
             14 RETURN_VALUE
>>> dis(g)
  2           0 LOAD_CONST               1 (('foo', 'bar'))
              2 STORE_FAST               0 (tuple1)

  3           4 LOAD_FAST                0 (tuple1)
              6 LOAD_CONST               2 (('baz',))
              8 BINARY_ADD
             10 STORE_FAST               1 (tuple2)

  4          12 LOAD_FAST                1 (tuple2)
             14 RETURN_VALUE

The only difference is BUILD_TUPLE_UNPACK vs BINARY_ADD. The exact performance depends on the Python interpreter implementation, but it's natural to implement BUILD_TUPLE_UNPACK faster than BINARY_ADD because BINARY_ADD is a polymorphic operator, requiring additional type calculation and implicit conversion.

Using OR in SQLAlchemy

From the tutorial:

from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))

AngularJS/javascript converting a date String to date object

This is what I did on the controller

var collectionDate = '2002-04-26T09:00:00';
var date = new Date(collectionDate);
//then pushed all my data into an array $scope.rows which I then used in the directive

I ended up formatting the date to my desired pattern on the directive as follows.

var data = new google.visualization.DataTable();
                    data.addColumn('date', 'Dates');
                    data.addColumn('number', 'Upper Normal');
                    data.addColumn('number', 'Result');
                    data.addColumn('number', 'Lower Normal');
                    data.addRows(scope.rows);
                    var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"});
                    formatDate.format(data, 0);
//set options for the line chart
var options = {'hAxis': format: 'dd/MM/yyyy'}

//Instantiate and draw the chart passing in options
var chart = new google.visualization.LineChart($elm[0]);
                    chart.draw(data, options);

This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.

How to get a product's image in Magento?

get product images in magento using product id

    $product_id = $_POST['product_id'];
    $storeId    = Mage::app()->getStore()->getId();
    $loadpro    = Mage::getModel('catalog/product')->load($product_id);

    $mediaApi      =  Mage::getModel("catalog/product_attribute_media_api");
    $mediaApiItems = $mediaApi->items($loadpro->getId());
    foreach ($mediaApiItems as $item) {
            //for getting existing Images
            echo $item['file'];
            }

two divs the same line, one dynamic width, one fixed

I've had success with using white-space: nowrap; on the outer container, display: inline-block; on the inner containers, and then (in my case since I wanted the second one to word-wrap) white-space: normal; on the inner ones.

How can I undo git reset --hard HEAD~1?

It is possible to recover it if Git hasn't garbage collected yet.

Get an overview of dangling commits with fsck:

$ git fsck --lost-found
dangling commit b72e67a9bb3f1fc1b64528bcce031af4f0d6fcbf

Recover the dangling commit with rebase:

$ git rebase b72e67a9bb3f1fc1b64528bcce031af4f0d6fcbf

Android: upgrading DB version and adding new table

You can use SQLiteOpenHelper's onUpgrade method. In the onUpgrade method, you get the oldVersion as one of the parameters.

In the onUpgrade use a switch and in each of the cases use the version number to keep track of the current version of database.

It's best that you loop over from oldVersion to newVersion, incrementing version by 1 at a time and then upgrade the database step by step. This is very helpful when someone with database version 1 upgrades the app after a long time, to a version using database version 7 and the app starts crashing because of certain incompatible changes.

Then the updates in the database will be done step-wise, covering all possible cases, i.e. incorporating the changes in the database done for each new version and thereby preventing your application from crashing.

For example:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
    case 1:
        String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " + "name_of_column_to_be_added" + " INTEGER";
        db.execSQL(sql);
        break;

    case 2:
        String sql = "SOME_QUERY";
        db.execSQL(sql);
        break;
    }

}

Notepad++ Setting for Disabling Auto-open Previous Files

Go to: Settings > Preferences > Backup > and Uncheck Remember current session for next launch

In older versions (6.5-), this option is located on Settings > Preferences > MISC.

Multiple argument IF statement - T-SQL

Your code is valid (with one exception). It is required to have code between BEGIN and END.

Replace

--do some work

with

print ''

I think maybe you saw "END and not "AND"

mysql count group by having

Maybe

SELECT count(*) FROM (
    SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total

although that would not be the sum of all the movies, just how many have 4 genre's.

So maybe you want

SELECT sum(
    SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

I had the same warning using the raster package.

> my_mask[my_mask[] != 1] <- NA
Error: cannot allocate vector of size 5.4 Gb

The solution is really simple and consist in increasing the storage capacity of R, here the code line:

##To know the current storage capacity
> memory.limit()
[1] 8103
## To increase the storage capacity
> memory.limit(size=56000)
[1] 56000    
## I did this to increase my storage capacity to 7GB

Hopefully, this will help you to solve the problem Cheers

Set value to an entire column of a pandas dataframe

You can do :

df['industry'] = 'yyy'

Use of alloc init instead of new

One Short Answere is:

  1. Both are same. But
  2. 'new' only works with the basic 'init' initializer, and will not work with other initializers (eg initWithString:).

What is the difference between syntax and semantics in programming languages?

The syntax of a programming language is the form of its expressions, statements, and program units. Its semantics is the meaning of those expressions, statements, and program units. For example, the syntax of a Java while statement is

while (boolean_expr) statement

The semantics of this statement form is that when the current value of the Boolean expression is true, the embedded statement is executed. Then control implicitly returns to the Boolean expression to repeat the process. If the Boolean expression is false, control transfers to the statement following the while construct.

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

I had the same issue. When compared the java version mentioned in the pom.xml file is different and the JAVA_HOME env variable was pointing to different version of jdk.

Have the JAVA_HOME and pom.xml updated to the same jdk installation path

How to check if a std::string is set or not?

Use empty():

std::string s;

if (s.empty())
    // nothing in s

In c++ what does a tilde "~" before a function name signify?

That would be the destructor(freeing up any dynamic memory)

Java generating Strings with placeholders

Justas answer is outdated so I'm posting up to date answer with apache text commons.

StringSubstitutor from Apache Commons Text may be used for string formatting with named placeholders: https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods. Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.

Example:

 // Build map
 Map<String, String> valuesMap = new HashMap<>();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumped over the ${target}.";

 // Build StringSubstitutor
 StringSubstitutor sub = new StringSubstitutor(valuesMap);

 // Replace
 String resolvedString = sub.replace(templateString);

Disabling same-origin policy in Safari

Unfortunately, there is no equivalent for Safari and the argument --disable-web-security doesn't work with Safari.

If you have access to the server side application, you can modify the https response headers to allow access. Mainly the Access-Control-Allow-Origin header. Modifying it will allow Safari to access the resource. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Origin for more information on the response headers that will help.

Laravel 4: Redirect to a given url

This worked for me in Laravel 5.8

return \Redirect::to('https://bla.com/?yken=KuQxIVTNRctA69VAL6lYMRo0');

Or instead of / you can use

use Redirect;

How to create an alert message in jsp page after submit process is complete

So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.

In test.jsp

Create a javascript

<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
} 
</script> 

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to

Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.

To do that i would highly recommendation to use session!

So what you want to do is in your servlet:

session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);

than in the test.jsp

<%
session.setMaxInactiveInterval(2);
%>

 <script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
    if (Msg != "null") {
 function alertName(){
 alert("Form has been submitted");
 } 
 }
 </script> 

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

So everytime you submit that form a session will be pass on! If session is not null the function will run!

Set iframe content height to auto resize dynamically

In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:

<body onload="parent.alertsize(document.body.scrollHeight);">

In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:

<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>

What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.

To that JavaScript function it sends how many pixels its (iframe) height is.

The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.

That's it, nothing else is needed.


But if you like to know some more small tricks keep on reading...

DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
}
</script>

to that script just add:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>

How you use the above script is easy:

<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>

For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)

Complete holding page code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>

<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>

Complete iframe code: (this iframe named "theiframe.htm")

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight);
}
</script>
</head>

<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END

</body>
</html>

Demo

How to show DatePickerDialog on Button click?

Following code works..

datePickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(0);
        }
    });

@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
    return new DatePickerDialog(this, datePickerListener, year, month, day);
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear,
                          int selectedMonth, int selectedDay) {
        day = selectedDay;
        month = selectedMonth;
        year = selectedYear;
        datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
                + selectedYear);
    }
};

Bootstrap NavBar with left, center or right aligned items

this is an update for BS5 and a suggested edit for @Zim's answer. Unfortunately I can't submit the edit as the edit queue is full. It would be good if a user with high reputation could submit the edit once the queue allows new edits.

2021 Update

Bootstrap 5.0.0 beta-1

With the addition of RTL-support, ml-auto and mr-auto become ms-auto and me-auto (left/right to start/end).

Bootstrap 5 also requires the navbar to be contained inside a container div.

This code produces the equivalent of the first Bootstrap 4 example:

Left, center(brand) and right links:

enter image description here

<nav class="navbar navbar-expand-md navbar-dark bg-dark">
  <div class="container-fluid">
    <div class="navbar-collapse collapse w-100 order-1 order-md-0 dual-collapse2">
      <ul class="navbar-nav me-auto">
        <li class="nav-item active">
          <a class="nav-link" href="#">Left</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="//codeply.com">Codeply</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
      </ul>
    </div>
    <div class="mx-auto order-0">
      <a class="navbar-brand mx-auto" href="#">Navbar 2</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2">
        <span class="navbar-toggler-icon"></span>
      </button>
    </div>
    <div class="navbar-collapse collapse w-100 order-3 dual-collapse2">
      <ul class="navbar-nav ms-auto">
        <li class="nav-item">
          <a class="nav-link" href="#">Right</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
      </ul>
    </div>
  </div>
</nav>

What does ^M character mean in Vim?

In FreeBSD, you can clear the ^M manually by typing the following:

:%s/ Ctrl+V, then Ctrl+M, then Ctrl+M again.

"Object doesn't support this property or method" error in IE11

This unfortunately breaks other things. Here is the fix I found on another site that seemed to work for me:

I'd say leave the X-UA-Compatible as "IE=8" and add the following code to the bottom of your master page:

<script language="javascript">
    /* IE11 Fix for SP2010 */
    if (typeof(UserAgentInfo) != 'undefined' && !window.addEventListener) 
    {
        UserAgentInfo.strBrowser=1; 
    } 
</script>

This fixes a bug in core.js which incorrectly calculates that sets UserAgentInfo.strBrowse=3 for IE11 and thus supporting addEventListener. I'm not entirely sure on the details other than that but the combination of keeping IE=8 and using this script is working for me. Fingers crossed until I find the next IE11/SharePoint "bug"!

CMD command to check connected USB devices

You can use the wmic command:

wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

If you aren't doing some kind of numeric comparison of the length property, it's better not to use it in the if statement, just do:

if(theHref){
   // do stuff
}else{
  // do other stuff
}

An empty (or undefined, as it is in this case) string will evaluate to false (just like a length of zero would.)

Draw horizontal rule in React Native

Creating a reusable Line component worked for me:

import React from 'react';
import { View } from 'react-native';

export default function Line() {
    return (
        <View style={{
            height: 1,
            backgroundColor: 'rgba(255, 255, 255 ,0.3)',
            alignSelf: 'stretch'
        }} />
    )
}

Now, Import and use Line anywhere:

<Line />

What is the difference between JOIN and UNION?

The UNION operator is just for combining two or more SELECT statements.

While JOIN is for selecting rows from each table, either by the inner, outer, left or right method.

Refer to here and here . There is a better explanation with examples.

Java Does Not Equal (!=) Not Working?

if (!"success".equals(statusCheck))

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

How to install PyQt5 on Windows?

If you are facing problem with pip3 install pyqt5 then try pip3 install pyqt5==5.12.0
This solved the problem for me

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

In HTML5, should the main navigation be inside or outside the <header> element?

It's a little unclear whether you're asking for opinions, eg. "it's common to do xxx" or an actual rule, so I'm going to lean in the direction of rules.

The examples you cite seem based upon the examples in the spec for the nav element. Remember that the spec keeps getting tweaked and the rules are sometimes convoluted, so I'd venture many people might tend to just do what's given rather than interpret. You're showing two separate examples with different behavior, so there's only so much you can read into it. Do either of those sites also have the opposing sub/nav situation, and if so how do they handle it?

Most importantly, though, there's nothing in the spec saying either is the way to do it. One of the goals with HTML5 was to be very clear[this for comparison] about semantics, requirements, etc. so the omission is worth noting. As far as I can see, the examples are independent of each other and equally valid within their own context of layout requirements, etc.

Having the nav's source position be conditional is kind of silly(another red flag). Just pick a method and go with it.

Defining arrays in Google Scripts

This may be of help to a few who are struggling like I was:

var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];

Python integer division yields float

Hope it might help someone instantly.

Behavior of Division Operator in Python 2.7 and Python 3

In Python 2.7: By default, division operator will return integer output.

to get the result in double multiple 1.0 to "dividend or divisor"

100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857

In Python 3

// => used for integer output
/ => used for double output

100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0    # floating-point result if divsor or dividend real

How to abort a Task like aborting a Thread (Thread.Abort method)?

You can "abort" a task by running it on a thread you control and aborting that thread. This causes the task to complete in a faulted state with a ThreadAbortException. You can control thread creation with a custom task scheduler, as described in this answer. Note that the caveat about aborting a thread applies.

(If you don't ensure the task is created on its own thread, aborting it would abort either a thread-pool thread or the thread initiating the task, neither of which you typically want to do.)

Adding values to a C# array

You can do this way -

int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.

List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
    termsList.Add(value);
}

// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();

Edit: a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).

Finding square root without using sqrt function?

After looking at the previous responses, I hope this will help resolve any ambiguities. In case the similarities in the previous solutions and my solution are illusive, or this method of solving for roots is unclear, I've also made a graph which can be found here.

This is a working root function capable of solving for any nth-root

(default is square root for the sake of this question)

#include <cmath> 
// for "pow" function

double sqrt(double A, double root = 2) {
    const double e = 2.71828182846;
    return pow(e,(pow(10.0,9.0)/root)*(1.0-(pow(A,-pow(10.0,-9.0)))));
}

Explanation:

click here for graph

This works via Taylor series, logarithmic properties, and a bit of algebra.

Take, for example:

log A = N
   x

*Note: for square-root, N = 2; for any other root you only need to change the one variable, N.

1) Change the base, convert the base 'x' log function to natural log,

log A   =>   ln(A)/ln(x) = N
   x

2) Rearrange to isolate ln(x), and eventually just 'x',

ln(A)/N = ln(x)

3) Set both sides as exponents of 'e',

e^(ln(A)/N) = e^(ln(x))  >~{ e^ln(x) == x }~>  e^(ln(A)/N) = x

4) Taylor series represents "ln" as an infinite series,

ln(x) = (k=1)Sigma: (1/k)(-1^(k+1))(k-1)^n

           <~~~ expanded ~~~>

[(x-1)] - [(1/2)(x-1)^2] + [(1/3)(x-1)^3] - [(1/4)(x-1)^4] + . . .

*Note: Continue the series for increased accuracy. For brevity, 10^9 is used in my function which expresses the series convergence for the natural log with about 7 digits, or the 10-millionths place, for precision,

ln(x) = 10^9(1-x^(-10^(-9)))

5) Now, just plug in this equation for natural log into the simplified equation obtained in step 3.

e^[((10^9)/N)(1-A^(-10^-9)] = nth-root of (A)

6) This implementation might seem like overkill; however, its purpose is to demonstrate how you can solve for roots without having to guess and check. Also, it would enable you to replace the pow function from the cmath library with your own pow function:

double power(double base, double exponent) {
    if (exponent == 0) return 1;
    int wholeInt = (int)exponent;
    double decimal = exponent - (double)wholeInt;
    if (decimal) {
        int powerInv = 1/decimal;
        if (!wholeInt) return root(base,powerInv);
        else return power(root(base,powerInv),wholeInt,true);
    }
    return power(base, exponent, true);
}

double power(double base, int exponent, bool flag) {
    if (exponent < 0) return 1/power(base,-exponent,true);
    if (exponent > 0) return base * power(base,exponent-1,true);
    else return 1;
}

int root(int A, int root) {
    return power(E,(1000000000000/root)*(1-(power(A,-0.000000000001))));
}

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Every SQL batch has to fit in the Batch Size Limit: 65,536 * Network Packet Size.

Other than that, your query is limited by runtime conditions. It will usually run out of stack size because x IN (a,b,c) is nothing but x=a OR x=b OR x=c which creates an expression tree similar to x=a OR (x=b OR (x=c)), so it gets very deep with a large number of OR. SQL 7 would hit a SO at about 10k values in the IN, but nowdays stacks are much deeper (because of x64), so it can go pretty deep.

Update

You already found Erland's article on the topic of passing lists/arrays to SQL Server. With SQL 2008 you also have Table Valued Parameters which allow you to pass an entire DataTable as a single table type parameter and join on it.

XML and XPath is another viable solution:

SELECT ...
FROM Table
JOIN (
   SELECT x.value(N'.',N'uniqueidentifier') as guid
   FROM @values.nodes(N'/guids/guid') t(x)) as guids
 ON Table.guid = guids.guid;

How do I remove a single breakpoint with GDB?

You can delete all breakpoints using

del <start_breakpoint_num> - <end_breakpoint_num>

To view the start_breakpoint_num and end_breakpoint_num use:

info break

Java TreeMap Comparator

you can swipe the key and the value. For example

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());

Angularjs error Unknown provider

bmleite has the correct answer about including the module.

If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.

Remember:

angular.module('ModuleName', [])   // creates a module.

angular.module('ModuleName')       // gets you a pre-existing module.

So if you are extending a existing module, remember not to overwrite when trying to fetch it.

How to import a csv file using python with headers intact, where first column is a non-numerical

You can use pandas library and reference the rows and columns like this:

import pandas as pd

input = pd.read_csv("path_to_file");

#for accessing ith row:
input.iloc[i]

#for accessing column named X
input.X

#for accessing ith row and column named X
input.iloc[i].X

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

Generic Interface

Here's one suggestion:

public interface Service<T,U> {
    T executeService(U... args);
}

public class MyService implements Service<String, Integer> {
    @Override
    public String executeService(Integer... args) {
        // do stuff
        return null;
    }
}

Because of type erasure any class will only be able to implement one of these. This eliminates the redundant method at least.

It's not an unreasonable interface that you're proposing but I'm not 100% sure of what value it adds either. You might just want to use the standard Callable interface. It doesn't support arguments but that part of the interface has the least value (imho).

ruby LoadError: cannot load such file

The directory where st.rb lives is most likely not on your load path.

Assuming that st.rb is located in a directory called lib relative to where you invoke irb, you can add that lib directory to the list of directories that ruby uses to load classes or modules with this:

$: << 'lib'

For example, in order to call the module called 'foobar' (foobar.rb) that lives in the lib directory, I would need to first add the lib directory to the list of load path. Here, I am just appending the lib directory to my load path:

irb(main):001:0> require 'foobar'
LoadError: no such file to load -- foobar
        from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
        from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
        from (irb):1
irb(main):002:0> $:
=> ["/usr/lib/ruby/gems/1.8/gems/spoon-0.0.1/lib", "/usr/lib/ruby/gems/1.8/gems/interactive_editor-0.0.10/lib", "/usr/lib/ruby/site_ruby/1.8", "/usr/lib/ruby/site_ruby/1.8/i386-cygwin", "/usr/lib/ruby/site_ruby", "/usr/lib/ruby/vendor_ruby/1.8", "/usr/lib/ruby/vendor_ruby/1.8/i386-cygwin", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.8", "/usr/lib/ruby/1.8/i386-cygwin", "."]
irb(main):004:0> $: << 'lib'
=> ["/usr/lib/ruby/gems/1.8/gems/spoon-0.0.1/lib", "/usr/lib/ruby/gems/1.8/gems/interactive_editor-0.0.10/lib", "/usr/lib/ruby/site_ruby/1.8", "/usr/lib/ruby/site_ruby/1.8/i386-cygwin", "/usr/lib/ruby/site_ruby", "/usr/lib/ruby/vendor_ruby/1.8", "/usr/lib/ruby/vendor_ruby/1.8/i386-cygwin", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.8", "/usr/lib/ruby/1.8/i386-cygwin", ".", "lib"]
irb(main):005:0> require 'foobar'
=> true

EDIT Sorry, I completely missed the fact that you are using ruby 1.9.x. All accounts report that your current working directory has been removed from LOAD_PATH for security reasons, so you will have to do something like in irb:

$: << "."

How to kill a nodejs process in Linux?

Run ps aux | grep nodejs, find the PID of the process you're looking for, then run kill starting with SIGTERM (kill -15 25239). If that doesn't work then use SIGKILL instead, replacing -15 with -9.

Vertically align text within input field of fixed-height without display: table or padding?

This is how I do it.

<ul>
   <li>First group of text here.</li>
   <li><input type="" value="" /></li>
</ul>

then inside your CSS file,

ul li {
  display: block;
  float: left;
}

That should work for you.

Trying to check if username already exists in MySQL database using PHP

Try this:

$query = mysql_query("SELECT username FROM Users WHERE username='$username' ")

Don't add $con to mysql_query() function.

Disclaimer: using the username variable in the string passed to mysql_query, as shown above, is a trivial SQL injection attack vector in so far the username depends on parameters of the Web request (query string, headers, request body, etc), or otherwise parameters a malicious entity may control.

How can I remove a child node in HTML using JavaScript?

You have to remove any event handlers you've set on the node before you remove it, to avoid memory leaks in IE

Use <Image> with a local file

If loading images dynamically one can create a .js file like following and do require in it.

export const data = [
  {
    id: "1",
    text: "blablabla1",
    imageLink: require('../assets/first-image.png')
  },
  {
    id: "2",
    text: "blablabla2",
    imageLink: require('../assets/second-image.png')
  }
]

In your component .js file

import {data} from './js-u-created-above';
...

function UsageExample({item}) {
   <View>
     <Image style={...} source={item.imageLink} /> 
   </View>
}

function ComponentName() {
   const elements = data.map(item => <UsageExample key={item.id} item={item}/> );
   return (...);
}

Convert DataSet to List

Try this....modify the code as per your needs.

      List<Employee> target = dt.AsEnumerable()
      .Select(row => new Employee
      {
        Name = row.Field<string?>(0).GetValueOrDefault(),
        Age= row.Field<int>(1)
      }).ToList();

How do I compare two variables containing strings in JavaScript?

You can use javascript dedicate string compare method string1.localeCompare(string2). it will five you -1 if the string not equals, 0 for strings equal and 1 if string1 is sorted after string2.

<script>
    var to_check=$(this).val();
    var cur_string=$("#0").text();
    var to_chk = "that";
    var cur_str= "that";
    if(to_chk.localeCompare(cur_str) == 0){
        alert("both are equal");
        $("#0").attr("class","correct");    
    } else {
        alert("both are not equal");
        $("#0").attr("class","incorrect");
    }
</script>

How to get hostname from IP (Linux)?

Another simple way I found for using in LAN is

ssh [username@ip] uname -n

If you need to login command line will be

sshpass -p "[password]" ssh [username@ip] uname -n

Why does Java have an "unreachable statement" compiler error?

While I think this compiler error is a good thing, there is a way you can work around it. Use a condition you know will be true:

public void myMethod(){

    someCodeHere();

    if(1 < 2) return; // compiler isn't smart enough to complain about this

    moreCodeHere();

}

The compiler is not smart enough to complain about that.

How to execute only one test spec with angular-cli

Adding to this for people like me who were searching for a way to run a single spec in Angular and found this SO.

According to the latest Angular docs (v9.0.6 at time of writing), the ng test command has an --include option where you can specify a directory of *.spec.(ts|tsx) files or just a single .spec.(ts|tsx) file itself.

https://angular.io/cli/test

More Pythonic Way to Run a Process X Times

If you are after the side effects that happen within the loop, I'd personally go for the range() approach.

If you care about the result of whatever functions you call within the loop, I'd go for a list comprehension or map approach. Something like this:

def f(n):
    return n * n

results = [f(i) for i in range(50)]
# or using map:
results = map(f, range(50))

How can I find which tables reference a given table in Oracle SQL Developer?

You may be able to query this from the ALL_CONSTRAINTS view:

SELECT table_name
FROM ALL_CONSTRAINTS
WHERE constraint_type = 'R' -- "Referential integrity"
  AND r_constraint_name IN
    ( SELECT constraint_name
      FROM ALL_CONSTRAINTS
      WHERE table_name = 'EMP'
        AND constraint_type IN ('U', 'P') -- "Unique" or "Primary key"
    );

In Angular, how to redirect with $location.path as $http.post success callback

Here is the changeLocation example from this article http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#apply-digest-and-phase

//be sure to inject $scope and $location
var changeLocation = function(url, forceReload) {
  $scope = $scope || angular.element(document).scope();
  if(forceReload || $scope.$$phase) {
    window.location = url;
  }
  else {
    //only use this if you want to replace the history stack
    //$location.path(url).replace();

    //this this if you want to change the URL and add it to the history stack
    $location.path(url);
    $scope.$apply();
  }
};

Upload Image using POST form data in Python-requests

Use this snippet

import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
  name_img= os.path.basename(path_img)
  files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
  with requests.Session() as s:
    r = s.post(url,files=files)
    print(r.status_code)

PHP function to get the subdomain of a URL

Uses the parse_url function.

$url = 'http://en.example.com';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomain = $host[0];
echo $subdomain;

For multiple subdomains

$url = 'http://usa.en.example.com';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomains = array_slice($host, 0, count($host) - 2 );
print_r($subdomains);

What is the location of mysql client ".my.cnf" in XAMPP for Windows?

If you install it directly with the community installer on windows 2008 server, it will reside on c:\ProgamData\MySql\MysqlServerVersion\my.ini

How to share my Docker-Image without using the Docker-Hub?

[Update]

More recently, there is Amazon AWS ECR (Elastic Container Registry), which provides a Docker image registry to which you can control access by means of the AWS IAM access management service. ECR can also run a CVE (vulnerabilities) check on your image when you push it.

Once you create your ECR, and obtain the "URL" you can push and pull as required, subject to the permissions you create: hence making it private or public as you wish.

Pricing is by amount of data stored, and data transfer costs.

https://aws.amazon.com/ecr/

[Original answer]

If you do not want to use the Docker Hub itself, you can host your own Docker repository under Artifactory by JFrog:

https://www.jfrog.com/confluence/display/RTF/Docker+Repositories

which will then run on your own server(s).

Other hosting suppliers are available, eg CoreOS:

http://www.theregister.co.uk/2014/10/30/coreos_enterprise_registry/

which bought quay.io

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

Editor's note: this is a very dangerous approach, if you are using a version of PHP old enough to use it. It opens your code to man-in-the-middle attacks and removes one of the primary purposes of an encrypted connection. The ability to do this has been removed from modern versions of PHP because it is so dangerous. The only reason this has been upvoted 70 time is because people are lazy. DO NOT DO THIS.


I know it's a (very) old question and it's about command line, but when I searched Google for "SSL: no alternative certificate subject name matches target host name", this was the first hit.

It took me a good while to figure out the answer so hope this saves someone a lot of time! In PHP add this to your cUrl setopts:

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

p.s: this should be a temporary solution. Since this is a certificate error, best thing is to have the certificate fixed ofcourse!

How to make the overflow CSS property work with hidden as value

This worked for me

<div style="display: flex; position: absolute; width: 100%;">
  <div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
  </div>
</div>

Adding position:absolute to the parent container made it work.

PS: This is for anyone looking for a solution to dynamically truncating text.

EDIT: This was meant to be an answer for this question but since they are related and it could help someone on this question I shall also leave it here instead of deleting it.

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

Difference between margin and padding?

Margin is a property in CSS that is used to create spaces around the elements, outside of the border. The programmer can set the margin for top, right, bottom and left. In other words, he can set those values using margin-top, margin-right, margin-bottom and margin-left.

The Margin values can be of the following types.

First, auto allows the browser to calculate the margin. Moreover, length denotes a margin in px, pt or cm, while % helps to describe a margin as a percentage relative to the width of the containing element. Finally, inherit denotes that the margin has to inherit from the parent element.

Padding is a property in CSS that helps to create space around an element inside the border. The programmer can set the padding for top, right, bottom and left. In other words, he can set those values using padding-top, padding-right, padding-bottom and padding-left.

The Padding values can be of the following types.

The length describes padding in px, pt or cm, while % denotes padding as a percentage relative to the width of the containing element. Finally, inherit describes that the padding should be inherited from the parent element.

_x000D_
_x000D_
 div.special {_x000D_
          width:200px; _x000D_
          border-style: solid; _x000D_
          border-width:thin; _x000D_
          border-color:#000;_x000D_
          margin:30px 20px 10px 25px;_x000D_
}     _x000D_
div.special2 {_x000D_
          width:200px;_x000D_
          border-style: solid;_x000D_
          border-width:thin;_x000D_
          border-color:#000;_x000D_
          padding:30px 20px 10px 25px;_x000D_
}        
_x000D_
<div class="special">_x000D_
             Hello its margin test _x000D_
</div>_x000D_
<div class="special2">_x000D_
            Hello its padding test_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference Between Margin and Padding

Margin is a CSS property that is used to create space around the element outside the defined border, while the padding is a CSS property that is used to create space around the element, inside the defined border. Thus, this explains the main difference between margin and padding.

Values Furthermore, the values of margin can be auto, length, % or inherit, whereas the values of padding can be length, % or inherit type. Hence, this is another difference between margin and padding.

In brief, margin and padding are two properties in CSS that allows styling the web pages. It is not possible to assign negative values for those properties. The main difference between margin and padding is that margin helps to create space around the element outside the border, while padding helps to create space around the element inside the border.

Converting String Array to an Integer Array

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class MultiArg {

    Scanner sc;
    int n;
    String as;
    List<Integer> numList = new ArrayList<Integer>();

    public void fun() {
        sc = new Scanner(System.in);
        System.out.println("enter value");
        while (sc.hasNextInt())
            as = sc.nextLine();
    }

    public void diplay() {
        System.out.println("x");
        Integer[] num = numList.toArray(new Integer[numList.size()]);
        System.out.println("show value " + as);
        for (Integer m : num) {
            System.out.println("\t" + m);
        }
    }
}

but to terminate the while loop you have to put any charecter at the end of input.

ex. input:

12 34 56 78 45 67 .

output:

12 34 56 78 45 67

Convert float64 column to int64 in Pandas

consider using

df['column name'].astype('Int64')

nan will be changed to NaN

Zoom in on a point (using scale and translate)

Here's an approach I use for tighter control over how things are drawn

_x000D_
_x000D_
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var scale = 1;
var xO = 0;
var yO = 0;

draw();

function draw(){
    // Clear screen
    ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);

    // Original coordinates
    const xData = 50, yData = 50, wData = 100, hData = 100;
    
    // Transformed coordinates
    const x = xData * scale + xO,
     y = yData * scale + yO,
     w = wData * scale,
     h = hData * scale;

    // Draw transformed positions
    ctx.fillStyle = "black";
    ctx.fillRect(x,y,w,h);
}

canvas.onwheel = function (e){
    e.preventDefault();

    const r = canvas.getBoundingClientRect(),
      xNode =  e.pageX - r.left,
      yNode =  e.pageY - r.top;

    const newScale = scale * Math.exp(-Math.sign(e.deltaY) * 0.2),
      scaleFactor = newScale/scale;

    xO = xNode - scaleFactor * (xNode - xO);
    yO = yNode - scaleFactor * (yNode - yO);
    scale = newScale;

    draw();
}
_x000D_
<canvas id="canvas" width="600" height="200"></canvas>
_x000D_
_x000D_
_x000D_

Check whether variable is number or string in JavaScript

Can you just divide it by 1?

I assume the issue would be a string input like: "123ABG"

var Check = "123ABG"

if(Check == Check / 1)
{
alert("This IS a number \n")
}

else
{
alert("This is NOT a number \n")
}

Just a way I did it recently.

How do I select elements of an array given condition?

Your expression works if you add parentheses:

>>> y[(1 < x) & (x < 5)]
array(['o', 'o', 'a'], 
      dtype='|S1')

PHP : send mail in localhost

You will need to install a local mailserver in order to do this. If you want to send it to external e-mail addresses, it might end up in unwanted e-mails or it may not arrive at all.

A good mailserver which I use (I use it on Linux, but it's also available for Windows) is Axigen: http://www.axigen.com/mail-server/download/

You might need some experience with mailservers to install it, but once it works, you can do anything you want with it.

Override valueof() and toString() in Java enum

You still have an option to implement in your enum this:

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name){...}

Iterating through a variable length array

Arrays have an implicit member variable holding the length:

for(int i=0; i<myArray.length; i++) {
    System.out.println(myArray[i]);
}

Alternatively if using >=java5, use a for each loop:

for(Object o : myArray) {
    System.out.println(o);
}

How to drop all stored procedures at once in SQL Server database?

Try this, it work for me

DECLARE @spname sysname;
DECLARE SPCursor CURSOR FOR
SELECT SCHEMA_NAME(schema_id) + '.' + name
FROM sys.objects
WHERE type = 'P';
OPEN SPCursor;
FETCH NEXT FROM SPCursor INTO @spname;
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC('DROP PROCEDURE ' + @spname);
FETCH NEXT FROM SPCursor INTO @spname;
END
CLOSE SPCursor;
DEALLOCATE SPCursor;

Convert from List into IEnumerable format

As far as I know List<T> implements IEnumerable<T>. It means that you do not have to convert or cast anything.

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

Apply these changes in phpmyconfig/config.inc. Type in your username and password that you have set:

$cfg['Servers'][$i]['user']                 = 'user';
$cfg['Servers'][$i]['password']             = 'password';
$cfg['Servers'][$i]['AllowNoPassword']      = false;

This works for me.

How can I move all the files from one folder to another using the command line?

This command will move all the files in originalfolder to destinationfolder.

MOVE c:\originalfolder\* c:\destinationfolder

(However it wont move any sub-folders to the new location.)

To lookup the instructions for the MOVE command type this in a windows command prompt:

MOVE /?

I want to delete all bin and obj folders to force all projects to rebuild everything

This Works Fine For Me: start for /d /r . %%d in (bin,obj, ClientBin,Generated_Code) do @if exist "%%d" rd /s /q "%%d"

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

You should use

 SSLContext.getInstance("TLSv1.2"); 

for specific protocol version.

The second exception occured because default socketFactory used fallback SSLv3 protocol for failures.

You can use NoSSLFactory from main answer here for its suppression How to disable SSLv3 in android for HttpsUrlConnection?

Also you should init SSLContext with all your certificates(client and trusted ones if you need them)

But all of that is useless without using

ProviderInstaller.installIfNeeded(getContext())

Here is more information with proper usage scenario https://developer.android.com/training/articles/security-gms-provider.html

Hope it helps.

XSS prevention in JSP/Servlet web application

Managing XSS requires multiple validations, data from the client side.

  1. Input Validations (form validation) on the Server side. There are multiple ways of going about it. You can try JSR 303 bean validation(hibernate validator), or ESAPI Input Validation framework. Though I've not tried it myself (yet), there is an annotation that checks for safe html (@SafeHtml). You could in fact use Hibernate validator with Spring MVC for bean validations -> Ref
  2. Escaping URL requests - For all your HTTP requests, use some sort of XSS filter. I've used the following for our web app and it takes care of cleaning up the HTTP URL request - http://www.servletsuite.com/servlets/xssflt.htm
  3. Escaping data/html returned to the client (look above at @BalusC explanation).

get one item from an array of name,value JSON

Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}. If you know that the name property of each object will be unique you can store them in an object instead of an array, as follows:

var obj = {};
obj["k1"] = "abc";
obj["k2"] = "hi";
obj["k3"] = "oa";

alert(obj["k2"]); // displays "hi"

If you actually want an array of objects like in your post you can loop through the array and return when you find an element with an object having the property you want:

function findElement(arr, propName, propValue) {
  for (var i=0; i < arr.length; i++)
    if (arr[i][propName] == propValue)
      return arr[i];

  // will return undefined if not found; you could return a default instead
}

// Using the array from the question
var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"}
alert(x["value"]); // displays "hi"

var y = findElement(arr, "name", "k9"); // y is undefined
alert(y["value"]); // error because y is undefined

alert(findElement(arr, "name", "k2")["value"]); // displays "hi";

alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property

PowerShell script to check the status of a URL

Below is the PowerShell code that I use for basic web URL testing. It includes the ability to accept invalid certs and get detailed information about the results of checking the certificate.

$CertificateValidatorClass = @'
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace CertificateValidation
{
    public class CertificateValidationResult
    {
        public string Subject { get; internal set; }
        public string Thumbprint { get; internal set; }
        public DateTime Expiration { get; internal set; }
        public DateTime ValidationTime { get; internal set; }
        public bool IsValid { get; internal set; }
        public bool Accepted { get; internal set; }
        public string Message { get; internal set; }

        public CertificateValidationResult()
        {
            ValidationTime = DateTime.UtcNow;
        }
    }

    public static class CertificateValidator
    {
        private static ConcurrentStack<CertificateValidationResult> certificateValidationResults = new ConcurrentStack<CertificateValidationResult>();

        public static CertificateValidationResult[] CertificateValidationResults
        {
            get
            {
                return certificateValidationResults.ToArray();
            }
        }

        public static CertificateValidationResult LastCertificateValidationResult
        {
            get
            {
                CertificateValidationResult lastCertificateValidationResult = null;
                certificateValidationResults.TryPeek(out lastCertificateValidationResult);

                return lastCertificateValidationResult;
            }
        }

        public static bool ServicePointManager_ServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            StringBuilder certificateValidationMessage = new StringBuilder();
            bool allowCertificate = true;

            if (sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
            {
                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) == System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch)
                {
                    certificateValidationMessage.AppendFormat("The remote certificate name does not match.\r\n", certificate.Subject);
                }

                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) == System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors)
                {
                    certificateValidationMessage.AppendLine("The certificate chain has the following errors:");
                    foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus chainStatus in chain.ChainStatus)
                    {
                        certificateValidationMessage.AppendFormat("\t{0}", chainStatus.StatusInformation);

                        if (chainStatus.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.Revoked)
                        {
                            allowCertificate = false;
                        }
                    }
                }

                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable) == System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable)
                {
                    certificateValidationMessage.AppendLine("The remote certificate was not available.");
                    allowCertificate = false;
                }

                System.Console.WriteLine();
            }
            else
            {
                certificateValidationMessage.AppendLine("The remote certificate is valid.");
            }

            CertificateValidationResult certificateValidationResult = new CertificateValidationResult
                {
                    Subject = certificate.Subject,
                    Thumbprint = certificate.GetCertHashString(),
                    Expiration = DateTime.Parse(certificate.GetExpirationDateString()),
                    IsValid = (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None),
                    Accepted = allowCertificate,
                    Message = certificateValidationMessage.ToString()
                };

            certificateValidationResults.Push(certificateValidationResult);
            return allowCertificate;
        }

        public static void SetDebugCertificateValidation()
        {
            ServicePointManager.ServerCertificateValidationCallback = ServicePointManager_ServerCertificateValidationCallback;
        }

        public static void SetDefaultCertificateValidation()
        {
            ServicePointManager.ServerCertificateValidationCallback = null;
        }

        public static void ClearCertificateValidationResults()
        {
            certificateValidationResults.Clear();
        }
    }
}
'@

function Set-CertificateValidationMode
{
    <#
    .SYNOPSIS
    Sets the certificate validation mode.
    .DESCRIPTION
    Set the certificate validation mode to one of three modes with the following behaviors:
        Default -- Performs the .NET default validation of certificates. Certificates are not checked for revocation and will be rejected if invalid.
        CheckRevocationList -- Cerftificate Revocation Lists are checked and certificate will be rejected if revoked or invalid.
        Debug -- Certificate Revocation Lists are checked and revocation will result in rejection. Invalid certificates will be accepted. Certificate validation
                 information is logged and can be retrieved from the certificate handler.
    .EXAMPLE
    Set-CertificateValidationMode Debug
    .PARAMETER Mode
    The mode for certificate validation.
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param
    (
        [Parameter()]
        [ValidateSet('Default', 'CheckRevocationList', 'Debug')]
        [string] $Mode
    )

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        switch ($Mode)
        {
            'Debug'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
                [CertificateValidation.CertificateValidator]::SetDebugCertificateValidation()
            }
            'CheckRevocationList'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
                [CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
            }
            'Default'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $false
                [CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
            }
        }
    }
}

function Clear-CertificateValidationResults
{
    <#
    .SYNOPSIS
    Clears the collection of certificate validation results.
    .DESCRIPTION
    Clears the collection of certificate validation results.
    .EXAMPLE
    Get-CertificateValidationResults
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param()

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        [CertificateValidation.CertificateValidator]::ClearCertificateValidationResults()
        Sleep -Milliseconds 20
    }
}

function Get-CertificateValidationResults
{
    <#
    .SYNOPSIS
    Gets the certificate validation results for all operations performed in the PowerShell session since the Debug cerificate validation mode was enabled.
    .DESCRIPTION
    Gets the certificate validation results for all operations performed in the PowerShell session since the Debug certificate validation mode was enabled in reverse chronological order.
    .EXAMPLE
    Get-CertificateValidationResults
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param()

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        return [CertificateValidation.CertificateValidator]::CertificateValidationResults
    }
}

function Test-WebUrl
{
    <#
    .SYNOPSIS
    Tests and reports information about the provided web URL.
    .DESCRIPTION
    Tests a web URL and reports the time taken to get and process the request and response, the HTTP status, and the error message if an error occurred.
    .EXAMPLE
    Test-WebUrl 'http://websitetotest.com/'
    .EXAMPLE
    'https://websitetotest.com/' | Test-WebUrl
    .PARAMETER HostName
    The Hostname to add to the back connection hostnames list.
    .PARAMETER UseDefaultCredentials
    If present the default Windows credential will be used to attempt to authenticate to the URL; otherwise, no credentials will be presented.
    #>
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Uri] $Url,
        [Parameter()]
        [Microsoft.PowerShell.Commands.WebRequestMethod] $Method = 'Get',
        [Parameter()]
        [switch] $UseDefaultCredentials
    )

    process
    {
        [bool] $succeeded = $false
        [string] $statusCode = $null
        [string] $statusDescription = $null
        [string] $message = $null
        [int] $bytesReceived = 0
        [Timespan] $timeTaken = [Timespan]::Zero 

        $timeTaken = Measure-Command `
            {
                try
                {
                    [Microsoft.PowerShell.Commands.HtmlWebResponseObject] $response = Invoke-WebRequest -UseDefaultCredentials:$UseDefaultCredentials -Method $Method -Uri $Url
                    $succeeded = $true
                    $statusCode = $response.StatusCode.ToString('D')
                    $statusDescription = $response.StatusDescription
                    $bytesReceived = $response.RawContent.Length

                    Write-Verbose "$($Url.ToString()): $($statusCode) $($statusDescription) $($message)"
                }
                catch [System.Net.WebException]
                {
                    $message = $Error[0].Exception.Message
                    [System.Net.HttpWebResponse] $exceptionResponse = $Error[0].Exception.GetBaseException().Response

                    if ($exceptionResponse -ne $null)
                    {
                        $statusCode = $exceptionResponse.StatusCode.ToString('D')
                        $statusDescription = $exceptionResponse.StatusDescription
                        $bytesReceived = $exceptionResponse.ContentLength

                        if ($statusCode -in '401', '403', '404')
                        {
                            $succeeded = $true
                        }
                    }
                    else
                    {
                        Write-Warning "$($Url.ToString()): $($message)"
                    }
                }
            }

        return [PSCustomObject] @{ Url = $Url; Succeeded = $succeeded; BytesReceived = $bytesReceived; TimeTaken = $timeTaken.TotalMilliseconds; StatusCode = $statusCode; StatusDescription = $statusDescription; Message = $message; }
    }
}

Set-CertificateValidationMode Debug
Clear-CertificateValidationResults

Write-Host 'Testing web sites:'
'https://expired.badssl.com/', 'https://wrong.host.badssl.com/', 'https://self-signed.badssl.com/', 'https://untrusted-root.badssl.com/', 'https://revoked.badssl.com/', 'https://pinning-test.badssl.com/', 'https://sha1-intermediate.badssl.com/' | Test-WebUrl | ft -AutoSize

Write-Host 'Certificate validation results (most recent first):'
Get-CertificateValidationResults | ft -AutoSize

What is the ellipsis (...) for in this method signature?

The three dot (...) notation is actually borrowed from mathematics, and it means "...and so on".

As for its use in Java, it stands for varargs, meaning that any number of arguments can be added to the method call. The only limitations are that the varargs must be at the end of the method signature and there can only be one per method.

How do you open an SDF file (SQL Server Compact Edition)?

You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to

  1. View ->
  2. Server Explorer ->
  3. Data Connections ->
  4. Add Connection...
  5. Change... (Data Source:)
  6. Microsoft SQL Server Compact 4.0
  7. Browse...

and following the instructions there.

If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.

(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)

Embedding SVG into ReactJS

If you just have a static svg string you want to include, you can use dangerouslySetInnerHTML:

render: function() {
    return <span dangerouslySetInnerHTML={{__html: "<svg>...</svg>"}} />;
}

and React will include the markup directly without processing it at all.

Setting a PHP $_SESSION['var'] using jQuery

You can't do it through jQuery alone; you'll need a combination of Ajax (which you can do with jQuery) and a PHP back-end. A very simple version might look like this:

HTML:

<img class="foo" src="img.jpg" />
<img class="foo" src="img2.jpg" />
<img class="foo" src="img3.jpg" />

Javascript:

$("img.foo").onclick(function()
{
    // Get the src of the image
    var src = $(this).attr("src");

    // Send Ajax request to backend.php, with src set as "img" in the POST data
    $.post("/backend.php", {"img": src});
});

PHP (backend.php):

<?php
    // do any authentication first, then add POST variable to session
    $_SESSION['imgsrc'] = $_POST['img'];
?>

Executing <script> elements inserted with .innerHTML

function insertHtml(id, html)  
{  
   var ele = document.getElementById(id);  
   ele.innerHTML = html;  
   var codes = ele.getElementsByTagName("script");   
   for(var i=0;i<codes.length;i++)  
   {  
       eval(codes[i].text);  
   }  
}  

It works in Chrome in my project

How can you export the Visual Studio Code extension list?

  1. code --list-extensions > list

  2. sed -i 's/.*/\"&\",/' list

  3. Copy contents of file list and add to file .vscode/extensions.json in the "recommendations" section.

  4. If extensions.json doesn't exist then create a file with the following contents

    {
        "recommendations": [
            // Add content of file list here
        ]
    }
    
  5. Share the extensions.json file and ask another user to add to the .vscode folder. Visual Studio Code will prompt for installation of extensions.

How to initialize List<String> object in Java?

Depending on what kind of List you want to use, something like

List<String> supplierNames = new ArrayList<String>();

should get you going.

List is the interface, ArrayList is one implementation of the List interface. More implementations that may better suit your needs can be found by reading the JavaDocs of the List interface.

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

You have three options:

  • Xcode Organizer
  • Jailbroken device with syslogd + openSSH
  • Use dup2 to redirect all STDERR and STDOUT to a file and then "tail -f" that file (this last one is more a simulator thing, since you are stuck with the same problem of tailing a file on the device).

So, to get the 2º one you just need to install syslogd and OpenSSH from Cydia, restart required after to get syslogd going; now just open a ssh session to your device (via terminal or putty on windows), and type "tail -f /var/log/syslog". And there you go, wireless real time system log.

If you would like to try the 3º just search for "dup2" online, it's a system call.

Add Whatsapp function to website, like sms, tel

This is possible by creating the following link:

whatsapp://send?text=Hello this has been opened from the browser&phone=+PHONENUMBER&abid=+PHONENUMBER

Thanks to:

https://forum.ionicframework.com/t/open-whatsapp-intent-with-msg-specific-contact/73903/4

I have tested this on iOS, Windows Phone and Android

What is the difference between the float and integer data type when the size is the same?

Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point

Pandas Replace NaN with blank/empty string

df = df.fillna('')

or just

df.fillna('', inplace=True)

This will fill na's (e.g. NaN's) with ''.

If you want to fill a single column, you can use:

df.column1 = df.column1.fillna('')

One can use df['column1'] instead of df.column1.

If statement in select (ORACLE)

use the variable, Oracle does not support SQL in that context without an INTO. With a properly named variable your code will be more legible anyway.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I am having the same issue when trying to upgrade Android Studio from 1.1 to 1.2 on Mac OS 10.10. I solved the problem by selecting custom installation instead of standard. Also we need to select the Android SDK Platform (Lollipop 5.1).

How to select data from 30 days?

Try this : Using this you can select date by last 30 days,

SELECT DATEADD(DAY,-30,GETDATE())

Write to text file without overwriting in Java

Just change PrintWriter out = new PrintWriter(log); to

PrintWriter out = new PrintWriter(new FileWriter(log, true));

Get the number of rows in a HTML table

In the DOM, a tr element is (implicitly or explicitly) a child of tbody, thead, or tfoot, not a child of table (hence the 0 you got). So a general answer is:

var count = $('#gvPerformanceResult > * > tr').length;

This includes the rows of the table but excludes rows of any inner table.

Oracle: how to UPSERT (update or insert into a table?)

I've been using the first code sample for years. Notice notfound rather than count.

UPDATE tablename SET val1 = in_val1, val2 = in_val2
    WHERE val3 = in_val3;
IF ( sql%notfound ) THEN
    INSERT INTO tablename
        VALUES (in_val1, in_val2, in_val3);
END IF;

The code below is the possibly new and improved code

MERGE INTO tablename USING dual ON ( val3 = in_val3 )
WHEN MATCHED THEN UPDATE SET val1 = in_val1, val2 = in_val2
WHEN NOT MATCHED THEN INSERT 
    VALUES (in_val1, in_val2, in_val3)

In the first example the update does an index lookup. It has to, in order to update the right row. Oracle opens an implicit cursor, and we use it to wrap a corresponding insert so we know that the insert will only happen when the key does not exist. But the insert is an independent command and it has to do a second lookup. I don't know the inner workings of the merge command but since the command is a single unit, Oracle could have execute the correct insert or update with a single index lookup.

I think merge is better when you do have some processing to be done that means taking data from some tables and updating a table, possibly inserting or deleting rows. But for the single row case, you may consider the first case since the syntax is more common.

How do Python's any and all functions work?

>>> any([False, False, False])
False
>>> any([False, True, False])
True
>>> all([False, True, True])
False
>>> all([True, True, True])
True

How can I remount my Android/system as read-write in a bash script using adb?

In addition to all the other answers you received, I want to explain the unknown option -- o error: Your command was

$ adb shell 'su -c  mount -o rw,remount /system'

which calls su through adb. You properly quoted the whole su command in order to pass it as one argument to adb shell. However, su -c <cmd> also needs you to quote the command with arguments it shall pass to the shell's -c option. (YMMV depending on su variants.) Therefore, you might want to try

$ adb shell 'su -c "mount -o rw,remount /system"'

(and potentially add the actual device listed in the output of mount | grep system before the /system arg – see the other answers.)

Pygame mouse clicking detection

The pygame documentation for mouse events is here. You can either use the pygame.mouse.get_pressed method in collaboration with the pygame.mouse.get_pos (if needed). But please use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.

EDIT: To perform pixel perfect collisions use pygame.sprite.collide_rect() found on their docs for sprites.

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

In the build.gradle(Module:app) file, insert the code below into defaultConfig :

  defaultConfig {
        applicationId "com.***.****"
minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }

and insert into to dependencies :

implementation 'com.android.support:multidex:2.0.1'

Then add code to manifest :

<application 
    android:name="android.support.multidex.MultiDexApplication"

How to scroll to an element in jQuery?

I think you might be looking for an "anchor" given the example you have.

<a href="#jump">This link will jump to the anchor named jump</a>
<a name="jump">This is where the link will jump to</a>

The focus jQuery method does something different from what you're trying to achieve.

Excel Validation Drop Down list using VBA

You are defining your array as xlValidateList(), so when you try to assign the type, it gets confused as to what you are trying to assign to the type.

Instead, try this:

Dim MyList(5) As String
MyList(0) = 1
MyList(1) = 2
MyList(2) = 3
MyList(3) = 4
MyList(4) = 5
MyList(5) = 6

With Range("A1").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
         Operator:=xlBetween, Formula1:=Join(MyList, ",")
End With

PostgreSQL: role is not permitted to log in

Using pgadmin4 :

  1. Select roles in side menu
  2. Select properties in dashboard.
  3. Click Edit and select privileges

Now there you can enable or disable login, roles and other options

Get pandas.read_csv to read empty values as empty string instead of nan

I added a ticket to add an option of some sort here:

https://github.com/pydata/pandas/issues/1450

In the meantime, result.fillna('') should do what you want

EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values, empty strings will stay empty strings in the result

Viewing unpushed Git commits

Handy git alias for looking for unpushed commits in current branch:

alias unpushed = !GIT_CURRENT_BRANCH=$(git name-rev --name-only HEAD) && git log origin/$GIT_CURRENT_BRANCH..$GIT_CURRENT_BRANCH --oneline

What this basically does:

git log origin/branch..branch

but also determines current branch name.

How to print to stderr in Python?

Answer to the question is : There are different way to print stderr in python but that depends on 1.) which python version we are using 2.) what exact output we want.

The differnce between print and stderr's write function: stderr : stderr (standard error) is pipe that is built into every UNIX/Linux system, when your program crashes and prints out debugging information (like a traceback in Python), it goes to the stderr pipe.

print: print is a wrapper that formats the inputs (the input is the space between argument and the newline at the end) and it then calls the write function of a given object, the given object by default is sys.stdout, but we can pass a file i.e we can print the input in a file also.

Python2: If we are using python2 then

>>> import sys
>>> print "hi"
hi
>>> print("hi")
hi
>>> print >> sys.stderr.write("hi")
hi

Python2 trailing comma has in Python3 become a parameter, so if we use trailing commas to avoid the newline after a print, this will in Python3 look like print('Text to print', end=' ') which is a syntax error under Python2.

http://python3porting.com/noconv.html

If we check same above sceario in python3:

>>> import sys
>>> print("hi")
hi

Under Python 2.6 there is a future import to make print into a function. So to avoid any syntax errors and other differences we should start any file where we use print() with from future import print_function. The future import only works under Python 2.6 and later, so for Python 2.5 and earlier you have two options. You can either convert the more complex print to something simpler, or you can use a separate print function that works under both Python2 and Python3.

>>> from __future__ import print_function
>>> 
>>> def printex(*args, **kwargs):
...     print(*args, file=sys.stderr, **kwargs)
... 
>>> printex("hii")
hii
>>>

Case: Point to be noted that sys.stderr.write() or sys.stdout.write() ( stdout (standard output) is a pipe that is built into every UNIX/Linux system) is not a replacement for print, but yes we can use it as a alternative in some case. Print is a wrapper which wraps the input with space and newline at the end and uses the write function to write. This is the reason sys.stderr.write() is faster.

Note: we can also trace and debugg using Logging

#test.py
import logging
logging.info('This is the existing protocol.')
FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning("Protocol problem: %s", "connection reset", extra=d)

https://docs.python.org/2/library/logging.html#logger-objects

How do I use hexadecimal color strings in Flutter?

I missed the obvious answer using hex numbers for the fromRGB constructor:

Color.fromRGBO(0xb7, 0x40, 0x93, 1),

What is the preferred Bash shebang?

Using a shebang line to invoke the appropriate interpreter is not just for BASH. You can use the shebang for any interpreted language on your system such as Perl, Python, PHP (CLI) and many others. By the way, the shebang

#!/bin/sh -

(it can also be two dashes, i.e. --) ends bash options everything after will be treated as filenames and arguments.

Using the env command makes your script portable and allows you to setup custom environments for your script hence portable scripts should use

#!/usr/bin/env bash

Or for whatever the language such as for Perl

#!/usr/bin/env perl

Be sure to look at the man pages for bash:

man bash

and env:

man env

Note: On Debian and Debian-based systems, like Ubuntu, sh is linked to dash not bash. As all system scripts use sh. This allows bash to grow and the system to stay stable, according to Debian.

Also, to keep invocation *nix like I never use file extensions on shebang invoked scripts, as you cannot omit the extension on invocation on executables as you can on Windows. The file command can identify it as a script.

Should 'using' directives be inside or outside the namespace?

Putting it inside the namespaces makes the declarations local to that namespace for the file (in case you have multiple namespaces in the file) but if you only have one namespace per file then it doesn't make much of a difference whether they go outside or inside the namespace.

using ThisNamespace.IsImported.InAllNamespaces.Here;

namespace Namespace1
{ 
   using ThisNamespace.IsImported.InNamespace1.AndNamespace2;

   namespace Namespace2
   { 
      using ThisNamespace.IsImported.InJustNamespace2;
   }       
}

namespace Namespace3
{ 
   using ThisNamespace.IsImported.InJustNamespace3;
}