Programs & Examples On #Loginview

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I could resolve it by overriding Configuration in MyContext through adding connection string to the DbContextOptionsBuilder:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json")
               .Build();
            var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
            optionsBuilder.UseSqlServer(connectionString);
        }
    }

Programmatically navigate to another view controller/scene

If you are building UI without drag and drop (without using storyboard) and want to navigate default page or ViewController.swift to another page? Follow these steps 1) add a class (.swift) 2) Import UIKit 3) Declare class name like

class DemoNavigationClass :UIViewController{
     override func viewDidLoad(){
         let lbl_Hello = UILabel(frame: CGRect(x:self.view.frame.width/3, y:self.view.frame.height/2, 200, 30));
lbl_Hello.text = "You are on Next Page"
lbl_Hello.textColor = UIColor.white
self.view.addSubview(lbl_Hello)
    }
}

after creating second page come back to first page (ViewController.swift) Here make a button in viewDidLoad method

let button = UIButton()
button.frame = (frame: CGRect(x: self.view.frame.width/3, y: self.view.frame.height/1.5,   width: 200, height: 50))
 button.backgroundColor = UIColor.red
 button.setTitle("Go to Next ", for: .normal)
 button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
 self.view.addSubview(button)

now define buttonAction method outside of viewDidLoad() in same class

func buttonAction(sender: UIButton!) 
{
    let obj : DemoNavigationClass = DemoNavigationClass();
    self.navigationController?.pushViewController(obj, animated: true)
}

Keep one thing that i forget in main.storyboard there is a scene with a arrow, select that arrow and press delete button

now drag and drop a navigationcontroller and delete tableview which comes with navaigation controller. select navigationcontroller press control on keyboard and drag it in to another scene on storyboard that is ViewController. This mean that your viewcontroller become root viewcontroller hope this help you Thanks in main.storyboard , drag and drop navigationcontroller,

What is the Swift equivalent of isEqualToString in Objective-C?

Actually, it feels like swift is trying to promote strings to be treated less like objects and more like values. However this doesn't mean under the hood swift doesn't treat strings as objects, as am sure you all noticed that you can still invoke methods on strings and use their properties.

For example:-

//example of calling method (String to Int conversion)
let intValue = ("12".toInt())
println("This is a intValue now \(intValue)")


//example of using properties (fetching uppercase value of string)
let caUpperValue = "ca".uppercaseString
println("This is the uppercase of ca \(caUpperValue)")

In objectC you could pass the reference to a string object through a variable, on top of calling methods on it, which pretty much establishes the fact that strings are pure objects.

Here is the catch when you try to look at String as objects, in swift you cannot pass a string object by reference through a variable. Swift will always pass a brand new copy of the string. Hence, strings are more commonly known as value types in swift. In fact, two string literals will not be identical (===). They are treated as two different copies.

let curious = ("ca" === "ca")
println("This will be false.. and the answer is..\(curious)")

As you can see we are starting to break aways from the conventional way of thinking of strings as objects and treating them more like values. Hence .isEqualToString which was treated as an identity operator for string objects is no more a valid as you can never get two identical string objects in Swift. You can only compare its value, or in other words check for equality(==).

 let NotSoCuriousAnyMore = ("ca" == "ca")
 println("This will be true.. and the answer is..\(NotSoCuriousAnyMore)")

This gets more interesting when you look at the mutability of string objects in swift. But thats for another question, another day. Something you should probably look into, cause its really interesting. :) Hope that clears up some confusion. Cheers!

MVC 5 Access Claims Identity User Data

To further touch on Darin's answer, you can get to your specific claims by using the FindFirst method:

var identity = (ClaimsIdentity)User.Identity;
var role = identity.FindFirst(ClaimTypes.Role).Value;

Multiple models in a view

Another way is to use:

@model Tuple<LoginViewModel,RegisterViewModel>

I have explained how to use this method both in the view and controller for another example: Two models in one view in ASP MVC 3

In your case you could implement it using the following code:

In the view:

@using YourProjectNamespace.Models;
@model Tuple<LoginViewModel,RegisterViewModel>

@using (Html.BeginForm("Login1", "Auth", FormMethod.Post))
{
        @Html.TextBoxFor(tuple => tuple.Item2.Name, new {@Name="Name"})
        @Html.TextBoxFor(tuple => tuple.Item2.Email, new {@Name="Email"})
        @Html.PasswordFor(tuple => tuple.Item2.Password, new {@Name="Password"})
}

@using (Html.BeginForm("Login2", "Auth", FormMethod.Post))
{
        @Html.TextBoxFor(tuple => tuple.Item1.Email, new {@Name="Email"})
        @Html.PasswordFor(tuple => tuple.Item1.Password, new {@Name="Password"})
}

Note that I have manually changed the Name attributes for each property when building the form. This needs to be done, otherwise it wouldn't get properly mapped to the method's parameter of type model when values are sent to the associated method for processing. I would suggest using separate methods to process these forms separately, for this example I used Login1 and Login2 methods. Login1 method requires to have a parameter of type RegisterViewModel and Login2 requires a parameter of type LoginViewModel.

if an actionlink is required you can use:

@Html.ActionLink("Edit", "Edit", new { id=Model.Item1.Id })

in the controller's method for the view, a variable of type Tuple needs to be created and then passed to the view.

Example:

public ActionResult Details()
{
    var tuple = new Tuple<LoginViewModel, RegisterViewModel>(new LoginViewModel(),new RegisterViewModel());
    return View(tuple);
}

or you can fill the two instances of LoginViewModel and RegisterViewModel with values and then pass it to the view.

How to bind to a PasswordBox in MVVM

My 2 cents:

I developed once a typical login dialog (user and password boxes, plus "Ok" button) using WPF and MVVM. I solved the password binding issue by simply passing the PasswordBox control itself as a parameter to the command attached to the "Ok" button. So in the view I had:

<PasswordBox Name="txtPassword" VerticalAlignment="Top" Width="120" />
<Button Content="Ok" Command="{Binding Path=OkCommand}"
   CommandParameter="{Binding ElementName=txtPassword}"/>

And in the ViewModel, the Execute method of the attached command was as follows:

void Execute(object parameter)
{
    var passwordBox = parameter as PasswordBox;
    var password = passwordBox.Password;
    //Now go ahead and check the user name and password
}

This slightly violates the MVVM pattern since now the ViewModel knows something about how the View is implemented, but in that particular project I could afford it. Hope it is useful for someone as well.

"Exception has been thrown by the target of an invocation" error (mscorlib)

' Get the your application's application domain.
Dim currentDomain As AppDomain = AppDomain.CurrentDomain 

' Define a handler for unhandled exceptions.
AddHandler currentDomain.UnhandledException, AddressOf MYExHandler 

' Define a handler for unhandled exceptions for threads behind forms.
AddHandler Application.ThreadException, AddressOf MYThreadHandler 

Private Sub MYExnHandler(ByVal sender As Object, _
ByVal e As UnhandledExceptionEventArgs) 
Dim EX As Exception 
EX = e.ExceptionObject 
Console.WriteLine(EX.StackTrace) 
End Sub 

Private Sub MYThreadHandler(ByVal sender As Object, _
ByVal e As Threading.ThreadExceptionEventArgs) 
Console.WriteLine(e.Exception.StackTrace) 
End Sub

' This code will throw an exception and will be caught.  
Dim X as Integer = 5
X = X / 0 'throws exception will be caught by subs below

How to properly apply a lambda function into a pandas data frame column

You need to add else in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.

sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x) 

Difference between window.location.href, window.location.replace and window.location.assign

These do the same thing:

window.location.assign(url);
window.location = url;
window.location.href = url;

They simply navigate to the new URL. The replace method on the other hand navigates to the URL without adding a new record to the history.

So, what you have read in those many forums is not correct. The assign method does add a new record to the history.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

ORA-01008: not all variables bound. They are bound

Came here looking for help as got same error running a statement listed below while going through a Udemy course:

INSERT INTO departments (department_id, department_name)
                  values( &dpet_id, '&dname');  

I'd been able to run statements with substitution variables before. Comment by Charles Burns about possibility of server reaching some threshold while recreating the variables prompted me to log out and restart the SQL Developer. The statement ran fine after logging back in.

Thought I'd share for anyone else venturing here with a limited scope issue as mine.

How to create .pfx file from certificate and private key?

Although it is probably easiest to generate a new CSR using IIS (like @rainabba said), assuming you have the intermediate certificates there are some online converters out there - for instance: https://www.sslshopper.com/ssl-converter.html

This will allow you to create a PFX from your certificate and private key without having to install another program.

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

How to check a string for specific characters?

s=input("Enter any character:")   
if s.isalnum():   
   print("Alpha Numeric Character")   
   if s.isalpha():   
       print("Alphabet character")   
       if s.islower():   
         print("Lower case alphabet character")   
       else:   
         print("Upper case alphabet character")   
   else:   
     print("it is a digit")   
elif s.isspace():   
    print("It is space character")   

else:
print("Non Space Special Character")

Redis: How to access Redis log file

You can also login to the redis-cli and use the MONITOR command to see what queries are happening against Redis.

SQL Statement with multiple SETs and WHEREs

Use a query terminator string and set this in the options of your SQL client application. I use ; as the query terminator.

Your SQL would look like this;

UPDATE table SET ID = 111111259 WHERE ID = 2555;
UPDATE table SET ID = 111111261 WHERE ID = 2724;
UPDATE table SET ID = 111111263 WHERE ID = 2021;
UPDATE table SET ID = 111111264 WHERE ID = 2017;

This will allow you to do a Ctrl + A and run all the lines at once.

The string terminator tells the SQL client that the update statement is finished and to go to the next line and process the next statement.

Hope that helps

Converting json results to a date

I use this:

function parseJsonDate(jsonDateString){
    return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}

Update 2018:

This is an old question. Instead of still using this old non standard serialization format I would recommend to modify the server code to return better format for date. Either an ISO string containing time zone information, or only the milliseconds. If you use only the milliseconds for transport it should be UTC on server and client.

  • 2018-07-31T11:56:48Z - ISO string can be parsed using new Date("2018-07-31T11:56:48Z") and obtained from a Date object using dateObject.toISOString()
  • 1533038208000 - milliseconds since midnight January 1, 1970, UTC - can be parsed using new Date(1533038208000) and obtained from a Date object using dateObject.getTime()

Trim Cells using VBA in Excel

If you have a non-printing character at the front of the string try this


Option Explicit
Sub DoTrim()
    Dim cell As Range
    Dim str As String
    Dim nAscii As Integer
    For Each cell In Selection.Cells
        If cell.HasFormula = False Then
            str = Trim(CStr(cell))
            If Len(str) > 0 Then
                nAscii = Asc(Left(str, 1))
                If nAscii < 33 Or nAscii = 160 Then
                    If Len(str) > 1 Then
                        str = Right(str, Len(str) - 1)
                    Else
                        strl = ""
                    End If
                End If
            End If
            cell=str
        End If
    Next
End Sub

How to send email to multiple address using System.Net.Mail

namespace WebForms.Code.Logging {

    public class ObserverLogToEmail: ILog {
        private string from;
        private string to;
        private string subject;
        private string body;
        private SmtpClient smtpClient;
        private MailMessage mailMessage;
        private MailPriority mailPriority;
        private MailAddressCollection mailAddressCollection;
        private MailAddress fromMailAddress, toMailAddress;
        public MailAddressCollection toMailAddressCollection {
            get;
            set;
        }
        public MailAddressCollection ccMailAddressCollection {
            get;
            set;
        }
        public MailAddressCollection bccMailAddressCollection {
            get;
            set;
        }

        public ObserverLogToEmail(string from, string to, string subject, string body, SmtpClient smtpClient) {
            this.from = from;
            this.to = to;
            this.subject = subject;
            this.body = body;

            this.smtpClient = smtpClient;
        }

        public ObserverLogToEmail(MailAddress fromMailAddress, MailAddress toMailAddress,
        string subject, string content, SmtpClient smtpClient) {
            try {
                this.fromMailAddress = fromMailAddress;
                this.toMailAddress = toMailAddress;
                this.subject = subject;
                this.body = content;

                this.smtpClient = smtpClient;

                mailAddressCollection = new MailAddressCollection();

            } catch {
                throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
            }
        }

        public ObserverLogToEmail(MailAddressCollection fromMailAddressCollection,
        MailAddressCollection toMailAddressCollection,
        string subject, string content, SmtpClient smtpClient) {
            try {
                this.toMailAddressCollection = toMailAddressCollection;
                this.ccMailAddressCollection = ccMailAddressCollection;
                this.subject = subject;
                this.body = content;

                this.smtpClient = smtpClient;

            } catch {
                throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
            }
        }

        public ObserverLogToEmail(MailAddressCollection toMailAddressCollection,
        MailAddressCollection ccMailAddressCollection,
        MailAddressCollection bccMailAddressCollection,
        string subject, string content, SmtpClient smtpClient) {
            try {
                this.toMailAddressCollection = toMailAddressCollection;
                this.ccMailAddressCollection = ccMailAddressCollection;
                this.bccMailAddressCollection = bccMailAddressCollection;

                this.subject = subject;
                this.body = content;

                this.smtpClient = smtpClient;

            } catch {
                throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
            }
        }#region ILog Members

        // sends a log request via email.
        // actual email 'Send' calls are commented out.
        // uncomment if you have the proper email privileges.
        public void Log(object sender, LogEventArgs e) {
            string message = "[" + e.Date.ToString() + "] " + e.SeverityString + ": " + e.Message;
            fromMailAddress = new MailAddress("", "HaNN", System.Text.Encoding.UTF8);
            toMailAddress = new MailAddress("", "XXX", System.Text.Encoding.UTF8);

            mailMessage = new MailMessage(fromMailAddress, toMailAddress);
            mailMessage.Subject = subject;
            mailMessage.Body = body;

            // commented out for now. you need privileges to send email.
            // _smtpClient.Send(from, to, subject, body);
            smtpClient.Send(mailMessage);
        }

