Programs & Examples On #Xml rpc

XML-RPC is a remote procedure call (RPC) protocol which uses XML to encode its calls and HTTP as a transport mechanism.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

Your site's root directory:

ini_set('memory_limit', '1024M');

Unescape HTML entities in Javascript?

Do you need to decode all encoded HTML entities or just & itself?

If you only need to handle & then you can do this:

var decoded = encoded.replace(/&/g, '&');

If you need to decode all HTML entities then you can do it without jQuery:

var elem = document.createElement('textarea');
elem.innerHTML = encoded;
var decoded = elem.value;

Please take note of Mark's comments below which highlight security holes in an earlier version of this answer and recommend using textarea rather than div to mitigate against potential XSS vulnerabilities. These vulnerabilities exist whether you use jQuery or plain JavaScript.

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

The following should work and not require any permissions in the manifest (basically override shouldOverrideUrlLoading and handle links separately from tel, mailto, etc.):

    mWebView = (WebView) findViewById(R.id.web_view);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if( url.startsWith("http:") || url.startsWith("https:") ) {
                return false;
            }

            // Otherwise allow the OS to handle things like tel, mailto, etc.
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity( intent );
            return true;
        }
    });
    mWebView.loadUrl(url);

Also, note that in the above snippet I am enabling JavaScript, which you will also most likely want, but if for some reason you don't, just remove those 2 lines.

PHP Function Comments

You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().

http://www.php.net/manual/en/reflectionclass.getdoccomment.php

SVN check out linux

You can use checkout or co

$ svn co http://example.com/svn/app-name directory-name

Some short codes:-

  1. checkout (co)
  2. commit (ci)
  3. copy (cp)
  4. delete (del, remove,rm)
  5. diff (di)

Press Keyboard keys using a batch file

Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)

The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.

@if (@CodeSection == @Batch) @then


@echo off

rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"

rem Start the other program in the same Window
start "" /B cmd

%SendKeys% "echo off{ENTER}"

set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"

set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"

set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"

%SendKeys% "exit{ENTER}"

goto :EOF


@end


// JScript section

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));

For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx

For example:

LEFT ARROW    {LEFT}
RIGHT ARROW   {RIGHT}

For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

Simply add this

$id = ''; 
if( isset( $_GET['id'])) {
    $id = $_GET['id']; 
} 

Counting number of words in a file

So easy we can get the String from files by method: getText();

public class Main {

    static int countOfWords(String str) {
        if (str.equals("") || str == null) {
            return 0;
        }else{
            int numberWords = 0;
            for (char c : str.toCharArray()) {
                if (c == ' ') {
                    numberWords++;
                }
            }

            return ++numberWordss;
        }
    }
}

How to convert string to float?

Use atof() or strtof()* instead:

printf("float value : %4.8f\n" ,atof(s)); 
printf("float value : %4.8f\n" ,strtof(s, NULL)); 

http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
http://www.cplusplus.com/reference/cstdlib/strtof/

  • atoll() is meant for integers.
  • atof()/strtof() is for floats.

The reason why you only get 4.00 with atoll() is because it stops parsing when it finds the first non-digit.

*Note that strtof() requires C99 or C++11.

How to request Administrator access inside a batch file

Since I have troubles with this script popping up a new command prompt with itself run again, in infinite loop (using Win 7 Pro), I suggest you try another approach :How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

Be careful, you have to add this at the end of script, as stated in an edit, so that you are back to script directory after privileges were elevated : cd /d %~dp0

sql server invalid object name - but tables are listed in SSMS tables list

Solved for SSMS 2016.

Had a similar problem, but Intellisense was not in Edit menu.

What seemed to fix it was turning Intellisens on and off, right click on the SQL editor and click 'Intellisense Enabled'. Right click again on 'Intellisense Enabled' to turn it back on again. Ctr Q, I also does this.

This solved the problem, and also I know get the Intellisense on the Edit menu.

Fragment MyFragment not attached to Activity

The problem with your code is the way the you are using the AsyncTask, because when you rotate the screen during your sleep thread:

Thread.sleep(2000) 

the AsyncTask is still working, it is because you didn't cancel the AsyncTask instance properly in onDestroy() before the fragment rebuilds (when you rotate) and when this same AsyncTask instance (after rotate) runs onPostExecute(), this tries to find the resources with getResources() with the old fragment instance(an invalid instance):

getResources().getString(R.string.app_name)

which is equivalent to:

MyFragment.this.getResources().getString(R.string.app_name)

So the final solution is manage the AsyncTask instance (to cancel if this is still working) before the fragment rebuilds when you rotate the screen, and if canceled during the transition, restart the AsyncTask after reconstruction by the aid of a boolean flag:

public class MyFragment extends SherlockFragment {

    private MyAsyncTask myAsyncTask = null;
    private boolean myAsyncTaskIsRunning = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState!=null) {
            myAsyncTaskIsRunning = savedInstanceState.getBoolean("myAsyncTaskIsRunning");
        }
        if(myAsyncTaskIsRunning) {
            myAsyncTask = new MyAsyncTask();
            myAsyncTask.execute();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("myAsyncTaskIsRunning",myAsyncTaskIsRunning);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(myAsyncTask!=null) myAsyncTask.cancel(true);
        myAsyncTask = null;

    }

    public class MyAsyncTask extends AsyncTask<Void, Void, Void>() {

        public MyAsyncTask(){}

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            myAsyncTaskIsRunning = true;
        }
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {}
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            getResources().getString(R.string.app_name);
            myAsyncTaskIsRunning = false;
            myAsyncTask = null;
        }

    }
}

Google Maps v2 - set both my location and zoom in

1.Add xml code in your layout for displaying maps.

2.Enable google maps api then get api key place that below.

<fragment
                   android:id="@+id/map"
               android:name="com.google.android.gms.maps.MapFragment"
                    android:layout_width="match_parent"
                    android:value="ADD-API-KEY"
                    android:layout_height="250dp"
                    tools:layout="@layout/newmaplayout" />
        <ImageView
            android:id="@+id/transparent_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@color/transparent" />

3.Add this code in oncreate.

 MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(UpadateProfile.this);

4.Add this code after oncreate. then access current location with marker placed in that

@Override
public void onMapReady(GoogleMap rmap) {
    DO WHATEVER YOU WANT WITH GOOGLEMAP
    map = rmap;
    setUpMap();
}
public void setUpMap() {
    map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
  map.setMyLocationEnabled(true);
    map.setTrafficEnabled(true);
    map.setIndoorEnabled(true);
    map.getCameraPosition();
    map.setBuildingsEnabled(true);
    map.getUiSettings().setZoomControlsEnabled(true);
    markerOptions = new MarkerOptions();
    markerOptions.title("Outlet Location");
    map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng point) {
            map.clear();
            markerOptions.position(point);
            map.animateCamera(CameraUpdateFactory.newLatLng(point));
            map.addMarker(markerOptions);
            String all_vals = String.valueOf(point);
            String[] separated = all_vals.split(":");
            String latlng[] = separated[1].split(",");
            MyLat = Double.parseDouble(latlng[0].trim().substring(1));
            MyLong = Double.parseDouble(latlng[1].substring(0,latlng[1].length()-1));
            markerOptions.title("Outlet Location");
            getLocation(MyLat,MyLong);
        }
    });
}
public void getLocation(double lat, double lng) {
    Geocoder geocoder = new Geocoder(UpadateProfile.this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
   } catch (IOException e) {
         TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
    }
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}

Speed tradeoff of Java's -Xms and -Xmx options

This was always the question I had when I was working on one of my application which created massive number of threads per request.

So this is a really good question and there are two aspects of this:
1. Whether my Xms and Xmx value should be same
       - Most websites and even oracle docs suggest it to be the same. However, I suggest to have some 10-20% of buffer between those values to give heap resizing an option to your application in case sudden high traffic spikes OR a incidental memory leak.

2. Whether I should start my Application with lower heap size
       - So here's the thing - no matter what GC Algo you use (even G1), large heap always has some trade off. The goal is to identify the behavior of your application to what heap size you can allow your GC pauses in terms of latency and throughput.
              - For example, if your application has lot of threads (each thread has 1 MB stack in native memory and not in heap) but does not occupy heavy object space, then I suggest have a lower value of Xms.
              - If your application creates lot of objects with increasing number of threads, then identify to what value of Xms you can set to tolerate those STW pauses. This means identify the max response time of your incoming requests you can tolerate and according tune the minimum heap size.

Can we add div inside table above every <tr>?

You could use display: table-row-group for your div.

<table>
  <div style="display: table-row-group">
    <tr><td></td></tr>
  </div>
  <div style="display: table-row-group">
    <tr><td></td></tr>
  </div>
</table>

You are trying to add a non-nullable field 'new_field' to userprofile without a default

In new_file add the boolean property null.

new_field = models.CharField(max_length=140, null=True)

after you run a ./manage.py syncdb for refresh the DB. and finally you run ./manage.py makemigrations and ./manage.py migrate

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

If the given solutions does not work, create a new project with 'KOTLIN' as the language even if your work is on java. Then replace the 'main' folder of the new project with the 'main' folder of the old.

Prevent direct access to a php include file

You can use phpMyAdmin Style:

/**
 * block attempts to directly run this script
 */
if (getcwd() == dirname(__FILE__)) {
    die('Attack stopped');
}

In Tensorflow, get the names of all the Tensors in a graph

Since the OP asked for the list of the tensors instead of the list of operations/nodes, the code should be slightly different:

graph = tf.get_default_graph()    
tensors_per_node = [node.values() for node in graph.get_operations()]
tensor_names = [tensor.name for tensors in tensors_per_node for tensor in tensors]

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

How to delete files/subfolders in a specific directory at the command prompt in Windows

Use:

del %pathtofolder%\*.*   /s /f  /q

This deletes all files and subfolders in %pathtofolder%, including read-only files, and does not prompt for confirmation.

How to remove all the occurrences of a char in c++ string

In case you have a predicate and/or a non empty output to fill with the filtered string, I would consider:

output.reserve(str.size() + output.size());  
std::copy_if(str.cbegin(), 
             str.cend(), 
             std::back_inserter(output), 
             predicate});

In the original question the predicate is [](char c){return c != 'a';}

Python3 project remove __pycache__ folders and .pyc files

The command I've used:

find . -type d -name "__pycache__" -exec rm -r {} +

Explains:

  1. First finds all __pycache__ folders in current directory.

  2. Execute rm -r {} + to delete each folder at step above ({} signify for placeholder and + to end the command)

Edited 1:

I'm using Linux, to reuse the command I've added the line below to the ~/.bashrc file

alias rm-pycache='find . -type d -name  "__pycache__" -exec rm -r {} +'

Edited 2: If you're using VS Code, you don't need to remove __pycache__ manually. You can add the snippet below to settings.json file. After that, VS Code will hide all __pycache__ folders for you

"files.exclude": {
     "**/__pycache__": true
}

Hope it helps !!!

Can't push to GitHub because of large file which I already deleted

I got the same problem and none of the answers work for me. I solved by the following steps:

1. Find which commit(s) contains the large file

git log --all -- 'large_file`

The bottom commit is the oldest commit in the result list.

2. Find the one just before the oldest.

git log

Suppose you got:

commit 3f7dd04a6e6dbdf1fff92df1f6344a06119d5d32

3. Git rebase

git rebase -i 3f7dd04a6e6dbdf1fff92df1f6344a06119d5d32

Tips:

  1. List item
  2. I just choose drop for the commits contains the large file.
  3. You may meet conflicts during rebase fix them and use git rebase --continue to continue until you finish it.
  4. If anything went wrong during rebase use git rebase --abort to cancel it.

CardView Corner Radius

dependencies: compile 'com.android.support:cardview-v7:23.1.1'

<android.support.v7.widget.CardView
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:elevation="12dp"
    android:id="@+id/view2"
    app:cardCornerRadius="40dp"
    android:layout_centerHorizontal="true"
    android:innerRadius="0dp"
    android:shape="ring"
    android:thicknessRatio="1.9">
    <ImageView
        android:layout_height="80dp"
        android:layout_width="match_parent"
        android:id="@+id/imageView1"
        android:src="@drawable/Your_image"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">
    </ImageView>
