Programs & Examples On #Ecmascript 5

ECMAScript is the name of the Ecma International Standard 262. It is based on the scripting language JavaScript which was delivered by Netscape to Ecma for standardization. The 5th Edition is an update of the 3rd edition specification after the cancellation of the 4th edition. It adds new features including strict mode, getters and setters, a JSON object, and new methods for Object, Array, Date, and Function prototypes.

Get array of object's keys

In case you're here looking for something to list the keys of an n-depth nested object as a flat array:

_x000D_
_x000D_
const getObjectKeys = (obj, prefix = '') => {_x000D_
  return Object.entries(obj).reduce((collector, [key, val]) => {_x000D_
    const newKeys = [ ...collector, prefix ? `${prefix}.${key}` : key ]_x000D_
    if (Object.prototype.toString.call(val) === '[object Object]') {_x000D_
      const newPrefix = prefix ? `${prefix}.${key}` : key_x000D_
      const otherKeys = getObjectKeys(val, newPrefix)_x000D_
      return [ ...newKeys, ...otherKeys ]_x000D_
    }_x000D_
    return newKeys_x000D_
  }, [])_x000D_
}_x000D_
_x000D_
console.log(getObjectKeys({a: 1, b: 2, c: { d: 3, e: { f: 4 }}}))
_x000D_
_x000D_
_x000D_

how to stop Javascript forEach?

You can use Lodash's forEach function if you don't mind using 3rd party libraries.

Example:

var _ = require('lodash');

_.forEach(comments, function (comment) {
    do_something_with(comment);

    if (...) {
        return false;     // Exits the loop.
    }
})

How to implement private method in ES6 class with Traceur

I hope this can be helpful. :)

I. Declaring vars, functions inside IIFE(Immediately-invoked function expression), those can be used only in the anonymous function. (It can be good to use "let, const" keywords without using 'var' when you need to change code for ES6.)

let Name = (function() {
  const _privateHello = function() {
  }
  class Name {
    constructor() {
    }
    publicMethod() {
      _privateHello()
    }
  }
  return Name;
})();

II. WeakMap object can be good for memoryleak trouble.

Stored variables in the WeakMap will be removed when the instance will be removed. Check this article. (Managing the private data of ES6 classes)

let Name = (function() {
  const _privateName = new WeakMap();
})();

III. Let's put all together.

let Name = (function() {
  const _privateName = new WeakMap();
  const _privateHello = function(fullName) {
    console.log("Hello, " + fullName);
  }

  class Name {
    constructor(firstName, lastName) {
      _privateName.set(this, {firstName: firstName, lastName: lastName});
    }
    static printName(name) {
      let privateName = _privateName.get(name);
      let _fullname = privateName.firstName + " " + privateName.lastName;
      _privateHello(_fullname);
    }
    printName() {
      let privateName = _privateName.get(this);
      let _fullname = privateName.firstName + " " + privateName.lastName;
      _privateHello(_fullname);
    }
  }

  return Name;
})();

var aMan = new Name("JH", "Son");
aMan.printName(); // "Hello, JH Son"
Name.printName(aMan); // "Hello, JH Son"

What is the purpose of the var keyword and when should I use it (or omit it)?

I see people are confused when declaring variables with or without var and inside or outside the function. Here is a deep example that will walk you through these steps:

See the script below in action here at jsfiddle

a = 1;// Defined outside the function without var
var b = 1;// Defined outside the function with var
alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");

function testVar1(){
    c = 1;// Defined inside the function without var
    var d = 1;// Defined inside the function with var
    alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};


testVar1();
alert("Run the 1. function again...");
testVar1();

function testVar2(){
    var d = 1;// Defined inside the function with var
    alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};

testVar2();

alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
alert("Now check console.log for the error when value d is requested next:");
alert(d);

Conclusion

  1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.
  2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2()
  3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.

Angular 4 setting selected option in Dropdown

Here is my example:

<div class="form-group">
    <label for="contactMethod">Contact method</label>
    <select 
        name="contactMethod" 
        id="contactMethod" 
        class="form-control"
        [(ngModel)]="contact.contactMethod">
        <option *ngFor="let method of contactMethods" [value]="method.id">{{ method.label }}</option>
    </select>
</div>

And in component you must get values from select:

contactMethods = [
    { id: 1, label: "Email" },
    { id: 2, label: "Phone" }
]

So, if you want select to have a default value selected (and proabbly you want that):

contact = {
    firstName: "CFR",
    comment: "No comment",
    subscribe: true,
    contactMethod: 2 // this id you'll send and get from backend
}

change pgsql port

You can also change the port when starting up:

$ pg_ctl -o "-F -p 5433" start

Or

$ postgres -p 5433

More about this in the manual.

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

I had same issue with my WPF RSS reader, I originally went with Awesomium (I think version 1.6) Awesomium is great. You get a lot of control for caching (images and HTML content), JavaScript execution, intercepting downloads and so forth. It's also super fast. The process isolation means when browser crashes it does not crash the app.

But it's also heavy, even release build adds about 10-15mb (can't remember exact number) and hence a slight start-up penalty. I then realized, only problem I had with IE browser control was that it would throw the JavaScript errors every now and again. But that was fixed with the following snippet.

I hardly used my app on XP or Vista but on Win 7 and above it never crashed (at least not because I used IE browser control)

IOleServiceProvider sp = browser.Document as IOleServiceProvider;
if (sp != null)
{
    IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
    Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E");

    webBrowser;
    sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out webBrowser);
    if (webBrowser != null)
    {
        webBrowser.GetType().InvokeMember("Silent", 
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.PutDispProperty, null, webBrowser, new object[] { silent });
    }
}

Count the items from a IEnumerable<T> without iterating?

IEnumerable doesn't support this. This is by design. IEnumerable uses lazy evaluation to get the elements you ask for just before you need them.

If you want to know the number of items without iterating over them you can use ICollection<T>, it has a Count property.

EF Core add-migration Build Failed

It's because of other projects in your solutions. e.g If you have two projects in your solution as Project A and Project B. If Project A is not successful build and then Project B data migration will fail. So you should unload Project A and add the migration to Project B again.

I think this is not a good answer but hope this help.

Uninstalling an MSI file from the command line without using msiexec

The msi file extension is mapped to msiexec (same way typing a .txt filename on a command prompt launches Notepad/default .txt file handler to display the file).

Thus typing in a filename with an .msi extension really runs msiexec with the MSI file as argument and takes the default action, install. For that reason, uninstalling requires you to invoke msiexec with uninstall switch to unstall it.

Using import fs from 'fs'

For default exports you should use:

import * as fs from 'fs';

Or in case the module has named exports:

import {fs} from 'fs';

Example:

//module1.js

export function function1() {
  console.log('f1')
}

export function function2() {
  console.log('f2')
}

export default function1;

And then:

import defaultExport, { function1, function2 } from './module1'

defaultExport();  // This calls function1
function1();
function2();

Additionally, you should use Webpack or something similar to be able to use ES6 import

Generating a WSDL from an XSD file

I'd like to differ with marc_s on this, who wrote:

a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.

WSDL does not describe functions. WSDL defines a network interface, which itself is comprised of endpoints that get messages and then sometimes reply with messages. WSDL describes the endpoints, and the request and reply messages. It is very much message oriented.

We often think of WSDL as a set of functions, but this is because the web services tools typically generate client-side proxies that expose the WSDL operations as methods or function calls. But the WSDL does not require this. This is a side effect of the tools.

EDIT: Also, in the general case, XSD does not define data aspects of a web service. XSD defines the elements that may be present in a compliant XML document. Such a document may be exchanged as a message over a web service endpoint, but it need not be.


Getting back to the question I would answer the original question a little differently. I woudl say YES, it is possible to generate a WSDL file given a xsd file, in the same way it is possible to generate an omelette using eggs.

EDIT: My original response has been unclear. Let me try again. I do not suggest that XSD is equivalent to WSDL, nor that an XSD is sufficient to produce a WSDL. I do say that it is possible to generate a WSDL, given an XSD file, if by that phrase you mean "to generate a WSDL using an XSD file". Doing so, you will augment the information in the XSD file to generate the WSDL. You will need to define additional things - message parts, operations, port types - none of these are present in the XSD. But it is possible to "generate a WSDL, given an XSD", with some creative effort.

If the phrase "generate a WSDL given an XSD" is taken to imply "mechanically transform an XSD into a WSDL", then the answer is NO, you cannot do that. This much should be clear given my description of the WSDL above.

When generating a WSDL using an XSD file, you will typically do something like this (note the creative steps in this procedure):

  1. import the XML schema into the WSDL (wsdl:types element)
  2. add to the set of types or elements with additional ones, or wrappers (let's say arrays, or structures containing the basic types) as desired. The result of #1 and #2 comprise all the types the WSDL will use.
  3. define a set of in and out messages (and maybe faults) in terms of those previously defined types.
  4. Define a port-type, which is the collection of pairings of in.out messages. You might think of port-type as a WSDL analog to a Java interface.
  5. Specify a binding, which implements the port-type and defines how messages will be serialized.
  6. Specify a service, which implements the binding.

Most of the WSDL is more or less boilerplate. It can look daunting, but that is mostly because of those scary and plentiful angle brackets, I've found.

Some have suggested that this is a long-winded manual process. Maybe. But this is how you can build interoperable services. You can also use tools for defining WSDL. Dynamically generating WSDL from code will lead to interop pitfalls.

How to avoid the "Circular view path" exception with Spring MVC test

if you have not used a @RequestBody and are using only @Controller, simplest way to fix this is using @RestController instead of @Controller

FloatingActionButton example with Support Library

So in your build.gradle file, add this:

compile 'com.android.support:design:27.1.1'

AndroidX Note: Google is introducing new AndroidX extension libraries to replace the older Support Libraries. To use AndroidX, first make sure you've updated your gradle.properties file, edited build.gradle to set compileSdkVersion to 28 (or higher), and use the following line instead of the previous compile one.

implementation 'com.google.android.material:material:1.0.0'

Next, in your themes.xml or styles.xml or whatever, make sure you set this- it's your app's accent color-- and the color of your FAB unless you override it (see below):

        <item name="colorAccent">@color/floating_action_button_color</item>

In the layout's XML:

<RelativeLayout
 ...
 xmlns:app="http://schemas.android.com/apk/res-auto">

       <android.support.design.widget.FloatingActionButton
            android:id="@+id/myFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_plus_sign"
            app:elevation="4dp"
            ... />

</RelativeLayout>

Or if you are using the AndroidX material library above, you'd instead use this:

<RelativeLayout
 ...
 xmlns:app="http://schemas.android.com/apk/res-auto">

       <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/myFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:srcCompat="@drawable/ic_plus_sign"
            app:elevation="4dp"
            ... />

</RelativeLayout>

You can see more options in the docs (material docs here) (setRippleColor, etc.), but one of note is:

    app:fabSize="mini"

Another interesting one-- to change the background color of just one FAB, add:

    app:backgroundTint="#FF0000"

(for example to change it to red) to the XML above.

Anyway, in code, after the Activity/Fragment's view is inflated....

    FloatingActionButton myFab = (FloatingActionButton)  myView.findViewById(R.id.myFAB);
    myFab.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            doMyThing();
        }
    });

Observations:

  • If you have one of those buttons that's on a "seam" splitting two views (using a RelativeLayout, for example) with, say, a negative bottom layout margin to overlap the border, you'll notice an issue: the FAB's size is actually very different on lollipop vs. pre-lollipop. You can actually see this in AS's visual layout editor when you flip between APIs-- it suddenly "puffs out" when you switch to pre-lollipop. The reason for the extra size seems to be that the shadow expands the size of the view in every direction. So you have to account for this when you're adjusting the FAB's margins if it's close to other stuff.
  • Here's a way to remove or change the padding if there's too much:

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) myFab.getLayoutParams();
        p.setMargins(0, 0, 0, 0); // get rid of margins since shadow area is now the margin
        myFab.setLayoutParams(p);
    }
    
  • Also, I was going to programmatically place the FAB on the "seam" between two areas in a RelativeLayout by grabbing the FAB's height, dividing by two, and using that as the margin offset. But myFab.getHeight() returned zero, even after the view was inflated, it seemed. Instead I used a ViewTreeObserver to get the height only after it's laid out and then set the position. See this tip here. It looked like this:

        ViewTreeObserver viewTreeObserver = closeButton.getViewTreeObserver();
        if (viewTreeObserver.isAlive()) {
            viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                        closeButton.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    } else {
                        closeButton.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                    // not sure the above is equivalent, but that's beside the point for this example...
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) closeButton.getLayoutParams();
                    params.setMargins(0, 0, 16, -closeButton.getHeight() / 2); // (int left, int top, int right, int bottom)
                    closeButton.setLayoutParams(params);
                }
            });
        }
    

    Not sure if this is the right way to do it, but it seems to work.

  • It seems you can make the shadow-space of the button smaller by decreasing the elevation.
  • If you want the FAB on a "seam" you can use layout_anchor and layout_anchorGravity here is an example:

    <android.support.design.widget.FloatingActionButton
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|right|end"
        android:src="@drawable/ic_discuss"
        android:layout_margin="@dimen/fab_margin"
        android:clickable="true"/>
    

Remember that you can automatically have the button jump out of the way when a Snackbar comes up by wrapping it in a CoordinatorLayout.

More:

Download data url file

Here is a pure JavaScript solution I tested working in Firefox and Chrome but not in Internet Explorer:

function downloadDataUrlFromJavascript(filename, dataUrl) {

    // Construct the 'a' element
    var link = document.createElement("a");
    link.download = filename;
    link.target = "_blank";

    // Construct the URI
    link.href = dataUrl;
    document.body.appendChild(link);
    link.click();

    // Cleanup the DOM
    document.body.removeChild(link);
    delete link;
}

Cross-browser solutions found up until now:

downloadify -> Requires Flash

databounce -> Tested in IE 10 and 11, and doesn't work for me. Requires a servlet and some customization. (Incorrectly detects navigator. I had to set IE in compatibility mode to test, default charset in servlet, JavaScript options object with correct servlet path for absolute paths...) For non-IE browsers, it opens the file in the same window.

download.js -> http://danml.com/download.html Another library similar but not tested. Claims to be pure JavaScript, not requiring servlet nor Flash, but doesn't work on IE <= 9.

How can I catch an error caused by mail()?

According to http://php.net/manual/en/function.error-get-last.php, use:

print_r(error_get_last());

Which will return an array of the last error generated. You can access the [message] element to display the error.

Importing .py files in Google Colab

You can upload those .py files to Google drive and allow Colab to use to them:

!mkdir -p drive
!google-drive-ocamlfuse drive

All your files and folders in root folder will be in drive.

Add CSS class to a div in code behind

For a non ASP.NET control, i.e. HTML controls like div, table, td, tr, etc. you need to first make them a server control, assign an ID, and then assign a property from server code:

ASPX page