        public void LogAllEmails(object sender, LogEventArgs e) {
            try {
                string message = "[" + e.Date.ToString() + "] " + e.SeverityString + ": " + e.Message;

                mailMessage = new MailMessage();
                mailMessage.Subject = subject;
                mailMessage.Body = body;

                foreach(MailAddress toMailAddress in toMailAddressCollection) {
                    mailMessage.To.Add(toMailAddress);

                }
                foreach(MailAddress ccMailAddress in ccMailAddressCollection) {
                    mailMessage.CC.Add(ccMailAddress);
                }
                foreach(MailAddress bccMailAddress in bccMailAddressCollection) {
                    mailMessage.Bcc.Add(bccMailAddress);
                }
                if (smtpClient == null) {
                    var smtp = new SmtpClient {
                        Host = "smtp.gmail.com",
                        Port = 587,
                        EnableSsl = true,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Credentials = new NetworkCredential("yourEmailAddress", "yourPassword"),
                        Timeout = 30000
                    };
                } else smtpClient.SendAsync(mailMessage, null);
            } catch (Exception) {

                throw;
            }
        }
    }

why should I make a copy of a data frame in pandas

Assumed you have data frame as below

df1
     A    B    C    D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0

When you would like create another df2 which is identical to df1, without copy

df2=df1
df2
     A    B    C    D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0

And would like modify the df2 value only as below

df2.iloc[0,0]='changed'

df2
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

At the same time the df1 is changed as well

df1
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

Since two df as same object, we can check it by using the id

id(df1)
140367679979600
id(df2)
140367679979600

So they as same object and one change another one will pass the same value as well.


If we add the copy, and now df1 and df2 are considered as different object, if we do the same change to one of them the other will not change.

df2=df1.copy()
id(df1)
140367679979600
id(df2)
140367674641232

df1.iloc[0,0]='changedback'
df2
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

Good to mention, when you subset the original dataframe, it is safe to add the copy as well in order to avoid the SettingWithCopyWarning

What is the difference between an interface and abstract class?

Interfaces are generally the classes without logic just a signature. Whereas abstract classes are those having logic. Both support contract as interface all method should be implemented in the child class but in abstract only the abstract method should be implemented. When to use interface and when to abstract? Why use Interface?

class Circle {

protected $radius;

public function __construct($radius)

{
    $this->radius = $radius
}

public function area()
{
    return 3.14159 * pow(2,$this->radius); // simply pie.r2 (square);
}

}

//Our area calculator class would look like

class Areacalculator {

$protected $circle;

public function __construct(Circle $circle)
{
    $this->circle = $circle;
}

public function areaCalculate()
{
    return $circle->area(); //returns the circle area now
}

}

We would simply do

$areacalculator = new Areacalculator(new Circle(7)); 

Few days later we would need the area of rectangle, Square, Quadrilateral and so on. If so do we have to change the code every time and check if the instance is of square or circle or rectangle? Now what OCP says is CODE TO AN INTERFACE NOT AN IMPLEMENTATION. Solution would be:

Interface Shape {

public function area(); //Defining contract for the classes

}

Class Square implements Shape {

$protected length;

public function __construct($length) {
    //settter for length like we did on circle class
}

public function area()
{
    //return l square for area of square
}

Class Rectangle implements Shape {

$protected length;
$protected breath;

public function __construct($length,$breath) {
    //settter for length, breath like we did on circle,square class
}

public function area()
{
    //return l*b for area of rectangle
}

}

Now for area calculator

class Areacalculator {

$protected $shape;

public function __construct(Shape $shape)
{
    $this->shape = $shape;
}

public function areaCalculate()
{
    return $shape->area(); //returns the circle area now
}

}

$areacalculator = new Areacalculator(new Square(1));
$areacalculator->areaCalculate();

$areacalculator = new Areacalculator(new Rectangle(1,2));
$areacalculator->;areaCalculate();

Isn't that more flexible? If we would code without interface we would check the instance for each shape redundant code.

Now when to use abstract?

Abstract Animal {

public function breathe(){

//all animals breathe inhaling o2 and exhaling co2

}

public function hungry() {

//every animals do feel hungry 

}

abstract function communicate(); 
// different communication style some bark, some meow, human talks etc

}

Now abstract should be used when one doesn't need instance of that class, having similar logic, having need for the contract.

How to export a Hive table into a CSV file?

In case you are doing it from Windows you can use Python script hivehoney to extract table data to local CSV file.

It will:

  • Login to bastion host.
  • pbrun.
  • kinit.
  • beeline (with your query).
  • Save echo from beeline to a file on Windows.

Execute it like this:

set PROXY_HOST=your_bastion_host

set SERVICE_USER=you_func_user

set LINUX_USER=your_SOID

set LINUX_PWD=your_pwd

python hh.py --query_file=query.sql

How to set text color to a text view programmatically

Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:

textView.setTextColor(getResources().getColor(R.color.some_color));

Please note that from API 23, getResources().getColor() is deprecated. Use instead:

textView.setTextColor(ContextCompat.getColor(context, R.color.some_color));

where the required color is defined in an xml as:

<resources>
  <color name="some_color">#bdbdbd</color>
</resources>

Update:

This method was deprecated in API level 23. Use getColor(int, Theme) instead.

Check this.

MySQL limit from descending order

No, you shouldn't do this. Without an ORDER BY clause you shouldn't rely on the order of the results being the same from query to query. It might work nicely during testing but the order is indeterminate and could break later. Use an order by.

SELECT * FROM table1 ORDER BY id LIMIT 5

By the way, another way of getting the last 3 rows is to reverse the order and select the first three rows:

SELECT * FROM table1 ORDER BY id DESC LIMIT 3

This will always work even if the number of rows in the result set isn't always 8.

MySQL 'create schema' and 'create database' - Is there any difference

Database is a collection of schemas and schema is a collection of tables. But in MySQL they use it the same way.

Laravel: Auth::user()->id trying to get a property of a non-object

In Laravel 8.6, the following works for me in a controller:

$id = auth()->user()->id;

Why is there no Constant feature in Java?

There is a way to create "const" variables in Java, but only for specific classes. Just define a class with final properties and subclass it. Then use the base class where you would want to use "const". Likewise, if you need to use "const" methods, add them to the base class. The compiler will not allow you to modify what it thinks is the final methods of the base class, but it will read and call methods on the subclass.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

To get past INSTALL_FAILED_MISSING_SHARED_LIBRARY error with Google Maps for Android:

  1. Install Google map APIs. This can be done in Eclipse Windows/Android SDK and AVD Manager -> Available Packages -> Third Party Add-ons -> Google Inc. -> Google APIs by Google Inc., Android API X

  2. From command line create new AVD. This can be done by listing targets (android list targets), then android create avd -n new_avd_api_233 -t "Google Inc.:Google APIs:X"

  3. Then create AVD (Android Virtual Device) in Eclipse Windows/Android SDK and AVD Manager -> New... -> (Name: new_avd_X, Target: Google APIs (Google Inc.) - API Level X)

    IMPORTANT : You must create your AVD with Target as Google APIs (Google Inc.) otherwise it will again failed.

  4. Create Android Project in Eclipse File/New/Android Project and select Google APIs Build Target.

  5. add <uses-library android:name="com.google.android.maps" /> between <application> </application> tags.

  6. Run Project as Android Application.

If error persists, then you still have problems, if it works, then this error is forever behind you.

What are the specific differences between .msi and setup.exe file?

An MSI is a Windows Installer database. Windows Installer (a service installed with Windows) uses this to install software on your system (i.e. copy files, set registry values, etc...).

A setup.exe may either be a bootstrapper or a non-msi installer. A non-msi installer will extract the installation resources from itself and manage their installation directly. A bootstrapper will contain an MSI instead of individual files. In this case, the setup.exe will call Windows Installer to install the MSI.

Some reasons you might want to use a setup.exe:

  • Windows Installer only allows one MSI to be installing at a time. This means that it is difficult to have an MSI install other MSIs (e.g. dependencies like the .NET framework or C++ runtime). Since a setup.exe is not an MSI, it can be used to install several MSIs in sequence.
  • You might want more precise control over how the installation is managed. An MSI has very specific rules about how it manages the installations, including installing, upgrading, and uninstalling. A setup.exe gives complete control over the software configuration process. This should only be done if you really need the extra control since it is a lot of work, and it can be tricky to get it right.

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

The view-source url prefix trick didn't work for me using chrome on an iphone. There are apps I could have installed to do this I guess but for whatever reason I just preferred to do it myself rather than install 'yet another app'.

I found this nice quick tutorial for how to setup a bookmark on mobile safari that will automatically open the view source of a page: https://appletoolbox.com/2014/03/how-to-view-webpage-html-source-codes-on-ipad-iphone-no-app-required/

It worked flawlessly for me and now I have it set as a permanent bookmark any time I want, with no app installed.

Edit: There are basically 6 steps which should work for either Chrome or Safari. Instructions for Safari are:

  1. Open Safari and browse to an arbitrary page.
  2. Select the "Share" (or action") button in Safari (looks like a square with an arrow coming out of the top).
  3. Select "Add Bookmark"
  4. Delete the page title and replace it with something useful like "Show Page Source". Click Save.
  5. Next browse to this exact Stack Overflow answer on your phone and copy the javascript code below to your phone clipboard (code credit: Rob Flaherty):
javascript:(function(){var a=window.open('about:blank').document;a.write('<!DOCTYPE html><html><head><title>Source of '+location.href+'</title><meta name="viewport" content="width=device-width" /></head><body></body></html>');a.close();var b=a.body.appendChild(a.createElement('pre'));b.style.overflow='auto';b.style.whiteSpace='pre-wrap';b.appendChild(a.createTextNode(document.documentElement.innerHTML))})();
  1. Open the "Bookmarks" in Safari and opt to Edit the newly created Show Page Source bookmark. Delete whatever was previously saved in the Address field and instead paste in the Javascript code. Save it.
  2. (Optional) Profit!

logout and redirecting session in php

<?php //initialize the session if (!isset($_SESSION)) {   session_start(); } 
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
    $logoutAction .= "&". htmlentities($_SERVER['QUERY_STRING']); 
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")) {
    // to fully log out a visitor we need to clear the session variables
    $_SESSION['MM_Username'] = NULL;
    $_SESSION['MM_UserGroup'] = NULL;
    $_SESSION['PrevUrl'] = NULL;
    unset($_SESSION['MM_Username']);  
    unset($_SESSION['MM_UserGroup']);
    unset($_SESSION['PrevUrl']);
    $logoutGoTo = "index.php";

    if ($logoutGoTo) {
        header("Location: $logoutGoTo");
        exit;
    }
} ?>

String vs. StringBuilder

Further to the previous answers, the first thing I always do when thinking of issues like this is to create a small test application. Inside this app, perform some timing test for both scenarios and see for yourself which is quicker.

IMHO, appending 500+ string entries should definitely use StringBuilder.

How to position the Button exactly in CSS

So, the trick here is to use absolute positioning calc like this:

top: calc(50% - XYpx);
left: calc(50% - XYpx);

where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.

DISTINCT for only one column

This assumes SQL Server 2005+ and your definition of "last" is the max PK for a given email

WITH CTE AS
(
SELECT ID, 
       Email, 
       ProductName, 
       ProductModel, 
       ROW_NUMBER() OVER (PARTITION BY Email ORDER BY ID DESC) AS RowNumber 
FROM   Products
)
SELECT ID, 
       Email, 
       ProductName, 
       ProductModel
FROM CTE 
WHERE RowNumber = 1

How to determine the Boost version on a system?

If you only need to know for your own information, just look in /usr/include/boost/version.hpp (Ubuntu 13.10) and read the information directly

json and empty array

The first version is a null object while the second is an Array object with zero elements.

Null may mean here for example that no location is available for that user, no location has been requested or that some restrictions apply. Hard to tell with no reference to the API.

Can an abstract class have a constructor?

Yes, Abstract Classes can have constructors !

Here is an example using constructor in abstract class:

abstract class Figure { 

    double dim1;        
    double dim2; 

    Figure(double a, double b) {         
        dim1 = a;         
        dim2 = b;         
    }

    // area is now an abstract method 

   abstract double area(); 

}


class Rectangle extends Figure { 
    Rectangle(double a, double b) { 
        super(a, b); 
    } 
    // override area for rectangle 
    double area() { 
        System.out.println("Inside Area for Rectangle."); 
        return dim1 * dim2; 
    } 
}

class Triangle extends Figure { 
    Triangle(double a, double b) { 
        super(a, b); 
    } 
    // override area for right triangle 
    double area() { 
        System.out.println("Inside Area for Triangle."); 
        return dim1 * dim2 / 2; 
    } 
}

class AbstractAreas { 
    public static void main(String args[]) { 
        // Figure f = new Figure(10, 10); // illegal now 
        Rectangle r = new Rectangle(9, 5); 
        Triangle t = new Triangle(10, 8); 
        Figure figref; // this is OK, no object is created 
        figref = r; 
        System.out.println("Area is " + figref.area()); 
        figref = t; 
        System.out.println("Area is " + figref.area()); 
    } 
}

So I think you got the answer.

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

Init method in Spring Controller (annotation version)

There are several ways to intercept the initialization process in Spring. If you have to initialize all beans and autowire/inject them there are at least two ways that I know of that will ensure this. I have only testet the second one but I belive both work the same.

If you are using @Bean you can reference by initMethod, like this.

@Configuration
public class BeanConfiguration {

  @Bean(initMethod="init")
  public BeanA beanA() {
    return new BeanA();
  }
}

public class BeanA {

  // method to be initialized after context is ready
  public void init() {
  }

} 

If you are using @Component you can annotate with @EventListener like this.

@Component
public class BeanB {

  @EventListener
  public void onApplicationEvent(ContextRefreshedEvent event) {
  }
}

In my case I have a legacy system where I am now taking use of IoC/DI where Spring Boot is the choosen framework. The old system brings many circular dependencies to the table and I therefore must use setter-dependency a lot. That gave me some headaches since I could not trust @PostConstruct since autowiring/injection by setter was not yet done. The order is constructor, @PostConstruct then autowired setters. I solved it with @EventListener annotation which wil run last and at the "same" time for all beans. The example shows implementation of InitializingBean aswell.

I have two classes (@Component) with dependency to each other. The classes looks the same for the purpose of this example displaying only one of them.

@Component
public class BeanA implements InitializingBean {
  private BeanB beanB;

  public BeanA() {
    log.debug("Created...");
  }

  @PostConstruct
  private void postConstruct() {
    log.debug("@PostConstruct");
  }

  @Autowired
  public void setBeanB(BeanB beanB) {
    log.debug("@Autowired beanB");
    this.beanB = beanB;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    log.debug("afterPropertiesSet()");
  }

  @EventListener
  public void onApplicationEvent(ContextRefreshedEvent event) {
    log.debug("@EventListener");
  } 
}

This is the log output showing the order of the calls when the container starts.

2018-11-30 18:29:30.504 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : Created...
2018-11-30 18:29:30.509 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : Created...
2018-11-30 18:29:30.517 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @Autowired beanA
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : afterPropertiesSet()
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @Autowired beanB
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : afterPropertiesSet()
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @EventListener
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @EventListener

As you can see @EventListener is run last after everything is ready and configured.

Shortcut for creating single item list in C#

Yet another way, found on "C#/.Net Little wonders" (unfortunately, the site doesn't exist anymore):

Enumerable.Repeat("value",1).ToList()

Capturing URL parameters in request.GET

Using GET

request.GET["id"]

Using POST

request.POST["id"]

how to convert date to a format `mm/dd/yyyy`

Use:

select convert(nvarchar(10), CREATED_TS, 101)

or

select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above

How to print VARCHAR(MAX) using Print Statement?

The following workaround does not use the PRINT statement. It works well in combination with the SQL Server Management Studio.

SELECT CAST('<root><![CDATA[' + @MyLongString + ']]></root>' AS XML)

You can click on the returned XML to expand it in the built-in XML viewer.

There is a pretty generous client side limit on the displayed size. Go to Tools/Options/Query Results/SQL Server/Results to Grid/XML data to adjust it if needed.

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

The following method may work:

git rebase HEAD master
git checkout master

This will rebase your current HEAD changes on top of the master. Then you can switch the branch.


Alternative way is to checkout the branch first:

git checkout master

Then Git should display SHA1 of your detached commits, then you can cherry pick them, e.g.

git cherry-pick YOURSHA1

Or you can also merge the latest one:

git merge YOURSHA1

To see all of your commits from different branches (to make sure you've them), run: git reflog.

Git submodule push

A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )

$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"

System.Net.Http: missing from namespace? (using .net 4.5)

Making the "Copy Local" property True for the reference did it for me. Expand References, right-click on System.Net.Http and change the value of Copy Local property to True in the properties window. I'm using VS2019.

How to bind inverse boolean properties in WPF?

Have you considered an IsNotReadOnly property? If the object being bound is a ViewModel in a MVVM domain, then the additional property makes perfect sense. If it's a direct Entity model, you might consider composition and presenting a specialized ViewModel of your entity to the form.

Disable Drag and Drop on HTML elements?

This JQuery Worked for me :-

$(document).ready(function() {
  $('#con_image').on('mousedown', function(e) {
      e.preventDefault();
  });
});

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

Try this:

net use * /delete /y

The /y key makes it select Yes in prompt silently

Declaring multiple variables in JavaScript

I believe that before we started using ES6, an approach with a single var declaration was neither good nor bad (in case if you have linters and 'use strict'. It was really a taste preference. But now things changed for me. These are my thoughts in favour of multiline declaration:

  1. Now we have two new kinds of variables, and var became obsolete. It is good practice to use const everywhere until you really need let. So quite often your code will contain variable declarations with assignment in the middle of the code, and because of block scoping you quite often will move variables between blocks in case of small changes. I think that it is more convenient to do that with multiline declarations.

  2. ES6 syntax became more diverse, we got destructors, template strings, arrow functions and optional assignments. When you heavily use all those features with single variable declarations, it hurts readability.

How to automatically import data from uploaded CSV or XLS file into Google Sheets

(Mar 2017) The accepted answer is not the best solution. It relies on manual translation using Apps Script, and the code may not be resilient, requiring maintenance. If your legacy system autogenerates CSV files, it's best they go into another folder for temporary processing (importing [uploading to Google Drive & converting] to Google Sheets files).

My thought is to let the Drive API do all the heavy-lifting. The Google Drive API team released v3 at the end of 2015, and in that release, insert() changed names to create() so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!

The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C that imports CSV files into Google Sheets format as desired.

Below is one alternate Python solution for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload class. This snippet assumes your auth code works where your service endpoint is DRIVE with a minimum auth scope of https://www.googleapis.com/auth/drive.file.

# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'

# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
    print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))

Better yet, rather than uploading to My Drive, you'd upload to one (or more) specific folder(s), meaning you'd add the parent folder ID(s) to METADATA. (Also see the code sample on this page.) Finally, there's no native .gsheet "file" -- that file just has a link to the online Sheet, so what's above is what you want to do.

If not using Python, you can use the snippet above as pseudocode to port to your system language. Regardless, there's much less code to maintain because there's no CSV parsing. The only thing remaining is to blow away the CSV file temp folder your legacy system wrote to.

Numpy - add row to array

You can use numpy.append() to append a row to numpty array and reshape to a matrix later on.

import numpy as np
a = np.array([1,2])
a = np.append(a, [3,4])
print a
# [1,2,3,4]
# in your example
A = [1,2]
for row in X:
    A = np.append(A, row)

Find the min/max element of an array in JavaScript

You may not want to add methods to the Array prototype, which may conflict with other libraries.

I've seen a lot of examples use forEach which, I wouldn't recommend for large arrays due to its poor performance vs a for loop. https://coderwall.com/p/kvzbpa/don-t-use-array-foreach-use-for-instead

Also Math.max(Math, [1,2,3]); Always gives me NaN?

function minArray(a) {
  var min=a[0]; for(var i=0,j=a.length;i<j;i++){min=a[i]<min?a[i]:min;}
  return min;
}

function maxArray(a) {
  var max=a[0]; for(var i=0,j=a.length;i<j;i++){max=a[i]>max?a[i]:max;}
  return max;
}

minArray([1,2,3]); // returns 1

If you have an array of objects the minArray() function example below will accept 2 parameters, the first is the array and the second is the key name for the object key value to compare. The function in this case would return the index of the array that has the smallest given key value.

function minArray(a, key) {
  var min, i, j, index=0;
  if(!key) {
    min=a[0]; 
    for(i=0,j=a.length;i<j;i++){min=a[i]<min?a[i]:min;}
    return min;
  }
  min=a[0][key];
  for(i=0,j=a.length;i<j;i++){
    if(a[i][key]<min) {
      min = a[i][key];
      index = i;
    }
  }
    return index;
}

var a = [{fee: 9}, {fee: 2}, {fee: 5}];

minArray(a, "fee"); // returns 1, as 1 is the proper array index for the 2nd array element.

iOS 8 UITableView separator inset 0 not working

For me none has worked except this workaround (Swift 3.0):

extension UIColor {
    static func colorWith(hex:String, alpha: CGFloat) -> UIColor {
        var cString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if cString.hasPrefix("#") {
            cString.remove(at: cString.startIndex)
        }

        if cString.characters.count != 6 {
            return UIColor.gray
        }

        var rgbValue:UInt32 = 0
        Scanner(string: cString).scanHexInt32(&rgbValue)

        return UIColor(red:   CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
                       green: CGFloat((rgbValue & 0x00FF00) >> 8)  / 255.0,
                       blue:  CGFloat( rgbValue & 0x0000FF)        / 255.0,
                       alpha: alpha)
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdendifier, for: indexPath)

    cell.backgroundColor = UIColor.colorWith(hex: "c8c7cc", alpha: 1) // same color of line separator

    return cell
}

ORA-01843 not a valid month- Comparing Dates

If the source date contains minutes and seconds part, your date comparison will fail. you need to convert source date to the required format using to_char and the target date also.

How to prevent favicon.ico requests?

Just add the following line to the <head> section of your HTML file:

<link rel="icon" href="data:,">

Features of this solution:

  • 100% valid HTML5
  • very short
  • does not incur any quirks from IE 8 and older
  • does not make the browser interpret the current HTML code as favicon (which would be the case with href="#")

How to call VS Code Editor from terminal / command line

For command line heads you can also run

sudo ln -s "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code" /usr/local/bin/code

this will do the exact same thing as the Shell Command: Install 'code' command in PATH command feature in VSCode.

How to generate the "create table" sql statement for an existing table in postgreSQL

Here is another solution to the old question. There have been many excellent answers to this question over the years and my attempt borrows heavily from them.

I used Andrey Lebedenko's solution as a starting point because its output was already very close to my requirements.

Features:

  • following common practice I have moved the foreign key constraints outside the table definition. They are now included as ALTER TABLE statements at the bottom. The reason is that a foreign key can also link to a column of the same table. In that fringe case the constraint can only be created after the table creation is completed. The create table statement would throw an error otherwise.
  • The layout and indenting looks nicer now (at least to my eye)
  • Drop command (commented out) in the header of the definition
  • The solution is offered here as a plpgsql function. The algorithm does however not use any procedural language. The function just wraps one single query that can be used in a pure sql context as well.
  • removed redundant subqueries
  • Identifiers are now quoted if they are identical to reserved postgresql language elements
  • replaced the string concatenation operator || with the appropriate string functions to improve performance, security and readability of the code. Note: the || operator produces NULL if one of the combined strings is NULL. It should only be used when that is the desired behaviour. (check out the usage in the code below for an example)

CREATE OR REPLACE FUNCTION public.wmv_get_table_definition (
    p_schema_name character varying,
    p_table_name character varying
)
    RETURNS SETOF TEXT
    AS $BODY$
BEGIN
    RETURN query 
    WITH table_rec AS (
        SELECT
            c.relname, n.nspname, c.oid
        FROM
            pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
        WHERE
            relkind = 'r'
            AND n.nspname = p_schema_name
            AND c.relname LIKE p_table_name
        ORDER BY
            c.relname
    ),
    col_rec AS (
        SELECT
            a.attname AS colname,
            pg_catalog.format_type(a.atttypid, a.atttypmod) AS coltype,
            a.attrelid AS oid,
            ' DEFAULT ' || (
                SELECT
                    pg_catalog.pg_get_expr(d.adbin, d.adrelid)
                FROM
                    pg_catalog.pg_attrdef d
                WHERE
                    d.adrelid = a.attrelid
                    AND d.adnum = a.attnum
                    AND a.atthasdef) AS column_default_value,
            CASE WHEN a.attnotnull = TRUE THEN
                'NOT NULL'
            ELSE
                'NULL'
            END AS column_not_null,
            a.attnum AS attnum
        FROM
            pg_catalog.pg_attribute a
        WHERE
            a.attnum > 0
            AND NOT a.attisdropped
        ORDER BY
            a.attnum
    ),
    con_rec AS (
        SELECT
            conrelid::regclass::text AS relname,
            n.nspname,
            conname,
            pg_get_constraintdef(c.oid) AS condef,
            contype,
            conrelid AS oid
        FROM
            pg_constraint c
            JOIN pg_namespace n ON n.oid = c.connamespace
    ),
    glue AS (
        SELECT
            format( E'-- %1$I.%2$I definition\n\n-- Drop table\n\n-- DROP TABLE IF EXISTS %1$I.%2$I\n\nCREATE TABLE %1$I.%2$I (\n', table_rec.nspname, table_rec.relname) AS top,
            format( E'\n);\n\n\n-- adempiere.wmv_ghgaudit foreign keys\n\n', table_rec.nspname, table_rec.relname) AS bottom,
            oid
        FROM
            table_rec
    ),
    cols AS (
        SELECT
            string_agg(format('    %I %s%s %s', colname, coltype, column_default_value, column_not_null), E',\n') AS lines,
            oid
        FROM
            col_rec
        GROUP BY
            oid
    ),
    constrnt AS (
        SELECT
            string_agg(format('    CONSTRAINT %s %s', con_rec.conname, con_rec.condef), E',\n') AS lines,
            oid
        FROM
            con_rec
        WHERE
            contype <> 'f'
        GROUP BY
            oid
    ),
    frnkey AS (
        SELECT
            string_agg(format('ALTER TABLE %I.%I ADD CONSTRAINT %s %s', nspname, relname, conname, condef), E';\n') AS lines,
            oid
        FROM
            con_rec
        WHERE
            contype = 'f'
        GROUP BY
            oid
    )
    SELECT
        concat(glue.top, cols.lines, E',\n', constrnt.lines, glue.bottom, frnkey.lines, ';')
    FROM
        glue
        JOIN cols ON cols.oid = glue.oid
        LEFT JOIN constrnt ON constrnt.oid = glue.oid
        LEFT JOIN frnkey ON frnkey.oid = glue.oid;
END;
$BODY$
LANGUAGE plpgsql;

Bootstrap 3 breakpoints and media queries

The reference to 480px has been removed. Instead it says:

/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */

There isn't a breakpoint below 768px in Bootstrap 3.

If you want to use the @screen-sm-min and other mixins then you need to be compiling with LESS, see http://getbootstrap.com/css/#grid-less

Here's a tutorial on how to use Bootstrap 3 and LESS: http://www.helloerik.com/bootstrap-3-less-workflow-tutorial

Can one class extend two classes?

Another solution is to create a private inner class that extends the second class. e.g a class that extends JMenuItem and AbstractAction:

public class MyClass extends JMenuItem {


    private class MyAction extends AbstractAction {
        // This class can access everything from its parent...
    }

}

Utils to read resource text file to String (Java)

If you want to get your String from a project resource like the file testcase/foo.json in src/main/resources in your project, do this:

String myString= 
 new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("testcase/foo.json").toURI())));