</android.support.v7.widget.CardView>

How does HttpContext.Current.User.Identity.Name know which usernames exist?

Assume a network environment where a "user" (aka you) has to logon. Usually this is a User ID (UID) and a Password (PW). OK then, what is your Identity, or who are you? You are the UID, and this gleans that "name" from your logon session. Simple! It should also work in an internet application that needs you to login, like Best Buy and others.

This will pull my UID, or "Name", from my session when I open the default page of the web application I need to use. Now, in my instance, I am part of a Domain, so I can use initial Windows authentication, and it needs to verify who I am, thus the 2nd part of the code. As for Forms Authentication, it would rely on the ticket (aka cookie most likely) sent to your workstation/computer. And the code would look like:

string id = HttpContext.Current.User.Identity.Name;

// Strip the domain off of the result
id = id.Substring(id.LastIndexOf(@"\", StringComparison.InvariantCulture) + 1);

Now it has my business name (aka UID) and can display it on the screen.

Alternative for frames in html5 using iframes

Frames have been deprecated because they caused trouble for url navigation and hyperlinking, because the url would just take to you the index page (with the frameset) and there was no way to specify what was in each of the frame windows. Today, webpages are often generated by server-side technologies such as PHP, ASP.NET, Ruby etc. So instead of using frames, pages can simply be generated by merging a template with content like this:

Template File

<html>
<head>
<title>{insert script variable for title}</title>
</head>

<body>
  <div class="menu">
   {menu items inserted here by server-side scripting}
  </div>
  <div class="main-content">
   {main content inserted here by server-side scripting}
  </div>
</body>
</html>

If you don't have full support for a server-side scripting language, you could also use server-side includes (SSI). This will allow you to do the same thing--i.e. generate a single web page from multiple source documents.

But if you really just want to have a section of your webpage be a separate "window" into which you can load other webpages that are not necessarily located on your own server, you will have to use an iframe.

You could emulate your example like this:

Frames Example

<html>
<head>
  <title>Frames Test</title>
  <style>
   .menu {
      float:left;
      width:20%;
      height:80%;
    }
    .mainContent {
      float:left;
      width:75%;
      height:80%;
    }
  </style>
</head>
<body>
  <iframe class="menu" src="menu.html"></iframe>
  <iframe class="mainContent" src="events.html"></iframe>
</body>
</html>

There are probably better ways to achieve the layout. I've used the CSS float attribute, but you could use tables or other methods as well.

Call Python function from MATLAB

A little known (and little documented) fact about MATLAB's system() function: On unixoid systems it uses whatever interpreter is given in the environment variable SHELL or MATLAB_SHELL at the time of starting MATLAB. So if you start MATLAB with

SHELL='/usr/bin/python' matlab

any subsequent system() calls will use Python instead of your default shell as an interpreter.

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

I had the same its because of version incompatibility check for version or remove version if using spring boot

How to substring in jquery

Yes you can, although it relies on Javascript's inherent functionality and not the jQuery library.

http://www.w3schools.com/jsref/jsref_substr.asp The substr function will allow you to extract certain parts of the string.

Now, if you're looking for a specific string or character to use to find what part of the string to extract, you can make use of the indexOf function as well. http://www.w3schools.com/jsref/jsref_IndexOf.asp

The question is somewhat vague though; even just link text with 'name' will achieve the desired result. What's the criteria for getting your substring, exactly?

How to overcome root domain CNAME restrictions?

I see readytocloud.com is hosted on Apache 2.2.

There is a much simpler and more efficient way to redirect the non-www site to the www site in Apache.

Add the following rewrite rules to the Apache configs (either inside the virtual host or outside. It doesn't matter):

RewriteCond %{HTTP_HOST} ^readytocloud.com [NC]
RewriteRule ^/$ http://www.readytocloud.com/ [R=301,L]

Or, the following rewrite rules if you want a 1-to-1 mapping of URLs from the non-www site to the www site:

RewriteCond %{HTTP_HOST} ^readytocloud.com [NC]
RewriteRule (.*) http://www.readytocloud.com$1 [R=301,L]

Note, the mod_rewrite module needs to be loaded for this to work. Luckily readytocloud.com is runing on a CentOS box, which by default loads mod_rewrite.

We have a client server running Apache 2.2 with just under 3,000 domains and nearly 4,000 redirects, however, the load on the server hover around 0.10 - 0.20.

Resolving require paths with webpack

This thread is old but since no one posted about require.context I'm going to mention it:

You can use require.context to set the folder to look through like this:

var req = require.context('../../mydir/', true)
// true here is for use subdirectories, you can also specify regex as third param

return req('./myfile.js')

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

You can get table/view details through below query.

For table :sp_help table_name For View :sp_help view_name

Any way to generate ant build.xml file automatically from Eclipse?

I have been trying to do the same myself. What I found was that the "Export Ant Buildfile" gets kicked off in the org.eclipse.ant.internal.ui.datatransfer.AntBuildfileExportPage.java file. This resides in the org.eclipse.ant.ui plugin.

To view the source, use the Plug-in Development perspective and open the Plug-ins view. Then right-click on the org.eclipse.ant.ui plugin and select import as > source project.

My plan is to create a Java program to programmatically kick off the ant buildfile generation and call this in an Ant file every time I build by adding the ant file to the builders of my projects (Right-click preferences on a projet, under the builders tab).

How to set button click effect in Android?

This is the best solution I came up with taking hints from @Vinayak's answer. All the other solutions have different drawbacks.

First of all create a function like this.

void addClickEffect(View view)
{
    Drawable drawableNormal = view.getBackground();

    Drawable drawablePressed = view.getBackground().getConstantState().newDrawable();
    drawablePressed.mutate();
    drawablePressed.setColorFilter(Color.argb(50, 0, 0, 0), PorterDuff.Mode.SRC_ATOP);

    StateListDrawable listDrawable = new StateListDrawable();
    listDrawable.addState(new int[] {android.R.attr.state_pressed}, drawablePressed);
    listDrawable.addState(new int[] {}, drawableNormal);
    view.setBackground(listDrawable);
}

Explanation:

getConstantState().newDrawable() is used to clone the existing Drawable otherwise the same drawable will be used. Read more from here: Android: Cloning a drawable in order to make a StateListDrawable with filters

mutate() is used to make the Drawable clone not share its state with other instances of Drawable. Read more about it here: https://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()

Usage:

You can pass any type of View (Button, ImageButton, View etc) as the parameter to the function and they will get the click effect applied to them.

addClickEffect(myButton);
addClickEffect(myImageButton);

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

The only thing that worked for me was to delete the Solution User Options (.suo) file. Note that, this is a hidden file.

To locate this file, close your Virsual studio and search for .suo from the file explorer within your project.

Delete the .suo file

PS: a new .suo file will be created again when you rebuild your project and hopefully this newly created one wont give you issues.

I hope that helps someone get rid of this anoying error :).

Hadoop/Hive : Loading data from .csv on a local machine

For csv file formate data will be in below format

"column1", "column2","column3","column4"

And if we will use field terminated by ',' then each column will get values like below.

"column1"    "column2"     "column3"     "column4"

also if any of the column value has comma as value then it will not work at all .

So the correct way to create a table would be by using OpenCSVSerde

create table tableName (column1 datatype, column2 datatype , column3 datatype , column4 datatype)
ROW FORMAT SERDE 
'org.apache.hadoop.hive.serde2.OpenCSVSerde' 
STORED AS TEXTFILE ;

AngularJS Uploading An Image With ng-upload

In my case above mentioned methods work fine with php but when i try to upload files with these methods in node.js then i have some problem. So instead of using $http({..,..,...}) use the normal jquery ajax.

For select file use this

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this)"/>

And in controller

$scope.uploadFile = function(element) {   
var data = new FormData();
data.append('file', $(element)[0].files[0]);
jQuery.ajax({
      url: 'brand/upload',
      type:'post',
      data: data,
      contentType: false,
      processData: false,
      success: function(response) {
      console.log(response);
      },
      error: function(jqXHR, textStatus, errorMessage) {
      alert('Error uploading: ' + errorMessage);
      }
 });   
};

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)

ERROR: Cannot open source file " "

You need to check your project settings, under C++, check include directories and make sure it points to where GameEngine.h resides, the other issue could be that GameEngine.h is not in your source file folder or in any include directory and resides in a different folder relative to your project folder. For instance you have 2 projects ProjectA and ProjectB, if you are including GameEngine.h in some source/header file in ProjectA then to include it properly, assuming that ProjectB is in the same parent folder do this:

include "../ProjectB/GameEngine.h"

This is if you have a structure like this:

Root\ProjectA

Root\ProjectB <- GameEngine.h actually lives here

How can I String.Format a TimeSpan object with a custom format in .NET?

You can also go with:

Dim ts As New TimeSpan(35, 21, 59, 59)  '(11, 22, 30, 30)    '
Dim TimeStr1 As String = String.Format("{0:c}", ts)
Dim TimeStr2 As String = New Date(ts.Ticks).ToString("dd.HH:mm:ss")

EDIT:

You can also look at Strings.Format.

    Dim ts As New TimeSpan(23, 30, 59)
    Dim str As String = Strings.Format(New DateTime(ts.Ticks), "H:mm:ss")

Create the perfect JPA entity

I'll try to answer several key points: this is from long Hibernate/ persistence experience including several major applications.

Entity Class: implement Serializable?

Keys needs to implement Serializable. Stuff that's going to go in the HttpSession, or be sent over the wire by RPC/Java EE, needs to implement Serializable. Other stuff: not so much. Spend your time on what's important.

Constructors: create a constructor with all required fields of the entity?

Constructor(s) for application logic, should have only a few critical "foreign key" or "type/kind" fields which will always be known when creating the entity. The rest should be set by calling the setter methods -- that's what they're for.

Avoid putting too many fields into constructors. Constructors should be convenient, and give basic sanity to the object. Name, Type and/or Parents are all typically useful.

OTOH if application rules (today) require a Customer to have an Address, leave that to a setter. That is an example of a "weak rule". Maybe next week, you want to create a Customer object before going to the Enter Details screen? Don't trip yourself up, leave possibility for unknown, incomplete or "partially entered" data.

Constructors: also, package private default constructor?

Yes, but use 'protected' rather than package private. Subclassing stuff is a real pain when the necessary internals are not visible.

Fields/Properties

Use 'property' field access for Hibernate, and from outside the instance. Within the instance, use the fields directly. Reason: allows standard reflection, the simplest & most basic method for Hibernate, to work.

As for fields 'immutable' to the application -- Hibernate still needs to be able to load these. You could try making these methods 'private', and/or put an annotation on them, to prevent application code making unwanted access.

Note: when writing an equals() function, use getters for values on the 'other' instance! Otherwise, you'll hit uninitialized/ empty fields on proxy instances.

Protected is better for (Hibernate) performance?

Unlikely.

Equals/HashCode?

This is relevant to working with entities, before they've been saved -- which is a thorny issue. Hashing/comparing on immutable values? In most business applications, there aren't any.

A customer can change address, change the name of their business, etc etc -- not common, but it happens. Corrections also need to be possible to make, when the data was not entered correctly.

The few things that are normally kept immutable, are Parenting and perhaps Type/Kind -- normally the user recreates the record, rather than changing these. But these do not uniquely identify the entity!

So, long and short, the claimed "immutable" data isn't really. Primary Key/ ID fields are generated for the precise purpose, of providing such guaranteed stability & immutability.

You need to plan & consider your need for comparison & hashing & request-processing work phases when A) working with "changed/ bound data" from the UI if you compare/hash on "infrequently changed fields", or B) working with "unsaved data", if you compare/hash on ID.

Equals/HashCode -- if a unique Business Key is not available, use a non-transient UUID which is created when the entity is initialized

Yes, this is a good strategy when required. Be aware that UUIDs are not free, performance-wise though -- and clustering complicates things.

Equals/HashCode -- never refer to related entities