<head>
    <style type="text/css">
        .top_rounded
        {
            height: 75px;
            width: 75px;
            border: 2px solid;
            border-radius: 5px;
            -moz-border-radius: 5px; /* Firefox 3.6 and earlier */
            border-color: #9c1c1f;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div runat="server" id="myDiv">This is my div</div>
    </form>
</body>

CS page

myDiv.Attributes.Add("class", "top_rounded");

Circle drawing with SVG's arc path

Written as a function, it looks like this:

function getPath(cx,cy,r){
  return "M" + cx + "," + cy + "m" + (-r) + ",0a" + r + "," + r + " 0 1,0 " + (r * 2) + ",0a" + r + "," + r + " 0 1,0 " + (-r * 2) + ",0";
}

C# Pass Lambda Expression as Method Parameter

If I understand you need following code. (passing expression lambda by parameter) The Method

public static void Method(Expression<Func<int, bool>> predicate) { 
    int[] number={1,2,3,4,5,6,7,8,9,10};
    var newList = from x in number
                  .Where(predicate.Compile()) //here compile your clausuly
                  select x;
                newList.ToList();//return a new list
    }

Calling method

Method(v => v.Equals(1));

You can do the same in their class, see this is example.

public string Name {get;set;}

public static List<Class> GetList(Expression<Func<Class, bool>> predicate)
    {
        List<Class> c = new List<Class>();
        c.Add(new Class("name1"));
        c.Add(new Class("name2"));

        var f = from g in c.
                Where (predicate.Compile())
                select g;
        f.ToList();

       return f;
    }

Calling method

Class.GetList(c=>c.Name=="yourname");

I hope this is useful

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

You can use this with replacement of CGRectZero

CGRect.zero

Extract column values of Dataframe as List in Apache Spark

List<String> whatever_list = df.toJavaRDD().map(new Function<Row, String>() {
    public String call(Row row) {
        return row.getAs("column_name").toString();
    }
}).collect();

logger.info(String.format("list is %s",whatever_list)); //verification

Since no one has given any solution in java(Real Programming Language) Can thank me later

How to Query an NTP Server using C#?

http://www.codeproject.com/Articles/237501/Windows-Phone-NTP-Client is going to work well for Windows Phone .

Adding the relevant code

/// <summary>
/// Class for acquiring time via Ntp. Useful for applications in which correct world time must be used and the 
/// clock on the device isn't "trusted."
/// </summary>
public class NtpClient
{
    /// <summary>
    /// Contains the time returned from the Ntp request
    /// </summary>
    public class TimeReceivedEventArgs : EventArgs
    {
        public DateTime CurrentTime { get; internal set; }
    }

    /// <summary>
    /// Subscribe to this event to receive the time acquired by the NTP requests
    /// </summary>
    public event EventHandler<TimeReceivedEventArgs> TimeReceived;

    protected void OnTimeReceived(DateTime time)
    {
        if (TimeReceived != null)
        {
            TimeReceived(this, new TimeReceivedEventArgs() { CurrentTime = time });
        }
    }


    /// <summary>
    /// Not reallu used. I put this here so that I had a list of other NTP servers that could be used. I'll integrate this
    /// information later and will provide method to allow some one to choose an NTP server.
    /// </summary>
    public string[] NtpServerList = new string[]
    {
        "pool.ntp.org ",
        "asia.pool.ntp.org",
        "europe.pool.ntp.org",
        "north-america.pool.ntp.org",
        "oceania.pool.ntp.org",
        "south-america.pool.ntp.org",
        "time-a.nist.gov"
    };

    string _serverName;
    private Socket _socket;

    /// <summary>
    /// Constructor allowing an NTP server to be specified
    /// </summary>
    /// <param name="serverName">the name of the NTP server to be used</param>
    public NtpClient(string serverName)
    {
        _serverName = serverName;
    }


    /// <summary>
    /// 
    /// </summary>
    public NtpClient()
        : this("time-a.nist.gov")
    { }

    /// <summary>
    /// Begins the network communication required to retrieve the time from the NTP server
    /// </summary>
    public void RequestTime()
    {
        byte[] buffer = new byte[48];
        buffer[0] = 0x1B;
        for (var i = 1; i < buffer.Length; ++i)
            buffer[i] = 0;
        DnsEndPoint _endPoint = new DnsEndPoint(_serverName, 123);

        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        SocketAsyncEventArgs sArgsConnect = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
        sArgsConnect.Completed += (o, e) =>
        {
            if (e.SocketError == SocketError.Success)
            {
                SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
                sArgs.Completed +=
                    new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
                sArgs.SetBuffer(buffer, 0, buffer.Length);
                sArgs.UserToken = buffer;
                _socket.SendAsync(sArgs);
            }
        };
        _socket.ConnectAsync(sArgsConnect);

    }

    void sArgs_Completed(object sender, SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            byte[] buffer = (byte[])e.Buffer;
            SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs();
            sArgs.RemoteEndPoint = e.RemoteEndPoint;

            sArgs.SetBuffer(buffer, 0, buffer.Length);
            sArgs.Completed += (o, a) =>
            {
                if (a.SocketError == SocketError.Success)
                {
                    byte[] timeData = a.Buffer;

                    ulong hTime = 0;
                    ulong lTime = 0;

                    for (var i = 40; i <= 43; ++i)
                        hTime = hTime << 8 | buffer[i];
                    for (var i = 44; i <= 47; ++i)
                        lTime = lTime << 8 | buffer[i];
                    ulong milliseconds = (hTime * 1000 + (lTime * 1000) / 0x100000000L);

                    TimeSpan timeSpan =
                        TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
                    var currentTime = new DateTime(1900, 1, 1) + timeSpan;
                    OnTimeReceived(currentTime);

                }
            };
            _socket.ReceiveAsync(sArgs);
        }
    }
}

Usage :

public partial class MainPage : PhoneApplicationPage
{
    private NtpClient _ntpClient;
    public MainPage()
    {
        InitializeComponent();
        _ntpClient = new NtpClient();
        _ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>(_ntpClient_TimeReceived);
    }

    void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
    {
        this.Dispatcher.BeginInvoke(() =>
                                        {
                                            txtCurrentTime.Text = e.CurrentTime.ToLongTimeString();
                                            txtSystemTime.Text = DateTime.Now.ToUniversalTime().ToLongTimeString();
                                        });
    }

    private void UpdateTimeButton_Click(object sender, RoutedEventArgs e)
    {
        _ntpClient.RequestTime();
    }
}

Does C# have a String Tokenizer like Java's?

You could use String.Split method.

class ExampleClass
{
    public ExampleClass()
    {
        string exampleString = "there is a cat";
        // Split string on spaces. This will separate all the words in a string
        string[] words = exampleString.Split(' ');
        foreach (string word in words)
        {
            Console.WriteLine(word);
            // there
            // is
            // a
            // cat
        }
    }
}

For more information see Sam Allen's article about splitting strings in c# (Performance, Regex)

GIT commit as different user without email / or only email

Format

A U Thor <[email protected]>

simply mean that you should specify

FirstName MiddleName LastName <[email protected]>

Looks like middle and last names are optional (maybe the part before email doesn't have a strict format at all). Try, for example, this:

git commit --author="John <[email protected]>" -m "some fix"

As the docs say:

  --author=<author>
       Override the commit author. Specify an explicit author using the standard 
       A U Thor <[email protected]> format. Otherwise <author> is assumed to 
       be a pattern and is used to search for an existing commit by that author 
       (i.e. rev-list --all -i --author=<author>); the commit author is then copied 
       from the first such commit found.

if you don't use this format, git treats provided string as a pattern and tries to find matching name among the authors of other commits.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Another case that could cause this error is

>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.

>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

How to check if pytorch is using the GPU?

Simply from command prompt or Linux environment run the following command.

python -c 'import torch; print(torch.cuda.is_available())'

The above should print True

python -c 'import torch; print(torch.rand(2,3).cuda())'

This one should print the following:

tensor([[0.7997, 0.6170, 0.7042], [0.4174, 0.1494, 0.0516]], device='cuda:0')

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

The get method of the HashMap is returning an Object, but the variable current is expected to take a ArrayList:

ArrayList current = new ArrayList();
// ...
current = dictMap.get(dictCode);

For the above code to work, the Object must be cast to an ArrayList:

ArrayList current = new ArrayList();
// ...
current = (ArrayList)dictMap.get(dictCode);

However, probably the better way would be to use generic collection objects in the first place:

HashMap<String, ArrayList<Object>> dictMap =
    new HashMap<String, ArrayList<Object>>();

// Populate the HashMap.

ArrayList<Object> current = new ArrayList<Object>();      
if(dictMap.containsKey(dictCode)) {
    current = dictMap.get(dictCode);   
}

The above code is assuming that the ArrayList has a list of Objects, and that should be changed as necessary.

For more information on generics, The Java Tutorials has a lesson on generics.

Duplicate keys in .NET dictionaries?

Duplicate keys break the entire contract of the Dictionary. In a dictionary each key is unique and mapped to a single value. If you want to link an object to an arbitrary number of additional objects, the best bet might be something akin to a DataSet (in common parlance a table). Put your keys in one column and your values in the other. This is significantly slower than a dictionary, but that's your tradeoff for losing the ability to hash the key objects.

WCF timeout exception detailed investigation

I'm not a WCF expert but I'm wondering if you aren't running into a DDOS protection on IIS. I know from experience that if you run a bunch of simultaneous connections from a single client to a server at some point the server stops responding to the calls as it suspects a DDOS attack. It will also hold the connections open until they time-out in order to slow the client down in his attacks.

Multiple connection coming from different machines/IP's should not be a problem however.

There's more info in this MSDN post:

http://msdn.microsoft.com/en-us/library/bb463275.aspx

Check out the MaxConcurrentSession sproperty.

how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);

problem with php mail 'From' header

Edit: I just noted that you are trying to use a gmail address as the from value. This is not going to work, and the ISP is right in overwriting it. If you want to redirect the replies to your outgoing messages, use reply-to.

A workaround for valid addresses that works with many ISPs:

try adding a fifth parameter to your mail() command:

mail($to,$subject,$message,$headers,"-f [email protected]");

How to add new line into txt file

var Line = textBox1.Text + "," + textBox2.Text;

File.AppendAllText(@"C:\Documents\m2.txt", Line + Environment.NewLine);

Determine the path of the executing BASH script

Assuming you type in the full path to the bash script, use $0 and dirname, e.g.:

#!/bin/bash
echo "$0"
dirname "$0"

Example output:

$ /a/b/c/myScript.bash
/a/b/c/myScript.bash
/a/b/c

If necessary, append the results of the $PWD variable to a relative path.

EDIT: Added quotation marks to handle space characters.

Clearing NSUserDefaults

Note: This answer has been updated for Swift too.

What about to have it on one line?

Extending @Christopher Rogers answer – the accepted one.

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];

and yes, sometime you may need to synchronize it,

[[NSUserDefaults standardUserDefaults] synchronize];

I've created a method to do this,