Note that the getClassLoader() method is missing on some of the other examples.

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

If you open /Users/{your name}/android sdks/tools/android (double click it), then click on "Android SDK Manager" menu and then "Preferences" and then you can change your proxy settings specifically for Android SDK Manager. These proxy settings also apply to "Android SDK Manager" if used within Eclipse.

How do I pass multiple parameter in URL?

I do not know much about Java but URL query arguments should be separated by "&", not "?"

http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.

Why would $_FILES be empty when uploading files to PHP?

Thank you everybody for the vary comprehensive replies. Those are all very helpful. The answer turned out to be something very odd. It turns out that PHP 5.2.11 doesn't like the following:

post_max_size = 2G

or

post_max_size = 2048M

If I change it to 2047M, the upload works.

How to recover MySQL database from .myd, .myi, .frm files

If these are MyISAM tables, then plopping the .FRM, .MYD, and .MYI files into a database directory (e.g., /var/lib/mysql/dbname) will make that table available. It doesn't have to be the same database as they came from, the same server, the same MySQL version, or the same architecture. You may also need to change ownership for the folder (e.g., chown -R mysql:mysql /var/lib/mysql/dbname)

Note that permissions (GRANT, etc.) are part of the mysql database. So they won't be restored along with the tables; you may need to run the appropriate GRANT statements to create users, give access, etc. (Restoring the mysql database is possible, but you need to be careful with MySQL versions and any needed runs of the mysql_upgrade utility.)

Actually, you probably just need the .FRM (table structure) and .MYD (table data), but you'll have to repair table to rebuild the .MYI (indexes).

The only constraint is that if you're downgrading, you'd best check the release notes (and probably run repair table). Newer MySQL versions add features, of course.

[Although it should be obvious, if you mix and match tables, the integrity of relationships between those tables is your problem; MySQL won't care, but your application and your users may. Also, this method does not work at all for InnoDB tables. Only MyISAM, but considering the files you have, you have MyISAM]

How do I fix MSB3073 error in my post-build event?

Playing around with different project properties, I found that the project build order was the problem. The project that generated the files I wanted to copy was built second, but the project that was running the batch file as a post-build event was built first, so I simply attached the build event to the second project instead, and it works just fine. Thanks for your help, everyone, though.

Change the encoding of a file in Visual Studio Code

The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:

File > Preferences > Settings > Encoding > Choose your option

This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

Formula to check if string is empty in Crystal Reports

You can check for IsNull condition.

If IsNull({TABLE.FIELD}) or {TABLE.FIELD} = "" then
  // do something

Regex for checking if a string is strictly alphanumeric

To check if a String is alphanumeric, you can use a method that goes through every character in the string and checks if it is alphanumeric.

    public static boolean isAlphaNumeric(String s){
            for(int i = 0; i < s.length(); i++){
                    char c = s.charAt(i);
                    if(!Character.isDigit(c) && !Character.isLetter(c))
                            return false;
            }
            return true;
    }

What is the difference between compare() and compareTo()?

When you want to sort a List which include the Object Foo, the Foo class has to implement the Comparable interface, because the sort methode of the List is using this methode.

When you want to write a Util class which compares two other classes you can implement the Comparator class.

How to enable native resolution for apps on iPhone 6 and 6 Plus?

I've made basic black launch screens that will make the app scale properly on the iPhone 6 and iPhone 6+:

iPhone 6 Portrait

iPhone 6 Plus Portrait

If you already have a LaunchImage in your .xcassett, open it, switch to the third tab in the right menu in Xcode and tick the iOS 8.0 iPhone images to add them to the existing set. Then drag the images over:

enter image description here

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!

ImportError: No module named model_selection

Update sklearn

conda update scikit-learn

Convert timestamp long to normal date format

To show leading zeros infront of hours, minutes and seconds use below modified code. The trick here is we are converting (or more accurately formatting) integer into string so that it shows leading zero whenever applicable :

public String convertTimeWithTimeZome(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.setTimeInMillis(time);
        String curTime = String.format("%02d:%02d:%02d", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
        return curTime;
    }

Result would be like : 00:01:30

How to Display Selected Item in Bootstrap Button Dropdown Title

Here is my version of this which I hope can save some of your time :)

enter image description here jQuery PART:

$(".dropdown-menu").on('click', 'li a', function(){
  var selText = $(this).children("h4").html();


 $(this).parent('li').siblings().removeClass('active');
    $('#vl').val($(this).attr('data-value'));
  $(this).parents('.btn-group').find('.selection').html(selText);
  $(this).parents('li').addClass("active");
});

HTML PART:

<div class="container">
  <div class="btn-group">
    <a class="btn btn-default dropdown-toggle btn-blog " data-toggle="dropdown" href="#" id="dropdownMenu1" style="width:200px;"><span class="selection pull-left">Select an option </span> 
      <span class="pull-right glyphiconglyphicon-chevron-down caret" style="float:right;margin-top:10px;"></span></a>

     <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
       <li><a href="#" class="" data-value=1><p> HER Can you write extra text or <b>HTLM</b></p> <h4> <span class="glyphicon glyphicon-plane"></span>  <span> Your Option 1</span> </h4></a>  </li>
       <li><a href="#" class="" data-value=2><p> HER Can you write extra text or <i>HTLM</i> or some long long long long long long long long long long text </p><h4> <span class="glyphicon glyphicon-briefcase"></span> <span>Your Option 2</span>  </h4></a>
      </li>
      <li class="divider"></li>
   <li><a href="#" class="" data-value=3><p> HER Can you write extra text or <b>HTLM</b> or some </p><h4> <span class="glyphicon glyphicon-heart text-danger"></span> <span>Your Option 3</span>  </h4></a>
      </li>
    </ul>
  </div>
  <input type="text" id="vl" />
</div>  

How do you test your Request.QueryString[] variables?

Well for one thing use int.TryParse instead...

int id;
if (!int.TryParse(Request.QueryString["id"], out id))
{
    id = -1;
}

That assumes that "not present" should have the same result as "not an integer" of course.

EDIT: In other cases, when you're going to use request parameters as strings anyway, I think it's definitely a good idea to validate that they're present.

How to copy part of an array to another array in C#?

int[] a = {1,2,3,4,5};

int [] b= new int[a.length]; //New Array and the size of a which is 4

Array.Copy(a,b,a.length);

Where Array is class having method Copy, which copies the element of a array to b array.

While copying from one array to another array, you have to provide same data type to another array of which you are copying.

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

The very keyword 'mutable' is actually a reserved keyword.often it is used to vary the value of constant variable.If you want to have multiple values of a constsnt,use the keyword mutable.

//Prototype 
class tag_name{
                :
                :
                mutable var_name;
                :
                :
               };   

How to read the last row with SQL Server

I think below query will work for SQL Server with maximum performance without any sortable column

SELECT * FROM table 
WHERE ID not in (SELECT TOP (SELECT COUNT(1)-1 
                             FROM table) 
                        ID 
                 FROM table)

Hope you have understood it... :)