"If related entity (like a parent entity) needs to be part of the Business Key then add a non insertable, non updatable field to store the parent id (with the same name as the ManytoOne JoinColumn) and use this id in the equality check"

Sounds like good advice.

Hope this helps!

What's the difference between passing by reference vs. passing by value?

If you don't want to change the value of the original variable after passing it into a function, the function should be constructed with a "pass by value" parameter.

Then the function will have ONLY the value but not the address of the passed in variable. Without the variable's address, the code inside the function cannot change the variable value as seen from the outside of the function.

But if you want to give the function the ability to change the value of the variable as seen from the outside, you need to use pass by reference. As both the value and the address (reference) are passed in and available inside the function.

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Use preventDefault() to stop the event of submit button and in ajax call success submit the form using submit():

$('#btnSave').click(function (e) {
    e.preventDefault(); // <------------------ stop default behaviour of button
    var element = this;    
    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.status == "Success") {
                alert("Done");
                $(element).closest("form").submit(); //<------------ submit form
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

How to do a deep comparison between 2 objects with lodash?

Here's a concise solution:

_.differenceWith(a, b, _.isEqual);

C++ - how to find the length of an integer

If you can use C libraries then one method would be to use sprintf, e.g.

#include <cstdio>

char s[32];

int len = sprintf(s, "%d", i);

Android: Bitmaps loaded from gallery are rotated in ImageView

I improved upon the answer by Teo Inke. It no longer rotates the image unless it is actually necessary. It is also easier to read, and should run faster.

// Load Image
Bitmap bitmap = BitmapFactory.decodeFile(filePath);

// Rotate Image if Needed
try
{
    // Determine Orientation
    ExifInterface exif = new ExifInterface(filePath);
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

    // Determine Rotation
    int rotation = 0;
    if      (orientation == 6)      rotation = 90;
    else if (orientation == 3)      rotation = 180;
    else if (orientation == 8)      rotation = 270;

    // Rotate Image if Necessary
    if (rotation != 0)
    {
        // Create Matrix
        Matrix matrix = new Matrix();
        matrix.postRotate(rotation);

        // Rotate Bitmap
        Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); 

        // Pretend none of this ever happened!
        bitmap.recycle();
        bitmap = rotated;
        rotated = null;
     }
}
catch (Exception e)
{
    // TODO: Log Error Messages Here
}

// TODO: Use Result Here
xxx.setBitmap(bitmap);

Jasmine.js comparing arrays

You can compare an array like the below mentioned if the array has some values

it('should check if the array are equal', function() {
        var mockArr = [1, 2, 3];
        expect(mockArr ).toEqual([1, 2, 3]);
 });

But if the array that is returned from some function has more than 1 elements and all are zero then verify by using

expect(mockArray[0]).toBe(0);

Access to the requested object is only available from the local network phpmyadmin

Nothing worked for me but following thing was awesome:

1) Open

httpd-xampp.conf

which is at

/opt/lampp/etc/extra/

2) Find <Directory "/opt/lampp/phpmyadmin">

3) Now just add Require all granted before

4) So the code will look like this
<Directory "/opt/lampp/phpmyadmin"> AllowOverride AuthConfig Limit Order allow,deny Allow from all Require all granted </Directory>

5) Now finally Restart the xampp with this command /opt/lampp/lampp restart

That's it and you are Done!

It also work with xampp. :)

How to install node.js as windows service?

I found the thing so useful that I built an even easier to use wrapper around it (npm, github).

Installing it:

npm install -g qckwinsvc

Installing your service:

qckwinsvc

prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed

Uninstalling your service:

qckwinsvc --uninstall

prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled

Escape single quote character for use in an SQLite query

for replace all (') in your string, use

.replace(/\'/g,"''")

example:

sample = "St. Mary's and St. John's";
escapedSample = sample.replace(/\'/g,"''")

Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

How do I get extra data from intent on Android?

Pass the intent with value on First Activity:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);

Receive intent on second Activity;-

Intent intent = getIntent();
String user = intent.getStringExtra("uid");
String pass = intent.getStringExtra("pwd");

We use generally two method in intent to send the value and to get the value. For sending the value we will use intent.putExtra("key", Value); and during receive intent on another activity we will use intent.getStringExtra("key"); to get the intent data as String or use some other available method to get other types of data (Integer, Boolean, etc.). The key may be any keyword to identify the value means that what value you are sharing. Hope it will work for you.

Alter column, add default constraint

Actually you have to Do Like below Example, which will help to Solve the Issue...

drop table ABC_table

create table ABC_table
(
    names varchar(20),
    age int
)

ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names

insert into ABC(age) values(10)

select * from ABC

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

jQuery get the id/value of <li> element after click function

If You Have Multiple li elements inside an li element then this will definitely help you, and i have checked it and it works....

<script>
$("li").on('click', function() {
          alert(this.id);
          return false;
      });
</script>

MySQL my.cnf performance tuning recommendations

Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.

https://tools.percona.com/wizard

Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/

Everyone points to key_buffer_size first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).

How do I enumerate through a JObject?

If you look at the documentation for JObject, you will see that it implements IEnumerable<KeyValuePair<string, JToken>>. So, you can iterate over it simply using a foreach:

foreach (var x in obj)
{
    string name = x.Key;
    JToken value = x.Value;
    …
}

plot.new has not been called yet

In my case, I was trying to call plot(x, y) and lines(x, predict(yx.lm), col="red") in two separate chunks in Rmarkdown file. It worked without problems when running chunk by chunk, but the corresponding document wouldn't knit. After I moved all plotting calls within one chunk, problem was resolved.

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

I just tested your snippet, and their is no double spacing line here. The end-of-line are \r\n, so what i would check in your case is:

  1. your editor is reading correctly DOS file
  2. no \n exist in values of your rows dict.

(Note that even by putting a value with \n, DictWriter automaticly quote the value.)

Entity Framework : How do you refresh the model when the db changes?

You need to be careful though, You need to setup the EDMX file exactly as it was before deleting it (if you choose the delete/regenerate route), otherwise, you'll have a naming mismatch between your code and the EF generated model (especialy for pluralization and singularization)

Hope this will prevent you some headaches =)

How to uncheck checkbox using jQuery Uniform library

