Programs & Examples On #Webexception

System.Net.WebException HTTP status code

You can try this code to get HTTP status code from WebException. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(WebException we)
{
    if (we.Response is HttpWebResponse)
    {
        HttpWebResponse response = (HttpWebResponse)we.Response;
        return response.StatusCode;
    }
    return null;
}

How to get name of dataframe column in pyspark?

Python

As @numeral correctly said, column._jc.toString() works fine in case of unaliased columns.

In case of aliased columns (i.e. column.alias("whatever") ) the alias can be extracted, even without the usage of regular expressions: str(column).split(" AS ")[1].split("`")[1] .

I don't know Scala syntax, but I'm sure It can be done the same.

How to show alert message in mvc 4 controller?

I know this is not typical alert box, but I hope it may help someone.

There is this expansion that enables you to show notifications inside HTML page using bootstrap.

It is very easy to implement and it works fine. Here is a github page for the project including some demo images.

Lock, mutex, semaphore... what's the difference?

Take a look at Multithreading Tutorial by John Kopplin.

In the section Synchronization Between Threads, he explain the differences among event, lock, mutex, semaphore, waitable timer

A mutex can be owned by only one thread at a time, enabling threads to coordinate mutually exclusive access to a shared resource

Critical section objects provide synchronization similar to that provided by mutex objects, except that critical section objects can be used only by the threads of a single process

Another difference between a mutex and a critical section is that if the critical section object is currently owned by another thread, EnterCriticalSection() waits indefinitely for ownership whereas WaitForSingleObject(), which is used with a mutex, allows you to specify a timeout

A semaphore maintains a count between zero and some maximum value, limiting the number of threads that are simultaneously accessing a shared resource.

JQuery Ajax Post results in 500 Internal Server Error

I run into the same thing today. As suggested before get Firebug for Firefox, Enable Console and preview POST response. That helped me to find out how stupid the problem was. My action was expecting value of a type int and I was posting string. (ASP.NET MVC2)

How to align LinearLayout at the center of its parent?

Try this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >
            <TableRow >
            <LinearLayout 
            android:orientation="horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal" 
                    android:layout_gravity="center_horizontal" >
                    <TextView
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="1"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

                     <TextView
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="2"
                    android:textAppearance="?android:attr/textAppearanceLarge" />
             </LinearLayout>
           </TableRow>
        </TableLayout>
    </FrameLayout>
</LinearLayout>

How to find controls in a repeater header or footer

This is in VB.NET, just translate to C# if you need it:

<Extension()>
Public Function FindControlInRepeaterHeader(Of T As Control)(obj As Repeater, ControlName As String) As T
    Dim ctrl As T = TryCast((From item As RepeaterItem In obj.Controls
                   Where item.ItemType = ListItemType.Header).SingleOrDefault.FindControl(ControlName),T)
    Return ctrl
End Function

And use it easy:

Dim txt as string = rptrComentarios.FindControlInRepeaterHeader(Of Label)("lblVerTodosComentarios").Text

Try to make it work with footer, and items controls too =)

javax vs java package

Some packages like javax.swing were not included in java standard library at first. Sun company decided to consider them official and included them into the early versions of java as standard libraries or standard extensions.

By convention, all the standard extensions start with an X while they can get promoted to first-class over time like what happened for javax.swing.

"Submit is not a function" error in JavaScript

giving a form element a name of submit will simple shadow the submit property . make sure you don't have a form element with the name submit and you should be able to access the submit function just fine .

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt

How to read multiple Integer values from a single line of input in Java?

I use it all the time on hackerrank/leetcode

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String  lines = br.readLine();    
        
    String[] strs = lines.trim().split("\\s+");
            
    for (int i = 0; i < strs.length; i++) {
    a[i] = Integer.parseInt(strs[i]);
    }

support FragmentPagerAdapter holds reference to old fragments

Do not try to interact between fragments in ViewPager. You cannot guarantee that other fragment attached or even exists. Istead of changing actionbar title from fragment, you can do it from your activity. Use standart interface pattern for this:

public interface UpdateCallback
{
    void update(String name);
}

public class MyActivity extends FragmentActivity implements UpdateCallback
{
    @Override
    public void update(String name)
    {
        getSupportActionBar().setTitle(name);
    }

}

public class MyFragment extends Fragment
{
    private UpdateCallback callback;

    @Override
    public void onAttach(SupportActivity activity)
    {
        super.onAttach(activity);
        callback = (UpdateCallback) activity;
    }

    @Override
    public void onDetach()
    {
        super.onDetach();
        callback = null;
    }

    public void updateActionbar(String name)
    {
        if(callback != null)
            callback.update(name);
    }
}

Mapping object to dictionary and vice versa

Seems reflection only help here.. I've done small example of converting object to dictionary and vise versa:

[TestMethod]
public void DictionaryTest()
{
    var item = new SomeCLass { Id = "1", Name = "name1" };
    IDictionary<string, object> dict = ObjectToDictionary<SomeCLass>(item);
    var obj = ObjectFromDictionary<SomeCLass>(dict);
}

private T ObjectFromDictionary<T>(IDictionary<string, object> dict)
    where T : class 
{
    Type type = typeof(T);
    T result = (T)Activator.CreateInstance(type);
    foreach (var item in dict)
    {
        type.GetProperty(item.Key).SetValue(result, item.Value, null);
    }
    return result;
}

private IDictionary<string, object> ObjectToDictionary<T>(T item)
    where T: class
{
    Type myObjectType = item.GetType();
    IDictionary<string, object> dict = new Dictionary<string, object>();
    var indexer = new object[0];
    PropertyInfo[] properties = myObjectType.GetProperties();
    foreach (var info in properties)
    {
        var value = info.GetValue(item, indexer);
        dict.Add(info.Name, value);
    }
    return dict;
}

How to send a JSON object using html form data

I found a way to pass a JSON message using only a HTML form.

This example is for GraphQL but it will work for any endpoint that is expecting a JSON message.

GrapqhQL by default expects a parameter called operations where you can add your query or mutation in JSON format. In this specific case I am invoking this query which is requesting to get allUsers and return the userId of each user.

{ 
 allUsers 
  { 
  userId 
  }
}

I am using a text input to demonstrate how to use it, but you can change it for a hidden input to hide the query from the user.

<html>
<body>
    <form method="post" action="http://localhost:8080/graphql">
        <input type="text" name="operations" value="{&quot;query&quot;: &quot;{ allUsers { userId } }&quot;, "variables":  {}}"/>
        <input type="submit" />
    </form>
</body>
</html>

In order to make this dynamic you will need JS to transport the values of the text fields to the query string before submitting your form. Anyway I found this approach very interesting. Hope it helps.

A Space between Inline-Block List Items

just remove the breaks between li's in your html code... make the li's in one line only..

How to read strings from a Scanner in a Java console application?

You are entering a null value to nextInt, it will fail if you give a null value...

i have added a null check to the piece of code

Try this code:

import java.util.Scanner;
class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                     eid=(scanner.nextInt());
                System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
                System.out.println("Enter SupervisiorId:");
                    if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                     sid=scanner.nextInt();
                     }//null check
        }
}

What's the difference between implementation and compile in Gradle?

Compile configuration was deprecated and should be replaced by implementation or api.

You can read the docs at https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_separation.

The brief part being-

The key difference between the standard Java plugin and the Java Library plugin is that the latter introduces the concept of an API exposed to consumers. A library is a Java component meant to be consumed by other components. It's a very common use case in multi-project builds, but also as soon as you have external dependencies.

The plugin exposes two configurations that can be used to declare dependencies: api and implementation. The api configuration should be used to declare dependencies which are exported by the library API, whereas the implementation configuration should be used to declare dependencies which are internal to the component.

For further explanation refer to this image. Brief explanation

clear table jquery

<table id="myTable" class="table" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
        </tr>
    </thead>
    <tbody id="tblBody">

    </tbody>
</table>

And Remove:

$("#tblBody").empty();

How to dynamically build a JSON object with Python?

There is already a solution provided which allows building a dictionary, (or nested dictionary for more complex data), but if you wish to build an object, then perhaps try 'ObjDict'. This gives much more control over the json to be created, for example retaining order, and allows building as an object which may be a preferred representation of your concept.

pip install objdict first.

from objdict import ObjDict

data = ObjDict()
data.key = 'value'
json_data = data.dumps()

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

Adding System.Web.Script reference in class library

The ScriptIgnoreAttribute class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.

You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.

How to make audio autoplay on chrome

temp fix

$(document).on('click', "#buttonStarter", function(evt)
{
var context = new AudioContext();
document.getElementById('audioPlayer').play();
$("#buttonStarter").hide()
$("#Game").show()
});

Or use a custom player to trigger play http://zohararad.github.io/audio5js/

Note : Autoplay will be renabled in 31 December

X-Frame-Options Allow-From multiple domains

Not exactly the same, but could work for some cases: there is another option ALLOWALL which will effectively remove the restriction, which might be a nice thing for testing/pre-production environments

How to do scanf for single char in C

Use string instead of char like

char c[10];
scanf ("%s", c);

I belive it works nice.

Angular ng-if not true

Use like this

<div ng-if="data.IsActive === 1">InActive</div>
<div ng-if="data.IsActive === 0">Active</div>

Use superscripts in R axis labels

The other option in this particular case would be to type the degree symbol: °

R seems to handle it fine. Type Option-k on a Mac to get it. Not sure about other platforms.

Two divs side by side - Fluid display

Make both divs like this. This will align both divs side-by-side.

.my-class {
  display : inline-flex;
} 

sql server convert date to string MM/DD/YYYY

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

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

Set the location in iPhone Simulator

Better late than never :)

I just came across this iSimulate which allows you to send Fake location to the app. The solution is NOT free.

> Q: How does iSimulate work? 

> A: When added to your project, the iSimulate
> SDK library creates a listening server
> on your iPhone Simulator that waits
> for a connection from an iPhone/iPod
> running the iSimulate client. When
> such connection is established, the
> iSimulate client running on your
> iPhone/iPod captures all data from the
> accelerometer sensor, the touch
> events, the location and device ID and
> streams them to the server. The
> iSimulate SDK library then recreates
> all input events synthetically. This
> is entirely transparent to your
> application and does not interfere
> with your application's functionality.

Anyway, i am planning to get this. will update more soon!

Django Multiple Choice Field / Checkbox Select Multiple