How to find and replace string?

void replaceAll(std::string & data, const std::string &toSearch, const std::string &replaceStr)
{
    // Get the first occurrence
    size_t pos = data.find(toSearch);
    // Repeat till end is reached
    while( pos != std::string::npos)
    {
        // Replace this occurrence of Sub String
        data.replace(pos, toSearch.size(), replaceStr);
        // Get the next occurrence from the current position
        pos =data.find(toSearch, pos + replaceStr.size());
    }
}

More CPP utilities: https://github.com/Heyshubham/CPP-Utitlities/blob/master/src/MEString.cpp#L60

How to add header data in XMLHttpRequest when using formdata?

Check to see if the key-value pair is actually showing up in the request:

In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers

Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like: F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.

But as other answers have said:

xhttp.setRequestHeader(key, value);

should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

Displaying splash screen for longer than default seconds

In Xcode 6.1, Swift 1.0 to delay the launch screen:

Add the below statement in e didFinishLaunchingWithOptions meth in AppDelegateod

NSThread.sleepForTimeInterval(3)

Here, time can be passed based on your requirement.

SWIFT 5

Thread.sleep(forTimeInterval: 3)

PPT to PNG with transparent background

You can select the shapes within a slide (Word Art also) and right click on the selection and choose "Save As Picture". It will save as a transparent PNG.

How to list only the file names that changed between two commits?

git diff --name-only SHA1 SHA2

where you only need to include enough of the SHA to identify the commits. You can also do, for example

git diff --name-only HEAD~10 HEAD~5

to see the differences between the tenth latest commit and the fifth latest (or so).

Do you use source control for your database items?

I've started working on sqlHawk which is aimed at providing (open source) tooling around this problem.

It's currently in fairly early stages, but does already support storing and enforcing stored procedures and running scripted updates.

I'd be grateful for any input from anyone who has the time to look at this tool.

Apologies for blatant self promotion, but I hope this is useful to someone!

HTML input time in 24 format

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <body>_x000D_
        Time: <input type="time" id="myTime" value="16:32:55">_x000D_
_x000D_
 <p>Click the button to get the time of the time field.</p>_x000D_
_x000D_
 <button onclick="myFunction()">Try it</button>_x000D_
_x000D_
 <p id="demo"></p>_x000D_
_x000D_
 <script>_x000D_
     function myFunction() {_x000D_
         var x = document.getElementById("myTime").value;_x000D_
         document.getElementById("demo").innerHTML = x;_x000D_
     }_x000D_
 </script>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

I found that by setting value field (not just what is given below) time input will be internally converted into the 24hr format.

How to prevent Screen Capture in Android

about photo screenshot, FLAG_SECURE not working rooted device.

but if you monitor the screenshot file, you can prevent from getting original file.

try this one.

1. monitoring screenshot(file monitor) with android remote service
2. delete original screenshot image.
3. deliver the bitmap instance so you can modify.

Convert base64 string to ArrayBuffer

Try this:

function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

PHP: cannot declare class because the name is already in use

You should use require_once and include_once. Inside parent.php use

include_once 'database.php';

And inside child1.php and child2.php use

include_once 'parent.php';

Remove spaces from std::string in C++

The best thing to do is to use the algorithm remove_if and isspace:

remove_if(str.begin(), str.end(), isspace);

Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:

str.erase(remove_if(str.begin(), str.end(), isspace), str.end());

We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:

template<typename T, typename P>
T remove_if(T beg, T end, P pred)
{
    T dest = beg;
    for (T itr = beg;itr != end; ++itr)
        if (!pred(*itr))
            *(dest++) = *itr;
    return dest;
}

How do I solve the INSTALL_FAILED_DEXOPT error?

in build.gradle change compiled and build to latest version. and it worked for me.

================