If you are using uniform 1.5 then use this simple trick to add or remove attribute of check
Just add value="check" in your checkbox's input field.
Add this code in uniform.js > function doCheckbox(elem){ > .click(function(){

if ( $(elem+':checked').val() == 'check' ) {
    $(elem).attr('checked','checked');           
}
else {
    $(elem).removeAttr('checked');
}   

if you not want to add value="check" in your input box because in some cases you add two checkboxes so use this

if ($(elem).is(':checked')) {
 $(elem).attr('checked','checked');
}    
else
{    
 $(elem).removeAttr('checked');
}

If you are using uniform 2.0 then use this simple trick to add or remove attribute of check
in this classUpdateChecked($tag, $el, options) { function change

if ($el.prop) {
    // jQuery 1.6+
    $el.prop(c, isChecked);
}

To

if ($el.prop) {
    // jQuery 1.6+
    $el.prop(c, isChecked);
    if (isChecked) {
        $el.attr(c, c);
    } else {
        $el.removeAttr(c);
    }

}

How to get the pure text without HTML element using JavaScript?

This answer will work to get just the text for any HTML element.

This first parameter "node" is the element to get the text from. The second parameter is optional and if true will add a space between the text within elements if no space would otherwise exist there.

function getTextFromNode(node, addSpaces) {
    var i, result, text, child;
    result = '';
    for (i = 0; i < node.childNodes.length; i++) {
        child = node.childNodes[i];
        text = null;
        if (child.nodeType === 1) {
            text = getTextFromNode(child, addSpaces);
        } else if (child.nodeType === 3) {
            text = child.nodeValue;
        }
        if (text) {
            if (addSpaces && /\S$/.test(result) && /^\S/.test(text)) text = ' ' + text;
            result += text;
        }
    }
    return result;
}

How to present popover properly in iOS 8

I found a complete example of how to get this all to work so that you can always display a popover no matter the device/orientation https://github.com/frogcjn/AdaptivePopover_iOS8_Swift.

The key is to implement UIAdaptivePresentationControllerDelegate

func adaptivePresentationStyleForPresentationController(PC: UIPresentationController!) -> UIModalPresentationStyle {
    // This *forces* a popover to be displayed on the iPhone
    return .None
}

Then extend the example above (from Imagine Digital):

nav.popoverPresentationController!.delegate = implOfUIAPCDelegate

How to get named excel sheets while exporting from SSRS

While this usage of the PageName property on an object does in fact allow you to customize the exported sheet names in Excel, be warned that it can also update your report's namespace definitions, which could affect the ability to redeploy the report to your server.

I had a report that I applied this to within BIDS and it updated my namespace from 2008 to 2010. When I tried to publish the report to a 2008R2 report server, I got an error that the namespace was not valid and had to revert everything back. I am sure that my circumstance may be unique and perhaps this won't always happen, but I thought it worthy to post about. Once I found the problem, this page helped to revert the namespace back (There are tags that must also be removed in addition to resetting the namespace):

http://beatheadagainstwall.blogspot.com/2011/03/invalid-target-namespace-when-deploying.html?showComment=1440647962263#c5741523651495876761

Develop Android app using C#

Here is a new one (Note: in Tech Preview stage): http://www.dot42.com

It is basically a Visual Studio add-in that lets you compile your C# code directly to DEX code. This means there is no run-time requirement such as Mono.

Disclosure: I work for this company


UPDATE: all sources are now on https://github.com/dot42

What is the memory consumption of an object in Java?

The rules about how much memory is consumed depend on the JVM implementation and the CPU architecture (32 bit versus 64 bit for example).

For the detailed rules for the SUN JVM check my old blog

Regards, Markus

Convert a row of a data frame to vector

Columns of data frames are already vectors, you just have to pull them out. Note that you place the column you want after the comma, not before it:

> newV <- df[,1]
> newV
[1] 1 2 4 2

If you actually want a row, then do what Ben said and please use words correctly in the future.

CSV in Python adding an extra carriage return, on Windows

You can introduce the lineterminator='\n' parameter in the csv writer command.

import csv
delimiter='\t'
with open('tmp.csv', '+w', encoding='utf-8') as stream:
    writer = csv.writer(stream, delimiter=delimiter, quoting=csv.QUOTE_NONE, quotechar='',  lineterminator='\n')
    writer.writerow(['A1' , 'B1', 'C1'])
    writer.writerow(['A2' , 'B2', 'C2'])
    writer.writerow(['A3' , 'B3', 'C3'])

How do I include negative decimal numbers in this regular expression?

If you have this val="-12XXX.0abc23" and you want to extract only the decimal number, in this case this regex (^-?[0-9]\d*(\.\d+)?$) will not help you to achieve it.
this is the proper code with the correct detection regex:

_x000D_
_x000D_
var val="-12XXX.0abc23";_x000D_
val = val.replace(/^\.|[^-?\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');_x000D_
console.log(val);
_x000D_
_x000D_
_x000D_

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

In Visual Studio: Properties -> Advanced -> Entry Point -> write just the name of the function you want the program to begin running from, case sensitive, without any brackets and command line arguments.

Create a remote branch on GitHub

Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.

To create a new branch with a copy of your current state

git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server

Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.

Difference between java HH:mm and hh:mm on SimpleDateFormat

Actually the last one is not weird. Code is setting the timezone for working instead of working2.

SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).

Fixing this error gives:

24:00:00
00:00:00
01:00:00

How can I add new item to the String array?

From arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

enter image description here

So in the case of a String array, once you create it with some length, you can't modify it, but you can add elements until you fill it.

String[] arr = new String[10]; // 10 is the length of the array.
arr[0] = "kk";
arr[1] = "pp";
...

So if your requirement is to add many objects, it's recommended that you use Lists like:

List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp"); 

Convert a SQL query result table to an HTML table for email

Following piece of code, I have prepared for generating the HTML file for documentation which includes Table Name and Purpose in each table and Table Metadata information. It might be helpful!

use Your_Database_Name;
print '<!DOCTYPE html>'
PRINT '<html><body>'
SET NOCOUNT ON
DECLARE @tableName VARCHAR(30)
DECLARE tableCursor CURSOR LOCAL FAST_FORWARD FOR
    SELECT T.name AS TableName 
      FROM sys.objects AS T
     WHERE T.type_desc = 'USER_TABLE'
     ORDER BY T.name
OPEN tableCursor
FETCH NEXT FROM tableCursor INTO @tableName
WHILE @@FETCH_STATUS = 0 BEGIN
    print '<table>'
    print '<tr><td><b>Table Name: <b></td><td>'+@tableName+'</td></tr>'
    print '<tr><td><b>Prupose: <b></td><td>????YOu can Fill later????</td></tr>'
    print '</table>'

    print '<table>'
    print '<tr><th>ColumnName</th><th>DataType</th><th>Size</th><th>PrecScale</th><th>Nullable</th><th>Default</th><th>Identity</th><th>Remarks</th></tr>'
    SELECT  concat('<tr><td>',
            LEFT(C.name, 30) /*AS ColumnName*/,'</td><td>',
           LEFT(ISC.DATA_TYPE, 10) /*AS DataType*/,'</td><td>',
           C.max_length /*AS Size*/,'</td><td>',
           CAST(P.precision AS VARCHAR(4)) + '/' + CAST(P.scale AS VARCHAR(4)) /*AS PrecScale*/,'</td><td>',
           CASE WHEN C.is_nullable = 1 THEN 'Null' ELSE 'No Null' END /*AS [Nullable]*/,'</td><td>',
           LEFT(ISNULL(ISC.COLUMN_DEFAULT, ' '), 5)  /*AS [Default]*/,'</td><td>',
           CASE WHEN C.is_identity = 1 THEN 'Identity' ELSE '' END /*AS [Identity]*/,'</td><td></td></tr>')
    FROM   sys.objects AS T
           JOIN sys.columns AS C ON T.object_id = C.object_id
           JOIN sys.types AS P ON C.system_type_id = P.system_type_id and c.user_type_id = p.user_type_id
           JOIN INFORMATION_SCHEMA.COLUMNS AS ISC ON T.name = ISC.TABLE_NAME AND C.name = ISC.COLUMN_NAME
    WHERE  T.type_desc = 'USER_TABLE'
      AND  T.name = @tableName
    ORDER BY T.name, ISC.ORDINAL_POSITION
    print '</table>'
    print '</br>'
    FETCH NEXT FROM tableCursor INTO @tableName

END

CLOSE tableCursor
DEALLOCATE tableCursor
SET NOCOUNT OFF
PRINT '</body></html>'

The EntityManager is closed

I had the same error using Symfony 5 / Doctrine 2. One of my fields was named using a MySQL reserved word "order", causing a DBALException. When you want to use a reserved word, you have to escape it's name using back-ticks. In annotation form :

@ORM\Column(name="`order`", type="integer", nullable=false)

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

How to get UTC value for SYSDATE on Oracle

select sys_extract_utc(systimestamp) from dual;

Won't work on Oracle 8, though.

Downloading video from YouTube

To all interested:

The "Coding for fun" book's chapter 4 "InnerTube: Download, Convert, and Sync YouTube Videos" deals with the topic. The code and discussion are at http://www.c4fbook.com/InnerTube.

[PLEASE BEWARE] While the overall concepts are valid some years after the publication, non-documented details of the youtube internals the project relies on can have changed (see the comment at the bottom of the page behind the second link).

How to customize the background color of a UITableViewCell?

You need to set the backgroundColor of the cell's contentView to your color. If you use accessories (such as disclosure arrows, etc), they'll show up as white, so you may need to roll custom versions of those.

Regular expression [Any number]

var mask = /^\d+$/;
if ( myString.exec(mask) ){
   /* That's a number */
}

How to set the color of an icon in Angular Material?

color="white" is not a known attribute to Angular Material.

color attribute can changed to primary, accent, and warn. as said in this doc

your icon inside button works because its parent class button has css class of color:white, or may be your color="accent" is white. check the developer tools to find it.

By default, icons will use the current font color

How do I expire a PHP session after 30 minutes?

Just Store the current time and If it exceeds 30 minutes by comparing then destroy the current session.

Disabling SSL Certificate Validation in Spring RestTemplate

What you need to add is a custom HostnameVerifier class bypasses certificate verification and returns true

HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

This needs to be placed appropriately in your code.

How to hide/show more text within a certain length (like youtube)

If you need some complete solution, you can use this :

http://jsfiddle.net/7Vv8u/2703/

JS (jQuery)

var text = $('.text-overflow'),
     btn = $('.btn-overflow'),
       h = text.scrollHeight; 

if(h > 120) {
    btn.addClass('less');
    btn.css('display', 'block');
}

btn.click(function(e) 
{
  e.stopPropagation();

  if (btn.hasClass('less')) {
      btn.removeClass('less');
      btn.addClass('more');
      btn.text('Show less');

      text.animate({'height': h});
  } else {
      btn.addClass('less');
      btn.removeClass('more');
      btn.text('Show more');
      text.animate({'height': '120px'});
  }  
});

HTML

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<div class="text-overflow">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<a class="btn-overflow" href="#">Show more</a> 

CSS

.text-overflow {
  width:250px;
  height:120px;
  display:block; 
  overflow:hidden;
  word-break: break-word;
  word-wrap: break-word;
}

.btn-overflow {
  display: none;
  text-decoration: none; 
}

show dbs gives "Not Authorized to execute command" error

It was Docker running in the background in my case. If you have Docker installed, you may wanna close it and try again.

Maven plugin not using Eclipse's proxy settings

Maven plugin uses a settings file where the configuration can be set. Its path is available in Eclipse at Window|Preferences|Maven|User Settings. If the file doesn't exist, create it and put on something like this:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>192.168.1.100</host>
      <port>6666</port>
      <username></username>
      <password></password>
      <nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
    </proxy>
  </proxies>
  <profiles/>
  <activeProfiles/>
</settings>

After editing the file, it's just a matter of clicking on Update Settings button and it's done. I've just done it and it worked :)

Parse a URI String into Name-Value Collection

If you are using Spring, add an argument of type @RequestParam Map<String,String> to your controller method, and Spring will construct the map for you!

annotation to make a private method public only for test classes

Or you can extract this method to some strategy object. In this case you can easily test extracted class and don't make method public or some magic with reflection/bytecode.

How do I align spans or divs horizontally?

You can use divs with the float: left; attribute which will make them appear horizontally next to each other, but then you may need to use clearing on the following elements to make sure they don't overlap.

Adding items to an object through the .push() method

Another way of doing it would be:

stuff = Object.assign(stuff, {$(this).attr('value'):$(this).attr('checked')});

Read more here: Object.assign()

How to add two strings as if they were numbers?

try

var x = parseFloat(num1) + parseFloat(num2) ;

or, depending on your needs:

var x = parseInt(num1) + parseInt(num2) ;

http://www.javascripter.net/faq/convert2.htm

You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also

and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.

Add key value pair to all objects in array

@Redu's solution is a good solution

arrOfObj.map(o => o.isActive = true;) but Array.map still counts as looping through all items.

if you absolutely don't want to have any looping here's a dirty hack :

Object.defineProperty(Object.prototype, "isActive",{
  value: true,
  writable: true,
  configurable: true,
  enumerable: true
});

my advice is not to use it carefully though, it will patch absolutely all javascript Objects (Date, Array, Number, String or any other that inherit Object ) which is really bad practice...

How to extract numbers from string in c?

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
        // Found a number
        long val = strtol(p, &p, 10); // Read number
        printf("%ld\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        p++;
    }
}

Link to ideone.

Using json_encode on objects in PHP (regardless of scope)

I usually include a small function in my objects which allows me to dump to array or json or xml. Something like:

public function exportObj($method = 'a')
{
     if($method == 'j')
     {
         return json_encode(get_object_vars($this));
     }
     else
     {
         return get_object_vars($this);
     }
}

either way, get_object_vars() is probably useful to you.

How to show and update echo on same line

If I have understood well, you can get it replacing your echo with the following line:

echo -ne "Movie $movies - $dir ADDED! \033[0K\r"

Here is a small example that you can run to understand its behaviour:

#!/bin/bash
for pc in $(seq 1 100); do
    echo -ne "$pc%\033[0K\r"
    sleep 1
done
echo

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

I'm going to go against the general wisdom here that std::copy will have a slight, almost imperceptible performance loss. I just did a test and found that to be untrue: I did notice a performance difference. However, the winner was std::copy.

I wrote a C++ SHA-2 implementation. In my test, I hash 5 strings using all four SHA-2 versions (224, 256, 384, 512), and I loop 300 times. I measure times using Boost.timer. That 300 loop counter is enough to completely stabilize my results. I ran the test 5 times each, alternating between the memcpy version and the std::copy version. My code takes advantage of grabbing data in as large of chunks as possible (many other implementations operate with char / char *, whereas I operate with T / T * (where T is the largest type in the user's implementation that has correct overflow behavior), so fast memory access on the largest types I can is central to the performance of my algorithm. These are my results:

Time (in seconds) to complete run of SHA-2 tests

std::copy   memcpy  % increase
6.11        6.29    2.86%
6.09        6.28    3.03%
6.10        6.29    3.02%
6.08        6.27    3.03%
6.08        6.27    3.03%

Total average increase in speed of std::copy over memcpy: 2.99%

My compiler is gcc 4.6.3 on Fedora 16 x86_64. My optimization flags are -Ofast -march=native -funsafe-loop-optimizations.

Code for my SHA-2 implementations.

I decided to run a test on my MD5 implementation as well. The results were much less stable, so I decided to do 10 runs. However, after my first few attempts, I got results that varied wildly from one run to the next, so I'm guessing there was some sort of OS activity going on. I decided to start over.

Same compiler settings and flags. There is only one version of MD5, and it's faster than SHA-2, so I did 3000 loops on a similar set of 5 test strings.

These are my final 10 results:

Time (in seconds) to complete run of MD5 tests

std::copy   memcpy      % difference
5.52        5.56        +0.72%
5.56        5.55        -0.18%
5.57        5.53        -0.72%
5.57        5.52        -0.91%
5.56        5.57        +0.18%
5.56        5.57        +0.18%
5.56        5.53        -0.54%
5.53        5.57        +0.72%
5.59        5.57        -0.36%
5.57        5.56        -0.18%

Total average decrease in speed of std::copy over memcpy: 0.11%

Code for my MD5 implementation

These results suggest that there is some optimization that std::copy used in my SHA-2 tests that std::copy could not use in my MD5 tests. In the SHA-2 tests, both arrays were created in the same function that called std::copy / memcpy. In my MD5 tests, one of the arrays was passed in to the function as a function parameter.

I did a little bit more testing to see what I could do to make std::copy faster again. The answer turned out to be simple: turn on link time optimization. These are my results with LTO turned on (option -flto in gcc):

Time (in seconds) to complete run of MD5 tests with -flto

std::copy   memcpy      % difference
5.54        5.57        +0.54%
5.50        5.53        +0.54%
5.54        5.58        +0.72%
5.50        5.57        +1.26%
5.54        5.58        +0.72%
5.54        5.57        +0.54%
5.54        5.56        +0.36%
5.54        5.58        +0.72%
5.51        5.58        +1.25%
5.54        5.57        +0.54%

Total average increase in speed of std::copy over memcpy: 0.72%

In summary, there does not appear to be a performance penalty for using std::copy. In fact, there appears to be a performance gain.

Explanation of results

So why might std::copy give a performance boost?

First, I would not expect it to be slower for any implementation, as long as the optimization of inlining is turned on. All compilers inline aggressively; it is possibly the most important optimization because it enables so many other optimizations. std::copy can (and I suspect all real world implementations do) detect that the arguments are trivially copyable and that memory is laid out sequentially. This means that in the worst case, when memcpy is legal, std::copy should perform no worse. The trivial implementation of std::copy that defers to memcpy should meet your compiler's criteria of "always inline this when optimizing for speed or size".

However, std::copy also keeps more of its information. When you call std::copy, the function keeps the types intact. memcpy operates on void *, which discards almost all useful information. For instance, if I pass in an array of std::uint64_t, the compiler or library implementer may be able to take advantage of 64-bit alignment with std::copy, but it may be more difficult to do so with memcpy. Many implementations of algorithms like this work by first working on the unaligned portion at the start of the range, then the aligned portion, then the unaligned portion at the end. If it is all guaranteed to be aligned, then the code becomes simpler and faster, and easier for the branch predictor in your processor to get correct.

Premature optimization?

std::copy is in an interesting position. I expect it to never be slower than memcpy and sometimes faster with any modern optimizing compiler. Moreover, anything that you can memcpy, you can std::copy. memcpy does not allow any overlap in the buffers, whereas std::copy supports overlap in one direction (with std::copy_backward for the other direction of overlap). memcpy only works on pointers, std::copy works on any iterators (std::map, std::vector, std::deque, or my own custom type). In other words, you should just use std::copy when you need to copy chunks of data around.

Regular Expression for password validation

Is a regular expression an easier/better way to enforce a simple constraint than the more obvious way?

static bool ValidatePassword( string password )
{
  const int MIN_LENGTH =  8 ;
  const int MAX_LENGTH = 15 ;

  if ( password == null ) throw new ArgumentNullException() ;

  bool meetsLengthRequirements = password.Length >= MIN_LENGTH && password.Length <= MAX_LENGTH ;
  bool hasUpperCaseLetter      = false ;
  bool hasLowerCaseLetter      = false ;
  bool hasDecimalDigit         = false ;

  if ( meetsLengthRequirements )
  {
    foreach (char c in password )
    {
      if      ( char.IsUpper(c) ) hasUpperCaseLetter = true ;
      else if ( char.IsLower(c) ) hasLowerCaseLetter = true ;
      else if ( char.IsDigit(c) ) hasDecimalDigit    = true ;
    }
  }

  bool isValid = meetsLengthRequirements
              && hasUpperCaseLetter
              && hasLowerCaseLetter
              && hasDecimalDigit
              ;
  return isValid ;

}

Which do you think that maintenance programmer 3 years from now who needs to modify the constraint will have an easier time understanding?

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

I have seen this error , for me the issue was there was a space in the absolute path of the persistance.xml , removal of the same helped me.

How to disable EditText in Android

You can try the following method :

 private void disableEditText(EditText editText) {
    editText.setFocusable(false);
    editText.setEnabled(false);
    editText.setCursorVisible(false);
    editText.setKeyListener(null);
    editText.setBackgroundColor(Color.TRANSPARENT); 
 }

Enabled EditText :

Enabled EditText

Disabled EditText :

Disabled EditText

It works for me and hope it helps you.

How to start Apache and MySQL automatically when Windows 8 comes up

One of the latest XAMPP releases (XAMPP for Windows v5.6.11 (PHP 5.6.11) for sure, probably some earlier versions too) does not have the Control Panel with the "Svc" checkbox that allows to install Apache and MySQL as a service.

Go to your XAMPP/Apache directory instead (typically C:/xampp/apache) and run apache_installservice.bat as an administrator. There is also apache_uninstallservice.bat for uninstall.

To run MySQL as a service. Do it the same way - the location is xampp/mysql and batch files are: mysql_installservice.bat for service installation and mysql_uninstallservice.bat for removing the MySQL service.

You can check if they were installed or not by going to services manager window (press Windows + R and type: services.msc) and check if you have Apache service (I had Apache2.4) running and set to startup automatically. The MySQL service name is just: mysql.

Count distinct value pairs in multiple columns in SQL

You can also do something like:

SELECT COUNT(DISTINCT id + name + address) FROM mytable

Best way to integrate Python and JavaScript?

There's a bridge based on JavaScriptCore (from WebKit), but it's pretty incomplete: http://code.google.com/p/pyjscore/

Wait until all jQuery Ajax requests are done?

To expand upon Alex's answer, I have an example with variable arguments and promises. I wanted to load images via ajax and display them on the page after they all loaded.

To do that, I used the following:

let urlCreator = window.URL || window.webkitURL;

// Helper function for making ajax requests
let fetch = function(url) {
    return $.ajax({
        type: "get",
        xhrFields: {
            responseType: "blob"
        },
        url: url,
    });
};

// Map the array of urls to an array of ajax requests
let urls = ["https://placekitten.com/200/250", "https://placekitten.com/300/250"];
let files = urls.map(url => fetch(url));

// Use the spread operator to wait for all requests
$.when(...files).then(function() {
    // If we have multiple urls, then loop through
    if(urls.length > 1) {
        // Create image urls and tags for each result
        Array.from(arguments).forEach(data => {
            let imageUrl = urlCreator.createObjectURL(data[0]);
            let img = `<img src=${imageUrl}>`;
            $("#image_container").append(img);
        });
    }
    else {
        // Create image source and tag for result
        let imageUrl = urlCreator.createObjectURL(arguments[0]);
        let img = `<img src=${imageUrl}>`;
        $("#image_container").append(img);
    }
});

Updated to work for either single or multiple urls: https://jsfiddle.net/euypj5w9/

Scala: what is the best way to append an element to an Array?

val array2 = array :+ 4
//Array(1, 2, 3, 4)

Works also "reversed":

val array2 = 4 +: array
Array(4, 1, 2, 3)

There is also an "in-place" version:

var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

If you are using "real" IIS, this can occur if the W3SVC (World Wide Web Publishing) service is stopped.

Should seem obvious but if you accidentally stopped the service or have it set to manual this could happen to you.

I know the title says IIS express however google doesn't seem to filter out the express even when using a -Express hint so hopefully this helps someone else who found this page instead of an IIS-specific one.

Efficient SQL test query or validation query that will work across all (or most) databases

After a little bit of research along with help from some of the answers here:

SELECT 1

  • H2
  • MySQL
  • Microsoft SQL Server (according to NimChimpsky)
  • PostgreSQL
  • SQLite

SELECT 1 FROM DUAL

  • Oracle

SELECT 1 FROM any_existing_table WHERE 1=0

or

SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS

or

CALL NOW()

  • HSQLDB (tested with version 1.8.0.10)

    Note: I tried using a WHERE 1=0 clause on the second query, but it didn't work as a value for Apache Commons DBCP's validationQuery, since the query doesn't return any rows


VALUES 1 or SELECT 1 FROM SYSIBM.SYSDUMMY1

SELECT 1 FROM SYSIBM.SYSDUMMY1

  • DB2

select count(*) from systables

  • Informix

How to access array elements in a Django template?

when you render a request tou coctext some information: for exampel:

return render(request, 'path to template',{'username' :username , 'email'.email})

you can acces to it on template like this : for variabels :

{% if username %}{{ username }}{% endif %}

for array :

{% if username %}{{ username.1 }}{% endif %}
{% if username %}{{ username.2 }}{% endif %}

you can also name array objects in views.py and ten use it like:

{% if username %}{{ username.first }}{% endif %}

if there is other problem i wish to help you

python - checking odd/even numbers and changing outputs on number size

The modulo 2 solutions with %2 is good, but that requires a division and a subtraction. Because computers use binary arithmetic, a much more efficient solution is:

# This first solution does not produce a Boolean value. 
is_odd_if_zero = value & 1

# or

is_odd = (value & 1) == 1

# or

is_even = (value & 1) == 0

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

For each conflicted file you get, you can specify

git checkout --ours -- <paths>
# or
git checkout --theirs -- <paths>

From the git checkout docs

git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>...

--ours
--theirs
When checking out paths from the index, check out stage #2 (ours) or #3 (theirs) for unmerged paths.

The index may contain unmerged entries because of a previous failed merge. By default, if you try to check out such an entry from the index, the checkout operation will fail and nothing will be checked out. Using -f will ignore these unmerged entries. The contents from a specific side of the merge can be checked out of the index by using --ours or --theirs. With -m, changes made to the working tree file can be discarded to re-create the original conflicted merge result.

Throwing exceptions in a PHP Try Catch block

Throw needs an object instantiated by \Exception. Just the $e catched can play the trick.

throw $e

How do you set a default value for a MySQL Datetime column?

While defining multi-line triggers one has to change the delimiter as semicolon will be taken by MySQL compiler as end of trigger and generate error. e.g.

DELIMITER //
CREATE TRIGGER `MyTable_UPDATE` BEFORE UPDATE ON `MyTable`
FOR EACH ROW BEGIN
        -- Set the udpate date
    Set new.UpdateDate = now();
END//
DELIMITER ;

Creating an index on a table variable

The question is tagged SQL Server 2000 but for the benefit of people developing on the latest version I'll address that first.

SQL Server 2014

In addition to the methods of adding constraint based indexes discussed below SQL Server 2014 also allows non unique indexes to be specified directly with inline syntax on table variable declarations.

Example syntax for that is below.

/*SQL Server 2014+ compatible inline index syntax*/
DECLARE @T TABLE (
C1 INT INDEX IX1 CLUSTERED, /*Single column indexes can be declared next to the column*/
C2 INT INDEX IX2 NONCLUSTERED,
       INDEX IX3 NONCLUSTERED(C1,C2) /*Example composite index*/
);

Filtered indexes and indexes with included columns can not currently be declared with this syntax however SQL Server 2016 relaxes this a bit further. From CTP 3.1 it is now possible to declare filtered indexes for table variables. By RTM it may be the case that included columns are also allowed but the current position is that they "will likely not make it into SQL16 due to resource constraints"

/*SQL Server 2016 allows filtered indexes*/
DECLARE @T TABLE
(
c1 INT NULL INDEX ix UNIQUE WHERE c1 IS NOT NULL /*Unique ignoring nulls*/
)

SQL Server 2000 - 2012

Can I create a index on Name?

Short answer: Yes.

DECLARE @TEMPTABLE TABLE (
  [ID]   [INT] NOT NULL PRIMARY KEY,
  [Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
  UNIQUE NONCLUSTERED ([Name], [ID]) 
  ) 

A more detailed answer is below.

Traditional tables in SQL Server can either have a clustered index or are structured as heaps.

Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique. If not unique then SQL Server silently adds a uniqueifier to any duplicate keys to make them unique.

Non clustered indexes can also be explicitly declared as unique. Otherwise for the non unique case SQL Server adds the row locator (clustered index key or RID for a heap) to all index keys (not just duplicates) this again ensures they are unique.

In SQL Server 2000 - 2012 indexes on table variables can only be created implicitly by creating a UNIQUE or PRIMARY KEY constraint. The difference between these constraint types are that the primary key must be on non nullable column(s). The columns participating in a unique constraint may be nullable. (though SQL Server's implementation of unique constraints in the presence of NULLs is not per that specified in the SQL Standard). Also a table can only have one primary key but multiple unique constraints.

Both of these logical constraints are physically implemented with a unique index. If not explicitly specified otherwise the PRIMARY KEY will become the clustered index and unique constraints non clustered but this behavior can be overridden by specifying CLUSTERED or NONCLUSTERED explicitly with the constraint declaration (Example syntax)

DECLARE @T TABLE
(
A INT NULL UNIQUE CLUSTERED,
B INT NOT NULL PRIMARY KEY NONCLUSTERED
)

As a result of the above the following indexes can be implicitly created on table variables in SQL Server 2000 - 2012.

+-------------------------------------+-------------------------------------+
|             Index Type              | Can be created on a table variable? |
+-------------------------------------+-------------------------------------+
| Unique Clustered Index              | Yes                                 |
| Nonunique Clustered Index           |                                     |
| Unique NCI on a heap                | Yes                                 |
| Non Unique NCI on a heap            |                                     |
| Unique NCI on a clustered index     | Yes                                 |
| Non Unique NCI on a clustered index | Yes                                 |
+-------------------------------------+-------------------------------------+

The last one requires a bit of explanation. In the table variable definition at the beginning of this answer the non unique non clustered index on Name is simulated by a unique index on Name,Id (recall that SQL Server would silently add the clustered index key to the non unique NCI key anyway).

A non unique clustered index can also be achieved by manually adding an IDENTITY column to act as a uniqueifier.

DECLARE @T TABLE
(
A INT NULL,
B INT NULL,
C INT NULL,
Uniqueifier INT NOT NULL IDENTITY(1,1),
UNIQUE CLUSTERED (A,Uniqueifier)
)

But this is not an accurate simulation of how a non unique clustered index would normally actually be implemented in SQL Server as this adds the "Uniqueifier" to all rows. Not just those that require it.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I am also having the same problem and I solved by as below.
in macro have a variable called rownumber and initially i set it as zero. this is the error because no excel sheet contains row number as zero. when i set as 1 and increment what i want.
now its working fine.

increase legend font size ggplot2

You can use theme_get() to display the possible options for theme. You can control the legend font size using:

+ theme(legend.text=element_text(size=X))

replacing X with the desired size.

How to remove Left property when position: absolute?

left:auto;

This will default the left back to the browser default.


So if you have your Markup/CSS as:

<div class="myClass"></div>

.myClass
{
  position:absolute;
  left:0;
}

When setting RTL, you could change to:

<div class="myClass rtl"></div>

.myClass
{
  position:absolute;
  left:0;
}
.myClass.rtl
{
  left:auto;
  right:0;
}

enum to string in modern C++11 / C++14 / C++17 and future C++20

My solution, using a preprocessor define.

You can check this code on https://repl.it/@JomaCorpFX/nameof#main.cpp

#include <iostream>
#include <stdexcept>
#include <regex>

typedef std::string String;
using namespace std::literals::string_literals;

class Strings
{
public:
    static String TrimStart(const std::string& data)
    {
        String s = data;
        s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
            return !std::isspace(ch);
        }));
        return s;
    }

    static String TrimEnd(const std::string& data)
    {
        String s = data;
        s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
            return !std::isspace(ch);
        }).base(),
            s.end());
        return s;
    }

    static String Trim(const std::string& data)
    {
        return TrimEnd(TrimStart(data));
    }

    static String Replace(const String& data, const String& toFind, const String& toReplace)
    {
        String result = data;
        size_t pos = 0;
        while ((pos = result.find(toFind, pos)) != String::npos)
        {
            result.replace(pos, toFind.length(), toReplace);
            pos += toReplace.length();
            pos = result.find(toFind, pos);
        }
        return result;
    }

};

static String Nameof(const String& name)
{
    std::smatch groups;
    String str = Strings::Trim(name);
    if (std::regex_match(str, groups, std::regex(u8R"(^&?([_a-zA-Z]\w*(->|\.|::))*([_a-zA-Z]\w*)$)")))
    {
        if (groups.size() == 4)
        {
            return groups[3];
        }
    }
    throw std::invalid_argument(Strings::Replace(u8R"(nameof(#). Invalid identifier "#".)", u8"#", name));
}

#define nameof(name) Nameof(u8## #name ## s)
#define cnameof(name) Nameof(u8## #name ## s).c_str()

enum TokenType {
    COMMA,
    PERIOD,
    Q_MARK
};

struct MyClass
{
    enum class MyEnum : char {
        AAA = -8,
        BBB = '8',
        CCC = AAA + BBB
    };
};

int main() {
    String greetings = u8"Hello"s;
    std::cout << nameof(COMMA) << std::endl;
    std::cout << nameof(TokenType::PERIOD) << std::endl;
    std::cout << nameof(TokenType::Q_MARK) << std::endl;
    std::cout << nameof(int) << std::endl;
    std::cout << nameof(std::string) << std::endl;
    std::cout << nameof(Strings) << std::endl;
    std::cout << nameof(String) << std::endl;
    std::cout << nameof(greetings) << std::endl;
    std::cout << nameof(&greetings) << std::endl;
    std::cout << nameof(greetings.c_str) << std::endl;
    std::cout << nameof(std::string::npos) << std::endl;
    std::cout << nameof(MyClass::MyEnum::AAA) << std::endl;
    std::cout << nameof(MyClass::MyEnum::BBB) << std::endl;
    std::cout << nameof(MyClass::MyEnum::CCC) << std::endl;


    std::cin.get();
    return 0;
}

Output

COMMA
PERIOD
Q_MARK
int
string
Strings
String
greetings
greetings
c_str
npos
AAA
BBB
CCC

Clang

clang

Visual C++

enter image description here

Javascript ES6/ES5 find in array and change

worked for me

let returnPayments = [ ...this.payments ];

returnPayments[this.payments.findIndex(x => x.id == this.payment.id)] = this.payment;

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:

' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook

' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook

' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)

Set customerWorkbook = Application.Workbooks.Open(customerFilename)

' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)

targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value

' Close customer workbook
customerWorkbook.Close

Clearing <input type='file' /> using jQuery

I have managed to get this to work using the following...

function resetFileElement(ele) 
{
    ele.val(''); 
    ele.wrap('<form>').parent('form').trigger('reset');   
    ele.unwrap();
    ele.prop('files')[0] = null;
    ele.replaceWith(ele.clone());    
}

This has been tested in IE10, FF, Chrome & Opera.

There are two caveats...

  1. Still doesn't work properly in FF, if you refresh the page, the file element gets re-populated with the selected file. Where it is getting this info from is beyond me. What else related to a file input element could I possible try to clear?

  2. Remember to use delegation on any events you had attached to the file input element, so they still work when the clone is made.

What I don't understand is who on earth thought not allowing you to clear an input field from an invalid unacceptable file selection was a good idea?

OK, don't let me dynamically set it with a value so I can't leach files from a user's OS, but let me clear an invalid selection without resetting an entire form.

It's not like 'accept' does anything other than a filter anyhow and in IE10, it doesn't even understand MS Word mime types, it's a joke!

Setting the default ssh key location

If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:

IdentityFile ~/.foo/identity

man ssh_config to find other config options.

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

how I can show the sum of in a datagridview column?

Use LINQ if you can.

  label1.Text =  dataGridView1.Rows.Cast<DataGridViewRow>()
                                   .AsEnumerable()
                                   .Sum(x => int.Parse(x.Cells[1].Value.ToString()))
                                   .ToString();

How to know which is running in Jupyter notebook?

Creating a virtual environment for Jupyter Notebooks

A minimal Python install is

sudo apt install python3.7 python3.7-venv python3.7-minimal python3.7-distutils python3.7-dev python3.7-gdbm python3-gdbm-dbg python3-pip

Then you can create and use the environment

/usr/bin/python3.7 -m venv test
cd test
source test/bin/activate
pip install jupyter matplotlib seaborn numpy pandas scipy
# install other packages you need with pip/apt
jupyter notebook
deactivate

You can make a kernel for Jupyter with

ipython3 kernel install --user --name=test

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

How to use hex() without 0x in Python?

You can simply write

hex(x)[2:]

to get the first two characters removed.

Best way to test for a variable's existence in PHP; isset() is clearly broken

As an addition to greatbigmassive's discussion of what NULL means, consider what "the existence of a variable" actually means.

In many languages, you have to explicitly declare every variable before you use it; this may determine its type, but more importantly it declares its scope. A variable "exists" everywhere in its scope, and nowhere outside it - be that a whole function, or a single "block".

Within its scope, a variable assigns some meaning to a label which you, the programmer, have chosen. Outside its scope, that label is meaningless (whether you use the same label in a different scope is basically irrelevant).

In PHP, variables do not need to be declared - they come to life as soon as you need them. When you write to a variable for the first time, PHP allocates an entry in memory for that variable. If you read from a variable that doesn't currently have an entry, PHP considers that variable to have the value NULL.

However, automatic code quality detectors will generally warn you if you use a variable without "initialising" it first. Firstly, this helps detect typos, such as assigning to $thingId but reading from $thing_id; but secondly, it forces you to consider the scope over which that variable has meaning, just as a declaration would.

Any code that cares whether a variable "exists" is part of the scope of that variable - whether or not it has been initialised, you as a programmer have given that label meaning at that point of the code. Since you're using it, it must in some sense "exist", and if it exists, it must have an implicit value; in PHP, that implicit value is null.

Because of the way PHP works, it is possible to write code that treats the namespace of existent variables not as a scope of labels you have given meaning to, but as some kind of key-value store. You can, for instance, run code like this: $var = $_GET['var_name']; $$var = $_GET['var_value'];. Just because you can, doesn't mean it's a good idea.

It turns out, PHP has a much better way of representing key-value stores, called associative arrays. And although the values of an array can be treated like variables, you can also perform operations on the array as a whole. If you have an associative array, you can test if it contains a key using array_key_exists().

You can also use objects in a similar way, dynamically setting properties, in which case you can use property_exists() in exactly the same way. Of course, if you define a class, you can declare which properties it has - you can even choose between public, private, and protected scope.

Although there is a technical difference between a variable (as opposed to an array key, or an object property) that hasn't been initialised (or that has been explicitly unset()) and one whose value is null, any code that considers that difference to be meaningful is using variables in a way they're not meant to be used.

How do I add PHP code/file to HTML(.html) files?

You can't run PHP in .html files because the server does not recognize that as a valid PHP extension unless you tell it to. To do this you need to create a .htaccess file in your root web directory and add this line to it:

AddType application/x-httpd-php .htm .html

This will tell Apache to process files with a .htm or .html file extension as PHP files.

Viewing root access files/folders of android on windows

You can use Eclipse DDMS perspective to see connected devices and browse through files, you can also pull and push files to the device. You can also do a bunch of stuff using DDMS, this link explains a little bit more of DDMS uses.

EDIT:

If you just want to copy a database you can locate the database on eclipse DDMS file explorer, select it and then pull the database from the device to your computer.

How to run php files on my computer

3 easy steps to run your PHP program is:

  1. The easiest way is to install MAMP!

  2. Do a 2-minute setup of MAMP.

  3. Open the localhost server in your browser at the created port to see your program up and runing!

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

In my case (not necessarily be the solution for you, but it may be helpful for someone), the solution was:

  1. Go menu Tools ? Extensions and Updates

  2. Select the Online tab from the right panel

  3. Search for the words web tools, and then select Microsoft ASP.NET and Web Tools and install it.

In my case, this was missing from my computer because of a lot of repairing operations for Visual Studio.

Get decimal portion of a number with JavaScript

Language independent way:

var a = 3.2;
var fract = a * 10 % 10 /10; //0.2
var integr = a - fract; //3

note that it correct only for numbers with one fractioanal lenght )

How to show Page Loading div until the page has finished loading?

Well, this largely depends on how you're loading the elements needed in the 'intensive call', my initial thought is that you're doing those loads via ajax. If that's the case, then you could use the 'beforeSend' option and make an ajax call like this:

$.ajax({
  type: 'GET',
  url: "some.php",
  data: "name=John&location=Boston",

  beforeSend: function(xhr){           <---- use this option here
     $('.select_element_you_want_to_load_into').html('Loading...');
  },

  success: function(msg){
     $('.select_element_you_want_to_load_into').html(msg);
  }
});

EDIT I see, in that case, using one of the 'display:block'/'display:none' options above in conjunction with $(document).ready(...) from jQuery is probably the way to go. The $(document).ready() function waits for the entire document structure to be loaded before executing (but it doesn't wait for all media to load). You'd do something like this:

$(document).ready( function() {
  $('table#with_slow_data').show();
  $('div#loading image or text').hide();
});

How do I use disk caching in Picasso?

I use this code and worked, maybe useful for you:

public static void makeImageRequest(final View parentView,final int id, final String imageUrl) {

    final int defaultImageResId = R.mipmap.user;
    final ImageView imageView = (ImageView) parentView.findViewById(id);
    Picasso.with(context)
            .load(imageUrl)
            .networkPolicy(NetworkPolicy.OFFLINE)
            .into(imageView, new Callback() {
                @Override
                public void onSuccess() {
                Log.v("Picasso","fetch image success in first time.");
                }

                @Override
                public void onError() {
                    //Try again online if cache failed
                    Log.v("Picasso","Could not fetch image in first time...");
                    Picasso.with(context).load(imageUrl).networkPolicy(NetworkPolicy.NO_CACHE)
                            .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).error(defaultImageResId)
                            .into(imageView, new Callback() {

                                @Override
                                public void onSuccess() {
                                    Log.v("Picasso","fetch image success in try again.");
                                }

                                @Override
                                public void onError() {
                                  Log.v("Picasso","Could not fetch image again...");
                                }

                            });
                }
            });

}

How do I get a class instance of generic type T?

A better route than the Class the others suggested is to pass in an object that can do what you would have done with the Class, e.g., create a new instance.

interface Factory<T> {
  T apply();
}

<T> void List<T> make10(Factory<T> factory) {
  List<T> result = new ArrayList<T>();
  for (int a = 0; a < 10; a++)
    result.add(factory.apply());
  return result;
}

class FooFactory<T> implements Factory<Foo<T>> {
  public Foo<T> apply() {
    return new Foo<T>();
  }
}

List<Foo<Integer>> foos = make10(new FooFactory<Integer>());

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

What is the difference between an int and an Integer in Java and C#?

In Java, the 'int' type is a primitive, whereas the 'Integer' type is an object.

In C#, the 'int' type is the same as System.Int32 and is a value type (ie more like the java 'int'). An integer (just like any other value types) can be boxed ("wrapped") into an object.


The differences between objects and primitives are somewhat beyond the scope of this question, but to summarize:

Objects provide facilities for polymorphism, are passed by reference (or more accurately have references passed by value), and are allocated from the heap. Conversely, primitives are immutable types that are passed by value and are often allocated from the stack.

C# "as" cast vs classic cast

With the "classic" method, if the cast fails, an InvalidCastException is thrown. With the as method, it results in null, which can be checked for, and avoid an exception being thrown.

Also, you can only use as with reference types, so if you are typecasting to a value type, you must still use the "classic" method.

Note:

The as method can only be used for types that can be assigned a null value. That use to only mean reference types, but when .NET 2.0 came out, it introduced the concept of a nullable value type. Since these types can be assigned a null value, they are valid to use with the as operator.

Difference between UTF-8 and UTF-16?

Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.

Other than sharing same unicode number for given character, each one is their own format.

UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...

UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.

Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.

Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.

Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )

So, people use UTF-8 where ever possible.

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.

How to install Java SDK on CentOS?

I have written a shell script to install/uninstall java on centos. You can get it done by just run the shell. The core of this shell is :

1.download the jdk rpm(RedHat Package Manager) package.
2.install java using rpm.

You can see more detail here: https://github.com/daikaixian/WaterShell/tree/master/program_installer

Hope it works for you.

How to pass parameters to maven build using pom.xml?

If we have parameter like below in our POM XML

<version>${project.version}.${svn.version}</version>
  <packaging>war</packaging>

I run maven command line as follows :

mvn clean install package -Dproject.version=10 -Dsvn.version=1

What's the point of the X-Requested-With header?

A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.

Only the following headers are allowed cross domain:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type

any others cause a "pre-flight" request to be issued in CORS supported browsers.

Without CORS it is not possible to add X-Requested-With to a cross domain XHR request.

If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin header could be an option in supported browsers, although you will leave old browsers vulnerable.)

New Flash bypass discovered

You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.

OWASP Recommend combining this with an Origin and Referer check:

This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)