- (void) clearDefaults {
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

Swift?

With swift its even more easy.

extension UserDefaults {
    class func clean() {
        guard let aValidIdentifier = Bundle.main.bundleIdentifier else { return }
        standard.removePersistentDomain(forName: aValidIdentifier)
        standard.synchronize()
    }
}

And usage:

UserDefaults.clean()

Merge two dataframes by index

A silly bug that got me: the joins failed because index dtypes differed. This was not obvious as both tables were pivot tables of the same original table. After reset_index, the indices looked identical in Jupyter. It only came to light when saving to Excel...

Fixed with: df1[['key']] = df1[['key']].apply(pd.to_numeric)

Hopefully this saves somebody an hour!

How do I get the path of the assembly the code is in?

Same as John's answer, but a slightly less verbose extension method.

public static string GetDirectoryPath(this Assembly assembly)
{
    string filePath = new Uri(assembly.CodeBase).LocalPath;
    return Path.GetDirectoryName(filePath);            
}

Now you can do:

var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();

or if you prefer:

var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();

Moving Panel in Visual Studio Code to right side

VSCode 1.42 (January 2020) introduces:

Panel on the left/right

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

"workbench.panel.defaultLocation": "left"

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

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

Adding background image to div using CSS

Use:

.content {
    background: url('http://www.gransebryan.com/wp-content/uploads/2016/03/bryan-ganzon-granse-who.png') center no-repeat;
 }

.displaybg {
   text-align: center;
   color: #FFF;
}

What is "X-Content-Type-Options=nosniff"?

Just to elaborate a bit on the meta-tag thing. I've heard a talk, where a statement was made, one should always insert the "no-sniff" meta tag in the html to prevent browser sniffing (just like OP did):

<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />

However, this is not a valid method for w3c compliant websites, the validator will raise an error:

Bad value text/html; charset=UTF-8; X-Content-Type-Options=nosniff for attribute content on element meta: The legacy encoding contained ;, which is not a valid character in an encoding name.

And there is no fixing this. To rightly turn off no-sniff, one has to go to the server settings and turn it off there. Because the "no-sniff" option is something from the HTTP header, not from the HTML file which is attached at the HTTP response.

To check if the no-sniff option is disabled, one can enable the developer console, networks tab and then inspect the HTTP response header:

Visualization of enabled no-sniff option

How do I create a pause/wait function using Qt?

We've been using the below class -

class SleepSimulator{
     QMutex localMutex;
     QWaitCondition sleepSimulator;
public:
    SleepSimulator::SleepSimulator()
    {
        localMutex.lock();
    }
    void sleep(unsigned long sleepMS)
    {
        sleepSimulator.wait(&localMutex, sleepMS);
    }
    void CancelSleep()
    {
        sleepSimulator.wakeAll();
    }
};

QWaitCondition is designed to coordinate mutex waiting between different threads. But what makes this work is the wait method has a timeout on it. When called this way, it functions exactly like a sleep function, but it uses Qt's event loop for the timing. So, no other events or the UI are blocked like normal windows sleep function does.

As a bonus, we added the CancelSleep function to allows another part of the program to cancel the "sleep" function.

What we liked about this is that it lightweight, reusable and is completely self contained.

QMutex: http://doc.qt.io/archives/4.6/qmutex.html

QWaitCondition: http://doc.qt.io/archives/4.6/qwaitcondition.html

Deserialize JSON string to c# object

I think the JavaScriptSerializer does not create a dynamic object.

So you should define the class first:

class MyObj {
    public int arg1 {get;set;}
    public int arg2 {get;set;}
}

And deserialize that instead of object:

serializer.Deserialize<MyObj>(str);

Not testet, please try.

Copy table from one database to another

Assuming that you want different names for the tables.

If you are using PHPmyadmin you can use their SQL option in the menu. Then you simply copy the SQL-code from the first table and paste it into the new table.

That worked out for me when I was moving from localhost to a webhost. Hope it works for you!

difference between variables inside and outside of __init__()

class foo(object):
    mStatic = 12

    def __init__(self):
        self.x = "OBj"

Considering that foo has no access to x at all (FACT)

the conflict now is in accessing mStatic by an instance or directly by the class .

think of it in the terms of Python's memory management :

12 value is on the memory and the name mStatic (which accessible from the class)

points to it .

c1, c2 = foo(), foo() 

this line makes two instances , which includes the name mStatic that points to the value 12 (till now) .

foo.mStatic = 99 

this makes mStatic name pointing to a new place in the memory which has the value 99 inside it .

and because the (babies) c1 , c2 are still following (daddy) foo , they has the same name (c1.mStatic & c2.mStatic ) pointing to the same new value .

but once each baby decides to walk alone , things differs :

c1.mStatic ="c1 Control"
c2.mStatic ="c2 Control"

from now and later , each one in that family (c1,c2,foo) has its mStatica pointing to different value .

[Please, try use id() function for all of(c1,c2,foo) in different sates that we talked about , i think it will make things better ]

and this is how our real life goes . sons inherit some beliefs from their father and these beliefs still identical to father's ones until sons decide to change it .

HOPE IT WILL HELP

How to delete selected text in the vi editor

Do it the vi way.

To delete 5 lines press: 5dd ( 5 delete )

To select ( actually copy them to the clipboard ) you type: 10yy

It is a bit hard to grasp, but very handy to learn when using those remote terminals

Be aware of the learning curves for some editors:


(source: calver at unix.rulez.org)

Django: List field in model?

It's quite an old topic, but since it is returned when searching for "django list field" I'll share the custom django list field code I modified to work with Python 3 and Django 2. It supports the admin interface now and not uses eval (which is a huge security breach in Prashant Gaur's code).

from django.db import models
from typing import Iterable

class ListField(models.TextField):
    """
    A custom Django field to represent lists as comma separated strings
    """

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop('token', ',')
        super().__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        kwargs['token'] = self.token
        return name, path, args, kwargs

    def to_python(self, value):

        class SubList(list):
            def __init__(self, token, *args):
                self.token = token
                super().__init__(*args)

            def __str__(self):
                return self.token.join(self)

        if isinstance(value, list):
            return value
        if value is None:
            return SubList(self.token)
        return SubList(self.token, value.split(self.token))

    def from_db_value(self, value, expression, connection):
        return self.to_python(value)

    def get_prep_value(self, value):
        if not value:
            return
        assert(isinstance(value, Iterable))
        return self.token.join(value)

    def value_to_string(self, obj):
        value = self.value_from_object(obj)
        return self.get_prep_value(value)

How to check if anonymous object has a method?

One way to do it must be if (typeof myObj.prop1 != "undefined") {...}

Cannot find Dumpbin.exe

Instead of using the dumpin.exe it is possible to call the link.exe with several options:

Example: link /dump /all myfile.lib

For detailed options see output of link /dump

In case of Visual Studio C++ Express installation, the link.exe is located here:

{root}\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\

The best way is to open the "Visual Studio Command Prompt" and then enter the lines above.

How can I remove jenkins completely from linux

First - stop Jenkins service:

sudo service jenkins stop

Next - delete:

sudo apt-get remove --purge jenkins

If you used separate server for Jenkins, some GCP or AWS - just delete this server. Here is a video how to uninstall Jenkins from GCP Compute Engine https://youtu.be/D2HUFAc_Trw

Writing data into CSV file in C#

This is a simple tutorial on creating csv files using C# that you will be able to edit and expand on to fit your own needs.

First you’ll need to create a new Visual Studio C# console application, there are steps to follow to do this.

The example code will create a csv file called MyTest.csv in the location you specify. The contents of the file should be 3 named columns with text in the first 3 rows.

https://tidbytez.com/2018/02/06/how-to-create-a-csv-file-with-c/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace CreateCsv
{
    class Program
    {
        static void Main()
        {
            // Set the path and filename variable "path", filename being MyTest.csv in this example.
            // Change SomeGuy for your username.
            string path = @"C:\Users\SomeGuy\Desktop\MyTest.csv";

            // Set the variable "delimiter" to ", ".
            string delimiter = ", ";

            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string createText = "Column 1 Name" + delimiter + "Column 2 Name" + delimiter + "Column 3 Name" + delimiter + Environment.NewLine;
                File.WriteAllText(path, createText);
            }

            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is text for Column 1" + delimiter + "This is text for Column 2" + delimiter + "This is text for Column 3" + delimiter + Environment.NewLine;
            File.AppendAllText(path, appendText);

            // Open the file to read from.
            string readText = File.ReadAllText(path);
            Console.WriteLine(readText);
        }
    }
}

Is it ok to run docker from inside docker?

Running Docker inside Docker (a.k.a. dind), while possible, should be avoided, if at all possible. (Source provided below.) Instead, you want to set up a way for your main container to produce and communicate with sibling containers.

Jérôme Petazzoni — the author of the feature that made it possible for Docker to run inside a Docker container — actually wrote a blog post saying not to do it. The use case he describes matches the OP's exact use case of a CI Docker container that needs to run jobs inside other Docker containers.

Petazzoni lists two reasons why dind is troublesome:

  1. It does not cooperate well with Linux Security Modules (LSM).
  2. It creates a mismatch in file systems that creates problems for the containers created inside parent containers.

From that blog post, he describes the following alternative,

[The] simplest way is to just expose the Docker socket to your CI container, by bind-mounting it with the -v flag.

Simply put, when you start your CI container (Jenkins or other), instead of hacking something together with Docker-in-Docker, start it with:

docker run -v /var/run/docker.sock:/var/run/docker.sock ...

Now this container will have access to the Docker socket, and will therefore be able to start containers. Except that instead of starting "child" containers, it will start "sibling" containers.

How to save final model using keras?

you can save the model in json and weights in a hdf5 file format.

# keras library import  for Saving and loading model and weights

from keras.models import model_from_json
from keras.models import load_model

# serialize model to JSON
#  the keras model which is trained is defined as 'model' in this example
model_json = model.to_json()


with open("model_num.json", "w") as json_file:
    json_file.write(model_json)

# serialize weights to HDF5
model.save_weights("model_num.h5")

files "model_num.h5" and "model_num.json" are created which contain our model and weights

To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.

# load json and create model
json_file = open('model_num.json', 'r')

loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("model_num.h5")
print("Loaded model from disk")

loaded_model.save('model_num.hdf5')
loaded_model=load_model('model_num.hdf5')

To predict for different data you can use this

loaded_model.predict_classes("your_test_data here")

How to extract text from a string using sed?

The pattern \d might not be supported by your sed. Try [0-9] or [[:digit:]] instead.

To only print the actual match (not the entire matching line), use a substitution.

sed -n 's/.*\([0-9][0-9]*G[0-9][0-9]*\).*/\1/p'

Insert picture/table in R Markdown

Several sites provide reasonable cheat sheets or HOWTOs for tables and images. Top on my list are:

Pictures are very simple to use but do not offer the ability to adjust the image to fit the page (see Update, below). To adjust the image properties (size, resolution, colors, border, etc), you'll need some form of image editor. I find I can do everything I need with one of ImageMagick, GIMP, or InkScape, all free and open source.

To add a picture, use:

![Caption for the picture.](/path/to/image.png)

I know pandoc supports PNG and JPG, which should meet most of your needs.

You do have control over image size if you are creating it in R (e.g., a plot). This can be done either directly in the command to create the image or, even better, via options if you are using knitr (highly recommended ... check out chunk options, specifically under Plots).

I strongly recommend perusing these tutorials; markdown is very handy and has many features most people don't use on a regular basis but really like once they learn it. (SO is not necessarily the best place to ask questions that are answered very directly in these tutorials.)


Update, 2019-Aug-31

Some time ago, pandoc incorporated "link_attributes" for images (apparently in 2015, with commit jgm/pandoc#244cd56). "Resizing images" can be done directly. For example:

![unchanged image](foo.jpg)
![much-smaller image](foo.jpg){#id .class width=30 height=20px}
![half-size image](foo.jpg){#id .class width=50% height=50%}

The dimensions can be provided with no units (pixels assumed), or with "px, cm, mm, in, inch and %" (ref: https://pandoc.org/MANUAL.html, search for link_attributes).

(I'm not certain that CommonMark has implemented this, though there was a lengthy discussion.)

Local dependency in package.json

If you want to further automate this, because you are checking your module into version control, and don't want to rely upon devs remembering to npm link, you can add this to your package.json "scripts" section:

"scripts": {
    "postinstall": "npm link ../somelocallib",
    "postupdate": "npm link ../somelocallib"
  }

This feels beyond hacky, but it seems to "work". Got the tip from this npm issue: https://github.com/npm/npm/issues/1558#issuecomment-12444454

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

sql select with column name like

Here is a nice way to display the information that you want:

SELECT B.table_catalog as 'Database_Name',
         B.table_name as 'Table_Name',
        stuff((select ', ' + A.column_name
              from INFORMATION_SCHEMA.COLUMNS A
              where A.Table_name = B.Table_Name
              FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)')
              , 1, 2, '') as 'Columns'
  FROM INFORMATION_SCHEMA.COLUMNS B
  WHERE B.TABLE_NAME like '%%'
        AND B.COLUMN_NAME like '%%'
  GROUP BY B.Table_Catalog, B.Table_Name
  Order by 1 asc

Add anything between either '%%' in the main select to narrow down what tables and/or column names you want.

using facebook sdk in Android studio

I have used facebook sdk 4.10.0 to integrate login in my android app. Tutorial I followed is :

facebook login android studio

You will be able to get first name, last name, email, gender , facebook id and birth date from facebbok.

Above tutorial also explains how to create app in facebook developer console through video.

add below in build.gradle(Module:app) file:

repositories {
        mavenCentral()
    }

and

 compile 'com.facebook.android:facebook-android-sdk:4.10.0'

now add below in AndroidManifest.xml file :

 <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="your app id from facebook developer console"/>

     <activity android:name="com.facebook.FacebookActivity"
               android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
               android:theme="@android:style/Theme.Translucent.NoTitleBar"
               android:label="@string/app_name" />

add following in activity_main.xml file :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.demonuts.fblogin.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:layout_marginLeft="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/text"/>

    <com.facebook.login.widget.LoginButton
        android:id="@+id/btnfb"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

And in last add below in MainActivity.java file :

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;


public class MainActivity extends AppCompatActivity {

    private TextView tvdetails;
    private CallbackManager callbackManager;
    private AccessTokenTracker accessTokenTracker;
    private ProfileTracker profileTracker;
    private LoginButton loginButton;
    private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v("LoginActivity", response.toString());

                            // Application code
                            try {
                                Log.d("tttttt",object.getString("id"));
                                String birthday="";
                                if(object.has("birthday")){
                                    birthday = object.getString("birthday"); // 01/31/1980 format
                                }

                                String fnm = object.getString("first_name");
                                String lnm = object.getString("last_name");
                                String mail = object.getString("email");
                                String gender = object.getString("gender");
                                String fid = object.getString("id");
                                tvdetails.setText(fnm+" "+lnm+" \n"+mail+" \n"+gender+" \n"+fid+" \n"+birthday);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id, first_name, last_name, email, gender, birthday, location");
            request.setParameters(parameters);
            request.executeAsync();

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
    };


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

        FacebookSdk.sdkInitialize(this);
        setContentView(R.layout.activity_main);

        tvdetails = (TextView) findViewById(R.id.text);

        loginButton = (LoginButton) findViewById(R.id.btnfb);

        callbackManager = CallbackManager.Factory.create();

        accessTokenTracker= new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {

            }
        };

        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {

            }
        };

        accessTokenTracker.startTracking();
        profileTracker.startTracking();
        loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
        loginButton.registerCallback(callbackManager, callback);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onStop() {
        super.onStop();
        accessTokenTracker.stopTracking();
        profileTracker.stopTracking();
    }

    @Override
    public void onResume() {
        super.onResume();
        Profile profile = Profile.getCurrentProfile();

    }

}

Flask Python Buttons

I handle it in the following way:

<html>
    <body>

        <form method="post" action="/">

                <input type="submit" value="Encrypt" name="Encrypt"/>
                <input type="submit" value="Decrypt" name="Decrypt" />

        </form>
    </body>
</html>
    

Python Code :

    from flask import Flask, render_template, request
    
    
    app = Flask(__name__)
    
    
    @app.route("/", methods=['GET', 'POST'])
    def index():
        print(request.method)
        if request.method == 'POST':
            if request.form.get('Encrypt') == 'Encrypt':
                # pass
                print("Encrypted")
            elif  request.form.get('Decrypt') == 'Decrypt':
                # pass # do something else
                print("Decrypted")
            else:
                # pass # unknown
                return render_template("index.html")
        elif request.method == 'GET':
            # return render_template("index.html")
            print("No Post Back Call")
        return render_template("index.html")
    
    
    if __name__ == '__main__':
        app.run()

What is the difference between MySQL, MySQLi and PDO?

Specifically, the MySQLi extension provides the following extremely useful benefits over the old MySQL extension..

OOP Interface (in addition to procedural) Prepared Statement Support Transaction + Stored Procedure Support Nicer Syntax Speed Improvements Enhanced Debugging

PDO Extension

PHP Data Objects extension is a Database Abstraction Layer. Specifically, this is not a MySQL interface, as it provides drivers for many database engines (of course including MYSQL).

PDO aims to provide a consistent API that means when a database engine is changed, the code changes to reflect this should be minimal. When using PDO, your code will normally "just work" across many database engines, simply by changing the driver you're using.

In addition to being cross-database compatible, PDO also supports prepared statements, stored procedures and more, whilst using the MySQL Driver.

Git submodule push

Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:

"git push --recurse-submodules" learned to optionally look into the histories of submodules bound to the superproject and push them out.

Probably done after this patch and the --on-demand option:

recurse-submodules=<check|on-demand>::

Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.

  • If check is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
    Otherwise the push will be aborted and exit with non-zero status.
  • If on-demand is used, all submodules that changed in the revisions to be pushed will be pushed.
    If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.

So you could push everything in one go with (from the parent repo) a:

git push --recurse-submodules=on-demand

This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.


With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.

See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe).
(Merged by Junio C Hamano -- gitster -- in commit 5d35d72, 21 Dec 2015)

push: add recurseSubmodules config option

The --recurse-submodules command line parameter has existed for some time but it has no config file equivalent.

Following the style of the corresponding parameter for git fetch, let's invent push.recurseSubmodules to provide a default for this parameter.
This also requires the addition of --recurse-submodules=no to allow the configuration to be overridden on the command line when required.

The most straightforward way to implement this appears to be to make push use code in submodule-config in a similar way to fetch.

The git config doc now include:

push.recurseSubmodules:

Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.

  • If the value is 'check', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.
  • If the value is 'on-demand' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -
  • If the value is 'no' then default behavior of ignoring submodules when pushing is retained.

You may override this configuration at time of push by specifying '--recurse-submodules=check|on-demand|no'.

So:

git config push.recurseSubmodules on-demand
git push

Git 2.12 (Q1 2017)

git push --dry-run --recurse-submodules=on-demand will actually work.

See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 12cf113, 16 Dec 2016)

push run with --dry-run doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.

Teach push to respect the --dry-run option when configured to recursively push submodules 'on-demand'.
This is done by passing the --dry-run flag to the child process which performs a push for a submodules when performing a dry-run.


And still in Git 2.12, you now havea "--recurse-submodules=only" option to push submodules out without pushing the top-level superproject.

See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 792e22e, 31 Jan 2017)

What Does This Mean in PHP -> or =>

=> is used in associative array key value assignment. Take a look at:

http://php.net/manual/en/language.types.array.php.

-> is used to access an object method or property. Example: $obj->method().

Using find to locate files that match one of multiple patterns

This works on AIX korn shell.

find *.cbl *.dms -prune -type f -mtime -1

This is looking for *.cbl or *.dms which are 1 day old, in current directory only, skipping the sub-directories.

Error: Cannot find module 'ejs'

i had the same problem. So i did the following and it worked for me.

solution:

  1. run " npm init " in the project directory if not already done.
  2. install ejs and express as follows:

npm install ejs --save
npm install express --save

by doing so it creates the required dependencies in the package.json file

How do I add all new files to SVN

I like these commands as they use svn status to find the new or missing files, which respects files that are ignored.

svn add $( svn status | sed -e '/^?/!d' -e 's/^?//' )

svn rm $( svn status | sed -e '/^!/!d' -e 's/^!//' )

Way to insert text having ' (apostrophe) into a SQL table

I know the question is aimed at the direct escaping of the apostrophe character but I assume that usually this is going to be triggered by some sort of program providing the input.

What I have done universally in the scripts and programs I have worked with is to substitute it with a ` character when processing the formatting of the text being input.

Now I know that in some cases, the backtick character may in fact be part of what you might be trying to save (such as on a forum like this) but if you're simply saving text input from users it's a possible solution.

Going into the SQL database

$newval=~s/\'/`/g;

Then, when coming back out for display, filtered again like this:

$showval=~s/`/\'/g;

This example was when PERL/CGI is being used but it can apply to PHP and other bases as well. I have found it works well because I think it helps prevent possible injection attempts, because all ' are removed prior to attempting an insertion of a record.

PHP String to Float

Use this function to cast a float value from any kind of text style:

function parseFloat($value) {
    return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,3}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}

This solution is not dependant on any locale settings. Thus for user input users can type float values in any way they like. This is really helpful e.g. when you have a project wich is in english only but people all over the world are using it and might not have in mind that the project wants a dot instead of a comma for float values. You could throw javascript in the mix and fetch the browsers default settings but still many people set these values to english but still typing 1,25 instead of 1.25 (especially but not limited to the translation industry, research and IT)

map vs. hash_map in C++

hash_map was a common extension provided by many library implementations. That is exactly why it was renamed to unordered_map when it was added to the C++ standard as part of TR1. map is generally implemented with a balanced binary tree like a red-black tree (implementations vary of course). hash_map and unordered_map are generally implemented with hash tables. Thus the order is not maintained. unordered_map insert/delete/query will be O(1) (constant time) where map will be O(log n) where n is the number of items in the data structure. So unordered_map is faster, and if you don't care about the order of the items should be preferred over map. Sometimes you want to maintain order (ordered by the key) and for that map would be the choice.

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

Use underscore inside Angular controllers

you can use this module -> https://github.com/jiahut/ng.lodash

this is for lodash so does underscore

How to change a css class style through Javascript?

I'd highly recommend jQuery. It then becomes as simple as:

$('#mydiv').addClass('newclass');

You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();

The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.

$('div').addClass('newclass');
$('.oldclass').addClass('newclass');

The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.

AngularJS Error: $injector:unpr Unknown Provider

Since this is the first Stackoverflow question that appears on Google when searching for Error: $injector:unpr Unknown Provider I'll add this here.

Make sure that in your index.html any modules/dependencies are not being loaded after they are needed.

For example in my code customFactory.factory.js begins like this:

angular
   .module("app.module1")
   .factory("customFactory", customFactory);

However the index.html looked like this:

    <script src="/src/client/app/customFactory.factory.js"></script>
    <script src="/src/client/app/module1.module.js"></script>

Where it should've really looked like this:

    <script src="/src/client/app/module1.module.js"></script>
    <script src="/src/client/app/customFactory.factory.js"></script>

Since customFactory.factory.js is declared as part of module1, it needs to be loaded before customFactory

Exception is never thrown in body of corresponding try statement

A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}-block can throw (or a super class of that).

try {
    //do something that throws ExceptionA, e.g.
    throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
    //do something to handle the exception, e.g.
    System.out.println("Message: " + e.getMessage());
}

What you are trying to do is this:

try {
    throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
    System.out.println("Message: " + e.getMessage());
}

This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement.

Uncaught (in promise) TypeError: Failed to fetch and Cors error

you can use solutions without adding "Access-Control-Allow-Origin": "*", if your server is already using Proxy gateway this issue will not happen because the front and backend will be route in the same IP and port in client side but for development, you need one of this three solution if you don't need extra code 1- simulate the real environment by using a proxy server and configure the front and backend in the same port

2- if you using Chrome you can use the extension called Allow-Control-Allow-Origin: * it will help you to avoid this problem

3- you can use the code but some browsers versions may not support that so try to use one of the previous solutions

the best solution is using a proxy like ngnix its easy to configure and it will simulate the real situation of the production deployment

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

In Run->Run Configuration find the Name of the class you have been running, select it, click the Arguments tab then add:

-Xms512M -Xmx1524M

to the VM Arguments section

What SOAP client libraries exist for Python, and where is the documentation for them?

Just an FYI warning for people looking at SUDS, until this ticket is resolved, SUDS does not support the "choice" tag in WSDL:

https://fedorahosted.org/suds/ticket/342

see: suds and choice tag

This declaration has no storage class or type specifier in C++

Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.

How to generate a random alpha-numeric string

Also, you can generate any lowercase or uppercase letters or even special characters through data from the ASCII table. For example, generate upper case letters from A (DEC 65) to Z (DEC 90):

String generateRandomStr(int min, int max, int size) {
    String result = "";
    for (int i = 0; i < size; i++) {
        result += String.valueOf((char)(new Random().nextInt((max - min) + 1) + min));
    }
    return result;
}

Generated output for generateRandomStr(65, 90, 100));:

TVLPFQJCYFXQDCQSLKUKKILKKHAUFYEXLUQFHDWNMRBIRRRWNXNNZQTINZPCTKLHGHVYWRKEOYNSOFPZBGEECFMCOKWHLHCEWLDZ

Android Studio 3.0 Flavor Dimension Issue

If you want not to use dimensions you should use this line

android { 
compileSdkVersion 24

...
flavorDimensions "default"
...
}

but if you want ti use dimensions you should declare your dimension name first and then use this name after THIS example is from the documentations:

android {
...
buildTypes {
debug {...}
release {...}
}

  // Specifies the flavor dimensions you want to use. The order in which you
  // list each dimension determines its priority, from highest to lowest,
  // when Gradle merges variant sources and configurations. You must assign
  // each product flavor you configure to one of the flavor dimensions.
  flavorDimensions "api", "mode"

  productFlavors {
    demo {
  // Assigns this product flavor to the "mode" flavor dimension.
  dimension "mode"
  ...
}

full {
  dimension "mode"
  ...
}

// Configurations in the "api" product flavors override those in "mode"
// flavors and the defaultConfig block. Gradle determines the priority
// between flavor dimensions based on the order in which they appear next
// to the flavorDimensions property above--the first dimension has a higher
// priority than the second, and so on.
minApi24 {
  dimension "api"
  minSdkVersion 24
  // To ensure the target device receives the version of the app with
  // the highest compatible API level, assign version codes in increasing
  // value with API level. To learn more about assigning version codes to
  // support app updates and uploading to Google Play, read Multiple APK Support
  versionCode 30000 + android.defaultConfig.versionCode
  versionNameSuffix "-minApi24"
  ...
}

minApi23 {
  dimension "api"
  minSdkVersion 23
  versionCode 20000  + android.defaultConfig.versionCode
  versionNameSuffix "-minApi23"
  ...
}

minApi21 {
  dimension "api"
  minSdkVersion 21
  versionCode 10000  + android.defaultConfig.versionCode
  versionNameSuffix "-minApi21"
  ...
    }
  }
}
...

How to create helper file full of functions in react native?

If you want to use class, you can do this.

Helper.js

  function x(){}

  function y(){}

  export default class Helper{

    static x(){ x(); }

    static y(){ y(); }

  }

App.js

import Helper from 'helper.js';

/****/

Helper.x

Adding an item to an associative array

I know this is an old question but you can use:

array_push($data, array($category => $question));

This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:

array_push($data,$question);

Rails - controller action name to string

Rails 2.X: @controller.action_name

Rails 3.1.X: controller.action_name, action_name

Rails 4.X: action_name

Git keeps asking me for my ssh key passphrase

Once you have started the SSH agent with:

eval $(ssh-agent)

Do either:

  1. To add your private key to it:

     ssh-add
    

    This will ask you your passphrase just once, and then you should be allowed to push, provided that you uploaded the public key to Github.

  2. To add and save your key permanently on macOS:

     ssh-add -K  
    

    This will persist it after you close and re-open it by storing it in user's keychain.

  3. To add and save your key permanently on Ubuntu (or equivalent):

      ssh-add ~/.ssh/id_rsa
    

HTML Tags in Javascript Alert() method

You can use all Unicode characters and the escape characters \n and \t. An example:

_x000D_
_x000D_
document.getElementById("test").onclick = function() {_x000D_
  alert(_x000D_
    'This is an alert with basic formatting\n\n' _x000D_
    + "\t• list item 1\n" _x000D_
    + '\t• list item 2\n' _x000D_
    + '\t• list item 3\n\n' _x000D_
    + '???????????????????????\n\n' _x000D_
    + 'Simple table\n\n' _x000D_
    + 'Char\t| Result\n' _x000D_
    + '\\n\t| line break\n' _x000D_
    + '\\t\t| tab space'_x000D_
  );_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<title>Alert formatting</title>_x000D_
<meta charset=utf-8>_x000D_
<button id=test>Click</button>
_x000D_
_x000D_
_x000D_

Result in Firefox:

screenshot Firefox

You get the same look in almost all browsers.

program cant start because php5.dll is missing

I had the same problem I switched from wamp to xampp and yes PHP was working because my path was still pointing to my old installation. I had forgotten to change it to point to my new php installation which version of php didn't match the rest at all.

What is the difference between pull and clone in git?

Miss Clone: I get a fresh copy to local.

Mr Pull: I already have it locally, I just update it.


Miss Clone: I can do what you do! You are just my subset.

Mr Pull: Ditto!


Miss Clone: No, you don't create. This is what I do:

  1. Create empty bare repository in local computer.
  2. Populate remote-tracking branches (all branches in repo downloaded to local computer)
  3. Run git fetch without arguments

You only do #3, and then you merge, which I do not need to do(mine is fresh).

Mr Pull: Smarty pants, no big deal, I will do a "git init" first! Then we are the same.


Miss Clone: No dear, don't you need a 'checked-out branch'... the git checkout? Who will do it? me!

Mr Pull: Oh right, that is needed. I need a default branch to act on. But..but I have the extra 'merge' capability on existing repo! Which makes me the most used command in Git ;)


Git creators: Hold your horses Mr Pull, if --bare or --mirror is used with clone or init, your merge won't happen. It remains read-only. And for you Miss Clone, git checkout can be replaced with a git fetch <remote> <srcBranch>:<destBranch> unless you want to use a -s <strategy> with pull which is missing in fetch.


Miss Clone: Somehow I feel like a winner already but let me drop this too: my command applies to all the branches in the repository. Are you that broad minded Mr. Pull?

Mr. Pull: I am broad minded when it comes to fetching all the branch names from the repo. But the merge will happen only on the current checked out branch. Exclusivity is the name! And in your case too, you only check-out one branch.

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

Javascript : get <img> src and set as variable?

var youtubeimgsrc = document.getElementById('youtubeimg').src;
document.write(youtubeimgsrc);

Here's a fiddle for you http://jsfiddle.net/cruxst/dvrEN/

How do you get total amount of RAM the computer has?

All the answers here, including the accepted one, will give you the total amount of RAM available for use. And that may have been what OP wanted.

But if you are interested in getting the amount of installed RAM, then you'll want to make a call to the GetPhysicallyInstalledSystemMemory function.

From the link, in the Remarks section:

The GetPhysicallyInstalledSystemMemory function retrieves the amount of physically installed RAM from the computer's SMBIOS firmware tables. This can differ from the amount reported by the GlobalMemoryStatusEx function, which sets the ullTotalPhys member of the MEMORYSTATUSEX structure to the amount of physical memory that is available for the operating system to use. The amount of memory available to the operating system can be less than the amount of memory physically installed in the computer because the BIOS and some drivers may reserve memory as I/O regions for memory-mapped devices, making the memory unavailable to the operating system and applications.

Sample code:

[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);

static void Main()
{
    long memKb;
    GetPhysicallyInstalledSystemMemory(out memKb);
    Console.WriteLine((memKb / 1024 / 1024) + " GB of RAM installed.");
}

How to convert list data into json in java

i wrote my own function to return list of object for populate combo box :

public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
        try {
            Object[] args={};
            Class cl = Class.forName(kelas);
            Method getName = cl.getMethod(name, null);
            Method getLabel = cl.getMethod(label, null);
            String json="[";
            for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            if(i>0){
                json+=",";
            }
            json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
            //System.out.println("Object = " + i+" -> "+o.getNumber());
            }
            json+="]";
            return json;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            System.out.println("Error in get JSON List");
            ex.printStackTrace();
        }
        return "";
    }

and call it from anywhere like :

String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");

Angular redirect to login page

Update: I've published a full skeleton Angular 2 project with OAuth2 integration on Github that shows the directive mentioned below in action.

One way to do that would be through the use of a directive. Unlike Angular 2 components, which are basically new HTML tags (with associated code) that you insert into your page, an attributive directive is an attribute that you put in a tag that causes some behavior to occur. Docs here.

The presence of your custom attribute causes things to happen to the component (or HTML element) that you placed the directive in. Consider this directive I use for my current Angular2/OAuth2 application:

import {Directive, OnDestroy} from 'angular2/core';
import {AuthService} from '../services/auth.service';
import {ROUTER_DIRECTIVES, Router, Location} from "angular2/router";

@Directive({
    selector: '[protected]'
})
export class ProtectedDirective implements OnDestroy {
    private sub:any = null;

    constructor(private authService:AuthService, private router:Router, private location:Location) {
        if (!authService.isAuthenticated()) {
            this.location.replaceState('/'); // clears browser history so they can't navigate with back button
            this.router.navigate(['PublicPage']);
        }

        this.sub = this.authService.subscribe((val) => {
            if (!val.authenticated) {
                this.location.replaceState('/'); // clears browser history so they can't navigate with back button
                this.router.navigate(['LoggedoutPage']); // tells them they've been logged out (somehow)
            }
        });
    }

    ngOnDestroy() {
        if (this.sub != null) {
            this.sub.unsubscribe();
        }
    }
}

This makes use of an Authentication service I wrote to determine whether or not the user is already logged in and also subscribes to the authentication event so that it can kick a user out if he or she logs out or times out.

You could do the same thing. You'd create a directive like mine that checks for the presence of a necessary cookie or other state information that indicates that the user is authenticated. If they don't have those flags you are looking for, redirect the user to your main public page (like I do) or your OAuth2 server (or whatever). You would put that directive attribute on any component that needs to be protected. In this case, it might be called protected like in the directive I pasted above.

<members-only-info [protected]></members-only-info>

Then you would want to navigate/redirect the user to a login view within your app, and handle the authentication there. You'd have to change the current route to the one you wanted to do that. So in that case you'd use dependency injection to get a Router object in your directive's constructor() function and then use the navigate() method to send the user to your login page (as in my example above).

This assumes that you have a series of routes somewhere controlling a <router-outlet> tag that looks something like this, perhaps:

@RouteConfig([
    {path: '/loggedout', name: 'LoggedoutPage', component: LoggedoutPageComponent, useAsDefault: true},
    {path: '/public', name: 'PublicPage', component: PublicPageComponent},
    {path: '/protected', name: 'ProtectedPage', component: ProtectedPageComponent}
])

If, instead, you needed to redirect the user to an external URL, such as your OAuth2 server, then you would have your directive do something like the following:

window.location.href="https://myserver.com/oauth2/authorize?redirect_uri=http://myAppServer.com/myAngular2App/callback&response_type=code&client_id=clientId&scope=my_scope

Use own username/password with git and bitbucket

I figured I should share my solution, since I wasn't able to find it anywhere, and only figured it out through trial and error.

I indeed was able to transfer ownership of the repository to a team on BitBucket.

Don't add the remote URL that BitBuckets suggests:

git remote add origin https://[email protected]/teamName/repo.git

Instead, add the remote URL without your username:

git remote add origin https://bitbucket.org/teamName/repo.git

This way, when you go to pull from or push to a repo, it prompts you for your username, then for your password: everyone on the team has access to it under their own credentials. This approach only works with teams on BitBucket, even though you can manage user permissions on single-owner repos.

What is the purpose of the : (colon) GNU Bash builtin?

I saw this usage in a script and thought it was a good substitute for invoking basename within a script.

oldIFS=$IFS  
IFS=/  
for basetool in $0 ; do : ; done  
IFS=$oldIFS  

... this is a replacement for the code: basetool=$(basename $0)

Python string.join(list) on object array rather than string array

The built-in string constructor will automatically call obj.__str__:

''.join(map(str,list))

How to hide a div after some time period?

In older versions of jquery you'll have to do it the "javascript way" using settimeout

setTimeout( function(){$('div').hide();} , 4000);

or

setTimeout( "$('div').hide();", 4000);

Recently with jquery 1.4 this solution has been added:

$("div").delay(4000).hide();

Of course replace "div" by the correct element using a valid jquery selector and call the function when the document is ready.

Could not load file or assembly 'System.Web.Mvc'

I've did a "Update-Package –reinstall Microsoft.AspNet.Mvc" to fix it in Visual Studio 2015.

Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

Laravel Checking If a Record Exists

this is simple code to check email is exist or not in database


    $data = $request->all();
    $user = DB::table('User')->pluck('email')->toArray();
    if(in_array($user,$data['email']))
    {
    echo 'existed email';
    }

Python and pip, list all versions of a package that's available?

You can try to install package version that does to exist. Then pip will list available versions

pip install hell==99999
ERROR: Could not find a version that satisfies the requirement hell==99999
(from versions: 0.1.0, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.3.0,
0.3.1, 0.3.2, 0.3.3, 0.3.4, 0.4.0, 0.4.1)
ERROR: No matching distribution found for hell==99999

What's the best UI for entering date of birth?

you can use plugin cxcalendar. It looks like other datepicker. but you can pick year and month in select after clicking year-month title.

enter image description here

Prompt for user input in PowerShell

As an alternative, you could add it as a script parameter for input as part of script execution

 param(
      [Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value1,
      [Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value2
      )

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

for eg if CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci replace it to CHARSET=latin1 and remove the collate

You are good to go

Remove white space above and below large text in an inline-block element

I had a similar problem. As you increase the line-height the space above the text increases. It's not padding but it will affect the vertical space between content. I found that adding a -ve top margin seemed to do the trick. It had to be done for all of the different instances of line-height and it varies with font-family too. Maybe this is something which designers need to be more aware of when passing design requirements (?) So for a particular instance of font-family and line-height:

h1 {
    font-family: 'Garamond Premier Pro Regular';
    font-size: 24px;
    color: #001230;
    line-height: 29px;
    margin-top: -5px;    /* CORRECTION FOR LINE-HEIGHT */
}

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

There are two problems with your attempt.

First, you've used n+1 instead of i+1, so you're going to return something like [5, 5, 5, 5] instead of [1, 2, 3, 4].

Second, you can't for-loop over a number like n, you need to loop over some kind of sequence, like range(n).

So:

def naturalNumbers(n):
    return [i+1 for i in range(n)]

But if you already have the range function, you don't need this at all; you can just return range(1, n+1), as arshaji showed.

So, how would you build this yourself? You don't have a sequence to loop over, so instead of for, you have to build it yourself with while:

def naturalNumbers(n):
    results = []
    i = 1
    while i <= n:
        results.append(i)
        i += 1
    return results

Of course in real-life code, you should always use for with a range, instead of doing things manually. In fact, even for this exercise, it might be better to write your own range function first, just to use it for naturalNumbers. (It's already pretty close.)


There is one more option, if you want to get clever.

If you have a list, you can slice it. For example, the first 5 elements of my_list are my_list[:5]. So, if you had an infinitely-long list starting with 1, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using count or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice. So:

from itertools import count, islice
def naturalNumbers(n):
    return list(islice(count(1), n))

RESTful API methods; HEAD & OPTIONS

As per: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

9.2 OPTIONS

The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

Responses to this method are not cacheable.

If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding), then the media type MUST be indicated by a Content-Type field. Although this specification does not define any use for such a body, future extensions to HTTP might use the OPTIONS body to make more detailed queries on the server. A server that does not support such an extension MAY discard the request body.

If the Request-URI is an asterisk ("*"), the OPTIONS request is intended to apply to the server in general rather than to a specific resource. Since a server's communication options typically depend on the resource, the "*" request is only useful as a "ping" or "no-op" type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof).

If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.

A 200 response SHOULD include any header fields that indicate optional features implemented by the server and applicable to that resource (e.g., Allow), possibly including extensions not defined by this specification. The response body, if any, SHOULD also include information about the communication options. The format for such a body is not defined by this specification, but might be defined by future extensions to HTTP. Content negotiation MAY be used to select the appropriate response format. If no response body is included, the response MUST include a Content-Length field with a field-value of "0".

The Max-Forwards request-header field MAY be used to target a specific proxy in the request chain. When a proxy receives an OPTIONS request on an absoluteURI for which request forwarding is permitted, the proxy MUST check for a Max-Forwards field. If the Max-Forwards field-value is zero ("0"), the proxy MUST NOT forward the message; instead, the proxy SHOULD respond with its own communication options. If the Max-Forwards field-value is an integer greater than zero, the proxy MUST decrement the field-value when it forwards the request. If no Max-Forwards field is present in the request, then the forwarded request MUST NOT include a Max-Forwards field.

9.4 HEAD

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.

PHP compare two arrays and get the matched values not the difference

Simple, use array_intersect() instead:

$result = array_intersect($array1, $array2);

How to Empty Caches and Clean All Targets Xcode 4 and later

I have been pulling out hair from my head because I thought that I had the same problem. When building the app I didn't get the same result on my iPhone as on the simulator.

The problem was that I had somehow made a localized version of the MainStoryboard.storyboard file. So when I ran the app on my phone it showed the danish version... and the simulator showed the english version.

Yeah I'm new! :)

How to concatenate strings in twig

To mix strings, variables and translations I simply do the following:

    {% set add_link = '
    <a class="btn btn-xs btn-icon-only" 
       title="' ~ 'string.to_be_translated'|trans ~ '" 
       href="' ~ path('acme_myBundle_link',{'link':link.id})  ~ '">
    </a>
    ' %}

Despite everything being mixed up, it works like a charm.

How to check if a Ruby object is a Boolean

There is no Boolean class in Ruby, the only way to check is to do what you're doing (comparing the object against true and false or the class of the object against TrueClass and FalseClass). Can't think of why you would need this functionality though, can you explain? :)

If you really need this functionality however, you can hack it in:

module Boolean; end
class TrueClass; include Boolean; end
class FalseClass; include Boolean; end

true.is_a?(Boolean) #=> true
false.is_a?(Boolean) #=> true

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

Web Application context extended Application Context which is designed to work with the standard javax.servlet.ServletContext so it's able to communicate with the container.

public interface WebApplicationContext extends ApplicationContext {
    ServletContext getServletContext();
}

Beans, instantiated in WebApplicationContext will also be able to use ServletContext if they implement ServletContextAware interface

package org.springframework.web.context;
public interface ServletContextAware extends Aware { 
     void setServletContext(ServletContext servletContext);
}

There are many things possible to do with the ServletContext instance, for example accessing WEB-INF resources(xml configs and etc.) by calling the getResourceAsStream() method. Typically all application contexts defined in web.xml in a servlet Spring application are Web Application contexts, this goes both to the root webapp context and the servlet's app context.

Also, depending on web application context capabilities may make your application a little harder to test, and you may need to use MockServletContext class for testing.

Difference between servlet and root context Spring allows you to build multilevel application context hierarchies, so the required bean will be fetched from the parent context if it's not present in the current application context. In web apps as default there are two hierarchy levels, root and servlet contexts: Servlet and root context.

This allows you to run some services as the singletons for the entire application (Spring Security beans and basic database access services typically reside here) and another as separated services in the corresponding servlets to avoid name clashes between beans. For example one servlet context will be serving the web pages and another will be implementing a stateless web service.

This two level separation comes out of the box when you use the spring servlet classes: to configure the root application context you should use context-param tag in your web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/root-context.xml
            /WEB-INF/applicationContext-security.xml
    </param-value>
</context-param>

(the root application context is created by ContextLoaderListener which is declared in web.xml

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> 

) and servlet tag for the servlet application contexts

<servlet>
   <servlet-name>myservlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>app-servlet.xml</param-value>
   </init-param>
</servlet>

Please note that if init-param will be omitted, then spring will use myservlet-servlet.xml in this example.

See also: Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

Import CSV file into SQL Server

2) If the client create the csv from excel then the data that have comma are enclosed within " ... " (double quotes) [as the below example] so how do the import can handle this?

You should use FORMAT = 'CSV', FIELDQUOTE = '"' options:

BULK INSERT SchoolsTemp
FROM 'C:\CSVData\Schools.csv'
WITH
(
    FORMAT = 'CSV', 
    FIELDQUOTE = '"',
    FIRSTROW = 2,
    FIELDTERMINATOR = ',',  --CSV field delimiter
    ROWTERMINATOR = '\n',   --Use to shift the control to next row
    TABLOCK
)

CSS div element - how to show horizontal scroll bars only?

You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.

However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.

IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:

overflow: auto;
overflow-y: hidden;

You may also need to add for IE8:

-ms-overflow-y: hidden;

as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)

On the other hand it's entirely possible IE8 will have fixed the bug anyway.

WCF gives an unsecured or incorrectly secured fault error

I've also had this problem from a service reference that was out of date, even with the server & client on the same machine. Running 'Update Service Reference' will generally fix it if this is the issue.

How to check for an empty object in an AngularJS view

I have met a similar problem when checking emptiness in a component. In this case, the controller must define a method that actually performs the test and the view uses it:

function FormNumericFieldController(/*$scope, $element, $attrs*/ ) {
    var ctrl = this;

    ctrl.isEmptyObject = function(object) {
        return angular.equals(object, {});
    }
}

<!-- any validation error will trigger an error highlight -->
<span ng-class="{'has-error': !$ctrl.isEmptyObject($ctrl.formFieldErrorRef) }">
    <!-- validated control here -->
</span>

Delete all documents from index/type without deleting type

The above answers no longer work with ES 6.2.2 because of Strict Content-Type Checking for Elasticsearch REST Requests. The curl command which I ended up using is this:

curl -H'Content-Type: application/json' -XPOST 'localhost:9200/yourindex/_doc/_delete_by_query?conflicts=proceed' -d' { "query": { "match_all": {} }}'

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

On a rather unrelated note: more performance hacks!

  • [the first «conjecture» has been finally debunked by @ShreevatsaR; removed]

  • When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N (shown first):

    1. [even] [odd]
    2. [odd] [even]
    3. [even] [even]

    To leap past these 2 elements means to compute (N >> 1) + N + 1, ((N << 1) + N + 1) >> 1 and N >> 2, respectively.

    Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1.

    Case (1) is obvious. Case (2) implies (N & 1) == 1, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba from most- to least-significant, then a = 1, and the following holds:

    (N << 1) + N + 1:     (N >> 1) + N + 1:
    
            b10                    b1
             b1                     b
           +  1                   + 1
           ----                   ---
           bBb0                   bBb
    

    where B = !b. Right-shifting the first result gives us exactly what we want.

    Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1.

    As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.

The resulting algorithm looks like this:

uint64_t sequence(uint64_t size, uint64_t *path) {
    uint64_t n, i, c, maxi = 0, maxc = 0;

    for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
        c = 2;
        while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
            c += 2;
        if (n == 2)
            c++;
        if (c > maxc) {
            maxi = i;
            maxc = c;
        }
    }
    *path = maxc;
    return maxi;
}

int main() {
    uint64_t maxi, maxc;

    maxi = sequence(1000000, &maxc);
    printf("%llu, %llu\n", maxi, maxc);
    return 0;
}

Here we compare n > 2 because the process may stop at 2 instead of 1 if the total length of the sequence is odd.

[EDIT:]

Let`s translate this into assembly!

MOV RCX, 1000000;



DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;

@main:
  XOR RSI, RSI;
  LEA RDI, [RCX + 1];

  @loop:
    ADD RSI, 2;
    LEA RDX, [RDI + RDI*2 + 2];
    SHR RDX, 1;
    SHRD RDI, RDI, 2;    ror rdi,2   would do the same thing
    CMOVL RDI, RDX;      Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
    CMOVS RDI, RDX;
    CMP RDI, 2;
  JA @loop;

  LEA RDX, [RSI + 1];
  CMOVE RSI, RDX;

  CMP RAX, RSI;
  CMOVB RAX, RSI;
  CMOVB RBX, RCX;

  SUB RCX, 2;
JA @main;



MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;

@itoa:
  XOR RDX, RDX;
  DIV RCX;
  ADD RDX, '0';
  PUSH RDX;
  TEST RAX, RAX;
JNE @itoa;

  PUSH RCX;
  LEA RAX, [RBX + 1];
  TEST RBX, RBX;
  MOV RBX, RDI;
JNE @itoa;

POP RCX;
INC RDI;
MOV RDX, RDI;

@outp:
  MOV RSI, RSP;
  MOV RAX, RDI;
  SYSCALL;
  POP RAX;
  TEST RAX, RAX;
JNE @outp;

LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;

Use these commands to compile:

nasm -f elf64 file.asm
ld -o file file.o

See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)