ManyToManyField isn`t a good choice.You can use some snippets to implement MultipleChoiceField.You can be inspired by MultiSelectField with comma separated values (Field + FormField) But it has some bug in it.And you can install django-multiselectfield.This is more prefect.

Reset local repository branch to be just like remote repository HEAD

This is something I face regularly, & I've generalised the script Wolfgang provided above to work with any branch

I also added an "are you sure" prompt, & some feedback output

#!/bin/bash
# reset the current repository
# WF 2012-10-15
# AT 2012-11-09
# see http://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head
timestamp=`date "+%Y-%m-%d-%H_%M_%S"`
branchname=`git rev-parse --symbolic-full-name --abbrev-ref HEAD`
read -p "Reset branch $branchname to origin (y/n)? "
[ "$REPLY" != "y" ] || 
echo "about to auto-commit any changes"
git commit -a -m "auto commit at $timestamp"
if [ $? -eq 0 ]
then
  echo "Creating backup auto-save branch: auto-save-$branchname-at-$timestamp"
  git branch "auto-save-$branchname-at-$timestamp" 
fi
echo "now resetting to origin/$branchname"
git fetch origin
git reset --hard origin/$branchname

How do I get the current absolute URL in Ruby on Rails?

I needed the application URL but with the subdirectory. I used:

root_url(:only_path => false)

How to get all files under a specific directory in MATLAB?

This is a handy function for getting filenames, with the specified format (usually .mat) in a root folder!

    function filenames = getFilenames(rootDir, format)
        % Get filenames with specified `format` in given `foler` 
        %
        % Parameters
        % ----------
        % - rootDir: char vector
        %   Target folder
        % - format: char vector = 'mat'
        %   File foramt

        % default values
        if ~exist('format', 'var')
            format = 'mat';
        end

        format = ['*.', format];
        filenames = dir(fullfile(rootDir, format));
        filenames = arrayfun(...
            @(x) fullfile(x.folder, x.name), ...
            filenames, ...
            'UniformOutput', false ...
        );
    end

In your case, you can use the following snippet :)

filenames = getFilenames('D:/dic/**');
for i = 1:numel(filenames)
    filename = filenames{i};
    % do your job!
end

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac

I actually tried all of the solutions which made sense, mentioned in this post and yet i still got the same error when running php -v or composer. The node version was fine, npm as well there were no issues on having installed correct versions and they were all running. Running reinstall [email protected] just threw an error. In the end i had to run:

brew reinstall icu4c

This basically worked, with me having to manually then install php dependencies such as imagick.so, imap.so As these libraries were installed for a project that i no longer maintain i can go without them. But if you do have dependancies on them, have in mind that there will be more work to do afterwards.

how to implement a long click listener on a listview

I tried most of these answers and they were all failing for TextViews that had autolink enabled but also had to use long press in the same place!

I made a custom class that works.

public class TextViewLinkLongPressUrl extends TextView {

    private boolean isLongClick = false;

    public TextViewLinkLongPressUrl(Context context) {
        super(context);
    }

    public TextViewLinkLongPressUrl(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TextViewLinkLongPressUrl(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, type);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_UP && isLongClick) {
            isLongClick = false;
            return false;
        }

        if (event.getAction() == MotionEvent.ACTION_UP) {
            isLongClick = false;
        }

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            isLongClick = false;
        }

        return super.onTouchEvent(event);
    }

    @Override
    public boolean performLongClick() {
        isLongClick = true;
        return super.performLongClick();
    }
}

How do I turn off Oracle password expiration?

As the other answers state, changing the user's profile (e.g. the 'DEFAULT' profile) appropriately will lead to passwords, that once set, will never expire.

However, as one commenter points out, passwords set under the profile's old values may already be expired, and (if after the profile's specified grace period) the account locked.

The solution for expired passwords with locked accounts (as provided in an answering comment) is to use one version of the ALTER USER command:

ALTER USER xyz_user ACCOUNT UNLOCK;

However the unlock command only works for accounts where the account is actually locked, but not for those accounts that are in the grace period, i.e. where the password is expired but the account is not yet locked. For these accounts the password must be reset with another version of the ALTER USER command:

ALTER USER xyz_user IDENTIFIED BY new_password;

Below is a little SQL*Plus script that a privileged user (e.g. user 'SYS') can use to reset a user's password to the current existing hashed value stored in the database.

EDIT: Older versions of Oracle store the password or password-hash in the pword column, newer versions of Oracle store the password-hash in the spare4 column. Script below changed to collect the pword and spare4 columns, but to use the spare4 column to reset the user's account; modify as needed.

REM Tell SQL*Plus to show before and after versions of variable substitutions.
SET VERIFY ON
SHOW VERIFY

REM Tell SQL*Plus to use the ampersand '&' to indicate variables in substitution/expansion.
SET DEFINE '&'
SHOW DEFINE

REM Specify in a SQL*Plus variable the account to 'reset'.
REM Note that user names are case sensitive in recent versions of Oracle.
REM DEFINE USER_NAME = 'xyz_user'

REM Show the status of the account before reset.
SELECT
  ACCOUNT_STATUS,
  TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
  TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
  DBA_USERS
WHERE
  USERNAME = '&USER_NAME';

REM Create SQL*Plus variable to hold the existing values of the password and spare4 columns.
DEFINE OLD_SPARE4 = ""
DEFINE OLD_PASSWORD = ""

REM Tell SQL*Plus where to store the values to be selected with SQL.
REM Note that the password hash value is stored in spare4 column in recent versions of Oracle,
REM   and in the password column in older versions of Oracle.
COLUMN SPARE4HASH NEW_VALUE OLD_SPARE4
COLUMN PWORDHASH NEW_VALUE OLD_PASSWORD

REM Select the old spare4 and password columns as delimited strings 
SELECT 
  '''' || SPARE4 || '''' AS SPARE4HASH,
  '''' || PASSWORD || '''' AS PWORDHASH
FROM 
  SYS.USER$ 
WHERE 
  NAME = '&USER_NAME';

REM Show the contents of the SQL*Plus variables
DEFINE OLD_SPARE4
DEFINE OLD_PASSWORD

REM Reset the password - Older versions of Oracle (e.g. Oracle 10g and older) 
REM ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_PASSWORD;

REM Reset the password - Newer versions of Oracle (e.g. Oracle 11g and newer) 
ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_SPARE4;

REM Show the status of the account after reset
SELECT
  ACCOUNT_STATUS,
  TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
  TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
  DBA_USERS
WHERE
  USERNAME = '&USER_NAME';

How can I open a website in my web browser using Python?

As the instructions state, using the open() function does work, and opens the default web browser - usually I would say: "why wouldn't I want to use Firefox?!" (my default and favorite browser)

import webbrowser as wb
wb.open_new_tab('http://www.google.com')

The above should work for the computer's default browser. However, what if you want to to open in Google Chrome?

The proper way to do this is:

import webbrowser as wb
wb.get('chrome %s').open_new_tab('http://www.google.com')

To be honest, I'm not really sure that I know the difference between 'chrome' and 'google-chrome', but apparently there is some since they've made the two different type names in the webbrowser documentation.

However, doing this didn't work right off the bat for me. Every time, I would get the error:

Traceback (most recent call last):
File "C:\Python34\programs\a_temp_testing.py", line 3, in <module>
wb.get('google-chrome')
File "C:\Python34\lib\webbrowser.py", line 51, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser

To solve this, I had to add the folder for chrome.exe to System PATH. My chrome.exe executable file is found at:

C:\Program Files (x86)\Google\Chrome\Application

You should check whether it is here or not for yourself.

To add this to your Environment Variables System PATH, right click on your Windows icon and go to System. System Control Panel applet (Start - Settings - Control Panel - System). Change advanced settings, or the advanced tab, and select the button there called Environment Varaibles.

Once you click on Environment Variables here, another window will pop up. Scroll through the items, select PATH, and click edit.

Once you're in here, click New to add the folder path to your chrome.exe file. Like I said above, mine was found at:

C:\Program Files (x86)\Google\Chrome\Application

Click save and exit out of there. Then make sure you reboot your computer.

Hope this helps!

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

Use its value directly:

In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]: 
array([[ 0.98836259,  0.82403141],
       [ 0.337358  ,  0.02054435],
       [ 0.29271728,  0.37813099],
       [ 0.70033513,  0.69919695]])

What is the difference between dict.items() and dict.iteritems() in Python2?

It's part of an evolution.

Originally, Python items() built a real list of tuples and returned that. That could potentially take a lot of extra memory.

Then, generators were introduced to the language in general, and that method was reimplemented as an iterator-generator method named iteritems(). The original remains for backwards compatibility.

One of Python 3’s changes is that items() now return views, and a list is never fully built. The iteritems() method is also gone, since items() in Python 3 works like viewitems() in Python 2.7.

How to draw circle by canvas in Android?

Here is example to draw stroke circle canvas

val paint = Paint().apply {
    color = Color.RED
    style = Paint.Style.STROKE
    strokeWidth = 10f
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    canvas?.drawCircle(200f, 100f, 100f, paint)
}

Result

Example to draw solid circle canvas

val paint = Paint().apply {
    color = Color.RED
}

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    canvas?.drawCircle(200f, 100f, 100f, paint)
}

Result

Hope it help

Android and Facebook share intent

Seems in version 4.0.0 of Facebook so many things has changed. This is my code which is working fine. Hope it helps you.

    /**
     * Facebook does not support sharing content without using their SDK however
     * it is possible to share URL
     *
     * @param content
     * @param url
     */
    private void shareOnFacebook(String content, String url)
    {
        try
        {
            // TODO: This part does not work properly based on my test
            Intent fbIntent = new Intent(Intent.ACTION_SEND);
            fbIntent.setType("text/plain");
            fbIntent.putExtra(Intent.EXTRA_TEXT, content);
            fbIntent.putExtra(Intent.EXTRA_STREAM, url);
            fbIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            fbIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            fbIntent.setComponent(new ComponentName("com.facebook.katana",
                    "com.facebook.composer.shareintent.ImplicitShareIntentHandler"));

            startActivity(fbIntent);
            return;
        }
        catch (Exception e)
        {
            // User doesn't have Facebook app installed. Try sharing through browser.
        }

        // If we failed (not native FB app installed), try share through SEND
        String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + url;
        SupportUtils.doShowUri(this.getActivity(), sharerUrl);
    }

JWT authentication for ASP.NET Web API

I've managed to achieve it with minimal effort (just as simple as with ASP.NET Core).

For that I use OWIN Startup.cs file and Microsoft.Owin.Security.Jwt library.

In order for the app to hit Startup.cs we need to amend Web.config:

<configuration>
  <appSettings>
    <add key="owin:AutomaticAppStartup" value="true" />
    ...

Here's how Startup.cs should look:

using MyApp.Helpers;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;

[assembly: OwinStartup(typeof(MyApp.App_Start.Startup))]

namespace MyApp.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidAudience = ConfigHelper.GetAudience(),
                        ValidIssuer = ConfigHelper.GetIssuer(),
                        IssuerSigningKey = ConfigHelper.GetSymmetricSecurityKey(),
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true
                    }
                });
        }
    }
}

Many of you guys use ASP.NET Core nowadays, so as you can see it doesn't differ a lot from what we have there.

It really got me perplexed first, I was trying to implement custom providers, etc. But I didn't expect it to be so simple. OWIN just rocks!

Just one thing to mention - after I enabled OWIN Startup NSWag library stopped working for me (e.g. some of you might want to auto-generate typescript HTTP proxies for Angular app).

The solution was also very simple - I replaced NSWag with Swashbuckle and didn't have any further issues.


Ok, now sharing ConfigHelper code:

public class ConfigHelper
{
    public static string GetIssuer()
    {
        string result = System.Configuration.ConfigurationManager.AppSettings["Issuer"];
        return result;
    }

    public static string GetAudience()
    {
        string result = System.Configuration.ConfigurationManager.AppSettings["Audience"];
        return result;
    }

    public static SigningCredentials GetSigningCredentials()
    {
        var result = new SigningCredentials(GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256);
        return result;
    }

    public static string GetSecurityKey()
    {
        string result = System.Configuration.ConfigurationManager.AppSettings["SecurityKey"];
        return result;
    }

    public static byte[] GetSymmetricSecurityKeyAsBytes()
    {
        var issuerSigningKey = GetSecurityKey();
        byte[] data = Encoding.UTF8.GetBytes(issuerSigningKey);
        return data;
    }

    public static SymmetricSecurityKey GetSymmetricSecurityKey()
    {
        byte[] data = GetSymmetricSecurityKeyAsBytes();
        var result = new SymmetricSecurityKey(data);
        return result;
    }

    public static string GetCorsOrigins()
    {
        string result = System.Configuration.ConfigurationManager.AppSettings["CorsOrigins"];
        return result;
    }
}

Another important aspect - I sent JWT Token via Authorization header, so typescript code looks for me as follows:

(the code below is generated by NSWag)

@Injectable()
export class TeamsServiceProxy {
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
        this.http = http;
        this.baseUrl = baseUrl ? baseUrl : "https://localhost:44384";
    }

    add(input: TeamDto | null): Observable<boolean> {
        let url_ = this.baseUrl + "/api/Teams/Add";
        url_ = url_.replace(/[?&]$/, "");

        const content_ = JSON.stringify(input);

        let options_ : any = {
            body: content_,
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Content-Type": "application/json", 
                "Accept": "application/json",
                "Authorization": "Bearer " + localStorage.getItem('token')
            })
        };

See headers part - "Authorization": "Bearer " + localStorage.getItem('token')

MySQL connection not working: 2002 No such file or directory

I've installed MySQL using installer. In fact, there was no data directory alongside 'bin' directory.

So, I manually created the 'data' directory under "C:\Program Files\MySQL\MySQL Server 8.0". And it worked (changing the root password following steps suggested on https://dev.mysql.com/doc/mysql-windows-excerpt/5.7/en/resetting-permissions-windows.html.

Convert an image (selected by path) to base64 string

You can convert it like this

  string test = @"C:/image/1.gif";
  byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(test);
  string base64String = System.Convert.ToBase64String(bytes);
  Console.WriteLine("Base 64 string: " + base64String);

Output

  QzovaW1hZ2UvMS5naWY=

Benefits of EBS vs. instance-store (and vice-versa)

EBS is like the virtual disk of a VM:

  • Durable, instances backed by EBS can be freely started and stopped (saving money)
  • Can be snapshotted at any point in time, to get point-in-time backups
  • AMIs can be created from EBS snapshots, so the EBS volume becomes a template for new systems

Instance storage is:

  • Local, so generally faster
  • Non-networked, in normal cases EBS I/O comes at the cost of network bandwidth (except for EBS-optimized instances, which have separate EBS bandwidth)
  • Has limited I/O per second IOPS. Even provisioned I/O maxes out at a few thousand IOPS
  • Fragile. As soon as the instance is stopped, you lose everything in instance storage.

Here's where to use each:

  • Use EBS for the backing OS partition and permanent storage (DB data, critical logs, application config)
  • Use instance storage for in-process data, noncritical logs, and transient application state. Example: external sort storage, tempfiles, etc.
  • Instance storage can also be used for performance-critical data, when there's replication between instances (NoSQL DBs, distributed queue/message systems, and DBs with replication)
  • Use S3 for data shared between systems: input dataset and processed results, or for static data used by each system when lauched.
  • Use AMIs for prebaked, launchable servers

Override element.style using CSS

As per my knowledge Inline sytle comes first so css class should not work.

Use Jquery as

$(document).ready(function(){

   $("#demoFour li").css("display","inline");
  });

You can also try 

#demoFour li { display:inline !important;}

How do I check the operating system in Python?

If you want to know on which platform you are on out of "Linux", "Windows", or "Darwin" (Mac), without more precision, you should use:

>>> import platform
>>> platform.system()
'Linux'  # or 'Windows'/'Darwin'

The platform.system function uses uname internally.

Converting a view to Bitmap without displaying it in Android?

here is my solution:

public static Bitmap getBitmapFromView(View view) {
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable =view.getBackground();
    if (bgDrawable!=null) 
        bgDrawable.draw(canvas);
    else 
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
}

Enjoy :)

How I could add dir to $PATH in Makefile?

Path changes appear to be persistent if you set the SHELL variable in your makefile first:

SHELL := /bin/bash
PATH := bin:$(PATH)

test all:
    x

I don't know if this is desired behavior or not.

Deep copy, shallow copy, clone

  • Deep copy: Clone this object and every reference to every other object it has
  • Shallow copy: Clone this object and keep its references
  • Object clone() throws CloneNotSupportedException: It is not specified whether this should return a deep or shallow copy, but at the very least: o.clone() != o

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

How to remove origin from git repository

Fairly straightforward:

git remote rm origin

As for the filter-branch question - just add --prune-empty to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:

git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD

Correct way to pause a Python program

I think I like this solution:

import getpass
getpass.getpass("Press Enter to Continue")

It hides whatever the user types in, which helps clarify that input is not used here.

But be mindful on the OS X platform. It displays a key which may be confusing.

It shows a key, like I said


Probably the best solution would be to do something similar to the getpass module yourself, without making a read -s call. Maybe making the foreground color match the background?

C# "as" cast vs classic cast

There's nothing deep happening here.. Basically, it's handy to test something to see if it's of a certain type (i.e. use 'as'). You would want to check the result of the 'as' call to see if the result is null.

When you expect a cast to work and you want the exception to be thrown, use the 'classic' method.

How can I make a UITextField move up when the keyboard is present - on starting to edit?

i had an issue with reseting to default main view while changing the text field or editing it's content (for example phone textfield and adding '-' sign, and view goes back covering textfields) i finnaly overcome this by using auto layout and changing constraints constant, not frame size or position in notification delegates functions, like this:

P.S. I'm not using scrollview just simple move view up, but it should work similar

func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
    if !keyboardIsShown{
        self.infoViewTopConstraint.constant -= keyboardSize.height
        self.infoViewBottomConstraint.constant += keyboardSize.height
        self.view.setNeedsLayout()
        self.view.layoutIfNeeded()
        keyboardIsShown = true
    }
}

func keyboardWillHide(notification: NSNotification) {
if keyboardIsShown {
    self.infoViewTopConstraint.constant += keyboardSize.height
    self.infoViewBottomConstraint.constant -= keyboardSize.height
    self.view.setNeedsLayout()
    self.view.layoutIfNeeded()
    keyboardIsShown = false
}

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

I was having the same problem. Turns out in my case, I was missing the comma after the last column. 30 minutes of my life wasted, I will never get back!

enter image description here

Ternary operator ?: vs if...else

Regardless the compiled code, They are semantically different thing. <cond>?<true expr>:<false expr> is an expression and if..else.. is a statement.

Although the syntax of conditional expression seems awkward, it is a good thing. You are forced to provide a <false expr> and the two expressions are type checked.

The equivalent to if..else.. in expression-based, functional language like Lisp, Haskell is ? : in C++, instead of if..else.. statement.

jQuery - Disable Form Fields

try this

$("#inp").focus(function(){$("#sel").attr('disabled','true');});

$("#inp").blur(function(){$("#sel").removeAttr('disabled');});

vice versa for the select also.

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

For people who find this when attempting to run tests because via npm test or ng test using Karma or whatever else. Your .spec module needs a special router testing import to be able to build.

import { RouterTestingModule } from '@angular/router/testing';

TestBed.configureTestingModule({
    imports: [RouterTestingModule],
    declarations: [AppComponent],
});

http://www.kirjai.com/ng2-component-testing-routerlink-routeroutlet/

Render partial from different folder (not shared)

you should try this

~/Views/Shared/parts/UMFview.ascx

place the ~/Views/ before your code

Install pip in docker

This command worked fine for me:

RUN apt-get -y install python3-pip

How to overwrite existing files in batch?

Here's what worked for me to copy and overwrite a file from B:\ to Z:\ drive in a batch script.

echo F| XCOPY B:\utils\MyFile.txt Z:\Backup\CopyFile.txt /Y

The "/Y" parameter at the end overwrites the destination file, if it exists.

Publish to IIS, setting Environment Variable

@tredder solution with editing applicationHost.config is the one that works if you have several different applications located within virtual directories on IIS.

My case is:

  • I do have API project and APP project, under the same domain, placed in different virtual directories
  • Root page XXX doesn't seem to propagate ASPNETCORE_ENVIRONMENT variable to its children in virtual directories and...
  • ...I'm unable to set the variables inside the virtual directory as @NickAb described (got error The request is not supported. (Exception from HRESULT: 0x80070032) during saving changes in Configuration Editor):
  • Going into applicationHost.config and manually creating nodes like this:

    <location path="XXX/app"> <system.webServer> <aspNetCore> <environmentVariables> <clear /> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </aspNetCore> </system.webServer> </location> <location path="XXX/api"> <system.webServer> <aspNetCore> <environmentVariables> <clear /> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </aspNetCore> </system.webServer> </location>

and restarting the IIS did the job.

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

Multiple conditions in WHILE loop

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

Git removing upstream from local repository

$ git remote remove <name>

ie.

$ git remote remove upstream

that should do the trick

AngularJS - Passing data between pages

What you should do is create a service to share data between controllers.

Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk

What is the difference between __init__ and __call__?

__call__ allows to return arbitrary values, while __init__ being an constructor returns the instance of class implicitly. As other answers properly pointed out, __init__ is called just once, while it's possible to call __call__ multiple times, in case the initialized instance is assigned to intermediate variable.

>>> class Test:
...     def __init__(self):
...         return 'Hello'
... 
>>> Test()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: __init__() should return None, not 'str'
>>> class Test2:
...     def __call__(self):
...         return 'Hello'
... 
>>> Test2()()
'Hello'
>>> 
>>> Test2()()
'Hello'
>>> 

Getting the class name from a static method in Java

If you are using reflection, you can get the Method object and then:

method.getDeclaringClass().getName()

To get the Method itself, you can probably use:

Class<?> c = Class.forName("class name");
Method  method = c.getDeclaredMethod ("method name", parameterTypes)

jQuery UI - Close Dialog When Clicked Outside

I had to do two parts. First the outside click-handler:

$(document).on('click', function(e){
    if ($(".ui-dialog").length) {
        if (!$(e.target).parents().filter('.ui-dialog').length) {
            $('.ui-dialog-content').dialog('close');
        }
    }
}); 

This calls dialog('close') on the generic ui-dialog-content class, and so will close all dialogs if the click didn't originate in one. It will work with modal dialogs too, since the overlay is not part of the .ui-dialog box.

The problem is:

  1. Most dialogs are created because of clicks outside of a dialog
  2. This handler runs after those clicks have created a dialog and bubbled up to the document, so it immediately closes them.

To fix this, I had to add stopPropagation to those click handlers:

moreLink.on('click', function (e) {
    listBox.dialog();
    e.stopPropagation(); //Don't trigger the outside click handler
});

json_encode() escaping forward slashes

On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -

my expected:

http://localhost/api/v1/admin/logs/testLog.log

would be encoded to:

http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log

If you need to do a comparison, transforming the url using:

addcslashes($url, '/')

allowed for the proper output during my comparisons.

python 2.7: cannot pip on windows "bash: pip: command not found"

  1. press [win] + Pause
  2. Advanced settings
  3. System variables
  4. Append ;C:\python27\Scripts to the end of Path variable
  5. Restart console

Given a URL to a text file, what is the simplest way to read the contents of the text file?

There's really no need to read line-by-line. You can get the whole thing like this:

import urllib
txt = urllib.urlopen(target_url).read()

Cycles in an Undirected Graph

By the way, if you happen to know that it is connected, then simply it is a tree (thus no cycles) if and only if |E|=|V|-1. Of course that's not a small amount of information :)

Python Dictionary Comprehension

You can use the dict.fromkeys class method ...

>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}

This is the fastest way to create a dictionary where all the keys map to the same value.

But do not use this with mutable objects:

d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!

If you don't actually need to initialize all the keys, a defaultdict might be useful as well:

from collections import defaultdict
d = defaultdict(True)

To answer the second part, a dict-comprehension is just what you need:

{k: k for k in range(10)}

You probably shouldn't do this but you could also create a subclass of dict which works somewhat like a defaultdict if you override __missing__:

>>> class KeyDict(dict):
...    def __missing__(self, key):
...       #self[key] = key  # Maybe add this also?
...       return key
... 
>>> d = KeyDict()
>>> d[1]
1
>>> d[2]
2
>>> d[3]
3
>>> print(d)
{}

Youtube - downloading a playlist - youtube-dl

I found the best solution after many attempts for this problem.

youtube-dl --ignore-errors --format bestaudio --extract-audio --audio-format mp3 --audio-quality 160K --output "%(title)s.%(ext)s" --yes-playlist https://www.youtube.com/playlist?list={your-youtube-playlist-id}

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

What I am thinking is having webpack would be easy when production release.

FYI : https://github.com/Piusha/ngx-lazyloading

How to sort a List of objects by their date (java collections, List<Object>)

You can use this:

Collections.sort(list, org.joda.time.DateTimeComparator.getInstance());

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

My solution below is for cases when default maven repositories are not accessible (e.g. due to firewalls).

In case the default repository is not accessible appropriate local <pluginRepository> has to be specified in the settings.xml. If it's the same as your local artifact repository it still needs to be added to the <pluginRepositories> section for plugin jars to be found. Regular <repositories> section is not used to fetch plugin jars.

In my case, however, the issue was caused by the fact that there were multiple plugin repositories defined in that section.

The first repository in the list did not contain the required maven-filtering jar.

I had to change the order of <pluginRepository> definitions to ensure the first one contains maven-filtering.

Changing of repository definitions typically requires to clean ~/.m2/repository and start fresh.

Run jar file in command prompt

If you dont have an entry point defined in your manifest invoking java -jar foo.jar will not work.

Use this command if you dont have a manifest or to run a different main class than the one specified in the manifest:

java -cp foo.jar full.package.name.ClassName

See also instructions on how to create a manifest with an entry point: https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

What's the fastest way to convert String to Number in JavaScript?

There are 4 ways to do it as far as I know.

Number(x);
parseInt(x, 10);
parseFloat(x);
+x;

By this quick test I made, it actually depends on browsers.

http://jsperf.com/best-of-string-to-number-conversion/2

Implicit marked the fastest on 3 browsers, but it makes the code hard to read… So choose whatever you feel like it!

Reading content from URL with Node.js

HTTP and HTTPS:

const getScript = (url) => {
    return new Promise((resolve, reject) => {
        const http      = require('http'),
              https     = require('https');

        let client = http;

        if (url.toString().indexOf("https") === 0) {
            client = https;
        }

        client.get(url, (resp) => {
            let data = '';

            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            });

            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(data);
            });

        }).on("error", (err) => {
            reject(err);
        });
    });
};

(async (url) => {
    console.log(await getScript(url));
})('https://sidanmor.com/');

What is the meaning of 'No bundle URL present' in react-native?

I have found the easiest/quickest way to bypass this is to exit the app within the simulator (2 x Cmd + Shift + H) and re-launch.

Checking if jquery is loaded using Javascript

if ('undefined' == typeof window.jQuery) {
    // jQuery not present
} else {
    // jQuery present
}

How to find current transaction level?

DECLARE   @UserOptions TABLE(SetOption varchar(100), Value varchar(100))
DECLARE   @IsolationLevel varchar(100)

INSERT    @UserOptions
EXEC('DBCC USEROPTIONS WITH NO_INFOMSGS')

SELECT    @IsolationLevel = Value
FROM      @UserOptions
WHERE     SetOption = 'isolation level'

-- Do whatever you want with the variable here...  
PRINT     @IsolationLevel

What is the python "with" statement designed for?

An example of an antipattern might be to use the with inside a loop when it would be more efficient to have the with outside the loop

for example

for row in lines:
    with open("outfile","a") as f:
        f.write(row)

vs

with open("outfile","a") as f:
    for row in lines:
        f.write(row)

The first way is opening and closing the file for each row which may cause performance problems compared to the second way with opens and closes the file just once.

Java to Jackson JSON serialization: Money fields

I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

If you don't want any decimals when the resulting decimals are all zeroes, something like this would work:

String fixedDecimals(double d, int decimals, {bool removeZeroDecimals = true}){
  double mod = pow(10.0, decimals);
  double result = ((d * mod).round().toDouble() / mod);
  if( removeZeroDecimals && result - (result.truncate()) == 0.0 ) decimals = 0;
  return result.toStringAsFixed(decimals);
}

This will simply output 9 instead of 9.00 if the input is 9.004 and you want 2 decimals.

SQL Server query - Selecting COUNT(*) with DISTINCT

SELECT COUNT(DISTINCT program_name) AS Count, program_type AS [Type] 
FROM cm_production 
WHERE push_number=@push_number 
GROUP BY program_type

Serial Port (RS -232) Connection in C++

Please take a look here:

1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.

2) Step-by-step tutorial how to use serial ports on windows

3) You can use this literally on MinGW

Here's some very, very simple code (without any error handling or settings):

#include <windows.h>

/* ... */


// Open serial port
HANDLE serialHandle;

serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);

GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);

// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;

SetCommTimeouts(serialHandle, &timeout);

Now you can use WriteFile() / ReadFile() to write / read bytes. Don't forget to close your connection:

CloseHandle(serialHandle);

Finding height in Binary Search Tree

class Solution{
    public static int getHeight(Node root) {
        int height = -1;

        if (root == null) {
            return height;
        } else {
            height = 1 + Math.max(getHeight(root.left), getHeight(root.right));
        }

        return height;
    }

Difference between application/x-javascript and text/javascript content types

mime-types starting with x- are not standardized. In case of javascript it's kind of outdated. Additional the second code snippet

<?Header('Content-Type: text/javascript');?>

requires short_open_tags to be enabled. you should avoid it.

<?php Header('Content-Type: text/javascript');?>

However, the completely correct mime-type for javascript is

application/javascript

http://www.iana.org/assignments/media-types/application/index.html

Sending emails with Javascript

You can use this free service: https://www.smtpjs.com

  1. Include the script:

<script src="https://smtpjs.com/v2/smtp.js"></script>

  1. Send an email using:
Email.send(
  "[email protected]",
  "[email protected]",
  "This is a subject",
  "this is the body",
  "smtp.yourisp.com",
  "username",
  "password"
);

How do you configure an OpenFileDialog to select folders?

On Vista you can use IFileDialog with FOS_PICKFOLDERS option set. That will cause display of OpenFileDialog-like window where you can select folders:

var frm = (IFileDialog)(new FileOpenDialogRCW());
uint options;
frm.GetOptions(out options);
options |= FOS_PICKFOLDERS;
frm.SetOptions(options);

if (frm.Show(owner.Handle) == S_OK) {
    IShellItem shellItem;
    frm.GetResult(out shellItem);
    IntPtr pszString;
    shellItem.GetDisplayName(SIGDN_FILESYSPATH, out pszString);
    this.Folder = Marshal.PtrToStringAuto(pszString);
}

For older Windows you can always resort to trick with selecting any file in folder.

Working example that works on .NET Framework 2.0 and later can be found here.

How to generate .env file for laravel?

If the .env a file is missing, then there is another way to generate a .env file

You can download env.example, rename it to .env and edit it. Just set up correct DB credentials etc.

Don't forget to When you use the php artisan key:generate it will generate the new key to your .env file

How to apply `git diff` patch without Git installed?

I use

patch -p1 --merge < patchfile

This way, conflicts may be resolved as usual.

How to add/subtract dates with JavaScript?

The best date utility I've used is date-fns for a few reasons:

  • Uses the native JavaScript Date format.
  • Immutable; built using pure functions and always returns a new date instance instead of changing the passed one.
  • Modular; import just the functions you need.

Package manager:

"date-fns": "^1.30.1"

Code:

import { addDays, subDays } from 'date-fns'

let today = new Date()
let yesterday = subDays(today, 1)
let tomorrow = addDays(today, 1)

Simple and awesome.

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

Better way to find control in ASP.NET

I decided to just build controls dictionaries. Harder to maintain, might run faster than the recursive FindControl().

protected void Page_Load(object sender, EventArgs e)
{
  this.BuildControlDics();
}

private void BuildControlDics()
{
  _Divs = new Dictionary<MyEnum, HtmlContainerControl>();
  _Divs.Add(MyEnum.One, this.divOne);
  _Divs.Add(MyEnum.Two, this.divTwo);
  _Divs.Add(MyEnum.Three, this.divThree);

}

And before I get down-thumbs for not answering the OP's question...

Q: Now, my question is that is there any other way/solution to find the nested control in ASP.NET? A: Yes, avoid the need to search for them in the first place. Why search for things you already know are there? Better to build a system allowing reference of known objects.

Mixing a PHP variable with a string literal

You can use {} arround your variable, to separate it from what's after:

echo "{$test}y"

As reference, you can take a look to the Variable parsing - Complex (curly) syntax section of the PHP manual.

How to write string literals in python without having to escape them?

Raw string literals:

>>> r'abc\dev\t'
'abc\\dev\\t'

bash string compare to multiple correct values

If the main intent is to check whether the supplied value is not found in a list, maybe you can use the extended regular expression matching built in BASH via the "equal tilde" operator (see also this answer):

if ! [[ "$cms" =~ ^(wordpress|meganto|typo3)$ ]]; then get_cms ; fi

Have a nice day

Return file in ASP.Net Core Web API

You can return FileResult with this methods:

1: Return FileStreamResult

    [HttpGet("get-file-stream/{id}"]
    public async Task<FileStreamResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var stream = await GetFileStreamById(id);

        return new FileStreamResult(stream, mimeType)
        {
            FileDownloadName = fileName
        };
    }

2: Return FileContentResult

    [HttpGet("get-file-content/{id}"]
    public async Task<FileContentResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var fileBytes = await GetFileBytesById(id);

        return new FileContentResult(fileBytes, mimeType)
        {
            FileDownloadName = fileName
        };
    }

CodeIgniter: "Unable to load the requested class"

I had a similar issue when deploying from OSx on my local to my Linux live site.

It ran fine on OSx, but on Linux I was getting:

An Error Was Encountered

Unable to load the requested class: Ckeditor

The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

I also changed my load call to match the capitalization:

$this->load->library('CKEditor');

Calling a method every x minutes

Example of using a Timer:

using System;
using System.Timers;

static void Main(string[] args)
{
    Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
    t.AutoReset = true;
    t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
    t.Start();
}

// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("..."); 
}

Iterating on a file doesn't work the second time

Yes, that is normal behavior. You basically read to the end of the file the first time (you can sort of picture it as reading a tape), so you can't read any more from it unless you reset it, by either using f.seek(0) to reposition to the start of the file, or to close it and then open it again which will start from the beginning of the file.

If you prefer you can use the with syntax instead which will automatically close the file for you.

e.g.,

with open('baby1990.html', 'rU') as f:
  for line in f:
     print line

once this block is finished executing, the file is automatically closed for you, so you could execute this block repeatedly without explicitly closing the file yourself and read the file this way over again.

How do I manually configure a DataSource in Java?

use MYSQL as Example: 1) use database connection pools: for Example: Apache Commons DBCP , also, you need basicDataSource jar package in your classpath

@Bean
public BasicDataSource dataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/gene");
    ds.setUsername("root");
    ds.setPassword("root");
    return ds;
}

2)use JDBC-based Driver it is usually used if you don't consider connection pool:

@Bean
public DataSource dataSource(){
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/gene");
    ds.setUsername("root");
    ds.setPassword("root");
    return ds;
}

How to find the mysql data directory from command line in windows

You can issue the following query from the command line:

mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name LIKE "%dir"'

Output (on Linux):

+---------------------------+----------------------------+
| Variable_name             | Value                      |
+---------------------------+----------------------------+
| basedir                   | /usr                       |
| character_sets_dir        | /usr/share/mysql/charsets/ |
| datadir                   | /var/lib/mysql/            |
| innodb_data_home_dir      |                            |
| innodb_log_group_home_dir | ./                         |
| lc_messages_dir           | /usr/share/mysql/          |
| plugin_dir                | /usr/lib/mysql/plugin/     |
| slave_load_tmpdir         | /tmp                       |
| tmpdir                    | /tmp                       |
+---------------------------+----------------------------+

Output (on macOS Sierra):

+---------------------------+-----------------------------------------------------------+
| Variable_name             | Value                                                     |
+---------------------------+-----------------------------------------------------------+
| basedir                   | /usr/local/mysql-5.7.17-macos10.12-x86_64/                |
| character_sets_dir        | /usr/local/mysql-5.7.17-macos10.12-x86_64/share/charsets/ |
| datadir                   | /usr/local/mysql/data/                                    |
| innodb_data_home_dir      |                                                           |
| innodb_log_group_home_dir | ./                                                        |
| innodb_tmpdir             |                                                           |
| lc_messages_dir           | /usr/local/mysql-5.7.17-macos10.12-x86_64/share/          |
| plugin_dir                | /usr/local/mysql/lib/plugin/                              |
| slave_load_tmpdir         | /var/folders/zz/zyxvpxvq6csfxvn_n000009800002_/T/         |
| tmpdir                    | /var/folders/zz/zyxvpxvq6csfxvn_n000009800002_/T/         |
+---------------------------+-----------------------------------------------------------+

Or if you want only the data dir use:

mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"'

These commands work on Windows too, but you need to invert the single and double quotes.

Btw, when executing which mysql in Linux as you told, you'll not get the installation directory on Linux. You'll only get the binary path, which is /usr/bin on Linux, but you see the mysql installation is using multiple folders to store files.


If you need the value of datadir as output, and only that, without column headers etc, but you don't have a GNU environment (awk|grep|sed ...) then use the following command line:

mysql -s -N -uUSER -p information_schema -e 'SELECT Variable_Value FROM GLOBAL_VARIABLES WHERE Variable_Name = "datadir"'

The command will select the value only from mysql's internal information_schema database and disables the tabular output and column headers.

Output on Linux:

/var/lib/mysql

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

The normal layout for a maven multi module project is:

parent
+-- pom.xml
+-- module
    +-- pom.xml

Check that you use this layout.

Additionally:

  1. the relativePath looks strange. Instead of '..'

    <relativePath>..</relativePath>
    

    try '../' instead:

    <relativePath>../</relativePath>
    

    You can also remove relativePath if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.

  2. The module path may be wrong. In the parent you define the module as:

    <module>junitcategorizer.cutdetection</module>
    

    You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection is not the name of the folder than change it accordingly.

Hope that helps..

EDIT have a look at the other post, I answered there.

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():
    print(vars(class_instance))

session.close()

Printing a java map Map<String, Object> - How?

There is a get method in HashMap:

for (String keys : objectSet.keySet())  
{
   System.out.println(keys + ":"+ objectSet.get(keys));
}

javascript /jQuery - For Loop

What about something like this?

var arr = [];

$('[id^=event]', response).each(function(){
    arr.push($(this).html());
});

The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

How can I use tabs for indentation in IntelliJ IDEA?

Have you tried .editorconfig? You can create this file in the root of your project and configure indentation for different file types. Your code will be automatically formatted. Here's the example:

# top-most EditorConfig file
root = true

# matches all files
[*]
indent_style = tab
indent_size = 4

# only json
[*.json]
indent_style = space
indent_size = 2

Git error on commit after merge - fatal: cannot do a partial commit during a merge

I got this when I forgot the -m in my git commit when resolving a git merge conflict.

git commit "commit message"

should be

git commit -m "commit message"

What is a good alternative to using an image map generator?

There is also Mappa - http://mappatool.com/.

It only supports polygons, but they are definitely the hardest parts :)

How to test if a string contains one of the substrings in a list, in pandas?

You can use str.contains alone with a regex pattern using OR (|):

s[s.str.contains('og|at')]

Or you could add the series to a dataframe then use str.contains:

df = pd.DataFrame(s)
df[s.str.contains('og|at')] 

Output:

0 cat
1 hat
2 dog
3 fog 

Which data type for latitude and longitude?

You can use the data type point - combines (x,y) which can be your lat / long. Occupies 16 bytes: 2 float8 numbers internally.

Or make it two columns of type float (= float8 or double precision). 8 bytes each.
Or real (= float4) if additional precision is not needed. 4 bytes each.
Or even numeric if you need absolute precision. 2 bytes for each group of 4 digits, plus 3 - 8 bytes overhead.

Read the fine manual about numeric types and geometric types.


The geometry and geography data types are provided by the additional module PostGIS and occupy one column in your table. Each occupies 32 bytes for a point. There is some additional overhead like an SRID in there. These types store (long/lat), not (lat/long).

Start reading the PostGIS manual here.

How to iterate over a std::map full of strings in C++

Use:

std::map<std::string, std::string>::const_iterator

instead:

std::map<std::string, std::string>::iterator

Memory errors and list limits?

There is no memory limit imposed by Python. However, you will get a MemoryError if you run out of RAM. You say you have 20301 elements in the list. This seems too small to cause a memory error for simple data types (e.g. int), but if each element itself is an object that takes up a lot of memory, you may well be running out of memory.

The IndexError however is probably caused because your ListTemp has got only 19767 elements (indexed 0 to 19766), and you are trying to access past the last element.

It is hard to say what you can do to avoid hitting the limit without knowing exactly what it is that you are trying to do. Using numpy might help. It looks like you are storing a huge amount of data. It may be that you don't need to store all of it at every stage. But it is impossible to say without knowing.

How to solve time out in phpmyadmin?

I had the same issue and I used command line in order to import the SQL file. This method has 3 advantages:

  1. It is a very easy way by running only 1 command line
  2. It runs way faster
  3. It does not have limitation

If you want to do this just follow this 3 steps:

  1. Navigate to this path (i use wamp):

    C:\wamp\bin\mysql\mysql5.6.17\bin>

  2. Copy your sql file inside this path (ex file.sql)

  3. Run this command:

    mysql -u username -p database_name < file.sql

Note: if you already have your msql enviroment variable path set, you don't need to move your file.sql in the bin directory and you should only navigate to the path of the file.

PDOException SQLSTATE[HY000] [2002] No such file or directory

Check your port carefully . In my case it was 8889 and i am using 8888. change "DB_HOST" from "localhost" to "127.0.0.1" and vice versa

javax.net.ssl.SSLException: Received fatal alert: protocol_version

This is due to the fact that you send a TLSv1 handshake, but then you send a message using SSLv2 protocol;

xxx, WRITE: TLSv1 Handshake, length = 75
xxx, WRITE: SSLv2 client hello message, length = 101

This means that the server expects the TLSv1 protocol to be used and will not accept the connection. Try specifying which protocol to use, or post some relevant code so we can have a look

unary operator expected in shell script when comparing null value with string

Since the value of $var is the empty string, this:

if [ $var == $var1 ]; then

expands to this:

if [ == abcd ]; then

which is a syntax error.

You need to quote the arguments:

if [ "$var" == "$var1" ]; then

You can also use = rather than ==; that's the original syntax, and it's a bit more portable.

If you're using bash, you can use the [[ syntax, which doesn't require the quotes:

if [[ $var = $var1 ]]; then

Even then, it doesn't hurt to quote the variable reference, and adding quotes:

if [[ "$var" = "$var1" ]]; then

might save a future reader a moment trying to remember whether [[ ... ]] requires them.

Is it not possible to define multiple constructors in Python?

For the example you gave, use default values:

class City:
    def __init__(self, name="Default City Name"):
        ...
    ...

In general, you have two options:

1) Do if-elif blocks based on the type:

def __init__(self, name):
    if isinstance(name, str):
        ...
    elif isinstance(name, City):
        ...
    ...

2) Use duck typing --- that is, assume the user of your class is intelligent enough to use it correctly. This is typically the preferred option.

How to skip "are you sure Y/N" when deleting files in batch files

Add /Q for quiet mode and it should remove the prompt.

Angular 2: Passing Data to Routes?

It changes in angular 2.1.0

In something.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
const routes = [
  {
    path: '',
    component: BlogComponent
  },
  {
    path: 'add',
    component: AddComponent
  },
  {
    path: 'edit/:id',
    component: EditComponent,
    data: {
      type: 'edit'
    }
  }

];
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
    MaterialModule.forRoot(),
    FormsModule
  ],
  declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }

To get the data or params in edit component

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {

    this.route.snapshot.params['id'];
    this.route.snapshot.data['type'];

  }
}

Draw radius around a point in Google map

It seems that the most common method of achieving this is to draw a GPolygon with enough points to simulate a circle. The example you referenced uses this method. This page has a good example - look for the function drawCircle in the source code.

How to attach a process in gdb

The first argument should be the path to the executable program. So

gdb progname 12271

What is "git remote add ..." and "git push origin master"?

Update: note that the currently accepted answer perpetuates a common misunderstanding about the behaviour of git push, which hasn't been corrected despite a comment pointing it out.

Your summary of what remotes are - like a nickname for the URL of a repository - is correct.

So why does the URL not git://[email protected]/peter/first_app.git but in the other syntax -- what syntax is it? Why must it end with .git? I tried not using .git at the end and it works too. If not .git, what else can it be? The git at the beginner seems to be a user account on the git server?

The two URLs that you've mentioned indicate that two different transport protocols should be used. The one beginning with git:// is for the git protocol, which is usually only used for read-only access to repositories. The other one, [email protected]:peter/first_app.git, is one of the different ways of specifying access to a repository over SSH - this is the "scp-style syntax" described in the documentation. That the username in the scp-style syntax is git is because of the way that GitHub deals with identifying users - essentially that username is ignored, and the user is identified based on the SSH key-pair that they used to authenticate.

As for the verbosity of git push origin master, you've noticed that after the first push, you can then just do git push. This is because of a series of difficult-to-remember-but-generally-helpful defaults :)

  • If no remote is specified, the remote configured for the current branch (in remote.master.url in your case) is used. If that's not set up, then origin is used.
  • If there's no "refspec" (e.g. master, master:my-experiment, etc.) specified, then git defaults to pushing every local branch that has the same name as a branch on the remote. If you just have a branch called master in common between your repository and the remote one, that'll be the same as pushing your master to the remote master.

Personally, since I tend to have many topic branches (and often several remotes) I always use the form:

git push origin master

... to avoid accidentally pushing other branches.


In reply to your comments on one of the other answers, it sounds to me as if are learning about git in a top-down way very effectively - you've discovered that the defaults work, and your question is asking about why ;) To be more serious, git can be used essentially as simply as SVN, but knowing a bit about remotes and branches means you can use it much more flexibily and this can really change the way you work for the better. Your remark about a semester course makes me think of something Scott Chacon said in a podcast interview - students are taught about all kinds of basic tools in computer science and software engineering, but very rarely version control. Distributed version control systems such as git and Mercurial are now so important, and so flexible, that it would be worth teaching courses on them to give people a good grounding.

My view is that with git, this learning curve is absolutely worth it - working with lots of topic branches, merging them easily, and pushing and pulling them about between different repositories is fantastically useful once you become confident with the system. It's just unfortunate that:

  • The primary documentation for git is so hard to parse for newcomers. (Although I'd argue that if you Google for almost any git question, helpful tutorial material (or Stack Overflow answers :)) come up nowadays.)
  • There are a few odd behaviours in git that are hard to change now because many scripts may rely on them, but are confusing to people.

Open a file with Notepad in C#

You can use Process.Start, calling notepad.exe with the file as a parameter.

 Process.Start(@"notepad.exe", pathToFile);

Copying a local file from Windows to a remote server using scp

Drive letters can be used in the target like

scp some_file user@host:/c/temp

where c is the drive letter. It's treated like a directory.

Maybe this works on the source, too.

Circular (or cyclic) imports in Python

Cyclic imports terminate, but you need to be careful not to use the cyclically-imported modules during module initialization.

Consider the following files:

a.py:

print "a in"
import sys
print "b imported: %s" % ("b" in sys.modules, )
import b
print "a out"

b.py:

print "b in"
import a
print "b out"
x = 3

If you execute a.py, you'll get the following:

$ python a.py
a in
b imported: False
b in
a in
b imported: True
a out
b out
a out

On the second import of b.py (in the second a in), the Python interpreter does not import b again, because it already exists in the module dict.

If you try to access b.x from a during module initialization, you will get an AttributeError.

Append the following line to a.py:

print b.x

Then, the output is:

$ python a.py
a in                    
b imported: False
b in
a in
b imported: True
a out
Traceback (most recent call last):
  File "a.py", line 4, in <module>
    import b
  File "/home/shlomme/tmp/x/b.py", line 2, in <module>
    import a
 File "/home/shlomme/tmp/x/a.py", line 7, in <module>
    print b.x
AttributeError: 'module' object has no attribute 'x'

This is because modules are executed on import and at the time b.x is accessed, the line x = 3 has not be executed yet, which will only happen after b out.

Place API key in Headers or URL

If you want an argument that might appeal to a boss: Think about what a URL is. URLs are public. People copy and paste them. They share them, they put them on advertisements. Nothing prevents someone (knowingly or not) from mailing that URL around for other people to use. If your API key is in that URL, everybody has it.

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

Using pip behind a proxy with CNTLM

This worked for me (on Windows via CMD):

pip install --proxy proxyserver:port requests

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

Adding multiple columns AFTER a specific column in MySQL

If you want to add a single column after a specific field, then the following MySQL query should work:

ALTER TABLE users
    ADD COLUMN count SMALLINT(6) NOT NULL
    AFTER lastname

If you want to add multiple columns, then you need to use 'ADD' command each time for a column. Here is the MySQL query for this:

ALTER TABLE users
    ADD COLUMN count SMALLINT(6) NOT NULL,
    ADD COLUMN log VARCHAR(12) NOT NULL,
    ADD COLUMN status INT(10) UNSIGNED NOT NULL
    AFTER lastname

Point to note

In the second method, the last ADD COLUMN column should actually be the first column you want to append to the table.

E.g: if you want to add count, log, status in the exact order after lastname, then the syntax would actually be:

ALTER TABLE users
    ADD COLUMN log VARCHAR(12) NOT NULL AFTER lastname,
    ADD COLUMN status INT(10) UNSIGNED NOT NULL AFTER lastname,
    ADD COLUMN count SMALLINT(6) NOT NULL AFTER lastname
    

‘ant’ is not recognized as an internal or external command

even with the environment variables set, I found that ant -version does not work in scripts. Try call ant -version

What is the difference between iterator and iterable and how to use them?

The most important consideration is whether the item in question should be able to be traversed more than once. This is because you can always rewind an Iterable by calling iterator() again, but there is no way to rewind an Iterator.

Android Studio-No Module

I was able to resolve this issue by performing a Gradle sync

To do this:

  1. In project view, right click the root (in my example below, "JamsMusicPlayer"

  2. Click "Synchronize {ProjectName}"

  3. Once this completes, you should see a module in your "Run" dialog

Gradle sync

Auto-indent in Notepad++

This may seem silly, but in the original question, Turion was editing a plain text file. Make sure you choose the correct language from the Language menu

Remove tracking branches no longer on remote

Windows Solution

For Microsoft Windows Powershell:

git checkout master; git remote update origin --prune; git branch -vv | Select-String -Pattern ": gone]" | % { $_.toString().Trim().Split(" ")[0]} | % {git branch -d $_}

Explaination

git checkout master switches to the master branch

git remote update origin --prune prunes remote branches

git branch -vv gets a verbose output of all branches (git reference)

Select-String -Pattern ": gone]" gets only the records where they have been removed from remote.

% { $_.toString().Trim().Split(" ")[0]} get the branch name

% {git branch -d $_} deletes the branch

https connection using CURL from command line

I had the same problem - I was fetching a page from my own site, which was served over HTTPS, but curl was giving the same "SSL certificate problem" message. I worked around it by adding a -k flag to the call to allow insecure connections.

curl -k https://whatever.com/script.php

Edit: I discovered the root of the problem. I was using an SSL certificate (from StartSSL, but I don't think that matters much) and hadn't set up the intermediate certificate properly. If you're having the same problem as user1270392 above, it's probably a good idea to test your SSL cert and fix any issues with it before resorting to the curl -k fix.

OperationalError: database is locked

From django doc:

SQLite is meant to be a lightweight database, and thus can't support a high level of concurrency. OperationalError: database is locked errors indicate that your application is experiencing more concurrency than sqlite can handle in default configuration. This error means that one thread or process has an exclusive lock on the database connection and another thread timed out waiting for the lock the be released.

Python's SQLite wrapper has a default timeout value that determines how long the second thread is allowed to wait on the lock before it times out and raises the OperationalError: database is locked error.

If you're getting this error, you can solve it by:

  • Switching to another database backend. At a certain point SQLite becomes too "lite" for real-world applications, and these sorts of concurrency errors indicate you've reached that point.
  • Rewriting your code to reduce concurrency and ensure that database transactions are short-lived.
  • Increase the default timeout value by setting the timeout database option

http://docs.djangoproject.com/en/dev/ref/databases/#database-is-locked-errorsoption

Init function in javascript and how it works

I can't believe no-one has answered the ops question!

The last set of brackets are used for passing in the parameters to the anonymous function. So, the following example creates a function, then runs it with the x=5 and y=8

(function(x,y){
    //code here
})(5,8)

This may seem not so useful, but it has its place. The most common one I have seen is

(function($){
    //code here
})(jQuery)

which allows for jQuery to be in compatible mode, but you can refer to it as "$" within the anonymous function.

Determine Whether Integer Is Between Two Other Integers?

Suppose there are 3 non-negative integers: a, b, and c. Mathematically speaking, if we want to determine if c is between a and b, inclusively, one can use this formula:

(c - a) * (b - c) >= 0

or in Python:

> print((c - a) * (b - c) >= 0)
True

Timing Delays in VBA

With Due credits and thanks to Steve Mallroy.

I had midnight issues in Word and the below code worked for me

Public Function Pause(NumberOfSeconds As Variant)
 '   On Error GoTo Error_GoTo

    Dim PauseTime, Start
    Dim objWord As Word.Document

    'PauseTime = 10 ' Set duration in seconds
    PauseTime = NumberOfSeconds
    Start = Timer ' Set start time.

    If Start + PauseTime > 86399 Then 'playing safe hence 86399

    Start = 0

    Do While Timer > 1
        DoEvents ' Yield to other processes.
    Loop

    End If

    Do While Timer < Start + PauseTime
        DoEvents ' Yield to other processes.
    Loop

End Function

Insert Update trigger how to determine if insert or update

I'm using the following, it also correctly detect delete statements that delete nothing:

CREATE TRIGGER dbo.TR_TableName_TriggerName
    ON dbo.TableName
    AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS(SELECT * FROM INSERTED)
        -- DELETE
        PRINT 'DELETE';
    ELSE
    BEGIN
        IF NOT EXISTS(SELECT * FROM DELETED)
            -- INSERT
            PRINT 'INSERT';
        ELSE
            -- UPDATE
            PRINT 'UPDATE';
    END
END;

How to get coordinates of an svg element?

I was trying to select an area of svg with a rectangle and get all the elements from it. For this, element.getBoundingClientRect() worked perfectly for me. It returns current coordinates of svg elements regardless of whether svg is scaled or transformed.

How do I set up IntelliJ IDEA for Android applications?

I've spent a day on trying to put all the pieces together, been in hundreds of sites and tutorials, but they all skip trivial steps.

So here's the full guide:

  1. Download and install Java JDK (Choose the Java platform)
  2. Download and install Android SDK (Installer is recommended)
  3. After android SD finishes installing, open SDK Manager under Android SDK Tools (sometimes needs to be opened under admin's privileges)
  4. Choose everything and mark Accept All and install.
  5. Download and install IntelliJ IDEA (The community edition is free)
  6. Wait for all downloads and installations and stuff to finish.

New Project:

  1. Run IntelliJ
  2. Create a new project (there's a tutorial here)
  3. Enter the name, choose Android type.
  4. There's a step missing in the tutorial, when you are asked to choose the JDK (before choosing the SDK) you need to choose the Java JDK you've installed earlier. Should be under C:\Program Files\Java\jdk{version}
  5. Choose a New platform ( if there's not one selected ) , the SDK platform is the android platform at C:\Program Files\Android\android-sdk-windows.
  6. Choose the android version.
  7. Now you can write your program.

Compiling:

  1. Near the Run button you need to select the drop-down-list, choose Edit Configurations
  2. In the Prefer Android Virtual device select the ... button
  3. Click on create, give it a name, press OK.
  4. Double click the new device to choose it.
  5. Press OK.
  6. You're ready to run the program.

What are named pipes?

Named pipes is a windows system for inter-process communication. In the case of SQL server, if the server is on the same machine as the client, then it is possible to use named pipes to tranfer the data, as opposed to TCP/IP.

Calling startActivity() from outside of an Activity context

In addition: if you show links in listview in fragment, do not create it like this

adapter = new ListAdapter(getActivity().getApplicationContext(),mStrings);

instead call

adapter = new ListAdapter(getActivity(),mStrings);

adapter works fine in both cases, but links work only in last one.

How to enable multidexing with the new Android Multidex support library

Here is an up-to-date approach as of October 2020, with Android X. This comes from Android's documentation, "Enable multidex for apps with over 64K methods."

For minSdk >= 21

You do not need to do anything. All of these devices use the Android RunTime (ART) VM, which supports multidex natively.

For minSdk < 21

In your module-level build.gradle, ensure that the following configurations are populated:

android {
    defaultConfig {
        multiDexEnabled true
    }
}

dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
}

You need to install explicit multidex support. The documentation includes three methods to do so, and you have to pick one.

For example, in your src/main/AndroidManifest.xml, you can declare MultiDexApplication as the application:name:

<manifest package="com.your.package"
          xmlns:android="http://schemas.android.com/apk/res/android">
    <application android:name="androidx.multidex.MultiDexApplication" />
</manifest>

connecting to MySQL from the command line

See here http://dev.mysql.com/doc/refman/5.0/en/connecting.html

mysql -u USERNAME -pPASSWORD -h HOSTNAMEORIP DATABASENAME 

The options above means:

-u: username
-p: password (**no space between -p and the password text**)
-h: host
last one is name of the database that you wanted to connect. 

Look into the link, it's detailed there!


As already mentioned by Rick, you can avoid passing the password as the part of the command by not passing the password like this:

mysql -u USERNAME -h HOSTNAMEORIP DATABASENAME -p

People editing this answer: PLEASE DONOT ADD A SPACE between -p and PASSWORD

How to check what version of jQuery is loaded?

My preference is:

console.debug("jQuery "+ (jQuery ? $().jquery : "NOT") +" loaded")

Result:

jQuery 1.8.0 loaded

Differences between Lodash and Underscore.js

Lodash has got _.mapValues() which is identical to Underscore.js's _.mapObject().

How to make "if not true condition"?

Here is an answer by way of example:

In order to make sure data loggers are online a cron script runs every 15 minutes that looks like this:

#!/bin/bash
#
if ! ping -c 1 SOLAR &>/dev/null
then
  echo "SUBJECT:  SOLAR is not responding to ping" | ssmtp [email protected]
  echo "SOLAR is not responding to ping" | ssmtp [email protected]
else
  echo "SOLAR is up"
fi
#
if ! ping -c 1 OUTSIDE &>/dev/null
then
  echo "SUBJECT:  OUTSIDE is not responding to ping" | ssmtp [email protected]
  echo "OUTSIDE is not responding to ping" | ssmtp [email protected]
else
  echo "OUTSIDE is up"
fi
#

...and so on for each data logger that you can see in the montage at http://www.SDsolarBlog.com/montage


FYI, using &>/dev/null redirects all output from the command, including errors, to /dev/null

(The conditional only requires the exit status of the ping command)

Also FYI, note that since cron jobs run as root there is no need to use sudo ping in a cron script.

Getting all types in a namespace via reflection

Following code prints names of classes in specified namespace defined in current assembly.
As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.

string nspace = "...";

var q = from t in Assembly.GetExecutingAssembly().GetTypes()
        where t.IsClass && t.Namespace == nspace
        select t;
q.ToList().ForEach(t => Console.WriteLine(t.Name));

How to search for a string in text files?

Your check function should return the found boolean and use that to determine what to print.

def check():
        datafile = file('example.txt')
        found = False
        for line in datafile:
            if blabla in line:
                found = True
                break

        return found

found = check()
if found:
    print "true"
else:
    print "false"

the second block could also be condensed to:

if check():
    print "true"
else:
    print "false"

How to round up value C# to the nearest integer?

It is simple. So follow this code.

decimal d = 10.5;
int roundNumber = (int)Math.Floor(d + 0.5);

Result is 11

How do I remove the "extended attributes" on a file in Mac OS X?

Try using:

xattr -rd com.apple.quarantine directoryname

This takes care of recursively removing the pesky attribute everywhere.

Abstract Class vs Interface in C++

An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).

Bash: infinite sleep (infinite blocking)

This approach will not consume any resources for keeping process alive.

while :; do sleep 1; done & kill -STOP $! && wait $!

Breakdown

  • while :; do sleep 1; done & Creates a dummy process in background
  • kill -STOP $! Stops the background process
  • wait $! Wait for the background process, this will be blocking forever, cause background process was stopped before

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

Solutions revolve around:

  • changing MySQL's permissions

    sudo chown -R _mysql:mysql /usr/local/var/mysql
    
  • Starting a MySQL process

    sudo mysql.server start
    

Just to add on a lot of great and useful answers that have been provided here and from many different posts, try specifying the host if the above commands did not resolve this issue for you, i.e

mysql -u root -p h127.0.0.1

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

One way I found after some struggling is creating a function which gets data_plot matrix, file name and order as parameter to create boxplots from the given data in the ordered figure (different orders = different figures) and save it under the given file_name.

def plotFigure(data_plot,file_name,order):
    fig = plt.figure(order, figsize=(9, 6))
    ax = fig.add_subplot(111)
    bp = ax.boxplot(data_plot)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close()

Intercept page exit event

See this article. The feature you are looking for is the onbeforeunload

sample code:

  <script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>

How do I turn off PHP Notices?

You are looking for:

php -d error_reporting="E_ERROR | E_WARNING | E_PARSE"

Unable to establish SSL connection, how do I fix my SSL cert?

There are a few possibilities:

  1. Your workstation doesn't have the root CA cert used to sign your server's cert. How exactly you fix that depends on what OS you're running and what release, etc. (I suspect this is not related)
  2. Your cert isn't installed properly. If your SSL cert requires an intermediate cert to be presented and you didn't set that up, you can get these warnings.
  3. Are you sure you've enabled SSL on port 443?

For starters, to eliminate (3), what happens if you telnet to that port?

Assuming it's not (3), then depending on your needs you may be fine with ignoring these errors and just passing --no-certificate-check. You probably want to use a regular browser (which generally will bundle the root certs directly) and see if things are happy.

If you want to manually verify the cert, post more details from the openssl s_client output. Or use openssl x509 -text -in /path/to/cert to print it out to your terminal.

Difference between the Apache HTTP Server and Apache Tomcat?

an apache server is an http server which can serve any simple http requests, where tomcat server is actually a servlet container which can serve java servlet requests.

Web server [apache] process web client (web browsers) requests and forwards it to servlet container [tomcat] and container process the requests and sends response which gets forwarded by web server to the web client [browser].

Also you can check this link for more clarification:-

https://sites.google.com/site/sureshdevang/servlet-architecture

Also check this answer for further researching :-

https://softwareengineering.stackexchange.com/a/221092

Declaring a custom android UI element using XML

Thanks a lot for the first answer.

As for me, I had just one problem with it. When inflating my view, i had a bug : java.lang.NoSuchMethodException : MyView(Context, Attributes)

I resolved it by creating a new constructor :

public MyView(Context context, AttributeSet attrs) {
     super(context, attrs);
     // some code
}

Hope this will help !

Is there a limit on how much JSON can hold?

The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.

Refer below URL

https://docs.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer.maxjsonlength?view=netframework-4.7.2

Initialize a byte array to a certain value, other than the default null?

For small arrays use array initialisation syntax:

var sevenItems = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };

For larger arrays use a standard for loop. This is the most readable and efficient way to do it:

var sevenThousandItems = new byte[7000];
for (int i = 0; i < sevenThousandItems.Length; i++)
{
    sevenThousandItems[i] = 0x20;
}

Of course, if you need to do this a lot then you could create a helper method to help keep your code concise:

byte[] sevenItems = CreateSpecialByteArray(7);
byte[] sevenThousandItems = CreateSpecialByteArray(7000);

// ...

public static byte[] CreateSpecialByteArray(int length)
{
    var arr = new byte[length];
    for (int i = 0; i < arr.Length; i++)
    {
        arr[i] = 0x20;
    }
    return arr;
}

Resolve host name to an ip address

Windows XP has the Windows Firewall which can interfere with network traffic if not configured properly. You can turn off the Windows Firewall, if you have administrator privileges, by accessing the Windows Firewall applet through the Control Panel. If your application works with the Windows Firewall turned off then the problem is probably due to the settings of the firewall.

We have an application which runs on multiple PCs communicating using UDP/IP and we have been doing experiments so that the application can run on a PC with a user who does not have administrator privileges. In order for our application to communicate between multiple PCs we have had to use an administrator account to modify the Windows Firewall settings.

In our application, one PC is designated as the server and the others are clients in a server/client group and there may be several groups on the same subnet.

The first change was to use the functionality of the Exceptions tab of the Windows Firewall applet to create an exception for the port that we use for communication.

We are using host name lookup so that the clients can locate their assigned server by using the computer name which is composed of a mnemonic prefix with a dash followed by an assigned terminal number (for instance SERVER100-1). This allows several servers with their assigned clients to coexist on the same subnet. The client uses its prefix to generate the computer name for the assigned server and to then use host name lookup to discover the IP address of the assigned server.

What we found is that the host name lookup using the computer name (assigned through the Computer Name tab of the System Properties dialog) would not work unless the server PC's Windows Firewall had the File and Printer Sharing Service port enabled.

So we had to make two changes: (1) setup an exception for the port we used for communication and (2) enable File and Printer Service in the Exceptions tab to allow for the host name lookup.

** EDIT **

You may also find this Microsoft Knowledge Base article on helpful on Windows XP networking.

And see this article on NETBIOS name resolution in Windows.

How to uncheck a checkbox in pure JavaScript?

<html>
    <body>
        <input id="mycheck" type="checkbox">
    </body>

    <script language="javascript">
        var=check;
        document.getElementById("mycheck");
        check.checked="false";
    </script>
</html>

CSS align one item right with flexbox

To align some elements (headerElement) in the center and the last element to the right (headerEnd).

.headerElement {
    margin-right: 5%;
    margin-left: 5%;
}
.headerEnd{
    margin-left: auto;
}

Python: Remove division decimal

def division(a, b):
    return a / b if a % b else a // b

Error QApplication: no such file or directory

For QT 5

Step1: .pro (in pro file, add these 2 lines)

QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

Step2: In main.cpp replace code:

#include <QtGui/QApplication> 

with:

#include <QApplication>

How can I align text in columns using Console.WriteLine?

I really like those libraries mentioned here but I had an idea that could be simpler than just padding or doing tons of string manipulations,

You could just manually set your cursor using the maximum string length of your data. Here's some code to get the idea (not tested):

var column1[] = {"test", "longer test", "etc"}
var column2[] = {"data", "more data", "etc"}
var offset = strings.OrderByDescending(s => s.Length).First().Length;
for (var i = 0; i < column.Length; i++) {
    Console.Write(column[i]);
    Console.CursorLeft = offset + 1;
    Console.WriteLine(column2[i]);
}

you could easily extrapolate if you have more rows.

How to debug PDO database queries?

for example you have this pdo statement :

$query="insert into tblTest (field1, field2, field3)
values (:val1, :val2, :val3)";
$res=$db->prepare($query);
$res->execute(array(
  ':val1'=>$val1,
  ':val2'=>$val2,
  ':val3'=>$val3,
));

now you can get the executed query by defining an array like this :

$assoc=array(
  ':val1'=>$val1,
  ':val2'=>$val2,
  ':val3'=>$val3,
);
$exQuery=str_replace(array_keys($assoc), array_values($assoc), $query);
echo $exQuery;

Android Min SDK Version vs. Target SDK Version

If you get some compile errors for example:

<uses-sdk
            android:minSdkVersion="10"
            android:targetSdkVersion="15" />

.

private void methodThatRequiresAPI11() {
        BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
                options.inSampleSize = 8;    // API Level 1
                options.inBitmap = bitmap;   // **API Level 11**
        //...
    }

You get compile error:

Field requires API level 11 (current min is 10): android.graphics.BitmapFactory$Options#inBitmap

Since version 17 of Android Development Tools (ADT) there is one new and very useful annotation @TargetApi that can fix this very easily. Add it before the method that is enclosing the problematic declaration:

@TargetApi
private void methodThatRequiresAPI11() {            
  BitmapFactory.Options options = new BitmapFactory.Options();
      options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
      options.inSampleSize = 8;    // API Level 1

      // This will avoid exception NoSuchFieldError (or NoSuchMethodError) at runtime. 
      if (Integer.valueOf(android.os.Build.VERSION.SDK) >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        options.inBitmap = bitmap;   // **API Level 11**
            //...
      }
    }

No compile errors now and it will run !

EDIT: This will result in runtime error on API level lower than 11. On 11 or higher it will run without problems. So you must be sure you call this method on an execution path guarded by version check. TargetApi just allows you to compile it but you run it on your own risk.

Installing NumPy and SciPy on 64-bit Windows (with Pip)

If you are on windows , you wouldn't need wheel anyway! You can directly install package by downloading the 32-bit package as win32 from this link [http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy] and then move that downloaded package to cmd's current directory and open cmd and write following codepip install numpy-1.13.1+mkl-cp36-cp36m-win32.whl then do it same for scipy

For 64-bit you need to install mingw-w64 as it is gcc and compiles numpy and scipy as precompiled status.

Currently it works fine with 32-bit.So I had opted for win32 package both for numpy+mkl and scipy in that link.

Hope This works! Give a try

SSL cert "err_cert_authority_invalid" on mobile chrome only

The report from SSLabs says:

  This server's certificate chain is incomplete. Grade capped to B.
  ....
  Chain Issues                  Incomplete

Desktop browsers often have chain certificates cached from previous connections or download them from the URL specified in the certificate. Mobile browsers and other applications usually don't.

Fix your chain by including the missing certificates and everything should be right.

How to set timer in android?

void method(boolean u,int max)
{
    uu=u;
    maxi=max;
    if (uu==true)
    { 
        CountDownTimer uy = new CountDownTimer(maxi, 1000) 
  {
            public void onFinish()
            {
                text.setText("Finish"); 
            }

            @Override
            public void onTick(long l) {
                String currentTimeString=DateFormat.getTimeInstance().format(new Date());
                text.setText(currentTimeString);
            }
        }.start();
    }

    else{text.setText("Stop ");
}

How to draw interactive Polyline on route google maps v2 android

You should use options.addAll(allPoints); instead of options.add(point);

How to parse JSON in Kotlin?

Without external library (on Android)

To parse this:

val jsonString = """
    {
       "type":"Foo",
       "data":[
          {
             "id":1,
             "title":"Hello"
          },
          {
             "id":2,
             "title":"World"
          }
       ]
    }        
"""

Use these classes:

import org.json.JSONObject

class Response(json: String) : JSONObject(json) {
    val type: String? = this.optString("type")
    val data = this.optJSONArray("data")
            ?.let { 0.until(it.length()).map { i -> it.optJSONObject(i) } } // returns an array of JSONObject
            ?.map { Foo(it.toString()) } // transforms each JSONObject of the array into Foo
}

class Foo(json: String) : JSONObject(json) {
    val id = this.optInt("id")
    val title: String? = this.optString("title")
}

Usage:

val foos = Response(jsonString)

How to start automatic download of a file in Internet Explorer?

This seemed to work for me - across all browsers.

 <script type="text/javascript">
    window.onload = function(){
     document.location = 'somefile.zip';
    }
    </script>

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

enter image description here

  • Choose the new UI Design >> next
  • Just try to cancel the "Downloading Components" from upper right corner 'X' button.
  • A dialog box will appear then click OK (wait a bit for first time launch)

UTF-8 text is garbled when form is posted as multipart/form-data

I had the same problem and it turned out that in addition to specifying the encoding in the Filter

request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

it is necessary to add "acceptcharset" to the form

<form method="post" enctype="multipart/form-data" acceptcharset="UTF-8" > 

and run the JVM with

-Dfile.encoding=UTF-8

The HTML meta tag is not necessary if you send it in the HTTP header using response.setCharacterEncoding().

How to secure database passwords in PHP?

Actually, the best practice is to store your database crendentials in environment variables because :

  • These credentials are dependant to environment, it means that you won't have the same credentials in dev/prod. Storing them in the same file for all environment is a mistake.
  • Credentials are not related to business logic which means login and password have nothing to do in your code.
  • You can set environment variables without creating any business code class file, which means you will never make the mistake of adding the credential files to a commit in Git.
  • Environments variables are superglobales : you can use them everywhere in your code without including any file.

How to use them ?

  • Using the $_ENV array :
    • Setting : $_ENV['MYVAR'] = $myvar
    • Getting : echo $_ENV["MYVAR"]
  • Using the php functions :
  • In vhosts files and .htaccess but it's not recommended since its in another file and its not resolving the problem by doing it this way.

You can easily drop a file such as envvars.php with all environment variables inside and execute it (php envvars.php) and delete it. It's a bit old school, but it still work and you don't have any file with your credentials in the server, and no credentials in your code. Since it's a bit laborious, frameworks do it better.

Example with Symfony (ok its not only PHP) The modern frameworks such as Symfony recommends using environment variables, and store them in a .env not commited file or directly in command lines which means you wether can do :

Documentation :

Javascript "Uncaught TypeError: object is not a function" associativity question

I got a similar error and it took me a while to realize that in my case I named the array variable payInvoices and the function also payInvoices. It confused AngularJs. Once I changed the name to processPayments() it finally worked. Just wanted to share this error and solution as it took me long time to figure this out.

Jackson serialization: ignore empty values (or null)

Also you can try to use

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

if you are dealing with jackson with version below 2+ (1.9.5) i tested it, you can easily use this annotation above the class. Not for specified for the attributes, just for class decleration.

label or @html.Label ASP.net MVC 4

When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance

  • When dealing with hyperlinks, since the HTML helper simplifies routing
  • When you bind to your model, using @Html.LabelFor, @Html.TextBoxFor, etc
  • When you use the @Html.EditorFor, as you can assign specific behavior och looks in a editor view

Call a REST API in PHP

You can use file_get_contents to issue any http POST/PUT/DELETE/OPTIONS/HEAD methods, in addition to the GET method as the function name suggests.

How to post data in PHP using file_get_contents?

Correct way to delete cookies server-side

Setting "expires" to a past date is the standard way to delete a cookie.

Your problem is probably because the date format is not conventional. IE probably expects GMT only.

html5: display video inside canvas

var canvas = document.getElementById('canvas');
var ctx    = canvas.getContext('2d');
var video  = document.getElementById('video');

video.addEventListener('play', function () {
    var $this = this; //cache
    (function loop() {
        if (!$this.paused && !$this.ended) {
            ctx.drawImage($this, 0, 0);
            setTimeout(loop, 1000 / 30); // drawing at 30fps
        }
    })();
}, 0);

I guess the above code is self Explanatory, If not drop a comment below, I will try to explain the above few lines of code

Edit :
here's an online example, just for you :)
Demo

_x000D_
_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
var video = document.getElementById('video');_x000D_
_x000D_
// set canvas size = video size when known_x000D_
video.addEventListener('loadedmetadata', function() {_x000D_
  canvas.width = video.videoWidth;_x000D_
  canvas.height = video.videoHeight;_x000D_
});_x000D_
_x000D_
video.addEventListener('play', function() {_x000D_
  var $this = this; //cache_x000D_
  (function loop() {_x000D_
    if (!$this.paused && !$this.ended) {_x000D_
      ctx.drawImage($this, 0, 0);_x000D_
      setTimeout(loop, 1000 / 30); // drawing at 30fps_x000D_
    }_x000D_
  })();_x000D_
}, 0);
_x000D_
<div id="theater">_x000D_
  <video id="video" src="http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv" controls="false"></video>_x000D_
  <canvas id="canvas"></canvas>_x000D_
  <label>_x000D_
    <br />Try to play me :)</label>_x000D_
  <br />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Saving a Numpy array as an image

For those looking for a direct fully working example:

from PIL import Image
import numpy

w,h = 200,100
img = numpy.zeros((h,w,3),dtype=numpy.uint8) # has to be unsigned bytes

img[:] = (0,0,255) # fill blue

x,y = 40,20
img[y:y+30, x:x+50] = (255,0,0) # 50x30 red box

Image.fromarray(img).convert("RGB").save("art.png") # don't need to convert

also, if you want high quality jpeg's
.save(file, subsampling=0, quality=100)

How to export and import a .sql file from command line with options?

Type the following command to import sql data file:

$ mysql -u username -p -h localhost DATA-BASE-NAME < data.sql

In this example, import 'data.sql' file into 'blog' database using vivek as username:

$ mysql -u vivek -p -h localhost blog < data.sql

If you have a dedicated database server, replace localhost hostname with with actual server name or IP address as follows:

$ mysql -u username -p -h 202.54.1.10 databasename < data.sql

To export a database, use the following:

mysqldump -u username -p databasename > filename.sql

Note the < and > symbols in each case.

Best PHP IDE for Mac? (Preferably free!)

Here's the lowdown on Mac IDE's for PHP

NetBeans Free! Plus, the best functionality of all offerings. Includes inline database connections, code completion, syntax checking, color coding, split views etc. Downside: It's a memory hog on the Mac. Be prepared to allow half a gig of memory then you'll need to shut down and restart.

Komodo A step above a Text Editor. Does not support database connections or split views. Color coding and syntax checking are there to an extent. The project control on Komodo is very unwieldy and strange compared to the other IDEs.

Aptana The perfect solution. Eclipsed based and uses the Aptana PHP plug in. Real time syntax checking, word wrap, drag and drop split views, database connections and a slew of other excellent features. Downside: Not a supported product any more. Aptana Studio 2.0+ uses PDT which is a watered down, under-developed (at present) php plug in.

Zend Studio - Almost identical to Aptana, except no word wrap and you can't change alot of the php configuration on the MAC apparently due to bugs.

Coda Created by Panic, Coda has nice integration with source control and their popular FTP client, transmit. They also have a collaboration feature which is cool for pair-programming.

PhpEd with Parallels or Wine. The best IDE for Windows has all the feature you could need and is worth the effort to pass it through either Parallels or Wine.

Dreamweaver Good for Javascript/HTML/CSS, but only marginal for PHP. There is some color coding, but no syntax checking or code completion native to the package. Database connections are supported, and so are split views.

I'm using NetBeans, which is free, and feature rich. I can deal with the memory issues for a while, but it could be slow coming to the MAC.

Cheers! Korky Kathman Senior Partner Entropy Dynamics, LLC

git pull fails "unable to resolve reference" "unable to update local ref"

I'm using Tower and for some reason my folder name was .git/refs/remotes/origin/Github. Changing it to lowercase .git/refs/remotes/origin/github solved the issue.