However, for the reasons already discussed checking Origin can be tricky.

Update

Written a more in depth blog post on CORS, CSRF and X-Requested-With here.

How do you use the ? : (conditional) operator in JavaScript?

This is probably not exactly the most elegant way to do this. But for someone who is not familiar with ternary operators, this could prove useful. My personal preference is to do 1-liner fallbacks instead of condition-blocks.

  // var firstName = 'John'; // Undefined
  var lastName = 'Doe';

  // if lastName or firstName is undefined, false, null or empty => fallback to empty string
  lastName = lastName || '';
  firstName = firstName || '';

  var displayName = '';

  // if lastName (or firstName) is undefined, false, null or empty
  // displayName equals 'John' OR 'Doe'

  // if lastName and firstName are not empty
  // a space is inserted between the names
  displayName = (!lastName || !firstName) ? firstName + lastName : firstName + ' ' + lastName;


  // if display name is undefined, false, null or empty => fallback to 'Unnamed'
  displayName = displayName || 'Unnamed';

  console.log(displayName);

Ternary Operator

How to delete a cookie?

Here a good link on Quirksmode.

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

Emulating a do-while loop in Bash

This implementation:

  • Has no code duplication
  • Doesn't require extra functions()
  • Doesn't depend on the return value of code in the "while" section of the loop:
do=true
while $do || conditions; do
  do=false
  # your code ...
done

It works with a read loop, too, skipping the first read:

do=true
while $do || read foo; do
  do=false

  # your code ...
  echo $foo
done

Regular expression to search multiple strings (Textpad)

If I understand what you are asking, it is a regular expression like this:

^(8768|9875|2353)

This matches the three sets of digit strings at beginning of line only.

Button background as transparent

You apply the background color as transparent(light gray) when you click the button.

ButtonName.setOnClickListener()

In the above method you set the background color of the button.

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Run the below commands as admin to install NuGet using Powershell:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider -Name NuGet

Cloning an array in Javascript/Typescript

Try this

const returnedTarget = Object.assign(target, source);

and pass empty array to target

in case complex objects this way works for me

$.extend(true, [], originalArray) in case of array

$.extend(true, {}, originalObject) in case of object

How to properly URL encode a string in PHP?

Here is my use case, which requires an exceptional amount of encoding. Maybe you think it contrived, but we run this on production. Coincidently, this covers every type of encoding, so I'm posting as a tutorial.

Use case description

Somebody just bought a prepaid gift card ("token") on our website. Tokens have corresponding URLs to redeem them. This customer wants to email the URL to someone else. Our web page includes a mailto link that lets them do that.