Subversion stuck due to "previous operation has not finished"?

Trying to run cleanup while your files are open gave me problems. as soon as I closed my application (Visual studio) I ran clean up and it was successful

How do I copy the contents of one ArrayList into another?

Here is a workaround to copy all the objects from one arrayList to another:

 ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();

myObject.addAll(myTempObject.subList(0, myTempObject.size()));

subList is intended to return a List with a range of data. so you can copy the whole arrayList or part of it.

TypeScript or JavaScript type casting

In typescript it is possible to do an instanceof check in an if statement and you will have access to the same variable with the Typed properties.

So let's say MarkerSymbolInfo has a property on it called marker. You can do the following:

if (symbolInfo instanceof MarkerSymbol) {
    // access .marker here
    const marker = symbolInfo.marker
}

It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.

Check out these two resources for more information:

TypeScript instanceof & JavaScript instanceof

iOS - Calling App Delegate method from ViewController

If someone need the same in Xamarin (Xamarin.ios / Monotouch), this worked for me:

var myDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;

(Require using UIKit;)

Determine what attributes were changed in Rails after_save callback?

The "selected" answer didn't work for me. I'm using rails 3.1 with CouchRest::Model (based on Active Model). The _changed? methods don't return true for changed attributes in the after_update hook, only in the before_update hook. I was able to get it to work using the (new?) around_update hook:

class SomeModel < ActiveRecord::Base
  around_update :send_notification_after_change

  def send_notification_after_change
    should_send_it = self.published_changed? && self.published == true

    yield

    Notification.send(...) if should_send_it
  end

end

How do I concatenate a string with a variable?

Another way to do it simpler using jquery.

sample:

function add(product_id){

    // the code to add the product
    //updating the div, here I just change the text inside the div. 
    //You can do anything with jquery, like change style, border etc.
    $("#added_"+product_id).html('the product was added to list');

}

Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.

Best Regards!

What is the purpose of Order By 1 in SQL select statement?

An example here from a sample test WAMP server database:-

mysql> select * from user_privileges;

| GRANTEE            | TABLE_CATALOG | PRIVILEGE_TYPE          | IS_GRANTABLE |
   +--------------------+---------------+-------------------------+--------------+
| 'root'@'localhost' | def           | SELECT                  | YES          |
| 'root'@'localhost' | def           | INSERT                  | YES          |
| 'root'@'localhost' | def           | UPDATE                  | YES          |
| 'root'@'localhost' | def           | DELETE                  | YES          |
| 'root'@'localhost' | def           | CREATE                  | YES          |
| 'root'@'localhost' | def           | DROP                    | YES          |
| 'root'@'localhost' | def           | RELOAD                  | YES          |
| 'root'@'localhost' | def           | SHUTDOWN                | YES          |
| 'root'@'localhost' | def           | PROCESS                 | YES          |
| 'root'@'localhost' | def           | FILE                    | YES          |
| 'root'@'localhost' | def           | REFERENCES              | YES          |
| 'root'@'localhost' | def           | INDEX                   | YES          |
| 'root'@'localhost' | def           | ALTER                   | YES          |
| 'root'@'localhost' | def           | SHOW DATABASES          | YES          |
| 'root'@'localhost' | def           | SUPER                   | YES          |
| 'root'@'localhost' | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'localhost' | def           | LOCK TABLES             | YES          |
| 'root'@'localhost' | def           | EXECUTE                 | YES          |
| 'root'@'localhost' | def           | REPLICATION SLAVE       | YES          |
| 'root'@'localhost' | def           | REPLICATION CLIENT      | YES          |
| 'root'@'localhost' | def           | CREATE VIEW             | YES          |
| 'root'@'localhost' | def           | SHOW VIEW               | YES          |
| 'root'@'localhost' | def           | CREATE ROUTINE          | YES          |
| 'root'@'localhost' | def           | ALTER ROUTINE           | YES          |
| 'root'@'localhost' | def           | CREATE USER             | YES          |
| 'root'@'localhost' | def           | EVENT                   | YES          |
| 'root'@'localhost' | def           | TRIGGER                 | YES          |
| 'root'@'localhost' | def           | CREATE TABLESPACE       | YES          |
| 'root'@'127.0.0.1' | def           | SELECT                  | YES          |
| 'root'@'127.0.0.1' | def           | INSERT                  | YES          |
| 'root'@'127.0.0.1' | def           | UPDATE                  | YES          |
| 'root'@'127.0.0.1' | def           | DELETE                  | YES          |
| 'root'@'127.0.0.1' | def           | CREATE                  | YES          |
| 'root'@'127.0.0.1' | def           | DROP                    | YES          |
| 'root'@'127.0.0.1' | def           | RELOAD                  | YES          |
| 'root'@'127.0.0.1' | def           | SHUTDOWN                | YES          |
| 'root'@'127.0.0.1' | def           | PROCESS                 | YES          |
| 'root'@'127.0.0.1' | def           | FILE                    | YES          |
| 'root'@'127.0.0.1' | def           | REFERENCES              | YES          |
| 'root'@'127.0.0.1' | def           | INDEX                   | YES          |
| 'root'@'127.0.0.1' | def           | ALTER                   | YES          |
| 'root'@'127.0.0.1' | def           | SHOW DATABASES          | YES          |
| 'root'@'127.0.0.1' | def           | SUPER                   | YES          |
| 'root'@'127.0.0.1' | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'127.0.0.1' | def           | LOCK TABLES             | YES          |
| 'root'@'127.0.0.1' | def           | EXECUTE                 | YES          |
| 'root'@'127.0.0.1' | def           | REPLICATION SLAVE       | YES          |
| 'root'@'127.0.0.1' | def           | REPLICATION CLIENT      | YES          |
| 'root'@'127.0.0.1' | def           | CREATE VIEW             | YES          |
| 'root'@'127.0.0.1' | def           | SHOW VIEW               | YES          |
| 'root'@'127.0.0.1' | def           | CREATE ROUTINE          | YES          |
| 'root'@'127.0.0.1' | def           | ALTER ROUTINE           | YES          |
| 'root'@'127.0.0.1' | def           | CREATE USER             | YES          |
| 'root'@'127.0.0.1' | def           | EVENT                   | YES          |
| 'root'@'127.0.0.1' | def           | TRIGGER                 | YES          |
| 'root'@'127.0.0.1' | def           | CREATE TABLESPACE       | YES          |
| 'root'@'::1'       | def           | SELECT                  | YES          |
| 'root'@'::1'       | def           | INSERT                  | YES          |
| 'root'@'::1'       | def           | UPDATE                  | YES          |
| 'root'@'::1'       | def           | DELETE                  | YES          |
| 'root'@'::1'       | def           | CREATE                  | YES          |
| 'root'@'::1'       | def           | DROP                    | YES          |
| 'root'@'::1'       | def           | RELOAD                  | YES          |
| 'root'@'::1'       | def           | SHUTDOWN                | YES          |
| 'root'@'::1'       | def           | PROCESS                 | YES          |
| 'root'@'::1'       | def           | FILE                    | YES          |
| 'root'@'::1'       | def           | REFERENCES              | YES          |
| 'root'@'::1'       | def           | INDEX                   | YES          |
| 'root'@'::1'       | def           | ALTER                   | YES          |
| 'root'@'::1'       | def           | SHOW DATABASES          | YES          |
| 'root'@'::1'       | def           | SUPER                   | YES          |
| 'root'@'::1'       | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'::1'       | def           | LOCK TABLES             | YES          |
| 'root'@'::1'       | def           | EXECUTE                 | YES          |
| 'root'@'::1'       | def           | REPLICATION SLAVE       | YES          |
| 'root'@'::1'       | def           | REPLICATION CLIENT      | YES          |
| 'root'@'::1'       | def           | CREATE VIEW             | YES          |
| 'root'@'::1'       | def           | SHOW VIEW               | YES          |
| 'root'@'::1'       | def           | CREATE ROUTINE          | YES          |
| 'root'@'::1'       | def           | ALTER ROUTINE           | YES          |
| 'root'@'::1'       | def           | CREATE USER             | YES          |
| 'root'@'::1'       | def           | EVENT                   | YES          |
| 'root'@'::1'       | def           | TRIGGER                 | YES          |
| 'root'@'::1'       | def           | CREATE TABLESPACE       | YES          |
| ''@'localhost'     | def           | USAGE                   | NO           |
+--------------------+---------------+-------------------------+--------------+
85 rows in set (0.00 sec)