android {
    compileSdkVersion 22
    buildToolsVersion "22"

How to stop (and restart) the Rails Server?

Press Ctrl+C

When you start the server it mentions this in the startup text.

Practical uses for AtomicInteger

If you look at the methods AtomicInteger has, you'll notice that they tend to correspond to common operations on ints. For instance:

static AtomicInteger i;

// Later, in a thread
int current = i.incrementAndGet();

is the thread-safe version of this:

static int i;

// Later, in a thread
int current = ++i;

The methods map like this:
++i is i.incrementAndGet()
i++ is i.getAndIncrement()
--i is i.decrementAndGet()
i-- is i.getAndDecrement()
i = x is i.set(x)
x = i is x = i.get()

There are other convenience methods as well, like compareAndSet or addAndGet

Python constructors and __init__

There is no function overloading in Python, meaning that you can't have multiple functions with the same name but different arguments.

In your code example, you're not overloading __init__(). What happens is that the second definition rebinds the name __init__ to the new method, rendering the first method inaccessible.

As to your general question about constructors, Wikipedia is a good starting point. For Python-specific stuff, I highly recommend the Python docs.

Groovy built-in REST/HTTP client?

I don't think http-builder is a Groovy module, but rather an external API on top of apache http-client so you do need to import classes and download a bunch of APIs. You are better using Gradle or @Grab to download the jar and dependencies:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

Note: since the CodeHaus site went down, you can find the JAR at (https://mvnrepository.com/artifact/org.codehaus.groovy.modules.http-builder/http-builder)

Use Font Awesome Icon in Placeholder

Sometimes above all answer not woking, when you can use below trick

_x000D_
_x000D_
.form-group {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input {_x000D_
  padding-left: 1rem;_x000D_
}_x000D_
_x000D_
i {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 50%;_x000D_
  transform: translateY(-50%);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">_x000D_
_x000D_
<form role="form">_x000D_
  <div class="form-group">_x000D_
    <input type="text" class="form-control empty" id="iconified" placeholder="search">_x000D_
    <i class="fas fa-search"></i>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

E: Unable to locate package mongodb-org

The currently accepted answer works, but will install an outdated version of Mongo.

The Mongo documentation states that: MongoDB only provides packages for Ubuntu 12.04 LTS (Precise Pangolin) and 14.04 LTS (Trusty Tahr). However, These packages may work with other Ubuntu releases.

So, to get the lastest stable Mongo (3.0), use this (the different step is the second one):

    apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
    echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb.list
    apt-get update
    apt-get install mongodb-org

Hope this helps.


I would like to add that as a previous step, you must check your GNU/Linux Distro Release, which will construct the Repo list url. For me, as I am using this:

DISTRIB_CODENAME=rafaela
DISTRIB_DESCRIPTION="Linux Mint 17.2 Rafaela"
NAME="Ubuntu"
VERSION="14.04.2 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.2 LTS"

The original 2nd step:

"Create a list file for MongoDB": "echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list"

Didn't work as intended because it generated an incorrect Repo url. Basically, it put the distribution codename "rafaela" within the url repo which doesn't exist. You can check the Repo url at your package manager under Software Sources, Additional Repositories.

What I did was to browse the site:

http://repo.mongodb.org/apt/ubuntu/dists/

And I found out that for Ubuntu, "trusty" and "precise" are the only web folders available, not "rafaela".

Solution: Open as root the file 'mongodb-org-3.1.list' or 'mongodb.list' and replace "rafaela" or your release version for the corresponding version (for me it was: "trusty"), save the changes and continue with next steps. Also, your package manager can let you change easily the repo url as well.

Hope it works for you.! ---

Why doesn't Java allow overriding of static methods?

A Static method, variable, block or nested class belongs to the entire class rather than an object.

A Method in Java is used to expose the behaviour of an Object / Class. Here, as the method is static (i.e, static method is used to represent the behaviour of a class only.) changing/ overriding the behaviour of entire class will violate the phenomenon of one of the fundamental pillar of Object oriented programming i.e, high cohesion. (remember a constructor is a special kind of method in Java.)

High Cohesion - One class should have only one role. For example: A car class should produce only car objects and not bike, trucks, planes etc. But the Car class may have some features(behaviour) that belongs to itself only.

Therefore, while designing the java programming language. The language designers thought to allow developers to keep some behaviours of a class to itself only by making a method static in nature.


The below piece code tries to override the static method, but will not encounter any compilation error.

public class Vehicle {
static int VIN;

public static int getVehileNumber() {
    return VIN;
}}

class Car extends Vehicle {
static int carNumber;

public static int getVehileNumber() {
    return carNumber;
}}

This is because, here we are not overriding a method but we are just re-declaring it. Java allows re-declaration of a method (static/non-static).

Removing the static keyword from getVehileNumber() method of Car class will result into compilation error, Since, we are trying to change the functionality of static method which belongs to Vehicle class only.

Also, If the getVehileNumber() is declared as final then the code will not compile, Since the final keyword restricts the programmer from re-declaring the method.

public static final int getVehileNumber() {
return VIN;     }

Overall, this is upto software designers for where to use the static methods. I personally prefer to use static methods to perform some actions without creating any instance of a class. Secondly, to hide the behaviour of a class from outside world.

List<Map<String, String>> vs List<? extends Map<String, String>>

Today, I have used this feature, so here's my very fresh real-life example. (I have changed class and method names to generic ones so they won't distract from the actual point.)

I have a method that's meant to accept a Set of A objects that I originally wrote with this signature:

void myMethod(Set<A> set)

But it want to actually call it with Sets of subclasses of A. But this is not allowed! (The reason for that is, myMethod could add objects to set that are of type A, but not of the subtype that set's objects are declared to be at the caller's site. So this could break the type system if it were possible.)

Now here come generics to the rescue, because it works as intended if I use this method signature instead:

<T extends A> void myMethod(Set<T> set)

or shorter, if you don't need to use the actual type in the method body:

void myMethod(Set<? extends A> set)

This way, set's type becomes a collection of objects of the actual subtype of A, so it becomes possible to use this with subclasses without endangering the type system.

How to Use slideDown (or show) function on a table row?

If you need to slide and fade a table row at the same time, try using these:

jQuery.fn.prepareTableRowForSliding = function() {
    $tr = this;
    $tr.children('td').wrapInner('<div style="display: none;" />');
    return $tr;
};

jQuery.fn.slideFadeTableRow = function(speed, easing, callback) {
    $tr = this;
    if ($tr.is(':hidden')) {
        $tr.show().find('td > div').animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
    } else {
        $tr.find('td > div').animate({opacity: 'toggle', height: 'toggle'}, speed, easing, function(){
            $tr.hide();
            callback();
        });
    }
    return $tr;
};

$(document).ready(function(){
    $('tr.special').hide().prepareTableRowForSliding();
    $('a.toggle').toggle(function(){
        $button = $(this);
        $tr = $button.closest('tr.special'); //this will be specific to your situation
        $tr.slideFadeTableRow(300, 'swing', function(){
            $button.text('Hide table row');
        });
    }, function(){
        $button = $(this);
        $tr = $button.closest('tr.special'); //this will be specific to your situation
        $tr.slideFadeTableRow(300, 'swing', function(){
            $button.text('Display table row');
        });
});
});

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

Angular 2 execute script after template render

I have found that the best place is in NgAfterViewChecked(). I tried to execute code that would scroll to an ng-accordion panel when the page was loaded. I tried putting the code in NgAfterViewInit() but it did not work there (NPE). The problem was that the element had not been rendered yet. There is a problem with putting it in NgAfterViewChecked(). NgAfterViewChecked() is called several times as the page is rendered. Some calls are made before the element is rendered. This means a check for null may be required to guard the code from NPE. I am using Angular 8.

SVG Positioning

There is a shorter alternative to the previous answer. SVG Elements can also be grouped by nesting svg elements:

<svg xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink">
  <svg x="10">
    <rect x="10" y="10" height="100" width="100" style="stroke:#ff0000;fill: #0000ff"/>
  </svg>
  <svg x="200">
    <rect x="10" y="10" height="100" width="100" style="stroke:#009900;fill: #00cc00"/>
  </svg>
</svg>

The two rectangles are identical (apart from the colors), but the parent svg elements have different x values.

See http://tutorials.jenkov.com/svg/svg-element.html.

How to set the current working directory?

Try os.chdir

os.chdir(path)

        Change the current working directory to path. Availability: Unix, Windows.

How do I store data in local storage using Angularjs?

You can use localStorage for the purpose.

Steps:

  1. add ngStorage.min.js in your file
  2. add ngStorage dependency in your module
  3. add $localStorage module in your controller
  4. use $localStorage.key = value

foreach for JSON array , syntax

You can use the .forEach() method of JavaScript for looping through JSON.

_x000D_
_x000D_
var datesBooking = [_x000D_
    {"date": "04\/24\/2018"},_x000D_
      {"date": "04\/25\/2018"}_x000D_
    ];_x000D_
    _x000D_
    datesBooking.forEach(function(data, index) {_x000D_
      console.log(data);_x000D_
    });
_x000D_
_x000D_
_x000D_

How to change line width in IntelliJ (from 120 character)

Be aware that need to change both location:

File > Settings... > Editor > Code Style > "Hard Wrap at"

and

File > Settings... > Editor > Code Style > (your language) > Wrapping and Braces > Hard wrap at

HTTP Error 404.3-Not Found in IIS 7.5

In windows server 2012, even after installing asp.net you might run into this issue.

Check for "Http activation" feature. This feature is present under Web services as well.

Make sure you add the above and everything should be awesome for you !!!

How to get all Errors from ASP.Net MVC modelState?

In your implementation you are missing static Class, this should be.

if (!ModelState.IsValid)
{
    var errors =  ModelStateErrorHandler.GetModelErrors(this.ModelState);
    return Json(new { errors });
}

rather

if (!ModelState.IsValid)
{
    var errors = ModelState.GetModelErrors();
    return Json(new { errors });
}

How can you zip or unzip from the script using ONLY Windows' built-in capabilities?

I've been looking to answer this exact question and from my research, DiryBoy's response seems to be accurate.

I found the compact.exe program compresses files but not to create a highly compressed file (or set of files). It is similar to the option you get when right clicking on a drive letter or partition in Windows. You get the option to do cleanup (remove temp files, etc) as well as compress files. The compressed files are still accessible but are just compressed to create space on a drive that is low on space.

I also found compress.exe which I did happen to have on my computer. It isn't natively on most windows machines and is part of the 2003 resource kit. It does make a zipped file of sorts but it is really more similar to files from a windows setup disk (has the underscore as the last character of the file extension or name). And the extract.exe command extracts those files.

However, the mantra is, if it can be done natively via the GUI then there is likely a way to do it via batch, .vbs, or some other type of script within the command line. Since windows has had the 'send to' option to create a zip file, I knew there had to be a way to do it via command line and I found some options.

Here is a great link that shows how to zip a file using windows native commands.

https://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili

I tested it with a directory containing multiple nested files and folders and it worked perfectly. Just follow the format of the command line.

There is also a way to unzip the files via command line which I found as well. One way, just brings open an explorer window showing what the content of the zipped file is. Some of these also use Java which isn't necessarily native to windows but is so common that it nearly seems so.

https://superuser.com/questions/149489/does-windows-7-have-unzip-at-the-command-line-installed-by-default

How to unzip a file using the command line?

Working with TIFFs (import, export) in Python using numpy

First, I downloaded a test TIFF image from this page called a_image.tif. Then I opened with PIL like this:

>>> from PIL import Image
>>> im = Image.open('a_image.tif')
>>> im.show()

This showed the rainbow image. To convert to a numpy array, it's as simple as:

>>> import numpy
>>> imarray = numpy.array(im)

We can see that the size of the image and the shape of the array match up:

>>> imarray.shape
(44, 330)
>>> im.size
(330, 44)

And the array contains uint8 values:

>>> imarray
array([[  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       ..., 
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246]], dtype=uint8)

Once you're done modifying the array, you can turn it back into a PIL image like this:

>>> Image.fromarray(imarray)
<Image.Image image mode=L size=330x44 at 0x2786518>

Change priorityQueue to max priorityqueue

You can try pushing elements with reverse sign. Eg: To add a=2 & b=5 and then poll b=5.

PriorityQueue<Integer>  pq = new PriorityQueue<>();
pq.add(-a);
pq.add(-b);
System.out.print(-pq.poll());

Once you poll the head of the queue, reverse the sign for your usage. This will print 5 (larger element). Can be used in naive implementations. Definitely not a reliable fix. I don't recommend it.

Changing the resolution of a VNC session in linux

As this question comes up first on Google I thought I'd share a solution using TigerVNC which is the default these days.

xrandr allows selecting the display modes (a.k.a resolutions) however due to modelines being hard coded any additional modeline such as "2560x1600" or "1600x900" would need to be added into the code. I think the developers who wrote the code are much smarter and the hard coded list is just a sample of values. It leads to the conclusion that there must be a way to add custom modelines and man xrandr confirms it.

With that background if the goal is to share a VNC session between two computers with the above resolutions and assuming that the VNC server is the computer with the resolution of "1600x900":

  1. Start a VNC session with a geometry matching the physical display:

    $ vncserver -geometry 1600x900 :1
    
  2. On the "2560x1600" computer start the VNC viewer (I prefer Remmina) and connect to the remote VNC session:

    host:5901
    
  3. Once inside the VNC session start up a terminal window.

  4. Confirm that the new geometry is available in the VNC session:

    $ xrandr
    Screen 0: minimum 32 x 32, current 1600 x 900, maximum 32768 x 32768
    VNC-0 connected 1600x900+0+0 0mm x 0mm
       1600x900      60.00 +
       1920x1200     60.00  
       1920x1080     60.00  
       1600x1200     60.00  
       1680x1050     60.00  
       1400x1050     60.00  
       1360x768      60.00  
       1280x1024     60.00  
       1280x960      60.00  
       1280x800      60.00  
       1280x720      60.00  
       1024x768      60.00  
       800x600       60.00  
       640x480       60.00  
    

    and you'll notice the screen being quite small.

  5. List the modeline (see xrandr article in ArchLinux wiki) for the "2560x1600" resolution:

    $ cvt 2560 1600
    # 2560x1600 59.99 Hz (CVT 4.10MA) hsync: 99.46 kHz; pclk: 348.50 MHz
    Modeline "2560x1600_60.00"  348.50  2560 2760 3032 3504  1600 1603 1609 1658 -hsync +vsync
    

    or if the monitor is old get the GTF timings:

    $ gtf 2560 1600 60
    # 2560x1600 @ 60.00 Hz (GTF) hsync: 99.36 kHz; pclk: 348.16 MHz
    Modeline "2560x1600_60.00"  348.16  2560 2752 3032 3504  1600 1601 1604 1656 -HSync +Vsync
    
  6. Add the new modeline to the current VNC session:

    $ xrandr --newmode "2560x1600_60.00"  348.16  2560 2752 3032 3504  1600 1601 1604 1656 -HSync +Vsync
    
  7. In the above xrandr output look for the display name on the second line:

    VNC-0 connected 1600x900+0+0 0mm x 0mm
    
  8. Bind the new modeline to the current VNC virtual monitor:

    $ xrandr --addmode VNC-0 "2560x1600_60.00"
    
  9. Use it:

    $ xrandr -s "2560x1600_60.00"
    

webpack: Module not found: Error: Can't resolve (with relative path)

Your file structure says that folder name is Container with a capital C. But you are trying to import it by container with a lowercase c. You will need to change the import or the folder name because the paths are case sensitive.

Convert IEnumerable to DataTable

Firstly you need to add a where T:class constraint - you can't call GetValue on value types unless they're passed by ref.

Secondly GetValue is very slow and gets called a lot.

To get round this we can create a delegate and call that instead:

MethodInfo method = property.GetGetMethod(true);
Delegate.CreateDelegate(typeof(Func<TClass, TProperty>), method );

The problem is that we don't know TProperty, but as usual on here Jon Skeet has the answer - we can use reflection to retrieve the getter delegate, but once we have it we don't need to reflect again:

public class ReflectionUtility
{
    internal static Func<object, object> GetGetter(PropertyInfo property)
    {
        // get the get method for the property
        MethodInfo method = property.GetGetMethod(true);

        // get the generic get-method generator (ReflectionUtility.GetSetterHelper<TTarget, TValue>)
        MethodInfo genericHelper = typeof(ReflectionUtility).GetMethod(
            "GetGetterHelper",
            BindingFlags.Static | BindingFlags.NonPublic);

        // reflection call to the generic get-method generator to generate the type arguments
        MethodInfo constructedHelper = genericHelper.MakeGenericMethod(
            method.DeclaringType,
            method.ReturnType);

        // now call it. The null argument is because it's a static method.
        object ret = constructedHelper.Invoke(null, new object[] { method });

        // cast the result to the action delegate and return it
        return (Func<object, object>) ret;
    }

    static Func<object, object> GetGetterHelper<TTarget, TResult>(MethodInfo method)
        where TTarget : class // target must be a class as property sets on structs need a ref param
    {
        // Convert the slow MethodInfo into a fast, strongly typed, open delegate
        Func<TTarget, TResult> func = (Func<TTarget, TResult>) Delegate.CreateDelegate(typeof(Func<TTarget, TResult>), method);

        // Now create a more weakly typed delegate which will call the strongly typed one
        Func<object, object> ret = (object target) => (TResult) func((TTarget) target);
        return ret;
    }
}

So now your method becomes:

public static DataTable ToDataTable<T>(this IEnumerable<T> items) 
    where T: class
{  
    // ... create table the same way

    var propGetters = new List<Func<T, object>>();
foreach (var prop in props)
    {
        Func<T, object> func = (Func<T, object>) ReflectionUtility.GetGetter(prop);
        propGetters.Add(func);
    }

    // Add the property values per T as rows to the datatable
    foreach (var item in items) 
    {  
        var values = new object[props.Length];  
        for (var i = 0; i < props.Length; i++) 
        {
            //values[i] = props[i].GetValue(item, null);   
            values[i] = propGetters[i](item);
        }    

        table.Rows.Add(values);  
    } 

    return table; 
} 

You could further optimise it by storing the getters for each type in a static dictionary, then you will only have the reflection overhead once for each type.

Nginx not picking up site in sites-enabled?

Changing from:

include /etc/nginx/sites-enabled/*; 

to

include /etc/nginx/sites-enabled/*.*; 

fixed my issue

Get the name of an object's type

Here is an implementation based on the accepted answer:

_x000D_
_x000D_
/**_x000D_
 * Returns the name of an object's type._x000D_
 *_x000D_
 * If the input is undefined, returns "Undefined"._x000D_
 * If the input is null, returns "Null"._x000D_
 * If the input is a boolean, returns "Boolean"._x000D_
 * If the input is a number, returns "Number"._x000D_
 * If the input is a string, returns "String"._x000D_
 * If the input is a named function or a class constructor, returns "Function"._x000D_
 * If the input is an anonymous function, returns "AnonymousFunction"._x000D_
 * If the input is an arrow function, returns "ArrowFunction"._x000D_
 * If the input is a class instance, returns "Object"._x000D_
 *_x000D_
 * @param {Object} object an object_x000D_
 * @return {String} the name of the object's class_x000D_
 * @see <a href="https://stackoverflow.com/a/332429/14731">https://stackoverflow.com/a/332429/14731</a>_x000D_
 * @see getFunctionName_x000D_
 * @see getObjectClass _x000D_
 */_x000D_
function getTypeName(object)_x000D_
{_x000D_
  const objectToString = Object.prototype.toString.call(object).slice(8, -1);_x000D_
  if (objectToString === "Function")_x000D_
  {_x000D_
    const instanceToString = object.toString();_x000D_
    if (instanceToString.indexOf(" => ") != -1)_x000D_
      return "ArrowFunction";_x000D_
    const getFunctionName = /^function ([^(]+)\(/;_x000D_
    const match = instanceToString.match(getFunctionName);_x000D_
    if (match === null)_x000D_
      return "AnonymousFunction";_x000D_
    return "Function";_x000D_
  }_x000D_
  // Built-in types (e.g. String) or class instances_x000D_
  return objectToString;_x000D_
};_x000D_
_x000D_
/**_x000D_
 * Returns the name of a function._x000D_
 *_x000D_
 * If the input is an anonymous function, returns ""._x000D_
 * If the input is an arrow function, returns "=>"._x000D_
 *_x000D_
 * @param {Function} fn a function_x000D_
 * @return {String} the name of the function_x000D_
 * @throws {TypeError} if {@code fn} is not a function_x000D_
 * @see getTypeName_x000D_
 */_x000D_
function getFunctionName(fn)_x000D_
{_x000D_
  try_x000D_
  {_x000D_
    const instanceToString = fn.toString();_x000D_
    if (instanceToString.indexOf(" => ") != -1)_x000D_
      return "=>";_x000D_
    const getFunctionName = /^function ([^(]+)\(/;_x000D_
    const match = instanceToString.match(getFunctionName);_x000D_
    if (match === null)_x000D_
    {_x000D_
      const objectToString = Object.prototype.toString.call(fn).slice(8, -1);_x000D_
      if (objectToString === "Function")_x000D_
        return "";_x000D_
      throw TypeError("object must be a Function.\n" +_x000D_
        "Actual: " + getTypeName(fn));_x000D_
    }_x000D_
    return match[1];_x000D_
  }_x000D_
  catch (e)_x000D_
  {_x000D_
    throw TypeError("object must be a Function.\n" +_x000D_
      "Actual: " + getTypeName(fn));_x000D_
  }_x000D_
};_x000D_
_x000D_
/**_x000D_
 * @param {Object} object an object_x000D_
 * @return {String} the name of the object's class_x000D_
 * @throws {TypeError} if {@code object} is not an Object_x000D_
 * @see getTypeName_x000D_
 */_x000D_
function getObjectClass(object)_x000D_
{_x000D_
  const getFunctionName = /^function ([^(]+)\(/;_x000D_
  const result = object.constructor.toString().match(getFunctionName)[1];_x000D_
  if (result === "Function")_x000D_
  {_x000D_
    throw TypeError("object must be an Object.\n" +_x000D_
      "Actual: " + getTypeName(object));_x000D_
  }_x000D_
  return result;_x000D_
};_x000D_
_x000D_
_x000D_
function UserFunction()_x000D_
{_x000D_
}_x000D_
_x000D_
function UserClass()_x000D_
{_x000D_
}_x000D_
_x000D_
let anonymousFunction = function()_x000D_
{_x000D_
};_x000D_
_x000D_
let arrowFunction = i => i + 1;_x000D_
_x000D_
console.log("getTypeName(undefined): " + getTypeName(undefined));_x000D_
console.log("getTypeName(null): " + getTypeName(null));_x000D_
console.log("getTypeName(true): " + getTypeName(true));_x000D_
console.log("getTypeName(5): " + getTypeName(5));_x000D_
console.log("getTypeName(\"text\"): " + getTypeName("text"));_x000D_
console.log("getTypeName(userFunction): " + getTypeName(UserFunction));_x000D_
console.log("getFunctionName(userFunction): " + getFunctionName(UserFunction));_x000D_
console.log("getTypeName(anonymousFunction): " + getTypeName(anonymousFunction));_x000D_
console.log("getFunctionName(anonymousFunction): " + getFunctionName(anonymousFunction));_x000D_
console.log("getTypeName(arrowFunction): " + getTypeName(arrowFunction));_x000D_
console.log("getFunctionName(arrowFunction): " + getFunctionName(arrowFunction));_x000D_
//console.log("getFunctionName(userClass): " + getFunctionName(new UserClass()));_x000D_
console.log("getTypeName(userClass): " + getTypeName(new UserClass()));_x000D_
console.log("getObjectClass(userClass): " + getObjectClass(new UserClass()));_x000D_
//console.log("getObjectClass(userFunction): " + getObjectClass(UserFunction));_x000D_
//console.log("getObjectClass(userFunction): " + getObjectClass(anonymousFunction));_x000D_
//console.log("getObjectClass(arrowFunction): " + getObjectClass(arrowFunction));_x000D_
console.log("getTypeName(nativeObject): " + getTypeName(navigator.mediaDevices.getUserMedia));_x000D_
console.log("getFunctionName(nativeObject): " + getFunctionName(navigator.mediaDevices.getUserMedia));
_x000D_
_x000D_
_x000D_

We only use the constructor property when we have no other choice.

How to select all instances of a variable and edit variable name in Sublime

Just in case anyone else stumbled on this question while looking for a way to replace a string across multiple files, it is Command+Shift+F

Java foreach loop: for (Integer i : list) { ... }

One way to do that is to use a counter:

ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) { 
    ...
    if (--size == 0) {
        // Last item.
        ...
    }
}

Edit

Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a for loop or the iterator, as everything you win when using the Java5 syntax will be lost in the loop itself...

for (int i = 0; i < list.size(); i++) {
    ...

    if (i == (list.size() - 1)) {
        // Last item...
    }
}

or

for (Iterator it = list.iterator(); it.hasNext(); ) {
    ...

    if (!it.hasNext()) {
        // Last item...
    }
}

What is the size of an enum in C?

In C language, an enum is guaranteed to be of size of an int. There is a compile time option (-fshort-enums) to make it as short (This is mainly useful in case the values are not more than 64K). There is no compile time option to increase its size to 64 bit.

Error: Java: invalid target release: 11 - IntelliJ IDEA

I tried all the above and found this secret sauce

  1. make sure pom.xml specifies your desired jdk.
  2. make sure maven specifies your desired jdk.
  3. make sure Projects specifies your desired jdk.
  4. make sure Modules specifies your integer jdk AND Dependencies specifies your jdk. hth.

What does "#include <iostream>" do?

In order to read or write to the standard input/output streams you need to include it.

int main( int argc, char * argv[] )
{
    std::cout << "Hello World!" << std::endl;
    return 0;
}

That program will not compile unless you add #include <iostream>

The second line isn't necessary

using namespace std;

What that does is tell the compiler that symbol names defined in the std namespace are to be brought into your program's scope, so you can omit the namespace qualifier, and write for example

#include <iostream>
using namespace std;
int main( int argc, char * argv[] )
{
    cout << "Hello World!" << endl;
    return 0;
}

Notice you no longer need to refer to the output stream with the fully qualified name std::cout and can use the shorter name cout.

I personally don't like bringing in all symbols in the namespace of a header file... I'll individually select the symbols I want to be shorter... so I would do this:

#include <iostream>
using std::cout;
using std::endl;

int main( int argc, char * argv[] )
{
    cout << "Hello World!" << endl;
    return 0;
}

But that is a matter of personal preference.

Angular2 Routing with Hashtag to page anchor

I've just tested very useful plugin available in nmp - ngx-scroll-to, which works great for me. However it's designed for Angular 4+, but maybe somebody will find this answer helpful.

PHP, MySQL error: Column count doesn't match value count at row 1

Your query has 8 or possibly even 9 variables, ie. Name, Description etc. But the values, these things ---> '', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", only total 7, the number of variables have to be the same as the values.

I had the same problem but I figured it out. Hopefully it will also work for you.

Java Swing revalidate() vs repaint()

revalidate is called on a container once new components are added or old ones removed. this call is an instruction to tell the layout manager to reset based on the new component list. revalidate will trigger a call to repaint what the component thinks are 'dirty regions.' Obviously not all of the regions on your JPanel are considered dirty by the RepaintManager.

repaint is used to tell a component to repaint itself. It is often the case that you need to call this in order to cleanup conditions such as yours.

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

ExecuteNonQuery():

  1. will work with Action Queries only (Create,Alter,Drop,Insert,Update,Delete).
  2. Returns the count of rows effected by the Query.
  3. Return type is int
  4. Return value is optional and can be assigned to an integer variable.

ExecuteReader():

  1. will work with Action and Non-Action Queries (Select)
  2. Returns the collection of rows selected by the Query.
  3. Return type is DataReader.
  4. Return value is compulsory and should be assigned to an another object DataReader.

ExecuteScalar():

  1. will work with Non-Action Queries that contain aggregate functions.
  2. Return the first row and first column value of the query result.
  3. Return type is object.
  4. Return value is compulsory and should be assigned to a variable of required type.

Reference URL:

http://nareshkamuni.blogspot.in/2012/05/what-is-difference-between.html

How can I pretty-print JSON using node.js?

Another workaround would be to make use of prettier to format the JSON. The example below is using 'json' parser but it could also use 'json5', see list of valid parsers.

const prettier = require("prettier");
console.log(prettier.format(JSON.stringify(object),{ semi: false, parser: "json" }));

Turning off eslint rule for a specific line

To disable all rules on a specific line:

alert('foo'); // eslint-disable-line

Replace non ASCII character from string

[Updated solution]

can be used with "Normalize" (Canonical decomposition) and "replaceAll", to replace it with the appropriate characters.

import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.regex.Pattern;

public final class NormalizeUtils {

    public static String normalizeASCII(final String string) {
        final String normalize = Normalizer.normalize(string, Form.NFD);

        return Pattern.compile("\\p{InCombiningDiacriticalMarks}+")
                      .matcher(normalize)
                      .replaceAll("");
    } ...

jQuery.inArray(), how to use it right?

If we want to check an element is inside a set of elements we can do for example:

var checkboxes_checked = $('input[type="checkbox"]:checked');

// Whenever a checkbox or input text is changed
$('input[type="checkbox"], input[type="text"]').change(function() {
    // Checking if the element was an already checked checkbox
    if($.inArray( $(this)[0], checkboxes_checked) !== -1) {
        alert('this checkbox was already checked');
    }
}

Unable instantiate android.gms.maps.MapFragment

i had everything what everyone above was saying and resolved the error by simply calling the super.onCreate(savedInstanceState); as first instruction in oncreate method; before it was last line in method. :| wasted whole day.

Unsupported Media Type in postman

Thanks for all Contributions;

that is happening with me in XML; I just Change application/XML to be text/XML which solve my Problem

what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?

Given this example url:

http://www.example.com/some-dir/yourpage.php?q=bogus&n=10

$_SERVER['REQUEST_URI'] will give you:

/some-dir/yourpage.php?q=bogus&n=10

Whereas $_GET['q'] will give you:

bogus

In other words, $_SERVER['REQUEST_URI'] will hold the full request path including the querystring. And $_GET['q'] will give you the value of parameter q in the querystring.

Use jQuery to change value of a label

.text is correct, the following code works for me:

$('#lb'+(n+1)).text(a[i].attributes[n].name+": "+ a[i].attributes[n].value);

How to open a folder in Windows Explorer from VBA?

I may not use shell command because of security in the company so the best way I found on internet.

Sub OpenFileOrFolderOrWebsite() 
'Shows how to open files and / or folders and / or websites / or create    emails using the FollowHyperlink method
Dim strXLSFile As String, strPDFFile As String, strFolder As String, strWebsite As String 
Dim strEmail As String, strSubject As String, strEmailHyperlink As     String 

strFolder = "C:\Test Files\" 
strXLSFile = strFolder & "Test1.xls" 
strPDFFile = strFolder & "Test.pdf" 
strWebsite = "http://www.blalba.com/" 

strEmail = "mailto:[email protected]" 
strSubject = "?subject=Test" 
strEmailHyperlink = strEmail & strSubject 

 '**************FEEL FREE TO COMMENT ANY OF THESE TO TEST JUST ONE ITEM*********
 'Open Folder
ActiveWorkbook.FollowHyperlink Address:=strFolder, NewWindow:=True 
 'Open excel workbook
ActiveWorkbook.FollowHyperlink Address:=strXLSFile, NewWindow:=True 
 'Open PDF file
ActiveWorkbook.FollowHyperlink Address:=strPDFFile, NewWindow:=True 
 'Open VBAX
ActiveWorkbook.FollowHyperlink Address:=strWebsite, NewWindow:=True 
 'Create New Email
ActiveWorkbook.FollowHyperlink Address:=strEmailHyperlink, NewWindow:=True 
 '******************************************************************************
End Sub 

so actually its

strFolder = "C:\Test Files\"

and

ActiveWorkbook.FollowHyperlink Address:=strFolder, NewWindow:=True 

Error in eval(expr, envir, enclos) : object not found

i use colname(train) = paste("A", colname(train)) and it turns out to the same problem as yours.

I finally figure out that randomForest is more stingy than rpart, it can't recognize the colname with space, comma or other specific punctuation.

paste function will prepend "A" and " " as seperator with each colname. so we need to avert the space and use this sentence instead:

colname(train) = paste("A", colname(train), sep = "")

this will prepend string without space.

Automatic creation date for Django model form objects?

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

ES6 class variable alternatives

This is a bit hackish combo of static and get works for me

class ConstantThingy{
        static get NO_REENTER__INIT() {
            if(ConstantThingy._NO_REENTER__INIT== null){
                ConstantThingy._NO_REENTER__INIT = new ConstantThingy(false,true);
            }
            return ConstantThingy._NO_REENTER__INIT;
        }
}

elsewhere used

var conf = ConstantThingy.NO_REENTER__INIT;
if(conf.init)...

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

The solution is to put an N in front of both the type and the SQL string to indicate it is a double-byte character string:

DECLARE @SQL NVARCHAR(100) 
SET @SQL = N'SELECT TOP 1 * FROM sys.tables' 
EXECUTE sp_executesql @SQL

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

This error comes when you are trying to load jasper report file with the extension .jasper
For Example 
c://reports//EmployeeReport.jasper"

While you should load jasper report file with the extension .jrxml
For Example 
c://reports//EmployeeReport.jrxml"
[See Problem Screenshot ][1] [1]: https://i.stack.imgur.com/D5SzR.png
[See Solution Screenshot][2] [2]: https://i.stack.imgur.com/VeQb9.png

  
  

PHP Excel Header

Try this

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I have just faced this issue in VS 2013 .NET 4.5 with a MapInfo DLL. Turns out, the problem was that I changed the Platform for Build from x86 to Any CPU and that was enough to trigger this error. Changing it back to x86 did the trick. Might help someone.

How to remove all whitespace from a string?

This way you can remove all spaces from all character variables in your data frame. If you would prefer to choose only some of the variables, use mutateor mutate_at.

library(dplyr)
library(stringr)

remove_all_ws<- function(string){
    return(gsub(" ", "", str_squish(string)))
}

df<-df %>%  mutate_if(is.character, remove_all_ws)

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

CMake complains "The CXX compiler identification is unknown"

I just had this problem setting up my new laptop. The issue for me was that my toolchain (CodeSourcery) is 32bit and I had not installed the 32bit libs.

sudo apt-get install ia32-libs

How to parse dates in multiple formats using SimpleDateFormat

I was having multiple date formats into json, and was extracting csv with universal format. I looked multiple places, tried different ways, but at the end I'm able to convert with the following simple code.

private String getDate(String anyDateFormattedString) {
    @SuppressWarnings("deprecation")
    Date date = new Date(anyDateFormattedString);
    SimpleDateFormat dateFormat = new SimpleDateFormat(yourDesiredDateFormat);
        String convertedDate = dateFormat.format(date);
    return convertedDate;
}

What is the difference between synchronous and asynchronous programming (in node.js)

The function makes the second one asynchronous.

The first one forces the program to wait for each line to finish it's run before the next one can continue. The second one allows each line to run together (and independently) at once.

Languages and frameworks (js, node.js) that allow asynchronous or concurrency is great for things that require real time transmission (eg. chat, stock applications).

How to check whether a int is not null or empty?

Possibly browser returns String representation of some integer value? Actually int can't be null. May be you could check for null, if value is not null, then transform String representation to int.

Android: Share plain text using intent (to all messaging apps)

New way of doing this would be using ShareCompat.IntentBuilder like so:

// Create and fire off our Intent in one fell swoop
ShareCompat.IntentBuilder
        // getActivity() or activity field if within Fragment
        .from(this) 
        // The text that will be shared
        .setText(textToShare)
        // most general text sharing MIME type
        .setType("text/plain") 
        .setStream(uriToContentThatMatchesTheArgumentOfSetType)
        /*
         * [OPTIONAL] Designate a URI to share. Your type that 
         * is set above will have to match the type of data
         * that your designating with this URI. Not sure
         * exactly what happens if you don't do that, but 
         * let's not find out.
         * 
         * For example, to share an image, you'd do the following:
         *     File imageFile = ...;
         *     Uri uriToImage = ...; // Convert the File to URI
         *     Intent shareImage = ShareCompat.IntentBuilder.from(activity)
         *       .setType("image/png")
         *       .setStream(uriToImage)
         *       .getIntent();
         */
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email recipients as an array
         * of Strings or a single String
         */ 
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email addresses that will be 
         * BCC'd on an email as an array of Strings or a single String
         */ 
        .addEmailBcc(arrayOfStringEmailAddresses)
        .addEmailBcc(singleStringEmailAddress)
        /* 
         * The title of the chooser that the system will show
         * to allow the user to select an app
         */
        .setChooserTitle(yourChooserTitle)
        .startChooser();

If you have any more questions about using ShareCompat, I highly recommend this great article from Ian Lake, an Android Developer Advocate at Google, for a more complete breakdown of the API. As you'll notice, I borrowed some of this example from that article.

If that article doesn't answer all of your questions, there is always the Javadoc itself for ShareCompat.IntentBuilder on the Android Developers website. I added more to this example of the API's usage on the basis of clemantiano's comment.

Angular 5 Scroll to top on every Route click

From Angular Version 6+ No need to use window.scroll(0,0)

For Angular version 6+ from @docs
Represents options to configure the router.

interface ExtraOptions {
  enableTracing?: boolean
  useHash?: boolean
  initialNavigation?: InitialNavigation
  errorHandler?: ErrorHandler
  preloadingStrategy?: any
  onSameUrlNavigation?: 'reload' | 'ignore'
  scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
  anchorScrolling?: 'disabled' | 'enabled'
  scrollOffset?: [number, number] | (() => [number, number])
  paramsInheritanceStrategy?: 'emptyOnly' | 'always'
  malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
  urlUpdateStrategy?: 'deferred' | 'eager'
  relativeLinkResolution?: 'legacy' | 'corrected'
}

One can use scrollPositionRestoration?: 'disabled' | 'enabled' | 'top' in

Example:

RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled'|'top' 
});

And if one requires to manually control the scrolling, No need to use window.scroll(0,0) Instead from Angular V6 common package has introduced ViewPortScoller.

abstract class ViewportScroller {
  static ngInjectableDef: defineInjectable({ providedIn: 'root', factory: () => new BrowserViewportScroller(inject(DOCUMENT), window) })
  abstract setOffset(offset: [number, number] | (() => [number, number])): void
  abstract getScrollPosition(): [number, number]
  abstract scrollToPosition(position: [number, number]): void
  abstract scrollToAnchor(anchor: string): void
  abstract setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void
}

Usage is pretty Straightforward Example:

import { Router } from '@angular/router';
import {  ViewportScroller } from '@angular/common'; //import
export class RouteService {

  private applicationInitialRoutes: Routes;
  constructor(
    private router: Router;
    private viewPortScroller: ViewportScroller//inject
  )
  {
   this.router.events.pipe(
            filter(event => event instanceof NavigationEnd))
            .subscribe(() => this.viewPortScroller.scrollToPosition([0, 0]));
}

Checking character length in ruby

You could take any of the answers above that use the string.length method and replace it with string.size.

They both work the same way.

if string.size <= 25
  puts "No problem here!"
else
  puts "Sorry too long!"
end

https://ruby-doc.org/core-2.4.0/String.html#method-i-size

Show ImageView programmatically

What is the best way to seed a database in Rails?

Rails has a built in way to seed data as explained here.

Another way would be to use a gem for more advanced or easy seeding such as: seedbank.

The main advantage of this gem and the reason I use it is that it has advanced capabilities such as data loading dependencies and per environment seed data.

Adding an up to date answer as this answer was first on google.

refresh both the External data source and pivot tables together within a time schedule

I found this solution online, and it addressed this pretty well. My only concern is looping through all the pivots and queries might become time consuming if there's a lot of them:

Sub RefreshTables()

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Dim objList As ListObject
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
    For Each objList In ws.ListObjects
        If objList.SourceType = 3 Then
            With objList.QueryTable
                .BackgroundQuery = False
                .Refresh
            End With
        End If
    Next objList
Next ws

Call UpdateAllPivots

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

Sub UpdateAllPivots()
Dim pt As PivotTable
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
    For Each pt In ws.PivotTables
        pt.RefreshTable
    Next pt
Next ws

End Sub

How to get the total number of rows of a GROUP BY query?

There are two ways you can count the number of rows.

$query = "SELECT count(*) as total from table1";
$prepare = $link->prepare($query);
$prepare->execute();
$row = $prepare->fetch(PDO::FETCH_ASSOC);
echo $row['total']; // This will return you a number of rows.

Or second way is

$query = "SELECT field1, field2 from table1";
$prepare = $link->prepare($query);
$prepare->execute();
$row = $prepare->fetch(PDO::FETCH_NUM);
echo $rows[0]; // This will return you a number of rows as well.

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

  1. Go to Help > Install New Software...
  2. Use this software repository

    Make sure "Contact all update sites during install to find required software" is checked.

  3. Install the AJDT m2e Configurator

Source: Upgrading Maven integration for SpringSource Tool Suite 2.8.0 (Andrew Eisenberg)

This should automatically install ADJT if you don't have it installed, but if it doesn't, install AspectJ Development Tools (ADJT) first from "Indigo update site" (according to your Eclipse version).

More info on AspectJ Development Tools site.

Get JavaScript object from array of objects by value of property

If I understand correctly, you want to find the object in the array whose b property is 6?

var found;
jsObjects.some(function (obj) {
  if (obj.b === 6) {
    found = obj;
    return true;
  }
});

Or if you were using underscore:

var found = _.select(jsObjects, function (obj) {
  return obj.b === 6;
});

X-Frame-Options on apache

This worked for me on all browsers:

  1. Created one page with all my javascript
  2. Created a 2nd page on the same server and embedded the first page using the object tag.
  3. On my third party site I used the Object tag to embed the 2nd page.
  4. Created a .htaccess file on the original server in the public_html folder and put Header unset X-Frame-Options in it.

Postgresql - change the size of a varchar column to lower length

if you put the alter into a transaction the table should not be locked:

BEGIN;
  ALTER TABLE "public"."mytable" ALTER COLUMN "mycolumn" TYPE varchar(40);
COMMIT;

this worked for me blazing fast, few seconds on a table with more than 400k rows.

Insert/Update Many to Many Entity Framework . How do I do it?

In entity framework, when object is added to context, its state changes to Added. EF also changes state of each object to added in object tree and hence you are either getting primary key violation error or duplicate records are added in table.

Netbeans how to set command line arguments in Java

IF you are using MyEclipse and want to add args before run the program, Then do as follows: 1.0) Run -> Run Config 2.1) Click "Arguments" on the right panel 2.2)add your args in the "Program Args" box, separated by blank

Take the content of a list and append it to another list

Take a look at itertools.chain for a fast way to treat many small lists as a single big list (or at least as a single big iterable) without copying the smaller lists:

>>> import itertools
>>> p = ['a', 'b', 'c']
>>> q = ['d', 'e', 'f']
>>> r = ['g', 'h', 'i']
>>> for x in itertools.chain(p, q, r):
        print x.upper()

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>

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

For the last Spring MVC app I wrote, I didn't inject the SecurityContext holder, but I did have a base controller that I had two utility methods related to this ... isAuthenticated() & getUsername(). Internally they do the static method call you described.

At least then it's only in once place if you need to later refactor.

No process is on the other end of the pipe (SQL Server 2012)

Also you can try to go to services and restart your Sql server instanceenter image description here

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

Try wrapping your dates in single quotes, like this:

'15-6-2005'

It should be able to parse the date this way.

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

Difference between a Structure and a Union

With a union, you're only supposed to use one of the elements, because they're all stored at the same spot. This makes it useful when you want to store something that could be one of several types. A struct, on the other hand, has a separate memory location for each of its elements and they all can be used at once.

To give a concrete example of their use, I was working on a Scheme interpreter a little while ago and I was essentially overlaying the Scheme data types onto the C data types. This involved storing in a struct an enum indicating the type of value and a union to store that value.

union foo {
  int a;   // can't use both a and b at once
  char b;
} foo;

struct bar {
  int a;   // can use both a and b simultaneously
  char b;
} bar;

union foo x;
x.a = 3; // OK
x.b = 'c'; // NO! this affects the value of x.a!

struct bar y;
y.a = 3; // OK
y.b = 'c'; // OK

edit: If you're wondering what setting x.b to 'c' changes the value of x.a to, technically speaking it's undefined. On most modern machines a char is 1 byte and an int is 4 bytes, so giving x.b the value 'c' also gives the first byte of x.a that same value:

union foo x;
x.a = 3;
x.b = 'c';
printf("%i, %i\n", x.a, x.b);

prints

99, 99

Why are the two values the same? Because the last 3 bytes of the int 3 are all zero, so it's also read as 99. If we put in a larger number for x.a, you'll see that this is not always the case:

union foo x;
x.a = 387439;
x.b = 'c';
printf("%i, %i\n", x.a, x.b);

prints

387427, 99

To get a closer look at the actual memory values, let's set and print out the values in hex:

union foo x;
x.a = 0xDEADBEEF;
x.b = 0x22;
printf("%x, %x\n", x.a, x.b);

prints

deadbe22, 22

You can clearly see where the 0x22 overwrote the 0xEF.

BUT

In C, the order of bytes in an int are not defined. This program overwrote the 0xEF with 0x22 on my Mac, but there are other platforms where it would overwrite the 0xDE instead because the order of the bytes that make up the int were reversed. Therefore, when writing a program, you should never rely on the behavior of overwriting specific data in a union because it's not portable.

For more reading on the ordering of bytes, check out endianness.

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

Where does Git store files?

If you are on an English Windows machine, Git's default storage path will be C:\Documents and Settings\< current_user>\, because on Windows the default Git local settings resides at C:\Documents and Settings\< current_user>\.git and so Git creates a separate folder for each repo/clone at C:\Documents and Settings\< current_user>\ and there are all the directories of cloned project.

For example, if you install Symfony 2 with

git clone git://github.com/symfony/symfony.git

the Symfony directory and file will be at

C:\Documents and Settings\< current_user>\symfony\

What is the difference between int, Int16, Int32 and Int64?

According to Jeffrey Richter(one of the contributors of .NET framework development)'s book 'CLR via C#':

int is a primitive type allowed by the C# compiler, whereas Int32 is the Framework Class Library type (available across languages that abide by CLS). In fact, int translates to Int32 during compilation.

Also,

In C#, long maps to System.Int64, but in a different programming language, long could map to Int16 or Int32. In fact, C++/CLI does treat long as Int32.

In fact, most (.NET) languages won't even treat long as a keyword and won't compile code that uses it.

I have seen this author, and many standard literature on .NET preferring FCL types(i.e., Int32) to the language-specific primitive types(i.e., int), mainly on such interoperability concerns.

Show/Hide Table Rows using Javascript classes

Well one way to do it would be to just put a class on the "parent" rows and remove all the ids and inline onclick attributes:

<table id="products">
    <thead>
    <tr>
        <th>Product</th>
        <th>Price</th>
        <th>Destination</th>
        <th>Updated on</th>
    </tr>
    </thead>
    <tbody>
    <tr class="parent">
        <td>Oranges</td>
        <td>100</td>
        <td><a href="#">+ On Store</a></td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>120</td>
        <td>City 1</td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>140</td>
        <td>City 2</td>
        <td>22/10</td>
    </tr>
    ...etc.
    </tbody>
</table>

And then have some CSS that hides all non-parents:

tbody tr {
    display : none;          // default is hidden
}
tr.parent {
    display : table-row;     // parents are shown
}
tr.open {
    display : table-row;     // class to be given to "open" child rows
}

That greatly simplifies your html. Note that I've added <thead> and <tbody> to your markup to make it easy to hide data rows and ignore heading rows.

With jQuery you can then simply do this:

// when an anchor in the table is clicked
$("#products").on("click","a",function(e) {
    // prevent default behaviour
    e.preventDefault();
    // find all the following TR elements up to the next "parent"
    // and toggle their "open" class
    $(this).closest("tr").nextUntil(".parent").toggleClass("open");
});

Demo: http://jsfiddle.net/CBLWS/1/

Or, to implement something like that in plain JavaScript, perhaps something like the following:

document.getElementById("products").addEventListener("click", function(e) {
    // if clicked item is an anchor
    if (e.target.tagName === "A") {
        e.preventDefault();
        // get reference to anchor's parent TR
        var row = e.target.parentNode.parentNode;
        // loop through all of the following TRs until the next parent is found
        while ((row = nextTr(row)) && !/\bparent\b/.test(row.className))
            toggle_it(row);
    }
});

function nextTr(row) {
    // find next sibling that is an element (skip text nodes, etc.)
    while ((row = row.nextSibling) && row.nodeType != 1);
    return row;
}

function toggle_it(item){ 
     if (/\bopen\b/.test(item.className))       // if item already has the class
         item.className = item.className.replace(/\bopen\b/," "); // remove it
     else                                       // otherwise
         item.className += " open";             // add it
}

Demo: http://jsfiddle.net/CBLWS/

Either way, put the JavaScript in a <script> element that is at the end of the body, so that it runs after the table has been parsed.

jQuery add blank option to top of list and make selected to existing dropdown

Solution native Javascript :

document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);

example : http://codepen.io/anon/pen/GprybL

Preserve Line Breaks From TextArea When Writing To MySQL

Got my own answer: Using this function from the data from the textarea solves the problem:

function mynl2br($text) { 
   return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')); 
} 

More here: http://php.net/nl2br

What is causing the error `string.split is not a function`?

document.location isn't a string.

You're probably wanting to use document.location.href or document.location.pathname instead.

How to use Servlets and Ajax?

The right way to update the page currently displayed in the user's browser (without reloading it) is to have some code executing in the browser update the page's DOM.

That code is typically javascript that is embedded in or linked from the HTML page, hence the AJAX suggestion. (In fact, if we assume that the updated text comes from the server via an HTTP request, this is classic AJAX.)

It is also possible to implement this kind of thing using some browser plugin or add-on, though it may be tricky for a plugin to reach into the browser's data structures to update the DOM. (Native code plugins normally write to some graphics frame that is embedded in the page.)

CodeIgniter: Create new helper?

A CodeIgniter helper is a PHP file with multiple functions. It is not a class

Create a file and put the following code into it.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('test_method'))
{
    function test_method($var = '')
    {
        return $var;
    }   
}

Save this to application/helpers/ . We shall call it "new_helper.php"

The first line exists to make sure the file cannot be included and ran from outside the CodeIgniter scope. Everything after this is self explanatory.

Using the Helper


This can be in your controller, model or view (not preferable)

$this->load->helper('new_helper');

echo test_method('Hello World');

If you use this helper in a lot of locations you can have it load automatically by adding it to the autoload configuration file i.e. <your-web-app>\application\config\autoload.php.

$autoload['helper'] = array('new_helper');

-Mathew

Extract MSI from EXE

The only way to do that is running the exe and collect the MSI. The thing you must take care of is that if you are tranforming the MSI using MST they might get lost.

I use this batch commandline:

SET TMP=c:\msipath

MD "%TMP%"

SET TEMP=%TMP%

start /d "c:\install" install.exe /L1033

PING 1.1.1.1 -n 1 -w 10000 >NUL

for /R "%TMP%" %%f in (*.msi) do copy "%%f" "%TMP%"

taskkill /F /IM msiexec.exe /T

Creating a border like this using :before And :after Pseudo-Elements In CSS?

#footer:after
{
   content: "";
    width: 40px;
    height: 3px;
    background-color: #529600;
    left: 0;
    position: relative;
    display: block;
    top: 10px;
}

How do I include the string header?

You shouldn't be using string.h if you're coding in C++. Strings in C++ are of the std::string variety which is a lot easier to use than then old C-style "strings". Use:

#include <string>

to get the correct information and something std::string s to declare one. The many wonderful ways you can use std::string can be seen here.

If you have a look at the large number of questions on Stack Overflow regarding the use of C strings, you'll see why you should avoid them where possible :-)

Android 5.0 - Add header/footer to a RecyclerView

I haven't tried this, but I would simply add 1 (or 2, if you want both a header and footer) to the integer returned by getItemCount in your adapter. You can then override getItemViewType in your adapter to return a different integer when i==0: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemViewType(int)

createViewHolder is then passed the integer you returned from getItemViewType, allowing you to create or configure the view holder differently for the header view: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#createViewHolder(android.view.ViewGroup, int)

Don't forget to subtract one from the position integer passed to bindViewHolder.

Matching strings with wildcard

It is necessary to take into consideration, that Regex IsMatch gives true with XYZ, when checking match with Y*. To avoid it, I use "^" anchor

isMatch(str1, "^" + str2.Replace("*", ".*?"));  

So, full code to solve your problem is

    bool isMatchStr(string str1, string str2)
    {
        string s1 = str1.Replace("*", ".*?");
        string s2 = str2.Replace("*", ".*?");
        bool r1 = Regex.IsMatch(s1, "^" + s2);
        bool r2 = Regex.IsMatch(s2, "^" + s1);
        return r1 || r2;
    }

Android - styling seek bar

I change the background_fill.xml

<?xml version="1.0" encoding="UTF-8"?>
  <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line" >
<size android:height="1dp" />
<gradient
    android:angle="0"
    android:centerColor="#616161"
    android:endColor="#616161"
    android:startColor="#616161" />
<corners android:radius="0dp" />
<stroke
    android:width="1dp"
    android:color="#616161" />
<stroke
    android:width="1dp"
    android:color="#616161" />
</shape>

and the progress_fill.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line" >
<size android:height="1dp" />
<gradient
    android:angle="0"
    android:centerColor="#fafafa"
    android:endColor="#fafafa"
    android:startColor="#fafafa" />
<corners android:radius="1dp" />
<stroke
    android:width="1dp"
    android:color="#cccccc" />
<stroke
    android:width="1dp"
    android:color="#cccccc" />
 </shape>

to make the background & progress 1dp height.

error: expected class-name before ‘{’ token

Replace

#include "Landing.h"

with

class Landing;

If you still get errors, also post Item.h, Flight.h and common.h

EDIT: In response to comment.

You will need to e.g. #include "Landing.h" from Event.cpp in order to actually use the class. You just cannot include it from Event.h

close fxml window by code, javafx

  1. give your close button an fx:id, if you haven't yet: <Button fx:id="closeButton" onAction="#closeButtonAction">
  2. In your controller class:

    @FXML private javafx.scene.control.Button closeButton;
    
    @FXML
    private void closeButtonAction(){
        // get a handle to the stage
        Stage stage = (Stage) closeButton.getScene().getWindow();
        // do what you have to do
        stage.close();
    }
    

Place API key in Headers or URL

It should be put in the HTTP Authorization header. The spec is here https://tools.ietf.org/html/rfc7235

How to get json key and value in javascript?

var data = {"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}

var parsedData = JSON.parse(data);
alert(parsedData.name);
alert(parsedData.skills);
alert(parsedData.jobtitel);
alert(parsedData.res_linkedin);

How can you make a custom keyboard in Android?

Well Suragch gave the best answer so far but he skipped certain minor stuff that was important to getting the app compiled.

I hope to make a better answer than Suragch by improving on his answer. I will add all the missing elements he didnt put.

I compiled my apk using the android app , APK Builder 1.1.0. So let's begin.

To build an Android app we need couple files and folders that are organized in a certain format and capitalized accordingly.

res layout -> xml files depicting how app will look on phone. Similar to how html shapes how web page looks on browser. Allowing your app to fit on screens accordingly.

values -> constant data such as colors.xml, strings.xml, styles.xml. These files must be properly spelt.

drawable -> pics{jpeg, png,...}; Name them anything.

mipmap -> more pics. used for app icon?

xml -> more xml files.

src -> acts like JavaScript in html. layout files will initiate the starting view and your java file will dynamically control the tag elements and trigger events. Events can also be activated directly in the layout.xml just like in html.

AndroidManifest.xml -> This file registers what your app is about. Application name, Type of program, permissions needed, etc. This seems to make Android rather safe. Programs literally cannot do what they didnt ask for in the Manifest.

Now there are 4 types of Android programs, an activity, a service, a content provider, and a broadcast reciever. Our keyboard will be a service, which allows it to run in the background. It will not appear in the list of apps to launch; but it can be uninstalled.

To compile your app, involves gradle, and apk signing. You can research that one or use APK Builder for android. It is super easy.

Now that we understand Android development, let us create the files and folders.

  1. Create the files and folders as I discussed above. My directory wil look as follows:

    • NumPad
      • AndroidManifest.xml
      • src
        • Saragch
          • num_pad
            • MyInputMethodService.java
      • res
        • drawable
          • Suragch_NumPad_icon.png
        • layout
          • key_preview.xml
          • keyboard_view.xml
        • xml
          • method.xml
          • number_pad.xml
        • values
          • colors.xml
          • strings.xml
          • styles.xml

Remember if you are using an ide such as Android Studio it may have a project file.

  1. Write files.

A: NumPad/res/layout/key_preview.xml

<?xml version="1.0" encoding="utf-8"?>
   <TextView
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:gravity="center"
      android:background="@android:color/white"
      android:textColor="@android:color/black"
      android:textSize="30sp">
</TextView>

B: NumPad/res/layout/keyboard_view.xml

<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:keyPreviewLayout="@layout/key_preview"
    android:layout_alignParentBottom="true">

</android.inputmethodservice.KeyboardView>

C: NumPad/res/xml/method.xml

<?xml version="1.0" encoding="utf-8"?>
<input-method  xmlns:android="http://schemas.android.com/apk/res/android">
    <subtype  android:imeSubtypeMode="keyboard"/>
</input-method>

D: Numpad/res/xml/number_pad.xml

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="20%p"
    android:horizontalGap="5dp"
    android:verticalGap="5dp"
    android:keyHeight="60dp">

    <Row>
        <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
        <Key android:codes="50" android:keyLabel="2"/>
        <Key android:codes="51" android:keyLabel="3"/>
        <Key android:codes="52" android:keyLabel="4"/>
        <Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/>
        <Key android:codes="55" android:keyLabel="7"/>
        <Key android:codes="56" android:keyLabel="8"/>
        <Key android:codes="57" android:keyLabel="9"/>
        <Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="-5"
             android:keyLabel="DELETE"
             android:keyWidth="40%p"
             android:keyEdgeFlags="left"
             android:isRepeatable="true"/>
        <Key android:codes="10"
             android:keyLabel="ENTER"
             android:keyWidth="60%p"
             android:keyEdgeFlags="right"/>
    </Row>

</Keyboard>

Of course this can be easily edited to your liking. You can even use images instead lf words for the label.

Suragch didnt demonstrate the files in the values folder and assumed we had access to Android Studio; which automatically creates them. Good thing I have APK Builder.

E: NumPad/res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

F: NumPad/res/values/strings.xml

<resources>
    <string name="app_name">Suragch NumPad</string>
</resources>

G: NumPad/res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

</resources>

H: Numpad/AndroidManifest.xml

This is the file that was really up for contension. Here I felt I would never compile my program. sob. sob. If you check Suracgh's answer you see he leaves the first set of fields empty, and adds the activity tag in this file. As I said there are four types of Android programs. An activity is a regular app with a launcher icon. This numpad is not an activity! Further he didnt implement any activity.

My friends do not include the activity tag. Your program will compile, and when you try to launch it will crash! As for xmlns:android and uses-sdk; I cant help you there. Just try my settings if they work.

As you can see there is a service tag, which register it as a service. Also service.android:name must be name of public class extending service in our java file. It MUST be capitalized accordingly. Also package is the name of the package we declared in java file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="Saragch.num_pad">

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="27" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/Suragch_NumPad_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <service
            android:name=".MyInputMethodService"
            android:label="Keyboard Display Name"
            android:permission="android.permission.BIND_INPUT_METHOD">

            <intent-filter>
                <action android:name="android.view.InputMethod"/>
            </intent-filter>

            <meta-data
                android:name="android.view.im"
                android:resource="@xml/method"/>

        </service>

    </application>
</manifest>

I: NumPad/src/Saragch/num_pad/MyInputMethodService.java

Note: I think java is an alternative to src.

This was another problem file but not as contentious as the manifest file. As I know Java good enough to know what is what, what is not. I barely know xml and how it ties in with Android development!

The problem here was he didnt import anything! I mean, he gave us a "complete" file which uses names that couldnt be resolved! InputMethodService, Keyboard, etc. That is bad practice Mr. Suragch. Thanks for helping me out but how did you expect the code to compile if the names cant be resolved?

Following is the correctly edited version. I just happened to pounce upon couple hints to drove me to the right place to learn what exactly to import.

package Saragch.num_pad;

import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.Keyboard;

import android.text.TextUtils;
import android.view.inputmethod.InputConnection;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener 
{
    @Override
    public View onCreateInputView() 
    {
     // get the KeyboardView and add our Keyboard layout to it
     KeyboardView keyboardView = (KeyboardView)getLayoutInflater().inflate(R.layout.keyboard_view, null);
     Keyboard keyboard = new Keyboard(this, R.xml.number_pad);
     keyboardView.setKeyboard(keyboard);
     keyboardView.setOnKeyboardActionListener(this);
     return keyboardView;
    }

    @Override
    public void onKey(int primaryCode, int[] keyCodes) 
    {

        InputConnection ic = getCurrentInputConnection();

        if (ic == null) return;

        switch (primaryCode)
        {
         case Keyboard.KEYCODE_DELETE:
            CharSequence selectedText = ic.getSelectedText(0);

            if (TextUtils.isEmpty(selectedText)) 
            {
             // no selection, so delete previous character
             ic.deleteSurroundingText(1, 0);
            }

            else 
            {
             // delete the selection
             ic.commitText("", 1);
            }

            ic.deleteSurroundingText(1, 0);
            break;

         default:
            char code = (char) primaryCode;
            ic.commitText(String.valueOf(code), 1);
        }
    }

    @Override
    public void onPress(int primaryCode) { }

    @Override
    public void onRelease(int primaryCode) { }

    @Override
    public void onText(CharSequence text) { }

    @Override
    public void swipeLeft() { }

    @Override
    public void swipeRight() { }

    @Override
    public void swipeDown() { }

    @Override
    public void swipeUp() { }
}
  1. Compile and sign your project.

    This is where I am clueless as a newby Android developer. I would like to learn it manually, as I believe real programmers can compile manually.

I think gradle is one of the tools for compiling and packaging to apk. apk seems to be like a jar file or a rar for zip file. There are then two types of signing. debug key which is not alllowed on play store and private key.

Well lets give Mr. Saragch a hand. And thank you for watching my video. Like, subscribe.

How many bits or bytes are there in a character?

It depends what is the character and what encoding it is in:

  • An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.

  • An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).

  • A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).

  • A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.

  • A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

  • An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.

  • The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.

That would mean that there are between 0.03125 and 0.125 characters in a bit.

Using Server.MapPath in external C# Classes in ASP.NET

class test
{
public static void useServerPath(string path)
{
   if (File.Exists(path)
{
 \\...... do whatever you wabt
}
else
{
\\.....
}
}

Now when you call the method from the codebehind

for example :

protected void BtAtualizacao_Click(object sender, EventArgs e)
        {
             string path = Server.MapPath("Folder") + "\\anifile.txt";

            test.useServerPath(path);
}

in this way your code is to simple and with one method u can use multiple path for each call :)

How do I format a date as ISO 8601 in moment.js?

Also possible with vanilla JS

new Date().toISOString() // "2017-08-26T16:31:02.349Z"

Validating an XML against referenced XSD in C#

The following example validates an XML file and generates the appropriate error or warning.

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Sample
{

    public static void Main()
    {
        //Load the XmlSchemaSet.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.Add("urn:bookstore-schema", "books.xsd");

        //Validate the file using the schema stored in the schema set.
        //Any elements belonging to the namespace "urn:cd-schema" generate
        //a warning because there is no schema matching that namespace.
        Validate("store.xml", schemaSet);
        Console.ReadLine();
    }

    private static void Validate(String filename, XmlSchemaSet schemaSet)
    {
        Console.WriteLine();
        Console.WriteLine("\r\nValidating XML file {0}...", filename.ToString());

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            compiledSchema = schema;
        }

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.Schemas.Add(compiledSchema);
        settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
        settings.ValidationType = ValidationType.Schema;

        //Create the schema validating reader.
        XmlReader vreader = XmlReader.Create(filename, settings);

        while (vreader.Read()) { }

        //Close the reader.
        vreader.Close();
    }

    //Display any warnings or errors.
    private static void ValidationCallBack(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
        else
            Console.WriteLine("\tValidation error: " + args.Message);

    }
}

The preceding example uses the following input files.

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema" xmlns:cd="urn:cd-schema">
  <book genre="novel">
    <title>The Confidence Man</title>
    <price>11.99</price>
  </book>
  <cd:cd>
    <title>Americana</title>
    <cd:artist>Offspring</cd:artist>
    <price>16.95</price>
  </cd:cd>
</bookstore>

books.xsd

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">

 <xsd:element name="bookstore" type="bookstoreType"/>

 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="bookType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="authorName"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>

 <xsd:complexType name="authorName">
  <xsd:sequence>
   <xsd:element name="first-name"  type="xsd:string"/>
   <xsd:element name="last-name" type="xsd:string"/>
  </xsd:sequence>
 </xsd:complexType>

</xsd:schema>

How to delete/truncate tables from Hadoop-Hive?

To Truncate:

hive -e "TRUNCATE TABLE IF EXISTS $tablename"

To Drop:

hive -e "Drop TABLE IF EXISTS $tablename"

jQuery - select all text from a textarea

I ended up using this:

$('.selectAll').toggle(function() {
  $(this).select();
}, function() {
  $(this).unselect();
});

How to disable copy/paste from/to EditText

Here is a hack to disable "paste" popup. You have to override EditText method:

@Override
public int getSelectionStart() {
    for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
        if (element.getMethodName().equals("canPaste")) {
            return -1;
        }
    }
    return super.getSelectionStart();
}

Similar can be done for the other actions.

What are file descriptors, explained in simple terms?

Hear it from the Horse's Mouth : APUE (Richard Stevens).
To the kernel, all open files are referred to by File Descriptors. A file descriptor is a non-negative number.

When we open an existing file or create a new file, the kernel returns a file descriptor to the process. The kernel maintains a table of all open file descriptors, which are in use. The allotment of file descriptors is generally sequential and they are allotted to the file as the next free file descriptor from the pool of free file descriptors. When we closes the file, the file descriptor gets freed and is available for further allotment.
See this image for more details :

Two Process

When we want to read or write a file, we identify the file with the file descriptor that was returned by open() or create() function call, and use it as an argument to either read() or write().
It is by convention that, UNIX System shells associates the file descriptor 0 with Standard Input of a process, file descriptor 1 with Standard Output, and file descriptor 2 with Standard Error.
File descriptor ranges from 0 to OPEN_MAX. File descriptor max value can be obtained with ulimit -n. For more information, go through 3rd chapter of APUE Book.

Return number of rows affected by UPDATE statements

You might need to collect the stats as you go, but @@ROWCOUNT captures this:

declare @Fish table (
Name varchar(32)
)

insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT  --gives 1

update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3

How to check if a directory containing a file exist?

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");
f.mkdirs();

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

How to select all records from one table that do not exist in another table?

This is pure set theory which you can achieve with the minus operation.

select id, name from table1
minus
select id, name from table2

What's the algorithm to calculate aspect ratio?

This algorithm in Python gets you part of the way there.


Tell me what happens if the windows is a funny size.

Maybe what you should have is a list of all acceptable ratios (to the 3rd party component). Then, find the closest match to your window and return that ratio from the list.

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

In practice, you will often want to act differently depending on whether a variable is an Array or a Hash, not just mere tell. In this situation, an elegant idiom is the following:

case item
  when Array
   #do something
  when Hash
   #do something else
end

Note that you don't call the .class method on item.

Add swipe to delete UITableViewCell

here See my result Swift with fully customizable button supported

Advance bonus for use this only one method implementation and you get a perfect button!!!

 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let action = UIContextualAction(
            style: .destructive,
            title: "",
            handler: { (action, view, completion) in

                let alert = UIAlertController(title: "", message: "Are you sure you want to delete this incident?", preferredStyle: .actionSheet)

                alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
                    let model = self.incedentArry[indexPath.row] as! HFIncedentModel
                    print(model.incent_report_id)
                    self.incedentArry.remove(model)
                    tableView.deleteRows(at: [indexPath], with: .fade)
                    delete_incedentreport_data(param: ["incent_report_id": model.incent_report_id])
                    completion(true)
                }))

                alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction)in
                    tableView.reloadData()
                }))

                self.present(alert, animated: true, completion: {

                })


        })
        action.image = HFAsset.ic_trash.image
        action.backgroundColor = UIColor.red
        let configuration = UISwipeActionsConfiguration(actions: [action])
        configuration.performsFirstActionWithFullSwipe = true
        return configuration
}

Bootstrap DatePicker, how to set the start date for tomorrow?

this.$('#datepicker').datepicker({minDate: 1});

minDate:0 - Enable dates in the calender from the current date. MinDate:1 enable dates in the calender currentDate+1

To Restrict date between from tomorrow and the same day next month u need to give something like

$( "#datepicker" ).datepicker({ minDate: 1, maxDate: "+1M" });

Spring Boot Configure and Use Two DataSources

# Here '1stDB' is the database name
spring.datasource.url=jdbc:mysql://localhost/A
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


# Here '2ndDB' is the database name
spring.second-datasourcee.url=jdbc:mysql://localhost/B
spring.second-datasource.username=root
spring.second-datasource.password=root
spring.second-datasource.driver-class-name=com.mysql.jdbc.Driver


    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource firstDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.second-datasource")
    public DataSource secondDataSource() {
       return DataSourceBuilder.create().build();
    }

How to print a certain line of a file with PowerShell?

This will show the 10th line of myfile.txt:

get-content myfile.txt | select -first 1 -skip 9

both -first and -skip are optional parameters, and -context, or -last may be useful in similar situations.