PHP code

// The order system generates some opaque token
$token = 'w%a&!e#"^2(^@azW';

// Here is a URL to redeem that token
$redeemUrl = 'https://httpbin.org/get?token=' . urlencode($token);

// Actual contents we want for the email
$subject = 'I just bought this for you';
$body = 'Please enter your shipping details here: ' . $redeemUrl;

// A URI for the email as prescribed
$mailToUri = 'mailto:?subject=' . rawurlencode($subject) . '&body=' . rawurlencode($body);

// Print an HTML element with that mailto link
echo '<a href="' . htmlspecialchars($mailToUri) . '">Email your friend</a>';

Note: the above assumes you are outputting to a text/html document. If your output media type is text/json then simply use $retval['url'] = $mailToUri; because output encoding is handled by json_encode().

Test case

  1. Run the code on a PHP test site (is there a canonical one I should mention here?)
  2. Click the link
  3. Send the email
  4. Get the email
  5. Click that link

You should see:

"args": {
  "token": "w%a&!e#\"^2(^@azW"
}, 

And of course this is the JSON representation of $token above.

Select method in List<t> Collection

you can also try

var query = from p in list
            where p.Age > 18
            select p;

How to remove a directory from git repository?

If you remove the files in the directory (with git rm as the other answers explain), then the directory no longer exists as far as git is concerned. You cannot commit an empty directory, nor can you remove one.

This is unlike subversion where you have to explicitly svn rm emptyfolder/, and is incidentally why the man page for git describes itself as "the stupid content tracker"

An answer on "How do I add an empty directory to a git repository" links to the FAQ on this subject:

Currently the design of the git index (staging area) only permits files to be listed, and nobody competent enough to make the change to allow empty directories has cared enough about this situation to remedy it.

Directories are added automatically when adding files inside them. That is, directories never have to be added to the repository, and are not tracked on their own.

You can say "git add <dir>" and it will add files in there.

If you really need a directory to exist in checkouts you should create a file in it. .gitignore works well for this purpose; you can leave it empty, or fill in the names of files you expect to show up in the directory.

how to display full stored procedure code?

Use \df to list all the stored procedure in Postgres.

Java: Calculating the angle between two points in degrees

Based on Saad Ahmed's answer, here is a method that can be used for any two points.

public static double calculateAngle(double x1, double y1, double x2, double y2)
{
    double angle = Math.toDegrees(Math.atan2(x2 - x1, y2 - y1));
    // Keep angle between 0 and 360
    angle = angle + Math.ceil( -angle / 360 ) * 360;

    return angle;
}

jQuery serialize does not register checkboxes

For those using the serialize() function:

(function ($) {
    var serialize = $.fn.serialize;

    $.fn.serialize = function () {
        let values = serialize.call(this);
        let checkboxes = [];

        checkboxes = checkboxes.concat(
            $('input[type=checkbox]:not(:checked)', this).map(
            function () {
                return this.name + '=false';
            }).get()
        );

        if(checkboxes.length > 0)
            values = checkboxes.join('&') + '&' + values;

        return values;
    };
})(jQuery);

Double % formatting question for printf in Java

Following is the list of conversion characters that you may use in the printf:

%d – for signed decimal integer

%f – for the floating point

%o – octal number

%c – for a character

%s – a string

%i – use for integer base 10

%u – for unsigned decimal number

%x – hexadecimal number

%% – for writing % (percentage)

%n – for new line = \n

How to get HttpContext.Current in ASP.NET Core?

As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.

HttpContext.Current was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.

HttpContext property

You can access the current HTTP context via the HttpContext property on any controller. The closest thing to your original code sample would be to pass HttpContext into the method you are calling:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        MyMethod(HttpContext);

        // Other code
    }
}

public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
    var host = $"{context.Request.Scheme}://{context.Request.Host}";

    // Other code
}

HttpContext parameter in middleware

If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically:

public Task Invoke(HttpContext context)
{
    // Do something with the current HTTP context...
}

HTTP context accessor

Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.

Request this interface in your constructor:

public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

You can then access the current HTTP context in a safe way:

var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...

IHttpContextAccessor isn't always added to the service container by default, so register it in ConfigureServices just to be safe:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    // if < .NET Core 2.2 use this
    //services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Other code...
}

Securely storing passwords for use in python script

the secure way is encrypt your sensitive data by AES and the encryption key is derivation by password-based key derivation function (PBE), the master password used to encrypt/decrypt the encrypt key for AES.

master password -> secure key-> encrypt data by the key

You can use pbkdf2

from PBKDF2 import PBKDF2
from Crypto.Cipher import AES
import os
salt = os.urandom(8)    # 64-bit salt
key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
iv = os.urandom(16)     # 128-bit IV
cipher = AES.new(key, AES.MODE_CBC, iv)

make sure to store the salt/iv/passphrase , and decrypt using same salt/iv/passphase

Weblogic used similar approach to protect passwords in config files

Access cell value of datatable

If you need a weak reference to the cell value:

object field = d.Rows[0][3]

or

object field = d.Rows[0].ItemArray[3]

Should do it

If you need a strongly typed reference (string in your case) you can use the DataRowExtensions.Field extension method:

string field = d.Rows[0].Field<string>(3);

(make sure System.Data is in listed in the namespaces in this case)

Indexes are 0 based so we first access the first row (0) and then the 4th column in this row (3)

Python: Removing list element while iterating over list

List comp:

results = [x for x in (do_action(element) for element in somelist) if check(element)]

ASP.NET Identity DbContext confusion

If you drill down through the abstractions of the IdentityDbContext you'll find that it looks just like your derived DbContext. The easiest route is Olav's answer, but if you want more control over what's getting created and a little less dependency on the Identity packages have a look at my question and answer here. There's a code example if you follow the link, but in summary you just add the required DbSets to your own DbContext subclass.

Spring can you autowire inside an abstract class?

I have that kind of spring setup working

an abstract class with an autowired field

public abstract class AbstractJobRoute extends RouteBuilder {