And when it is given additional order by PRIVILEGE_TYPE or can be given order by 3 . Notice the 3rd column (PRIVILEGE_TYPE) getting sorted alphabetically.

mysql> select * from user_privileges order by PRIVILEGE_TYPE;
+--------------------+---------------+-------------------------+--------------+
| GRANTEE            | TABLE_CATALOG | PRIVILEGE_TYPE          | IS_GRANTABLE |
+--------------------+---------------+-------------------------+--------------+
| 'root'@'127.0.0.1' | def           | ALTER                   | YES          |
| 'root'@'::1'       | def           | ALTER                   | YES          |
| 'root'@'localhost' | def           | ALTER                   | YES          |
| 'root'@'::1'       | def           | ALTER ROUTINE           | YES          |
| 'root'@'localhost' | def           | ALTER ROUTINE           | YES          |
| 'root'@'127.0.0.1' | def           | ALTER ROUTINE           | YES          |
| 'root'@'127.0.0.1' | def           | CREATE                  | YES          |
| 'root'@'::1'       | def           | CREATE                  | YES          |
| 'root'@'localhost' | def           | CREATE                  | YES          |
| 'root'@'::1'       | def           | CREATE ROUTINE          | YES          |
| 'root'@'localhost' | def           | CREATE ROUTINE          | YES          |
| 'root'@'127.0.0.1' | def           | CREATE ROUTINE          | YES          |
| 'root'@'::1'       | def           | CREATE TABLESPACE       | YES          |
| 'root'@'localhost' | def           | CREATE TABLESPACE       | YES          |
| 'root'@'127.0.0.1' | def           | CREATE TABLESPACE       | YES          |
| 'root'@'::1'       | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'localhost' | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'127.0.0.1' | def           | CREATE TEMPORARY TABLES | YES          |
| 'root'@'localhost' | def           | CREATE USER             | YES          |
| 'root'@'127.0.0.1' | def           | CREATE USER             | YES          |
| 'root'@'::1'       | def           | CREATE USER             | YES          |
| 'root'@'localhost' | def           | CREATE VIEW             | YES          |
| 'root'@'127.0.0.1' | def           | CREATE VIEW             | YES          |
| 'root'@'::1'       | def           | CREATE VIEW             | YES          |
| 'root'@'127.0.0.1' | def           | DELETE                  | YES          |
| 'root'@'::1'       | def           | DELETE                  | YES          |
| 'root'@'localhost' | def           | DELETE                  | YES          |
| 'root'@'::1'       | def           | DROP                    | YES          |
| 'root'@'localhost' | def           | DROP                    | YES          |
| 'root'@'127.0.0.1' | def           | DROP                    | YES          |
| 'root'@'127.0.0.1' | def           | EVENT                   | YES          |
| 'root'@'::1'       | def           | EVENT                   | YES          |
| 'root'@'localhost' | def           | EVENT                   | YES          |
| 'root'@'127.0.0.1' | def           | EXECUTE                 | YES          |
| 'root'@'::1'       | def           | EXECUTE                 | YES          |
| 'root'@'localhost' | def           | EXECUTE                 | YES          |
| 'root'@'127.0.0.1' | def           | FILE                    | YES          |
| 'root'@'::1'       | def           | FILE                    | YES          |
| 'root'@'localhost' | def           | FILE                    | YES          |
| 'root'@'localhost' | def           | INDEX                   | YES          |
| 'root'@'127.0.0.1' | def           | INDEX                   | YES          |
| 'root'@'::1'       | def           | INDEX                   | YES          |
| 'root'@'::1'       | def           | INSERT                  | YES          |
| 'root'@'localhost' | def           | INSERT                  | YES          |
| 'root'@'127.0.0.1' | def           | INSERT                  | YES          |
| 'root'@'127.0.0.1' | def           | LOCK TABLES             | YES          |
| 'root'@'::1'       | def           | LOCK TABLES             | YES          |
| 'root'@'localhost' | def           | LOCK TABLES             | YES          |
| 'root'@'127.0.0.1' | def           | PROCESS                 | YES          |
| 'root'@'::1'       | def           | PROCESS                 | YES          |
| 'root'@'localhost' | def           | PROCESS                 | YES          |
| 'root'@'::1'       | def           | REFERENCES              | YES          |
| 'root'@'localhost' | def           | REFERENCES              | YES          |
| 'root'@'127.0.0.1' | def           | REFERENCES              | YES          |
| 'root'@'::1'       | def           | RELOAD                  | YES          |
| 'root'@'localhost' | def           | RELOAD                  | YES          |
| 'root'@'127.0.0.1' | def           | RELOAD                  | YES          |
| 'root'@'::1'       | def           | REPLICATION CLIENT      | YES          |
| 'root'@'localhost' | def           | REPLICATION CLIENT      | YES          |
| 'root'@'127.0.0.1' | def           | REPLICATION CLIENT      | YES          |
| 'root'@'::1'       | def           | REPLICATION SLAVE       | YES          |
| 'root'@'localhost' | def           | REPLICATION SLAVE       | YES          |
| 'root'@'127.0.0.1' | def           | REPLICATION SLAVE       | YES          |
| 'root'@'127.0.0.1' | def           | SELECT                  | YES          |
| 'root'@'::1'       | def           | SELECT                  | YES          |
| 'root'@'localhost' | def           | SELECT                  | YES          |
| 'root'@'127.0.0.1' | def           | SHOW DATABASES          |  YES          |
| 'root'@'::1'       | def           | SHOW DATABASES          | YES          |
| 'root'@'localhost' | def           | SHOW DATABASES          | YES          |
| 'root'@'127.0.0.1' | def           | SHOW VIEW               | YES          |
| 'root'@'::1'       | def           | SHOW VIEW               | YES          |
| 'root'@'localhost' | def           | SHOW VIEW               | YES          |
| 'root'@'localhost' | def           | SHUTDOWN                | YES          |
| 'root'@'127.0.0.1' | def           | SHUTDOWN                | YES          |
| 'root'@'::1'       | def           | SHUTDOWN                | YES          |
| 'root'@'::1'       | def           | SUPER                   | YES          |
| 'root'@'localhost' | def           | SUPER                   | YES          |
| 'root'@'127.0.0.1' | def           | SUPER                   | YES          |
| 'root'@'127.0.0.1' | def           | TRIGGER                 | YES          |
| 'root'@'::1'       | def           | TRIGGER                 | YES          |
| 'root'@'localhost' | def           | TRIGGER                 | YES          |
| 'root'@'::1'       | def           | UPDATE                  | YES          |
| 'root'@'localhost' | def           | UPDATE                  | YES          |
| 'root'@'127.0.0.1' | def           | UPDATE                  | YES          |
| ''@'localhost'     | def           | USAGE                   | NO           |     +--------------------+---------------+-------------------------+--------------+
85 rows in set (0.00 sec)

DEFINITIVELY, a long answer and alot of scrolling. Also I struggled hard to pass the output of the queries to a text file. Here is how to do that without using the annoying into outfile thing-

tee E:/sqllogfile.txt;

And when you are done, stop the logging-

tee off;

Hope it adds more clarity.

How to convert an object to JSON correctly in Angular 2 with TypeScript

Because you're encapsulating the product again. Try to convert it like so:

let body = JSON.stringify(product); 

How to set a binding in Code?

Replace:

myBinding.Source = ViewModel.SomeString;

with:

myBinding.Source = ViewModel;

Example:

Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);

Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

How to create SPF record for multiple IPs?

Yes the second syntax is fine.

Have you tried using the SPF wizard? https://www.spfwizard.net/

It can quickly generate basic and complex SPF records.

Determining complexity for recursive functions (Big O notation)

The time complexity, in Big O notation, for each function:


int recursiveFun1(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun1(n-1);
}

This function is being called recursively n times before reaching the base case so its O(n), often called linear.


int recursiveFun2(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun2(n-5);
}

This function is called n-5 for each time, so we deduct five from n before calling the function, but n-5 is also O(n). (Actually called order of n/5 times. And, O(n/5) = O(n) ).


int recursiveFun3(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun3(n/5);
}

This function is log(n) base 5, for every time we divide by 5 before calling the function so its O(log(n))(base 5), often called logarithmic and most often Big O notation and complexity analysis uses base 2.


void recursiveFun4(int n, int m, int o)
{
    if (n <= 0)
    {
        printf("%d, %d\n",m, o);
    }
    else
    {
        recursiveFun4(n-1, m+1, o);
        recursiveFun4(n-1, m, o+1);
    }
}

Here, it's O(2^n), or exponential, since each function call calls itself twice unless it has been recursed n times.



int recursiveFun5(int n)
{
    for (i = 0; i < n; i += 2) {
        // do something
    }

    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun5(n-5);
}

And here the for loop takes n/2 since we're increasing by 2, and the recursion takes n/5 and since the for loop is called recursively, therefore, the time complexity is in

(n/5) * (n/2) = n^2/10,

due to Asymptotic behavior and worst-case scenario considerations or the upper bound that big O is striving for, we are only interested in the largest term so O(n^2).


Good luck on your midterms ;)

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

just put all apache comons jar and file upload jar in lib folder of tomcat

Why do I always get the same sequence of random numbers with rand()?

None of you guys are answering his question.

with this code i get the same sequance everytime the code but it generates random sequences if i add srand(/somevalue/) before the for loop . can someone explain why ?

From what my professor has told me, it is used if you want to make sure your code is running properly and to see if there is something wrong or if you can change something.

Update .NET web service to use TLS 1.2

Three steps needed:

  1. Explicitly mark SSL2.0, TLS1.0, TLS1.1 as forbidden on your server machine, by adding Enabled=0 and DisabledByDefault=1 to your registry (the full path is HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols). See screen for details registry

  2. Explicitly enable TLS1.2 by following the steps from 1. Just use Enabled=1 and DisabledByDefault=0 respectively.

NOTE: verify server version: Windows Server 2003 does not support the TLS 1.2 protocol

  1. Enable TLS1.2 only on app level, like @John Wu suggested above.

    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Hope this guide helps.

UPDATE As @Subbu mentioned: Official guide

How to print current date on python3?

I always use this code, which print the year to second in a tuple

import datetime

now = datetime.datetime.now()

time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)

print(time_now)

DATEDIFF function in Oracle

In Oracle, you can simply subtract two dates and get the difference in days. Also note that unlike SQL Server or MySQL, in Oracle you cannot perform a select statement without a from clause. One way around this is to use the builtin dummy table, dual:

SELECT TO_DATE('2000-01-02', 'YYYY-MM-DD') -  
       TO_DATE('2000-01-01', 'YYYY-MM-DD') AS DateDiff
FROM   dual

How do I run a spring boot executable jar in a Production environment?

On Windows OS without Service.

start.bat

@ECHO OFF
call run.bat start

stop.bat:

@ECHO OFF
call run.bat stop

run.bat

@ECHO OFF
IF "%1"=="start" (
    ECHO start myapp
    start "myapp" java -jar -Dspring.profiles.active=staging myapp.jar
) ELSE IF "%1"=="stop" (
    ECHO stop myapp
    TASKKILL /FI "WINDOWTITLE eq myapp"
) ELSE (
    ECHO please, use "run.bat start" or "run.bat stop"
)
pause

How do I get this javascript to run every second?

You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.

var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);

//To abort the interval you can use this:
clearInterval(b);

How to return dictionary keys as a list in Python?

If you need to store the keys separately, here's a solution that requires less typing than every other solution presented thus far, using Extended Iterable Unpacking (python3.x+).

newdict = {1: 0, 2: 0, 3: 0}
*k, = newdict

k
# [1, 2, 3]

            +---------------------------------------------------------+
            ¦ k = list(d)   ¦   9 characters (excluding whitespace)   ¦
            +---------------+-----------------------------------------¦
            ¦ k = [*d]      ¦   6 characters                          ¦
            +---------------+-----------------------------------------¦
            ¦ *k, = d       ¦   5 characters                          ¦
            +---------------------------------------------------------+

HTML form with side by side input fields

Put style="float:left" on each of your divs:

<div style="float:left;">...........

Example:

<div style="float:left;">
  <label for="username">First Name</label>
  <input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>

<div style="float:left;">
  <label for="name">Last Name</label>
  <input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>

To put an element on new line, put this div below it:

<div style="clear:both;">&nbsp;</div>

Of course, you can also create classes in the CSS file:

.left{
  float:left;
}

.clear{
  clear:both;
}

And then your html should look like this:

<div class="left">
  <label for="username">First Name</label>
  <input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>

<div class="left">
  <label for="name">Last Name</label>
  <input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>

To put an element on new line, put this div below it:

<div class="clear">&nbsp;</div>

More Info:

How to convert integer to string in C?

That's because itoa isn't a standard function. Try snprintf instead.

char str[LEN];
snprintf(str, LEN, "%d", 42);

Escape double quotes for JSON in Python

i know this question is old, but hopefully it will help someone. i found a great plugin for those who are using PyCharm IDE: string-manipulation that can easily escape double quotes (and many more...), this plugin is great for cases where you know what the string going to be. for other cases, using json.dumps(string) will be the recommended solution

str_to_escape = 'my string with "double quotes" blablabla'

after_escape = 'my string with \"double quotes\" blablabla'

Calculating distance between two geographic locations

Try This Code. here we have two longitude and latitude values and selected_location.distanceTo(near_locations) function returns the distance between those places in meters.

Location selected_location = new Location("locationA");
            selected_location.setLatitude(17.372102);
            selected_location.setLongitude(78.484196);
Location near_locations = new Location("locationB");
            near_locations.setLatitude(17.375775);
            near_locations.setLongitude(78.469218);
double distance = selected_location.distanceTo(near_locations);

here "distance" is distance between locationA & locationB (in Meters)

Iterate through a HashMap

Smarter:

for (String key : hashMap.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}

Calling a php function by onclick event

probably the onclick handler should read onclick='hello();' instead of onclick=hello();

How to use a keypress event in AngularJS?

An alternative is to use standard directive ng-keypress="myFunct($event)"

Then in your controller you can have:

...

$scope.myFunct = function(keyEvent) {
  if (keyEvent.which === 13)
    alert('I am an alert');
}

...

Angular 5, HTML, boolean on checkbox is checked

Hope this will help somebody to develop custom checkbox component with custom styles. This solution can use with forms too.

HTML

<label class="lbl">

  <input #inputEl type="checkbox" [name]="label" [(ngModel)]="isChecked" (change)="onChange(inputEl.checked)"
   *ngIf="isChecked" checked>
  <input #inputEl type="checkbox" [name]="label" [(ngModel)]="isChecked" (change)="onChange(inputEl.checked)"
   *ngIf="!isChecked" >
  <span class="chk-box {{isChecked ? 'chk':''}}"></span>
  <span class="lbl-txt" *ngIf="label" >{{label}}</span>
</label>

checkbox.component.ts

    import { Component, Input, EventEmitter, Output, forwardRef, HostListener } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

const noop = () => {
};

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => CheckboxComponent),
  multi: true
};

/** Custom check box  */
@Component({
  selector: 'app-checkbox',
  templateUrl: './checkbox.component.html',
  styleUrls: ['./checkbox.component.scss'],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CheckboxComponent implements ControlValueAccessor {


  @Input() label: string;
  @Input() isChecked = false;
  @Input() disabled = false;
  @Output() getChange = new EventEmitter();
  @Input() className: string;

  // get accessor
  get value(): any {
    return this.isChecked;
  }

  // set accessor including call the onchange callback
  set value(value: any) {
    this.isChecked = value;
  }

  private onTouchedCallback: () => void = noop;
  private onChangeCallback: (_: any) => void = noop;


  writeValue(value: any): void {
    if (value !== this.isChecked) {
      this.isChecked = value;
    }
  }

  onChange(isChecked) {
    this.value = isChecked;
    this.getChange.emit(this.isChecked);
    this.onChangeCallback(this.value);
  }

  // From ControlValueAccessor interface
  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  // From ControlValueAccessor interface
  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }

  setDisabledState?(isDisabled: boolean): void {

  }

}

checkbox.component.scss

   @import "../../../assets/scss/_variables";
/* CHECKBOX */

.lbl {
    font-size: 12px;
    color: #282828;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    cursor: pointer;
    &.checked {
        font-weight: 600;
    }
    &.focus {
      .chk-box{
        border: 1px solid #a8a8a8;
        &.chk{
          border: none;
        }
      }
    }
    input {
        display: none;
    }

    /* checkbox icon */
    .chk-box {
        display: block;
        min-width: 15px;
        min-height: 15px;
        background: url('/assets/i/checkbox-not-selected.svg');
        background-size: 15px 15px;
        margin-right: 10px;
    }
    input:checked+.chk-box {
        background: url('/assets/i/checkbox-selected.svg');
        background-size: 15px 15px;
    }
    .lbl-txt {
        margin-top: 0px;
    } 

}

Usage

Outside forms

<app-checkbox [label]="'Example'" [isChecked]="true"></app-checkbox>

Inside forms

<app-checkbox [label]="'Type 0'" formControlName="Type1"></app-checkbox>

How to get row number from selected rows in Oracle

The below query helps to get the row number in oracle,

SELECT ROWNUM AS SNO,ID,NAME,EMAIL,BRANCH FROM student WHERE NAME LIKE '%ram%';

Git:nothing added to commit but untracked files present

You have two options here. You can either add the untracked files to your Git repository (as the warning message suggested), or you can add the files to your .gitignore file, if you want Git to ignore them.

To add the files use git add:

git add Optimization/language/languageUpdate.php
git add email_test.php

To ignore the files, add the following lines to your .gitignore:

/Optimization/language/languageUpdate.php
/email_test.php

Either option should allow the git pull to succeed afterwards.

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

Try this

var time = $("#starttime").val();
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);

What is the meaning of "__attribute__((packed, aligned(4))) "

Before answering, I would like to give you some data from Wiki


Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.


gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.

If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)

Two submit buttons in one form

You can present the buttons like this:

<input type="submit" name="typeBtn" value="BUY">
<input type="submit" name="typeBtn" value="SELL">

And then in the code you can get the value using:

if request.method == 'POST':
    #valUnits = request.POST.get('unitsInput','')
    #valPrice = request.POST.get('priceInput','')
    valType = request.POST.get('typeBtn','')

(valUnits and valPrice are some other values I extract from the form that I left in for illustration)

Django: OperationalError No Such Table

I'm using Django 1.9, SQLite3 and DjangoCMS 3.2 and had the same issue. I solved it by running python manage.py makemigrations. This was followed by a prompt stating that the database contained non-null value types but did not have a default value set. It gave me two options: 1) select a one off value now or 2) exit and change the default setting in models.py. I selected the first option and gave the default value of 1. Repeated this four or five times until the prompt said it was finished. I then ran python manage.py migrate. Now it works just fine. Remember, by running python manage.py makemigrations first, a revised copy of the database is created (mine was 0004) and you can always revert back to a previous database state.

Git merge error "commit is not possible because you have unmerged files"

This error occurs when you resolve the conflicts but the file still needs to be added in the stage area. git add . would solve it. Then, try to commit and merge.

Xcode 10 Error: Multiple commands produce

Issue: Faced Error on creating xcodebuild archive for Cocoapod Project in the command line.

Error in Console: error: Multiple commands produce '/Users/xxxx/Library/Developer/Xcode/DerivedData/...':

Steps that resolved this issue:

  1. Open Xcode
  2. Select Scheme in the Top of Xcode Editor
  3. Select Edit Scheme
  4. Select Build in the left column of the Popup window.
  5. If any additional Target got added other than the Target related to Edited Scheme.
  6. Select the irrelevant Target and remove it by pressing "minus icon" and close the popup.
  7. Run the xcodebuild command again in the command line to get the issue resolved.

Description with image:

Step 1:

Select Scheme

Step 3:

Select Edit Scheme

Step 4-6:

Remove Irrelevant Target and Save

How do I empty an array in JavaScript?

The answers that have no less that 2739 upvotes by now are misleading and incorrect.

The question is: "How do you empty your existing array?" E.g. for A = [1,2,3,4].

  1. Saying "A = [] is the answer" is ignorant and absolutely incorrect. [] == [] is false.

    This is because these two arrays are two separate, individual objects, with their own two identities, taking up their own space in the digital world, each on its own.


Let's say your mother asks you to empty the trash can.

  • You don't bring in a new one as if you've done what you've been asked for.
  • Instead, you empty the trash can.
  • You don't replace the filled one with a new empty can, and you don't take the label "A" from the filled can and stick it to the new one as in A = [1,2,3,4]; A = [];

Emptying an array object is the easiest thing ever:

A.length = 0;

This way, the can under "A" is not only empty, but also as clean as new!


  1. Furthermore, you are not required to remove the trash by hand until the can is empty! You were asked to empty the existing one, completely, in one turn, not to pick up the trash until the can gets empty, as in:

    while(A.length > 0) {
        A.pop();
    }
    
  2. Nor, to put your left hand at the bottom of the trash, holding it with your right at the top to be able to pull its content out as in:

    A.splice(0, A.length);
    

No, you were asked to empty it:

A.length = 0;

This is the only code that correctly empties the contents of a given JavaScript array.

Difference between binary semaphore and mutex

Nice articles on the topic:

From part 2:

The mutex is similar to the principles of the binary semaphore with one significant difference: the principle of ownership. Ownership is the simple concept that when a task locks (acquires) a mutex only it can unlock (release) it. If a task tries to unlock a mutex it hasn’t locked (thus doesn’t own) then an error condition is encountered and, most importantly, the mutex is not unlocked. If the mutual exclusion object doesn't have ownership then, irrelevant of what it is called, it is not a mutex.

Pass variables between two PHP pages without using a form or the URL of page

<?php
session_start();

$message1 = "A message";
$message2 = "Another message";

$_SESSION['firstMessage'] = $message1;
$_SESSION['secondMessage'] = $message2; 
?>

Stores the sessions on page 1 then on page 2 do

<?php
session_start();

echo $_SESSION['firstMessage'];
echo $_SESSION['secondMessage'];
?>

Bat file to run a .exe at the command prompt

As described here, about the Start command, the following would start your application with the parameters you've specified:

start "svcutil" "svcutil.exe" "language:cs" "out:generatedProxy.cs" "config:app.config" "http://localhost:8000/ServiceModelSamples/service"
  • "svcutil", after the start command, is the name given to the CMD window upon running the application specified. This is a required parameter of the start command.

  • "svcutil.exe" is the absolute or relative path to the application you want to run. Using quotation marks allows you to have spaces in the path.

  • After the application to start has been specified, all the following parameters are interpreted as arguments sent to the application.

Android Studio cannot resolve R in imported project?

Had this error when importing project from Eclipse. The reason was some of the xml files had errors. Check ALL your XML files for errors. Including androidmanifest.xml, and values, themes, styles, layouts folders, etc. Warnings in xml are ok, but errors will generate this error.

Afterwards, do a Clean Project and rebuild.

How do you test to see if a double is equal to NaN?

Beginners needs practical examples. so try the following code.

public class Not_a_Number {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";        
    String dottedLine = "------------------------------------------------";     

    Double numerator = -2.0;
    Double denominator = -2.0;      
    while (denominator <= 1) {
        Double x = numerator/denominator;           
        Double y = new Double (x);
        boolean z = y.isNaN();
        System.out.println("y =  " + y);
        System.out.println("z =  " + z);
        if (z == true){
            System.out.println(message);                
        }
        else {
            System.out.println("Hi, everyone"); 
        }
        numerator = numerator + 1;
        denominator = denominator +1;
        System.out.println(dottedLine);         
    } // end of while

} // end of main

} // end of class

Javascript objects: get parent

Try this until a non-no answer appears:

function parent() {
  this.child;
  interestingProperty = "5";
  ...
}

function child() {
  this.parent;
  ...
}

a = new parent();
a.child = new child();
a.child.parent = a; // this gives the child a reference to its parent

alert(a.interestingProperty+" === "+a.child.parent.interestingProperty);

How does PHP 'foreach' actually work?

Some points to note when working with foreach():

a) foreach works on the prospected copy of the original array. It means foreach() will have SHARED data storage until or unless a prospected copy is not created foreach Notes/User comments.

b) What triggers a prospected copy? A prospected copy is created based on the policy of copy-on-write, that is, whenever an array passed to foreach() is changed, a clone of the original array is created.

c) The original array and foreach() iterator will have DISTINCT SENTINEL VARIABLES, that is, one for the original array and other for foreach; see the test code below. SPL , Iterators, and Array Iterator.

Stack Overflow question How to make sure the value is reset in a 'foreach' loop in PHP? addresses the cases (3,4,5) of your question.

The following example shows that each() and reset() DOES NOT affect SENTINEL variables (for example, the current index variable) of the foreach() iterator.

$array = array(1, 2, 3, 4, 5);

list($key2, $val2) = each($array);
echo "each() Original (outside): $key2 => $val2<br/>";

foreach($array as $key => $val){
    echo "foreach: $key => $val<br/>";

    list($key2,$val2) = each($array);
    echo "each() Original(inside): $key2 => $val2<br/>";

    echo "--------Iteration--------<br/>";
    if ($key == 3){
        echo "Resetting original array pointer<br/>";
        reset($array);
    }
}

list($key2, $val2) = each($array);
echo "each() Original (outside): $key2 => $val2<br/>";

Output:

each() Original (outside): 0 => 1
foreach: 0 => 1
each() Original(inside): 1 => 2
--------Iteration--------
foreach: 1 => 2
each() Original(inside): 2 => 3
--------Iteration--------
foreach: 2 => 3
each() Original(inside): 3 => 4
--------Iteration--------
foreach: 3 => 4
each() Original(inside): 4 => 5
--------Iteration--------
Resetting original array pointer
foreach: 4 => 5
each() Original(inside): 0=>1
--------Iteration--------
each() Original (outside): 1 => 2

Difference between request.getSession() and request.getSession(true)

request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

MySQL DROP all tables, ignoring foreign keys

From this answer,

execute:

  use `dbName`; --your db name here
  SET FOREIGN_KEY_CHECKS = 0; 
  SET @tables = NULL;
  SET GROUP_CONCAT_MAX_LEN=32768;

  SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables
  FROM   information_schema.tables 
  WHERE  table_schema = (SELECT DATABASE());
  SELECT IFNULL(@tables, '') INTO @tables;

  SET        @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
  PREPARE    stmt FROM @tables;
  EXECUTE    stmt;
  DEALLOCATE PREPARE stmt;
  SET        FOREIGN_KEY_CHECKS = 1;

This drops tables from the database currently in use. You can set current database using use.


Or otherwise, Dion's accepted answer is simpler, except you need to execute it twice, first to get the query, and second to execute the query. I provided some silly back-ticks to escape special characters in db and table names.

  SELECT CONCAT('DROP TABLE IF EXISTS `', table_schema, '`.`', table_name, '`;')
  FROM   information_schema.tables
  WHERE  table_schema = 'dbName'; --your db name here

Error "The connection to adb is down, and a severe error has occurred."

AndroidSDK ? Platform Tools ? Kill did not work.

But after restarting my computer, it worked.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

Right click on project > properties > android > and try with different version of the android earlier i was doing with android 4.4 then i changed to android 4.3 and it worked !

How can I sort a List alphabetically?

Same in JAVA 8 :-

//Assecnding order
        listOfCountryNames.stream().sorted().forEach((x) -> System.out.println(x));

//Decending order
        listOfCountryNames.stream().sorted((o1, o2) -> o2.compareTo(o1)).forEach((x) -> System.out.println(x));

psql: command not found Mac

If someone used homebrew with Mojave or later:

export PATH=/usr/local/opt/[email protected]/bin:$PATH

change version if you need!

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

Should I use Vagrant or Docker for creating an isolated environment?

With Vagrant now you can have Docker as a provider. http://docs.vagrantup.com/v2/docker/. Docker provider can be used instead of VirtualBox or VMware.

Please note that you can also use Docker for provisioning with Vagrant. This is very different than using Docker as a provider. http://docs.vagrantup.com/v2/provisioning/docker.html

This means you can replace Chef or Puppet with Docker. You can use combinations like Docker as provider (VM) with Chef as provisioner. Or you can use VirtualBox as provider and Docker as provisioner.

How to check for DLL dependency?

dumpbin from Visual Studio tools (VC\bin folder) can help here:

dumpbin /dependents your_dll_file.dll

How to convert CSV to JSON in Node.js

Using lodash:

function csvToJson(csv) {
  const content = csv.split('\n');
  const header = content[0].split(',');
  return _.tail(content).map((row) => {
    return _.zipObject(header, row.split(','));
  });
}

How can I get a list of users from active directory?

If you want to filter y active accounts add this to Harvey's code:

 UserPrincipal userPrin = new UserPrincipal(context);
 userPrin.Enabled = true;

after the first using. Then add

  searcher.QueryFilter = userPrin;

before the find all. And that should get you the active ones.

invalid byte sequence for encoding "UTF8"

It depends on what type of machine/encoding generated your import file.

If you're getting it from an English or Western European version of Windows, your best bet is probably setting it to 'WIN1252'. If you are getting it from a different source, consult the list of character encodings here:

http://www.postgresql.org/docs/8.3/static/multibyte.html

If you're getting it from a Mac, you may have to run it through the "iconv" utility first to convert it from MacRoman to UTF-8.

How do I test if a variable is a number in Bash?

Below is a Script written by me and used for a script integration with Nagios and it is working properly till now

#!/bin/bash
# Script to test variable is numeric or not
# Shirish Shukla
# Pass arg1 as number
a1=$1
a=$(echo $a1|awk '{if($1 > 0) print $1; else print $1"*-1"}')
b=$(echo "scale=2;$a/$a + 1" | bc -l 2>/dev/null)
if [[ $b > 1 ]]
then
    echo "$1 is Numeric"
else
    echo "$1 is Non Numeric"
fi

EG:

# sh isnumsks.sh   "-22.22"
-22.22 is Numeric

# sh isnumsks.sh   "22.22"
22.22 is Numeric

# sh isnumsks.sh   "shirish22.22"
shirish22.22 is Non  Numeric

Checking the form field values before submitting that page

Don't know for sure, but it sounds like it is still submitting. I quick solution would be to change your (guessing at your code here):

<input type="submit" value="Submit" onclick="checkform()">

to a button:

<input type="button" value="Submit" onclick="checkform()">

That way your form still gets submitted (from the else part of your checkform()) and it shouldn't be reloading the page.

There are other, perhaps better, ways of handling it but this works in the mean time.

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

The SELECT ... INTO needs to be in the select from the CTE.

;WITH Calendar
     AS (SELECT /*... Rest of CTE definition removed for clarity*/)
SELECT EventID,
       EventStartDate,
       EventEndDate,
       PlannedDate                   AS [EventDates],
       Cast(PlannedDate AS DATETIME) AS DT,
       Cast(EventStartTime AS TIME)  AS ST,
       Cast(EventEndTime AS TIME)    AS ET,
       EventTitle,
       EventType
INTO TEMPBLOCKEDDATES /* <---- INTO goes here*/        
FROM   Calendar
WHERE  ( PlannedDate >= Getdate() )
       AND ',' + EventEnumDays + ',' LIKE '%,' + Cast(Datepart(dw, PlannedDate) AS CHAR(1)) + ',%'
        OR EventEnumDays IS NULL
ORDER  BY EventID,
          PlannedDate
OPTION (maxrecursion 0) 

MySQL VARCHAR size?

Actually, it will takes 101 bytes.

MySQL Reference

LIKE operator in LINQ

Just add to string object extention methods.

public static class StringEx
{
    public static bool Contains(this String str, string[] Arr, StringComparison comp)
    {
        if (Arr != null)
        {
            foreach (string s in Arr)
            {
                if (str.IndexOf(s, comp)>=0)
                { return true; }
            }
        }

        return false;
    }

    public static bool Contains(this String str,string[] Arr)
    {
        if (Arr != null)
        {
            foreach (string s in Arr)
            {
                if (str.Contains(s))
                { return true; }
            }
        }

        return false;
    }
}

usage:

use namespase that contains this class;

var sPortCode = Database.DischargePorts
            .Where(p => p.PortName.Contains(new string [] {"BALTIMORE"},  StringComparison.CurrentCultureIgnoreCase) )
            .Single().PortCode;

Adding blur effect to background in swift

let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
                    let blurEffectView = UIVisualEffectView(effect: blurEffect)
                    blurEffectView.backgroundColor = .black
                    blurEffectView.alpha = 0.5
                    blurEffectView.frame = topView.bounds
                    if !self.presenting {
                        blurEffectView.frame.origin.x = 0
                    } else {
                        blurEffectView.frame.origin.x = -topView.frame.width
                    }
                    blurEffectView.frame.origin.x = -topView.frame.width
                    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                    UIView.animate(withDuration: 0.2, delay: 0.0, options: [.curveEaseIn]) {
                        if !self.presenting {
                            blurEffectView.frame.origin.x = -topView.frame.width
                        } else {
                            blurEffectView.frame.origin.x = 0
                        }
                        view.addSubview(blurEffectView)
                    } completion: { (status) in
                        
                    }

How do I change the default application icon in Java?

java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");

May or may not require a '/' at the front of the path.

Remove blank attributes from an Object in Javascript

This question has been thoroughly answered already, i'd just like to contribute my version based on other examples given:

function filterObject(obj, filter) {
    return Object.entries(obj)
        .map(([key, value]) => {
            return [key, value && typeof value === 'object'
                ? filterObject(value, filter)
                : value];
        })
        .reduce((acc, [key, value]) => {
            if (!filter.includes(value)) {
                acc[key] = value;
            }

            return acc;
        }, {});
}

What makes this solution different is the ability to specify which values you'd like to filter in the second parameter like this:

const filtered = filterObject(originalObject, [null, '']);

Which will return a new object (does not mutate the original object) not including the properties with a value of null or ''.

detect back button click in browser

best way I know

         window.onbeforeunload = function (e) {
            var e = e || window.event;
            var msg = "Do you really want to leave this page?"

            // For IE and Firefox
            if (e) {
                e.returnValue = msg;
            }

            // For Safari / chrome
            return msg;
         };

What is the point of "Initial Catalog" in a SQL Server connection string?

Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.

How to refresh page on back button click?

did you try something like this? not tested...

$(document).ready(function(){
    $('.ajaxAnchor').on('click', function (event){ 
        event.preventDefault(); 
        var url = $(this).attr('href');
        $.get(url, function(data) {
            $('section.center').html(data);
            var shortened = url.substring(0,url.length - 5);
            window.location.hash = shortened;
        });
    });
});

Android: remove left margin from actionbar's custom layout

Just add app:contentInsetStart="0dp" to the XML attribute of the toolbar.

How to fix Warning Illegal string offset in PHP

Magic word is: isset

Validate the entry:

if(isset($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

Merging two images in C#/.NET

This will add an image to another.

using (Graphics grfx = Graphics.FromImage(image))
{
    grfx.DrawImage(newImage, x, y)
}

Graphics is in the namespace System.Drawing

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

In Windows, I only managed to be able to delete the lock file after Ending Task for all Git Windows (32bit) processes in the Task Manager.

Solution (Win 10)

1. End Task for all Git Windows (32bit) processes in the Task Manager

2. Delete the .git/index.lock file

Django - filtering on foreign key properties

student_user = User.objects.get(id=user_id)
available_subjects = Subject.objects.exclude(subject_grade__student__user=student_user) # My ans
enrolled_subjects = SubjectGrade.objects.filter(student__user=student_user)
context.update({'available_subjects': available_subjects, 'student_user': student_user, 
                'request':request, 'enrolled_subjects': enrolled_subjects})

In my application above, i assume that once a student is enrolled, a subject SubjectGrade instance will be created that contains the subject enrolled and the student himself/herself.

Subject and Student User model is a Foreign Key to the SubjectGrade Model.

In "available_subjects", i excluded all the subjects that are already enrolled by the current student_user by checking all subjectgrade instance that has "student" attribute as the current student_user

PS. Apologies in Advance if you can't still understand because of my explanation. This is the best explanation i Can Provide. Thank you so much

Why is there still a row limit in Microsoft Excel?

Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?

14 bits = 16 384, 20 bits = 1 048 576

14 + 20 = 34 bits = more than one 32 bit register can hold.

But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.

Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.

Update 2016:

Found a link to Microsoft's specification for Excel 2013 & 2016

  • Open workbooks: Limited by available memory and system resources
  • Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
  • Column width: 255 characters (8 bits)
  • Row height: 409 points
  • Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
  • Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
  • Characters in a header or footer: 255 (8 bits)
  • Sheets in a workbook: Limited by available memory (default is 1 sheet)
  • Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
  • Named views in a workbook: Limited by available memory
  • Unique cell formats/cell styles: 64,000 (16 bits = 65536)
  • Fill styles: 256 (8 bits)
  • Line weight and styles: 256 (8 bits)
  • Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
  • Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
  • Names in a workbook: Limited by available memory
  • Windows in a workbook: Limited by available memory
  • Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
  • Panes in a window: 4
  • Linked sheets: Limited by available memory
  • Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
  • Changing cells in a scenario: 32
  • Adjustable cells in Solver: 200
  • Custom functions: Limited by available memory
  • Zoom range: 10 percent to 400 percent
  • Reports: Limited by available memory
  • Sort references: 64 in a single sort; unlimited when using sequential sorts
  • Undo levels: 100
  • Fields in a data form: 32
  • Workbook parameters: 255 parameters per workbook
  • Items displayed in filter drop-down lists: 10,000

Java "?" Operator for checking null - What is it? (Not Ternary!)

You can test the code which you have provided and it will give syntax error.So, it is not supported in Java. Groovy does support it and it was proposed for Java 7 (but never got included).

However, you can use the Optional provided in Java 8. This might help you in achieving something on similar line. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html

Example Code for Optional

TOMCAT - HTTP Status 404

To get your program to run, please put jsp files under web-content and not under WEB-INF because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:

http://localhost:8080/YourProject/yourfile.jsp

then your problem will be solved.

curl: (60) SSL certificate problem: unable to get local issuer certificate

This is ssh certificate store issue. You need to download the valid certificate pem file from target CA website, and then build the soft link file to instruct ssl the trusted certifacate.

openssl x509 -hash -noout -in DigiCert_Global_Root_G3.pem

you will get dd8e9d41

build solf link with hash number and suffix the file with a .0 (dot-zero)

dd8e9d41.0

Then try again.

How to get root directory in yii2

Open file D:\wamp\www\yiistore2\common\config\params-local.php

Paste below code before return

Yii::setAlias('@anyname', realpath(dirname(__FILE__).'/../../'));

After inserting above code in params-local.php file your file should look like this.

Yii::setAlias('@anyname', realpath(dirname(__FILE__).'/../../'));

return [
];

Now to get path of your root (in my case its D:\wamp\www\yiistore2) directory you can use below code in any php file.

echo Yii::getAlias('@anyname');

Difference between parameter and argument

Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).

double sqrt(double x)
{
    ...
    return x;
}

void other(void)
{
     double two = sqrt(2.0);
}

Under my thesis, x is the parameter to sqrt() and 2.0 is the argument.

The terms are often used at least somewhat interchangeably.

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

The easiest way to get rid of the the ugly frame in newer versions of matplotlib:

import matplotlib.pyplot as plt
plt.box(False)

If you really must always use the object oriented approach, then do: ax.set_frame_on(False).

Writing unit tests in Python: How do I start?

As others already replied, it's late to write unit tests, but not too late. The question is whether your code is testable or not. Indeed, it's not easy to put existing code under test, there is even a book about this: Working Effectively with Legacy Code (see key points or precursor PDF).

Now writing the unit tests or not is your call. You just need to be aware that it could be a tedious task. You might tackle this to learn unit-testing or consider writing acceptance (end-to-end) tests first, and start writing unit tests when you'll change the code or add new feature to the project.

How to prevent a background process from being stopped after closing SSH client in Linux

daemonize? nohup? SCREEN? (tmux ftw, screen is junk ;-)

Just do what every other app has done since the beginning -- double fork.

# ((exec sleep 30)&)
# grep PPid /proc/`pgrep sleep`/status
PPid:   1
# jobs
# disown
bash: disown: current: no such job

Bang! Done :-) I've used this countless times on all types of apps and many old machines. You can combine with redirects and whatnot to open a private channel between you and the process.

Create as coproc.sh:

#!/bin/bash

IFS=

run_in_coproc () {
    echo "coproc[$1] -> main"
    read -r; echo $REPLY
}

# dynamic-coprocess-generator. nice.
_coproc () {
    local i o e n=${1//[^A-Za-z0-9_]}; shift
    exec {i}<> <(:) {o}<> >(:) {e}<> >(:)
. /dev/stdin <<COPROC "${@}"
    (("\$@")&) <&$i >&$o 2>&$e
    $n=( $o $i $e )
COPROC
}

# pi-rads-of-awesome?
for x in {0..5}; do
    _coproc COPROC$x run_in_coproc $x
    declare -p COPROC$x
done

for x in COPROC{0..5}; do
. /dev/stdin <<RUN
    read -r -u \${$x[0]}; echo \$REPLY
    echo "$x <- main" >&\${$x[1]}
    read -r -u \${$x[0]}; echo \$REPLY
RUN
done

and then

# ./coproc.sh 
declare -a COPROC0='([0]="21" [1]="16" [2]="23")'
declare -a COPROC1='([0]="24" [1]="19" [2]="26")'
declare -a COPROC2='([0]="27" [1]="22" [2]="29")'
declare -a COPROC3='([0]="30" [1]="25" [2]="32")'
declare -a COPROC4='([0]="33" [1]="28" [2]="35")'
declare -a COPROC5='([0]="36" [1]="31" [2]="38")'
coproc[0] -> main
COPROC0 <- main
coproc[1] -> main
COPROC1 <- main
coproc[2] -> main
COPROC2 <- main
coproc[3] -> main
COPROC3 <- main
coproc[4] -> main
COPROC4 <- main
coproc[5] -> main
COPROC5 <- main

And there you go, spawn whatever. the <(:) opens an anonymous pipe via process substitution, which dies, but the pipe sticks around because you have a handle to it. I usually do a sleep 1 instead of : because its slightly racy, and I'd get a "file busy" error -- never happens if a real command is ran (eg, command true)

"heredoc sourcing":

. /dev/stdin <<EOF
[...]
EOF

This works on every single shell I've ever tried, including busybox/etc (initramfs). I've never seen it done before, I independently discovered it while prodding, who knew source could accept args? But it often serves as a much more manageable form of eval, if there is such a thing.

How to create an Observable from static data similar to http one in Angular?

Perhaps you could try to use the of method of the Observable class:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return Observable.of(new TestModel()).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}

How to find whether or not a variable is empty in Bash?

In Bash at least the following command tests if $var is empty:

if [[ -z "$var" ]]; then
   # Do what you want
fi

The command man test is your friend.

php timeout - set_time_limit(0); - don't work

I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).

I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.

I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.

Hope this helps!

What are the rules for casting pointers in C?

Casting pointers is usually invalid in C. There are several reasons:

  1. Alignment. It's possible that, due to alignment considerations, the destination pointer type is not able to represent the value of the source pointer type. For example, if int * were inherently 4-byte aligned, casting char * to int * would lose the lower bits.

  2. Aliasing. In general it's forbidden to access an object except via an lvalue of the correct type for the object. There are some exceptions, but unless you understand them very well you don't want to do it. Note that aliasing is only a problem if you actually dereference the pointer (apply the * or -> operators to it, or pass it to a function that will dereference it).

The main notable cases where casting pointers is okay are:

  1. When the destination pointer type points to character type. Pointers to character types are guaranteed to be able to represent any pointer to any type, and successfully round-trip it back to the original type if desired. Pointer to void (void *) is exactly the same as a pointer to a character type except that you're not allowed to dereference it or do arithmetic on it, and it automatically converts to and from other pointer types without needing a cast, so pointers to void are usually preferable over pointers to character types for this purpose.

  2. When the destination pointer type is a pointer to structure type whose members exactly match the initial members of the originally-pointed-to structure type. This is useful for various object-oriented programming techniques in C.

Some other obscure cases are technically okay in terms of the language requirements, but problematic and best avoided.

How to enter in a Docker container already running with a new TTY

With docker 1.3, there is a new command docker exec. This allows you to enter a running container:

docker exec -it [container-id] bash

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

You may need to change the Appication Pool setting "Enable 32bit Applications" to TRUE in IIS7 if you have at least 1 32bit dll\exe in your project.

SQL Server: UPDATE a table by using ORDER BY

The row_number() function would be the best approach to this problem.

UPDATE T
    SET T.Number = R.rowNum
    FROM Test T
    JOIN (
        SELECT T2.id,row_number() over (order by T2.Id desc) rowNum from Test T2
    ) R on T.id=R.id