    @Autowired
    private GlobalSettingsService settingsService;

and several children defined with @Component annotation.

SOAP PHP fault parsing WSDL: failed to load external entity?

try this. works for me

$options = array(
    'cache_wsdl' => 0,
    'trace' => 1,
    'stream_context' => stream_context_create(array(
          'ssl' => array(
               'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
          )
    ));

$client = new SoapClient(url, $options);

Android sample bluetooth code to send a simple string via bluetooth

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

multiplayerConnect.java

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

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

public class multiplayerConnect extends AppCompatActivity {

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


String bluetooth_message="00";




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

        switch (msg_type.what){
            case MESSAGE_READ:

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

                //do some task based on recieved string

                break;
            case MESSAGE_WRITE:

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

                }
                break;

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

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

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



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

}

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

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

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

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

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

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

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

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

    else {
        set_pairedDevices = bluetoothAdapter.getBondedDevices();

        if (set_pairedDevices.size() > 0) {

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

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


public class AcceptThread extends Thread
{
    private final BluetoothServerSocket serverSocket;

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

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

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


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

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

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

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

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

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

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

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

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

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

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

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

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

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

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

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

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

multiplayer_bluetooth.xml

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

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

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

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

</LinearLayout>

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

The first suggestion in latkin's answer seems good, although I would suggest the less long-winded way below.

PS c:\temp> $global:test="one"

PS c:\temp> $test
one

PS c:\temp> function changet() {$global:test="two"}

PS c:\temp> changet

PS c:\temp> $test
two

His second suggestion however about being bad programming practice, is fair enough in a simple computation like this one, but what if you want to return a more complicated output from your variable? For example, what if you wanted the function to return an array or an object? That's where, for me, PowerShell functions seem to fail woefully. Meaning you have no choice other than to pass it back from the function using a global variable. For example:

PS c:\temp> function changet([byte]$a,[byte]$b,[byte]$c) {$global:test=@(($a+$b),$c,($a+$c))}

PS c:\temp> changet 1 2 3

PS c:\temp> $test
3
3
4

PS C:\nb> $test[2]
4

I know this might feel like a bit of a digression, but I feel in order to answer the original question we need to establish whether global variables are bad programming practice and whether, in more complex functions, there is a better way. (If there is one I'd be interested to here it.)

Publish to IIS, setting Environment Variable

To extend on @tredder's answer you can alter the environmentVariables using appcmd

Staging

%windir%\system32\inetsrv\appcmd set config "staging.example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Staging'] /commit:APPHOST

Production

%windir%\system32\inetsrv\appcmd set config "example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Production'] /commit:APPHOST

How can I detect if a selector returns null?

I like to do something like this:

$.fn.exists = function(){
    return this.length > 0 ? this : false;
}

So then you can do something like this:

var firstExistingElement = 
    $('#iDontExist').exists() ||      //<-returns false;
    $('#iExist').exists() ||          //<-gets assigned to the variable 
    $('#iExistAsWell').exists();      //<-never runs

firstExistingElement.doSomething();   //<-executes on #iExist

http://jsfiddle.net/vhbSG/

Difference Between One-to-Many, Many-to-One and Many-to-Many?

Take a look at this article: Mapping Object Relationships

There are two categories of object relationships that you need to be concerned with when mapping. The first category is based on multiplicity and it includes three types:

*One-to-one relationships.  This is a relationship where the maximums of each of its multiplicities is one, an example of which is holds relationship between Employee and Position in Figure 11.  An employee holds one and only one position and a position may be held by one employee (some positions go unfilled).
*One-to-many relationships. Also known as a many-to-one relationship, this occurs when the maximum of one multiplicity is one and the other is greater than one.  An example is the works in relationship between Employee and Division.  An employee works in one division and any given division has one or more employees working in it.
*Many-to-many relationships. This is a relationship where the maximum of both multiplicities is greater than one, an example of which is the assigned relationship between Employee and Task.  An employee is assigned one or more tasks and each task is assigned to zero or more employees. 

The second category is based on directionality and it contains two types, uni-directional relationships and bi-directional relationships.

*Uni-directional relationships.  A uni-directional relationship when an object knows about the object(s) it is related to but the other object(s) do not know of the original object.  An example of which is the holds relationship between Employee and Position in Figure 11, indicated by the line with an open arrowhead on it.  Employee objects know about the position that they hold, but Position objects do not know which employee holds it (there was no requirement to do so).  As you will soon see, uni-directional relationships are easier to implement than bi-directional relationships.
*Bi-directional relationships.  A bi-directional relationship exists when the objects on both end of the relationship know of each other, an example of which is the works in relationship between Employee and Division.  Employee objects know what division they work in and Division objects know what employees work in them. 

Import data.sql MySQL Docker Container

This one work for me

$ docker exec -i NAME_CONTAINER_MYSQL mysql -u DB_USER -pPASSWORD DATABASE < /path/to/your/file.sql

First if do you want to know what is the NAME_CONTAINER_MYSQL, you should use this command below :

$ docker ps

In the output column NAME you will see the NAME_CONTAINER_MYSQL that do you need to replace in the command above.

What is the proper way to re-attach detached objects in Hibernate?

Sorry, cannot seem to add comments (yet?).

Using Hibernate 3.5.0-Final

Whereas the Session#lock method this deprecated, the javadoc does suggest using Session#buildLockRequest(LockOptions)#lock(entity)and if you make sure your associations have cascade=lock, the lazy-loading isn't an issue either.

So, my attach method looks a bit like

MyEntity attach(MyEntity entity) {
    if(getSession().contains(entity)) return entity;
    getSession().buildLockRequest(LockOptions.NONE).lock(entity);
    return entity;

Initial tests suggest it works a treat.

Android ImageView setImageResource in code

This is how to set an image into ImageView using the setImageResource() method:

ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);

Changing file permission in Python

You can use, pathlib also

from pathlib import Path

fl = Path("file_name")

fl.chmod(0o444)

How do I deal with corrupted Git object files?

For anyone stumbling across the same issue:

I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.

How to Insert Double or Single Quotes

If you save the Excel file as a CSV format file, you might find that the result is convenient to inserting into a database, though I'm not sure all of the fields would be quoted.

Changing upload_max_filesize on PHP

I've faced the same problem , but I found out that not all the configuration settings could be set using ini_set() function , check this Where a configuration setting may be set

Retrofit and GET using parameters

AFAIK, {...} can only be used as a path, not inside a query-param. Try this instead:

public interface FooService {    

    @GET("/maps/api/geocode/json?sensor=false")
    void getPositionByZip(@Query("address") String address, Callback<String> cb);
}

If you have an unknown amount of parameters to pass, you can use do something like this:

public interface FooService {    

    @GET("/maps/api/geocode/json")
    @FormUrlEncoded
    void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
}

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

Free easy way to draw graphs and charts in C++?

My favourite has always been gnuplot. It's very extensive, so it might be a bit too complex for your needs though. It is cross-platform and there is a C++ API.

Creating a Menu in Python

This should do it. You were missing a ) and you only need """ not 4 of them. Also you don't need a elif at the end.

ans=True
while ans:
    print("""
    1.Add a Student
    2.Delete a Student
    3.Look Up Student Record
    4.Exit/Quit
    """)
    ans=raw_input("What would you like to do? ")
    if ans=="1":
      print("\nStudent Added")
    elif ans=="2":
      print("\n Student Deleted")
    elif ans=="3":
      print("\n Student Record Found")
    elif ans=="4":
      print("\n Goodbye") 
      ans = None
    else:
       print("\n Not Valid Choice Try again")

Convert generic list to dataset in C#

Have you tried binding the list to the datagridview directly? If not, try that first because it will save you lots of pain. If you have tried it already, please tell us what went wrong so we can better advise you. Data binding gives you different behaviour depending on what interfaces your data object implements. For example, if your data object only implements IEnumerable (e.g. List), you will get very basic one-way binding, but if it implements IBindingList as well (e.g. BindingList, DataView), then you get two-way binding.

AngularJS : ng-model binding not updating when changed with jQuery

Just use:

$('#selectedDueDate').val(dateText).trigger('input');

instead of:

$('#selectedDueDate').val(dateText);

How to create string with multiple spaces in JavaScript

var a = 'something' + Array(10).fill('\xa0').join('') + 'something'

number inside Array(10) can be changed to needed number of spaces

ImportError: No module named six

I did the following to solve the mentioned problem. I got the mentioned problem when I was trying to run the built exe, even I successfully built the exe using pyinstaller. I did this on Windows 10.

  1. go to https://pypi.org/project/six/#files
  2. download "six-1.14.0.tar.gz (33.9 kB)"
  3. unzip it, copy and paste "six.py" into your source directory.
  4. import "six" module into your source code (import six)
  5. run source script.

ImportError: No Module named simplejson

On Ubuntu/Debian, you can install it with apt-get install python-simplejson

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

You can also just copy the file to GAC using a command prompt. I use the following batch script to copy the DLL and restart IIS.

copy /b/v/y "PathToAssembly\MyAssembly.dll" "C:\Windows\assembly\" 
iisreset /noforce
pause

Saves the need to use or install gacutil

Add Insecure Registry to Docker

The solution with the /etc/docker/daemon.json file didn't work for me on Ubuntu.

I was able to configure Docker insecure registries on Ubuntu by providing command line options to the Docker daemon in /etc/default/docker file, e.g.:

# /etc/default/docker    
DOCKER_OPTS="--insecure-registry=a.example.com --insecure-registry=b.example.com"

The same way can be used to configure custom directory for docker images and volumes storage, default DNS servers, etc..

Now, after the Docker daemon has restarted (after executing sudo service docker restart), running docker info will show:

Insecure Registries:
  a.example.com
  b.example.com
  127.0.0.0/8

type checking in javascript

A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.

You can test if the variable contains a number, and if that number is an integer.

(typeof foo === "number") && Math.floor(foo) === foo

If the variable might be a string containing an integer and you want to see if that is the case:

foo == parseInt(foo, 10)

Should I use SVN or Git?

I have never understand this concept of "git not being good on Windows"; I develop exclusively under Windows and I have never had any problems with git.

I would definitely recommend git over subversion; its simply so much more versatile and allows "offline development" in a way subversion never really could. Its available on almost every platform imaginable and has more features than you'll probably ever use.

Build error, This project references NuGet

Quick solution that worked like a charm for me and others:

If you are using VS 2015+, just remove the following lines from the .csproj file of your project:

  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
  </Target>

In VS 2015+ Solution Explorer:

  1. Right-click project name -> Unload Project
  2. Right-click project name -> Edit .csproj
  3. Remove the lines specified above from the file and save
  4. Right-click project name -> Reload Project

Error TF30063: You are not authorized to access ... \DefaultCollection

When Visual Studio prompted me for Visual Studio Team Services credentials there are two options:

  1. Use a "Work or School"
  2. Use a "Personal" account

In my situation I was using a work email address, however, I had to select "Personal" in order to get connected. Selecting "Work or School" gave me the "tf30063 you are not authorized to access..." error.

For some reason my email address appears to be registered as "personal" even though everything is setup in Office 365 / Azure as a company. I believe the Microsoft account was created prior to our Silver Partnership status with Microsoft.

ValueError: unsupported format character while forming strings

For anyone checking this using python 3:

If you want to print the following output "100% correct":

python 3.8: print("100% correct")
python 3.7 and less: print("100%% correct")


A neat programming workaround for compatibility across diff versions of python is shown below:

Note: If you have to use this, you're probably experiencing many other errors... I'd encourage you to upgrade / downgrade python in relevant machines so that they are all compatible.

DevOps is a notable exception to the above -- implementing the following code would indeed be appropriate for specific DevOps / Debugging scenarios.

import sys

if version_info.major==3:
    if version_info.minor>=8:
        my_string = "100% correct"
    else:
        my_string = "100%% correct"

# Finally
print(my_string)

Does JavaScript pass by reference?

JavaScript is pass by value.

For primitives, primitive's value is passed. For Objects, Object's reference "value" is passed.

Example with Object:

var f1 = function(inputObject){
    inputObject.a = 2;
}

var f2 = function(){
    var inputObject = {"a": 1};
    f1(inputObject);
    console.log(inputObject.a);
}

Calling f2 results in printing out "a" value as 2 instead of 1, as the reference is passed and the "a" value in reference is updated.

Example with primitive:

var f1 = function(a){
    a = 2;
}
var f2 = function(){
    var a = 1;
    f1(a);
    console.log(a);
}

Calling f2 results in printing out "a" value as 1.

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd